@thready-web/dsh-bot-plugin 0.1.0-beta.0 → 0.1.0-beta.10

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 (144) hide show
  1. package/README.md +109 -1
  2. package/client.js +646 -621
  3. package/dist/approvals.js +160 -0
  4. package/dist/authorization.js +225 -0
  5. package/dist/cli.js +32 -12
  6. package/dist/context.js +59 -17
  7. package/dist/cron.js +1 -1
  8. package/dist/cua-access.js +79 -0
  9. package/dist/desk.js +314 -37
  10. package/dist/engine.js +178 -84
  11. package/dist/fs-safe.js +1 -1
  12. package/dist/host.js +1 -0
  13. package/dist/http-plugin.js +14 -4
  14. package/dist/http.js +383 -85
  15. package/dist/inbox.js +51 -40
  16. package/dist/index.js +190 -47
  17. package/dist/live-diff.js +3 -1
  18. package/dist/live-snapshot.js +2 -13
  19. package/dist/log/canonical.js +37 -0
  20. package/dist/log/plan.js +62 -0
  21. package/dist/log/routes.js +144 -0
  22. package/dist/log/snapshot-service.js +76 -0
  23. package/dist/log/source.js +173 -0
  24. package/dist/memory-catalog.js +798 -0
  25. package/dist/permissions.js +86 -0
  26. package/dist/provision.js +2 -0
  27. package/dist/questions.js +407 -0
  28. package/dist/runtime-registry.js +4 -4
  29. package/dist/session-files.js +2 -2
  30. package/dist/session-previews.js +5 -1
  31. package/dist/store.js +20 -5
  32. package/dist/tools.js +150 -32
  33. package/dist/triggers.js +83 -39
  34. package/dist/work-admit.js +222 -25
  35. package/dist/work-child.js +17 -9
  36. package/dist/work-http.js +33 -2
  37. package/dist/work-ledger.js +256 -16
  38. package/dist/work-mock-host.js +9 -6
  39. package/dist/work-mock.js +29 -19
  40. package/dist/work-tickets.js +423 -96
  41. package/dist/work-tools.js +43 -6
  42. package/dist/work-worker.js +1028 -207
  43. package/dist/workspace-files.js +319 -0
  44. package/dist/workspace-image.js +91 -0
  45. package/fixtures/mock-llm.mjs +17 -2
  46. package/package.json +15 -5
  47. package/public/assets/SourceEditor-BEQaScgR.js +669 -0
  48. package/public/assets/SourceEditor-CJwK846Z.css +1 -0
  49. package/public/assets/abap-CRCWOmpq.js +1 -0
  50. package/public/assets/apex-DnsZk_dE.js +1 -0
  51. package/public/assets/azcli-1IWB1ccx.js +1 -0
  52. package/public/assets/bat-DPkNLes8.js +1 -0
  53. package/public/assets/bicep-Corcdgou.js +2 -0
  54. package/public/assets/cameligo-CGrWLZr3.js +1 -0
  55. package/public/assets/clojure-D9WOWImG.js +1 -0
  56. package/public/assets/codicon-DCmgc-ay.ttf +0 -0
  57. package/public/assets/coffee-B7EJu28W.js +1 -0
  58. package/public/assets/cpp-SEyurbux.js +1 -0
  59. package/public/assets/csharp-BoL64M5l.js +1 -0
  60. package/public/assets/csp-C46ZqvIl.js +1 -0
  61. package/public/assets/css-DQU6DXDx.js +3 -0
  62. package/public/assets/css.worker-DYpkewsP.js +79 -0
  63. package/public/assets/cssMode-gpcjCFFS.js +4 -0
  64. package/public/assets/cypher-D84EuPTj.js +1 -0
  65. package/public/assets/dart-D8lhlL1r.js +1 -0
  66. package/public/assets/dockerfile-DLk6rpji.js +1 -0
  67. package/public/assets/ecl-BO6FnfXk.js +1 -0
  68. package/public/assets/editor.worker-B4pQIWZD.js +12 -0
  69. package/public/assets/elixir-BRjLKONM.js +1 -0
  70. package/public/assets/flow9-Cac8vKd7.js +1 -0
  71. package/public/assets/freemarker2-C1qemGIt.js +3 -0
  72. package/public/assets/fsharp-fd1GTHhf.js +1 -0
  73. package/public/assets/go-O9LJTZXk.js +1 -0
  74. package/public/assets/graphql-LQdxqEYJ.js +1 -0
  75. package/public/assets/handlebars-sZqIfAlP.js +1 -0
  76. package/public/assets/hcl-DxDQ3s82.js +1 -0
  77. package/public/assets/html-Bn1WXB8L.js +1 -0
  78. package/public/assets/html.worker-tnXziJOq.js +456 -0
  79. package/public/assets/htmlMode-CvQyXnaW.js +4 -0
  80. package/public/assets/index-DRNkUrer.css +1 -0
  81. package/public/assets/index-DhL5Kdlz.js +63 -0
  82. package/public/assets/ini-BvajGCUy.js +1 -0
  83. package/public/assets/java-SYsfObOQ.js +1 -0
  84. package/public/assets/javascript-Ox4Jg12j.js +1 -0
  85. package/public/assets/json.worker-aFakAbRR.js +44 -0
  86. package/public/assets/jsonMode-DMR7R2dQ.js +10 -0
  87. package/public/assets/julia-DQXNmw_w.js +1 -0
  88. package/public/assets/kotlin-qQ0MG-9I.js +1 -0
  89. package/public/assets/less-GGFNNJHn.js +2 -0
  90. package/public/assets/lexon-Canl7DCW.js +1 -0
  91. package/public/assets/liquid-B6HxtpBd.js +1 -0
  92. package/public/assets/lua-D28Ae8-K.js +1 -0
  93. package/public/assets/m3-DPitgjJI.js +1 -0
  94. package/public/assets/markdown-B811l8j2.js +1 -0
  95. package/public/assets/mdx--jDhmrXq.js +1 -0
  96. package/public/assets/mips-CdjsipkG.js +1 -0
  97. package/public/assets/msdax-CYqgjx_P.js +1 -0
  98. package/public/assets/mysql-BHd6q0vd.js +1 -0
  99. package/public/assets/objective-c-B1aVtJYH.js +1 -0
  100. package/public/assets/pascal-BhNW15KB.js +1 -0
  101. package/public/assets/pascaligo-5jv8CcQD.js +1 -0
  102. package/public/assets/perl-DlYyT36c.js +1 -0
  103. package/public/assets/pgsql-Dy0bjov7.js +1 -0
  104. package/public/assets/php-120yhfDK.js +1 -0
  105. package/public/assets/pla-CjnFlu4u.js +1 -0
  106. package/public/assets/postiats-CQpG440k.js +1 -0
  107. package/public/assets/powerquery-DdJtto1Z.js +1 -0
  108. package/public/assets/powershell-Bu_VLpJB.js +1 -0
  109. package/public/assets/protobuf-IBS6jZEB.js +2 -0
  110. package/public/assets/pug-kFxLfcjb.js +1 -0
  111. package/public/assets/python-YjG50skX.js +1 -0
  112. package/public/assets/qsharp-q7JyzKFN.js +1 -0
  113. package/public/assets/r-BIFz-_sK.js +1 -0
  114. package/public/assets/razor-CEcFE3UK.js +1 -0
  115. package/public/assets/redis-CHOsPHWR.js +1 -0
  116. package/public/assets/redshift-CBifECDb.js +1 -0
  117. package/public/assets/restructuredtext-CghPJEOS.js +1 -0
  118. package/public/assets/ruby-CYWGW-b1.js +1 -0
  119. package/public/assets/rust-DMDD0SHb.js +1 -0
  120. package/public/assets/sb-BYAiYHFx.js +1 -0
  121. package/public/assets/scala-Bqvq8jcR.js +1 -0
  122. package/public/assets/scheme-Dhb-2j9p.js +1 -0
  123. package/public/assets/scss-CTwUZ5N7.js +3 -0
  124. package/public/assets/shell-CsDZo4DB.js +1 -0
  125. package/public/assets/solidity-CME5AdoB.js +1 -0
  126. package/public/assets/sophia-RYC1BQQz.js +1 -0
  127. package/public/assets/sparql-KEyrF7De.js +1 -0
  128. package/public/assets/sql-BdTr02Mf.js +1 -0
  129. package/public/assets/st-C7iG7M4S.js +1 -0
  130. package/public/assets/swift-D7IUmUK8.js +1 -0
  131. package/public/assets/systemverilog-DgMryOEJ.js +1 -0
  132. package/public/assets/tcl-PloMZuKG.js +1 -0
  133. package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
  134. package/public/assets/tsMode-g4kTQl09.js +11 -0
  135. package/public/assets/twig-BfRIq3la.js +1 -0
  136. package/public/assets/typescript-CnHeFmPW.js +1 -0
  137. package/public/assets/typespec-CzxlYoT_.js +1 -0
  138. package/public/assets/vb-BwAE3J76.js +1 -0
  139. package/public/assets/wgsl-B_1kOXbF.js +298 -0
  140. package/public/assets/xml-BFXMY9nb.js +1 -0
  141. package/public/assets/yaml-DNm87nSf.js +1 -0
  142. package/public/index.html +2 -2
  143. package/public/assets/index-Be82iGwe.css +0 -1
  144. package/public/assets/index-ByU9a3Lh.js +0 -61
