@thready-web/dsh-bot-plugin 0.1.0-beta.7 → 0.1.0-beta.9

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 (107) hide show
  1. package/dist/context.js +2 -0
  2. package/dist/desk.js +158 -1
  3. package/dist/http.js +42 -5
  4. package/dist/work-ledger.js +123 -0
  5. package/dist/work-mock.js +3 -0
  6. package/dist/work-tools.js +19 -0
  7. package/dist/work-worker.js +73 -1
  8. package/dist/workspace-files.js +319 -0
  9. package/package.json +1 -1
  10. package/public/assets/SourceEditor-CJwK846Z.css +1 -0
  11. package/public/assets/SourceEditor-Cu3oRqA0.js +669 -0
  12. package/public/assets/abap-CRCWOmpq.js +1 -0
  13. package/public/assets/apex-DnsZk_dE.js +1 -0
  14. package/public/assets/azcli-1IWB1ccx.js +1 -0
  15. package/public/assets/bat-DPkNLes8.js +1 -0
  16. package/public/assets/bicep-Corcdgou.js +2 -0
  17. package/public/assets/cameligo-CGrWLZr3.js +1 -0
  18. package/public/assets/clojure-D9WOWImG.js +1 -0
  19. package/public/assets/codicon-DCmgc-ay.ttf +0 -0
  20. package/public/assets/coffee-B7EJu28W.js +1 -0
  21. package/public/assets/cpp-SEyurbux.js +1 -0
  22. package/public/assets/csharp-BoL64M5l.js +1 -0
  23. package/public/assets/csp-C46ZqvIl.js +1 -0
  24. package/public/assets/css-DQU6DXDx.js +3 -0
  25. package/public/assets/css.worker-DYpkewsP.js +79 -0
  26. package/public/assets/cssMode-FWS1gu61.js +4 -0
  27. package/public/assets/cypher-D84EuPTj.js +1 -0
  28. package/public/assets/dart-D8lhlL1r.js +1 -0
  29. package/public/assets/dockerfile-DLk6rpji.js +1 -0
  30. package/public/assets/ecl-BO6FnfXk.js +1 -0
  31. package/public/assets/editor.worker-B4pQIWZD.js +12 -0
  32. package/public/assets/elixir-BRjLKONM.js +1 -0
  33. package/public/assets/flow9-Cac8vKd7.js +1 -0
  34. package/public/assets/freemarker2-U6v7W5T8.js +3 -0
  35. package/public/assets/fsharp-fd1GTHhf.js +1 -0
  36. package/public/assets/go-O9LJTZXk.js +1 -0
  37. package/public/assets/graphql-LQdxqEYJ.js +1 -0
  38. package/public/assets/handlebars-Dz33dYnR.js +1 -0
  39. package/public/assets/hcl-DxDQ3s82.js +1 -0
  40. package/public/assets/html-Bg_jMpt6.js +1 -0
  41. package/public/assets/html.worker-tnXziJOq.js +456 -0
  42. package/public/assets/htmlMode-CzB3QL-e.js +4 -0
  43. package/public/assets/index-Ah9i9dFa.js +63 -0
  44. package/public/assets/index-PsHINv2D.css +1 -0
  45. package/public/assets/ini-BvajGCUy.js +1 -0
  46. package/public/assets/java-SYsfObOQ.js +1 -0
  47. package/public/assets/javascript-DMkhf8OX.js +1 -0
  48. package/public/assets/json.worker-aFakAbRR.js +44 -0
  49. package/public/assets/jsonMode-DRHhZtb7.js +10 -0
  50. package/public/assets/julia-DQXNmw_w.js +1 -0
  51. package/public/assets/kotlin-qQ0MG-9I.js +1 -0
  52. package/public/assets/less-GGFNNJHn.js +2 -0
  53. package/public/assets/lexon-Canl7DCW.js +1 -0
  54. package/public/assets/liquid-C-8-PQ92.js +1 -0
  55. package/public/assets/lua-D28Ae8-K.js +1 -0
  56. package/public/assets/m3-DPitgjJI.js +1 -0
  57. package/public/assets/markdown-B811l8j2.js +1 -0
  58. package/public/assets/mdx-z749XIEc.js +1 -0
  59. package/public/assets/mips-CdjsipkG.js +1 -0
  60. package/public/assets/msdax-CYqgjx_P.js +1 -0
  61. package/public/assets/mysql-BHd6q0vd.js +1 -0
  62. package/public/assets/objective-c-B1aVtJYH.js +1 -0
  63. package/public/assets/pascal-BhNW15KB.js +1 -0
  64. package/public/assets/pascaligo-5jv8CcQD.js +1 -0
  65. package/public/assets/perl-DlYyT36c.js +1 -0
  66. package/public/assets/pgsql-Dy0bjov7.js +1 -0
  67. package/public/assets/php-120yhfDK.js +1 -0
  68. package/public/assets/pla-CjnFlu4u.js +1 -0
  69. package/public/assets/postiats-CQpG440k.js +1 -0
  70. package/public/assets/powerquery-DdJtto1Z.js +1 -0
  71. package/public/assets/powershell-Bu_VLpJB.js +1 -0
  72. package/public/assets/protobuf-IBS6jZEB.js +2 -0
  73. package/public/assets/pug-kFxLfcjb.js +1 -0
  74. package/public/assets/python-BHKY4qLy.js +1 -0
  75. package/public/assets/qsharp-q7JyzKFN.js +1 -0
  76. package/public/assets/r-BIFz-_sK.js +1 -0
  77. package/public/assets/razor-CNY--QcM.js +1 -0
  78. package/public/assets/redis-CHOsPHWR.js +1 -0
  79. package/public/assets/redshift-CBifECDb.js +1 -0
  80. package/public/assets/restructuredtext-CghPJEOS.js +1 -0
  81. package/public/assets/ruby-CYWGW-b1.js +1 -0
  82. package/public/assets/rust-DMDD0SHb.js +1 -0
  83. package/public/assets/sb-BYAiYHFx.js +1 -0
  84. package/public/assets/scala-Bqvq8jcR.js +1 -0
  85. package/public/assets/scheme-Dhb-2j9p.js +1 -0
  86. package/public/assets/scss-CTwUZ5N7.js +3 -0
  87. package/public/assets/shell-CsDZo4DB.js +1 -0
  88. package/public/assets/solidity-CME5AdoB.js +1 -0
  89. package/public/assets/sophia-RYC1BQQz.js +1 -0
  90. package/public/assets/sparql-KEyrF7De.js +1 -0
  91. package/public/assets/sql-BdTr02Mf.js +1 -0
  92. package/public/assets/st-C7iG7M4S.js +1 -0
  93. package/public/assets/swift-D7IUmUK8.js +1 -0
  94. package/public/assets/systemverilog-DgMryOEJ.js +1 -0
  95. package/public/assets/tcl-PloMZuKG.js +1 -0
  96. package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
  97. package/public/assets/tsMode-BdcCVhTZ.js +11 -0
  98. package/public/assets/twig-BfRIq3la.js +1 -0
  99. package/public/assets/typescript-BD5fPxu4.js +1 -0
  100. package/public/assets/typespec-CzxlYoT_.js +1 -0
  101. package/public/assets/vb-BwAE3J76.js +1 -0
  102. package/public/assets/wgsl-B_1kOXbF.js +298 -0
  103. package/public/assets/xml-DuYJr6Y5.js +1 -0
  104. package/public/assets/yaml-DMyywRAi.js +1 -0
  105. package/public/index.html +2 -2
  106. package/public/assets/index-BL0MiCSK.js +0 -63
  107. package/public/assets/index-DS3-wcOY.css +0 -1
