@thready-web/dsh-bot-plugin 0.1.0-beta.11 → 0.1.0-beta.13

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 (55) hide show
  1. package/README.md +20 -3
  2. package/dist/approvals.js +19 -1
  3. package/dist/canvas-compose.js +73 -0
  4. package/dist/canvas-http.js +124 -0
  5. package/dist/canvas-inspector.js +350 -0
  6. package/dist/canvas-store.js +227 -6
  7. package/dist/canvas-tools.js +199 -30
  8. package/dist/card-log.js +216 -0
  9. package/dist/context.js +5 -3
  10. package/dist/deleting.js +54 -0
  11. package/dist/desk-ledger.js +18 -0
  12. package/dist/desk.js +30 -5
  13. package/dist/http-plugin.js +2 -1
  14. package/dist/http.js +200 -4
  15. package/dist/inbox.js +24 -2
  16. package/dist/index.js +65 -13
  17. package/dist/questions.js +10 -0
  18. package/dist/runtime-registry.js +20 -0
  19. package/dist/session-delete-job.js +77 -0
  20. package/dist/session-files.js +33 -1
  21. package/dist/session-wipe.js +204 -0
  22. package/dist/store.js +46 -3
  23. package/dist/triggers.js +8 -0
  24. package/dist/work-admit.js +9 -20
  25. package/dist/work-child.js +27 -10
  26. package/dist/work-ledger.js +5 -1
  27. package/dist/work-mock.js +10 -0
  28. package/dist/work-tickets.js +5 -3
  29. package/dist/work-tools.js +11 -9
  30. package/dist/work-worker.js +240 -6
  31. package/dist/worker-handles.js +33 -0
  32. package/dist/workspace-files.js +98 -17
  33. package/package.json +6 -3
  34. package/public/assets/{SourceEditor-uu0G7jsM.js → SourceEditor-BjtoMvcX.js} +3 -3
  35. package/public/assets/{cssMode-C5DAFF5H.js → cssMode--96PQtWh.js} +1 -1
  36. package/public/assets/{freemarker2-DExNwSiZ.js → freemarker2-Bz-HlISL.js} +1 -1
  37. package/public/assets/{handlebars-BK7YAvpQ.js → handlebars-D9ScJ8AM.js} +1 -1
  38. package/public/assets/{html-CdDm_zae.js → html-Czc0jojJ.js} +1 -1
  39. package/public/assets/{htmlMode-CLdn9oa1.js → htmlMode-CCww5Z1w.js} +1 -1
  40. package/public/assets/index-DRCgKxWk.css +1 -0
  41. package/public/assets/index-ztUdW074.js +72 -0
  42. package/public/assets/{javascript-mLl83_3W.js → javascript-B-yRZSiz.js} +1 -1
  43. package/public/assets/{jsonMode-B1-bihFd.js → jsonMode-ASWsY833.js} +1 -1
  44. package/public/assets/{liquid-Cv8m0HUb.js → liquid-BGoox2vJ.js} +1 -1
  45. package/public/assets/{mdx-Q12b91rL.js → mdx-DHgvnl_U.js} +1 -1
  46. package/public/assets/{python-Kda811W0.js → python-BJvVD30_.js} +1 -1
  47. package/public/assets/{razor-CRuCpdOW.js → razor-0PwR35mu.js} +1 -1
  48. package/public/assets/{tsMode-BGHcz-M3.js → tsMode-3ETp8Gdh.js} +1 -1
  49. package/public/assets/{typescript-Db1e0DCT.js → typescript-BT0iTK6K.js} +1 -1
  50. package/public/assets/{xml-H3zzFmnd.js → xml-BTaNc_uT.js} +1 -1
  51. package/public/assets/{yaml-BQrKvmTF.js → yaml-Dr7LW3tK.js} +1 -1
  52. package/public/index.html +2 -2
  53. package/skills/ui/ui-design/SKILL.md +11 -5
  54. package/public/assets/index-BB-QDSf2.css +0 -1
  55. package/public/assets/index-CsX-_qbo.js +0 -62