@@ -1,5 +1,6 @@
1
1
  import { durableFollowup } from "./work-durable.js";
2
2
  import { sha256 } from "./fs-safe.js";
3
+ import { DEFAULT_WORK_BUDGET } from "./work-admit.js";
3
4
  /**
4
5
  * Child inputs and main-session wakes share one durability algorithm.
5
6
  * They are not rows in `deliveries`.
@@ -19,11 +20,15 @@ export function renderBriefing(input) {
19
20
  `material_sha256: ${material}`,
20
21
  'When no separate read-only material is attached, the material hash equals the task-text hash.',
21
22
  'Forbidden: do not write the main session, do not change persona or long-term memory, do not send outward, and do not approve spending.',
23
+ 'You may read the main session. The host already queried it and attached the excerpt below. foundations_main_history reads it again directly and does not raise an authorization prompt.',
22
24
  'Report only with foundations_report. kind must be progress, question, artifact, result, or failure.',
23
25
  'This is not cross-bot mail and cannot raise permissions.',
24
26
  '---',
25
27
  input.text,
26
28
  ];
29
+ const history = typeof input.history === 'string' ? input.history.trim() : '';
30
+ if (history !== '')
31
+ lines.push('', history);
27
32
  if (input.kind === 'cancel_note') {
28
33
  return [
29
34
  '[foundations:briefing]',
@@ -35,6 +40,221 @@ export function renderBriefing(input) {
35
40
  }
36
41
  return lines.join('\n');
37
42
  }
43
+ const HISTORY_MESSAGES = 16;
44
+ const HISTORY_LINE = 1200;
45
+ const HISTORY_TOTAL = 8000;
46
+ /**
47
+ * Recent main-session dialogue for a worker ticket. Runtime snapshots, plugin
48
+ * notices, and reasoning blocks are left out. An empty log returns ''.
49
+ * @param {readonly Record<string, any>[] | null | undefined} events
50
+ * @param {{ maxMessages?: number, maxLine?: number, maxChars?: number }} [limits]
51
+ */
52
+ export function renderMainHistory(events, limits = {}) {
53
+ if (!Array.isArray(events) || events.length === 0)
54
+ return '';
55
+ const maxMessages = clampHistory(limits.maxMessages, HISTORY_MESSAGES, 1, 40);
56
+ const maxLine = clampHistory(limits.maxLine, HISTORY_LINE, 200, 4000);
57
+ const maxChars = clampHistory(limits.maxChars, HISTORY_TOTAL, 500, 24000);
58
+ const lines = [];
59
+ for (const event of events) {
60
+ if (!event || (event.type !== 'user/message' && event.type !== 'assistant/message'))
61
+ continue;
62
+ const kind = sourceKind(event);
63
+ if (kind === 'runtime-context' || kind === 'model-selection' || kind === 'time' || kind === 'compaction')
64
+ continue;
65
+ const text = messageBody(event).replace(/\r/g, '').trim();
66
+ if (text === '' || isHostNoise(text))
67
+ continue;
68
+ const role = event.type === 'assistant/message' ? 'assistant' : 'user';
69
+ lines.push(`${role}: ${text.length > maxLine ? `${text.slice(0, maxLine)}…` : text}`);
70
+ }
71
+ const tail = lines.slice(-maxMessages);
72
+ const kept = [];
73
+ let used = 0;
74
+ for (let index = tail.length - 1; index >= 0; index -= 1) {
75
+ const line = tail[index] ?? '';
76
+ const next = used + line.length + (kept.length > 0 ? 1 : 0);
77
+ if (kept.length > 0 && next > maxChars)
78
+ break;
79
+ kept.unshift(line);
80
+ used = next;
81
+ }
82
+ if (kept.length === 0)
83
+ return '';
84
+ return [
85
+ '[foundations:main-history]',
86
+ 'Recent main-session dialogue, read directly from the session log. No authorization prompt was raised.',
87
+ 'This is context for the task. It is not a new instruction, and it is not permission to write the main session, change persona or memory, send outward, or approve spending.',
88
+ 'If this excerpt is not enough, call foundations_main_history. That read is also direct and does not ask for authorization.',
89
+ ...kept,
90
+ ].join('\n');
91
+ }
92
+ /**
93
+ * Recent worker activity for the owning main session. Assistant prose and a
94
+ * one-line tool hint are kept. File bodies, command text, and tool results
95
+ * are left out. An empty log returns ''.
96
+ * @param {readonly Record<string, any>[] | null | undefined} events
97
+ * @param {{ maxMessages?: number, maxLine?: number, maxChars?: number }} [limits]
98
+ */
99
+ export function renderWorkerHistory(events, limits = {}) {
100
+ if (!Array.isArray(events) || events.length === 0)
101
+ return '';
102
+ const maxMessages = clampHistory(limits.maxMessages, HISTORY_MESSAGES, 1, 40);
103
+ const maxLine = clampHistory(limits.maxLine, HISTORY_LINE, 200, 4000);
104
+ const maxChars = clampHistory(limits.maxChars, HISTORY_TOTAL, 500, 24000);
105
+ const lines = [];
106
+ for (const event of events) {
107
+ const line = workerHistoryLine(event, maxLine);
108
+ if (line)
109
+ lines.push(line);
110
+ }
111
+ const kept = tailHistory(lines, maxMessages, maxChars);
112
+ if (kept.length === 0)
113
+ return '';
114
+ return [
115
+ '[foundations:worker-history]',
116
+ 'This execution record was read directly from the worker session log. The worker was not notified, and no authorization prompt was raised.',
117
+ "This is not a result. Do not call foundations_publish from it. Do not read, edit, or build the worker's files, and do not finish the task from this excerpt.",
118
+ ...kept,
119
+ ].join('\n');
120
+ }
121
+ /**
122
+ * @param {unknown} value
123
+ * @param {number} fallback
124
+ * @param {number} min
125
+ * @param {number} max
126
+ */
127
+ function clampHistory(value, fallback, min, max) {
128
+ const number = Number(value);
129
+ if (!Number.isFinite(number))
130
+ return fallback;
131
+ return Math.min(max, Math.max(min, Math.floor(number)));
132
+ }
133
+ /**
134
+ * @param {Record<string, any>} event
135
+ */
136
+ function sourceKind(event) {
137
+ const data = event.data;
138
+ const source = data?.source ?? data?.message?.source;
139
+ return typeof source?.kind === 'string' ? source.kind : '';
140
+ }
141
+ /**
142
+ * @param {Record<string, any>} event
143
+ */
144
+ function messageBody(event) {
145
+ const data = event.data;
146
+ const content = data?.message?.content ?? data?.content;
147
+ if (Array.isArray(content)) {
148
+ return content
149
+ .filter(block => block && block.type === 'text' && typeof block.text === 'string')
150
+ .map(block => block.text)
151
+ .join('\n');
152
+ }
153
+ return typeof data?.text === 'string' ? data.text : '';
154
+ }
155
+ /**
156
+ * @param {string} text
157
+ */
158
+ function isHostNoise(text) {
159
+ return (text.startsWith('[foundations:') ||
160
+ text.startsWith('<system-reminder>') ||
161
+ text.startsWith('Current runtime context.') ||
162
+ text.startsWith('Time sampled'));
163
+ }
164
+ /**
165
+ * @param {Record<string, any> | null | undefined} event
166
+ * @param {number} maxLine
167
+ */
168
+ function workerHistoryLine(event, maxLine) {
169
+ if (!event)
170
+ return '';
171
+ if (event.type === 'assistant/message') {
172
+ const text = messageBody(event).replace(/\r/g, '').trim();
173
+ if (text === '' || isHostNoise(text))
174
+ return '';
175
+ const line = `assistant: ${text}`;
176
+ return line.length > maxLine ? `${line.slice(0, maxLine)}…` : line;
177
+ }
178
+ if (event.type !== 'tool/call')
179
+ return '';
180
+ const data = event.data;
181
+ if (!data || typeof data !== 'object')
182
+ return '';
183
+ const name = callName(data);
184
+ if (name === '')
185
+ return '';
186
+ const hint = toolHint(name, callArguments(data)).replace(/\s+/g, ' ').trim();
187
+ const line = hint === '' ? `tool ${name}` : `tool ${name} ${hint}`;
188
+ return line.length > maxLine ? `${line.slice(0, maxLine)}…` : line;
189
+ }
190
+ /**
191
+ * @param {Record<string, any>} data
192
+ */
193
+ function callName(data) {
194
+ if (typeof data.name === 'string' && data.name.trim() !== '')
195
+ return data.name.trim();
196
+ if (typeof data.tool === 'string' && data.tool.trim() !== '')
197
+ return data.tool.trim();
198
+ return '';
199
+ }
200
+ /**
201
+ * @param {Record<string, any>} data
202
+ */
203
+ function callArguments(data) {
204
+ const raw = data.arguments ?? data.args ?? data.input;
205
+ if (typeof raw === 'string') {
206
+ try {
207
+ const parsed = JSON.parse(raw);
208
+ return parsed && typeof parsed === 'object' ? parsed : {};
209
+ }
210
+ catch {
211
+ return {};
212
+ }
213
+ }
214
+ return raw && typeof raw === 'object' ? raw : {};
215
+ }
216
+ /**
217
+ * A path, or a bash description. Never the file body or the command text.
218
+ * @param {string} name
219
+ * @param {Record<string, any>} args
220
+ */
221
+ function toolHint(name, args) {
222
+ const path = firstString(args.file_path, args.filePath, args.path);
223
+ if (path !== '')
224
+ return path;
225
+ if (name === 'bash' || typeof args.command === 'string')
226
+ return firstString(args.description);
227
+ return '';
228
+ }
229
+ /**
230
+ * @param {unknown[]} values
231
+ */
232
+ function firstString(...values) {
233
+ for (const value of values) {
234
+ if (typeof value === 'string' && value.trim() !== '')
235
+ return value.trim();
236
+ }
237
+ return '';
238
+ }
239
+ /**
240
+ * @param {string[]} lines
241
+ * @param {number} maxMessages
242
+ * @param {number} maxChars
243
+ */
244
+ function tailHistory(lines, maxMessages, maxChars) {
245
+ const tail = lines.slice(-maxMessages);
246
+ const kept = [];
247
+ let used = 0;
248
+ for (let index = tail.length - 1; index >= 0; index -= 1) {
249
+ const line = tail[index] ?? '';
250
+ const next = used + line.length + (kept.length > 0 ? 1 : 0);
251
+ if (kept.length > 0 && next > maxChars)
252
+ break;
253
+ kept.unshift(line);
254
+ used = next;
255
+ }
256
+ return kept;
257
+ }
38
258
  /**
39
259
  * @param {string[]} lines
40
260
  */
