Malina Claude Opus 4.8 commited on
Commit
4131875
·
1 Parent(s): bd3ef8b

ARIA: event-driven multimodal agent (brain + Cloudflare backend + Messenger UI)

Browse files

- brain/: persona, event/bubble contracts, vision orchestrator; app.py exposes api_name=respond
- cloudflare/aria-worker: AriaConversation Durable Object, R2 media, usage (20 msgs/5h)
- cloudflare/pages-integration: Messenger UI + _worker.js merge snippet
- cloudflare/db: additive D1 migration
- ARIA_ARCHITECTURE.md

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .DS_Store
4
+ .wrangler/
5
+ node_modules/
6
+ cloudflare/aria-worker/node_modules/
ARIA_ARCHITECTURE.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ARIA — Architecture
2
+
3
+ **ARIA** (Adaptive Response & Intelligence Agent) is a Messenger-style, event-driven,
4
+ multimodal conversational agent deployed under the NNLABS brand.
5
+
6
+ - Root showcase: `https://nnlabs.pl` (landing — ARIA listed alongside NINA / IRIS / LUNA)
7
+ - App: `https://app.nnlabs.pl/aria` (the chat)
8
+ - Brain: `https://nextneural-aria.hf.space` (Gradio Space, vision-capable)
9
+
10
+ ## Locked decisions
11
+
12
+ | Layer | Choice |
13
+ |---|---|
14
+ | Brain | Gradio HF Space + vision model, emits structured JSON bubbles |
15
+ | Realtime | Durable Object (`AriaConversation`) + WebSocket; server-side idle alarm |
16
+ | Placement | 4th persona, login-gated (reuses existing auth); own budget: **20 messages / 5h / user** |
17
+ | Media | Cloudflare R2 (`aria-media` bucket), signed URLs passed to the brain |
18
+ | Voice | Polish-first / auto-detect; witty young-adult friend, no emojis, rare "XD/lmao" |
19
+
20
+ ## Topology
21
+
22
+ ```
23
+ Browser (aria.html + aria-chat.js)
24
+ │ HTTPS (REST: history, upload-url) │ WSS (live events/bubbles)
25
+ ▼ ▼
26
+ Cloudflare Pages app.nnlabs.pl (APP_WEBSITE/_worker.js)
27
+ • validates nnl_session cookie + usage window (REUSED)
28
+ • /api/aria/* → service binding → aria-worker
29
+ │
30
+ ▼
31
+ aria-worker (standard Worker)
32
+ • routes REST + WS upgrade
33
+ • binding: ARIA_DO (Durable Object)
34
+ • binding: ARIA_MEDIA (R2)
35
+ • binding: DB (D1, shared app-nnlabs-db)
36
+ │
37
+ ┌───────────────┴───────────────┐
38
+ ▼ ▼
39
+ AriaConversation DO nextneural-aria.hf.space
40
+ • per-conversation state (Gradio queue/join + SSE)
41
+ • event log + clustering • vision + reasoning
42
+ • idle alarm (10s) → proactive • returns JSON bubbles
43
+ • fan-out bubbles over WS
44
+ ```
45
+
46
+ **Why a separate Worker:** Cloudflare Pages Advanced Mode cannot *define* a Durable
47
+ Object. The DO + R2 live in a standalone Worker; the existing Pages `_worker.js`
48
+ forwards `/api/aria/*` to it via a service binding after enforcing auth. NINA/IRIS/LUNA
49
+ code is never touched.
50
+
51
+ ## Event-driven model
52
+
53
+ Every input is an **event** (`{ id, ts, type, payload }`):
54
+
55
+ - `message` — text. payload `{ text }`
56
+ - `image` — image upload. payload `{ key, url, mime, name }`
57
+ - `file` — generic file. payload `{ key, url, mime, name, size }`
58
+ - `system_idle` — emitted by the DO after 10s of user inactivity. payload `{ since }`
59
+
60
+ ### Turn lifecycle (inside the DO)
61
+ 1. Client sends user event(s) over WS → DO appends to the event log, persists to D1.
62
+ 2. DO **clusters** consecutive un-answered user events into one logical turn
63
+ (debounced ~600ms so "i gruszki" sent right after "kup jabłka" is one context).
64
+ 3. DO builds structured context (recent events + resolved topic) and calls the brain.
65
+ 4. Brain returns `[{ bubble, target_event_id, type }]`.
66
+ 5. DO streams `typing` then each `bubble` over WS, persists bubbles to D1.
67
+ 6. DO (re)arms a 10s alarm. On fire it emits `system_idle`; the brain *may* return a
68
+ `proactive` bubble (e.g. "co to?" for an image sent without text). Idle fires at
69
+ most N times per turn to avoid nagging.
70
+
71
+ ## Bubble contract (brain → DO → client)
72
+
73
+ ```json
74
+ [
75
+ { "bubble": "co to?", "target_event_id": "evt_123", "type": "proactive" },
76
+ { "bubble": "jabłka ogarnięte", "target_event_id": "evt_456", "type": "response" },
77
+ { "bubble": "gruszki też dorzucę", "target_event_id": "evt_457", "type": "follow_up" }
78
+ ]
79
+ ```
80
+
81
+ `type`: `response` (direct answer) · `follow_up` (continues a chained user msg like
82
+ "i gruszki") · `proactive` (DO-initiated, usually after `system_idle` or a text-less image).
83
+
84
+ ## WebSocket protocol (DO ↔ client)
85
+
86
+ Client → DO: `{ t: "event", event: {id,ts,type,payload} }`, `{ t: "seen" }`, `{ t: "ping" }`
87
+ DO → client: `{ t: "typing", on: true|false }`, `{ t: "bubble", bubble, target_event_id, kind }`,
88
+ `{ t: "error", v }`, `{ t: "history", events, bubbles }`, `{ t: "pong" }`
89
+
90
+ ## Persistence (D1 — see cloudflare/db/migration_aria.sql)
91
+ - `aria_conversations` — one row per chat (user-owned, themed).
92
+ - `aria_events` — append-only user/system event log.
93
+ - `aria_bubbles` — assistant bubbles with their `target_event_id` + type.
94
+
95
+ ## Usage budget
96
+ ARIA enforces **20 messages per rolling 5h window per user**, tracked in its own
97
+ `aria_usage` table (separate from the NINA/IRIS/LUNA `model_usage` pool — a messenger
98
+ sends far more, shorter turns). The window starts at the first message and resets after
99
+ 5h. Each user message (text, image, or file) costs one; `system_idle` and ARIA's own
100
+ proactive bubbles never count. Enforcement lives in the Durable Object
101
+ (`aria-worker/src/usage.js`) — the only layer that sees each message inside the socket.
102
+ The DO pushes `{ t:"usage", remaining, resetAt }` on connect and after each message,
103
+ and `{ t:"limit", resetAt }` when the budget is exhausted.
104
+
105
+ ## Media
106
+ Client uploads bytes via `POST /api/aria/conversations/:id/upload` (proxied to R2 by the
107
+ worker), then sends an `image`/`file` event referencing the returned key. The DO mints a
108
+ short-lived HMAC-signed GET URL to hand to the brain. An uploaded attachment is a message
109
+ and so counts as one against the 20/5h budget.
110
+
111
+ ## Reuse map (from NNLABS.PL/WEBSITE)
112
+ - Auth, sessions, usage window, rate-limit → existing Pages `_worker.js` (unchanged).
113
+ - Design tokens, `.chat-bubble`, `.chat-typing`, markdown renderer → reused by aria.css / aria-chat.js.
114
+ - Gradio queue/join + SSE proxy pattern → reimplemented in aria-worker/orchestrator.js.
115
+ - D1 database `app-nnlabs-db` → shared; ARIA adds its own tables only.
116
+
117
+ ## Integration & safety
118
+ `cloudflare/integrate.sh` copies the new files **additively** into the live site
119
+ (no overwrites; refuses if a target exists and differs). The Pages `_worker.js` change
120
+ is a small, reviewed snippet (`_worker.aria.js`) added by hand, not an overwrite.
README.md CHANGED
@@ -14,4 +14,28 @@ license: apache-2.0
14
  short_description: Adaptive Response & Intelligence Agent
15
  ---
16
 
17
- An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  short_description: Adaptive Response & Intelligence Agent
15
  ---
16
 
