toolroll 0.9.129 → 0.9.130

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.
Files changed (113) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/agent-fence.js +0 -2
  3. package/dist/agents-board.js +0 -3
  4. package/dist/assignment.js +4 -3
  5. package/dist/backup-ui.js +6 -3
  6. package/dist/bounded-spawn.js +0 -1
  7. package/dist/browser/manifest.json +57 -0
  8. package/dist/browser/terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.br +0 -0
  9. package/dist/browser/terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.gz +0 -0
  10. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.br +0 -0
  11. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.gz +0 -0
  12. package/dist/browser/{workspace.js → workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js} +25 -25
  13. package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.br +0 -0
  14. package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.gz +0 -0
  15. package/dist/browser/{workspace.css → workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css} +1 -1
  16. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.br +0 -0
  17. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.gz +0 -0
  18. package/dist/browser-shell.js +271 -25
  19. package/dist/canvas-freshness.js +122 -0
  20. package/dist/canvas-fs.js +273 -0
  21. package/dist/canvas-reads.js +747 -0
  22. package/dist/canvas-state-key.js +45 -0
  23. package/dist/canvas-state-worker.js +12 -0
  24. package/dist/central-recovery-stage.js +3 -3
  25. package/dist/chat-actions.js +26 -0
  26. package/dist/chat-channel.js +4 -3
  27. package/dist/chat-task-actions.js +1 -1
  28. package/dist/chat-warmth.js +0 -1
  29. package/dist/check-report.js +0 -6
  30. package/dist/commit-extract.js +79 -40
  31. package/dist/companion/access.js +1 -0
  32. package/dist/companion/actions.js +79 -16
  33. package/dist/companion/canvas.js +141 -0
  34. package/dist/companion/chat-origin.js +92 -0
  35. package/dist/companion/chat.js +571 -0
  36. package/dist/companion/daemon.js +46 -5
  37. package/dist/companion/finish.js +51 -0
  38. package/dist/companion/reads.js +5 -1
  39. package/dist/companion/schema.js +64 -0
  40. package/dist/companion/service.js +1 -0
  41. package/dist/companion/store.js +1 -0
  42. package/dist/companion/webauthn.js +11 -2
  43. package/dist/console-instance.js +0 -4
  44. package/dist/contracts/console-api.js +1 -1
  45. package/dist/converse.js +0 -1
  46. package/dist/coordinator.js +1 -1
  47. package/dist/desktop-config.js +156 -0
  48. package/dist/desktop-host.js +6 -152
  49. package/dist/desktop-update.js +1 -1
  50. package/dist/finished-task-sql.js +14 -0
  51. package/dist/flexible-answers.js +0 -1
  52. package/dist/github-read.js +41 -0
  53. package/dist/guides.js +4 -3
  54. package/dist/lead-doors.js +50 -3
  55. package/dist/lead-queue-runtime.js +11 -2
  56. package/dist/lead-queue.js +25 -0
  57. package/dist/live-backup-change.js +93 -0
  58. package/dist/live-backup.js +75 -31
  59. package/dist/live-bus.js +3 -2
  60. package/dist/live-records.js +0 -1
  61. package/dist/local-owner.js +0 -1
  62. package/dist/model-choices.js +0 -11
  63. package/dist/nightly-check.js +0 -3
  64. package/dist/nightly-github.js +1 -2
  65. package/dist/notification-retention.js +119 -0
  66. package/dist/observations.js +0 -1
  67. package/dist/operate.js +17 -4
  68. package/dist/pull-request-flow.js +56 -15
  69. package/dist/qr.js +0 -25
  70. package/dist/release-adapters.js +12 -42
  71. package/dist/release-auto.js +17 -13
  72. package/dist/release-card.js +0 -4
  73. package/dist/release-cli.js +37 -2
  74. package/dist/release.js +13 -2
  75. package/dist/restore-retirement.js +4 -1
  76. package/dist/result-review.js +0 -3
  77. package/dist/retention-ui.js +1 -1
  78. package/dist/retention.js +14 -21
  79. package/dist/review-context.js +0 -5
  80. package/dist/route-rules.js +1 -5
  81. package/dist/sandbox-runtime.js +0 -1
  82. package/dist/scope.js +1 -13
  83. package/dist/scout.js +0 -6
  84. package/dist/serve.js +31 -7
  85. package/dist/server/kit.js +1 -0
  86. package/dist/server/live.js +9 -2
  87. package/dist/server/pages.js +3 -2
  88. package/dist/server/phone-engine-api.js +22 -2
  89. package/dist/server/render-pages.js +1 -11
  90. package/dist/server/render-results.js +0 -1
  91. package/dist/server/render-tasks.js +0 -68
  92. package/dist/server/route-table.js +1 -1
  93. package/dist/server/settings-phone.js +32 -9
  94. package/dist/server/settings-scripts.js +1 -1
  95. package/dist/server/settings-section-table.js +0 -3
  96. package/dist/server/settings-sections.js +4 -2
  97. package/dist/server/settings.js +20 -5
  98. package/dist/server/terminals.js +2 -1
  99. package/dist/store.js +20 -5
  100. package/dist/structured-output.js +0 -1
  101. package/dist/style-asset.js +20 -7
  102. package/dist/tailnet.js +0 -3
  103. package/dist/task-control.js +5 -0
  104. package/dist/task-sizing.js +0 -1
  105. package/dist/toolroll-update-cli.js +19 -3
  106. package/dist/toolroll-update-ui.js +2 -2
  107. package/dist/toolroll-update.js +95 -15
  108. package/package.json +1 -1
  109. package/dist/companion/webauthn-test-support.js +0 -44
  110. package/dist/contracts/contract-test.js +0 -55
  111. package/dist/unfenced-test-support.js +0 -6
  112. /package/dist/browser/{terminal.js → terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js} +0 -0
  113. /package/dist/browser/{terminal.css → terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css} +0 -0
