@adminide-stack/clock-tik-mobile 12.0.37-alpha.1 → 12.0.37-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,18 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [12.0.37-alpha.2](https://github.com/Clockbook-com/clock-tik/compare/v12.0.37-alpha.1...v12.0.37-alpha.2) (2026-11-22)
7
+
8
+ ### Bug Fixes
9
+
10
+ - **lucy:** Lucy uses her computer for sign-ins without being told, and the phone draws its hand-over ([ad0dc38](https://github.com/Clockbook-com/clock-tik/commit/ad0dc38ab582714105c197c842ce27a82b439c1d))
11
+ - **mobile:** keep Lucy's reply when the chat stops listening ([4cbee86](https://github.com/Clockbook-com/clock-tik/commit/4cbee863bcc893de0debf1616f531c87b629c6d1))
12
+
13
+ ### Features
14
+
15
+ - **clockbook-mobile:** Yantra surfaces open signed in, with no "Sign in to Yantra" card ([7a4770f](https://github.com/Clockbook-com/clock-tik/commit/7a4770fa9453d7e42b7a8f622daa7cdec725912d)), closes [adminIde-stack#5434](https://github.com/adminIde-stack/issues/5434)
16
+ - **mobile:** Lucy keeps working when the chat is left; her turns are chores ([8954de6](https://github.com/Clockbook-com/clock-tik/commit/8954de6d5bcf53cf9e35ccd53bc82a20f47007cc))
17
+
6
18
  ## [12.0.37-alpha.1](https://github.com/Clockbook-com/clock-tik/compare/v12.0.37-alpha.0...v12.0.37-alpha.1) (2026-11-22)
7
19
 
8
20
  ### Bug Fixes
package/jest.config.cjs CHANGED
@@ -11,6 +11,9 @@ const mergeData = merge.recursive(
11
11
  moduleNameMapper: {
12
12
  '^__mocks__/(.*)$': '<rootDir>/../../__mocks__/$1',
13
13
  '^lodash-es$': '<rootDir>/../../../node_modules/lodash/index.js',
14
+ // What this package reads from the browser package's build, read from its source: the tests then do not
15
+ // depend on that package having been built first.
16
+ '^@adminide-stack/clock-tik-browser/lib/(.*)\\.js$': '<rootDir>/../browser/src/$1',
14
17
  },
15
18
  roots: ['src'],
16
19
  },
package/lib/chat/agent.js CHANGED
@@ -310,6 +310,36 @@ const wait = (ms, signal) => new Promise((resolve, reject) => {
310
310
  resolve();
311
311
  }, ms);
312
312
  });
313
+ const WAITING_FOR_LAST = "Waiting for the last message to finish";
314
+ const BUSY_BACKOFF_MS = [2e3, 4e3, 8e3, 15e3, 3e4];
315
+ const BUSY_POLL_MS = 5e3;
316
+ const BUSY_GIVE_UP_MS = 25 * 6e4;
317
+ async function waitForRoom(sessionId, refusals, deadline, handlers, signal) {
318
+ handlers.onStatus(WAITING_FOR_LAST);
319
+ await wait(BUSY_BACKOFF_MS[Math.min(Math.max(refusals, 1), BUSY_BACKOFF_MS.length) - 1], signal);
320
+ for (; ; ) {
321
+ if (Date.now() > deadline)
322
+ return false;
323
+ try {
324
+ const res = await authed(`/v1/agent/session?id=${encodeURIComponent(sessionId)}`, {
325
+ method: "GET"
326
+ });
327
+ if (res.status === 404)
328
+ return true;
329
+ if (res.ok) {
330
+ const s = await res.json().catch(() => null);
331
+ const full = typeof (s == null ? void 0 : s.queued) === "boolean" ? s.queued : !!(s == null ? void 0 : s.in_flight);
332
+ if (s && !full)
333
+ return true;
334
+ }
335
+ } catch (e) {
336
+ if (signal.aborted)
337
+ throw stoppedError();
338
+ }
339
+ handlers.onStatus(WAITING_FOR_LAST);
340
+ await wait(BUSY_POLL_MS, signal);
341
+ }
342
+ }
313
343
  async function sendTurn(message, sessionId, handlers, signal, job) {
314
344
  var _a;
315
345
  let turnId = newId("turn");
@@ -318,6 +348,8 @@ async function sendTurn(message, sessionId, handlers, signal, job) {
318
348
  let attempt = 0;
319
349
  let pickups = 0;
320
350
  let shutInFront = 0;
351
+ let refusals = 0;
352
+ let busySince = 0;
321
353
  for (; ; ) {
322
354
  const line = watchLine(signal);
323
355
  try {
@@ -338,6 +370,13 @@ async function sendTurn(message, sessionId, handlers, signal, job) {
338
370
  if (shutInFront > SHUT_IN_FRONT_TRIES)
339
371
  throw err;
340
372
  await wait(1e3, signal);
373
+ } else if (err instanceof TurnError && err.kind === "busy") {
374
+ refusals += 1;
375
+ if (!busySince)
376
+ busySince = Date.now();
377
+ const room = await waitForRoom(err.sessionId || sessionId, refusals, busySince + BUSY_GIVE_UP_MS, handlers, signal);
378
+ if (!room)
379
+ throw err;
341
380
  } else {
342
381
  const e = err;
343
382
  if (!(e instanceof TurnError) || !e.retry || attempt >= BACKOFF_MS.length || e.kind === "stopped")
@@ -355,4 +394,4 @@ async function sendTurn(message, sessionId, handlers, signal, job) {
355
394
  line.end();
356
395
  }
357
396
  }
358
- }export{BACK_GRACE_MS,SILENT_MS,TurnError,cancelTurn,openSession,sendTurn,watchLine};//# sourceMappingURL=agent.js.map
397
+ }export{BACK_GRACE_MS,BUSY_BACKOFF_MS,BUSY_GIVE_UP_MS,SILENT_MS,TurnError,WAITING_FOR_LAST,cancelTurn,openSession,sendTurn,watchLine};//# sourceMappingURL=agent.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sources":["../../src/chat/agent.ts"],"sourcesContent":["/**\n * Lucy's agent over plain HTTP, as the web chat talks to it (@yantra/surface-kit agentChat.ts):\n * POST /v1/agent/session {system_prompt, permission_mode} -> {session_id}\n * POST /v1/agent/chat {message, stream, session_id, turn_id, permission_mode} -> SSE\n * POST /v1/chat/cancel X-Session-ID -> stops the turn on the agent\n * The reply streams as Server-Sent Events: session, delta, output, status, tool_call, tool_result, thinking, error, done.\n * React Native's fetch cannot read a body as it arrives; expo/fetch can.\n *\n * A turn outlives its line. The agent keeps running it when the line drops, and the same turn sent again is followed\n * to its end there, never run twice. So when the phone is locked or the app leaves the front mid-reply, the turn is\n * not failed: it waits for the app to be in front again and sends the same turn once more. A line that has gone\n * silent (the agent writes at least every 15 seconds) is let go the same way.\n */\nimport { fetch as streamFetch } from 'expo/fetch';\nimport { inFront, onFront, whenInFront } from './appFront';\nimport { agentBackendUrl, agentUrl, clearChatToken, getChatToken, isLockedOut } from './auth';\nimport type { JobRef } from './jobs';\nimport { CONTINUE_PROMPT, SYSTEM_PROMPT, joinOutput, statusLine, toolLine, visibleOutput } from './protocol';\n\nexport type TurnErrorKind = 'busy' | 'auth' | 'network' | 'service' | 'stopped';\n\nexport class TurnError extends Error {\n readonly kind: TurnErrorKind;\n /** What the agent asks for: send the same turn again, or carry on from a cut-off step. */\n readonly retry?: 'resend' | 'continue';\n readonly sessionId?: string;\n\n constructor(kind: TurnErrorKind, message: string, retry?: 'resend' | 'continue', sessionId?: string) {\n super(message);\n this.name = 'TurnError';\n this.kind = kind;\n this.retry = retry;\n this.sessionId = sessionId;\n }\n}\n\nfunction newId(prefix: string): string {\n const r = () => Math.random().toString(16).slice(2, 10);\n return `${prefix}-${Date.now().toString(16)}-${r()}${r()}`;\n}\n\nasync function authed(\n path: string,\n init: { method: string; headers?: Record<string, string>; body?: string },\n retried = false,\n) {\n const token = await getChatToken({ fresh: retried });\n const res = await fetch(`${agentUrl()}${path}`, {\n ...init,\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, ...(init.headers ?? {}) },\n });\n if (res.status === 401 && !retried) {\n await clearChatToken();\n return authed(path, init, true);\n }\n return res;\n}\n\n/** A new conversation with Lucy; its id is the chat's id from then on. */\nexport async function openSession(): Promise<string> {\n let res: Response;\n try {\n res = await authed('/v1/agent/session', {\n method: 'POST',\n body: JSON.stringify({ system_prompt: SYSTEM_PROMPT, permission_mode: 'auto' }),\n });\n } catch (err) {\n if ((err as Error).name === 'ChatAuthError') throw err;\n throw new TurnError('network', 'Could not reach Lucy. Check your connection.');\n }\n if (res.status === 401) throw new TurnError('auth', 'Sign in again to chat with Lucy');\n if (!res.ok) throw new TurnError('service', `Lucy could not start a chat (HTTP ${res.status})`);\n const j = (await res.json()) as { session_id?: string };\n if (!j.session_id) throw new TurnError('service', 'Lucy could not start a chat');\n return j.session_id;\n}\n\n/** Stops the turn on the agent; closing the stream alone would leave it running. */\nexport async function cancelTurn(sessionId: string): Promise<void> {\n await authed('/v1/chat/cancel', { method: 'POST', headers: { 'X-Session-ID': sessionId } }).catch(() => undefined);\n}\n\nexport interface TurnHandlers {\n /** The reply so far, whole, each time it grows. */\n onText: (text: string) => void;\n /** What Lucy is doing right now (a tool, a queue); null when she is writing. */\n onStatus: (line: string | null) => void;\n /** The session the turn landed on (it can differ from the one asked for). */\n onSession: (sessionId: string) => void;\n}\n\ninterface SseEvent {\n event: string;\n data: Record<string, unknown>;\n}\n\nfunction parseEvents(buffer: string): { events: SseEvent[]; rest: string } {\n const parts = buffer.replace(/\\r\\n/g, '\\n').split('\\n\\n');\n const rest = parts.pop() ?? '';\n const events = parts\n .map((block) => {\n let event = 'message';\n const data: string[] = [];\n for (const line of block.split('\\n')) {\n if (line.startsWith('event:')) event = line.slice(6).trim();\n else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));\n }\n if (!data.length) return null;\n try {\n return { event, data: JSON.parse(data.join('\\n')) as Record<string, unknown> };\n } catch {\n return { event, data: { text: data.join('\\n') } };\n }\n })\n .filter((e): e is SseEvent => e !== null);\n return { events, rest };\n}\n\n/** The agent writes on every reply line at least this often (a keepalive while it works). */\nconst AGENT_KEEPALIVE_MS = 15_000;\n/** In front and nothing heard for this long: the line is gone (two keepalives missed, and some). */\nexport const SILENT_MS = 40_000;\n/** Back in front: what a live line held while the app was away arrives at once; nothing in this long, it is gone. */\nexport const BACK_GRACE_MS = 3_000;\nconst LINE_CHECK_MS = 1_000;\n\n/**\n * The line one try reads on. It ends when the turn is stopped, or when it has gone silent: in front for SILENT_MS with\n * nothing heard, or back in front after missing a keepalive while away and nothing heard in BACK_GRACE_MS.\n */\nexport function watchLine(stop: AbortSignal) {\n const line = new AbortController();\n let heardAt = Date.now();\n let backAt = 0;\n let dead = false;\n const endLine = () => line.abort();\n stop.addEventListener('abort', endLine);\n const stopFront = onFront(() => {\n backAt = Date.now();\n });\n const timer = setInterval(() => {\n if (dead || !inFront()) return;\n const now = Date.now();\n if (backAt && now - backAt < BACK_GRACE_MS) return;\n const missedWhileAway = backAt > heardAt && backAt - heardAt > AGENT_KEEPALIVE_MS;\n if (missedWhileAway || now - heardAt > SILENT_MS) {\n dead = true;\n line.abort();\n }\n }, LINE_CHECK_MS);\n return {\n signal: line.signal,\n /** Something arrived on the line. */\n heard: () => {\n heardAt = Date.now();\n },\n /** It was let go for its silence (not stopped). */\n dead: () => dead,\n end: () => {\n clearInterval(timer);\n stopFront();\n stop.removeEventListener('abort', endLine);\n },\n };\n}\n\n/** One turn, streamed. Resolves with the whole reply; rejects with a TurnError. */\nasync function streamOnce(\n message: string,\n sessionId: string,\n turnId: string,\n prefix: string,\n handlers: TurnHandlers,\n signal: AbortSignal,\n job?: JobRef,\n heard: () => void = () => undefined,\n): Promise<string> {\n const token = await getChatToken();\n // The chore record this turn is: the agent reports to it (at the backend this token was minted on), app or no app.\n const jobFields = job ? { job, backend_graphql_url: await agentBackendUrl().catch(() => undefined) } : {};\n let res: Awaited<ReturnType<typeof streamFetch>>;\n try {\n res = await streamFetch(`${agentUrl()}/v1/agent/chat`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n message,\n stream: true,\n session_id: sessionId,\n turn_id: turnId,\n permission_mode: 'auto',\n ...jobFields,\n }),\n signal,\n });\n } catch (err) {\n if (signal.aborted) throw new TurnError('stopped', 'Stopped');\n throw new TurnError('network', `Could not reach Lucy (${(err as Error).message})`, 'resend');\n }\n if (res.status === 401) {\n await clearChatToken();\n throw new TurnError('auth', 'Sign in again to chat with Lucy', 'resend');\n }\n if (res.status === 409) throw new TurnError('busy', 'Lucy is still finishing the last message');\n if ([429, 502, 503, 504].includes(res.status))\n throw new TurnError('service', `Lucy is busy (HTTP ${res.status})`, 'resend');\n if (!res.ok || !res.body) throw new TurnError('service', `Lucy could not take that (HTTP ${res.status})`);\n\n let reply = prefix;\n let held = '';\n let done = false;\n let buffer = '';\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n const flushHeld = () => {\n if (!held) return;\n reply = joinOutput(reply, held);\n held = '';\n handlers.onText(reply);\n };\n\n try {\n for (;;) {\n const { value, done: ended } = await reader.read();\n if (ended) break;\n heard();\n buffer += decoder.decode(value, { stream: true });\n const parsed = parseEvents(buffer);\n buffer = parsed.rest;\n for (const { event, data } of parsed.events) {\n switch (event) {\n case 'session':\n if (data.session_id) handlers.onSession(String(data.session_id));\n break;\n case 'delta':\n flushHeld();\n reply += String(data.text ?? '');\n handlers.onStatus(null);\n handlers.onText(reply);\n break;\n case 'output': {\n const out = visibleOutput(String(data.text ?? ''));\n if (!out) break;\n flushHeld();\n // A warning can be the preface of a failure: show it only if no error follows.\n if (out.startsWith('⚠')) held = out;\n else {\n reply = joinOutput(reply, out);\n handlers.onText(reply);\n }\n break;\n }\n case 'status': {\n const line = statusLine(String(data.status ?? ''));\n if (line)\n handlers.onStatus(/^queued/i.test(line) ? 'Waiting for the last message to finish' : line);\n break;\n }\n case 'tool_call':\n handlers.onStatus(\n toolLine(String(data.name ?? ''), data.detail ? String(data.detail) : undefined),\n );\n break;\n case 'error': {\n held = '';\n const text = String(data.error ?? 'Something went wrong');\n const cls = String(data.class ?? '');\n const retry = data.retry === 'resend' || data.retry === 'continue' ? data.retry : undefined;\n if (cls === 'session_busy' || /busy processing a previous message/i.test(text)) {\n throw new TurnError(\n 'busy',\n 'Lucy is still finishing the last message',\n undefined,\n sessionId,\n );\n }\n const err = new TurnError('service', text, retry, sessionId);\n // A cut-off step keeps what was written so far.\n (err as TurnError & { partial?: string }).partial = reply;\n throw err;\n }\n case 'done':\n done = true;\n break;\n default:\n break;\n }\n }\n }\n } catch (err) {\n if (signal.aborted) throw new TurnError('stopped', 'Stopped');\n if (err instanceof TurnError) throw err;\n throw new TurnError('network', 'The connection to Lucy dropped', 'resend');\n }\n flushHeld();\n if (!done && reply === prefix) throw new TurnError('network', 'The connection to Lucy dropped', 'resend');\n handlers.onStatus(null);\n return reply;\n}\n\nconst BACKOFF_MS = [3000, 8000, 15000];\n/** A turn's line is picked up again at most this often (each time only follows the turn on the agent). */\nconst MAX_PICKUPS = 12;\n/** In front with the keychain still shut (it opens a moment after the unlock): read again this often, a second apart. */\nconst SHUT_IN_FRONT_TRIES = 3;\nconst stoppedError = () => new TurnError('stopped', 'Stopped');\nconst wait = (ms: number, signal: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n const onAbort = () => reject(stoppedError());\n signal.addEventListener('abort', onAbort, { once: true });\n setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n });\n\n/**\n * Sends `message` on `sessionId` and streams Lucy's reply, retrying the way the web chat does: a resend repeats the same\n * turn id (so the agent never runs it twice), a continue keeps the partial reply and asks Lucy to carry on.\n *\n * A line lost while the app was away (the phone locked, the app in the background), a keychain the lock shut, or a\n * line gone silent never fails the turn: once the app is in front, the same turn is sent again and followed to its end.\n */\nexport async function sendTurn(\n message: string,\n sessionId: string,\n handlers: TurnHandlers,\n signal: AbortSignal,\n job?: JobRef,\n): Promise<string> {\n let turnId = newId('turn');\n let text = message;\n let prefix = '';\n let attempt = 0;\n let pickups = 0;\n let shutInFront = 0;\n for (;;) {\n const line = watchLine(signal);\n try {\n return await streamOnce(text, sessionId, turnId, prefix, handlers, line.signal, job, line.heard);\n } catch (err) {\n if (signal.aborted) throw stoppedError();\n const away = !inFront();\n const lost = err instanceof TurnError && err.kind === 'network';\n if (line.dead() || (away && (lost || isLockedOut(err)))) {\n // The same turn again (resent, not retried): the agent follows the one it took to its end.\n pickups += 1;\n if (pickups > MAX_PICKUPS) throw new TurnError('network', 'The connection to Lucy dropped');\n await whenInFront(signal, stoppedError);\n handlers.onStatus('Reconnecting');\n } else if (isLockedOut(err)) {\n shutInFront += 1;\n if (shutInFront > SHUT_IN_FRONT_TRIES) throw err;\n await wait(1000, signal);\n } else {\n const e = err as TurnError & { partial?: string };\n if (!(e instanceof TurnError) || !e.retry || attempt >= BACKOFF_MS.length || e.kind === 'stopped')\n throw e;\n handlers.onStatus('Reconnecting');\n await wait(BACKOFF_MS[attempt], signal);\n attempt += 1;\n if (e.retry === 'continue') {\n prefix = e.partial ?? prefix;\n text = CONTINUE_PROMPT;\n turnId = newId('turn');\n }\n }\n } finally {\n line.end();\n }\n }\n}\n"],"names":["streamFetch"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmBO,MAAM,kBAAkB,KAAM,CAAA;AAAA,EAKnC,WAAY,CAAA,IAAA,EAAqB,OAAiB,EAAA,KAAA,EAA+B,SAAoB,EAAA;AACnG,IAAA,KAAA,CAAM,OAAO,CAAA;AALf,IAAS,aAAA,CAAA,IAAA,EAAA,MAAA,CAAA;AAET,IAAS,aAAA,CAAA,IAAA,EAAA,OAAA,CAAA;AACT,IAAS,aAAA,CAAA,IAAA,EAAA,WAAA,CAAA;AAGP,IAAA,IAAA,CAAK,IAAO,GAAA,WAAA;AACZ,IAAA,IAAA,CAAK,IAAO,GAAA,IAAA;AACZ,IAAA,IAAA,CAAK,KAAQ,GAAA,KAAA;AACb,IAAA,IAAA,CAAK,SAAY,GAAA,SAAA;AAAA;AAErB;AACA,SAAS,MAAM,MAAwB,EAAA;AACrC,EAAM,MAAA,CAAA,GAAI,MAAM,IAAA,CAAK,MAAO,EAAA,CAAE,SAAS,EAAE,CAAA,CAAE,KAAM,CAAA,CAAA,EAAG,EAAE,CAAA;AACtD,EAAO,OAAA,CAAA,EAAG,MAAU,CAAA,CAAA,EAAA,IAAA,CAAK,GAAI,EAAA,CAAE,SAAS,EAAE,CAAA,CAAA,CAAA,EAAK,CAAE,EAAA,CAAA,EAAI,CAAE,EAAA,CAAA,CAAA;AACzD;AACA,eAAe,MAAO,CAAA,IAAA,EAAc,IAIjC,EAAA,OAAA,GAAU,KAAO,EAAA;AAxCpB,EAAA,IAAA,EAAA;AAyCE,EAAM,MAAA,KAAA,GAA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ACA,SAAA;AACA,MAAA,IAAA,CAAK,GAAI,EAAA;AAAA;AACX;AAEJ"}
1
+ {"version":3,"file":"agent.js","sources":["../../src/chat/agent.ts"],"sourcesContent":["/**\n * Lucy's agent over plain HTTP, as the web chat talks to it (@yantra/surface-kit agentChat.ts):\n * POST /v1/agent/session {system_prompt, permission_mode} -> {session_id}\n * POST /v1/agent/chat {message, stream, session_id, turn_id, permission_mode} -> SSE\n * POST /v1/chat/cancel X-Session-ID -> stops the turn on the agent\n * The reply streams as Server-Sent Events: session, delta, output, status, tool_call, tool_result, thinking, error, done.\n * React Native's fetch cannot read a body as it arrives; expo/fetch can.\n *\n * A turn outlives its line. The agent keeps running it when the line drops, and the same turn sent again is followed\n * to its end there, never run twice. So when the phone is locked or the app leaves the front mid-reply, the turn is\n * not failed: it waits for the app to be in front again and sends the same turn once more. A line that has gone\n * silent (the agent writes at least every 15 seconds) is let go the same way.\n *\n * A message the agent refuses as busy is not failed either: the session is still on an earlier turn (one this phone\n * stopped listening to, or another device's) and took nothing. It waits until the agent says the session has room\n * GET /v1/agent/session?id=<session> -> {in_flight, queued}\n * and then goes, with the same turn id.\n */\nimport { fetch as streamFetch } from 'expo/fetch';\nimport { inFront, onFront, whenInFront } from './appFront';\nimport { agentBackendUrl, agentUrl, clearChatToken, getChatToken, isLockedOut } from './auth';\nimport type { JobRef } from './jobs';\nimport { CONTINUE_PROMPT, SYSTEM_PROMPT, joinOutput, statusLine, toolLine, visibleOutput } from './protocol';\n\nexport type TurnErrorKind = 'busy' | 'auth' | 'network' | 'service' | 'stopped';\n\nexport class TurnError extends Error {\n readonly kind: TurnErrorKind;\n /** What the agent asks for: send the same turn again, or carry on from a cut-off step. */\n readonly retry?: 'resend' | 'continue';\n readonly sessionId?: string;\n\n constructor(kind: TurnErrorKind, message: string, retry?: 'resend' | 'continue', sessionId?: string) {\n super(message);\n this.name = 'TurnError';\n this.kind = kind;\n this.retry = retry;\n this.sessionId = sessionId;\n }\n}\n\nfunction newId(prefix: string): string {\n const r = () => Math.random().toString(16).slice(2, 10);\n return `${prefix}-${Date.now().toString(16)}-${r()}${r()}`;\n}\n\nasync function authed(\n path: string,\n init: { method: string; headers?: Record<string, string>; body?: string },\n retried = false,\n) {\n const token = await getChatToken({ fresh: retried });\n const res = await fetch(`${agentUrl()}${path}`, {\n ...init,\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, ...(init.headers ?? {}) },\n });\n if (res.status === 401 && !retried) {\n await clearChatToken();\n return authed(path, init, true);\n }\n return res;\n}\n\n/** A new conversation with Lucy; its id is the chat's id from then on. */\nexport async function openSession(): Promise<string> {\n let res: Response;\n try {\n res = await authed('/v1/agent/session', {\n method: 'POST',\n body: JSON.stringify({ system_prompt: SYSTEM_PROMPT, permission_mode: 'auto' }),\n });\n } catch (err) {\n if ((err as Error).name === 'ChatAuthError') throw err;\n throw new TurnError('network', 'Could not reach Lucy. Check your connection.');\n }\n if (res.status === 401) throw new TurnError('auth', 'Sign in again to chat with Lucy');\n if (!res.ok) throw new TurnError('service', `Lucy could not start a chat (HTTP ${res.status})`);\n const j = (await res.json()) as { session_id?: string };\n if (!j.session_id) throw new TurnError('service', 'Lucy could not start a chat');\n return j.session_id;\n}\n\n/** Stops the turn on the agent; closing the stream alone would leave it running. */\nexport async function cancelTurn(sessionId: string): Promise<void> {\n await authed('/v1/chat/cancel', { method: 'POST', headers: { 'X-Session-ID': sessionId } }).catch(() => undefined);\n}\n\nexport interface TurnHandlers {\n /** The reply so far, whole, each time it grows. */\n onText: (text: string) => void;\n /** What Lucy is doing right now (a tool, a queue); null when she is writing. */\n onStatus: (line: string | null) => void;\n /** The session the turn landed on (it can differ from the one asked for). */\n onSession: (sessionId: string) => void;\n}\n\ninterface SseEvent {\n event: string;\n data: Record<string, unknown>;\n}\n\nfunction parseEvents(buffer: string): { events: SseEvent[]; rest: string } {\n const parts = buffer.replace(/\\r\\n/g, '\\n').split('\\n\\n');\n const rest = parts.pop() ?? '';\n const events = parts\n .map((block) => {\n let event = 'message';\n const data: string[] = [];\n for (const line of block.split('\\n')) {\n if (line.startsWith('event:')) event = line.slice(6).trim();\n else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));\n }\n if (!data.length) return null;\n try {\n return { event, data: JSON.parse(data.join('\\n')) as Record<string, unknown> };\n } catch {\n return { event, data: { text: data.join('\\n') } };\n }\n })\n .filter((e): e is SseEvent => e !== null);\n return { events, rest };\n}\n\n/** The agent writes on every reply line at least this often (a keepalive while it works). */\nconst AGENT_KEEPALIVE_MS = 15_000;\n/** In front and nothing heard for this long: the line is gone (two keepalives missed, and some). */\nexport const SILENT_MS = 40_000;\n/** Back in front: what a live line held while the app was away arrives at once; nothing in this long, it is gone. */\nexport const BACK_GRACE_MS = 3_000;\nconst LINE_CHECK_MS = 1_000;\n\n/**\n * The line one try reads on. It ends when the turn is stopped, or when it has gone silent: in front for SILENT_MS with\n * nothing heard, or back in front after missing a keepalive while away and nothing heard in BACK_GRACE_MS.\n */\nexport function watchLine(stop: AbortSignal) {\n const line = new AbortController();\n let heardAt = Date.now();\n let backAt = 0;\n let dead = false;\n const endLine = () => line.abort();\n stop.addEventListener('abort', endLine);\n const stopFront = onFront(() => {\n backAt = Date.now();\n });\n const timer = setInterval(() => {\n if (dead || !inFront()) return;\n const now = Date.now();\n if (backAt && now - backAt < BACK_GRACE_MS) return;\n const missedWhileAway = backAt > heardAt && backAt - heardAt > AGENT_KEEPALIVE_MS;\n if (missedWhileAway || now - heardAt > SILENT_MS) {\n dead = true;\n line.abort();\n }\n }, LINE_CHECK_MS);\n return {\n signal: line.signal,\n /** Something arrived on the line. */\n heard: () => {\n heardAt = Date.now();\n },\n /** It was let go for its silence (not stopped). */\n dead: () => dead,\n end: () => {\n clearInterval(timer);\n stopFront();\n stop.removeEventListener('abort', endLine);\n },\n };\n}\n\n/** One turn, streamed. Resolves with the whole reply; rejects with a TurnError. */\nasync function streamOnce(\n message: string,\n sessionId: string,\n turnId: string,\n prefix: string,\n handlers: TurnHandlers,\n signal: AbortSignal,\n job?: JobRef,\n heard: () => void = () => undefined,\n): Promise<string> {\n const token = await getChatToken();\n // The chore record this turn is: the agent reports to it (at the backend this token was minted on), app or no app.\n const jobFields = job ? { job, backend_graphql_url: await agentBackendUrl().catch(() => undefined) } : {};\n let res: Awaited<ReturnType<typeof streamFetch>>;\n try {\n res = await streamFetch(`${agentUrl()}/v1/agent/chat`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n message,\n stream: true,\n session_id: sessionId,\n turn_id: turnId,\n permission_mode: 'auto',\n ...jobFields,\n }),\n signal,\n });\n } catch (err) {\n if (signal.aborted) throw new TurnError('stopped', 'Stopped');\n throw new TurnError('network', `Could not reach Lucy (${(err as Error).message})`, 'resend');\n }\n if (res.status === 401) {\n await clearChatToken();\n throw new TurnError('auth', 'Sign in again to chat with Lucy', 'resend');\n }\n if (res.status === 409) throw new TurnError('busy', 'Lucy is still finishing the last message');\n if ([429, 502, 503, 504].includes(res.status))\n throw new TurnError('service', `Lucy is busy (HTTP ${res.status})`, 'resend');\n if (!res.ok || !res.body) throw new TurnError('service', `Lucy could not take that (HTTP ${res.status})`);\n\n let reply = prefix;\n let held = '';\n let done = false;\n let buffer = '';\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n const flushHeld = () => {\n if (!held) return;\n reply = joinOutput(reply, held);\n held = '';\n handlers.onText(reply);\n };\n\n try {\n for (;;) {\n const { value, done: ended } = await reader.read();\n if (ended) break;\n heard();\n buffer += decoder.decode(value, { stream: true });\n const parsed = parseEvents(buffer);\n buffer = parsed.rest;\n for (const { event, data } of parsed.events) {\n switch (event) {\n case 'session':\n if (data.session_id) handlers.onSession(String(data.session_id));\n break;\n case 'delta':\n flushHeld();\n reply += String(data.text ?? '');\n handlers.onStatus(null);\n handlers.onText(reply);\n break;\n case 'output': {\n const out = visibleOutput(String(data.text ?? ''));\n if (!out) break;\n flushHeld();\n // A warning can be the preface of a failure: show it only if no error follows.\n if (out.startsWith('⚠')) held = out;\n else {\n reply = joinOutput(reply, out);\n handlers.onText(reply);\n }\n break;\n }\n case 'status': {\n const line = statusLine(String(data.status ?? ''));\n if (line)\n handlers.onStatus(/^queued/i.test(line) ? 'Waiting for the last message to finish' : line);\n break;\n }\n case 'tool_call':\n handlers.onStatus(\n toolLine(String(data.name ?? ''), data.detail ? String(data.detail) : undefined),\n );\n break;\n case 'error': {\n held = '';\n const text = String(data.error ?? 'Something went wrong');\n const cls = String(data.class ?? '');\n const retry = data.retry === 'resend' || data.retry === 'continue' ? data.retry : undefined;\n if (cls === 'session_busy' || /busy processing a previous message/i.test(text)) {\n throw new TurnError(\n 'busy',\n 'Lucy is still finishing the last message',\n undefined,\n sessionId,\n );\n }\n const err = new TurnError('service', text, retry, sessionId);\n // A cut-off step keeps what was written so far.\n (err as TurnError & { partial?: string }).partial = reply;\n throw err;\n }\n case 'done':\n done = true;\n break;\n default:\n break;\n }\n }\n }\n } catch (err) {\n if (signal.aborted) throw new TurnError('stopped', 'Stopped');\n if (err instanceof TurnError) throw err;\n throw new TurnError('network', 'The connection to Lucy dropped', 'resend');\n }\n flushHeld();\n if (!done && reply === prefix) throw new TurnError('network', 'The connection to Lucy dropped', 'resend');\n handlers.onStatus(null);\n return reply;\n}\n\nconst BACKOFF_MS = [3000, 8000, 15000];\n/** A turn's line is picked up again at most this often (each time only follows the turn on the agent). */\nconst MAX_PICKUPS = 12;\n/** In front with the keychain still shut (it opens a moment after the unlock): read again this often, a second apart. */\nconst SHUT_IN_FRONT_TRIES = 3;\nconst stoppedError = () => new TurnError('stopped', 'Stopped');\nconst wait = (ms: number, signal: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n const onAbort = () => reject(stoppedError());\n signal.addEventListener('abort', onAbort, { once: true });\n setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n });\n\n/** What the reply says while its message waits for the session to finish an earlier turn. */\nexport const WAITING_FOR_LAST = 'Waiting for the last message to finish';\n/**\n * Before asking again after the n-th refusal: the session's own report can say it has room a moment before the agent\n * lets the earlier turn go (seen live on dev, cdecli 2.20.120), so each refusal waits a little longer.\n */\nexport const BUSY_BACKOFF_MS = [2000, 4000, 8000, 15_000, 30_000] as const;\n/** How often to ask while the session is on its turn. */\nconst BUSY_POLL_MS = 5000;\n/** Past the agent's own 20-minute turn limit: a session still refusing then is a real refusal. */\nexport const BUSY_GIVE_UP_MS = 25 * 60_000;\n\n/**\n * Waits until the agent says `sessionId` has room for another message: no turn held behind the one it is on\n * (`queued`), or, from an agent that does not say, not on a turn at all (`in_flight`). False past `deadline`.\n */\nasync function waitForRoom(\n sessionId: string,\n refusals: number,\n deadline: number,\n handlers: TurnHandlers,\n signal: AbortSignal,\n): Promise<boolean> {\n handlers.onStatus(WAITING_FOR_LAST);\n await wait(BUSY_BACKOFF_MS[Math.min(Math.max(refusals, 1), BUSY_BACKOFF_MS.length) - 1], signal);\n for (;;) {\n if (Date.now() > deadline) return false;\n try {\n const res = await authed(`/v1/agent/session?id=${encodeURIComponent(sessionId)}`, { method: 'GET' });\n // Gone from the agent: nothing is in the way any more.\n if (res.status === 404) return true;\n if (res.ok) {\n const s = (await res.json().catch(() => null)) as { in_flight?: boolean; queued?: boolean } | null;\n const full = typeof s?.queued === 'boolean' ? s.queued : !!s?.in_flight;\n if (s && !full) return true;\n }\n } catch {\n if (signal.aborted) throw stoppedError();\n // Unreachable for a moment, or the keychain shut: keep waiting.\n }\n handlers.onStatus(WAITING_FOR_LAST);\n await wait(BUSY_POLL_MS, signal);\n }\n}\n\n/**\n * Sends `message` on `sessionId` and streams Lucy's reply, retrying the way the web chat does: a resend repeats the same\n * turn id (so the agent never runs it twice), a continue keeps the partial reply and asks Lucy to carry on.\n *\n * A line lost while the app was away (the phone locked, the app in the background), a keychain the lock shut, or a\n * line gone silent never fails the turn: once the app is in front, the same turn is sent again and followed to its end.\n * Nor does a refusal as busy: the same turn goes once the session has room (waitForRoom), for up to BUSY_GIVE_UP_MS.\n */\nexport async function sendTurn(\n message: string,\n sessionId: string,\n handlers: TurnHandlers,\n signal: AbortSignal,\n job?: JobRef,\n): Promise<string> {\n let turnId = newId('turn');\n let text = message;\n let prefix = '';\n let attempt = 0;\n let pickups = 0;\n let shutInFront = 0;\n let refusals = 0;\n let busySince = 0;\n for (;;) {\n const line = watchLine(signal);\n try {\n return await streamOnce(text, sessionId, turnId, prefix, handlers, line.signal, job, line.heard);\n } catch (err) {\n if (signal.aborted) throw stoppedError();\n const away = !inFront();\n const lost = err instanceof TurnError && err.kind === 'network';\n if (line.dead() || (away && (lost || isLockedOut(err)))) {\n // The same turn again (resent, not retried): the agent follows the one it took to its end.\n pickups += 1;\n if (pickups > MAX_PICKUPS) throw new TurnError('network', 'The connection to Lucy dropped');\n await whenInFront(signal, stoppedError);\n handlers.onStatus('Reconnecting');\n } else if (isLockedOut(err)) {\n shutInFront += 1;\n if (shutInFront > SHUT_IN_FRONT_TRIES) throw err;\n await wait(1000, signal);\n } else if (err instanceof TurnError && err.kind === 'busy') {\n // Refused, not taken: the same turn id goes once there is room.\n refusals += 1;\n if (!busySince) busySince = Date.now();\n const room = await waitForRoom(\n err.sessionId || sessionId,\n refusals,\n busySince + BUSY_GIVE_UP_MS,\n handlers,\n signal,\n );\n if (!room) throw err;\n } else {\n const e = err as TurnError & { partial?: string };\n if (!(e instanceof TurnError) || !e.retry || attempt >= BACKOFF_MS.length || e.kind === 'stopped')\n throw e;\n handlers.onStatus('Reconnecting');\n await wait(BACKOFF_MS[attempt], signal);\n attempt += 1;\n if (e.retry === 'continue') {\n prefix = e.partial ?? prefix;\n text = CONTINUE_PROMPT;\n turnId = newId('turn');\n }\n }\n } finally {\n line.end();\n }\n }\n}\n"],"names":["streamFetch"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBO,MAAM,kBAAkB,KAAM,CAAA;AAAA,EAKnC,WAAY,CAAA,IAAA,EAAqB,OAAiB,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A;AACX,QAAI,IAAA,CAAA,CAAE,UAAU,UAAY,EAAA;AAC1B,UAAS,MAAA,GAAA,CAAA,EAAA,GAAA,CAAA,CAAE,YAAF,IAAa,GAAA,EAAA,GAAA,MAAA;AACtB,UAAO,IAAA,GAAA,eAAA;AACP,UAAA,MAAA,GAAS,MAAM,MAAM,CAAA;AAAA;AACvB;AACF,KACA,SAAA;AACA,MAAA,IAAA,CAAK,GAAI,EAAA;AAAA;AACX;AAEJ"}
@@ -0,0 +1,196 @@
1
+ import {takeSurfaceMarkers,surfaceLink}from'@adminide-stack/clock-tik-browser/lib/pages/Home/chat/surfaces.js';var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ function surfaceHandovers(text) {
21
+ const seen = /* @__PURE__ */ new Set();
22
+ return takeSurfaceMarkers(text).markers.flatMap((marker) => {
23
+ const link = surfaceLink(marker.id);
24
+ if (!link || seen.has(link.id))
25
+ return [];
26
+ seen.add(link.id);
27
+ return [__spreadProps(__spreadValues({}, link), {
28
+ label: marker.label
29
+ })];
30
+ });
31
+ }
32
+ function surfaceButton(surface) {
33
+ return `Open ${surface.title}`;
34
+ }
35
+ const SITE_LOGIN = "site-login";
36
+ const OPEN_TAG = /\[CONNECTOR_CONNECT\]\s*(?=\{)/g;
37
+ const CLOSE_TAG = /^\s*\[\/CONNECTOR_CONNECT\]/;
38
+ const SAFE_ID = /^[A-Za-z0-9_-]+$/;
39
+ function balancedObject(text, start) {
40
+ let depth = 0;
41
+ let inString = false;
42
+ for (let i = start; i < text.length; i += 1) {
43
+ const ch = text[i];
44
+ if (inString) {
45
+ if (ch === "\\")
46
+ i += 1;
47
+ else if (ch === '"')
48
+ inString = false;
49
+ } else if (ch === '"')
50
+ inString = true;
51
+ else if (ch === "{")
52
+ depth += 1;
53
+ else if (ch === "}") {
54
+ depth -= 1;
55
+ if (depth === 0)
56
+ return text.slice(start, i + 1);
57
+ }
58
+ }
59
+ return null;
60
+ }
61
+ function cardBody(text, start) {
62
+ const json = balancedObject(text, start);
63
+ if (json)
64
+ return json;
65
+ const escaped = /^\{\s*\\"[\s\S]*?\}(?=\s*(?:\[\/CONNECTOR_CONNECT\]|$))/.exec(text.slice(start));
66
+ return escaped ? escaped[0] : null;
67
+ }
68
+ const clean = (v) => typeof v === "string" && v.trim() ? v.trim() : void 0;
69
+ function readBody(json) {
70
+ var _a;
71
+ const parse = (s) => {
72
+ try {
73
+ const body = JSON.parse(s);
74
+ return body && typeof body === "object" && !Array.isArray(body) ? body : null;
75
+ } catch (e) {
76
+ return null;
77
+ }
78
+ };
79
+ return (_a = parse(json)) != null ? _a : /^\{\s*\\"/.test(json) ? parse(json.replace(/\\(["\\])/g, "$1")) : null;
80
+ }
81
+ function toHandover(body, index) {
82
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
83
+ const connector = (_b = (_a = clean(body.connector)) != null ? _a : clean(body.provider)) != null ? _b : clean(body.type);
84
+ if (!connector)
85
+ return null;
86
+ const card = {
87
+ requestId: (_d = (_c = clean(body.requestId)) != null ? _c : clean(body.id)) != null ? _d : `connect-${index}`,
88
+ connector
89
+ };
90
+ const title = (_f = (_e = clean(body.title)) != null ? _e : clean(body.label)) != null ? _f : clean(body.name);
91
+ const reason = clean(body.reason);
92
+ const credentialId = (_g = clean(body.credentialId)) != null ? _g : clean(body.credential_id);
93
+ if (title)
94
+ card.title = title;
95
+ if (reason)
96
+ card.reason = reason;
97
+ if (credentialId && SAFE_ID.test(credentialId))
98
+ card.credentialId = credentialId;
99
+ const form = body.form && typeof body.form === "object" ? body.form : body;
100
+ const site = clean(form.site);
101
+ const loginUrl = (_i = (_h = clean(form.loginUrl)) != null ? _h : clean(form.login_url)) != null ? _i : clean(form.url);
102
+ if (site)
103
+ card.site = site;
104
+ if (loginUrl && /^https?:\/\//i.test(loginUrl))
105
+ card.loginUrl = loginUrl;
106
+ return card;
107
+ }
108
+ function connectHandovers(text) {
109
+ var _a;
110
+ const cards = [];
111
+ for (const m of text.matchAll(OPEN_TAG)) {
112
+ const start = ((_a = m.index) != null ? _a : 0) + m[0].length;
113
+ const json = cardBody(text, start);
114
+ const body = json ? readBody(json) : null;
115
+ const card = body ? toHandover(body, cards.length) : null;
116
+ if (card && !cards.some((c) => c.requestId === card.requestId))
117
+ cards.push(card);
118
+ }
119
+ return cards;
120
+ }
121
+ function stripConnectCards(text) {
122
+ var _a;
123
+ let out = "";
124
+ let at = 0;
125
+ for (const m of text.matchAll(OPEN_TAG)) {
126
+ const index = (_a = m.index) != null ? _a : 0;
127
+ if (index >= at) {
128
+ out += text.slice(at, index);
129
+ const start = index + m[0].length;
130
+ const json = cardBody(text, start);
131
+ if (!json)
132
+ return out;
133
+ const close = CLOSE_TAG.exec(text.slice(start + json.length));
134
+ at = start + json.length + (close ? close[0].length : 0);
135
+ }
136
+ }
137
+ out += text.slice(at);
138
+ return out.replace(/\[CONNECTOR_CONNECT\][\s\S]*?(?:\[\/CONNECTOR_CONNECT\]|$)/g, "").replace(/\[\/CONNECTOR_CONNECT\]/g, "");
139
+ }
140
+ const isSiteLogin = (card) => card.connector.toLowerCase() === SITE_LOGIN;
141
+ function autofillNoun(connector) {
142
+ const raw = connector.trim().toLowerCase();
143
+ if (!/^autofill[-_ ]/.test(raw))
144
+ return void 0;
145
+ return raw.replace(/^autofill[-_ ]+/, "").replace(/[-_]+/g, " ").trim() || void 0;
146
+ }
147
+ function connectName(card) {
148
+ if (card.title)
149
+ return card.title;
150
+ if (isSiteLogin(card))
151
+ return card.site ? `${card.site} login` : "website login";
152
+ const noun = autofillNoun(card.connector);
153
+ if (noun)
154
+ return noun;
155
+ const words = card.connector.replace(/-app-[a-z0-9]+$/i, "").replace(/[_-]+/g, " ").trim();
156
+ return words ? words.replace(/\b\w/g, (c) => c.toUpperCase()) : card.connector;
157
+ }
158
+ function connectHeading(card) {
159
+ const noun = autofillNoun(card.connector);
160
+ if (noun && !card.title)
161
+ return `${card.credentialId ? "Update" : "Add"} your ${noun}`;
162
+ if (isSiteLogin(card))
163
+ return `${card.credentialId ? "Update" : "Save"} your ${connectName(card)}`;
164
+ return `Connect ${connectName(card)}`;
165
+ }
166
+ function connectButton(card) {
167
+ if (card.credentialId)
168
+ return "Update";
169
+ if (isSiteLogin(card))
170
+ return "Save";
171
+ return autofillNoun(card.connector) ? "Add" : "Connect";
172
+ }
173
+ function connectUrl(appUrl, card) {
174
+ const base = appUrl.trim().replace(/\/+$/, "");
175
+ if (!base)
176
+ return "";
177
+ const params = [];
178
+ const add = (key, value) => params.push(`${key}=${encodeURIComponent(value)}`);
179
+ if (SAFE_ID.test(card.requestId))
180
+ add("request", card.requestId);
181
+ add("via", "surface");
182
+ if (card.title)
183
+ add("title", card.title);
184
+ if (card.credentialId)
185
+ add("credential", card.credentialId);
186
+ if (isSiteLogin(card)) {
187
+ if (card.site)
188
+ add("site", card.site);
189
+ if (card.loginUrl)
190
+ add("loginUrl", card.loginUrl);
191
+ }
192
+ return `${base}/connect/${encodeURIComponent(card.connector)}?${params.join("&")}`;
193
+ }
194
+ function doneWords(kind, name) {
195
+ return kind === "connect" ? `I saved my ${name}.` : "Done";
196
+ }export{SITE_LOGIN,connectButton,connectHandovers,connectHeading,connectName,connectUrl,doneWords,stripConnectCards,surfaceButton,surfaceHandovers};//# sourceMappingURL=handover.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handover.js","sources":["../../src/chat/handover.ts"],"sourcesContent":["/**\n * What Lucy hands over beside her words: a place to do a step herself can't (her Computer, to sign in to a site or pass\n * a robot check; another of Yantra's surfaces), as a `[[surface:<id>|<what to do there>]]` marker, and something to\n * connect or keep in the vault (a website login, a card, an app), as a `[CONNECTOR_CONNECT]{…}[/CONNECTOR_CONNECT]`\n * card. The web chat draws both (browser surfaces.ts with CallsCard's SurfaceLinks, and the kit's ConnectorConnectCard).\n * This chat used to take them out of the bubble and draw nothing, so \"save it below\" and \"sign in on your Computer\"\n * pointed at nothing a phone could tap. components/HandoverCards.tsx draws them; these are the pure parts.\n *\n * The connect marker rules are a copy of the kit's (`@yantra/surface-kit` chat/connectorConnectProtocol.ts, itself a\n * copy of yantra-app common's CONNECTOR_CONNECT_PROTOCOL): the documented shape, and the same shape whose closing tag\n * the model left off. Keep the link in step with the kit's connectorConnectUrl, which Yantra's /connect page reads.\n */\nimport { surfaceLink, takeSurfaceMarkers } from '@adminide-stack/clock-tik-browser/lib/pages/Home/chat/surfaces.js';\n\n/* ----------------------------------------------------------------------------- surfaces */\n\nexport interface SurfaceHandover {\n /** The surface's own id, an alias resolved: `computer`. */\n id: string;\n /** \"your Computer\". */\n title: string;\n /** Its host's first label: `computer-surface`. */\n host: string;\n /** What Lucy said to do there (\"Sign in to Flipkart\"); may be empty. */\n label: string;\n}\n\n/** The surfaces a reply hands over, each once, in order; one this chat cannot open is left out. */\nexport function surfaceHandovers(text: string): SurfaceHandover[] {\n const seen = new Set<string>();\n return takeSurfaceMarkers(text).markers.flatMap((marker) => {\n const link = surfaceLink(marker.id);\n if (!link || seen.has(link.id)) return [];\n seen.add(link.id);\n return [{ ...link, label: marker.label }];\n });\n}\n\n/** The card's button: \"Open your Computer\", \"Open Phone Calls\". */\nexport function surfaceButton(surface: Pick<SurfaceHandover, 'title'>): string {\n return `Open ${surface.title}`;\n}\n\n/* ----------------------------------------------------------------------------- connect cards */\n\nexport const SITE_LOGIN = 'site-login';\n\nexport interface ConnectHandover {\n requestId: string;\n /** A catalog connector's template key, `site-login`, or an autofill kind (`autofill-payment-card`). */\n connector: string;\n /** The card's name for it (\"Flipkart login\"). */\n title?: string;\n /** Why Lucy asks, one sentence. */\n reason?: string;\n /** For a website login: the site and the sign-in page her Computer is on. */\n site?: string;\n loginUrl?: string;\n /** The saved entry the card updates, when Lucy names one. */\n credentialId?: string;\n}\n\nconst OPEN_TAG = /\\[CONNECTOR_CONNECT\\]\\s*(?=\\{)/g;\nconst CLOSE_TAG = /^\\s*\\[\\/CONNECTOR_CONNECT\\]/;\nconst SAFE_ID = /^[A-Za-z0-9_-]+$/;\n\n/** The JSON object that opens at `text[start]`, through its matching `}`; null while it is still coming in. */\nfunction balancedObject(text: string, start: number): string | null {\n let depth = 0;\n let inString = false;\n for (let i = start; i < text.length; i += 1) {\n const ch = text[i];\n if (inString) {\n if (ch === '\\\\') i += 1;\n else if (ch === '\"') inString = false;\n } else if (ch === '\"') inString = true;\n else if (ch === '{') depth += 1;\n else if (ch === '}') {\n depth -= 1;\n if (depth === 0) return text.slice(start, i + 1);\n }\n }\n return null;\n}\n\n/**\n * A card's body opening at `text[start]`: the object through its matching `}`, or, for a body copied out of a tool result\n * with its quotes still escaped (`{\\\"connector\\\":…}`, whose braces never balance), through the `}` before the closing\n * tag or the end. null while it is still coming in.\n */\nfunction cardBody(text: string, start: number): string | null {\n const json = balancedObject(text, start);\n if (json) return json;\n const escaped = /^\\{\\s*\\\\\"[\\s\\S]*?\\}(?=\\s*(?:\\[\\/CONNECTOR_CONNECT\\]|$))/.exec(text.slice(start));\n return escaped ? escaped[0] : null;\n}\n\nconst clean = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v.trim() : undefined);\n\nfunction readBody(json: string): Record<string, unknown> | null {\n const parse = (s: string) => {\n try {\n const body = JSON.parse(s) as unknown;\n return body && typeof body === 'object' && !Array.isArray(body) ? (body as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n };\n // A body copied out of a tool result with one level of escaping left on (`{\\\"connector\\\":…}`).\n return parse(json) ?? (/^\\{\\s*\\\\\"/.test(json) ? parse(json.replace(/\\\\([\"\\\\])/g, '$1')) : null);\n}\n\nfunction toHandover(body: Record<string, unknown>, index: number): ConnectHandover | null {\n // `provider` and `type` are what the model writes in place of `connector`.\n const connector = clean(body.connector) ?? clean(body.provider) ?? clean(body.type);\n if (!connector) return null;\n const card: ConnectHandover = {\n requestId: clean(body.requestId) ?? clean(body.id) ?? `connect-${index}`,\n connector,\n };\n const title = clean(body.title) ?? clean(body.label) ?? clean(body.name);\n const reason = clean(body.reason);\n const credentialId = clean(body.credentialId) ?? clean(body.credential_id);\n if (title) card.title = title;\n if (reason) card.reason = reason;\n if (credentialId && SAFE_ID.test(credentialId)) card.credentialId = credentialId;\n // Only the fields the form reads, only as strings: the marker is model output. Nested under `form`, or flat.\n const form = (body.form && typeof body.form === 'object' ? body.form : body) as Record<string, unknown>;\n const site = clean(form.site);\n const loginUrl = clean(form.loginUrl) ?? clean(form.login_url) ?? clean(form.url);\n if (site) card.site = site;\n if (loginUrl && /^https?:\\/\\//i.test(loginUrl)) card.loginUrl = loginUrl;\n return card;\n}\n\n/** Every finished connect card in a reply, in order; one still streaming in is left for the next read. */\nexport function connectHandovers(text: string): ConnectHandover[] {\n const cards: ConnectHandover[] = [];\n for (const m of text.matchAll(OPEN_TAG)) {\n const start = (m.index ?? 0) + m[0].length;\n const json = cardBody(text, start);\n const body = json ? readBody(json) : null;\n const card = body ? toHandover(body, cards.length) : null;\n if (card && !cards.some((c) => c.requestId === card.requestId)) cards.push(card);\n }\n return cards;\n}\n\n/** Every connect card's text, gone from the words: finished, missing its closing tag, or still coming in. */\nexport function stripConnectCards(text: string): string {\n let out = '';\n let at = 0;\n // A tag inside a card already cut (index < at) went with that card.\n for (const m of text.matchAll(OPEN_TAG)) {\n const index = m.index ?? 0;\n if (index >= at) {\n out += text.slice(at, index);\n const start = index + m[0].length;\n const json = cardBody(text, start);\n if (!json) return out; // still streaming in: nothing after it is the bubble's yet\n const close = CLOSE_TAG.exec(text.slice(start + json.length));\n at = start + json.length + (close ? close[0].length : 0);\n }\n }\n out += text.slice(at);\n // An opening tag the cards above did not take (no body yet, or not JSON) runs to its closing tag or the end, as\n // the bubble always cut it; a closing tag left on its own goes alone.\n return out\n .replace(/\\[CONNECTOR_CONNECT\\][\\s\\S]*?(?:\\[\\/CONNECTOR_CONNECT\\]|$)/g, '')\n .replace(/\\[\\/CONNECTOR_CONNECT\\]/g, '');\n}\n\nconst isSiteLogin = (card: Pick<ConnectHandover, 'connector'>) => card.connector.toLowerCase() === SITE_LOGIN;\n\n/** An autofill entry the vault keeps (a card, an address, a passport), as words: \"payment card\". */\nfunction autofillNoun(connector: string): string | undefined {\n const raw = connector.trim().toLowerCase();\n if (!/^autofill[-_ ]/.test(raw)) return undefined;\n return (\n raw\n .replace(/^autofill[-_ ]+/, '')\n .replace(/[-_]+/g, ' ')\n .trim() || undefined\n );\n}\n\n/** What the card connects, as it names it: \"Flipkart login\", \"Google Calendar\". */\nexport function connectName(card: ConnectHandover): string {\n if (card.title) return card.title;\n if (isSiteLogin(card)) return card.site ? `${card.site} login` : 'website login';\n const noun = autofillNoun(card.connector);\n if (noun) return noun;\n const words = card.connector\n .replace(/-app-[a-z0-9]+$/i, '')\n .replace(/[_-]+/g, ' ')\n .trim();\n return words ? words.replace(/\\b\\w/g, (c) => c.toUpperCase()) : card.connector;\n}\n\n/** The card's heading (the kit's connectorConnectHeading): \"Save your Flipkart login\", \"Connect Google Calendar\". */\nexport function connectHeading(card: ConnectHandover): string {\n const noun = autofillNoun(card.connector);\n if (noun && !card.title) return `${card.credentialId ? 'Update' : 'Add'} your ${noun}`;\n if (isSiteLogin(card)) return `${card.credentialId ? 'Update' : 'Save'} your ${connectName(card)}`;\n return `Connect ${connectName(card)}`;\n}\n\n/** The button's word. */\nexport function connectButton(card: ConnectHandover): string {\n if (card.credentialId) return 'Update';\n if (isSiteLogin(card)) return 'Save';\n return autofillNoun(card.connector) ? 'Add' : 'Connect';\n}\n\n/**\n * Yantra's page for the card (the kit's connectorConnectUrl): `/connect/<connector>` with the site, the sign-in page\n * and the entry it updates, `via=surface` because no gateway answers this chat. '' without an app.\n */\nexport function connectUrl(appUrl: string, card: ConnectHandover): string {\n const base = appUrl.trim().replace(/\\/+$/, '');\n if (!base) return '';\n const params: string[] = [];\n const add = (key: string, value: string) => params.push(`${key}=${encodeURIComponent(value)}`);\n if (SAFE_ID.test(card.requestId)) add('request', card.requestId);\n add('via', 'surface');\n if (card.title) add('title', card.title);\n if (card.credentialId) add('credential', card.credentialId);\n if (isSiteLogin(card)) {\n if (card.site) add('site', card.site);\n if (card.loginUrl) add('loginUrl', card.loginUrl);\n }\n return `${base}/connect/${encodeURIComponent(card.connector)}?${params.join('&')}`;\n}\n\n/**\n * What the person says back from a card once they have been there, so Lucy carries on without them typing it: \"Done\"\n * is the word her Computer hand-over waits for (yantra-computer \"When they say done\"); a saved login she looks up.\n */\nexport function doneWords(kind: 'surface' | 'connect', name: string): string {\n return kind === 'connect' ? `I saved my ${name}.` : 'Done';\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AA4BO,SAAS,iBAAiB,IAAiC,EAAA;AAChE,EAAM,MAAA,IAAA,uBAAW,GAAY,EAAA;AAC7B,EAAA,OAAO,kBAAmB,CAAA,IAAI,CAAE,CAAA,OAAA,CAAQ,QAAQ,CAAU,MAAA,KAAA;AACxD,IAAM,MAAA,IAAA,GAAO,WAAY,CAAA,MAAA,CAAO,EAAE,CAAA;AAClC,IAAA,IAAI,CAAC,IAAA,IAAQ,IAAK,CAAA,GAAA,CAAI,KAAK,EAAE,CAAA;AAAG,MAAA,OAAO,EAAC;AACxC,IAAK,IAAA,CAAA,GAAA,CAAI,KAAK,EAAE,CAAA;AAChB,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AA,QAAA;AAAU,MAAI,GAAA,CAAA,UAAA,EAAY,KAAK,QAAQ,CAAA;AAAA;AAElD,EAAO,OAAA,CAAA,EAAG,gBAAgB,kBAAmB,CAAA,IAAA,CAAK,SAAS,CAAK,CAAA,CAAA,EAAA,MAAA,CAAO,KAAK,GAAG,CAAA,CAAA,CAAA;AACjF;AAMgB,SAAA,SAAA,CAAU,MAA6B,IAAsB,EAAA;AAC3E,EAAO,OAAA,IAAA,KAAS,SAAY,GAAA,CAAA,WAAA,EAAc,IAAU,CAAA,CAAA,CAAA,GAAA,MAAA;AACtD"}
@@ -1,4 +1,4 @@
1
- import {LUCY_SYSTEM_PROMPT}from'@adminide-stack/clock-tik-browser/lib/pages/Home/chat/lucy.js';import {RESULT_CARDS_PROMPT,takeResultWidgets}from'@adminide-stack/clock-tik-browser/lib/pages/Home/chat/results.js';const MAX_QUESTIONS = 6;
1
+ import {LUCY_SYSTEM_PROMPT}from'@adminide-stack/clock-tik-browser/lib/pages/Home/chat/lucy.js';import {RESULT_CARDS_PROMPT,takeResultWidgets}from'@adminide-stack/clock-tik-browser/lib/pages/Home/chat/results.js';import {surfaceLink}from'@adminide-stack/clock-tik-browser/lib/pages/Home/chat/surfaces.js';import {stripConnectCards}from'./handover.js';const MAX_QUESTIONS = 6;
2
2
  const ASK_USER_PROMPT = ["CLARIFYING QUESTIONS: When you need information from the user before you can act (missing details, a choice between approaches), do NOT ask in prose. Instead reply with ONLY this marker (no other text before or after):", '[ASK_USER]{"requestId":"<short-unique-id>","questions":[{"id":"<id>","title":"<the question>","options":[{"id":"<id>","label":"<choice>"}],"allowText":true,"textPlaceholder":"<hint for free-text>"}]}[/ASK_USER]', `Rules: 1-${MAX_QUESTIONS} questions max, shown one at a time (the user can skip any, or type their own answer); options are optional (omit for pure free-text questions); keep titles short \u2014 they are echoed back as "**title:** answer", and a skipped question is left out. The UI renders this as an interactive card, so the raw marker is never shown to the user. Only use it when genuinely blocked on user input; if you can proceed with sensible assumptions, proceed.`, `Optional fields: a question's "header" (a 1-2 word topic above it); "multiSelect":true when several options can apply (the answer is their labels, comma-separated). An option's "detail" (one line under the label).`].join("\n");
3
3
  const SYSTEM_PROMPT = `${LUCY_SYSTEM_PROMPT}
4
4
 
@@ -83,8 +83,22 @@ function formatAskAnswers(ask, answers) {
83
83
  return `**${q.title.replace(/[::]\s*$/, "")}:** ${value}`;
84
84
  }).filter(Boolean).join("\n\n");
85
85
  }
86
+ const SURFACE_MARKER = /[ \t]*\[\[\s*surface\s*:\s*([A-Za-z0-9_-]{1,40})\s*(?:\|\s*([^\]\n]{0,200}?))?\s*\]\]/gi;
87
+ function withoutUnfinishedSurface(text) {
88
+ const at = text.lastIndexOf("[[");
89
+ if (at < 0)
90
+ return text;
91
+ const tail = text.slice(at + 2);
92
+ if (tail.includes("\n") || tail.includes("]]"))
93
+ return text;
94
+ const head = tail.trimStart().toLowerCase();
95
+ return head.startsWith("surface") || "surface".startsWith(head) ? text.slice(0, at) : text;
96
+ }
86
97
  function displayText(text) {
87
- return takeResultWidgets(text).content.replace(ASK_RE_ALL, "").replace(/\[CONNECTOR_CONNECT\][\s\S]*?(?:\[\/CONNECTOR_CONNECT\]|$)/g, "").replace(/```yantra:widget[\s\S]*?(?:```|$)/g, "").replace(/\[\[surface:[^|\]]+\|([^\]]+)\]\]/g, "$1").replace(/\[\[surface:([^\]]+)\]\]/g, "$1").replace(/\n{3,}/g, "\n\n").trim();
98
+ return withoutUnfinishedSurface(stripConnectCards(takeResultWidgets(text).content.replace(ASK_RE_ALL, ""))).replace(/```yantra:widget[\s\S]*?(?:```|$)/g, "").replace(SURFACE_MARKER, (marker, id, label) => {
99
+ var _a, _b;
100
+ return surfaceLink(id) ? "" : `${(_b = (_a = /^[ \t]*/.exec(marker)) == null ? void 0 : _a[0]) != null ? _b : ""}${(label != null ? label : id).trim()}`;
101
+ }).replace(/^[ \t]+$/gm, "").replace(/\n{3,}/g, "\n\n").trim();
88
102
  }
89
103
  function chatTitle(firstMessage) {
90
104
  const t = firstMessage.replace(/\*\*/g, "").replace(/\s+/g, " ").trim();
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.js","sources":["../../src/chat/protocol.ts"],"sourcesContent":["/**\n * What Lucy's agent says, made readable: the same rules the web chat applies (@yantra/surface-kit agentChat.ts\n * visibleAgentOutput, chat/askUser.ts), without the DOM. Pure functions; tested in __tests__/protocol.test.ts.\n */\n// Lucy's own prompt and how she hands over results as cards, read-only from the browser package's build.\nimport { LUCY_SYSTEM_PROMPT } from '@adminide-stack/clock-tik-browser/lib/pages/Home/chat/lucy.js';\nimport {\n RESULT_CARDS_PROMPT,\n takeResultWidgets,\n} from '@adminide-stack/clock-tik-browser/lib/pages/Home/chat/results.js';\n\nexport const MAX_QUESTIONS = 6;\n\n/**\n * How to ask instead of asking in prose (the web's ASK_USER_SYSTEM_PROMPT), minus what this app does not draw yet:\n * attachments and audio previews.\n */\nexport const ASK_USER_PROMPT = [\n 'CLARIFYING QUESTIONS: When you need information from the user before you can act (missing details, a choice between approaches), do NOT ask in prose. Instead reply with ONLY this marker (no other text before or after):',\n '[ASK_USER]{\"requestId\":\"<short-unique-id>\",\"questions\":[{\"id\":\"<id>\",\"title\":\"<the question>\",\"options\":[{\"id\":\"<id>\",\"label\":\"<choice>\"}],\"allowText\":true,\"textPlaceholder\":\"<hint for free-text>\"}]}[/ASK_USER]',\n `Rules: 1-${MAX_QUESTIONS} questions max, shown one at a time (the user can skip any, or type their own answer); options are optional (omit for pure free-text questions); keep titles short — they are echoed back as \"**title:** answer\", and a skipped question is left out. The UI renders this as an interactive card, so the raw marker is never shown to the user. Only use it when genuinely blocked on user input; if you can proceed with sensible assumptions, proceed.`,\n 'Optional fields: a question\\'s \"header\" (a 1-2 word topic above it); \"multiSelect\":true when several options can apply (the answer is their labels, comma-separated). An option\\'s \"detail\" (one line under the label).',\n].join('\\n');\n\n/** The session's system prompt: Lucy, then how to ask. Set once, when the session opens. */\nexport const SYSTEM_PROMPT = `${LUCY_SYSTEM_PROMPT}\\n\\n${ASK_USER_PROMPT}`;\n\n/** Sent with a new turn id when a step was cut off part-way (agentChat.ts AGENT_CONTINUE_PROMPT). */\nexport const CONTINUE_PROMPT =\n '[Note from the app, not from the user: your last step was cut off by a temporary problem on our side, ' +\n 'after some of its actions had already run. Everything you already did is in the conversation above. ' +\n \"Carry on with the user's request from where you stopped, and do not repeat an action that already went through.]\";\n\n/**\n * A turn as the agent gets it: the person's words, then how to hand over flights and products so the chat draws them\n * as cards (components/ResultCards.tsx), for the agent alone, in the Yantra app's `<agent-context>` envelope (the web's\n * lucyTurn). It rides every turn because a session keeps the system prompt it opened with. The thread, the chore\n * record and History keep the words as typed.\n */\nexport function agentTurn(words: string): string {\n return `${words}\\n\\n<agent-context>${RESULT_CARDS_PROMPT.trim()}</agent-context>`;\n}\n\n// eslint-disable-next-line no-control-regex\nconst ANSI = /\\u001b\\[[0-9;]*m/g;\nconst TERMINAL_QUESTION =\n /^\\s*[╭╮╰╯│─┌┐└┘├┤]|^\\s*(?:Answer 1-\\d+(?: \\(comma-separated\\))? or type your own|Type your answer); Enter to skip:?\\s*$|^ {2}(?:✓ |⨯ Skipped)/u;\nconst TERMINAL_ACCOUNTING =\n /^\\s*(?:⚡ Tokens: |💡 (?:Context growing fast|\\d+ tool-use iterations detected|Session cost \\$)|⚠ billing policy check unavailable \\(.*allowing metered action\\s*$|⚠ billing policy: .*\\(CDECLI_BILLING_POLICY=warn: not blocking\\)\\s*$)/u;\n\n/** A whole `output` event, minus the terminal's own furniture. */\nexport function visibleOutput(text: string): string {\n return text\n .replace(ANSI, '')\n .replace(/\\[CDECLI_ASK_USER_QUESTION\\][\\s\\S]*?(?:\\[\\/CDECLI_ASK_USER_QUESTION\\]|$)/g, '')\n .split('\\n')\n .filter((line) => !/^\\s*🧠/u.test(line) && !TERMINAL_ACCOUNTING.test(line) && !TERMINAL_QUESTION.test(line))\n .join('\\n')\n .trimStart();\n}\n\n/** What goes between the reply so far and a following output, so the output starts its own paragraph. */\nexport function joinOutput(reply: string, output: string): string {\n if (!output) return reply;\n if (!reply) return output;\n if (reply.endsWith('\\n\\n')) return reply + output;\n return reply + (reply.endsWith('\\n') ? '\\n' : '\\n\\n') + output;\n}\n\n/* ----------------------------------------------------------------------------- question cards */\n\nexport interface AskOption {\n id: string;\n label: string;\n detail?: string;\n}\nexport interface AskQuestion {\n id: string;\n header?: string;\n title: string;\n options: AskOption[];\n allowText: boolean;\n textPlaceholder?: string;\n multiSelect: boolean;\n}\nexport interface AskUser {\n requestId: string;\n questions: AskQuestion[];\n}\n\nconst ASK_RE = /\\[ASK_USER\\]([\\s\\S]*?)\\[\\/ASK_USER\\]/;\nconst ASK_RE_ALL = /\\[ASK_USER\\][\\s\\S]*?(?:\\[\\/ASK_USER\\]|$)/g;\n\n/** The question card in a reply, if it has a whole one. */\nexport function parseAskUser(text: string): AskUser | null {\n const m = ASK_RE.exec(text);\n if (!m) return null;\n let raw: { requestId?: string; questions?: unknown[] };\n try {\n raw = JSON.parse(m[1].trim());\n } catch {\n return null;\n }\n const questions = (Array.isArray(raw?.questions) ? raw.questions : [])\n .slice(0, MAX_QUESTIONS)\n .map((q, i): AskQuestion | null => {\n const o = q as Record<string, unknown>;\n const title = String(o.title ?? o.question ?? '').trim();\n if (!title) return null;\n const options = (Array.isArray(o.options) ? o.options : []).map((op, j): AskOption => {\n if (typeof op === 'string') return { id: `o${j}`, label: op };\n const p = op as Record<string, unknown>;\n return {\n id: String(p.id ?? `o${j}`),\n label: String(p.label ?? ''),\n detail: (p.detail ?? p.description) ? String(p.detail ?? p.description) : undefined,\n };\n });\n return {\n id: String(o.id ?? `q${i}`),\n header: o.header ? String(o.header) : undefined,\n title,\n options: options.filter((op) => op.label),\n allowText: o.allowText !== false,\n textPlaceholder: o.textPlaceholder ? String(o.textPlaceholder) : undefined,\n multiSelect: o.multiSelect === true,\n };\n })\n .filter((q): q is AskQuestion => q !== null);\n if (!questions.length) return null;\n return { requestId: String(raw.requestId ?? 'ask'), questions };\n}\n\n/** One answer: picked option labels, or typed text (typed text wins). Empty = skipped. */\nexport interface AskAnswer {\n picked: string[];\n text: string;\n}\n\n/** The answer message, as the web sends it: \"**Title:** answer\" paragraphs, skipped questions left out. */\nexport function formatAskAnswers(ask: AskUser, answers: Record<string, AskAnswer>): string {\n return ask.questions\n .map((q) => {\n const a = answers[q.id];\n const value = a?.text.trim() || (a?.picked.length ? a.picked.join(', ') : '');\n if (!value) return '';\n return `**${q.title.replace(/[::]\\s*$/, '')}:** ${value}`;\n })\n .filter(Boolean)\n .join('\\n\\n');\n}\n\n/* ----------------------------------------------------------------------------- display */\n\n/**\n * A reply's text as the bubble shows it: no question block (it has its own card), no result blocks in any of the forms\n * a model writes them (fenced, under a bare marker, or still streaming in: they draw as cards), and the web-only\n * markers either dropped (Connect cards, other widgets) or reduced to a plain label (surface links).\n */\nexport function displayText(text: string): string {\n return takeResultWidgets(text)\n .content.replace(ASK_RE_ALL, '')\n .replace(/\\[CONNECTOR_CONNECT\\][\\s\\S]*?(?:\\[\\/CONNECTOR_CONNECT\\]|$)/g, '')\n .replace(/```yantra:widget[\\s\\S]*?(?:```|$)/g, '')\n .replace(/\\[\\[surface:[^|\\]]+\\|([^\\]]+)\\]\\]/g, '$1')\n .replace(/\\[\\[surface:([^\\]]+)\\]\\]/g, '$1')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\n/** A short title for a chat in History: its first message. */\nexport function chatTitle(firstMessage: string): string {\n const t = firstMessage.replace(/\\*\\*/g, '').replace(/\\s+/g, ' ').trim();\n return t.length > 60 ? `${t.slice(0, 57)}…` : t || 'New chat';\n}\n\n/** A progress line for a tool Lucy is using (the web's humanizeToolLine, in Clockbook's words). */\nexport function toolLine(name: string, detail?: string): string {\n const n = `${name} ${detail ?? ''}`.toLowerCase();\n if (/phone|call|dial|twilio|voice/.test(n)) return 'Making a call';\n if (/calendar|schedule|booking|meeting/.test(n)) return 'Checking the calendar';\n if (/mail|gmail|email/.test(n)) return 'Looking through email';\n if (/search|web|browse|fetch|http|site|page/.test(n)) return 'Looking it up';\n if (/message|sms|imessage|text/.test(n)) return 'Sending a message';\n if (/file|read|write|edit/.test(n)) return 'Working through the details';\n return 'Working on it';\n}\n\n/** A status event's line without its leading glyphs. */\nexport function statusLine(status: string): string {\n return status.replace(/^[^\\p{L}\\p{N}]+/u, '').trim();\n}\n"],"names":["_a","_b","_c"],"mappings":"oNAOO,MAAM,aAAgB,GAAA;AAMhB,MAAA,eAAA,GAAkB,CAAC,4NAA8N,EAAA,oNAAA,EAAsN,YAAY,aAAyc,CAAA,6bAAA,CAAA,EAAA,CAAA,qNAAA,CAAyN,CAAE,CAAA,IAAA,CAAK,IAAI;AAGtoC,MAAM,gBAAgB,CAAG,EAAA,kBAAA;;AAAA,EAAyB,eAAA,CAAA;AAGlD,MAAM,eAAkB,GAAA;AAQxB,SAAS,UAAU,KAAuB,EAAA;AAC/C,EAAA,OAAO,CAAG,EAAA,KAAA;;AAAA,eAAA,EAA2B,oBAAoB,IAAK,EAAA,CAAA,gBAAA,CAAA;AAChE;AAGA,MAAM,IAAO,GAAA,mBAAA;AACb,MAAM,iBAAoB,GAAA,gJAAA;AAC1B,MAAM,mBAAsB,GAAA,0OAAA;AAGrB,SAAS,cAAc,IAAsB,EAAA;AAClD,EAAA,OAAO,IAAK,CAAA,OAAA,CAAQ,IAAM,EAAA,EAAE,EAAE,OAAQ,CAAA,2EAAA,EAA6E,EAAE,CAAA,CAAE,KAAM,CAAA,IAAI,CAAE,CAAA,MAAA,CAAO,UAAQ,CAAC,SAAA,CAAU,IAAK,CAAA,IAAI,CAAK,IAAA,CAAC,mBAAoB,CAAA,IAAA,CAAK,IAAI,CAAK,IAAA,CAAC,iBAAkB,CAAA,IAAA,CAAK,IAAI,CAAC,CAAA,CAAE,IAAK,CAAA,IAAI,EAAE,SAAU,EAAA;AACpQ;AAGgB,SAAA,UAAA,CAAW,OAAe,MAAwB,EAAA;AAChE,EAAA,IAAI,CAAC,MAAA;AAAQ,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AAChD,EAAI,IAAA,sBAAA,CAAuB,KAAK,CAAC,CAAA;AAAG,IAAO,OAAA,6BAAA;AAC3C,EAAO,OAAA,eAAA;AACT;AAGO,SAAS,WAAW,MAAwB,EAAA;AACjD,EAAA,OAAO,MAAO,CAAA,OAAA,CAAQ,kBAAoB,EAAA,EAAE,EAAE,IAAK,EAAA;AACrD"}
1
+ {"version":3,"file":"protocol.js","sources":["../../src/chat/protocol.ts"],"sourcesContent":["/**\n * What Lucy's agent says, made readable: the same rules the web chat applies (@yantra/surface-kit agentChat.ts\n * visibleAgentOutput, chat/askUser.ts), without the DOM. Pure functions; tested in __tests__/protocol.test.ts.\n */\n// Lucy's own prompt and how she hands over results as cards, read-only from the browser package's build.\nimport { LUCY_SYSTEM_PROMPT } from '@adminide-stack/clock-tik-browser/lib/pages/Home/chat/lucy.js';\nimport {\n RESULT_CARDS_PROMPT,\n takeResultWidgets,\n} from '@adminide-stack/clock-tik-browser/lib/pages/Home/chat/results.js';\nimport { surfaceLink } from '@adminide-stack/clock-tik-browser/lib/pages/Home/chat/surfaces.js';\nimport { stripConnectCards } from './handover';\n\nexport const MAX_QUESTIONS = 6;\n\n/**\n * How to ask instead of asking in prose (the web's ASK_USER_SYSTEM_PROMPT), minus what this app does not draw yet:\n * attachments and audio previews.\n */\nexport const ASK_USER_PROMPT = [\n 'CLARIFYING QUESTIONS: When you need information from the user before you can act (missing details, a choice between approaches), do NOT ask in prose. Instead reply with ONLY this marker (no other text before or after):',\n '[ASK_USER]{\"requestId\":\"<short-unique-id>\",\"questions\":[{\"id\":\"<id>\",\"title\":\"<the question>\",\"options\":[{\"id\":\"<id>\",\"label\":\"<choice>\"}],\"allowText\":true,\"textPlaceholder\":\"<hint for free-text>\"}]}[/ASK_USER]',\n `Rules: 1-${MAX_QUESTIONS} questions max, shown one at a time (the user can skip any, or type their own answer); options are optional (omit for pure free-text questions); keep titles short — they are echoed back as \"**title:** answer\", and a skipped question is left out. The UI renders this as an interactive card, so the raw marker is never shown to the user. Only use it when genuinely blocked on user input; if you can proceed with sensible assumptions, proceed.`,\n 'Optional fields: a question\\'s \"header\" (a 1-2 word topic above it); \"multiSelect\":true when several options can apply (the answer is their labels, comma-separated). An option\\'s \"detail\" (one line under the label).',\n].join('\\n');\n\n/** The session's system prompt: Lucy, then how to ask. Set once, when the session opens. */\nexport const SYSTEM_PROMPT = `${LUCY_SYSTEM_PROMPT}\\n\\n${ASK_USER_PROMPT}`;\n\n/** Sent with a new turn id when a step was cut off part-way (agentChat.ts AGENT_CONTINUE_PROMPT). */\nexport const CONTINUE_PROMPT =\n '[Note from the app, not from the user: your last step was cut off by a temporary problem on our side, ' +\n 'after some of its actions had already run. Everything you already did is in the conversation above. ' +\n \"Carry on with the user's request from where you stopped, and do not repeat an action that already went through.]\";\n\n/**\n * A turn as the agent gets it: the person's words, then how to hand over flights and products so the chat draws them\n * as cards (components/ResultCards.tsx), for the agent alone, in the Yantra app's `<agent-context>` envelope (the web's\n * lucyTurn). It rides every turn because a session keeps the system prompt it opened with. The thread, the chore\n * record and History keep the words as typed.\n */\nexport function agentTurn(words: string): string {\n return `${words}\\n\\n<agent-context>${RESULT_CARDS_PROMPT.trim()}</agent-context>`;\n}\n\n// eslint-disable-next-line no-control-regex\nconst ANSI = /\\u001b\\[[0-9;]*m/g;\nconst TERMINAL_QUESTION =\n /^\\s*[╭╮╰╯│─┌┐└┘├┤]|^\\s*(?:Answer 1-\\d+(?: \\(comma-separated\\))? or type your own|Type your answer); Enter to skip:?\\s*$|^ {2}(?:✓ |⨯ Skipped)/u;\nconst TERMINAL_ACCOUNTING =\n /^\\s*(?:⚡ Tokens: |💡 (?:Context growing fast|\\d+ tool-use iterations detected|Session cost \\$)|⚠ billing policy check unavailable \\(.*allowing metered action\\s*$|⚠ billing policy: .*\\(CDECLI_BILLING_POLICY=warn: not blocking\\)\\s*$)/u;\n\n/** A whole `output` event, minus the terminal's own furniture. */\nexport function visibleOutput(text: string): string {\n return text\n .replace(ANSI, '')\n .replace(/\\[CDECLI_ASK_USER_QUESTION\\][\\s\\S]*?(?:\\[\\/CDECLI_ASK_USER_QUESTION\\]|$)/g, '')\n .split('\\n')\n .filter((line) => !/^\\s*🧠/u.test(line) && !TERMINAL_ACCOUNTING.test(line) && !TERMINAL_QUESTION.test(line))\n .join('\\n')\n .trimStart();\n}\n\n/** What goes between the reply so far and a following output, so the output starts its own paragraph. */\nexport function joinOutput(reply: string, output: string): string {\n if (!output) return reply;\n if (!reply) return output;\n if (reply.endsWith('\\n\\n')) return reply + output;\n return reply + (reply.endsWith('\\n') ? '\\n' : '\\n\\n') + output;\n}\n\n/* ----------------------------------------------------------------------------- question cards */\n\nexport interface AskOption {\n id: string;\n label: string;\n detail?: string;\n}\nexport interface AskQuestion {\n id: string;\n header?: string;\n title: string;\n options: AskOption[];\n allowText: boolean;\n textPlaceholder?: string;\n multiSelect: boolean;\n}\nexport interface AskUser {\n requestId: string;\n questions: AskQuestion[];\n}\n\nconst ASK_RE = /\\[ASK_USER\\]([\\s\\S]*?)\\[\\/ASK_USER\\]/;\nconst ASK_RE_ALL = /\\[ASK_USER\\][\\s\\S]*?(?:\\[\\/ASK_USER\\]|$)/g;\n\n/** The question card in a reply, if it has a whole one. */\nexport function parseAskUser(text: string): AskUser | null {\n const m = ASK_RE.exec(text);\n if (!m) return null;\n let raw: { requestId?: string; questions?: unknown[] };\n try {\n raw = JSON.parse(m[1].trim());\n } catch {\n return null;\n }\n const questions = (Array.isArray(raw?.questions) ? raw.questions : [])\n .slice(0, MAX_QUESTIONS)\n .map((q, i): AskQuestion | null => {\n const o = q as Record<string, unknown>;\n const title = String(o.title ?? o.question ?? '').trim();\n if (!title) return null;\n const options = (Array.isArray(o.options) ? o.options : []).map((op, j): AskOption => {\n if (typeof op === 'string') return { id: `o${j}`, label: op };\n const p = op as Record<string, unknown>;\n return {\n id: String(p.id ?? `o${j}`),\n label: String(p.label ?? ''),\n detail: (p.detail ?? p.description) ? String(p.detail ?? p.description) : undefined,\n };\n });\n return {\n id: String(o.id ?? `q${i}`),\n header: o.header ? String(o.header) : undefined,\n title,\n options: options.filter((op) => op.label),\n allowText: o.allowText !== false,\n textPlaceholder: o.textPlaceholder ? String(o.textPlaceholder) : undefined,\n multiSelect: o.multiSelect === true,\n };\n })\n .filter((q): q is AskQuestion => q !== null);\n if (!questions.length) return null;\n return { requestId: String(raw.requestId ?? 'ask'), questions };\n}\n\n/** One answer: picked option labels, or typed text (typed text wins). Empty = skipped. */\nexport interface AskAnswer {\n picked: string[];\n text: string;\n}\n\n/** The answer message, as the web sends it: \"**Title:** answer\" paragraphs, skipped questions left out. */\nexport function formatAskAnswers(ask: AskUser, answers: Record<string, AskAnswer>): string {\n return ask.questions\n .map((q) => {\n const a = answers[q.id];\n const value = a?.text.trim() || (a?.picked.length ? a.picked.join(', ') : '');\n if (!value) return '';\n return `**${q.title.replace(/[::]\\s*$/, '')}:** ${value}`;\n })\n .filter(Boolean)\n .join('\\n\\n');\n}\n\n/* ----------------------------------------------------------------------------- display */\n\n/** A surface marker as the gateway reads it (surfaces.ts MARKER): `[[surface:<id>]]` or `[[surface:<id>|<label>]]`. */\nconst SURFACE_MARKER = /[ \\t]*\\[\\[\\s*surface\\s*:\\s*([A-Za-z0-9_-]{1,40})\\s*(?:\\|\\s*([^\\]\\n]{0,200}?))?\\s*\\]\\]/gi;\n\n/** The text without a surface marker still streaming in at its end (`[[surface:comp`), as surfaces.ts cuts it. */\nfunction withoutUnfinishedSurface(text: string): string {\n const at = text.lastIndexOf('[[');\n if (at < 0) return text;\n const tail = text.slice(at + 2);\n if (tail.includes('\\n') || tail.includes(']]')) return text;\n const head = tail.trimStart().toLowerCase();\n return head.startsWith('surface') || 'surface'.startsWith(head) ? text.slice(0, at) : text;\n}\n\n/**\n * A reply's text as the bubble shows it: no question block (it has its own card), no result blocks in any of the forms\n * a model writes them (fenced, under a bare marker, or still streaming in: they draw as cards), no Connect cards and no\n * marker of a surface this chat opens (both drawn under the bubble, components/HandoverCards.tsx), other widgets\n * dropped, and a surface this chat cannot open reduced to its plain label.\n */\nexport function displayText(text: string): string {\n return withoutUnfinishedSurface(stripConnectCards(takeResultWidgets(text).content.replace(ASK_RE_ALL, '')))\n .replace(/```yantra:widget[\\s\\S]*?(?:```|$)/g, '')\n .replace(SURFACE_MARKER, (marker: string, id: string, label: string | undefined) =>\n surfaceLink(id) ? '' : `${/^[ \\t]*/.exec(marker)?.[0] ?? ''}${(label ?? id).trim()}`,\n )\n .replace(/^[ \\t]+$/gm, '')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\n/** A short title for a chat in History: its first message. */\nexport function chatTitle(firstMessage: string): string {\n const t = firstMessage.replace(/\\*\\*/g, '').replace(/\\s+/g, ' ').trim();\n return t.length > 60 ? `${t.slice(0, 57)}…` : t || 'New chat';\n}\n\n/** A progress line for a tool Lucy is using (the web's humanizeToolLine, in Clockbook's words). */\nexport function toolLine(name: string, detail?: string): string {\n const n = `${name} ${detail ?? ''}`.toLowerCase();\n if (/phone|call|dial|twilio|voice/.test(n)) return 'Making a call';\n if (/calendar|schedule|booking|meeting/.test(n)) return 'Checking the calendar';\n if (/mail|gmail|email/.test(n)) return 'Looking through email';\n if (/search|web|browse|fetch|http|site|page/.test(n)) return 'Looking it up';\n if (/message|sms|imessage|text/.test(n)) return 'Sending a message';\n if (/file|read|write|edit/.test(n)) return 'Working through the details';\n return 'Working on it';\n}\n\n/** A status event's line without its leading glyphs. */\nexport function statusLine(status: string): string {\n return status.replace(/^[^\\p{L}\\p{N}]+/u, '').trim();\n}\n"],"names":["_a","_b","_c"],"mappings":"8VASO,MAAM,aAAgB,GAAA;AAMhB,MAAA,eAAA,GAAkB,CAAC,4NAA8N,EAAA,oNAAA,EAAsN,YAAY,aAAyc,CAAA,6bAAA,CAAA,EAAA,CAAA,qNAAA,CAAyN,CAAE,CAAA,IAAA,CAAK,IAAI;AAGtoC,MAAM,gBAAgB,CAAG,EAAA,kBAAA;;AAAA,EAAyB,eAAA,CAAA;AAGlD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