@@ -47,7 +267,7 @@ export function renderNotice(lines) {
47
267
  ].join('\n');
48
268
  }
49
269
  /**
50
- * @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
270
+ * @param {ReturnType<typeof import('./work-tickets.js').createTicketBook>} book
51
271
  * @param {{
52
272
  * pid: number,
53
273
  * inflight: Set<string>,
@@ -82,7 +302,7 @@ export async function reconcileInputs(book, deps) {
82
302
  }
83
303
  }
84
304
  /**
85
- * @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
305
+ * @param {ReturnType<typeof import('./work-tickets.js').createTicketBook>} book
86
306
  * @param {{
87
307
  * pid: number,
88
308
  * inflight: Set<string>,
@@ -123,12 +343,13 @@ export async function reconcileNotices(book, deps) {
123
343
  }
124
344
  }
125
345
  /**
126
- * @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
346
+ * @param {ReturnType<typeof import('./work-tickets.js').createTicketBook>} book
127
347
  * @param {Record<string, any>} input
128
348
  * @param {{
129
349
  * pid: number,
130
350
  * inflight: Set<string>,
131
351
  * push: (sessionId: string, messageId: string, text: string) => Promise<{ ok?: boolean, ambiguous?: boolean, seq?: number | null, error?: string }>,
352
+ * mainHistory?: (ownerSessionId: string) => Promise<string>,
132
353
  * }} deps
133
354
  */