@@ -0,0 +1,571 @@
1
+ import { createHash } from "node:crypto";
2
+ import { resolveChannelLead } from "../chat-channel.js";
3
+ import { isDirectChatProvider } from "../converse.js";
4
+ import { leadChatOf } from "../engine-chat.js";
5
+ import { scanForSecrets } from "../evidence.js";
6
+ import { leadNameOf } from "../lead-identity.js";
7
+ import { LEAD_MESSAGE_MAX_CHARS } from "../lead.js";
8
+ import { verifyApproverStanding } from "../principal.js";
9
+ import { chatSnapshot } from "../server/live.js";
10
+ import { decisionsFor } from "../server/render-chat.js";
11
+ import { requestContext } from "../server/request-context.js";
12
+ import { LEAD_THREAD } from "../store.js";
13
+ import { chatKeysOf, chatReceiptOf } from "./chat-origin.js";
14
+ import { TokenBucket } from "./framing.js";
15
+ import { deviceAccountStands, getPairedDevice } from "./store.js";
16
+ export class CompanionChatError extends Error {
17
+ code;
18
+ constructor(code, message) {
19
+ super(message);
20
+ this.code = code;
21
+ }
22
+ }
23
+ export const CHAT_WATCH_RECORD_BYTES = 56_000;
24
+ export const CHAT_READ_BYTES = 512 * 1024;
25
+ export const CHAT_SEND_LIMITS = { device: { perMinute: 6, perHour: 60 }, account: { perMinute: 10, perHour: 120 } };
26
+ export const CHAT_NOT_APPROVER = "The lead talks with approvers. Ask an approver to change your role.";
27
+ const MESSAGES_READ = 40;
28
+ const CARD_LINES = 40;
29
+ const CARD_LINE_CHARS = 2_000;
30
+ const CARD_WORDS_CHARS = 1_000;
31
+ const WATCH_STEPS = 8;
32
+ const WATCH_TOOLS = 12;
33
+ const WATCH_LABEL_CHARS = 120;
34
+ const WATCH_STATUS_CHARS = 160;
35
+ const WATCH_TEXT_CHARS = 40_000;
36
+ const TASK_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
37
+ const IDEMPOTENCY_KEY = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
38
+ const bytesOf = (value) => Buffer.byteLength(JSON.stringify(value), "utf8");
39
+ const clip = (text, chars) => (text.length <= chars ? text : text.slice(0, chars));
40
+ function threadParam(params) {
41
+ const thread = params["thread"];
42
+ if (thread === null || typeof thread !== "object" || Array.isArray(thread))
43
+ throw new CompanionChatError("invalid_params", "thread is required");
44
+ const asked = thread;
45
+ if (asked["kind"] === "lead" && Object.keys(asked).length === 1)
46
+ return { kind: "lead" };
47
+ if (asked["kind"] === "task" && typeof asked["task"] === "string" && TASK_ID.test(asked["task"]) && Object.keys(asked).length === 2)
48
+ return { kind: "task", task: asked["task"] };
49
+ throw new CompanionChatError("invalid_params", "thread must be the lead conversation or one task");
50
+ }
51
+ export function chatRequestHash(thread, text, context) {
52
+ return createHash("sha256").update(JSON.stringify({ v: 1, thread: thread.kind, family: thread.kind === "task" ? thread.key : null, text, attachments: [], context })).digest("hex");
53
+ }
54
+ function deliveryOf(row, ahead) {
55
+ switch (row.status) {
56
+ case "queued":
57
+ if (row.error?.startsWith("Waiting: ") === true)
58
+ return { state: "waiting", detail: row.error.slice("Waiting: ".length) };
59
+ return ahead ? { state: "waiting", detail: "Waiting for your earlier messages…" } : { state: "saved", detail: null };
60
+ case "running": return { state: "replying", detail: null };
61
+ case "answered": return { state: "answered", detail: null };
62
+ case "uncertain": return { state: "uncertain", detail: row.error ?? "Delivery could not be confirmed. Nothing was sent again." };
63
+ default: return { state: "not_sent", detail: row.error ?? "It was not sent." };
64
+ }
65
+ }
66
+ class SendLimits {
67
+ buckets = new Map();
68
+ bucket(key, perMin, burst, nowMs) {
69
+ let bucket = this.buckets.get(key);
70
+ if (bucket === undefined) {
71
+ if (this.buckets.size > 4_096)
72
+ this.buckets.clear();
73
+ bucket = new TokenBucket(perMin, burst, nowMs);
74
+ this.buckets.set(key, bucket);
75
+ }
76
+ return bucket;
77
+ }
78
+ take(deviceId, account, nowMs) {
79
+ const { device, account: person } = CHAT_SEND_LIMITS;
80
+ const minute = [this.bucket(`d:m:${deviceId}`, device.perMinute, device.perMinute, nowMs), this.bucket(`a:m:${account}`, person.perMinute, person.perMinute, nowMs)];
81
+ const hour = [this.bucket(`d:h:${deviceId}`, device.perHour / 60, device.perHour, nowMs), this.bucket(`a:h:${account}`, person.perHour / 60, person.perHour, nowMs)];
82
+ if (minute.some(one => one.available(nowMs) < 1))
83
+ return "minute";
84
+ if (hour.some(one => one.available(nowMs) < 1))
85
+ return "hour";
86
+ for (const one of [...minute, ...hour])
87
+ one.take(1, nowMs);
88
+ return "ok";
89
+ }
90
+ }
91
+ export function chatTurnRecord(key, seq, turn, snapshot) {
92
+ const steps = snapshot.steps.slice(-WATCH_STEPS).map(step => ({
93
+ tools: step.toolCalls.slice(-WATCH_TOOLS).map(tool => ({ label: clip(tool.label, WATCH_LABEL_CHARS), state: tool.state })),
94
+ }));
95
+ const record = {
96
+ k: "turn", thread: key, turn, seq, phase: snapshot.phase, status: clip(snapshot.status, WATCH_STATUS_CHARS),
97
+ text: clip(snapshot.text, WATCH_TEXT_CHARS), steps, done: snapshot.done, ok: snapshot.ok,
98
+ };
99
+ if (snapshot.text.length > WATCH_TEXT_CHARS)
100
+ record["truncated"] = true;
101
+ let text = record["text"];
102
+ while (bytesOf(record) > CHAT_WATCH_RECORD_BYTES && text.length > 0) {
103
+ text = text.slice(0, Math.floor(text.length / 2));
104
+ record["text"] = text;
105
+ record["truncated"] = true;
106
+ }
107
+ if (bytesOf(record) > CHAT_WATCH_RECORD_BYTES)
108
+ record["steps"] = [];
109
+ return bytesOf(record) <= CHAT_WATCH_RECORD_BYTES ? record : { k: "changed", thread: key, seq };
110
+ }
111
+ const READ_LIMITS = { cards: 8, cardBytes: 24 * 1024, label: 200, kind: 40, state: 20, task: 200, activity: 200, detail: 300, key: 64, createdAt: 40,
112
+ leadName: 80, problem: 500, title: 300, threadKey: 220 };
113
+ export const CARD_UNAVAILABLE = "Too long to show here. Open it on your Mac.";
114
+ function boundedCard(card) {
115
+ const head = { id: card.id, kind: clip(card.kind, READ_LIMITS.kind), label: clip(card.label, READ_LIMITS.label), state: clip(card.state, READ_LIMITS.state),
116
+ task: card.task === null ? null : clip(card.task, READ_LIMITS.task) };
117
+ const unavailable = { ...head, lines: [], said: null, note: CARD_UNAVAILABLE, truncated: true };
118
+ const cut = card.kind.length > READ_LIMITS.kind || card.label.length > READ_LIMITS.label || card.state.length > READ_LIMITS.state
119
+ || (card.task?.length ?? 0) > READ_LIMITS.task || card.lines.length > CARD_LINES || card.lines.some(line => line.length > CARD_LINE_CHARS)
120
+ || (card.said?.length ?? 0) > CARD_WORDS_CHARS || (card.note?.length ?? 0) > CARD_WORDS_CHARS;
121
+ const bounded = cut
122
+ ? { ...head, lines: card.lines.slice(0, CARD_LINES).map(line => clip(line, CARD_LINE_CHARS)), said: card.said === null ? null : clip(card.said, CARD_WORDS_CHARS),
123
+ note: card.note === null ? null : clip(card.note, CARD_WORDS_CHARS), truncated: true }
124
+ : { ...head, lines: card.lines, said: card.said, note: card.note, ...(card.truncated === true ? { truncated: true } : {}) };
125
+ return bytesOf(bounded) <= READ_LIMITS.cardBytes ? bounded : unavailable;
126
+ }
127
+ function boundedMessage(message) {
128
+ return {
129
+ id: message.id, role: message.role, text: message.text, ...(message.truncated === true ? { truncated: true } : {}),
130
+ createdAt: clip(message.createdAt, READ_LIMITS.createdAt), activity: message.activity === null ? null : clip(message.activity, READ_LIMITS.activity),
131
+ ...(message.key === undefined ? {} : { key: clip(message.key, READ_LIMITS.key) }),
132
+ ...(message.delivery === undefined ? {} : { delivery: { state: message.delivery.state, detail: message.delivery.detail === null ? null : clip(message.delivery.detail, READ_LIMITS.detail) } }),
133
+ cards: message.cards.slice(0, READ_LIMITS.cards).map(boundedCard),
134
+ };
135
+ }
136
+ function boundedHead(head) {
137
+ const text = (value, chars) => (typeof value === "string" ? clip(value, chars) : value);
138
+ const thread = head["thread"] !== null && typeof head["thread"] === "object" ? head["thread"] : null;
139
+ return {
140
+ ...head,
141
+ ...(head["key"] === undefined ? {} : { key: text(head["key"], READ_LIMITS.threadKey) }),
142
+ ...(head["leadName"] === undefined ? {} : { leadName: text(head["leadName"], READ_LIMITS.leadName) }),
143
+ ...(head["problem"] === undefined ? {} : { problem: text(head["problem"], READ_LIMITS.problem) }),
144
+ ...(thread === null ? {} : { thread: { ...thread, ...(thread["task"] === undefined ? {} : { task: text(thread["task"], READ_LIMITS.task) }),
145
+ ...(thread["title"] === undefined ? {} : { title: text(thread["title"], READ_LIMITS.title) }) } }),
146
+ };
147
+ }
148
+ export function boundedRead(head, messages, earlier) {
149
+ const top = boundedHead(head);
150
+ let kept = messages.map(boundedMessage);
151
+ let older = earlier;
152
+ const envelope = (list) => ({ ok: true, result: { ...top, earlier: older, messages: list } });
153
+ while (kept.length > 1 && bytesOf(envelope(kept)) > CHAT_READ_BYTES) {
154
+ kept = kept.slice(1);
155
+ older = true;
156
+ }
157
+ if (kept.length === 1 && bytesOf(envelope(kept)) > CHAT_READ_BYTES) {
158
+ const only = { ...kept[0], cards: kept[0].cards.map(card => ({ id: card.id, kind: card.kind, label: card.label, state: card.state, lines: [], said: null,
159
+ note: CARD_UNAVAILABLE, task: card.task, truncated: true })), truncated: true };
160
+ let text = only.text;
161
+ while (bytesOf(envelope([{ ...only, text }])) > CHAT_READ_BYTES && text.length > 0)
162
+ text = text.slice(0, Math.floor(text.length * 0.75));
163
+ kept = [{ ...only, text }];
164
+ }
165
+ if (bytesOf(envelope(kept)) <= CHAT_READ_BYTES)
166
+ return { ...top, earlier: older, messages: kept };
167
+ const thread = top["thread"] !== null && typeof top["thread"] === "object" ? top["thread"] : { kind: "lead" };
168
+ return {
169
+ v: 1, key: clip(String(top["key"] ?? "lead"), READ_LIMITS.threadKey),
170
+ thread: { kind: thread["kind"] === "task" ? "task" : "lead", ...(typeof thread["task"] === "string" ? { task: clip(thread["task"], READ_LIMITS.task) } : {}),
171
+ ...(typeof thread["title"] === "string" ? { title: clip(thread["title"], 80) } : {}) },
172
+ leadName: clip(String(top["leadName"] ?? "Lead"), READ_LIMITS.leadName), canSend: top["canSend"] === true,
173
+ problem: typeof top["problem"] === "string" ? clip(top["problem"], 200) : null, busy: top["busy"] === true, earlier: true, messages: [],
174
+ };
175
+ }
176
+ export function createCompanionChat(deps) {
177
+ const { runtime } = deps;
178
+ const store = runtime.store;
179
+ const nowMs = deps.nowMs ?? (() => runtime.clock().getTime());
180
+ const limits = new SendLimits();
181
+ const watchers = new Set();
182
+ const demoReceipts = new Map();
183
+ const demoWriting = new Map();
184
+ const demoListeners = new Set();
185
+ let demoTurn = 0;
186
+ function stands(principal) {
187
+ const device = getPairedDevice(store.handle, principal.deviceId);
188
+ const identity = store.workspaceIdentity();
189
+ if (device === null || device.revokedAt !== null || device.activatedAt === null || device.recoveryGeneration !== identity.recoveryGeneration
190
+ || device.accountName !== principal.accountName || identity.recoveryGeneration !== principal.recoveryGeneration || identity.id !== principal.workspaceId)
191
+ return false;
192
+ return deviceAccountStands(device, store.accountOf(principal.accountName));
193
+ }
194
+ const asAccount = (principal, work) => requestContext.run({ csrf: "", returnTo: "/", actor: principal.accountName }, work);
195
+ function approverOf(principal) {
196
+ const account = store.accountOf(principal.accountName);
197
+ if (account === null || account.revokedAt !== null)
198
+ throw new CompanionChatError("standing_revoked", "This iPhone is no longer paired.");
199
+ if (account.role !== "approver")
200
+ throw new CompanionChatError("not_approver", CHAT_NOT_APPROVER);
201
+ const repos = asAccount(principal, () => runtime.managedRepos());
202
+ const verified = verifyApproverStanding(store, principal.accountName, account.generation, repos);
203
+ if (!verified.ok)
204
+ throw new CompanionChatError("not_approver", CHAT_NOT_APPROVER);
205
+ return verified.who;
206
+ }
207
+ function resolveThread(principal, asked) {
208
+ if (asked.kind === "lead")
209
+ return { scope: LEAD_THREAD, key: "lead", family: null };
210
+ const family = asAccount(principal, () => runtime.familyOf(asked.task));
211
+ const visible = family !== null && family.problem === null && asAccount(principal, () => runtime.visible(family.current.repo) && runtime.visible(family.root.repo));
212
+ if (family === null || !visible)
213
+ throw new CompanionChatError("not_found", "No such task.");
214
+ return { scope: { kind: "task", key: family.root.id }, key: `task:${family.root.id}`, family };
215
+ }
216
+ function admit(principal) {
217
+ if (!stands(principal))
218
+ throw new CompanionChatError("standing_revoked", "This iPhone is no longer paired.");
219
+ }
220
+ function sendProblem() {
221
+ if (store.isDemo())
222
+ return deps.demoLead?.() == null ? "The demo lead isn't running." : null;
223
+ const config = store.getChatConfig();
224
+ if (config === null)
225
+ return "Chat isn't set up yet. Choose a chat provider in Toolroll settings on your Mac.";
226
+ if (isDirectChatProvider(config.provider))
227
+ return "Chat from the iPhone uses your membership login. Direct API chat stays on your Mac.";
228
+ const enabled = runtime.chatEnablement();
229
+ return enabled.ok ? null : enabled.why;
230
+ }
231
+ function threadHead(resolved, who, busy) {
232
+ const problem = sendProblem();
233
+ return {
234
+ v: 1, key: resolved.key,
235
+ thread: resolved.family === null ? { kind: "lead" } : { kind: "task", task: resolved.family.root.id, title: resolved.family.root.title },
236
+ leadName: leadNameOf(store, who.name), canSend: problem === null, problem, busy,
237
+ };
238
+ }
239
+ function readThread(principal, asked) {
240
+ const who = approverOf(principal);
241
+ const resolved = resolveThread(principal, asked);
242
+ if (store.isDemo() && resolved.family === null)
243
+ return demoRead(resolved, who);
244
+ const found = store.liveLeadThreadFor(who.name, resolved.scope);
245
+ const thread = found !== null && found.ceilingDigest === who.ceilingDigest ? found : null;
246
+ if (thread === null)
247
+ return boundedRead(threadHead(resolved, who, false), [], false);
248
+ const rows = store.listLeadMessages(thread.id, MESSAGES_READ + 1);
249
+ const earlier = rows.length > MESSAGES_READ;
250
+ const messages = earlier ? rows.slice(1) : rows;
251
+ const proposals = store.listLeadProposals(thread.id);
252
+ const live = store.liveLeadTurnFor(who.name);
253
+ const pending = live !== null && live.thread === thread.id ? live : null;
254
+ const asks = new Map(messages.flatMap(one => { const asked = one.role === "assistant" && one.turn !== null ? store.leadAsk(one.turn) : null; return asked === null ? [] : [[asked.turn, asked]]; }));
255
+ const projected = leadChatOf({ room: resolved.key, session: null, leadName: leadNameOf(store, who.name), canSend: false, problem: null, project: null,
256
+ messages, proposals, decisions: decisionsFor(store, proposals), pending, ask: null, asks });
257
+ const queueRows = deps.queue.queue.forThread(thread.id);
258
+ const queued = new Map(queueRows.map(row => [row.message, row]));
259
+ const keys = chatKeysOf(store.handle, principal.deviceId, thread.id);
260
+ const phoneMessages = projected.messages.map(message => {
261
+ const row = queued.get(message.id);
262
+ const ahead = row !== undefined && queueRows.some(other => other.message < row.message && (other.status === "queued" || other.status === "running"));
263
+ const key = keys.get(message.id);
264
+ return {
265
+ id: message.id, role: message.role, text: message.text, createdAt: message.createdAt, activity: message.activity,
266
+ ...(key === undefined ? {} : { key }),
267
+ ...(row === undefined ? {} : { delivery: deliveryOf(row, ahead) }),
268
+ cards: message.cards.map(card => ({
269
+ id: card.id, kind: card.kind, label: card.label, state: card.state, lines: card.lines, said: card.said, note: card.note,
270
+ task: card.links.find(link => link.task !== null)?.task ?? (card.primary?.kind === "link" ? card.primary.task : null) ?? null,
271
+ })),
272
+ };
273
+ });
274
+ return boundedRead(threadHead(resolved, who, pending !== null), phoneMessages, earlier);
275
+ }
276
+ function sendMessage(principal, params) {
277
+ const asked = threadParam(params);
278
+ const key = params["idempotencyKey"], raw = params["text"];
279
+ if (typeof key !== "string" || !IDEMPOTENCY_KEY.test(key))
280
+ throw new CompanionChatError("invalid_params", "idempotencyKey must be a UUID");
281
+ if (typeof raw !== "string")
282
+ throw new CompanionChatError("invalid_params", "text is required");
283
+ for (const extra of Object.keys(params))
284
+ if (!["thread", "text", "idempotencyKey"].includes(extra))
285
+ throw new CompanionChatError("invalid_params", `unknown parameter ${extra}`);
286
+ const text = raw.trim();
287
+ if (text === "")
288
+ throw new CompanionChatError("empty_message", "Write a message first.");
289
+ if (text.length > LEAD_MESSAGE_MAX_CHARS)
290
+ throw new CompanionChatError("too_long", `That message is ${text.length.toLocaleString("en-US")} characters; the lead takes up to ${LEAD_MESSAGE_MAX_CHARS.toLocaleString("en-US")}. Nothing was sent.`);
291
+ if (scanForSecrets(text).length > 0)
292
+ throw new CompanionChatError("secret_in_message", "That message looks like it contains a password or key, so it wasn't sent or saved. Remove it and send again.");
293
+ const who = approverOf(principal);
294
+ const resolved = resolveThread(principal, asked);
295
+ const context = resolved.family === null ? null : { task: resolved.family.root.id };
296
+ const hash = chatRequestHash(resolved.family === null ? { kind: "lead" } : { kind: "task", key: resolved.family.root.id }, text, context);
297
+ if (store.isDemo())
298
+ return demoSend(principal, resolved, who, key, hash, text);
299
+ const receipt = chatReceiptOf(store.handle, principal.deviceId, key);
300
+ if (receipt !== null) {
301
+ if (receipt.requestHash !== hash)
302
+ throw new CompanionChatError("idempotency_key_conflict", "This message was already sent with different words. Check the conversation.");
303
+ const row = deps.queue.queue.get(receipt.message);
304
+ return { message: receipt.message, key, replayed: true, delivery: row === null ? { state: "not_sent", detail: "It was not sent." } : deliveryOf(row, false) };
305
+ }
306
+ const limited = limits.take(principal.deviceId, principal.accountName, nowMs());
307
+ if (limited !== "ok")
308
+ throw new CompanionChatError("rate_limited", limited === "minute" ? "You're sending quickly. Wait a moment, then send again." : "You've sent a lot this hour. Try again later, or use Toolroll on your Mac.");
309
+ const problem = sendProblem();
310
+ if (problem !== null)
311
+ throw new CompanionChatError("chat_unavailable", problem);
312
+ const now = runtime.clock();
313
+ const queued = store.transact(() => {
314
+ const conversation = resolveChannelLead(store, { approver: who.name, approverGeneration: who.generation }, who.repos, now, resolved.scope);
315
+ if (!conversation.ok) {
316
+ throw new CompanionChatError(conversation.reason === "busy" ? "busy" : "chat_unavailable", conversation.said ?? (conversation.reason === "busy" ? "The lead is finishing a reply on your Mac. Send again in a moment." : "Chat isn't available right now."));
317
+ }
318
+ const identity = store.workspaceIdentity();
319
+ const device = getPairedDevice(store.handle, principal.deviceId);
320
+ if (device === null)
321
+ throw new CompanionChatError("standing_revoked", "This iPhone is no longer paired.");
322
+ const decided = deps.queue.queue.queueFromPhone({
323
+ approver: conversation.who.name, approverGeneration: conversation.who.generation, session: conversation.session.id, ceilingDigest: conversation.who.ceilingDigest,
324
+ thread: conversation.thread.id, text, requestId: createHash("sha256").update(`${principal.deviceId}\0${key}`).digest("hex").slice(0, 32), context,
325
+ origin: { deviceId: principal.deviceId, account: principal.accountName, accountGeneration: device.accountGeneration, workspaceId: identity.id,
326
+ recoveryGeneration: identity.recoveryGeneration, idempotencyKey: key, requestHash: hash, session: conversation.session.id, thread: conversation.thread.id, threadKey: resolved.key },
327
+ }, now);
328
+ if (decided.kind === "conflict")
329
+ throw new CompanionChatError("idempotency_key_conflict", "This message was already sent with different words. Check the conversation.");
330
+ if (decided.kind === "full")
331
+ throw new CompanionChatError("queue_full", decided.message);
332
+ return decided;
333
+ });
334
+ deps.queue.kick();
335
+ for (const watcher of watchers)
336
+ watcher();
337
+ return { message: queued.row.message, key, replayed: queued.already, delivery: deliveryOf(queued.row, false) };
338
+ }
339
+ function watch(principal, params, emit, end) {
340
+ let resolved, who;
341
+ try {
342
+ admit(principal);
343
+ who = approverOf(principal);
344
+ resolved = resolveThread(principal, threadParam(params));
345
+ }
346
+ catch (error) {
347
+ return { ok: false, code: error instanceof CompanionChatError ? error.code : "invalid_params", message: error instanceof Error ? error.message : "Can't watch that conversation." };
348
+ }
349
+ let closed = false, seq = 0, fingerprint = null;
350
+ let following = null;
351
+ let pacing = null, owed = false, lastSentAt = 0;
352
+ const send = (record) => { if (!closed)
353
+ emit(Buffer.from(JSON.stringify(record), "utf8")); };
354
+ const allowed = () => {
355
+ try {
356
+ admit(principal);
357
+ approverOf(principal);
358
+ resolveThread(principal, resolved.family === null ? { kind: "lead" } : { kind: "task", task: resolved.family.root.id });
359
+ return true;
360
+ }
361
+ catch {
362
+ return false;
363
+ }
364
+ };
365
+ const deny = () => { stop(); end?.("denied"); };
366
+ const snapshotNow = () => {
367
+ if (following === null || closed)
368
+ return;
369
+ const turn = following.turn;
370
+ const record = chatTurnRecord(resolved.key, ++seq, turn.turn ?? 0, chatSnapshot(turn));
371
+ send(record);
372
+ lastSentAt = nowMs();
373
+ if (turn.done) {
374
+ unfollow();
375
+ tick();
376
+ }
377
+ };
378
+ const offer = () => {
379
+ if (following === null || closed)
380
+ return;
381
+ if (following.turn.done) {
382
+ if (pacing !== null) {
383
+ clearTimeout(pacing);
384
+ pacing = null;
385
+ }
386
+ snapshotNow();
387
+ return;
388
+ }
389
+ const wait = 120 - (nowMs() - lastSentAt);
390
+ if (wait <= 0 && pacing === null) {
391
+ snapshotNow();
392
+ return;
393
+ }
394
+ owed = true;
395
+ if (pacing === null) {
396
+ pacing = setTimeout(() => { pacing = null; if (owed) {
397
+ owed = false;
398
+ snapshotNow();
399
+ } }, Math.max(1, wait));
400
+ pacing.unref?.();
401
+ }
402
+ };
403
+ const unfollow = () => {
404
+ if (following !== null)
405
+ following.turn.listeners.delete(following.listener);
406
+ following = null;
407
+ };
408
+ const follow = (thread) => {
409
+ const turn = deps.liveTurns.get(thread);
410
+ if (turn === undefined || turn.done || (following !== null && following.turn === turn))
411
+ return;
412
+ unfollow();
413
+ const listener = () => { if (!allowed()) {
414
+ deny();
415
+ return;
416
+ } offer(); };
417
+ turn.listeners.add(listener);
418
+ following = { thread, turn, listener };
419
+ offer();
420
+ };
421
+ const tick = () => {
422
+ if (closed)
423
+ return;
424
+ if (!allowed()) {
425
+ deny();
426
+ return;
427
+ }
428
+ if (store.isDemo() && resolved.family === null) {
429
+ const now = demoFingerprint(resolved.key);
430
+ if (now !== fingerprint) {
431
+ fingerprint = now;
432
+ send({ k: "changed", thread: resolved.key, seq: ++seq });
433
+ }
434
+ return;
435
+ }
436
+ const found = store.liveLeadThreadFor(who.name, resolved.scope);
437
+ const thread = found !== null && found.ceilingDigest === who.ceilingDigest ? found : null;
438
+ const now = thread === null ? "none" : threadFingerprint(thread.id, who.name);
439
+ if (fingerprint !== null && now !== fingerprint)
440
+ send({ k: "changed", thread: resolved.key, seq: ++seq });
441
+ fingerprint = now;
442
+ if (thread !== null)
443
+ follow(thread.id);
444
+ };
445
+ const demoListener = (threadKey) => {
446
+ if (closed || threadKey !== resolved.key)
447
+ return;
448
+ const writing = demoWriting.get(threadKey);
449
+ if (writing === undefined) {
450
+ tick();
451
+ return;
452
+ }
453
+ const done = writing.shown >= writing.text.length;
454
+ send({ k: "turn", thread: resolved.key, turn: writing.turn, seq: ++seq, phase: done ? "closed" : "writing", status: done ? "" : "Writing…",
455
+ text: writing.text.slice(0, writing.shown), steps: [], done, ok: done });
456
+ };
457
+ const onWake = () => tick();
458
+ watchers.add(onWake);
459
+ demoListeners.add(demoListener);
460
+ const unsubscribeBus = deps.subscribeBus?.(onWake) ?? (() => { });
461
+ const timer = setInterval(tick, deps.watchPollMs ?? 2_000);
462
+ timer.unref?.();
463
+ function stop() {
464
+ if (closed)
465
+ return;
466
+ closed = true;
467
+ clearInterval(timer);
468
+ if (pacing !== null)
469
+ clearTimeout(pacing);
470
+ unfollow();
471
+ watchers.delete(onWake);
472
+ demoListeners.delete(demoListener);
473
+ unsubscribeBus();
474
+ }
475
+ queueMicrotask(tick);
476
+ return { ok: true, unsubscribe: stop };
477
+ }
478
+ function threadFingerprint(thread, approver) {
479
+ const last = store.handle.prepare("SELECT max(id) AS id, count(*) AS n, total(length(text)) AS chars FROM lead_message WHERE thread = ?").get(thread);
480
+ const queue = store.handle.prepare("SELECT message, status, revision FROM lead_queue WHERE thread = ? ORDER BY message").all(thread);
481
+ const proposals = store.handle.prepare("SELECT id, state FROM lead_proposal WHERE thread = ? ORDER BY id").all(thread);
482
+ const live = store.liveLeadTurnFor(approver);
483
+ return JSON.stringify([last, queue, proposals, live !== null && live.thread === thread ? [live.id, live.state] : null]);
484
+ }
485
+ function demoFingerprint(threadKey) {
486
+ const lead = deps.demoLead?.() ?? null;
487
+ const writing = demoWriting.get(threadKey);
488
+ return JSON.stringify([lead?.version() ?? null, writing === undefined ? null : [writing.turn, writing.shown >= writing.text.length]]);
489
+ }
490
+ function demoRead(resolved, who) {
491
+ const lead = deps.demoLead?.() ?? null;
492
+ const writing = demoWriting.get(resolved.key);
493
+ const messages = [];
494
+ for (const exchange of lead?.exchanges() ?? []) {
495
+ const at = new Date(0).toISOString();
496
+ const mine = [...demoReceipts.entries()].find(([, value]) => value.message === exchange.id)?.[0].split("\0")[1];
497
+ const still = writing !== undefined && writing.exchange === exchange.id && writing.shown < writing.text.length;
498
+ messages.push({ id: exchange.id * 2 - 1, role: "operator", text: exchange.asked, createdAt: at, activity: null, ...(mine === undefined ? {} : { key: mine }),
499
+ delivery: still ? { state: "replying", detail: null } : { state: "answered", detail: null }, cards: [] });
500
+ if (still)
501
+ continue;
502
+ messages.push({ id: exchange.id * 2, role: "assistant", text: exchange.reply, createdAt: at, activity: null, cards: [{
503
+ id: exchange.id, kind: "task", label: "New task", state: exchange.state === "proposed" ? "pending" : "confirmed",
504
+ lines: [exchange.plan.title, exchange.plan.goal, ...exchange.plan.boundaries], said: exchange.taskId === null ? null : `Filed ${exchange.taskId}.`,
505
+ note: exchange.state === "proposed" ? "Approve it in Toolroll on your Mac." : null, task: exchange.taskId,
506
+ }] });
507
+ }
508
+ return boundedRead(threadHead(resolved, who, writing !== undefined && writing.shown < writing.text.length), messages, false);
509
+ }
510
+ function demoWrite(threadKey, text, exchange, done) {
511
+ const writing = { turn: ++demoTurn, text, shown: 0, exchange };
512
+ demoWriting.set(threadKey, writing);
513
+ const words = text.split(/(?<=\s)/);
514
+ let index = 0;
515
+ const step = () => {
516
+ if (demoWriting.get(threadKey) !== writing)
517
+ return;
518
+ index++;
519
+ writing.shown = words.slice(0, index).join("").length;
520
+ for (const listener of demoListeners)
521
+ listener(threadKey);
522
+ if (index < words.length) {
523
+ const next = setTimeout(step, deps.demoWordMs ?? 70);
524
+ next.unref?.();
525
+ return;
526
+ }
527
+ done();
528
+ demoWriting.delete(threadKey);
529
+ for (const listener of demoListeners)
530
+ listener(threadKey);
531
+ };
532
+ const first = setTimeout(step, deps.demoWordMs ?? 70);
533
+ first.unref?.();
534
+ }
535
+ function demoSend(principal, resolved, who, key, hash, text) {
536
+ const receiptKey = `${principal.deviceId}\0${key}`;
537
+ const seen = demoReceipts.get(receiptKey);
538
+ if (seen !== undefined) {
539
+ if (seen.hash !== hash)
540
+ throw new CompanionChatError("idempotency_key_conflict", "This message was already sent with different words. Check the conversation.");
541
+ return { message: resolved.family === null ? seen.message * 2 - 1 : seen.message, key, replayed: true, delivery: { state: "answered", detail: null } };
542
+ }
543
+ const limited = limits.take(principal.deviceId, principal.accountName, nowMs());
544
+ if (limited !== "ok")
545
+ throw new CompanionChatError("rate_limited", "You're sending quickly. Wait a moment, then send again.");
546
+ const lead = deps.demoLead?.() ?? null;
547
+ if (lead === null)
548
+ throw new CompanionChatError("chat_unavailable", "The demo lead isn't running.");
549
+ const now = runtime.clock();
550
+ if (resolved.family === null) {
551
+ const exchange = lead.ask(text, now);
552
+ demoReceipts.set(receiptKey, { hash, message: exchange.id });
553
+ demoWrite(resolved.key, exchange.reply, exchange.id, () => undefined);
554
+ return { message: exchange.id * 2 - 1, key, replayed: false, delivery: { state: "replying", detail: null } };
555
+ }
556
+ const thread = store.openLeadThread(who.name, who.ceilingDigest, now, resolved.scope).thread;
557
+ const message = store.appendLeadMessage({ thread: thread.id, turn: null, role: "operator", text }, now);
558
+ demoReceipts.set(receiptKey, { hash, message });
559
+ const title = resolved.family.root.title;
560
+ const reply = `This demo lead is scripted, so it can't read "${title}" for real. On your own Mac, the lead reads the task and answers here.`;
561
+ demoWrite(resolved.key, reply, null, () => { store.appendLeadMessage({ thread: thread.id, turn: null, role: "assistant", text: reply }, runtime.clock()); });
562
+ return { message, key, replayed: false, delivery: { state: "replying", detail: null } };
563
+ }
564
+ return {
565
+ chatRead: (principal, params) => { admit(principal); const read = readThread(principal, threadParam(params)); admit(principal); return read; },
566
+ chatSend: (principal, params) => { admit(principal); return sendMessage(principal, params); },
567
+ chatWatchSubscribe: watch,
568
+ turnStarted: () => { for (const watcher of watchers)
569
+ watcher(); },
570
+ };
571
+ }