@@ -19,19 +19,11 @@ const OUTPUT = {
19
19
  */
20
20
  export function workToolDefinitions(work, engine) {
21
21
  return [
22
- tool('foundations_dispatch', 'Hand a non-trivial job to a worker session. Prefer this over doing the work with bash, write, edit, or an official subagent in the main session. Available only on a bot. status=accepted means received, and may wait for an execution slot. status=enqueued means it entered the execution queue, not that it has started. queued=true means it is waiting for a slot and will start automatically when one is free. The return value is never started. A BUDGET error means both the slot cap and the queue cap are full; do not start the job in the main session. ownerSessionId is ignored.', {
22
+ tool('foundations_dispatch', `Hand a non-trivial job to a worker session. Prefer this over doing the work with bash, write, edit, or an official subagent in the main session. Available only on a bot. The host assigns the opening budget of one standard slice (${SLICE}). Do not pass a budget. status=accepted means received, and may wait for an execution slot. status=enqueued means it entered the execution queue, not that it has started. queued=true means it is waiting for a slot and will start automatically when one is free. The return value is never started. A BUDGET error means both the slot cap and the queue cap are full; do not start the job in the main session. ownerSessionId is ignored.`, {
23
23
  type: 'object',
24
24
  properties: {
25
25
  briefing: { type: 'string' },
26
26
  idempotencyKey: { type: 'string' },
27
- budget: {
28
- type: 'object',
29
- description: `Time and token budget for this ticket. When omitted, the host uses one standard slice (${SLICE}). Pass that slice. Do not estimate a smaller budget. Later grants add more slices with no cumulative ceiling.`,
30
- properties: {
31
- wallMs: { type: 'integer', description: 'Expected maximum runtime in milliseconds.' },
32
- maxTokens: { type: 'integer', description: 'Expected maximum tokens.' },
33
- },
34
- },
35
27
  correlationId: { type: 'string' },
36
28
  ownerSessionId: { type: 'string', description: 'Ignored. The host uses the current session.' },
37
29
  parentTicketId: { type: 'string', description: 'The MVP rejects a non-empty value.' },
@@ -58,6 +50,16 @@ export function workToolDefinitions(work, engine) {
58
50
  },
59
51
  required: ['text'],
60
52
  }, (args, hostId) => work.redirect(hostId, args), 'bot'),
53
+ tool('foundations_steer', 'Interrupt a running worker. The current turn stops and text is what the worker does next. Use this when the worker is on the wrong path. foundations_redirect does not stop the current turn. Old reports from the previous generation become stale.', {
54
+ type: 'object',
55
+ properties: {
56
+ text: { type: 'string', description: 'The correction. Say what to stop and what to do instead.' },
57
+ ticketId: { type: 'string' },
58
+ expectedRevision: { type: 'integer' },
59
+ ownerSessionId: { type: 'string', description: 'Ignored.' },
60
+ },
61
+ required: ['text'],
62
+ }, (args, hostId) => work.steer(hostId, args), 'bot'),
61
63
  tool('foundations_cancel', 'Cancel the ticket. Ticket notices that have not been claimed are removed from the inbox. It does not start again on its own.', {
62
64
  type: 'object',
63
65
  properties: {
@@ -1,10 +1,13 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { sha256 } from "./fs-safe.js";
3
+ import { isFenced } from "./deleting.js";
3
4
  import { toolError } from "./errors.js";
5
+ import { isCanvasWorkerBriefing } from "./canvas-tools.js";
4
6
  import { createTicketBook } from "./work-tickets.js";
5
7
  import { decideAdmission, budgetTrip, estimateWorkerBudget, DEFAULT_WORK_BUDGET, effectiveWorkLimits, } from "./work-admit.js";
6
8
  import { messageIdOf, pushInput, pushNotice, reasonKindOf, reconcileInputs, reconcileNotices, renderMainHistory, renderNotice, renderWorkerHistory, } from "./work-ledger.js";
7
9
  const KINDS = new Set(['progress', 'question', 'artifact', 'result', 'failure']);
10
+ const CONTINUE_TEXT = '[foundations:continue] You ended the turn before foundations_report. The ticket is still running. This is not a timeout. Continue the same task from the current files. Do not repeat completed writes. Finish the task, then call foundations_report. If this is a canvas preview, it is unfinished until canvas_publish succeeds; a workspace file is not the preview.';
8
11
  const OPEN_TICKET_STATUSES = ['accepted', 'enqueued', 'started', 'needs_user', 'ready'];
9
12
  const LABEL = {
10
13
  accepted: 'accepted',
@@ -65,15 +68,20 @@ export function createWorkRuntime(store, engine, options = {}) {
65
68
  return { ok: false, ambiguous: true, error: 'no-push' };
66
69
  return options.push(sessionId, messageId, text);
67
70
  },
71
+ steer: options.steer
72
+ ? async (sessionId, messageId, text) => options.steer(sessionId, messageId, text)
73
+ : undefined,
68
74
  noticeText: (nativeId) => noticeText(nativeId),
69
75
  mainHistory: (ownerSessionId) => readMainHistory(ownerSessionId),
70
76
  };
77
+ backlogCards();
71
78
  return {
72
79
  limits,
73
80
  book,
74
81
  dispatch,
75
82
  supply,
76
83
  redirect,
84
+ steer,
77
85
  cancelTicket,
78
86
  retry,
79
87
  grant,
@@ -88,6 +96,7 @@ export function createWorkRuntime(store, engine, options = {}) {
88
96
  admit,
89
97
  promoteQueued,
90
98
  observeSession,
99
+ silence,
91
100
  observeClaimed,
92
101
  gateStep,
93
102
  waitForBudget,
@@ -344,7 +353,7 @@ export function createWorkRuntime(store, engine, options = {}) {
344
353
  const started = [];
345
354
  const launched = [];
346
355
  const launch = (ticket) => {
347
- if (!ticket?.id || starting.has(ticket.id))
356
+ if (!ticket?.id || starting.has(ticket.id) || isFenced(ticket.owner_session_id))
348
357
  return;
349
358
  started.push(ticket.id);
350
359
  launched.push(startReserved(ticket).catch(error => {
@@ -359,6 +368,8 @@ export function createWorkRuntime(store, engine, options = {}) {
359
368
  for (const ticket of book.nextPromotable()) {
360
369
  if (book.slotHeld(ticket))
361
370
  continue;
371
+ if (isFenced(ticket.owner_session_id))
372
+ continue;
362
373
  if (ticket.status !== 'accepted' && ticket.status !== 'needs_user')
363
374
  continue;
364
375
  if (!hasSlot(ticket.owner_session_id))
@@ -435,20 +446,34 @@ export function createWorkRuntime(store, engine, options = {}) {
435
446
  });
436
447
  if (prepared.error)
437
448
  return prepared.error;
438
- if (prepared.replay)
439
- return publicDispatch(prepared.replay, { replayed: true });
449
+ if (prepared.replay) {
450
+ const view = publicDispatch(prepared.replay, { replayed: true });
451
+ noteWorker(owner, prepared.replay, typeof view.status === 'string' ? view.status : String(prepared.replay.status));
452
+ return view;
453
+ }
440
454
  const ticket = prepared.created.ticket;
441
455
  if (!prepared.start) {
442
- return publicDispatch(book.ticket(ticket.id), {
456
+ const view = publicDispatch(book.ticket(ticket.id), {
443
457
  flush: 'pending',
444
458
  queued: true,
445
459
  childSessionId: null,
446
460
  nativeMessageId: null,
447
461
  });
462
+ noteWorker(owner, book.ticket(ticket.id) ?? ticket, typeof view.status === 'string' ? view.status : 'accepted');
463
+ return view;
448
464
  }
449
465
  if (!resident) {
450
- return { ...publicDispatch(ticket), flush: 'pending', resident: false, message: 'Only a resident host continues' };
466
+ const view = {
467
+ ...publicDispatch(ticket),
468
+ flush: 'pending',
469
+ resident: false,
470
+ message: 'Only a resident host continues',
471
+ };
472
+ noteWorker(owner, ticket, typeof view.status === 'string' ? view.status : 'accepted');
473
+ return view;
451
474
  }
475
+ const fresh = book.ticket(ticket.id) ?? ticket;
476
+ noteWorker(owner, fresh, String(fresh.status ?? 'accepted'));
452
477
  return startReserved(ticket);
453
478
  }
454
479
  /**
@@ -465,10 +490,18 @@ export function createWorkRuntime(store, engine, options = {}) {
465
490
  async function redirect(owner, args) {
466
491
  return retarget(owner, args, 'redirect');
467
492
  }
493
+ /**
494
+ * Stop the worker's current turn, then hand it the correction.
495
+ * Cancel runs first so a later steer wakes the next turn instead of sitting
496
+ * in a turn that is about to abort.
497
+ */
498
+ async function steer(owner, args) {
499
+ return retarget(owner, args, 'steer');
500
+ }
468
501
  /**
469
502
  * @param {string} owner
470
503
  * @param {Record<string, unknown>} args
471
- * @param {'supply' | 'redirect'} kind
504
+ * @param {'supply' | 'redirect' | 'steer'} kind
472
505
  */
473
506
  async function retarget(owner, args, kind) {
474
507
  if (!engine.isBot(owner))
@@ -504,6 +537,10 @@ export function createWorkRuntime(store, engine, options = {}) {
504
537
  }
505
538
  if (!resident)
506
539
  return { ...publicDispatch(advanced.ticket), flush: 'pending', message: 'Only a resident host continues' };
540
+ const child = advanced.ticket.child_session_id;
541
+ if (kind === 'steer' && resident && child && options.cancel) {
542
+ await options.cancel(child, { keepInbox: true, reason: 'worker-steer' });
543
+ }
507
544
  const flushed = await pushInput(book, advanced.input, deps);
508
545
  return publicDispatch(book.ticket(found.ticket.id), {
509
546
  flush: flushWord(flushed),
@@ -808,10 +845,35 @@ export function createWorkRuntime(store, engine, options = {}) {
808
845
  kind,
809
846
  };
810
847
  }
848
+ function noteWorker(owner, ticket, status) {
849
+ if (!options.recordCard || typeof ticket?.id !== 'string')
850
+ return;
851
+ const text = typeof ticket.briefing_hash === 'string' ? book.readBriefing(ticket.briefing_hash) : '';
852
+ const line = text.split('\n')[0]?.trim() ?? '';
853
+ options.recordCard({
854
+ kind: 'worker',
855
+ key: ticket.id,
856
+ sessionId: owner,
857
+ payload: { ticketId: ticket.id, summary: line.slice(0, 80) || ticket.id, status },
858
+ });
859
+ }
860
+ function backlogCards() {
861
+ if (!options.recordCard)
862
+ return;
863
+ const rows = store.db.prepare('SELECT id, owner_session_id, briefing_hash, status FROM work_tickets').all();
864
+ for (const row of rows) {
865
+ if (typeof row.owner_session_id !== 'string')
866
+ continue;
867
+ noteWorker(row.owner_session_id, row, typeof row.status === 'string' ? row.status : 'accepted');
868
+ }
869
+ }
811
870
  async function tick() {
871
+ options.flushCards?.();
812
872
  await reconcileInputs(book, deps);
813
873
  await reconcileNotices(book, deps);
814
874
  await renewLiveLeases();
875
+ const quiet = await continueQuietWorkers();
876
+ await stopExpiredChildren(quiet);
815
877
  const expired = await store.write('work', () => book.expireQuiet());
816
878
  await stopExpiredChildren(expired);
817
879
  for (const owner of book.ownerIds()) {
@@ -824,6 +886,122 @@ export function createWorkRuntime(store, engine, options = {}) {
824
886
  await reconcileOwner(owner);
825
887
  await promoteQueued();
826
888
  }
889
+ async function isChildPresent(sessionId) {
890
+ if (options.childPresent) {
891
+ try {
892
+ return (await options.childPresent(sessionId)) === true;
893
+ }
894
+ catch {
895
+ return false;
896
+ }
897
+ }
898
+ return options.snapshot != null;
899
+ }
900
+ function extensionOpen(ticket) {
901
+ try {
902
+ return JSON.parse(ticket.budget_json ?? '')?.extension === 'open';
903
+ }
904
+ catch {
905
+ return false;
906
+ }
907
+ }
908
+ function hasTerminalReport(ticketId, attemptId) {
909
+ const detail = book.detail(ticketId);
910
+ return (detail?.events ?? []).some((event) => event.attempt_id === attemptId &&
911
+ (event.kind === 'result' || event.kind === 'failure' || event.kind === 'question') &&
912
+ event.apply_status !== 'stale');
913
+ }
914
+ function continueInput(ticketId) {
915
+ const rows = store.db
916
+ .prepare(`SELECT * FROM work_inputs WHERE ticket_id = ? AND kind = 'supply' ORDER BY created_at`)
917
+ .all(ticketId);
918
+ return rows.find(row => String(book.readBriefing(row.payload_hash)).startsWith('[foundations:continue]')) ?? null;
919
+ }
920
+ /**
921
+ * A completed turn with no result, question, or failure is the worker stopping
922
+ * early, not a dead process. Continue that same ticket once. A second completed
923
+ * turn with no report fails as no-report, so the main session does not describe
924
+ * a lease or heartbeat timeout. An open turn still renews through renewLiveLeases.
925
+ * A child that is gone still lease-expires.
926
+ */
927
+ async function continueQuietWorkers() {
928
+ const failed = [];
929
+ for (const child of book.childIdsForReconcile()) {
930
+ const attempt = book.attemptForChild(child);
931
+ if (!attempt || (attempt.status !== 'started' && attempt.status !== 'enqueued'))
932
+ continue;
933
+ const ticket = book.ticket(attempt.ticket_id);
934
+ if (!ticket || (ticket.status !== 'started' && ticket.status !== 'enqueued'))
935
+ continue;
936
+ if (ticket.active_attempt_id !== attempt.id)
937
+ continue;
938
+ if (extensionOpen(ticket))
939
+ continue;
940
+ if (!(await isChildPresent(child)))
941
+ continue;
942
+ let events = [];
943
+ try {
944
+ events = options.snapshot ? await options.snapshot(child) : [];
945
+ }
946
+ catch {
947
+ continue;
948
+ }
949
+ const ended = latestEndedTurn(events);
950
+ if (!ended || ended.reason !== 'completed')
951
+ continue;
952
+ if (hasTerminalReport(ticket.id, attempt.id))
953
+ continue;
954
+ const nudge = continueInput(ticket.id);
955
+ if (!nudge) {
956
+ const input = await store.write('work', () => {
957
+ const fresh = book.ticket(ticket.id);
958
+ if (!fresh || fresh.status !== 'started' || fresh.active_attempt_id !== attempt.id)
959
+ return null;
960
+ if (continueInput(fresh.id))
961
+ return null;
962
+ store.db
963
+ .prepare('UPDATE work_tickets SET revision = revision + 1, briefing_revision = briefing_revision + 1, updated_at = ? WHERE id = ?')
964
+ .run(now().toISOString(), fresh.id);
965
+ const created = book.insertInput({
966
+ ticketId: fresh.id,
967
+ attemptId: fresh.active_attempt_id,
968
+ revision: fresh.briefing_revision + 1,
969
+ kind: 'supply',
970
+ text: CONTINUE_TEXT,
971
+ });
972
+ book.touchLease(attempt.id, new Date(now().getTime() + limits.leaseMs).toISOString(), typeof attempt.lease_observed_seq === 'number' ? attempt.lease_observed_seq : null);
973
+ return created;
974
+ });
975
+ if (input)
976
+ await pushInput(book, input, deps);
977
+ continue;
978
+ }
979
+ if (nudge.flush_status !== 'accepted') {
980
+ await store.write('work', () => {
981
+ book.touchLease(attempt.id, new Date(now().getTime() + limits.leaseMs).toISOString(), typeof attempt.lease_observed_seq === 'number' ? attempt.lease_observed_seq : null);
982
+ });
983
+ continue;
984
+ }
985
+ const nudgeTurn = turnOfMessage(events, nudge.native_message_id);
986
+ if (nudgeTurn == null || !turnEnded(events, nudgeTurn)) {
987
+ await store.write('work', () => {
988
+ book.touchLease(attempt.id, new Date(now().getTime() + limits.leaseMs).toISOString(), typeof attempt.lease_observed_seq === 'number' ? attempt.lease_observed_seq : null);
989
+ });
990
+ continue;
991
+ }
992
+ const stopped = await store.write('work', () => {
993
+ const fresh = book.ticket(ticket.id);
994
+ if (!fresh || (fresh.status !== 'started' && fresh.status !== 'enqueued'))
995
+ return null;
996
+ if (hasTerminalReport(fresh.id, attempt.id))
997
+ return null;
998
+ return book.failRunning(fresh.id, 'no-report');
999
+ });
1000
+ if (stopped)
1001
+ failed.push({ ticketId: ticket.id, reason: 'no-report', childSessionId: child });
1002
+ }
1003
+ return failed;
1004
+ }
827
1005
  /**
828
1006
  * Renew the lease of a started worker that is still alive, so a silent
829
1007
  * model or tool turn longer than leaseMs does not false-expire it.
@@ -932,6 +1110,8 @@ export function createWorkRuntime(store, engine, options = {}) {
932
1110
  * @param {string} owner
933
1111
  */
934
1112
  async function admit(owner) {
1113
+ if (isFenced(owner))
1114
+ return { admitted: false, reason: 'deleting' };
935
1115
  if (admitting.has(owner))
936
1116
  return { admitted: false, reason: 'admission-inflight' };
937
1117
  admitting.add(owner);
@@ -1125,6 +1305,8 @@ export function createWorkRuntime(store, engine, options = {}) {
1125
1305
  * @param {Record<string, any>} ticket
1126
1306
  */
1127
1307
  async function ensureChild(ticket) {
1308
+ if (isFenced(ticket.owner_session_id))
1309
+ return { error: toolError('FORBIDDEN', 'This session is being deleted.') };
1128
1310
  if (ticket.child_session_id)
1129
1311
  return { ticket };
1130
1312
  if (!options.createChild)
@@ -1133,11 +1315,13 @@ export function createWorkRuntime(store, engine, options = {}) {
1133
1315
  const attemptId = ticket.active_attempt_id;
1134
1316
  const fencingToken = book.attempt(attemptId)?.fencing_token ?? 1;
1135
1317
  try {
1318
+ const briefing = typeof ticket.briefing_hash === 'string' ? book.readBriefing(ticket.briefing_hash) : '';
1136
1319
  const created = await options.createChild({
1137
1320
  sessionId,
1138
1321
  ownerSessionId: ticket.owner_session_id,
1139
1322
  ticketId: ticket.id,
1140
1323
  fencingToken,
1324
+ canvas: isCanvasWorkerBriefing(briefing),
1141
1325
  });
1142
1326
  const child = typeof created === 'string' && created !== '' ? created : sessionId;
1143
1327
  const saved = await store.write('work', () => book.setChildIfEmpty(ticket.id, child, { attemptId, fencingToken }));
@@ -1884,6 +2068,15 @@ export function createWorkRuntime(store, engine, options = {}) {
1884
2068
  /**
1885
2069
  * @param {string} sessionId
1886
2070
  */
2071
+ function silence(sessionId) {
2072
+ holds.delete(sessionId);
2073
+ const waiters = budgetWaiters.get(sessionId);
2074
+ if (waiters) {
2075
+ for (const done of [...waiters])
2076
+ done(false);
2077
+ }
2078
+ clearBudget(sessionId);
2079
+ }
1887
2080
  function clearBudget(sessionId) {
1888
2081
  const state = arms.get(sessionId);
1889
2082
  if (state?.role === 'worker')
@@ -1899,6 +2092,47 @@ export function createWorkRuntime(store, engine, options = {}) {
1899
2092
  * No turn at all, or an open turn, means it may still be running.
1900
2093
  * @param {Array<Record<string, any>>} events
1901
2094
  */
2095
+ function latestEndedTurn(events) {
2096
+ const open = new Set();
2097
+ const reason = new Map();
2098
+ let sawTurn = false;
2099
+ for (const event of events) {
2100
+ const turn = event.data?.turn;
2101
+ if (typeof turn !== 'number')
2102
+ continue;
2103
+ if (event.type === 'turn/start' || event.type === 'user/message') {
2104
+ sawTurn = true;
2105
+ open.add(turn);
2106
+ }
2107
+ else if (event.type === 'turn/end') {
2108
+ sawTurn = true;
2109
+ open.delete(turn);
2110
+ reason.set(turn, reasonKindOf(event));
2111
+ }
2112
+ }
2113
+ if (!sawTurn || open.size > 0)
2114
+ return null;
2115
+ let last = -1;
2116
+ let kind = '';
2117
+ for (const [turn, value] of reason) {
2118
+ if (turn >= last) {
2119
+ last = turn;
2120
+ kind = value;
2121
+ }
2122
+ }
2123
+ return last < 0 ? null : { turn: last, reason: kind };
2124
+ }
2125
+ function turnOfMessage(events, messageId) {
2126
+ for (const event of events) {
2127
+ if (event.type !== 'user/message' || messageIdOf(event) !== messageId)
2128
+ continue;
2129
+ return typeof event.data?.turn === 'number' ? event.data.turn : null;
2130
+ }
2131
+ return null;
2132
+ }
2133
+ function turnEnded(events, turn) {
2134
+ return events.some(event => event.type === 'turn/end' && event.data?.turn === turn);
2135
+ }
1902
2136
  function latestTurnEnded(events) {
1903
2137
  const open = new Set();
1904
2138
  let sawTurn = false;
@@ -0,0 +1,33 @@
1
+ /** Child-agent handles that must survive a plugin reload.
2
+
3
+ DSH HMR evicts a changed plugin module and the modules that import it. This
4
+ module stays in the ESM cache when only the plugin entry changes, so the next
5
+ `apply` still sees the agents the host kept alive. Fiber unload must not
6
+ dispose them: the next tick would treat a live worker as gone. Session delete
7
+ forgets a handle and disposes that agent.
8
+ */
9
+ const handles = new Map();
10
+ export function rememberWorker(sessionId, handle) {
11
+ if (sessionId !== '')
12
+ handles.set(sessionId, handle);
13
+ }
14
+ export function workerHandle(sessionId) {
15
+ return handles.get(sessionId);
16
+ }
17
+ /** Unload keeps every handle. Hot reload publishes a new runtime over the same agents. */
18
+ export function retainWorkers() {
19
+ return [...handles.keys()];
20
+ }
21
+ /** Session delete drops one agent. Other handles stay. */
22
+ export async function forgetWorker(sessionId) {
23
+ const handle = handles.get(sessionId);
24
+ handles.delete(sessionId);
25
+ if (!handle?.dispose)
26
+ return;
27
+ try {
28
+ await handle.dispose();
29
+ }
30
+ catch {
31
+ /* already closed */
32
+ }
33
+ }
@@ -1,24 +1,51 @@
1
- /** Workbench file browser. Workspace and the process home are readable. DSH_HOME stays closed. */
1
+ /**
2
+ * Workbench file browser. Workspace and a separate home directory are readable.
3
+ * DSH_HOME, the filesystem root, and /etc stay closed.
4
+ */
2
5
  import { randomBytes } from 'node:crypto';
3
6
  import { closeSync, constants, createReadStream, createWriteStream, fstatSync, lstatSync, openSync, readdirSync, readSync, realpathSync, renameSync, unlinkSync, } from 'node:fs';
7
+ import { homedir } from 'node:os';
4
8
  import { basename, join, resolve, sep } from 'node:path';
9
+ /** Explicit file-drawer home. Independent of process HOME. */
10
+ export const FILES_HOME_ENV = 'THREADY_FILES_HOME';
5
11
  export const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
6
12
  export const MAX_TEXT_BYTES = 1024 * 1024;
13
+ /**
14
+ * Candidate home directory. A non-empty plugin config wins over THREADY_FILES_HOME,
15
+ * which wins over HOME. A non-string config selects nothing, so it is not replaced
16
+ * by HOME or the environment. This does not write the process environment.
17
+ */
18
+ export function selectBrowserHome(env, configured) {
19
+ if (configured != null && typeof configured !== 'string')
20
+ return '';
21
+ if (typeof configured === 'string' && configured.trim() !== '')
22
+ return configured.trim();
23
+ const fromEnv = env[FILES_HOME_ENV];
24
+ if (typeof fromEnv === 'string' && fromEnv.trim() !== '')
25
+ return fromEnv.trim();
26
+ const home = typeof env.HOME === 'string' ? env.HOME.trim() : '';
27
+ if (home !== '')
28
+ return home;
29
+ return homedir();
30
+ }
7
31
  /**
8
32
  * Real paths the browser may use. A workspace that is DSH_HOME, or that contains it, is unusable.
9
33
  * The workspace directory itself stays allowed when it lives at <DSH_HOME>/workspace.
34
+ * `legacyWorkspace` is used only when the stored cwd is exactly DSH_HOME. Any other overlap stays closed.
10
35
  */
11
36
  export function resolveFileRoots(input) {
12
- const home = realDir(input.home);
13
- const dshHome = realDir(input.dshHome);
14
- const workspaceRaw = realDir(input.workspace);
15
- let workspace = workspaceRaw;
16
- let workspaceReason = workspaceRaw ? '' : 'missing';
17
- if (workspaceRaw && dshHome && (workspaceRaw === dshHome || inside(workspaceRaw, dshHome))) {
18
- workspace = null;
19
- workspaceReason = 'overlap';
20
- }
21
- return { roots: { workspace, workspaceReason, home }, dshHome };
37
+ const dshHome = realDirectory(input.dshHome).path;
38
+ const home = resolveHome(input.home, dshHome);
39
+ const workspace = resolveWorkspace(input.workspace, dshHome, input.legacyWorkspace);
40
+ return {
41
+ roots: {
42
+ workspace: workspace.workspace,
43
+ workspaceReason: workspace.workspaceReason,
44
+ home: home.home,
45
+ homeReason: home.homeReason,
46
+ },
47
+ dshHome,
48
+ };
22
49
  }
23
50
  export function listDirectory(filePath, access) {
24
51
  const located = locate(filePath, access);
@@ -172,18 +199,72 @@ export function safeFileName(value) {
172
199
  return null;
173
200
  return value;
174
201
  }
175
- function realDir(filePath) {
176
- if (filePath.trim() === '')
177
- return null;
202
+ function resolveHome(candidate, dshHome) {
203
+ const found = realDirectory(candidate);
204
+ if (!found.path)
205
+ return { home: null, homeReason: found.reason === 'invalid' ? 'invalid' : 'missing' };
206
+ if (isForbiddenLocation(found.path) || (dshHome != null && inside(dshHome, found.path))) {
207
+ return { home: null, homeReason: 'forbidden' };
208
+ }
209
+ return { home: found.path, homeReason: '' };
210
+ }
211
+ /**
212
+ * A stored cwd of exactly DSH_HOME can fall back to the configured session workspace.
213
+ * A cwd that merely contains DSH_HOME, or that is `/` or `/etc`, cannot.
214
+ */
215
+ function resolveWorkspace(candidate, dshHome, legacy) {
216
+ const found = realDirectory(candidate);
217
+ if (!found.path)
218
+ return { workspace: null, workspaceReason: 'missing' };
219
+ if (dshHome != null && found.path === dshHome) {
220
+ const fallback = legacy ? realDirectory(legacy).path : null;
221
+ if (fallback != null && fallback !== found.path && safeWorkspace(fallback, dshHome)) {
222
+ return { workspace: fallback, workspaceReason: '' };
223
+ }
224
+ return { workspace: null, workspaceReason: 'overlap' };
225
+ }
226
+ if (isForbiddenLocation(found.path))
227
+ return { workspace: null, workspaceReason: 'forbidden' };
228
+ if (dshHome != null && inside(found.path, dshHome))
229
+ return { workspace: null, workspaceReason: 'overlap' };
230
+ return { workspace: found.path, workspaceReason: '' };
231
+ }
232
+ function safeWorkspace(root, dshHome) {
233
+ if (isForbiddenLocation(root))
234
+ return false;
235
+ if (dshHome != null && (root === dshHome || inside(root, dshHome)))
236
+ return false;
237
+ return true;
238
+ }
239
+ function realDirectory(filePath) {
240
+ if (filePath.trim() === '' || filePath.includes('\0'))
241
+ return { path: null, reason: 'missing' };
242
+ let real;
178
243
  try {
179
- return realpathSync(resolve(filePath));
244
+ real = realpathSync(resolve(filePath));
180
245
  }
181
246
  catch {
182
- return null;
247
+ return { path: null, reason: 'missing' };
183
248
  }
249
+ try {
250
+ if (!lstatSync(real).isDirectory())
251
+ return { path: null, reason: 'invalid' };
252
+ }
253
+ catch {
254
+ return { path: null, reason: 'missing' };
255
+ }
256
+ return { path: real, reason: '' };
257
+ }
258
+ function isForbiddenLocation(filePath) {
259
+ if (filePath === sep)
260
+ return true;
261
+ const etc = `${sep}etc`;
262
+ return filePath === etc || filePath.startsWith(`${etc}${sep}`);
184
263
  }
185
264
  function inside(root, target) {
186
- return target === root || target.startsWith(root + sep);
265
+ if (root === sep)
266
+ return target.startsWith(sep);
267
+ return target === root || target.startsWith(`${root}${sep}`);
187
268
  }
188
269
  function rootOf(filePath, access) {
189
270
  const inWorkspace = access.roots.workspace != null && inside(access.roots.workspace, filePath);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thready-web/dsh-bot-plugin",
3
- "version": "0.1.0-beta.11",
3
+ "version": "0.1.0-beta.13",
4
4
  "type": "module",
5
5
  "description": "DSH bot plugin: session persona, memory, work, hash routing, and the workbench. Pinned to @deepseek-ai/dsh 0.2.2-rc.1.",
6
6
  "license": "MIT",
@@ -31,6 +31,7 @@
31
31
  },
32
32
  "scripts": {
33
33
  "build": "node build.mjs",
34
+ "verify:publish": "node scripts/verify-publish.mjs",
34
35
  "type-check": "tsc -p tsconfig.typecheck.json --noEmit && tsc -p tsconfig.client.json --noEmit",
35
36
  "test": "node scripts/unit-tests.mjs",
36
37
  "test:host": "npm run build && node --test test/host-integration.test.ts && node --test test/triggers-host.test.ts && node --test test/budget-host.test.ts && node --test test/activity-host.test.ts && node --test test/work-host.test.ts && node --test test/work-bash-host.test.ts",
@@ -41,16 +42,18 @@
41
42
  "node": ">=22.18.0",
42
43
  "dsh": ">=0.2.2-rc.1 <0.2.3-0"
43
44
  },
45
+ "dependencies": {
46
+ "@deepseek-ai/dsh-session": "^0.2.2-rc.1",
47
+ "linkedom": "^0.18.15"
48
+ },
44
49
  "devDependencies": {
45
50
  "@biomejs/biome": "^2.6.6",
46
51
  "@deepseek-ai/cordis": "~4.1.0",
47
52
  "@deepseek-ai/dsh-api-session-controller": "^0.2.2-rc.1",
48
53
  "@deepseek-ai/dsh-client-connection": "^0.2.2-rc.1",
49
- "@deepseek-ai/dsh-session": "^0.2.2-rc.1",
50
54
  "@deepseek-ai/dsh-session-query": "^0.2.2-rc.1",
51
55
  "@types/node": "^24.10.0",
52
56
  "esbuild": "^0.25.0",
53
- "linkedom": "^0.18.15",
54
57
  "typescript": "^5.9.3"
55
58
  },
56
59
  "dsh": {