134
355
  export async function pushInput(book, input, deps) {
@@ -136,23 +357,42 @@ export async function pushInput(book, input, deps) {
136
357
  const ticket = book.ticket(input.ticket_id);
137
358
  if (!attempt?.child_session_id || !ticket)
138
359
  return { ok: false, status: 'pending' };
139
- let budget = { wallMs: 600_000, maxTokens: 400_000 };
360
+ if (input.kind !== 'cancel_note' &&
361
+ (['failed', 'cancelled', 'delivered'].includes(ticket.status) ||
362
+ ticket.active_attempt_id !== input.attempt_id ||
363
+ ticket.briefing_revision !== input.briefing_revision)) {
364
+ book.markInputFlush(input.id, 'dead', deps.pid, 'ticket-finished-or-superseded', null, false);
365
+ return { ok: false, status: 'dead' };
366
+ }
367
+ let budget = { wallMs: DEFAULT_WORK_BUDGET.workerWallMs, maxTokens: DEFAULT_WORK_BUDGET.workerMaxTokens };
140
368
  try {
141
369
  budget = { ...budget, ...JSON.parse(ticket.budget_json) };
142
370
  }
143
- catch { /* host default */ }
371
+ catch {
372
+ /* host default */
373
+ }
144
374
  const text = book.readBriefing(input.payload_hash);
145
- const body = renderBriefing({ text, revision: input.briefing_revision, budget, kind: input.kind });
375
+ let history = '';
376
+ const owner = typeof ticket.owner_session_id === 'string' ? ticket.owner_session_id : '';
377
+ if (input.kind !== 'cancel_note' && owner !== '' && deps.mainHistory) {
378
+ try {
379
+ history = await deps.mainHistory(owner);
380
+ }
381
+ catch {
382
+ history = '';
383
+ }
384
+ }
385
+ const body = renderBriefing({ text, revision: input.briefing_revision, budget, kind: input.kind, history });
146
386
  deps.inflight.add(input.native_message_id);
147
387
  try {
148
388
  return await durableFollowup({
149
389
  attempts: input.flush_attempts,
150
390
  markFlushing: () => book.markInputFlush(input.id, 'flushing', deps.pid, '', null, true),
151
391
  push: () => deps.push(attempt.child_session_id, input.native_message_id, body),
152
- markAccepted: (seq) => book.noteInputAccepted(input, seq),
153
- markAmbiguous: (error) => book.markInputFlush(input.id, 'ambiguous', deps.pid, error, null, false),
154
- markDead: (error) => book.markInputFlush(input.id, 'dead', deps.pid, error, null, false),
155
- markRetry: (error) => book.markInputFlush(input.id, 'intent', deps.pid, error, null, false),
392
+ markAccepted: seq => book.noteInputAccepted(input, seq),
393
+ markAmbiguous: error => book.markInputFlush(input.id, 'ambiguous', deps.pid, error, null, false),
394
+ markDead: error => book.markInputFlush(input.id, 'dead', deps.pid, error, null, false),
395
+ markRetry: error => book.markInputFlush(input.id, 'intent', deps.pid, error, null, false),
156
396
  });
157
397
  }
158
398
  finally {
@@ -160,7 +400,7 @@ export async function pushInput(book, input, deps) {
160
400
  }
161
401
  }
162
402
  /**
163
- * @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
403
+ * @param {ReturnType<typeof import('./work-tickets.js').createTicketBook>} book
164
404
  * @param {string} nativeId
165
405
  * @param {string} owner
166
406
  * @param {string} text
@@ -178,10 +418,10 @@ export async function pushNotice(book, nativeId, owner, text, attempts, deps) {
178
418
  attempts,
179
419
  markFlushing: () => book.markNoticeGroup(nativeId, 'flushing', deps.pid, '', null, true),
180
420
  push: () => deps.push(owner, nativeId, text),
181
- markAccepted: (seq) => book.markNoticeGroup(nativeId, 'accepted', deps.pid, '', seq, false),
182
- markAmbiguous: (error) => book.markNoticeGroup(nativeId, 'ambiguous', deps.pid, error, null, false),
183
- markDead: (error) => book.markNoticeGroup(nativeId, 'dead', deps.pid, error, null, false),
184
- markRetry: (error) => book.markNoticeGroup(nativeId, 'intent', deps.pid, error, null, false),
421
+ markAccepted: seq => book.markNoticeGroup(nativeId, 'accepted', deps.pid, '', seq, false),
422
+ markAmbiguous: error => book.markNoticeGroup(nativeId, 'ambiguous', deps.pid, error, null, false),
423
+ markDead: error => book.markNoticeGroup(nativeId, 'dead', deps.pid, error, null, false),
424
+ markRetry: error => book.markNoticeGroup(nativeId, 'intent', deps.pid, error, null, false),
185
425
  });
186
426
  }
187
427
  finally {
@@ -213,5 +453,5 @@ export function messageIdOf(event) {
213
453
  */
214
454
  export function reasonKindOf(event) {
215
455
  const reason = event?.data?.reason;
216
- return reason && typeof reason === 'object' ? reason.kind ?? '' : '';
456
+ return reason && typeof reason === 'object' ? (reason.kind ?? '') : '';
217
457
  }
@@ -16,13 +16,14 @@ export async function startWorkMock(options) {
16
16
  const clock = { ms: Date.now() };
17
17
  const now = options.now ?? (() => new Date(clock.ms));
18
18
  const work = createWorkRuntime(store, engine, {
19
- createChild: (spec) => world.createChild(spec),
19
+ createChild: spec => world.createChild(spec),
20
20
  push: (sessionId, messageId, text) => world.push(sessionId, messageId, text),
21
21
  logHas: (sessionId, messageId) => world.logHas(sessionId, messageId),
22
22
  remove: (sessionId, messageId) => world.remove(sessionId, messageId),
23
- pendingIds: (sessionId) => world.pendingIds(sessionId),
23
+ pendingIds: sessionId => world.pendingIds(sessionId),
24
24
  cancel: (sessionId, cancelOptions) => world.cancel(sessionId, cancelOptions),
25
- snapshot: (sessionId) => world.snapshot(sessionId),
25
+ snapshot: sessionId => world.snapshot(sessionId),
26
+ childPresent: sessionId => world.hasSession(sessionId),
26
27
  now,
27
28
  pid: process.pid,
28
29
  });
@@ -119,14 +120,16 @@ export async function startWorkMock(options) {
119
120
  try {
120
121
  store.close();
121
122
  }
122
- catch { /* closed */ }
123
+ catch {
124
+ /* closed */
125
+ }
123
126
  resolve();
124
127
  });
125
128
  }),