package/dist/context.js CHANGED
@@ -25,6 +25,7 @@ export const CHAT = [
25
25
  'The host attaches recent main-session dialogue to the ticket, and the worker reads that log directly with no authorization prompt. Write the task in the briefing. Do not paste the transcript.',
26
26
  'Workers usually have file tools (read, write, edit, working_directory) and foundations_report. They often do not have bash or other command tools. Assign work the worker can actually do. If a worker reports it is blocked because it has no command tools, do not dispatch that same command-only task to another worker with the same tools, and do not silently finish the job in the main session; tell the user the blockage.',
27
27
  'foundations_dispatch may return status=accepted (received, and possibly waiting for a slot), status=enqueued (placed on the execution queue, not started), or a BUDGET error when both the slot cap and the queue cap are full. accepted or enqueued is not completion and not started. Say in one sentence that the work is in the background, then end the turn. Do not sleep, poll, or keep calling tools while waiting.',
28
+ "When the user asks how an unfinished ticket is progressing, call foundations_worker_history once and answer from that excerpt. Do not call it in a loop and do not sleep. The excerpt is not a result: do not call foundations_publish from it, and do not read, edit, or build the worker's files or finish the task. If the excerpt is empty, say there is no execution record yet.",
28
29
  "A ticket notice is not something the user said. On progress or artifact notices, do not take over the work and do not poll. On a question, answer or call foundations_supply. On a budget-extension notice, call foundations_grant with enough to exceed current usage, then end the turn. You cannot refuse a worker budget. Do not take over the worker's task: do not inspect, edit, or build its files, and do not run its commands. On a successful result, call foundations_publish, then write the user-visible reply. On a failed result, tell the user the reason and stop. Do not take over the task. Do not treat a later failed status after a published result as if the worker never delivered. Do not invent a final answer or accept the work on the user's behalf before a result. Do not call foundations_retry unless the user explicitly asks.",
29
30
  'If dispatch returns BUDGET, do not start the job yourself and do not keep opening tickets to bypass the cap. Tell the user the host is at its limit.',
30
31
  `On a budget-wait notice, call foundations_grant and add at least one standard slice (${DEFAULT_WORK_BUDGET.workerMaxTokens} tokens and ${DEFAULT_WORK_BUDGET.workerWallMs} ms), or more when current usage is already past granted plus that slice. Grant every time the notice arrives. There is no limit on how many grants and no cumulative ceiling. Do not refuse because earlier grants were many or large. A grant that does not exceed current usage leaves the worker paused, so do not add a token or two. A terminal failed or cancelled ticket cannot be revived by a grant. Do not foundations_dispatch a replacement ticket for the same work. Do not cancel unless the user asks to stop.`,
@@ -278,6 +279,7 @@ export function renderTickets(rows) {
278
279
  return [
279
280
  '[foundations:tickets]',
280
281
  'These are ticket summaries, not the execution transcript, and not a reply the user has already been given.',
282
+ 'Ticket summaries are not the execution record. To see how far a worker has gotten, call foundations_worker_history.',
281
283
  'accepted means received. enqueued means placed on the execution queue. started is the only status that means work has begun.',
282
284
  'A ticket notice is not something the user said. accepted is not enqueued, and enqueued is not started.',
283
285
  'publish only records an intent to deliver. The words you write next are the reply to the user. Tell the user the result. Do not say accepted, enqueued, or publish.',
package/dist/desk.js CHANGED
@@ -1,9 +1,12 @@
1
1
  /** Workbench routes inside the DSH process. The browser calls /dsh-bot/api. */
2
2
  import { mkdirSync, readFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
3
4
  import { dirname, join, resolve } from 'node:path';
5
+ import { Readable } from 'node:stream';
4
6
  import { openLedger, validIdempotencyKey } from "./desk-ledger.js";
5
7
  import { openSessionPreviews } from "./session-previews.js";
6
8
  import { purgeSessionFiles, sessionDirectory, writeBotMarker } from "./session-files.js";
9
+ import { MAX_UPLOAD_BYTES, listDirectory, openDownload, readFileText, resolveFileRoots, saveUploadFile, } from "./workspace-files.js";
7
10
  /**
8
11
  * Working directory for workbench-created sessions. THREADY_SESSION_CWD wins;
9
12
  * otherwise <DSH_HOME>/workspace, so the model does not start inside DSH_HOME
@@ -45,6 +48,7 @@ const SECRET_KEY = /token|secret|password|authorization|api[-_]?key|cookie/i;
45
48
  * @param {(sessionId: string) => boolean} [options.stillAttached]
46
49
  * @param {(endpoint: string, args: Record<string, unknown>, req: DeskRequest) => Promise<{ status: number, body: RpcEnvelope }>} options.rpc
47
50
  * @param {(req: DeskRequest) => Promise<Record<string, unknown>>} options.usage
51
+ * @param {{ home: string, dshHome: string }} [options.files] Browser roots. Defaults to the process home and DSH_HOME.
48
52
  */
49
53
  export function createDesk(options) {
50
54
  const ledger = openLedger(options.ledgerFile);
@@ -65,7 +69,14 @@ export function createDesk(options) {
65
69
  if (sub === null)
66
70
  return false;
67
71
  if (method === 'GET' &&
68
- (sub === '/health' || sub === '/sessions' || sub === '/tasks' || sub === '/usage' || sub === '/file'))
72
+ (sub === '/health' ||
73
+ sub === '/sessions' ||
74
+ sub === '/tasks' ||
75
+ sub === '/usage' ||
76
+ sub === '/file' ||
77
+ sub === '/files' ||
78
+ sub === '/files/roots' ||
79
+ sub === '/files/text'))
69
80
  return true;
70
81
  if (method === 'POST' && (sub === '/sessions' || sub === '/sessions/previews' || sub === '/tasks'))
71
82
  return true;
@@ -114,8 +125,20 @@ export function createDesk(options) {
114
125
  return { status: 200, body: redactSecrets(await options.usage(req)) };
115
126
  if (method === 'GET' && sub === '/file')
116
127
  return filePreview(req, url);
128
+ if (method === 'GET' && sub === '/files/roots')
129
+ return fileRoots(req, url.searchParams.get('sessionId') ?? '');
130
+ if (method === 'GET' && sub === '/files')
131
+ return fileList(req, url.searchParams.get('sessionId') ?? '', url.searchParams.get('path') ?? '');
132
+ if (method === 'GET' && sub === '/files/text')
133
+ return fileText(req, url.searchParams.get('sessionId') ?? '', url.searchParams.get('path') ?? '');
117
134
  return { status: 404, body: { error: 'not_found' } };
118
135
  },
136
+ openDownload(req, url) {
137
+ return downloadFile(req, url.searchParams.get('sessionId') ?? '', url.searchParams.get('path') ?? '');
138
+ },
139
+ saveUpload(req, url) {
140
+ return uploadFile(req, url.searchParams.get('sessionId') ?? '', url.searchParams.get('dir') ?? '', url.searchParams.get('name') ?? '', url.searchParams.get('overwrite') === '1');
141
+ },
119
142
  };
120
143
  /**
121
144
  * @param {DeskRequest} req
@@ -399,6 +422,118 @@ export function createDesk(options) {
399
422
  });
400
423
  return { status: result.body?.result?.ok === true ? 200 : 502, body: { task: updated } };
401
424
  }
425
+ /**
426
+ * @param {DeskRequest} req
427
+ * @param {string} sessionId
428
+ */
429
+ async function fileRoots(req, sessionId) {
430
+ const ready = await browserAccess(req, sessionId);
431
+ if ('error' in ready)
432
+ return fileFailure(ready.error);
433
+ return { status: 200, body: ready.access.roots };
434
+ }
435
+ /**
436
+ * @param {DeskRequest} req
437
+ * @param {string} sessionId
438
+ * @param {string} filePath
439
+ */
440
+ async function fileList(req, sessionId, filePath) {
441
+ const ready = await browserAccess(req, sessionId);
442
+ if ('error' in ready)
443
+ return fileFailure(ready.error);
444
+ const listed = listDirectory(filePath, ready.access);
445
+ if (!listed.ok)
446
+ return fileFailure(listed.error);
447
+ return { status: 200, body: listed.value };
448
+ }
449
+ /**
450
+ * @param {DeskRequest} req
451
+ * @param {string} sessionId
452
+ * @param {string} filePath
453
+ */
454
+ async function fileText(req, sessionId, filePath) {
455
+ const ready = await browserAccess(req, sessionId);
456
+ if ('error' in ready)
457
+ return fileFailure(ready.error);
458
+ const text = readFileText(filePath, ready.access);
459
+ if (!text.ok)
460
+ return fileFailure(text.error);
461
+ return { status: 200, body: text.value };
462
+ }
463
+ /**
464
+ * @param {DeskRequest} req
465
+ * @param {string} sessionId
466
+ * @param {string} filePath
467
+ */
468
+ async function downloadFile(req, sessionId, filePath) {
469
+ const ready = await browserAccess(req, sessionId);
470
+ if ('error' in ready)
471
+ return fileFailure(ready.error);
472
+ const opened = openDownload(filePath, ready.access);
473
+ if (!opened.ok)
474
+ return fileFailure(opened.error);
475
+ return { status: 200, ...opened.value };
476
+ }
477
+ /**
478
+ * @param {DeskRequest} req
479
+ * @param {string} sessionId
480
+ * @param {string} dir
481
+ * @param {string} name
482
+ * @param {boolean} overwrite
483
+ */
484
+ async function uploadFile(req, sessionId, dir, name, overwrite) {
485
+ const declared = Number(headerValue(req, 'content-length'));
486
+ if (Number.isFinite(declared) && declared > MAX_UPLOAD_BYTES)
487
+ return fileFailure('too_large');
488
+ if (!(req instanceof Readable))
489
+ return fileFailure('bad_path');
490
+ const ready = await browserAccess(req, sessionId);
491
+ if ('error' in ready) {
492
+ req.resume();
493
+ return fileFailure(ready.error);
494
+ }
495
+ const saved = await saveUploadFile(dir, name, req, ready.access, { overwrite, maxBytes: MAX_UPLOAD_BYTES });
496
+ if (!saved.ok) {
497
+ if (saved.error !== 'too_large')
498
+ req.resume();
499
+ return fileFailure(saved.error);
500
+ }
501
+ return { status: 201, body: saved.value };
502
+ }
503
+ /**
504
+ * @param {DeskRequest} req
505
+ * @param {string} sessionId
506
+ */
507
+ async function browserAccess(req, sessionId) {
508
+ const cwd = await workspaceCwd(req, sessionId);
509
+ if (typeof cwd !== 'string')
510
+ return cwd;
511
+ const files = options.files ?? { home: homedir(), dshHome: process.env.DSH_HOME ?? '' };
512
+ return { access: resolveFileRoots({ workspace: cwd, home: files.home, dshHome: files.dshHome }) };
513
+ }
514
+ /**
515
+ * @param {DeskRequest} req
516
+ * @param {string} sessionId
517
+ * @returns {Promise<string | { error: 'invalid_session' }>}
518
+ */
519
+ async function workspaceCwd(req, sessionId) {
520
+ if (!PREVIEW_SESSION.test(sessionId))
521
+ return { error: 'invalid_session' };
522
+ let cwd = options.sessionCwd;
523
+ try {
524
+ const listed = await options.rpc('session/list', { _request: {} }, req);
525
+ const items = listed.body?.result?.value?.items;
526
+ if (Array.isArray(items)) {
527
+ const item = items.find(entry => entry?.sessionId === sessionId);
528
+ if (typeof item?.cwd === 'string' && item.cwd !== '')
529
+ cwd = item.cwd;
530
+ }
531
+ }
532
+ catch {
533
+ /* the configured workspace remains */
534
+ }
535
+ return cwd;
536
+ }
402
537
  /**
403
538
  * @param {DeskRequest} req
404
539
  * @param {URL} url
@@ -560,6 +695,28 @@ function idempotencyOf(req, body) {
560
695
  return header;
561
696
  return typeof body.idempotencyKey === 'string' ? body.idempotencyKey : '';
562
697
  }
698
+ function fileFailure(error) {
699
+ const status = error === 'denied'
700
+ ? 403
701
+ : error === 'missing'
702
+ ? 404
703
+ : error === 'binary'
704
+ ? 415
705
+ : error === 'too_large'
706
+ ? 413
707
+ : error === 'exists'
708
+ ? 409
709
+ : 400;
710
+ return { status, body: { error } };
711
+ }
712
+ /**
713
+ * @param {DeskRequest} req
714
+ * @param {string} name
715
+ */
716
+ function headerValue(req, name) {
717
+ const value = req.headers[name];
718
+ return Array.isArray(value) ? (value[0] ?? '') : (value ?? '');
719
+ }
563
720
  /**
564
721
  * Keep a preview path inside a session workspace: relative, no parent segments.
565
722
  * @param {string} value
package/dist/http.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createReadStream, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
2
3
  import { dirname, extname, join, resolve, sep } from 'node:path';
3
4
  import { fileURLToPath } from 'node:url';
4
5
  import { createDesk, defaultSessionCwd } from "./desk.js";
@@ -49,6 +50,7 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
49
50
  stillAttached: sessionId => attachedSession(ctx, sessionId),
50
51
  rpc: (endpoint, args, req) => hostRpc(req, endpoint, args),
51
52
  usage: req => hostUsage(req),
53
+ files: { home: homedir(), dshHome: process.env.DSH_HOME ?? '' },
52
54
  });
53
55
  /**
54
56
  * @param {import('node:http').IncomingMessage} req
@@ -107,6 +109,16 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
107
109
  ? '/session-foundations/api' + rawPath.slice('/dsh-bot/api'.length)
108
110
  : rawPath;
109
111
  try {
112
+ if (desk && req.method === 'GET' && path === '/session-foundations/api/files/raw') {
113
+ return pipeDownload(res, await desk.openDownload(req, url), url.searchParams.get('inline') === '1');
114
+ }
115
+ if (desk && req.method === 'POST' && path === '/session-foundations/api/files') {
116
+ const outcome = await desk.saveUpload(req, url);
117
+ send(res, outcome.status, outcome.body);
118
+ if (outcome.status === 413)
119
+ res.on('finish', () => req.destroy());
120
+ return;
121
+ }
110
122
  if (desk && desk.owns(req.method ?? 'GET', path)) {
111
123
  const outcome = await desk.handle(req.method ?? 'GET', path, url, req);
112
124
  return send(res, outcome.status, outcome.body);
@@ -599,11 +611,35 @@ function reject(ctx, req) {
599
611
  return 403;
600
612
  return 0;
601
613
  }
602
- /**
603
- * @param {import('node:http').ServerResponse} res
604
- * @param {number} status
605
- * @param {unknown} body
606
- */
614
+ function imageMedia(name) {
615
+ const ext = name.split('.').pop()?.toLowerCase() ?? '';
616
+ if (ext === 'png')
617
+ return 'image/png';
618
+ if (ext === 'jpg' || ext === 'jpeg')
619
+ return 'image/jpeg';
620
+ if (ext === 'gif')
621
+ return 'image/gif';
622
+ if (ext === 'webp')
623
+ return 'image/webp';
624
+ return null;
625
+ }
626
+ function pipeDownload(res, opened, inline = false) {
627
+ if (!('stream' in opened))
628
+ return send(res, opened.status, opened.body);
629
+ const encoded = encodeURIComponent(opened.name);
630
+ const image = inline ? imageMedia(opened.name) : null;
631
+ res.writeHead(opened.status, {
632
+ 'content-type': image ?? 'application/octet-stream',
633
+ 'content-length': opened.size,
634
+ 'content-disposition': image ? `inline; filename*=UTF-8''${encoded}` : `attachment; filename*=UTF-8''${encoded}`,
635
+ 'x-content-type-options': 'nosniff',
636
+ 'cache-control': 'private, no-store',
637
+ 'content-security-policy': "default-src 'none'; sandbox",
638
+ });
639
+ opened.stream.on('error', () => res.destroy());
640
+ res.on('close', () => opened.stream.destroy());
641
+ opened.stream.pipe(res);
642
+ }
607
643
  function send(res, status, body) {
608
644
  if (status === 0)
609
645
  return;
@@ -784,6 +820,7 @@ const DESK_TYPES = new Map([
784
820
  ['.png', 'image/png'],
785
821
  ['.webp', 'image/webp'],
786
822
  ['.woff2', 'font/woff2'],
823
+ ['.ttf', 'font/ttf'],
787
824
  ]);
788
825
  /** Workbench files built into public/. API routes are handled before this. */
789
826
  function serveDesk(req, res, pathname) {
@@ -89,6 +89,35 @@ export function renderMainHistory(events, limits = {}) {
89
89
  ...kept,
90
90
  ].join('\n');
91
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
+ }
92
121
  /**
93
122
  * @param {unknown} value
94
123
  * @param {number} fallback
@@ -132,6 +161,100 @@ function isHostNoise(text) {
132
161
  text.startsWith('Current runtime context.') ||
133
162
  text.startsWith('Time sampled'));
134
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
+ }
135
258
  /**
136
259
  * @param {string[]} lines
137
260
  */
package/dist/work-mock.js CHANGED
@@ -53,6 +53,9 @@ export function createMockWorld() {
53
53
  const slot = session(sessionId);
54
54
  return append(slot, 'tool/call', { name, arguments: args });
55
55
  },
56
+ record(sessionId, type, data) {
57
+ return append(session(sessionId), type, data);
58
+ },
56
59
  assistant(sessionId, text) {
57
60
  const slot = session(sessionId);
58
61
  return append(slot, 'assistant/message', { text, message: { content: [{ type: 'text', text }] } });
@@ -106,6 +106,25 @@ export function workToolDefinitions(work, engine) {
106
106
  },
107
107
  required: ['resultEventId'],
108
108
  }, (args, hostId) => work.reject(hostId, args), 'bot'),
109
+ tool('foundations_worker_history', "Read the worker session log for a ticket this main session owns. The host queries that log directly. The worker is not notified and no authorization prompt is raised. Call it once when the user asks how an unfinished ticket is progressing. The excerpt is not a result: do not call foundations_publish from it, and do not read, edit, or build the worker's files. Omit ticketId only when this session has one unfinished ticket. When several are unfinished, the result lists their ids and does not include a log.", {
110
+ type: 'object',
111
+ properties: {
112
+ ticketId: {
113
+ type: 'string',
114
+ description: 'Ticket to read. Omit only when one unfinished ticket is open.',
115
+ },
116
+ maxChars: {
117
+ type: 'integer',
118
+ description: 'Optional cap for the returned excerpt, from 500 to 24000. Omit it for the default excerpt.',
119
+ },
120
+ },
121
+ }, async (args, hostId) => {
122
+ const maxChars = Number(args.maxChars);
123
+ return work.workerHistory(hostId, {
124
+ ...(typeof args.ticketId === 'string' ? { ticketId: args.ticketId } : {}),
125
+ ...(Number.isFinite(maxChars) ? { maxChars } : {}),
126
+ });
127
+ }, 'bot'),
109
128
  tool('foundations_main_history', 'Read the main session that owns this ticket. The host queries the session log directly and does not raise an authorization prompt. Use it when the attached excerpt is missing a line you need. Do not write the main session.', {
110
129
  type: 'object',
111
130
  properties: {
@@ -3,8 +3,9 @@ import { sha256 } from "./fs-safe.js";
3
3
  import { toolError } from "./errors.js";
4
4
  import { createTicketBook } from "./work-tickets.js";
5
5
  import { decideAdmission, budgetTrip, estimateWorkerBudget, DEFAULT_WORK_BUDGET, effectiveWorkLimits, } from "./work-admit.js";
6
- import { messageIdOf, pushInput, pushNotice, reasonKindOf, reconcileInputs, reconcileNotices, renderMainHistory, renderNotice, } from "./work-ledger.js";
6
+ import { messageIdOf, pushInput, pushNotice, reasonKindOf, reconcileInputs, reconcileNotices, renderMainHistory, renderNotice, renderWorkerHistory, } from "./work-ledger.js";
7
7
  const KINDS = new Set(['progress', 'question', 'artifact', 'result', 'failure']);
8
+ const OPEN_TICKET_STATUSES = ['accepted', 'enqueued', 'started', 'needs_user', 'ready'];
8
9
  const LABEL = {
9
10
  accepted: 'accepted',
10
11
  enqueued: 'enqueued',
@@ -80,6 +81,7 @@ export function createWorkRuntime(store, engine, options = {}) {
80
81
  reject,
81
82
  report,
82
83
  mainHistory,
84
+ workerHistory,
83
85
  holdNotices,
84
86
  releaseHold,
85
87
  tick,
@@ -135,6 +137,76 @@ export function createWorkRuntime(store, engine, options = {}) {
135
137
  const events = await options.snapshot(ownerSessionId);
136
138
  return renderMainHistory(events);
137
139
  }
140
+ /**
141
+ * Direct read of a worker session owned by this main bot. No inbox write,
142
+ * and the worker is not notified.
143
+ * @param {string} sessionId
144
+ * @param {{ ticketId?: unknown, maxChars?: number }} [args]
145
+ */
146
+ async function workerHistory(sessionId, args = {}) {
147
+ if (!engine.isBot(sessionId))
148
+ return toolError('FORBIDDEN', 'Only the main session that owns the ticket can read the worker log.');
149
+ const requested = typeof args.ticketId === 'string' ? args.ticketId.trim() : '';
150
+ let ticket = null;
151
+ if (requested !== '') {
152
+ ticket = book.ticket(requested);
153
+ if (!ticket)
154
+ return toolError('NOT_FOUND', 'No such ticket.');
155
+ if (ticket.owner_session_id !== sessionId)
156
+ return toolError('FORBIDDEN', 'Only the main session that owns the ticket can read the worker log.');
157
+ }
158
+ else {
159
+ const rows = openTickets(sessionId);
160
+ if (rows.length === 0)
161
+ return toolError('NOT_FOUND', 'No unfinished ticket.');
162
+ if (rows.length > 1) {
163
+ return {
164
+ ok: true,
165
+ direct: true,
166
+ tickets: rows.map(row => ({ ticketId: row.id, status: row.status })),
167
+ text: '',
168
+ };
169
+ }
170
+ ticket = rows[0] ?? null;
171
+ }
172
+ if (!ticket)
173
+ return toolError('NOT_FOUND', 'No such ticket.');
174
+ const child = typeof ticket.child_session_id === 'string' ? ticket.child_session_id : '';
175
+ if (child === '') {
176
+ return {
177
+ ok: true,
178
+ direct: true,
179
+ ticketId: ticket.id,
180
+ status: ticket.status,
181
+ childSessionId: null,
182
+ text: '',
183
+ };
184
+ }
185
+ if (!options.snapshot)
186
+ return toolError('UNAVAILABLE', 'The host cannot read the worker session log.');
187
+ const events = await options.snapshot(child);
188
+ const limits = Number.isFinite(args.maxChars) ? { maxChars: args.maxChars } : undefined;
189
+ return {
190
+ ok: true,
191
+ direct: true,
192
+ ticketId: ticket.id,
193
+ status: ticket.status,
194
+ childSessionId: child,
195
+ text: renderWorkerHistory(events, limits),
196
+ };
197
+ }
198
+ /**
199
+ * @param {string} owner
200
+ */
201
+ function openTickets(owner) {
202
+ return store.db
203
+ .prepare(`
204
+ SELECT * FROM work_tickets
205
+ WHERE owner_session_id = ? AND status IN (${OPEN_TICKET_STATUSES.map(() => '?').join(',')})
206
+ ORDER BY updated_at DESC
207
+ `)
208
+ .all(owner, ...OPEN_TICKET_STATUSES);
209
+ }
138
210
  /**
139
211
  * A running slot is free when both the per-bot and global running caps have room.
140
212
  * needs_user does not occupy a running slot.