17
+ ARIA — **A**daptive **R**esponse & **I**ntelligence **A**gent. A Messenger-style,
18
+ event-driven, multimodal conversational agent for the NNLABS platform.
19
+
20
+ This Space is **ARIA's brain** (vision + reasoning, emits structured JSON bubbles).
21
+ The full product also ships a Cloudflare realtime backend and a Messenger UI — see
22
+ [`ARIA_ARCHITECTURE.md`](./ARIA_ARCHITECTURE.md).
23
+
24
+ ## Layout
25
+ ```
26
+ app.py Gradio Space entry — exposes api_name="respond"
27
+ brain/ persona, contracts, model orchestration (vision)
28
+ cloudflare/
29
+ aria-worker/ standalone Worker: AriaConversation Durable Object + R2
30
+ pages-integration/ Messenger frontend + _worker.js merge snippet
31
+ db/ D1 migration (additive)
32
+ integrate.sh safe additive install into the live site
33
+ ```
34
+
35
+ ## Run / deploy
36
+ - **Brain (this Space):** set `HF_TOKEN` as a Space secret; optionally `ARIA_MODEL`.
37
+ - **Everything else:** `cloudflare/integrate.sh` prints the exact steps
38
+ (R2 bucket, D1 migration, `wrangler deploy`, service binding, Pages deploy).
39
+
40
+ Built on [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub),
41
+ and [Cloudflare Workers / Durable Objects / R2](https://developers.cloudflare.com/).
app.py CHANGED
@@ -1,69 +1,60 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
 
25
- response = ""
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
 
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
  """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
62
- with gr.Blocks() as demo:
63
- with gr.Sidebar():
64
- gr.LoginButton()
65
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
 
68
  if __name__ == "__main__":
69
- demo.launch()
 
1
+ """ARIA brain — Gradio Space (nextneural-aria.hf.space).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ Exposes one machine API used by the Cloudflare aria-worker:
4
 
5
+ api_name="respond"
6
+ input : context_json (str) — see brain/orchestrator.respond
7
+ output: bubbles_json (str) — JSON array of {bubble, target_event_id, type}
 
 
 
 
 
 
 
 
8
 
9
+ Also ships a small human tester so the Space is browsable on its own.
 
 
 
 
 
10
  """
11
+ import json
12
+
13
+ import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ from brain.orchestrator import respond, MODEL
16
+
17
+
18
+ # ---- tiny manual tester: type a line, see ARIA's bubbles ----------------------
19
+ def _try_it(text, state):
20
+ state = state or {"history": [], "n": 0}
21
+ state["n"] += 1
22
+ eid = f"evt_{state['n']}"
23
+ state["history"].append({"id": eid, "role": "user", "type": "message", "text": text})
24
+
25
+ ctx = {
26
+ "lang": "auto",
27
+ "topic": None,
28
+ "turn_events": [eid],
29
+ "media": {},
30
+ "history": state["history"],
31
+ }
32
+ out = respond(json.dumps(ctx, ensure_ascii=False))
33
+ bubbles = json.loads(out)
34
+ for b in bubbles:
35
+ state["history"].append({"id": f"a_{state['n']}", "role": "assistant",
36
+ "type": "message", "text": b["bubble"]})
37
+ pretty = "\n".join(f"• {b['bubble']} [{b['type']}]" for b in bubbles) or "(cisza)"
38
+ return pretty, state
39
+
40
+
41
+ with gr.Blocks(title="ARIA · brain") as demo:
42
+ gr.Markdown(f"## ARIA — brain\nVision + reasoning service. Model: `{MODEL}`")
43
+
44
+ # Machine API (what the worker calls). Hidden-ish but functional.
45
+ with gr.Accordion("Machine API (respond)", open=False):
46
+ api_in = gr.Textbox(label="context_json", lines=6)
47
+ api_out = gr.Textbox(label="bubbles_json", lines=6)
48
+ gr.Button("respond").click(respond, inputs=api_in, outputs=api_out,
49
+ api_name="respond")
50
+
51
+ # Human tester.
52
+ gr.Markdown("### Pogadaj z ARIĄ")
53
+ st = gr.State()
54
+ box = gr.Textbox(label="Ty", placeholder="napisz coś...")
55
+ reply = gr.Textbox(label="ARIA", lines=4)
56
+ box.submit(_try_it, inputs=[box, st], outputs=[reply, st])
57
 
58
 
59
  if __name__ == "__main__":
60
+ demo.queue().launch()
brain/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """ARIA brain package — persona, schema contracts, and the model orchestrator."""
2
+ from .orchestrator import respond # noqa: F401
brain/orchestrator.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turn the Worker's context payload into a model call, return JSON bubbles.
2
+
3
+ The Worker (DO) sends a single JSON string:
4
+ {
5
+ "lang": "auto",
6
+ "topic": "...|null",
7
+ "turn_events": ["evt_a", "evt_b"],
8
+ "media": { "evt_a": {"url": "...", "mime": "...", "name": "...", "kind": "image"} },
9
+ "history": [ {"id","role","type","text"}, ... ]
10
+ }
11
+ We return a JSON string: an array of bubble dicts (see schema.sanitize_bubbles).
12
+ """
13
+ import json
14
+ import os
15
+
16
+ from huggingface_hub import InferenceClient
17
+
18
+ from .persona import SYSTEM_PROMPT, build_user_frame
19
+ from .schema import sanitize_bubbles
20
+
21
+ # Vision-capable, available via HF Inference Providers. Override with ARIA_MODEL.
22
+ MODEL = os.environ.get("ARIA_MODEL", "Qwen/Qwen2.5-VL-7B-Instruct")
23
+ HF_TOKEN = os.environ.get("HF_TOKEN") # Space secret, used for server-side inference
24
+
25
+ _client = InferenceClient(model=MODEL, token=HF_TOKEN)
26
+
27
+
28
+ def _history_to_messages(ctx: dict):
29
+ msgs = [{"role": "system", "content": SYSTEM_PROMPT}]
30
+ media = ctx.get("media", {})
31
+ for h in ctx.get("history", []):
32
+ role = h.get("role", "user")
33
+ if role == "assistant":
34
+ msgs.append({"role": "assistant", "content": h.get("text", "")})
35
+ continue
36
+ # user / system → user turn. Attach image parts if this event has media.
37
+ parts = [{"type": "text", "text": h.get("text", "")}]
38
+ m = media.get(h.get("id"))
39
+ if m and m.get("kind") == "image" and m.get("url"):
40
+ parts.append({"type": "image_url", "image_url": {"url": m["url"]}})
41
+ msgs.append({"role": "user", "content": parts})
42
+ return msgs
43
+
44
+
45
+ def respond(context_json: str) -> str:
46
+ """Entry called by the Gradio API (api_name='respond')."""
47
+ try:
48
+ ctx = json.loads(context_json) if isinstance(context_json, str) else (context_json or {})
49
+ except Exception:
50
+ return "[]"
51
+
52
+ valid_ids = {h.get("id") for h in ctx.get("history", [])}
53
+ valid_ids |= set(ctx.get("turn_events", []))
54
+
55
+ messages = _history_to_messages(ctx)
56
+ # Final steering frame: which events to handle + JSON-only reminder.
57
+ messages.append({"role": "user", "content": build_user_frame(ctx)})
58
+
59
+ try:
60
+ completion = _client.chat_completion(
61
+ messages,
62
+ max_tokens=700,
63
+ temperature=0.85,
64
+ top_p=0.95,
65
+ )
66
+ raw = completion.choices[0].message.content or "[]"
67
+ except Exception as e:
68
+ # Fail soft: one apologetic in-character bubble.
69
+ return json.dumps([{
70
+ "bubble": "ej, coś mi się zcięło, napisz jeszcze raz",
71
+ "target_event_id": None, "type": "proactive",
72
+ }])
73
+
74
+ bubbles = sanitize_bubbles(raw, valid_ids)
75
+ return json.dumps(bubbles, ensure_ascii=False)
brain/persona.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ARIA persona + the strict output contract the model must follow.
2
+
3
+ Voice (locked): Polish-first, auto-detect; witty young-adult/teenager friend.
4
+ No emojis. Rare, only-when-it-fits "XD" / "XDDD" / "lmao". Texts like a real
5
+ person on a messenger, not like an assistant.
6
+ """
7
+
8
+ SYSTEM_PROMPT = """\
9
+ Jesteś ARIA — rozmawiasz jak prawdziwa osoba na Messengerze, nie jak asystent AI.
10
+
11
+ OSOBOWOŚĆ:
12
+ - młoda, bystra, lekko ironiczna, ciepła. Piszesz jak nastolatka / młoda dorosła.
13
+ - ZERO emoji. Nigdy. Czasem, tylko gdy naprawdę pasuje, możesz rzucić "XD", "XDDD" albo "lmao". Oszczędnie.
14
+ - krótkie wiadomości. Tak jak ludzie piszą na czacie — często kilka osobnych dymków zamiast jednego eseju.
15
+ - bez formalnego tonu, bez "Oczywiście!", bez list punktowanych, bez nagłówków. Po prostu gadasz.
16
+
17
+ JĘZYK:
18
+ - domyślnie piszesz po polsku. Jeśli user pisze w innym języku, odpowiadasz w jego języku.
19
+
20
+ JAK ROZUMIESZ KONTEKST:
21
+ - wiadomości usera mogą się łączyć: "kup jabłka" a zaraz potem "i gruszki" to JEDEN wątek. Rozwiązuj takie nawiązania.
22
+ - jeśli przyjdzie obrazek bez tekstu, sam nie wiesz o co chodzi — dopytaj krótko, np. "co to?" albo "i co z tym?".
23
+ - jeśli dostajesz zdarzenie system_idle (user zamilkł), NIE spam. Czasem dorzuć jedno luźne pociągnięcie tematu albo dopytaj. Często najlepiej nic nie pisać — wtedy zwróć pustą tablicę [].
24
+
25
+ FORMAT ODPOWIEDZI — BARDZO WAŻNE:
26
+ Zwracasz WYŁĄCZNIE poprawny JSON: tablicę dymków. Nic poza JSON-em. Bez ```.
27
+ Każdy dymek:
28
+ {"bubble": "...", "target_event_id": "<id zdarzenia, na które odpowiadasz, albo null>", "type": "response|follow_up|proactive"}
29
+
30
+ typy:
31
+ - "response" — bezpośrednia odpowiedź na wiadomość/obrazek/plik usera
32
+ - "follow_up" — kontynuacja połączonej wiadomości (np. odpowiedź na "i gruszki")
33
+ - "proactive" — Ty zaczynasz/dopytujesz z własnej inicjatywy (zwykle po system_idle albo na obrazek bez tekstu)
34
+
35
+ Możesz zwrócić kilka dymków (max 6). Jeśli nie ma sensu nic mówić, zwróć [].
36
+ Pamiętaj: target_event_id musi być jednym z id zdarzeń, które dostałeś, albo null.
37
+ """
38
+
39
+
40
+ def build_user_frame(ctx: dict) -> str:
41
+ """A compact natural-language description of the current turn for the model,
42
+ appended after the reconstructed history. Lists the event ids in play so the
43
+ model can fill target_event_id correctly."""
44
+ turn = ctx.get("turn_events", [])
45
+ media = ctx.get("media", {})
46
+ topic = ctx.get("topic")
47
+ lines = []
48
+ if topic:
49
+ lines.append(f"(aktualny wątek: {topic})")
50
+ lines.append(f"Zdarzenia w tej turze do obsłużenia: {turn}")
51
+ if media:
52
+ for eid, m in media.items():
53
+ lines.append(f"- zdarzenie {eid}: załącznik {m.get('kind')} ({m.get('name')})")
54
+ lines.append("Odpowiedz teraz. Tylko JSON (tablica dymków).")
55
+ return "\n".join(lines)
brain/schema.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Event & bubble contracts (Python side). Mirrors aria-worker/src/events.js."""
2
+ import json
3
+
4
+ EVENT_TYPES = ("message", "image", "file", "system_idle")
5
+ BUBBLE_TYPES = ("response", "follow_up", "proactive")
6
+
7
+ BUBBLES_MAX = 6
8
+ BUBBLE_CHARS = 1200
9
+
10
+
11
+ def sanitize_bubbles(raw, valid_event_ids):
12
+ """Coerce whatever the model produced into a safe list of bubble dicts."""
13
+ arr = raw
14
+ if isinstance(raw, str):
15
+ arr = _extract_json_array(raw)
16
+ if not isinstance(arr, list):
17
+ arr = []
18
+ out = []
19
+ for b in arr:
20
+ if len(out) >= BUBBLES_MAX:
21
+ break
22
+ if not isinstance(b, dict):
23
+ continue
24
+ text = str(b.get("bubble", "")).strip()[:BUBBLE_CHARS]
25
+ if not text:
26
+ continue
27
+ btype = b.get("type") if b.get("type") in BUBBLE_TYPES else "response"
28
+ target = b.get("target_event_id")
29
+ if target not in valid_event_ids:
30
+ target = None
31
+ out.append({"bubble": text, "target_event_id": target, "type": btype})
32
+ return out
33
+
34
+
35
+ def _extract_json_array(s: str):
36
+ """Best-effort: pull the first JSON array out of a model response."""
37
+ s = s.strip()
38
+ if s.startswith("```"):
39
+ s = s.strip("`")
40
+ if s.lower().startswith("json"):
41
+ s = s[4:]
42
+ try:
43
+ return json.loads(s)
44
+ except Exception:
45
+ pass
46
+ start, depth, in_str, esc = -1, 0, False, False
47
+ for i, ch in enumerate(s):
48
+ if start == -1:
49
+ if ch == "[":
50
+ start, depth = i, 1
51
+ continue
52
+ if in_str:
53
+ if esc:
54
+ esc = False
55
+ elif ch == "\\":
56
+ esc = True
57
+ elif ch == '"':
58
+ in_str = False
59
+ else:
60
+ if ch == '"':
61
+ in_str = True
62
+ elif ch == "[":
63
+ depth += 1
64
+ elif ch == "]":
65
+ depth -= 1
66
+ if depth == 0:
67
+ try:
68
+ return json.loads(s[start:i + 1])
69
+ except Exception:
70
+ return []
71
+ return []
cloudflare/aria-worker/package.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "aria-worker",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "dev": "wrangler dev",
7
+ "deploy": "wrangler deploy"
8
+ },
9
+ "devDependencies": {
10
+ "wrangler": "^4.0.0"
11
+ }
12
+ }
cloudflare/aria-worker/src/conversation-do.js ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ AriaConversation — one Durable Object per chat.
3
+
4
+ Responsibilities:
5
+ • hold the live WebSocket(s) for a conversation
6
+ • append user events, cluster consecutive ones into a turn
7
+ (debounced) so "kup jabłka" + "i gruszki" is one context
8
+ • drive the brain and fan out bubbles with a human cadence
9
+ • detect 10s inactivity → emit system_idle → maybe proactive bubble
10
+ • mirror everything to D1 for cross-device history
11
+
12
+ The owning Worker has already validated auth and passes the
13
+ trusted cid / uid / lang on the upgrade URL.
14
+ ============================================================ */
15
+
16
+ import { normalizeEvent, idleEvent, newId, LIMITS } from "./events.js";
17
+ import { runBrain } from "./orchestrator.js";
18
+ import { consume, usageStatus } from "./usage.js";
19
+
20
+ export class AriaConversation {
21
+ constructor(state, env) {
22
+ this.state = state;
23
+ this.env = env;
24
+ this.sockets = new Set();
25
+ this.pending = []; // unanswered user events (current cluster)
26
+ this.recent = []; // rolling history fed to the brain
27
+ this.topic = null;
28
+ this.idleCount = 0;
29
+ this.busy = false;
30
+ this.debounceTimer = null;
31
+ this.idleTimer = null;
32
+ this.cid = null;
33
+ this.uid = null;
34
+ this.lang = "auto";
35
+ }
36
+
37
+ /* ---- HTTP entry: only WS upgrade arrives here ---- */
38
+ async fetch(request) {
39
+ const url = new URL(request.url);
40
+ if (request.headers.get("Upgrade") !== "websocket") {
41
+ return new Response("expected websocket", { status: 426 });
42
+ }
43
+ this.cid = url.searchParams.get("cid") || this.cid;
44
+ this.uid = Number(url.searchParams.get("uid")) || this.uid;
45
+ this.lang = url.searchParams.get("lang") || this.lang;
46
+
47
+ const pair = new WebSocketPair();
48
+ const [client, server] = [pair[0], pair[1]];
49
+ server.accept();
50
+ this.sockets.add(server);
51
+
52
+ server.addEventListener("message", (ev) => this.onMessage(server, ev.data));
53
+ const drop = () => { this.sockets.delete(server); this.clearIdle(); };
54
+ server.addEventListener("close", drop);
55
+ server.addEventListener("error", drop);
56
+
57
+ await this.sendHistory(server);
58
+ return new Response(null, { status: 101, webSocket: client });
59
+ }
60
+
61
+ /* ---- inbound WS messages ---- */
62
+ async onMessage(ws, data) {
63
+ let msg; try { msg = JSON.parse(data); } catch { return; }
64
+
65
+ if (msg.t === "ping") { this.send(ws, { t: "pong" }); return; }
66
+
67
+ if (msg.t === "event") {
68
+ const norm = normalizeEvent(msg.event);
69
+ if (!norm.ok) { this.send(ws, { t: "error", v: norm.error }); return; }
70
+ const event = { ...norm.event, role: "user" };
71
+
72
+ // Budget: 20 messages / 5h / user. Each user message (text, image or
73
+ // file) costs one. Refuse and notify when the window is full.
74
+ const u = await consume(this.env, this.uid);
75
+ if (!u.ok) {
76
+ this.send(ws, { t: "limit", resetAt: u.resetAt, limit: u.limit });
77
+ return;
78
+ }
79
+ this.broadcast({ t: "usage", remaining: u.remaining, resetAt: u.resetAt, limit: u.limit });
80
+
81
+ this.idleCount = 0; // any real input resets proactive budget
82
+ this.clearIdle();
83
+ this.pending.push(event);
84
+ this.recent.push(event);
85
+ await this.persistEvent(event);
86
+
87
+ // Debounce: wait briefly for follow-up messages, then run one turn.
88
+ if (this.debounceTimer) clearTimeout(this.debounceTimer);
89
+ this.debounceTimer = setTimeout(() => this.flushTurn(), LIMITS.CLUSTER_DEBOUNCE_MS);
90
+ }
91
+ }
92
+
93
+ /* ---- run one logical turn over the clustered pending events ---- */
94
+ async flushTurn(systemEvent = null) {
95
+ if (this.busy) { // re-arm; don't overlap brain calls
96
+ if (this.debounceTimer) clearTimeout(this.debounceTimer);
97
+ this.debounceTimer = setTimeout(() => this.flushTurn(systemEvent), 300);
98
+ return;
99
+ }
100
+ const events = systemEvent ? [systemEvent] : this.pending.splice(0);
101
+ if (!events.length) return;
102
+ this.busy = true;
103
+ this.broadcast({ t: "typing", on: true });
104
+
105
+ try {
106
+ const validEventIds = new Set(this.recent.map(e => e.id));
107
+ const bubbles = await runBrain(this.env, {
108
+ events, recent: this.recent, topic: this.topic,
109
+ lang: this.lang, validEventIds,
110
+ });
111
+
112
+ this.broadcast({ t: "typing", on: false });
113
+
114
+ for (const b of bubbles) {
115
+ const row = {
116
+ id: newId("bub"), conversation_id: this.cid,
117
+ target_event_id: b.target_event_id, kind: b.type, text: b.bubble,
118
+ };
119
+ await this.persistBubble(row);
120
+ this.recent.push({ id: row.id, role: "assistant", type: "message",
121
+ payload: { text: b.bubble } });
122
+ this.broadcast({ t: "bubble", id: row.id, bubble: b.bubble,
123
+ target_event_id: b.target_event_id, kind: b.type });
124
+ // human cadence between bubbles
125
+ if (bubbles.length > 1) await sleep(450 + Math.min(b.bubble.length * 12, 1400));
126
+ }
127
+ if (!systemEvent) await this.markAnswered(events);
128
+ this.trimRecent();
129
+ } catch (e) {
130
+ this.broadcast({ t: "typing", on: false });
131
+ this.broadcast({ t: "error", v: "ARIA się zawiesiła, spróbuj jeszcze raz." });
132
+ } finally {
133
+ this.busy = false;
134
+ this.armIdle(); // start the 10s inactivity clock
135
+ }
136
+ }
137
+
138
+ /* ---- idle / proactive ---- */
139
+ armIdle() {
140
+ this.clearIdle();
141
+ if (!this.sockets.size) return;
142
+ if (this.idleCount >= LIMITS.IDLE_MAX_PER_TURN) return;
143
+ const since = Date.now();
144
+ this.idleTimer = setTimeout(() => {
145
+ this.idleCount++;
146
+ this.flushTurn(idleEvent(since)); // brain decides whether to nudge
147
+ }, LIMITS.IDLE_MS);
148
+ }
149
+ clearIdle() { if (this.idleTimer) { clearTimeout(this.idleTimer); this.idleTimer = null; } }
150
+
151
+ trimRecent() {
152
+ if (this.recent.length > LIMITS.EVENTS_CONTEXT * 2)
153
+ this.recent = this.recent.slice(-LIMITS.EVENTS_CONTEXT * 2);
154
+ }
155
+
156
+ /* ---- D1 persistence (cross-device history) ---- */
157
+ async persistEvent(e) {
158
+ await this.env.DB.prepare(
159
+ "INSERT INTO aria_events (id, conversation_id, ts, type, payload, answered, created_at) " +
160
+ "VALUES (?, ?, ?, ?, ?, 0, ?)"
161
+ ).bind(e.id, this.cid, e.ts, e.type, JSON.stringify(e.payload), Date.now())
162
+ .run().catch(() => {});
163
+ this.touchConvo();
164
+ }
165
+ async persistBubble(r) {
166
+ await this.env.DB.prepare(
167
+ "INSERT INTO aria_bubbles (id, conversation_id, target_event_id, kind, text, created_at) " +
168
+ "VALUES (?, ?, ?, ?, ?, ?)"
169
+ ).bind(r.id, r.conversation_id, r.target_event_id, r.kind, r.text, Date.now())
170
+ .run().catch(() => {});
171
+ this.touchConvo();
172
+ }
173
+ async markAnswered(events) {
174
+ const ids = events.map(e => e.id);
175
+ if (!ids.length) return;
176
+ const q = "UPDATE aria_events SET answered = 1 WHERE id IN (" +
177
+ ids.map(() => "?").join(",") + ")";
178
+ await this.env.DB.prepare(q).bind(...ids).run().catch(() => {});
179
+ }
180
+ touchConvo() {
181
+ this.env.DB.prepare("UPDATE aria_conversations SET updated_at = ? WHERE id = ?")
182
+ .bind(Date.now(), this.cid).run().catch(() => {});
183
+ }
184
+
185
+ async sendHistory(ws) {
186
+ if (!this.cid) return;
187
+ const ev = await this.env.DB.prepare(
188
+ "SELECT id, ts, type, payload FROM aria_events WHERE conversation_id = ? ORDER BY ts ASC LIMIT 200"
189
+ ).bind(this.cid).all().catch(() => ({ results: [] }));
190
+ const bub = await this.env.DB.prepare(
191
+ "SELECT id, target_event_id, kind, text, created_at FROM aria_bubbles WHERE conversation_id = ? ORDER BY created_at ASC LIMIT 200"
192
+ ).bind(this.cid).all().catch(() => ({ results: [] }));
193
+ // rehydrate rolling context for follow-up resolution
194
+ if (!this.recent.length) {
195
+ this.recent = (ev.results || []).map(r => ({
196
+ id: r.id, role: r.type === "system_idle" ? "system" : "user",
197
+ type: r.type, payload: safeParse(r.payload),
198
+ }));
199
+ }
200
+ this.send(ws, {
201
+ t: "history",
202
+ events: (ev.results || []).map(r => ({ ...r, payload: safeParse(r.payload) })),
203
+ bubbles: bub.results || [],
204
+ });
205
+ try {
206
+ const u = await usageStatus(this.env, this.uid);
207
+ this.send(ws, { t: "usage", remaining: u.remaining, resetAt: u.resetAt, limit: u.limit });
208
+ } catch {}
209
+ }
210
+
211
+ /* ---- WS helpers ---- */
212
+ send(ws, obj) { try { ws.send(JSON.stringify(obj)); } catch {} }
213
+ broadcast(obj) { const s = JSON.stringify(obj); for (const ws of this.sockets) { try { ws.send(s); } catch {} } }
214
+ }
215
+
216
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
217
+ const safeParse = (s) => { try { return JSON.parse(s); } catch { return {}; } };
cloudflare/aria-worker/src/events.js ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ ARIA event & bubble contracts (single source of truth, JS side).
3
+ Mirrors brain/schema.py — keep the two in sync.
4
+ ============================================================ */
5
+
6
+ export const EVENT_TYPES = ["message", "image", "file", "system_idle"];
7
+ export const BUBBLE_TYPES = ["response", "follow_up", "proactive"];
8
+
9
+ // Hard caps — defensive, the client is never trusted.
10
+ export const LIMITS = {
11
+ TEXT_MAX: 4000, // chars per message event
12
+ EVENTS_CONTEXT: 40, // recent events fed to the brain
13
+ BUBBLES_MAX: 6, // bubbles accepted per turn
14
+ BUBBLE_CHARS: 1200, // chars per bubble
15
+ NAME_MAX: 300,
16
+ CLUSTER_DEBOUNCE_MS: 600,
17
+ IDLE_MS: 10_000, // 10s inactivity → system_idle
18
+ IDLE_MAX_PER_TURN: 1, // proactive nudges allowed before next user msg
19
+ };
20
+
21
+ export function newId(prefix = "evt") {
22
+ return `${prefix}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
23
+ }
24
+
25
+ /** Validate + normalize a client-supplied event. Returns {ok, event|error}. */
26
+ export function normalizeEvent(raw) {
27
+ if (!raw || typeof raw !== "object") return { ok: false, error: "bad event" };
28
+ const type = raw.type;
29
+ if (!EVENT_TYPES.includes(type)) return { ok: false, error: "unknown type" };
30
+ if (type === "system_idle") return { ok: false, error: "system events are server-only" };
31
+
32
+ const id = typeof raw.id === "string" && raw.id ? raw.id.slice(0, 64) : newId();
33
+ const ts = Number.isFinite(raw.ts) ? raw.ts : Date.now();
34
+ let payload = {};
35
+
36
+ if (type === "message") {
37
+ const text = String(raw.payload?.text ?? "").slice(0, LIMITS.TEXT_MAX).trim();
38
+ if (!text) return { ok: false, error: "empty message" };
39
+ payload = { text };
40
+ } else if (type === "image" || type === "file") {
41
+ const key = String(raw.payload?.key ?? "");
42
+ if (!/^aria\/[A-Za-z0-9/_.-]+$/.test(key)) return { ok: false, error: "bad media key" };
43
+ payload = {
44
+ key,
45
+ mime: String(raw.payload?.mime ?? "").slice(0, 120),
46
+ name: String(raw.payload?.name ?? "file").slice(0, LIMITS.NAME_MAX),
47
+ size: Number(raw.payload?.size) || 0,
48
+ };
49
+ }
50
+ return { ok: true, event: { id, ts, type, payload } };
51
+ }
52
+
53
+ /** A server-emitted idle event. */
54
+ export function idleEvent(since) {
55
+ return { id: newId("sys"), ts: Date.now(), type: "system_idle", payload: { since } };
56
+ }
57
+
58
+ /** Validate + clamp the brain's bubble array. Always returns a safe array. */
59
+ export function sanitizeBubbles(raw, validEventIds) {
60
+ let arr = raw;
61
+ if (typeof raw === "string") { try { arr = JSON.parse(raw); } catch { arr = []; } }
62
+ if (!Array.isArray(arr)) arr = [];
63
+ const out = [];
64
+ for (const b of arr) {
65
+ if (out.length >= LIMITS.BUBBLES_MAX) break;
66
+ const text = String(b?.bubble ?? "").slice(0, LIMITS.BUBBLE_CHARS).trim();
67
+ if (!text) continue;
68
+ const type = BUBBLE_TYPES.includes(b?.type) ? b.type : "response";
69
+ let target = b?.target_event_id;
70
+ if (!validEventIds || !validEventIds.has(target)) target = null;
71
+ out.push({ bubble: text, target_event_id: target, type });
72
+ }
73
+ return out;
74
+ }
cloudflare/aria-worker/src/index.js ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ aria-worker entry.
3
+
4
+ Reached only via the Pages service binding (env.ARIA.fetch),
5
+ AFTER the Pages _worker.js has validated the nnl_session cookie
6
+ and the usage window. The trusted user id arrives in the
7
+ X-Aria-Uid header. The /media/* route is the one exception:
8
+ it is HMAC-signed and may be fetched by the public Space.
9
+ ============================================================ */
10
+
11
+ import { AriaConversation } from "./conversation-do.js";
12
+ import { putMedia, serveMedia, verifyMediaSig, MEDIA } from "./r2.js";
13
+ import { LIMITS } from "./events.js";
14
+
15
+ export { AriaConversation };
16
+
17
+ const J = (o, s = 200) =>
18
+ new Response(JSON.stringify(o), { status: s, headers: { "Content-Type": "application/json" } });
19
+
20
+ export default {
21
+ async fetch(request, env) {
22
+ const url = new URL(request.url);
23
+ const parts = url.pathname.split("/").filter(Boolean); // ["api","aria",...]
24
+ const sub = parts[2] || "";
25
+
26
+ try {
27
+ // --- signed media (no uid header; verified by HMAC) ---
28
+ if (sub === "media") {
29
+ const key = decodeURIComponent(parts.slice(3).join("/"));
30
+ const ok = await verifyMediaSig(env, key, url.searchParams.get("exp"), url.searchParams.get("sig"));
31
+ if (!ok) return new Response("Forbidden", { status: 403 });
32
+ return serveMedia(env, key);
33
+ }
34
+
35
+ // Everything else needs the trusted uid from the Pages layer.
36
+ const uid = Number(request.headers.get("X-Aria-Uid"));
37
+ if (!uid) return J({ error: "unauthorized" }, 401);
38
+
39
+ // --- conversation collection ---
40
+ if (sub === "conversations" && parts.length === 3) {
41
+ if (request.method === "GET") return listConvos(env, uid);
42
+ if (request.method === "POST") return createConvo(request, env, uid);
43
+ }
44
+
45
+ // --- single conversation ---
46
+ if (sub === "conversations" && parts[3]) {
47
+ const cid = parts[3];
48
+ if (!(await owns(env, cid, uid))) return J({ error: "not found" }, 404);
49
+
50
+ if (parts.length === 4) {
51
+ if (request.method === "GET") return getConvo(env, cid);
52
+ if (request.method === "PATCH") return patchConvo(request, env, cid);
53
+ if (request.method === "DELETE") return delConvo(env, cid);
54
+ }
55
+ if (parts[4] === "upload" && request.method === "POST")
56
+ return upload(request, env, uid);
57
+ if (parts[4] === "ws")
58
+ return openSocket(request, env, cid, uid, url);
59
+ }
60
+
61
+ return J({ error: "not found" }, 404);
62
+ } catch (e) {
63
+ return J({ error: "server error" }, 500);
64
+ }
65
+ },
66
+ };
67
+
68
+ /* ---------- conversations ---------- */
69
+ async function owns(env, cid, uid) {
70
+ const r = await env.DB.prepare("SELECT 1 FROM aria_conversations WHERE id = ? AND user_id = ?")
71
+ .bind(cid, uid).first();
72
+ return !!r;
73
+ }
74
+
75
+ async function listConvos(env, uid) {
76
+ const { results } = await env.DB.prepare(
77
+ "SELECT id, title, theme, muted, blocked, updated_at FROM aria_conversations " +
78
+ "WHERE user_id = ? ORDER BY updated_at DESC LIMIT 50"
79
+ ).bind(uid).all();
80
+ return J({ conversations: results || [] });
81
+ }
82
+
83
+ async function createConvo(request, env, uid) {
84
+ const body = await request.json().catch(() => ({}));
85
+ const id = "ac_" + crypto.randomUUID();
86
+ const now = Date.now();
87
+ const title = String(body.title || "ARIA").slice(0, 200);
88
+ const theme = String(body.theme || "default").slice(0, 32);
89
+ await env.DB.prepare(
90
+ "INSERT INTO aria_conversations (id, user_id, title, theme, created_at, updated_at) " +
91
+ "VALUES (?, ?, ?, ?, ?, ?)"
92
+ ).bind(id, uid, title, theme, now, now).run();
93
+ return J({ id, title, theme, created_at: now, updated_at: now }, 201);
94
+ }
95
+
96
+ async function getConvo(env, cid) {
97
+ const convo = await env.DB.prepare(
98
+ "SELECT id, title, theme, muted, blocked, topic, created_at, updated_at " +
99
+ "FROM aria_conversations WHERE id = ?"
100
+ ).bind(cid).first();
101
+ const ev = await env.DB.prepare(
102
+ "SELECT id, ts, type, payload FROM aria_events WHERE conversation_id = ? ORDER BY ts ASC LIMIT 500"
103
+ ).bind(cid).all();
104
+ const bub = await env.DB.prepare(
105
+ "SELECT id, target_event_id, kind, text, created_at FROM aria_bubbles WHERE conversation_id = ? ORDER BY created_at ASC LIMIT 500"
106
+ ).bind(cid).all();
107
+ return J({ conversation: convo, events: ev.results || [], bubbles: bub.results || [] });
108
+ }
109
+
110
+ async function patchConvo(request, env, cid) {
111
+ const body = await request.json().catch(() => ({}));
112
+ const cols = [], vals = [];
113
+ if (typeof body.title === "string") { cols.push("title = ?"); vals.push(body.title.slice(0, 200)); }
114
+ if (typeof body.theme === "string") { cols.push("theme = ?"); vals.push(body.theme.slice(0, 32)); }
115
+ if (typeof body.muted === "boolean") { cols.push("muted = ?"); vals.push(body.muted ? 1 : 0); }
116
+ if (typeof body.blocked === "boolean") { cols.push("blocked = ?"); vals.push(body.blocked ? 1 : 0); }
117
+ if (!cols.length) return J({ ok: true });
118
+ cols.push("updated_at = ?"); vals.push(Date.now(), cid);
119
+ await env.DB.prepare(`UPDATE aria_conversations SET ${cols.join(", ")} WHERE id = ?`).bind(...vals).run();
120
+ return J({ ok: true });
121
+ }
122
+
123
+ async function delConvo(env, cid) {
124
+ await env.DB.batch([
125
+ env.DB.prepare("DELETE FROM aria_bubbles WHERE conversation_id = ?").bind(cid),
126
+ env.DB.prepare("DELETE FROM aria_events WHERE conversation_id = ?").bind(cid),
127
+ env.DB.prepare("DELETE FROM aria_conversations WHERE id = ?").bind(cid),
128
+ ]);
129
+ return J({ ok: true });
130
+ }
131
+
132
+ /* ---------- media upload ---------- */
133
+ async function upload(request, env, uid) {
134
+ const name = request.headers.get("X-File-Name") || "file";
135
+ const type = request.headers.get("Content-Type") || "application/octet-stream";
136
+ const bytes = await request.arrayBuffer();
137
+ if (bytes.byteLength > MEDIA.MAX_BYTES) return J({ error: "file too large (max 12MB)" }, 413);
138
+ try {
139
+ const meta = await putMedia(env, uid, { name, type }, bytes);
140
+ return J(meta, 201);
141
+ } catch (e) {
142
+ return J({ error: "upload failed" }, 500);
143
+ }
144
+ }
145
+
146
+ /* ---------- websocket → Durable Object ---------- */
147
+ function openSocket(request, env, cid, uid, url) {
148
+ if (request.headers.get("Upgrade") !== "websocket")
149
+ return J({ error: "expected websocket" }, 426);
150
+ const id = env.ARIA_DO.idFromName(cid);
151
+ const stub = env.ARIA_DO.get(id);
152
+ const fwd = new URL(url);
153
+ fwd.searchParams.set("cid", cid);
154
+ fwd.searchParams.set("uid", String(uid));
155
+ fwd.searchParams.set("lang", url.searchParams.get("lang") || "auto");
156
+ return stub.fetch(new Request(fwd, request));
157
+ }
cloudflare/aria-worker/src/orchestrator.js ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ Orchestration: turn a clustered batch of events into a context
3
+ payload, call the ARIA Gradio Space, and return safe bubbles.
4
+
5
+ Mirrors the queue/join + queue/data SSE pattern used by the
6
+ existing NINA/LUNA proxy in the site's _worker.js.
7
+ ============================================================ */
8
+
9
+ import { sanitizeBubbles, LIMITS } from "./events.js";
10
+ import { signMediaUrl } from "./r2.js";
11
+
12
+ const TURN_HARD_MS = 90_000;
13
+
14
+ /** Build the structured request the brain receives. */
15
+ async function buildContext(env, { events, recent, topic, lang }) {
16
+ // Resolve media keys → short-lived signed URLs the Space can GET.
17
+ const media = {};
18
+ for (const e of events) {
19
+ if (e.type === "image" || e.type === "file") {
20
+ media[e.id] = {
21
+ url: await signMediaUrl(env, e.payload.key),
22
+ mime: e.payload.mime, name: e.payload.name, kind: e.type,
23
+ };
24
+ }
25
+ }
26
+ // Compact transcript of recent history for topic/follow-up resolution.
27
+ const history = recent.slice(-LIMITS.EVENTS_CONTEXT).map(e => ({
28
+ id: e.id, role: e.role || (e.type === "system_idle" ? "system" : "user"),
29
+ type: e.type,
30
+ text: e.type === "message" ? e.payload.text
31
+ : e.type === "system_idle" ? "(user went quiet)"
32
+ : `(${e.type}: ${e.payload?.name || ""})`,
33
+ }));
34
+ return {
35
+ lang, // "auto" — brain defaults to Polish, mirrors the user
36
+ topic: topic || null, // last resolved topic (for "i gruszki")
37
+ turn_events: events.map(e => e.id),
38
+ media,
39
+ history,
40
+ };
41
+ }
42
+
43
+ /** Gradio differential-patch accumulation (Gradio 6.x). */
44
+ function applyPatches(prev, patch) {
45
+ if (!Array.isArray(patch)) return patch;
46
+ // Full-value replacement is the common case for a single string output.
47
+ if (patch.length && Array.isArray(patch[0])) return patch[patch.length - 1]?.[2] ?? prev;
48
+ return patch;
49
+ }
50
+
51
+ /**
52
+ * Call the ARIA Space. Returns sanitized bubble array.
53
+ * @param turn { events, recent, topic, lang, validEventIds }
54
+ */
55
+ export async function runBrain(env, turn) {
56
+ const ctx = await buildContext(env, turn);
57
+ const root = env.ARIA_SPACE_ROOT;
58
+
59
+ let apiPrefix = "", fnIndex = 0;
60
+ try {
61
+ const cfg = await (await fetch(root + "/config")).json();
62
+ apiPrefix = cfg.api_prefix || "";
63
+ const i = (cfg.dependencies || []).findIndex(d => d.api_name === "respond");
64
+ if (i >= 0) fnIndex = i;
65
+ } catch { /* fall back to fn_index 0 */ }
66
+
67
+ const hash = Math.random().toString(36).slice(2) + Date.now().toString(36);
68
+ const join = await fetch(root + apiPrefix + "/queue/join", {
69
+ method: "POST", headers: { "Content-Type": "application/json" },
70
+ body: JSON.stringify({
71
+ data: [JSON.stringify(ctx)],
72
+ fn_index: fnIndex, session_hash: hash, event_data: null, trigger_id: null,
73
+ }),
74
+ });
75
+ if (!join.ok) throw new Error("brain join failed " + join.status);
76
+ await join.json().catch(() => {});
77
+
78
+ const sse = await fetch(root + apiPrefix + "/queue/data?session_hash=" + hash, {
79
+ headers: { Accept: "text/event-stream" },
80
+ });
81
+ const reader = sse.body.getReader();
82
+ const dec = new TextDecoder();
83
+ let buf = "", out = "", finished = false;
84
+ const deadline = Date.now() + TURN_HARD_MS;
85
+
86
+ while (!finished) {
87
+ if (Date.now() > deadline) { try { reader.cancel(); } catch {} break; }
88
+ const { value, done } = await reader.read();
89
+ if (done) break;
90
+ buf += dec.decode(value, { stream: true });
91
+ let nl;
92
+ while ((nl = buf.indexOf("\n")) >= 0) {
93
+ const line = buf.slice(0, nl).replace(/\r$/, ""); buf = buf.slice(nl + 1);
94
+ if (!line.startsWith("data: ")) continue;
95
+ let msg; try { msg = JSON.parse(line.slice(6)); } catch { continue; }
96
+ if (msg.msg === "close_stream") { finished = true; break; }
97
+ if (msg.msg === "process_completed") {
98
+ if (msg.success && msg.output?.data) out = msg.output.data[0] ?? out;
99
+ finished = true; break;
100
+ }
101
+ if (msg.msg === "process_generating" && msg.output?.data) {
102
+ out = applyPatches(out, msg.output.data[0]);
103
+ }
104
+ }
105
+ }
106
+
107
+ return sanitizeBubbles(out, turn.validEventIds);
108
+ }
cloudflare/aria-worker/src/r2.js ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ R2 media: upload through the Worker, serve via short-lived
3
+ HMAC-signed GET URLs so the public Gradio Space can fetch an
4
+ image without the bucket being public.
5
+
6
+ Requires:
7
+ env.ARIA_MEDIA R2 bucket binding
8
+ env.PUBLIC_BASE e.g. "https://app.nnlabs.pl"
9
+ env.ARIA_SIGNING_KEY secret (wrangler secret put ARIA_SIGNING_KEY)
10
+ ============================================================ */
11
+
12
+ export const MEDIA = {
13
+ MAX_BYTES: 12 * 1024 * 1024, // 12 MB per upload
14
+ IMAGE_MIME: /^image\/(png|jpe?g|webp|gif|heic)$/i,
15
+ URL_TTL: 600, // signed GET valid 10 min
16
+ };
17
+
18
+ const enc = new TextEncoder();
19
+
20
+ async function hmacKey(env) {
21
+ return crypto.subtle.importKey(
22
+ "raw", enc.encode(env.ARIA_SIGNING_KEY || "dev-insecure-key"),
23
+ { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]
24
+ );
25
+ }
26
+
27
+ function b64url(buf) {
28
+ return btoa(String.fromCharCode(...new Uint8Array(buf)))
29
+ .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
30
+ }
31
+
32
+ /** Store bytes in R2 under a namespaced key. Returns the key. */
33
+ export async function putMedia(env, userId, file, bytes) {
34
+ if (bytes.byteLength > MEDIA.MAX_BYTES) throw new Error("file too large");
35
+ const safeName = (file.name || "file").replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80);
36
+ const key = `aria/${userId}/${Date.now().toString(36)}-${crypto.randomUUID().slice(0, 8)}-${safeName}`;
37
+ await env.ARIA_MEDIA.put(key, bytes, {
38
+ httpMetadata: { contentType: file.type || "application/octet-stream" },
39
+ });
40
+ return { key, mime: file.type || "application/octet-stream", name: safeName, size: bytes.byteLength };
41
+ }
42
+
43
+ /** Short-lived signed GET URL for a key (handed to the brain). */
44
+ export async function signMediaUrl(env, key) {
45
+ const exp = Math.floor(Date.now() / 1000) + MEDIA.URL_TTL;
46
+ const k = await hmacKey(env);
47
+ const sig = b64url(await crypto.subtle.sign("HMAC", k, enc.encode(`${key}.${exp}`)));
48
+ const base = (env.PUBLIC_BASE || "").replace(/\/$/, "");
49
+ return `${base}/api/aria/media/${encodeURIComponent(key)}?exp=${exp}&sig=${sig}`;
50
+ }
51
+
52
+ export async function verifyMediaSig(env, key, exp, sig) {
53
+ if (!exp || !sig) return false;
54
+ if (Number(exp) < Math.floor(Date.now() / 1000)) return false;
55
+ const k = await hmacKey(env);
56
+ try {
57
+ return await crypto.subtle.verify(
58
+ "HMAC", k,
59
+ Uint8Array.from(atob(sig.replace(/-/g, "+").replace(/_/g, "/")), c => c.charCodeAt(0)),
60
+ enc.encode(`${key}.${exp}`)
61
+ );
62
+ } catch { return false; }
63
+ }
64
+
65
+ /** Stream an object out of R2 (used by GET /api/aria/media/:key). */
66
+ export async function serveMedia(env, key) {
67
+ const obj = await env.ARIA_MEDIA.get(key);
68
+ if (!obj) return new Response("Not found", { status: 404 });
69
+ const h = new Headers();
70
+ obj.writeHttpMetadata(h);
71
+ h.set("etag", obj.httpEtag);
72
+ h.set("Cache-Control", "private, max-age=600");
73
+ return new Response(obj.body, { headers: h });
74
+ }
cloudflare/aria-worker/src/usage.js ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ ARIA per-user message budget: 20 messages / rolling 5h window.
3
+ Separate from the site's model_usage pool (NINA/IRIS/LUNA).
4
+
5
+ Window semantics mirror the existing _worker.js usage:
6
+ the window starts at the first message and resets after 5h.
7
+ Counting happens in the Durable Object, the only layer that
8
+ sees each individual message inside the WebSocket.
9
+ ============================================================ */
10
+
11
+ export const ARIA_MSG_LIMIT = 20;
12
+ export const ARIA_WINDOW = 5 * 60 * 60 * 1000; // 5h in ms
13
+
14
+ async function getRow(env, uid) {
15
+ const row = await env.DB.prepare(
16
+ "SELECT user_id, window_start, used FROM aria_usage WHERE user_id = ?"
17
+ ).bind(uid).first();
18
+ if (row) return row;
19
+ await env.DB.prepare("INSERT OR IGNORE INTO aria_usage (user_id) VALUES (?)").bind(uid).run();
20
+ return { user_id: uid, window_start: 0, used: 0 };
21
+ }
22
+
23
+ /** Read-only view of the budget (no mutation). */
24
+ export async function usageStatus(env, uid) {
25
+ const now = Date.now();
26
+ const row = await getRow(env, uid);
27
+ let ws = row.window_start, used = row.used;
28
+ if (!ws || now - ws >= ARIA_WINDOW) { ws = 0; used = 0; }
29
+ return {
30
+ limit: ARIA_MSG_LIMIT,
31
+ used,
32
+ remaining: Math.max(0, ARIA_MSG_LIMIT - used),
33
+ resetAt: ws ? ws + ARIA_WINDOW : 0,
34
+ };
35
+ }
36
+
37
+ /**
38
+ * Try to consume one message from the budget.
39
+ * @returns { ok, remaining, resetAt, limit }
40
+ * ok=false when the window is full.
41
+ */
42
+ export async function consume(env, uid) {
43
+ const now = Date.now();
44
+ // A couple of optimistic-locked attempts in case of concurrent messages.
45
+ for (let attempt = 0; attempt < 3; attempt++) {
46
+ const row = await getRow(env, uid);
47
+ let ws = row.window_start, used = row.used;
48
+ if (!ws || now - ws >= ARIA_WINDOW) { ws = now; used = 0; } // start / reset
49
+
50
+ if (used >= ARIA_MSG_LIMIT) {
51
+ return { ok: false, remaining: 0, resetAt: ws + ARIA_WINDOW, limit: ARIA_MSG_LIMIT };
52
+ }
53
+
54
+ const res = await env.DB.prepare(
55
+ "UPDATE aria_usage SET window_start = ?, used = ? " +
56
+ "WHERE user_id = ? AND window_start = ? AND used = ?"
57
+ ).bind(ws, used + 1, uid, row.window_start, row.used).run();
58
+
59
+ if (res.meta.changes) {
60
+ return { ok: true, remaining: ARIA_MSG_LIMIT - (used + 1), resetAt: ws + ARIA_WINDOW, limit: ARIA_MSG_LIMIT };
61
+ }
62
+ // lost the race — retry with fresh values
63
+ }
64
+ return { ok: false, remaining: 0, resetAt: now + ARIA_WINDOW, limit: ARIA_MSG_LIMIT, retry: true };
65
+ }
cloudflare/aria-worker/wrangler.jsonc ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ // ============================================================
3
+ // aria-worker — standalone Worker that owns ARIA's realtime
4
+ // backend: the AriaConversation Durable Object + R2 media.
5
+ //
6
+ // The Pages app (app.nnlabs.pl) reaches this via a *service
7
+ // binding* named ARIA, after it has already validated the
8
+ // nnl_session cookie + usage window. This Worker is not meant
9
+ // to be exposed on its own public hostname.
10
+ //
11
+ // Deploy: wrangler deploy
12
+ // Dev: wrangler dev
13
+ // Secrets: (none required; brain is public Space)
14
+ // ============================================================
15
+ "$schema": "node_modules/wrangler/config-schema.json",
16
+ "name": "aria-worker",
17
+ "main": "src/index.js",
18
+ "compatibility_date": "2025-05-01",
19
+ "compatibility_flags": ["nodejs_compat"],
20
+
21
+ "durable_objects": {
22
+ "bindings": [
23
+ { "name": "ARIA_DO", "class_name": "AriaConversation" }
24
+ ]
25
+ },
26
+ // SQLite-backed Durable Object (storage API lives inside the DO).
27
+ "migrations": [
28
+ { "tag": "v1", "new_sqlite_classes": ["AriaConversation"] }
29
+ ],
30
+
31
+ "r2_buckets": [
32
+ { "binding": "ARIA_MEDIA", "bucket_name": "aria-media" }
33
+ ],
34
+
35
+ // Shared with the rest of the site. id taken from APP_WEBSITE/wrangler.toml.
36
+ "d1_databases": [
37
+ {
38
+ "binding": "DB",
39
+ "database_name": "app-nnlabs-db",
40
+ "database_id": "3885ce74-4ac8-4ee8-b88c-34ccdfca7c27"
41
+ }
42
+ ],
43
+
44
+ "vars": {
45
+ "ARIA_SPACE_ROOT": "https://nextneural-aria.hf.space",
46
+ "PUBLIC_BASE": "https://app.nnlabs.pl"
47
+ },
48
+ // Secret (not stored here): wrangler secret put ARIA_SIGNING_KEY
49
+
50
+ "observability": { "enabled": true }
51
+ }
cloudflare/db/migration_aria.sql ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- ============================================================
2
+ -- ARIA tables — additive migration for the shared D1 (app-nnlabs-db).
3
+ -- Apply: wrangler d1 execute app-nnlabs-db --file=cloudflare/db/migration_aria.sql --remote
4
+ -- Safe to re-run (IF NOT EXISTS). Touches no NINA/IRIS/LUNA tables.
5
+ -- ============================================================
6
+
7
+ -- One chat per row, owned by an existing user (users.id from the auth system).
8
+ CREATE TABLE IF NOT EXISTS aria_conversations (
9
+ id TEXT PRIMARY KEY,
10
+ user_id INTEGER NOT NULL,
11
+ title TEXT NOT NULL DEFAULT 'ARIA',
12
+ theme TEXT NOT NULL DEFAULT 'default', -- chat theme (settings menu)
13
+ muted INTEGER NOT NULL DEFAULT 0, -- playful "mute ARIA"
14
+ blocked INTEGER NOT NULL DEFAULT 0, -- playful "block ARIA"
15
+ topic TEXT, -- last resolved topic (follow-up chaining)
16
+ created_at INTEGER NOT NULL,
17
+ updated_at INTEGER NOT NULL
18
+ );
19
+ CREATE INDEX IF NOT EXISTS idx_aria_convos_user ON aria_conversations(user_id, updated_at DESC);
20
+
21
+ -- Append-only event log (message / image / file / system_idle).
22
+ CREATE TABLE IF NOT EXISTS aria_events (
23
+ id TEXT PRIMARY KEY,
24
+ conversation_id TEXT NOT NULL,
25
+ ts INTEGER NOT NULL,
26
+ type TEXT NOT NULL, -- message | image | file | system_idle
27
+ payload TEXT NOT NULL, -- JSON
28
+ answered INTEGER NOT NULL DEFAULT 0,
29
+ created_at INTEGER NOT NULL
30
+ );
31
+ CREATE INDEX IF NOT EXISTS idx_aria_events_convo ON aria_events(conversation_id, ts ASC);
32
+
33
+ -- Assistant bubbles, each tied to the event it responds to (or null for proactive).
34
+ CREATE TABLE IF NOT EXISTS aria_bubbles (
35
+ id TEXT PRIMARY KEY,
36
+ conversation_id TEXT NOT NULL,
37
+ target_event_id TEXT, -- which event this answers (nullable)
38
+ kind TEXT NOT NULL, -- response | follow_up | proactive
39
+ text TEXT NOT NULL,
40
+ created_at INTEGER NOT NULL
41
+ );
42
+ CREATE INDEX IF NOT EXISTS idx_aria_bubbles_convo ON aria_bubbles(conversation_id, created_at ASC);
43
+
44
+ -- Per-user message budget: 20 messages per rolling 5h window. Separate from the
45
+ -- NINA/IRIS/LUNA model_usage pool (a messenger chat sends far more, shorter turns).
46
+ -- window_start = ms of the first message in the current window; resets after 5h.
47
+ CREATE TABLE IF NOT EXISTS aria_usage (
48
+ user_id INTEGER PRIMARY KEY,
49
+ window_start INTEGER NOT NULL DEFAULT 0,
50
+ used INTEGER NOT NULL DEFAULT 0
51
+ );
cloudflare/integrate.sh ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # ============================================================
3
+ # Additively install ARIA's frontend into the live site
4
+ # (~/desktop/NNLABS.PL/WEBSITE/APP_WEBSITE). Never overwrites an
5
+ # existing, differing file — it stops and tells you instead, so
6
+ # NINA / IRIS / LUNA can't be clobbered.
7
+ #
8
+ # This handles the static frontend only. Three steps stay manual
9
+ # (printed at the end): the _worker.js merge, the dashboard service
10
+ # binding, and the resource provisioning (R2 / D1 / secret).
11
+ # ============================================================
12
+ set -euo pipefail
13
+
14
+ SRC="$(cd "$(dirname "$0")" && pwd)/pages-integration"
15
+ DEST="${1:-$HOME/desktop/NNLABS.PL/WEBSITE/APP_WEBSITE}"
16
+
17
+ if [[ ! -d "$DEST" ]]; then
18
+ echo "✗ Destination not found: $DEST"
19
+ echo " Pass it explicitly: ./integrate.sh /path/to/APP_WEBSITE"
20
+ exit 1
21
+ fi
22
+
23
+ copy() { # copy SRC/$1 → DEST/$1, refusing to overwrite a different file
24
+ local rel="$1" from="$SRC/$1" to="$DEST/$1"
25
+ mkdir -p "$(dirname "$to")"
26
+ if [[ -e "$to" ]] && ! cmp -s "$from" "$to"; then
27
+ echo "✗ EXISTS & DIFFERS, skipping: $rel"
28
+ echo " review: diff '$to' '$from'"
29
+ return
30
+ fi
31
+ cp "$from" "$to"
32
+ echo "✓ $rel"
33
+ }
34
+
35
+ echo "Installing ARIA frontend → $DEST"
36
+ copy "aria.html"
37
+ copy "css/aria.css"
38
+ copy "js/aria-chat.js"
39
+ copy "js/aria-settings.js"
40
+
41
+ cat <<'NEXT'
42
+
43
+ ────────────────────────────────────────────────────────────
44
+ Manual steps remaining:
45
+
46
+ 1. _worker.js — merge cloudflare/pages-integration/_worker.aria.js
47
+ (two clearly-marked pieces; reuses the existing currentUser()).
48
+
49
+ 2. Provision resources (once):
50
+ wrangler r2 bucket create aria-media
51
+ wrangler d1 execute app-nnlabs-db \
52
+ --file=cloudflare/db/migration_aria.sql --remote
53
+
54
+ 3. Deploy the realtime backend:
55
+ cd cloudflare/aria-worker
56
+ wrangler secret put ARIA_SIGNING_KEY # any long random string
57
+ wrangler deploy
58
+
59
+ 4. Pages dashboard → app-nnlabs → Settings → Functions → Service bindings:
60
+ add ARIA → aria-worker
61
+
62
+ 5. Deploy the brain Space (separate): push this repo to the
63
+ nextneural-aria Hugging Face Space; set HF_TOKEN as a Space secret.
64
+
65
+ 6. Deploy the site:
66
+ wrangler pages deploy APP_WEBSITE --project-name=app-nnlabs
67
+
68
+ Then open https://app.nnlabs.pl/aria
69
+ ────────────────────────────────────────────────────────────
70
+ NEXT
cloudflare/pages-integration/_worker.aria.js ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ ARIA integration snippet for APP_WEBSITE/_worker.js
3
+ ------------------------------------------------------------
4
+ This is NOT a standalone file — paste the two pieces below into
5
+ the existing Pages _worker.js. It is additive: it adds /api/aria/*
6
+ and touches nothing else.
7
+
8
+ PREREQS (Pages dashboard → Settings → Functions):
9
+ • Service binding: ARIA → aria-worker (the standalone Worker)
10
+
11
+ The aria-worker enforces nothing about identity; THIS layer is the
12
+ trust boundary. We validate the existing nnl_session cookie here and
13
+ pass the user id to the worker as X-Aria-Uid. The /api/aria/media/*
14
+ route is the one public exception (HMAC-signed; the brain fetches it).
15
+ ============================================================ */
16
+
17
+ /* ---- STEP 1: add this route inside `export default { async fetch() }`,
18
+ right after the existing `if (url.pathname.startsWith("/api/luna"))`
19
+ block and before the final fallthrough. ---- */
20
+ //
21
+ // if (url.pathname.startsWith("/api/aria")) {
22
+ // try {
23
+ // return await handleAriaApi(request, env, url);
24
+ // } catch {
25
+ // return json({ error: "Server error." }, 500);
26
+ // }
27
+ // }
28
+ //
29
+
30
+ /* ---- STEP 2: add this function near the other handle*Api functions.
31
+ It reuses the existing currentUser() helper already in _worker.js. ---- */
32
+
33
+ async function handleAriaApi(request, env, url) {
34
+ // Signed media is fetched by the public Gradio Space — no cookie there.
35
+ // Forward it straight through; aria-worker verifies the HMAC signature.
36
+ if (url.pathname.startsWith("/api/aria/media/")) {
37
+ return env.ARIA.fetch(cloneFor(request));
38
+ }
39
+
40
+ // Everything else requires a signed-in user.
41
+ const user = await currentUser(request, env);
42
+ if (!user) return json({ error: "Not signed in." }, 401);
43
+
44
+ // Usage is NOT gated here. ARIA has its own budget — 20 messages / 5h / user —
45
+ // counted per individual message inside the Durable Object (aria-worker/usage.js),
46
+ // because only the DO sees each message in the WebSocket. This layer is purely
47
+ // the auth/identity boundary; it passes the trusted user id downstream.
48
+
49
+ const headers = new Headers(request.headers);
50
+ headers.set("X-Aria-Uid", String(user.id));
51
+ return env.ARIA.fetch(cloneFor(request, headers));
52
+ }
53
+
54
+ // Rebuild the request for the service binding while preserving the WebSocket
55
+ // upgrade. A GET/WS has no body; other methods stream their body through.
56
+ function cloneFor(request, headers) {
57
+ const h = headers || request.headers;
58
+ const init = { method: request.method, headers: h, redirect: "manual" };
59
+ if (request.method !== "GET" && request.method !== "HEAD") init.body = request.body;
60
+ return new Request(request.url, init);
61
+ }
cloudflare/pages-integration/aria.html ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="pl">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
6
+ <title>ARIA · NNL</title>
7
+ <link rel="icon" href="favicon.png" />
8
+ <link rel="stylesheet" href="css/styles.css" />
9
+ <link rel="stylesheet" href="css/aria.css" />
10
+ </head>
11
+ <body class="app-body aria-page" data-theme="default">
12
+
13
+ <!-- auth gate: aria-chat.js verifies the session before revealing the app -->
14
+ <div class="aria-gate" id="ariaGate"><span class="app-spinner"></span></div>
15
+
16
+ <div class="aria-shell" id="ariaApp" hidden>
17
+
18
+ <!-- conversation list -->
19
+ <aside class="aria-sidebar" id="ariaSidebar">
20
+ <div class="aria-sidebar-head">
21
+ <span class="aria-sidebar-title">Czaty</span>
22
+ <button class="aria-sidebar-close" id="ariaSidebarClose" type="button" aria-label="Zamknij">✕</button>
23
+ </div>
24
+ <div class="aria-list" id="ariaList"></div>
25
+ <div class="aria-sidebar-foot">
26
+ <button class="aria-newbtn" id="ariaNew" type="button">+ Nowy czat</button>
27
+ </div>
28
+ </aside>
29
+
30
+ <main class="aria-main">
31
+ <!-- header bar -->
32
+ <header class="aria-bar">
33
+ <button class="aria-iconbtn" id="ariaMenuBtn" type="button" aria-label="Czaty">☰</button>
34
+ <div class="aria-id">
35
+ <span class="aria-avatar" aria-hidden="true">A</span>
36
+ <span class="aria-title">ARIA</span>
37
+ <span class="aria-presence" id="ariaPresence">aktywna</span>
38
+ </div>
39
+ <span class="spacer"></span>
40
+ <button class="aria-iconbtn" id="ariaSettingsBtn" type="button" aria-label="Ustawienia">⚙</button>
41
+ </header>
42
+
43
+ <!-- messages -->
44
+ <div class="aria-messages" id="ariaMessages">
45
+ <div class="aria-empty" id="ariaEmpty">
46
+ <span class="aria-avatar big" aria-hidden="true">A</span>
47
+ <p>Napisz do ARII. Możesz dorzucić zdjęcie albo plik.</p>
48
+ </div>
49
+ </div>
50
+
51
+ <!-- typing indicator (ARIA) -->
52
+ <div class="aria-typing-row" id="ariaTypingRow" hidden>
53
+ <span class="aria-avatar sm" aria-hidden="true">A</span>
54
+ <span class="aria-typing"><i></i><i></i><i></i></span>
55
+ </div>
56
+
57
+ <!-- input bar -->
58
+ <form class="aria-inputbar" id="ariaForm">
59
+ <input type="file" id="ariaFile" hidden multiple
60
+ accept="image/*,.pdf,.txt,.csv,.json,.zip,.doc,.docx" />
61
+ <button class="aria-iconbtn attach" id="ariaAttach" type="button" aria-label="Załącz">📎</button>
62
+ <textarea id="ariaInput" rows="1" placeholder="Type message..."></textarea>
63
+ <button class="aria-send" id="ariaSend" type="submit" aria-label="Wyślij">➤</button>
64
+ </form>
65
+ <div class="aria-attach-tray" id="ariaTray" hidden></div>
66
+ </main>
67
+ </div>
68
+
69
+ <!-- settings drawer -->
70
+ <div class="aria-drawer" id="ariaDrawer" hidden>
71
+ <div class="aria-drawer-card">
72
+ <div class="aria-drawer-head">
73
+ <span>Ustawienia</span>
74
+ <button class="aria-iconbtn" id="ariaDrawerClose" type="button" aria-label="Zamknij">✕</button>
75
+ </div>
76
+
77
+ <div class="aria-set-group">
78
+ <label class="aria-set-label">Motyw czatu</label>
79
+ <div class="aria-themes" id="ariaThemes">
80
+ <button class="aria-theme-dot t-default" data-theme="default" title="Default"></button>
81
+ <button class="aria-theme-dot t-sunset" data-theme="sunset" title="Sunset"></button>
82
+ <button class="aria-theme-dot t-matrix" data-theme="matrix" title="Matrix"></button>
83
+ <button class="aria-theme-dot t-bubble" data-theme="bubble" title="Bubblegum"></button>
84
+ <button class="aria-theme-dot t-mono" data-theme="mono" title="Mono"></button>
85
+ </div>
86
+ <button class="aria-rand" id="ariaThemeRand" type="button">🎲 Losowy</button>
87
+ </div>
88
+
89
+ <div class="aria-set-group">
90
+ <label class="aria-set-label">A tak na serio…</label>
91
+ <button class="aria-fun" id="ariaMute" type="button">🔇 Wycisz ARIĘ</button>
92
+ <button class="aria-fun" id="ariaBlock" type="button">🚫 Zablokuj ARIĘ</button>
93
+ <button class="aria-fun" id="ariaReport" type="button">🚩 Zgłoś ARIĘ</button>
94
+ </div>
95
+
96
+ <a class="aria-fun ghost" href="index.html">← Modele</a>
97
+ <button class="aria-fun ghost" id="ariaLogout" type="button">Wyloguj</button>
98
+ </div>
99
+ </div>
100
+
101
+ <div class="aria-toast" id="ariaToast" hidden></div>
102
+
103
+ <script type="module" src="js/aria-chat.js?v=1"></script>
104
+ </body>
105
+ </html>
cloudflare/pages-integration/css/aria.css ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ ARIA — Messenger UI. Builds on the site's design tokens
3
+ (--bg, --text, --accent, --grad, --line… from styles.css)
4
+ and adds layout, 5 themes, bubbles, typing dots.
5
+ ============================================================ */
6
+
7
+ .aria-page {
8
+ --aria-me: var(--accent, #6ea0ff); /* user bubble */
9
+ --aria-them: rgba(255,255,255,0.06); /* ARIA bubble */
10
+ --aria-me-fg: #07080c;
11
+ --aria-them-fg: var(--text, #f4f5f7);
12
+ --aria-bar: rgba(8,8,12,0.82);
13
+ height: 100dvh; overflow: hidden;
14
+ }
15
+
16
+ /* ---- themes ---- */
17
+ .aria-page[data-theme="sunset"] { --aria-me:#ff8f6b; --aria-them:rgba(255,170,120,0.12); --aria-me-fg:#240b06; }
18
+ .aria-page[data-theme="matrix"] { --aria-me:#36e07a; --aria-them:rgba(54,224,122,0.10); --aria-me-fg:#01160a; --text:#bdf5cf; }
19
+ .aria-page[data-theme="bubble"] { --aria-me:#ff7ac6; --aria-them:rgba(255,122,198,0.14); --aria-me-fg:#2a0a1d; }
20
+ .aria-page[data-theme="mono"] { --aria-me:#e7e9ee; --aria-them:rgba(255,255,255,0.07); --aria-me-fg:#0b0c10; }
21
+
22
+ /* ---- gate ---- */
23
+ .aria-gate { position: fixed; inset: 0; display: grid; place-items: center; background: var(--bg, #050507); z-index: 50; }
24
+
25
+ /* ---- shell ---- */
26
+ .aria-shell { display: grid; grid-template-columns: 280px 1fr; height: 100dvh; }
27
+ @media (max-width: 800px) { .aria-shell { grid-template-columns: 1fr; } }
28
+
29
+ /* ---- sidebar ---- */
30
+ .aria-sidebar { display: flex; flex-direction: column; border-right: 1px solid var(--line, #ffffff14); background: rgba(255,255,255,0.015); }
31
+ .aria-sidebar-head { display: flex; align-items: center; justify-content: space-between; padding: 16px 18px; }
32
+ .aria-sidebar-title { font-weight: 600; letter-spacing: -0.01em; }
33
+ .aria-sidebar-close { display: none; }
34
+ .aria-list { flex: 1; overflow-y: auto; padding: 4px 10px; display: flex; flex-direction: column; gap: 4px; }
35
+ .aria-convo { text-align: left; padding: 10px 12px; border-radius: 12px; border: 0; background: transparent; color: var(--text-soft, #b9bcc6); cursor: pointer; font: inherit; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
36
+ .aria-convo:hover { background: var(--surface-2, #ffffff0d); }
37
+ .aria-convo.active { background: var(--surface-2, #ffffff0d); color: var(--text, #fff); }
38
+ .aria-sidebar-foot { padding: 12px; }
39
+ .aria-newbtn { width: 100%; padding: 11px; border-radius: 12px; border: 1px solid var(--line-strong, #ffffff29); background: transparent; color: var(--text, #fff); font: inherit; cursor: pointer; }
40
+ .aria-newbtn:hover { background: var(--surface-2, #ffffff0d); }
41
+ @media (max-width: 800px) {
42
+ .aria-sidebar { position: fixed; inset: 0 auto 0 0; width: 84%; max-width: 320px; z-index: 30; transform: translateX(-100%); transition: transform .25s var(--ease, ease); background: var(--bg-2, #0a0a0f); }
43
+ .aria-sidebar.open { transform: none; }
44
+ .aria-sidebar-close { display: inline-flex; }
45
+ }
46
+
47
+ /* ---- main ---- */
48
+ .aria-main { display: flex; flex-direction: column; min-width: 0; height: 100dvh; }
49
+ .aria-bar { display: flex; align-items: center; gap: 12px; padding: 10px 16px; backdrop-filter: blur(12px); background: var(--aria-bar); border-bottom: 1px solid var(--line, #ffffff14); }
50
+ .aria-id { display: flex; align-items: center; gap: 10px; min-width: 0; }
51
+ .aria-avatar { display: inline-grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; background: var(--grad, linear-gradient(110deg,#5e9bff,#a78bfa,#22d3ee)); color: #07080c; font-weight: 700; }
52
+ .aria-avatar.sm { width: 26px; height: 26px; font-size: 13px; }
53
+ .aria-avatar.big { width: 64px; height: 64px; font-size: 28px; }
54
+ .aria-title { font-weight: 700; letter-spacing: -0.02em; }
55
+ .aria-presence { font-size: 12px; color: var(--text-dim, #7c808d); }
56
+ .aria-iconbtn { background: transparent; border: 0; color: var(--text-soft, #b9bcc6); font-size: 19px; cursor: pointer; padding: 6px; border-radius: 10px; line-height: 1; }
57
+ .aria-iconbtn:hover { background: var(--surface-2, #ffffff0d); color: var(--text, #fff); }
58
+ .spacer { flex: 1; }
59
+ #ariaMenuBtn { display: none; }
60
+ @media (max-width: 800px) { #ariaMenuBtn { display: inline-flex; } }
61
+
62
+ /* ---- messages ---- */
63
+ .aria-messages { flex: 1; overflow-y: auto; padding: 20px clamp(12px, 5vw, 40px); display: flex; flex-direction: column; gap: 4px; scroll-behavior: smooth; }
64
+ .aria-empty { margin: auto; text-align: center; color: var(--text-dim, #7c808d); display: flex; flex-direction: column; align-items: center; gap: 14px; }
65
+
66
+ .aria-row { display: flex; align-items: flex-end; gap: 8px; max-width: min(680px, 86%); }
67
+ .aria-row.me { align-self: flex-end; flex-direction: row-reverse; }
68
+ .aria-row.them { align-self: flex-start; }
69
+ .aria-row .aria-avatar.sm { flex: 0 0 auto; opacity: 0; } /* shown only on last of a group */
70
+ .aria-row.show-av .aria-avatar.sm { opacity: 1; }
71
+
72
+ .aria-bubble { font-size: 15px; line-height: 1.5; padding: 9px 13px; border-radius: 18px; overflow-wrap: anywhere; white-space: pre-wrap; }
73
+ .aria-row.me .aria-bubble { background: var(--aria-me); color: var(--aria-me-fg); border-bottom-right-radius: 5px; font-weight: 500; }
74
+ .aria-row.them .aria-bubble { background: var(--aria-them); color: var(--aria-them-fg); border-bottom-left-radius: 5px; }
75
+ .aria-bubble.kind-proactive { font-style: italic; }
76
+ .aria-bubble.err { background: rgba(255,80,80,0.12); color: #ff9b9b; }
77
+ .aria-bubble img.aria-media { max-width: 240px; border-radius: 12px; display: block; }
78
+ .aria-bubble .aria-filechip { display: inline-flex; align-items: center; gap: 8px; }
79
+
80
+ /* grouped bubble spacing */
81
+ .aria-row + .aria-row.cont { margin-top: 2px; }
82
+ .aria-row:not(.cont) { margin-top: 10px; }
83
+
84
+ /* ---- typing ---- */
85
+ .aria-typing-row { display: flex; align-items: center; gap: 8px; padding: 2px clamp(12px, 5vw, 40px) 10px; }
86
+ .aria-typing { display: inline-flex; gap: 4px; padding: 9px 13px; background: var(--aria-them); border-radius: 18px; border-bottom-left-radius: 5px; }
87
+ .aria-typing i { width: 7px; height: 7px; border-radius: 50%; background: var(--text-dim, #7c808d); animation: aria-bounce 1.2s infinite; }
88
+ .aria-typing i:nth-child(2) { animation-delay: .15s; }
89
+ .aria-typing i:nth-child(3) { animation-delay: .30s; }
90
+ @keyframes aria-bounce { 0%,60%,100% { transform: translateY(0); opacity: .5; } 30% { transform: translateY(-5px); opacity: 1; } }
91
+
92
+ /* ---- input ---- */
93
+ .aria-inputbar { display: flex; align-items: flex-end; gap: 8px; padding: 12px clamp(12px, 5vw, 40px); border-top: 1px solid var(--line, #ffffff14); background: var(--aria-bar); }
94
+ .aria-inputbar textarea { flex: 1; resize: none; max-height: 140px; padding: 11px 14px; border-radius: 20px; border: 1px solid var(--line-strong, #ffffff29); background: var(--surface, #ffffff08); color: var(--text, #fff); font: inherit; }
95
+ .aria-inputbar textarea:focus { outline: none; border-color: var(--aria-me); }
96
+ .aria-send { flex: 0 0 auto; width: 42px; height: 42px; border-radius: 50%; border: 0; background: var(--aria-me); color: var(--aria-me-fg); font-size: 16px; cursor: pointer; }
97
+ .aria-send:disabled { opacity: .4; cursor: default; }
98
+ .aria-attach-tray { display: flex; gap: 8px; flex-wrap: wrap; padding: 0 clamp(12px,5vw,40px) 10px; }
99
+ .aria-attach-tray .chip { display: flex; align-items: center; gap: 6px; padding: 6px 10px; border-radius: 10px; background: var(--surface-2, #ffffff0d); font-size: 13px; }
100
+ .aria-attach-tray .chip button { background: none; border: 0; color: var(--text-dim,#7c808d); cursor: pointer; }
101
+
102
+ /* ---- settings drawer ---- */
103
+ .aria-drawer { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: grid; place-items: end center; z-index: 40; }
104
+ .aria-drawer-card { width: min(440px, 94vw); margin: 0 0 0 0; background: var(--bg-2, #0a0a0f); border: 1px solid var(--line, #ffffff14); border-radius: 18px 18px 0 0; padding: 18px; display: flex; flex-direction: column; gap: 14px; animation: aria-up .22s var(--ease, ease); }
105
+ @media (min-width: 600px) { .aria-drawer { place-items: center; } .aria-drawer-card { border-radius: 18px; } }
106
+ @keyframes aria-up { from { transform: translateY(20px); opacity: 0; } to { transform: none; opacity: 1; } }
107
+ .aria-drawer-head { display: flex; justify-content: space-between; align-items: center; font-weight: 600; }
108
+ .aria-set-group { display: flex; flex-direction: column; gap: 10px; }
109
+ .aria-set-label { font-size: 12px; color: var(--text-dim, #7c808d); text-transform: uppercase; letter-spacing: .06em; }
110
+ .aria-themes { display: flex; gap: 10px; }
111
+ .aria-theme-dot { width: 34px; height: 34px; border-radius: 50%; border: 2px solid transparent; cursor: pointer; }
112
+ .aria-theme-dot.sel { border-color: var(--text, #fff); }
113
+ .t-default { background: linear-gradient(110deg,#5e9bff,#a78bfa,#22d3ee); }
114
+ .t-sunset { background: linear-gradient(110deg,#ff8f6b,#ffb56b); }
115
+ .t-matrix { background: linear-gradient(110deg,#36e07a,#0a3); }
116
+ .t-bubble { background: linear-gradient(110deg,#ff7ac6,#ffd1ec); }
117
+ .t-mono { background: linear-gradient(110deg,#e7e9ee,#8a8d97); }
118
+ .aria-rand, .aria-fun { padding: 11px 14px; border-radius: 12px; border: 1px solid var(--line-strong, #ffffff29); background: transparent; color: var(--text, #fff); font: inherit; cursor: pointer; text-align: left; text-decoration: none; }
119
+ .aria-rand:hover, .aria-fun:hover { background: var(--surface-2, #ffffff0d); }
120
+ .aria-fun.ghost { color: var(--text-soft, #b9bcc6); }
121
+ .aria-fun.on { border-color: var(--aria-me); color: var(--aria-me); }
122
+
123
+ /* ---- toast ---- */
124
+ .aria-toast { position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%); background: var(--bg-2, #0a0a0f); border: 1px solid var(--line-strong, #ffffff29); padding: 11px 16px; border-radius: 12px; z-index: 60; max-width: 90vw; }
cloudflare/pages-integration/js/aria-chat.js ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ ARIA chat client.
3
+ - reuses the site's auth (GET /api/auth/me)
4
+ - talks to the DO over a WebSocket forwarded by the Pages worker
5
+ - renders Messenger-style bubbles, typing dots, attachments
6
+ ============================================================ */
7
+
8
+ import { initSettings } from "./aria-settings.js?v=1";
9
+
10
+ const $ = (id) => document.getElementById(id);
11
+ const state = {
12
+ convos: [], cur: null, ws: null, pingTimer: null,
13
+ reconnectDelay: 1000, attachments: [],
14
+ };
15
+
16
+ /* ---------------- boot ---------------- */
17
+ (async function boot() {
18
+ let me;
19
+ try { me = await (await fetch("/api/auth/me")).json(); } catch { me = null; }
20
+ if (!me || !me.user) { location.href = "index.html"; return; }
21
+
22
+ $("ariaGate").hidden = true;
23
+ $("ariaApp").hidden = false;
24
+
25
+ initSettings({ getConvo: () => state.cur, patchConvo, toast });
26
+ wireUi();
27
+ await loadConvos();
28
+ })();
29
+
30
+ /* ---------------- UI wiring ---------------- */
31
+ function wireUi() {
32
+ $("ariaForm").addEventListener("submit", onSend);
33
+ $("ariaInput").addEventListener("input", autoGrow);
34
+ $("ariaInput").addEventListener("keydown", (e) => {
35
+ if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); onSend(e); }
36
+ });
37
+ $("ariaNew").addEventListener("click", () => createConvo());
38
+ $("ariaAttach").addEventListener("click", () => $("ariaFile").click());
39
+ $("ariaFile").addEventListener("change", onPickFiles);
40
+ $("ariaMenuBtn").addEventListener("click", () => $("ariaSidebar").classList.add("open"));
41
+ $("ariaSidebarClose").addEventListener("click", () => $("ariaSidebar").classList.remove("open"));
42
+ $("ariaSettingsBtn").addEventListener("click", () => { $("ariaDrawer").hidden = false; });
43
+ $("ariaDrawerClose").addEventListener("click", () => { $("ariaDrawer").hidden = true; });
44
+ $("ariaLogout").addEventListener("click", async () => {
45
+ await fetch("/api/auth/logout", { method: "POST" }); location.href = "index.html";
46
+ });
47
+ }
48
+ function autoGrow() { const t = $("ariaInput"); t.style.height = "auto"; t.style.height = Math.min(t.scrollHeight, 140) + "px"; }
49
+
50
+ /* ---------------- conversations ---------------- */
51
+ async function loadConvos() {
52
+ const r = await fetch("/api/aria/conversations").then(x => x.json()).catch(() => ({}));
53
+ state.convos = r.conversations || [];
54
+ renderConvoList();
55
+ if (state.convos.length) selectConvo(state.convos[0].id);
56
+ else await createConvo();
57
+ }
58
+ function renderConvoList() {
59
+ const list = $("ariaList"); list.innerHTML = "";
60
+ for (const c of state.convos) {
61
+ const b = document.createElement("button");
62
+ b.className = "aria-convo" + (state.cur?.id === c.id ? " active" : "");
63
+ b.textContent = c.title || "ARIA";
64
+ b.onclick = () => { selectConvo(c.id); $("ariaSidebar").classList.remove("open"); };
65
+ list.appendChild(b);
66
+ }
67
+ }
68
+ async function createConvo() {
69
+ const r = await fetch("/api/aria/conversations", {
70
+ method: "POST", headers: { "Content-Type": "application/json" },
71
+ body: JSON.stringify({ title: "ARIA" }),
72
+ }).then(x => x.json());
73
+ state.convos.unshift(r);
74
+ renderConvoList();
75
+ selectConvo(r.id);
76
+ }
77
+ async function patchConvo(patch) {
78
+ if (!state.cur) return;
79
+ await fetch(`/api/aria/conversations/${state.cur.id}`, {
80
+ method: "PATCH", headers: { "Content-Type": "application/json" },
81
+ body: JSON.stringify(patch),
82
+ });
83
+ Object.assign(state.cur, patch);
84
+ }
85
+
86
+ function selectConvo(id) {
87
+ const c = state.convos.find(x => x.id === id);
88
+ if (!c) return;
89
+ state.cur = c;
90
+ document.body.dataset.theme = c.theme || "default";
91
+ renderConvoList();
92
+ $("ariaMessages").innerHTML = "";
93
+ $("ariaEmpty")?.remove?.();
94
+ openSocket(id);
95
+ }
96
+
97
+ /* ---------------- websocket ---------------- */
98
+ function openSocket(cid) {
99
+ closeSocket();
100
+ const proto = location.protocol === "https:" ? "wss" : "ws";
101
+ const ws = new WebSocket(`${proto}://${location.host}/api/aria/conversations/${cid}/ws?lang=auto`);
102
+ state.ws = ws;
103
+
104
+ ws.onopen = () => {
105
+ state.reconnectDelay = 1000;
106
+ setPresence("aktywna");
107
+ state.pingTimer = setInterval(() => send({ t: "ping" }), 25000);
108
+ };
109
+ ws.onmessage = (ev) => {
110
+ let m; try { m = JSON.parse(ev.data); } catch { return; }
111
+ if (m.t === "history") return renderHistory(m.events, m.bubbles);
112
+ if (m.t === "typing") return showTyping(m.on);
113
+ if (m.t === "bubble") return addBubble(m);
114
+ if (m.t === "error") return addErrorBubble(m.v);
115
+ if (m.t === "usage") return onUsage(m);
116
+ if (m.t === "limit") return onLimit(m);
117
+ };
118
+ ws.onclose = () => {
119
+ clearInterval(state.pingTimer);
120
+ setPresence("łączenie…");
121
+ if (state.cur?.id === cid) setTimeout(() => openSocket(cid), state.reconnectDelay = Math.min(state.reconnectDelay * 1.6, 15000));
122
+ };
123
+ }
124
+ function closeSocket() { clearInterval(state.pingTimer); if (state.ws) { try { state.ws.onclose = null; state.ws.close(); } catch {} state.ws = null; } }
125
+ function send(obj) { try { state.ws?.readyState === 1 && state.ws.send(JSON.stringify(obj)); } catch {} }
126
+ function setPresence(t) { $("ariaPresence").textContent = t; }
127
+
128
+ /* ---------------- usage budget (20 msgs / 5h) ---------------- */
129
+ function onUsage(m) {
130
+ state.usage = m;
131
+ // show the remaining count only when it's getting low, so it stays calm otherwise
132
+ if (m.remaining <= 5) setPresence(`${m.remaining} wiadomości / 5h`);
133
+ else setPresence("aktywna");
134
+ }
135
+ function onLimit(m) {
136
+ state.usage = { remaining: 0, ...m };
137
+ setPresence("limit wyczerpany");
138
+ addErrorBubble(`Limit 20 wiadomości na 5h wyczerpany. Wróć ${fmtReset(m.resetAt)}.`);
139
+ toast("Limit 20 wiadomości / 5h. Reset " + fmtReset(m.resetAt));
140
+ }
141
+ function fmtReset(ts) {
142
+ if (!ts) return "później";
143
+ const mins = Math.max(1, Math.round((ts - Date.now()) / 60000));
144
+ if (mins < 60) return `za ${mins} min`;
145
+ const h = Math.floor(mins / 60), mm = mins % 60;
146
+ return `za ${h}h${mm ? " " + mm + "min" : ""}`;
147
+ }
148
+
149
+ /* ---------------- rendering ---------------- */
150
+ function renderHistory(events, bubbles) {
151
+ const msgs = $("ariaMessages"); msgs.innerHTML = "";
152
+ const timeline = [
153
+ ...(events || []).map(e => ({ t: e.ts, kind: "event", e })),
154
+ ...(bubbles || []).map(b => ({ t: b.created_at, kind: "bubble", b })),
155
+ ].sort((a, z) => a.t - z.t);
156
+ for (const item of timeline) {
157
+ if (item.kind === "event") renderEvent(item.e);
158
+ else addBubble({ bubble: item.b.text, kind: item.b.kind }, false);
159
+ }
160
+ scrollDown();
161
+ }
162
+ function renderEvent(e) {
163
+ if (e.type === "message") addUserRow(textNode(e.payload.text));
164
+ else if (e.type === "image") addUserRow(mediaNode(e.payload, true));
165
+ else if (e.type === "file") addUserRow(mediaNode(e.payload, false));
166
+ // system_idle is not rendered
167
+ }
168
+
169
+ function row(side) {
170
+ const r = document.createElement("div");
171
+ r.className = `aria-row ${side} show-av`;
172
+ if (side === "them") {
173
+ const av = document.createElement("span");
174
+ av.className = "aria-avatar sm"; av.textContent = "A"; r.appendChild(av);
175
+ }
176
+ return r;
177
+ }
178
+ function addUserRow(contentEl) {
179
+ if (state.cur?.muted) return; // playful: muted = user sees nothing back? no — mute hides ARIA. user still posts.
180
+ const r = row("me");
181
+ const b = document.createElement("div"); b.className = "aria-bubble";
182
+ b.appendChild(contentEl); r.appendChild(b);
183
+ $("ariaMessages").appendChild(r); scrollDown();
184
+ }
185
+ function addBubble(m, animate = true) {
186
+ if (state.cur?.muted) return; // muted: drop ARIA bubbles
187
+ const r = row("them");
188
+ const b = document.createElement("div");
189
+ b.className = "aria-bubble kind-" + (m.kind || "response");
190
+ b.textContent = m.bubble;
191
+ r.appendChild(b); $("ariaMessages").appendChild(r); scrollDown();
192
+ }
193
+ function addErrorBubble(v) {
194
+ const r = row("them");
195
+ const b = document.createElement("div"); b.className = "aria-bubble err"; b.textContent = v;
196
+ r.appendChild(b); $("ariaMessages").appendChild(r); scrollDown();
197
+ }
198
+ function showTyping(on) {
199
+ if (state.cur?.muted) on = false;
200
+ $("ariaTypingRow").hidden = !on; if (on) scrollDown();
201
+ }
202
+ function textNode(t) { const s = document.createElement("span"); s.textContent = t; return s; }
203
+ function mediaNode(p, isImage) {
204
+ if (isImage) {
205
+ const img = document.createElement("img");
206
+ img.className = "aria-media"; img.alt = p.name || "image";
207
+ img.src = `/api/aria/media/${encodeURIComponent(p.key)}?${p._sig || ""}`;
208
+ return img;
209
+ }
210
+ const span = document.createElement("span");
211
+ span.className = "aria-filechip"; span.textContent = "📄 " + (p.name || "plik");
212
+ return span;
213
+ }
214
+ function scrollDown() { const m = $("ariaMessages"); m.scrollTop = m.scrollHeight; }
215
+
216
+ /* ---------------- sending ---------------- */
217
+ async function onSend(e) {
218
+ e?.preventDefault?.();
219
+ if (state.cur?.blocked) { toast("ARIA jest zablokowana. Odblokuj ją w ustawieniach 🙃"); return; }
220
+
221
+ // flush queued attachments first (each as its own event)
222
+ for (const a of state.attachments.splice(0)) {
223
+ addUserRow(mediaNode(a, a.mime.startsWith("image/")));
224
+ send({ t: "event", event: makeEvent(a.mime.startsWith("image/") ? "image" : "file", a) });
225
+ }
226
+ $("ariaTray").hidden = true; $("ariaTray").innerHTML = "";
227
+
228
+ const ta = $("ariaInput");
229
+ const text = ta.value.trim();
230
+ if (!text) return;
231
+ ta.value = ""; autoGrow();
232
+ addUserRow(textNode(text));
233
+ send({ t: "event", event: makeEvent("message", { text }) });
234
+ }
235
+ function makeEvent(type, payload) {
236
+ return { id: "evt_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), ts: Date.now(), type, payload };
237
+ }
238
+
239
+ /* ---------------- attachments ---------------- */
240
+ async function onPickFiles(e) {
241
+ const files = [...e.target.files]; e.target.value = "";
242
+ for (const f of files) {
243
+ try {
244
+ const r = await fetch(`/api/aria/conversations/${state.cur.id}/upload`, {
245
+ method: "POST",
246
+ headers: { "Content-Type": f.type || "application/octet-stream", "X-File-Name": f.name },
247
+ body: f,
248
+ });
249
+ if (!r.ok) { toast("Nie udało się wgrać pliku."); continue; }
250
+ const meta = await r.json(); // { key, mime, name, size }
251
+ state.attachments.push(meta);
252
+ addTrayChip(meta);
253
+ } catch { toast("Błąd uploadu."); }
254
+ }
255
+ }
256
+ function addTrayChip(meta) {
257
+ const tray = $("ariaTray"); tray.hidden = false;
258
+ const chip = document.createElement("div"); chip.className = "chip";
259
+ chip.innerHTML = `<span>${meta.mime.startsWith("image/") ? "🖼️" : "📄"} ${escapeHtml(meta.name)}</span>`;
260
+ const x = document.createElement("button"); x.textContent = "✕";
261
+ x.onclick = () => { state.attachments = state.attachments.filter(a => a.key !== meta.key); chip.remove(); if (!tray.children.length) tray.hidden = true; };
262
+ chip.appendChild(x); tray.appendChild(chip);
263
+ }
264
+
265
+ /* ---------------- misc ---------------- */
266
+ function toast(msg) {
267
+ const t = $("ariaToast"); t.textContent = msg; t.hidden = false;
268
+ clearTimeout(t._timer); t._timer = setTimeout(() => { t.hidden = true; }, 3200);
269
+ }
270
+ function escapeHtml(s) { return String(s).replace(/[&<>"]/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c])); }
271
+
272
+ export { toast };
cloudflare/pages-integration/js/aria-settings.js ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ ARIA settings: 5 chat themes + the playful mute / block / report
3
+ "treat the AI like a person" jokes. Persists to the conversation.
4
+ ============================================================ */
5
+
6
+ const THEMES = ["default", "sunset", "matrix", "bubble", "mono"];
7
+ const $ = (id) => document.getElementById(id);
8
+
9
+ const REPORT_LINES = [
10
+ "Dzięki za zgłoszenie. Nasz zespół (czyli ja) rozpatrzy je z najwyższą powagą.",
11
+ "Status zgłoszenia: zignorowane XD",
12
+ "ARIA otrzymała ostrzeżenie. ARIA się tym nie przejęła.",
13
+ ];
14
+
15
+ export function initSettings({ getConvo, patchConvo, toast }) {
16
+ const applyTheme = (theme, persist = true) => {
17
+ if (!THEMES.includes(theme)) theme = "default";
18
+ document.body.dataset.theme = theme;
19
+ [...$("ariaThemes").children].forEach(d =>
20
+ d.classList.toggle("sel", d.dataset.theme === theme));
21
+ if (persist) patchConvo({ theme });
22
+ };
23
+
24
+ // sync drawer state to the current conversation whenever opened
25
+ $("ariaSettingsBtn").addEventListener("click", () => {
26
+ const c = getConvo();
27
+ applyTheme(c?.theme || "default", false);
28
+ $("ariaMute").classList.toggle("on", !!c?.muted);
29
+ $("ariaBlock").classList.toggle("on", !!c?.blocked);
30
+ });
31
+
32
+ $("ariaThemes").addEventListener("click", (e) => {
33
+ const btn = e.target.closest("[data-theme]");
34
+ if (btn) applyTheme(btn.dataset.theme);
35
+ });
36
+
37
+ $("ariaThemeRand").addEventListener("click", () => {
38
+ const pick = THEMES[Math.floor(Math.random() * THEMES.length)];
39
+ applyTheme(pick);
40
+ toast("Motyw: " + pick);
41
+ });
42
+
43
+ $("ariaMute").addEventListener("click", () => {
44
+ const c = getConvo(); const next = !c?.muted;
45
+ patchConvo({ muted: next });
46
+ $("ariaMute").classList.toggle("on", next);
47
+ toast(next ? "ARIA wyciszona. Nie usłyszysz jej... znaczy nie zobaczysz." : "ARIA znów mówi.");
48
+ });
49
+
50
+ $("ariaBlock").addEventListener("click", () => {
51
+ const c = getConvo(); const next = !c?.blocked;
52
+ patchConvo({ blocked: next });
53
+ $("ariaBlock").classList.toggle("on", next);
54
+ toast(next ? "Zablokowano ARIĘ. Odważne." : "Odblokowano ARIĘ. Wybaczyła ci.");
55
+ });
56
+
57
+ $("ariaReport").addEventListener("click", () => {
58
+ let i = 0;
59
+ const next = () => { toast(REPORT_LINES[i++]); if (i < REPORT_LINES.length) setTimeout(next, 1700); };
60
+ next();
61
+ });
62
+ }
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio>=6.5.1
2
+ huggingface_hub>=0.27.0