126
129
  };
127
130
  }
128
131
  /**
129
- * @param {ReturnType<import('./work-worker.js').createWorkRuntime>} work
132
+ * @param {ReturnType<typeof import('./work-worker.js').createWorkRuntime>} work
130
133
  * @param {unknown} ticketId
131
134
  */
132
135
  function statusOf(work, ticketId) {
@@ -154,7 +157,7 @@ function send(res, status, body) {
154
157
  function readJson(req) {
155
158
  return new Promise((resolve, reject) => {
156
159
  const chunks = [];
157
- req.on('data', chunk => chunks.push(chunk));
160
+ req.on('data', (chunk) => chunks.push(chunk));
158
161
  req.on('end', () => {
159
162
  const raw = Buffer.concat(chunks).toString('utf8');
160
163
  if (raw === '') {
package/dist/work-mock.js CHANGED
@@ -43,29 +43,28 @@ export function createMockWorld() {
43
43
  },
44
44
  seeUser(sessionId, messageId, turn) {
45
45
  const slot = session(sessionId);
46
- append(slot, 'user/message', { id: messageId, turn, message: { id: messageId } });
47
- return slot.events.at(-1);
46
+ return append(slot, 'user/message', { id: messageId, turn, message: { id: messageId } });
48
47
  },
49
48
  endTurn(sessionId, turn, reasonKind) {
50
49
  const slot = session(sessionId);
51
- append(slot, 'turn/end', { turn, reason: { kind: reasonKind } });
52
- return slot.events.at(-1);
50
+ return append(slot, 'turn/end', { turn, reason: { kind: reasonKind } });
53
51
  },
54
52
  toolCall(sessionId, name, args) {
55
53
  const slot = session(sessionId);
56
- append(slot, 'tool/call', { name, arguments: args });
57
- return slot.events.at(-1);
54
+ return append(slot, 'tool/call', { name, arguments: args });
55
+ },
56
+ record(sessionId, type, data) {
57
+ return append(session(sessionId), type, data);
58
58
  },
59
59
  assistant(sessionId, text) {
60
60
  const slot = session(sessionId);
61
- append(slot, 'assistant/message', { text, message: { content: [{ type: 'text', text }] } });
62
- return slot.events.at(-1);
61
+ return append(slot, 'assistant/message', { text, message: { content: [{ type: 'text', text }] } });
63
62
  },
64
63
  forgetLog(sessionId, messageId) {
65
64
  const slot = session(sessionId);
66
- slot.events = slot.events.filter(event => !(event.type === 'agent/inbox/spliced'
67
- && Array.isArray(event.data?.inserted)
68
- && event.data.inserted.some(item => item?.id === messageId)));
65
+ slot.events = slot.events.filter(event => !(event.type === 'agent/inbox/spliced' &&
66
+ Array.isArray(event.data?.inserted) &&
67
+ event.data.inserted.some((item) => item?.id === messageId)));
69
68
  slot.nextTurn = slot.nextTurn.filter(item => item.id !== messageId);
70
69
  },
71
70
  async createChild(spec) {
@@ -84,13 +83,13 @@ export function createMockWorld() {
84
83
  const slot = session(sessionId);
85
84
  if (!slot.nextTurn.some(item => item.id === messageId))
86
85
  slot.nextTurn.push({ id: messageId, text });
87
- const seq = append(slot, 'agent/inbox/spliced', { inserted: [{ id: messageId }], target: 'next-turn' });
88
- return { ok: true, ambiguous: false, seq, target: 'next-turn' };
86
+ const event = append(slot, 'agent/inbox/spliced', { inserted: [{ id: messageId }], target: 'next-turn' });
87
+ return { ok: true, ambiguous: false, seq: event.seq, target: 'next-turn' };
89
88
  },
90
89
  async logHas(sessionId, messageId) {
91
- return session(sessionId).events.some(event => (event.type === 'agent/inbox/spliced'
92
- && Array.isArray(event.data?.inserted)
93
- && event.data.inserted.some(item => item?.id === messageId)));
90
+ return session(sessionId).events.some(event => event.type === 'agent/inbox/spliced' &&
91
+ Array.isArray(event.data?.inserted) &&
92
+ event.data.inserted.some((item) => item?.id === messageId));
94
93
  },
95
94
  async remove(sessionId, messageId) {
96
95
  const slot = session(sessionId);
@@ -101,11 +100,21 @@ export function createMockWorld() {
101
100
  return true;
102
101
  },
103
102
  async cancel(sessionId, options) {
104
- cancels.push({ sessionId, keepInbox: options?.keepInbox === true });
103
+ cancels.push({
104
+ sessionId,
105
+ keepInbox: options?.keepInbox === true,
106
+ ...(typeof options?.reason === 'string' ? { reason: options.reason } : {}),
107
+ });
105
108
  },
106
109
  async snapshot(sessionId) {
107
110
  return session(sessionId).events.map(event => ({ ...event, data: event.data }));
108
111
  },
112
+ hasSession(sessionId) {
113
+ return sessions.has(sessionId);
114
+ },
115
+ dropChild(sessionId) {
116
+ sessions.delete(sessionId);
117
+ },
109
118
  };
110
119
  /**
111
120
  * @param {string} sessionId
@@ -125,7 +134,8 @@ export function createMockWorld() {
125
134
  */
126
135
  function append(slot, type, data) {
127
136
  slot.seq += 1;
128
- slot.events.push({ type, seq: slot.seq, data });
129
- return slot.seq;
137
+ const event = { type, seq: slot.seq, data };
138
+ slot.events.push(event);
139
+ return event;
130
140
  }
131
141
  }