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

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 (54) hide show
  1. package/README.md +19 -2
  2. package/dist/approvals.js +19 -1
  3. package/dist/canvas-compose.js +73 -0
  4. package/dist/canvas-http.js +131 -0
  5. package/dist/canvas-store.js +227 -6
  6. package/dist/canvas-tools.js +199 -30
  7. package/dist/card-log.js +216 -0
  8. package/dist/context.js +5 -3
  9. package/dist/deleting.js +54 -0
  10. package/dist/desk-ledger.js +18 -0
  11. package/dist/desk.js +30 -5
  12. package/dist/http-plugin.js +2 -1
  13. package/dist/http.js +200 -4
  14. package/dist/inbox.js +24 -2
  15. package/dist/index.js +65 -13
  16. package/dist/questions.js +10 -0
  17. package/dist/runtime-registry.js +20 -0
  18. package/dist/session-delete-job.js +77 -0
  19. package/dist/session-files.js +33 -1
  20. package/dist/session-wipe.js +204 -0
  21. package/dist/store.js +46 -3
  22. package/dist/triggers.js +8 -0
  23. package/dist/work-admit.js +9 -20
  24. package/dist/work-child.js +27 -10
  25. package/dist/work-ledger.js +5 -1
  26. package/dist/work-mock.js +10 -0
  27. package/dist/work-tickets.js +5 -3
  28. package/dist/work-tools.js +11 -9
  29. package/dist/work-worker.js +240 -6
  30. package/dist/worker-handles.js +33 -0
  31. package/dist/workspace-files.js +98 -17
  32. package/package.json +1 -1
  33. package/public/assets/{SourceEditor-uu0G7jsM.js → SourceEditor-BjtoMvcX.js} +3 -3
  34. package/public/assets/{cssMode-C5DAFF5H.js → cssMode--96PQtWh.js} +1 -1
  35. package/public/assets/{freemarker2-DExNwSiZ.js → freemarker2-Bz-HlISL.js} +1 -1
  36. package/public/assets/{handlebars-BK7YAvpQ.js → handlebars-D9ScJ8AM.js} +1 -1
  37. package/public/assets/{html-CdDm_zae.js → html-Czc0jojJ.js} +1 -1
  38. package/public/assets/{htmlMode-CLdn9oa1.js → htmlMode-CCww5Z1w.js} +1 -1
  39. package/public/assets/index-DRCgKxWk.css +1 -0
  40. package/public/assets/index-ztUdW074.js +72 -0
  41. package/public/assets/{javascript-mLl83_3W.js → javascript-B-yRZSiz.js} +1 -1
  42. package/public/assets/{jsonMode-B1-bihFd.js → jsonMode-ASWsY833.js} +1 -1
  43. package/public/assets/{liquid-Cv8m0HUb.js → liquid-BGoox2vJ.js} +1 -1
  44. package/public/assets/{mdx-Q12b91rL.js → mdx-DHgvnl_U.js} +1 -1
  45. package/public/assets/{python-Kda811W0.js → python-BJvVD30_.js} +1 -1
  46. package/public/assets/{razor-CRuCpdOW.js → razor-0PwR35mu.js} +1 -1
  47. package/public/assets/{tsMode-BGHcz-M3.js → tsMode-3ETp8Gdh.js} +1 -1
  48. package/public/assets/{typescript-Db1e0DCT.js → typescript-BT0iTK6K.js} +1 -1
  49. package/public/assets/{xml-H3zzFmnd.js → xml-BTaNc_uT.js} +1 -1
  50. package/public/assets/{yaml-BQrKvmTF.js → yaml-Dr7LW3tK.js} +1 -1
  51. package/public/index.html +2 -2
  52. package/skills/ui/ui-design/SKILL.md +11 -5
  53. package/public/assets/index-BB-QDSf2.css +0 -1
  54. package/public/assets/index-CsX-_qbo.js +0 -62
@@ -80,6 +80,24 @@ export function openLedger(file) {
80
80
  tasks() {
81
81
  return tasksOf().sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
82
82
  },
83
+ /** Drop idempotency rows and tasks that point at one deleted session. */
84
+ forgetSession(sessionId) {
85
+ let changed = false;
86
+ for (const [key, record] of Object.entries(state.sessions)) {
87
+ if (record.sessionId !== sessionId)
88
+ continue;
89
+ delete state.sessions[key];
90
+ changed = true;
91
+ }
92
+ for (const [key, record] of Object.entries(state.tasks)) {
93
+ if (record.sessionId !== sessionId)
94
+ continue;
95
+ delete state.tasks[key];
96
+ changed = true;
97
+ }
98
+ if (changed)
99
+ save();
100
+ },
83
101
  };
84
102
  }
85
103
  /**
package/dist/desk.js CHANGED
@@ -1,12 +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';
4
3
  import { dirname, join, resolve } from 'node:path';
5
4
  import { Readable } from 'node:stream';
6
5
  import { openLedger, validIdempotencyKey } from "./desk-ledger.js";
7
6
  import { openSessionPreviews } from "./session-previews.js";
7
+ import { isFenced } from "./deleting.js";
8
8
  import { purgeSessionFiles, sessionDirectory, writeBotMarker } from "./session-files.js";
9
- import { MAX_UPLOAD_BYTES, listDirectory, openDownload, readFileText, resolveFileRoots, saveUploadFile, } from "./workspace-files.js";
9
+ import { MAX_UPLOAD_BYTES, listDirectory, openDownload, readFileText, resolveFileRoots, saveUploadFile, selectBrowserHome, } from "./workspace-files.js";
10
10
  /**
11
11
  * Working directory for workbench-created sessions. THREADY_SESSION_CWD wins;
12
12
  * otherwise <DSH_HOME>/workspace, so the model does not start inside DSH_HOME
@@ -48,7 +48,7 @@ const SECRET_KEY = /token|secret|password|authorization|api[-_]?key|cookie/i;
48
48
  * @param {(sessionId: string) => boolean} [options.stillAttached]
49
49
  * @param {(endpoint: string, args: Record<string, unknown>, req: DeskRequest) => Promise<{ status: number, body: RpcEnvelope }>} options.rpc
50
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.
51
+ * @param {{ home: string, dshHome: string }} [options.files] Browser roots. Home is an explicit safe directory, not process HOME. DSH_HOME stays closed.
52
52
  */
53
53
  export function createDesk(options) {
54
54
  const ledger = openLedger(options.ledgerFile);
@@ -139,6 +139,12 @@ export function createDesk(options) {
139
139
  saveUpload(req, url) {
140
140
  return uploadFile(req, url.searchParams.get('sessionId') ?? '', url.searchParams.get('dir') ?? '', url.searchParams.get('name') ?? '', url.searchParams.get('overwrite') === '1');
141
141
  },
142
+ forgetSessions(sessionIds) {
143
+ for (const sessionId of sessionIds) {
144
+ sessionPreviews.forget(sessionId);
145
+ ledger.forgetSession(sessionId);
146
+ }
147
+ },
142
148
  };
143
149
  /**
144
150
  * @param {DeskRequest} req
@@ -508,8 +514,18 @@ export function createDesk(options) {
508
514
  const cwd = await workspaceCwd(req, sessionId);
509
515
  if (typeof cwd !== 'string')
510
516
  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 }) };
517
+ const files = options.files ?? {
518
+ home: selectBrowserHome(process.env, undefined),
519
+ dshHome: process.env.DSH_HOME ?? '',
520
+ };
521
+ return {
522
+ access: resolveFileRoots({
523
+ workspace: cwd,
524
+ home: files.home,
525
+ dshHome: files.dshHome,
526
+ legacyWorkspace: options.sessionCwd,
527
+ }),
528
+ };
513
529
  }
514
530
  /**
515
531
  * @param {DeskRequest} req
@@ -626,6 +642,15 @@ export function createDesk(options) {
626
642
  * @param {string} requestId
627
643
  */
628
644
  async function deliverPrompt(req, sessionId, text, requestId) {
645
+ if (isFenced(sessionId)) {
646
+ return {
647
+ ok: false,
648
+ status: 409,
649
+ error: 'deleting',
650
+ reason: 'This session is being deleted.',
651
+ upstreamCode: '',
652
+ };
653
+ }
629
654
  const running = await sessionRunning(req, sessionId);
630
655
  if (running === null) {
631
656
  return {
@@ -13,7 +13,7 @@ export const inject = ['webServer', 'agents', 'sessionPersistence', 'sessionQuer
13
13
  * Local management routes for the same SQLite the main plugin uses.
14
14
  * Loaded only on profiles that have a web server, so headless does not need it.
15
15
  * @param {import('@deepseek-ai/cordis').Context} ctx
16
- * @param {{ dataDir?: string }} [config]
16
+ * @param {{ dataDir?: string, files?: { home?: unknown } }} [config]
17
17
  */
18
18
  export function apply(ctx, config = {}) {
19
19
  const dataDir = config.dataDir ?? (ctx.profileContext?.dir ? join(ctx.profileContext.dir, 'session-foundations') : '');
@@ -39,5 +39,6 @@ export function apply(ctx, config = {}) {
39
39
  registerHttp(ctx, engine, () => runtimeFor(key) ?? runtimeFor(dataDir), () => workRuntimeFor(key) ?? workRuntimeFor(dataDir), dataDir, () => questionAnswererFor(key) ?? questionAnswererFor(dataDir), {
40
40
  getApprovals: () => approvalAnswererFor(key) ?? approvalAnswererFor(dataDir),
41
41
  getAuthorization: () => authorizationFor(key) ?? authorizationFor(dataDir),
42
+ filesHome: config.files?.home,
42
43
  });
43
44
  }
package/dist/http.js CHANGED
@@ -1,9 +1,14 @@
1
1
  import { createReadStream, statSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
- import { dirname, extname, join, resolve, sep } from 'node:path';
2
+ import { request as httpRequest } from 'node:http';
3
+ import { connect as connectSocket } from 'node:net';
4
+ import { dirname, extname, isAbsolute, join, resolve, sep } from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
6
+ import { beginDelete, deleteStatus } from "./deleting.js";
5
7
  import { createDesk, defaultSessionCwd } from "./desk.js";
8
+ import { dropSessions } from "./runtime-registry.js";
9
+ import { executeDelete } from "./session-delete-job.js";
6
10
  import { serveWorkspaceImage } from "./workspace-image.js";
11
+ import { selectBrowserHome } from "./workspace-files.js";
7
12
  import { toolError } from "./errors.js";
8
13
  import { permissionView, setPermission } from "./permissions.js";
9
14
  import { cuaAction, cuaSnapshot } from "./cua-access.js";
@@ -14,8 +19,9 @@ import { createLogSource } from "./log/source.js";
14
19
  import { createLogSnapshotService } from "./log/snapshot-service.js";
15
20
  import { dispatchLogRequest, probeConnection, registerLogRoutes } from "./log/routes.js";
16
21
  import { handleMemoryRoute } from "./memory-catalog.js";
17
- import { handleCanvasApi, serveCanvasMedia } from "./canvas-http.js";
22
+ import { handleCanvasApi, serveCanvasInspect, serveCanvasMedia } from "./canvas-http.js";
18
23
  import { openCanvasStore } from "./canvas-store.js";
24
+ import { bindCanvasCards } from "./card-log.js";
19
25
  /**
20
26
  * Local management routes. Model tools cannot confirm a persona or change revocation.
21
27
  * @param {import('@deepseek-ai/cordis').Context} ctx
@@ -30,6 +36,8 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
30
36
  const storeDir = dataDir || (ctx.profileContext?.dir ? join(ctx.profileContext.dir, 'session-foundations') : '');
31
37
  const profileDir = ctx.profileContext?.dir || (storeDir !== '' ? dirname(storeDir) : '');
32
38
  const canvas = storeDir === '' ? null : openCanvasStore(join(storeDir, 'canvas.sqlite'));
39
+ if (canvas && storeDir !== '')
40
+ bindCanvasCards(canvas, ctx, storeDir);
33
41
  const logService = createLogSnapshotService(createLogSource(ctx));
34
42
  const logOnConnection = registerLogRoutes(ctx, logService);
35
43
  const persistence = ctx.sessionPersistence;
@@ -54,7 +62,10 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
54
62
  stillAttached: sessionId => attachedSession(ctx, sessionId),
55
63
  rpc: (endpoint, args, req) => hostRpc(req, endpoint, args),
56
64
  usage: req => hostUsage(req),
57
- files: { home: homedir(), dshHome: process.env.DSH_HOME ?? '' },
65
+ files: {
66
+ home: selectBrowserHome(process.env, extras.filesHome),
67
+ dshHome: process.env.DSH_HOME ?? '',
68
+ },
58
69
  });
59
70
  /**
60
71
  * @param {import('node:http').IncomingMessage} req
@@ -91,11 +102,48 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
91
102
  },
92
103
  };
93
104
  }
105
+ const stateRoot = sessionsRoot !== '' ? dirname(sessionsRoot) : '';
106
+ function sessionDeleteRoute(res, req, ownerId, statusOnly) {
107
+ if (statusOnly)
108
+ return send(res, 200, deleteStatus(ownerId) ?? { phase: 'absent', percent: 0 });
109
+ const job = beginDelete(ownerId, publish => executeDelete({
110
+ store: engine.store,
111
+ canvas,
112
+ sessionsRoot,
113
+ stateRoot,
114
+ running: sessionId => sessionListedRunning(req, sessionId),
115
+ stop: sessionId => stopForDelete(ctx, sessionId),
116
+ silence: sessionId => {
117
+ getWork()?.silence(sessionId);
118
+ },
119
+ cancelQuestions: sessionId => {
120
+ getQuestions()?.cancelSession(sessionId);
121
+ },
122
+ abandonApprovals: sessionId => {
123
+ getApprovals()?.abandonSession(sessionId);
124
+ },
125
+ forgetDesk: sessionIds => {
126
+ desk?.forgetSessions(sessionIds);
127
+ },
128
+ dropMemory: sessionIds => {
129
+ for (const sessionId of sessionIds) {
130
+ engine.openViews.delete(sessionId);
131
+ engine.surface.delete(sessionId);
132
+ }
133
+ dropSessions(engine.store.root, sessionIds);
134
+ },
135
+ }, ownerId, publish));
136
+ writeDeleteStream(res, job);
137
+ }
94
138
  const handler = async (req, res) => {
95
139
  const requestTarget = req.url ?? '/';
96
140
  if ((requestTarget.split('?')[0] ?? '').startsWith('/dsh-bot/canvas-media/')) {
97
141
  return serveCanvasMedia(req, res, requestTarget, canvas);
98
142
  }
143
+ if ((requestTarget.split('?')[0] ?? '') === '/dsh-bot/canvas-inspector.js' ||
144
+ (requestTarget.split('?')[0] ?? '').startsWith('/dsh-bot/canvas-inspect/')) {
145
+ return serveCanvasInspect(req, res, requestTarget, canvas);
146
+ }
99
147
  const rejection = reject(ctx, req);
100
148
  if (rejection)
101
149
  return send(res, rejection, { ok: false, code: 'FORBIDDEN' });
@@ -107,6 +155,8 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
107
155
  return sendFetchResponse(res, response);
108
156
  }
109
157
  if (rawPath === '/dsh-bot' || (rawPath.startsWith('/dsh-bot/') && !rawPath.startsWith('/dsh-bot/api'))) {
158
+ if (await proxyDevUi(req, res))
159
+ return;
110
160
  if (serveDesk(req, res, rawPath))
111
161
  return;
112
162
  if (serveWorkspaceImage(req, res, rawPath, defaultSessionCwd(process.env, { mkdir: false })))
@@ -127,6 +177,10 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
127
177
  res.on('finish', () => req.destroy());
128
178
  return;
129
179
  }
180
+ const sessionDelete = path.match(/^\/session-foundations\/api\/sessions\/(session-[A-Za-z0-9-]+)\/delete$/);
181
+ if (sessionDelete && (req.method === 'GET' || req.method === 'POST')) {
182
+ return sessionDeleteRoute(res, req, sessionDelete[1], req.method === 'GET');
183
+ }
130
184
  if (desk && desk.owns(req.method ?? 'GET', path)) {
131
185
  const outcome = await desk.handle(req.method ?? 'GET', path, url, req);
132
186
  return send(res, outcome.status, outcome.body);
@@ -475,6 +529,18 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
475
529
  path: '/api/dsh-bot',
476
530
  handler,
477
531
  });
532
+ const disposeUpgrade = devUiSocket() && typeof webServer.registerUpgrade === 'function'
533
+ ? webServer.registerUpgrade({
534
+ path: '/dsh-bot/',
535
+ handler: (req, socket, head) => {
536
+ if (reject(ctx, req)) {
537
+ socket.destroy();
538
+ return;
539
+ }
540
+ proxyDevUpgrade(req, socket, head);
541
+ },
542
+ })
543
+ : null;
478
544
  return () => {
479
545
  if (typeof disposeFoundations === 'function')
480
546
  disposeFoundations();
@@ -482,6 +548,8 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
482
548
  disposeDesk();
483
549
  if (typeof disposeLog === 'function')
484
550
  disposeLog();
551
+ if (typeof disposeUpgrade === 'function')
552
+ disposeUpgrade();
485
553
  try {
486
554
  canvas?.close();
487
555
  }
@@ -744,6 +812,58 @@ function readJson(req) {
744
812
  * @param {string} endpoint
745
813
  * @param {Record<string, unknown>} args
746
814
  */
815
+ async function sessionListedRunning(req, sessionId) {
816
+ const listed = await hostRpc(req, 'session/list', { _request: {} });
817
+ const items = listed.body?.result?.value?.items;
818
+ if (listed.body?.result?.ok !== true || !Array.isArray(items))
819
+ return null;
820
+ const item = items.find((entry) => entry?.sessionId === sessionId);
821
+ if (!item)
822
+ return false;
823
+ return item.running === true;
824
+ }
825
+ async function stopForDelete(ctx, sessionId) {
826
+ let timer;
827
+ const stopped = await Promise.race([
828
+ unloadAttachedSession(ctx, sessionId).then(() => true, () => true),
829
+ new Promise(resolve => {
830
+ timer = setTimeout(() => resolve(false), 15_000);
831
+ }),
832
+ ]);
833
+ clearTimeout(timer);
834
+ return stopped;
835
+ }
836
+ function writeDeleteStream(res, job) {
837
+ res.writeHead(200, {
838
+ 'content-type': 'application/x-ndjson; charset=utf-8',
839
+ 'cache-control': 'no-store',
840
+ });
841
+ let finished = false;
842
+ const write = (event) => {
843
+ if (finished || res.writableEnded)
844
+ return;
845
+ res.write(`${JSON.stringify(event)}\n`);
846
+ };
847
+ const finish = () => {
848
+ if (finished)
849
+ return;
850
+ finished = true;
851
+ job.unlisten(listener);
852
+ if (!res.writableEnded)
853
+ res.end();
854
+ };
855
+ const listener = (event) => {
856
+ write(event);
857
+ if (event.phase === 'done' || event.phase === 'error')
858
+ finish();
859
+ };
860
+ job.listen(listener);
861
+ write(job.latest);
862
+ res.on('close', () => {
863
+ job.unlisten(listener);
864
+ });
865
+ void job.promise.finally(finish);
866
+ }
747
867
  async function hostRpc(req, endpoint, args) {
748
868
  const origin = localOrigin(req);
749
869
  const cookie = header(req, 'cookie') ?? '';
@@ -847,6 +967,82 @@ const DESK_TYPES = new Map([
847
967
  ['.woff2', 'font/woff2'],
848
968
  ['.ttf', 'font/ttf'],
849
969
  ]);
970
+ /**
971
+ * Absolute Unix socket where the dev Vite server listens.
972
+ * Unset in production, where `/dsh-bot/` is read from `public/`.
973
+ */
974
+ export function devUiSocket() {
975
+ const raw = process.env.DSH_BOT_UI_DEV;
976
+ if (!raw || !isAbsolute(raw))
977
+ return null;
978
+ return raw;
979
+ }
980
+ /**
981
+ * Forward one workbench document or asset to the Vite socket.
982
+ * A connection failure returns false so the caller can serve `public/`.
983
+ */
984
+ export function proxyDevUi(req, res) {
985
+ const socketPath = devUiSocket();
986
+ if (!socketPath)
987
+ return Promise.resolve(false);
988
+ return new Promise(resolvePromise => {
989
+ let settled = false;
990
+ const finish = (proxied) => {
991
+ if (settled)
992
+ return;
993
+ settled = true;
994
+ resolvePromise(proxied);
995
+ };
996
+ const headers = { ...req.headers };
997
+ delete headers.connection;
998
+ delete headers['transfer-encoding'];
999
+ const proxy = httpRequest({
1000
+ socketPath,
1001
+ method: req.method,
1002
+ path: req.url,
1003
+ headers,
1004
+ }, upstream => {
1005
+ res.writeHead(upstream.statusCode ?? 502, upstream.headers);
1006
+ upstream.pipe(res);
1007
+ finish(true);
1008
+ });
1009
+ proxy.on('error', () => {
1010
+ proxy.destroy();
1011
+ finish(false);
1012
+ });
1013
+ req.pipe(proxy);
1014
+ });
1015
+ }
1016
+ /** Forward the workbench hot-reload upgrade to the Vite socket. */
1017
+ export function proxyDevUpgrade(req, socket, head) {
1018
+ const socketPath = devUiSocket();
1019
+ if (!socketPath) {
1020
+ socket.destroy();
1021
+ return;
1022
+ }
1023
+ const upstream = connectSocket(socketPath);
1024
+ const fail = () => {
1025
+ upstream.destroy();
1026
+ socket.destroy();
1027
+ };
1028
+ upstream.on('error', fail);
1029
+ socket.on('error', () => upstream.destroy());
1030
+ upstream.once('connect', () => {
1031
+ const lines = [`${req.method ?? 'GET'} ${req.url ?? '/'} HTTP/1.1`];
1032
+ for (const [key, value] of Object.entries(req.headers)) {
1033
+ if (value == null || key === 'transfer-encoding')
1034
+ continue;
1035
+ const items = Array.isArray(value) ? value : [value];
1036
+ for (const item of items)
1037
+ lines.push(`${key}: ${item}`);
1038
+ }
1039
+ upstream.write(`${lines.join('\r\n')}\r\n\r\n`);
1040
+ if (head.length > 0)
1041
+ upstream.write(head);
1042
+ upstream.pipe(socket);
1043
+ socket.pipe(upstream);
1044
+ });
1045
+ }
850
1046
  /** Workbench files built into public/. API routes are handled before this. */
851
1047
  function serveDesk(req, res, pathname) {
852
1048
  if (req.method !== 'GET' && req.method !== 'HEAD')
package/dist/inbox.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * agent.followup(), which appends agent/inbox/spliced and wakes a later turn.
4
4
  * This module does not keep a second execution queue.
5
5
  */
6
+ import { isFenced } from "./deleting.js";
6
7
  import { createLogSource, logHasMessage as eventsHaveMessage, spliceSeq as seqOfSplice, } from "./log/source.js";
7
8
  import { workerFileSetup } from "./work-child.js";
8
9
  const handles = new Map();
@@ -92,10 +93,31 @@ export async function followupDurable(ctx, sessionId, messageId, text) {
92
93
  loaded.agent.followup(userMessage(messageId, text));
93
94
  process.exit(97);
94
95
  }
96
+ return deliverUser(ctx, sessionId, messageId, text, 'followup');
97
+ }
98
+ /**
99
+ * Steering for the nearest step. On a running worker the host aborts first,
100
+ * so this call lands after the abort and wakes the next turn. An idle worker
101
+ * starts a turn immediately.
102
+ */
103
+ export async function steerDurable(ctx, sessionId, messageId, text) {
104
+ return deliverUser(ctx, sessionId, messageId, text, 'steer');
105
+ }
106
+ async function deliverUser(ctx, sessionId, messageId, text, method) {
107
+ if (isFenced(sessionId)) {
108
+ return {
109
+ ok: false,
110
+ ambiguous: false,
111
+ seq: null,
112
+ error: 'deleting',
113
+ target: method === 'steer' ? 'next-step' : 'next-turn',
114
+ wakeup: false,
115
+ };
116
+ }
95
117
  const loaded = await loadAgent(ctx, sessionId);
96
118
  const agent = loaded.agent;
97
119
  try {
98
- agent.followup(userMessage(messageId, text));
120
+ agent[method](userMessage(messageId, text));
99
121
  }
100
122
  catch (error) {
101
123
  const message = error instanceof Error ? error.message : String(error);
@@ -122,7 +144,7 @@ export async function followupDurable(ctx, sessionId, messageId, text) {
122
144
  ambiguous: !flushed,
123
145
  seq,
124
146
  error: flushError,
125
- target: 'next-turn',
147
+ target: method === 'steer' ? 'next-step' : 'next-turn',
126
148
  wakeup: true,
127
149
  };
128
150
  }
package/dist/index.js CHANGED
@@ -5,19 +5,22 @@ import { createEngine } from "./engine.js";
5
5
  import { renderPeers, renderSession, renderTickets, WORKER_MEMORY } from "./context.js";
6
6
  import { callMemoryTool, memorySessionFor, toolDefinitions } from "./tools.js";
7
7
  import { createTriggers } from "./triggers.js";
8
- import { followupDurable, liveAgent, logHasMessage, removePending } from "./inbox.js";
8
+ import { followupDurable, liveAgent, logHasMessage, removePending, steerDurable } from "./inbox.js";
9
9
  import { createLogSource } from "./log/source.js";
10
10
  import { toolError } from "./errors.js";
11
11
  import { createQuestionAnswerer, publishQuestionAnswerer, questionAnswererFor } from "./questions.js";
12
12
  import { createApprovalAnswerer, publishApprovalAnswerer, approvalAnswererFor } from "./approvals.js";
13
13
  import { createAuthorizationController, publishAuthorization, authorizationFor } from "./authorization.js";
14
- import { publishRuntime, publishWorkRuntime, runtimeFor } from "./runtime-registry.js";
14
+ import { isFenced } from "./deleting.js";
15
+ import { publishRuntime, publishSessionDrop, publishWorkRuntime, runtimeFor } from "./runtime-registry.js";
15
16
  import { childCreateOptions, effectiveWorkLimits, pinMainReasoning, resolveWorkBudget, workerModelSelection, WORK_BUDGET_ENV, } from "./work-admit.js";
16
- import { ensureWorkerFilePreset, WORKER_FILE_PRESET, workerFileSetup } from "./work-child.js";
17
+ import { CANVAS_WORKER_PRESET, ensureWorkerFilePreset, WORKER_FILE_PRESET, workerFileSetup } from "./work-child.js";
17
18
  import { BUDGET_NOTICE_PREFIX, createWorkRuntime } from "./work-worker.js";
18
19
  import { workToolDefinitions } from "./work-tools.js";
19
20
  import { openCanvasStore } from "./canvas-store.js";
21
+ import { backlogCanvases, bindCanvasCards, createCardLog, publishCardLog } from "./card-log.js";
20
22
  import { canvasToolDefinitions } from "./canvas-tools.js";
23
+ import { forgetWorker, rememberWorker } from "./worker-handles.js";
21
24
  export const name = 'session-foundations';
22
25
  // Cordis throws if a plugin reads a service it did not inject. Crash recovery reads the session log through this one.
23
26
  export const inject = [
@@ -39,7 +42,11 @@ export function apply(ctx, config = {}) {
39
42
  if (dataDir === '')
40
43
  throw new Error('session-foundations: pass dataDir or launch with dsh profileContext');
41
44
  const store = openStore(dataDir);
45
+ const cards = createCardLog(store.db);
46
+ publishCardLog(dataDir, cards);
42
47
  const canvas = openCanvasStore(join(dataDir, 'canvas.sqlite'));
48
+ bindCanvasCards(canvas, ctx, dataDir);
49
+ backlogCanvases(canvas, ctx, dataDir);
43
50
  const engine = createEngine(store);
44
51
  const recovery = engine.recover();
45
52
  const ownerFile = join(dataDir, 'owner.json');
@@ -53,6 +60,7 @@ export function apply(ctx, config = {}) {
53
60
  catch {
54
61
  /* already gone */
55
62
  }
63
+ publishCardLog(dataDir, null);
56
64
  try {
57
65
  store.close();
58
66
  }
@@ -222,7 +230,12 @@ export function apply(ctx, config = {}) {
222
230
  pinMainReasoning(payload?.agent, id => engine.isBot(id));
223
231
  });
224
232
  triggers = ctx.agents ? startTriggers(ctx, store, engine) : null;
225
- work = ctx.agents ? startWork(ctx, store, engine, config) : null;
233
+ work = ctx.agents
234
+ ? startWork(ctx, store, engine, config, cards, sessionIds => {
235
+ for (const sessionId of sessionIds)
236
+ rendered.delete(sessionId);
237
+ })
238
+ : null;
226
239
  if (triggers) {
227
240
  for (const definition of triggerTools(triggers, engine))
228
241
  ctx.tools.register(definition);
@@ -230,7 +243,17 @@ export function apply(ctx, config = {}) {
230
243
  if (work) {
231
244
  for (const definition of workToolDefinitions(work, engine))
232
245
  ctx.tools.register(definition);
233
- for (const definition of canvasToolDefinitions(canvas, work, engine))
246
+ for (const definition of canvasToolDefinitions(canvas, work, engine, {
247
+ workspaceCwd(sessionId) {
248
+ try {
249
+ const cwd = ctx.sessions?.get(sessionId)?.header?.cwd;
250
+ return typeof cwd === 'string' ? cwd : '';
251
+ }
252
+ catch {
253
+ return '';
254
+ }
255
+ },
256
+ }))
234
257
  ctx.tools.register(definition);
235
258
  const gate = work;
236
259
  // Main-session step budget: refuse the next step instead of cancelling a
@@ -268,7 +291,19 @@ export function apply(ctx, config = {}) {
268
291
  if (questionAnswererFor(store.root) === questions)
269
292
  publishQuestionAnswerer(store.root, null);
270
293
  });
271
- const approvals = createApprovalAnswerer();
294
+ const approvals = createApprovalAnswerer(entry => {
295
+ cards.record(ctx, {
296
+ kind: 'approval',
297
+ key: entry.requestId,
298
+ sessionId: entry.sessionId,
299
+ payload: {
300
+ requestId: entry.requestId,
301
+ toolName: entry.toolName,
302
+ reason: entry.reason,
303
+ ...(entry.callId ? { callId: entry.callId } : {}),
304
+ },
305
+ });
306
+ });
272
307
  publishApprovalAnswerer(store.root, approvals);
273
308
  ctx.effect(() => approvals.listen(ctx));
274
309
  ctx.effect(() => () => {
@@ -327,9 +362,7 @@ function startTriggers(ctx, store, engine) {
327
362
  * @param {import('./src/engine.js').Engine} engine
328
363
  * @param {{ work?: Partial<import('./src/work-admit.js').DEFAULT_WORK_BUDGET> }} config
329
364
  */
330
- function startWork(ctx, store, engine, config) {
331
- /** @type {Map<string, { dispose?: () => Promise<void> }>} */
332
- const workerHandles = new Map();
365
+ function startWork(ctx, store, engine, config, cards, onDrop = () => { }) {
333
366
  const filePreset = ensureWorkerFilePreset(ctx);
334
367
  const resolved = resolveWorkBudget(config.work ?? {}, process.env[WORK_BUDGET_ENV]);
335
368
  if (resolved.ignored.length > 0) {
@@ -362,6 +395,9 @@ function startWork(ctx, store, engine, config) {
362
395
  });
363
396
  },
364
397
  createChild: async (spec) => {
398
+ if (isFenced(spec.ownerSessionId) || isFenced(spec.sessionId)) {
399
+ throw Object.assign(new Error('session is being deleted'), { code: 'DELETING' });
400
+ }
365
401
  let cwd = '';
366
402
  let model = null;
367
403
  try {
@@ -385,14 +421,22 @@ function startWork(ctx, store, engine, config) {
385
421
  const options = childCreateOptions(spec.sessionId, cwd, model, cap);
386
422
  const presetId = await filePreset;
387
423
  if (presetId) {
388
- options.meta = { ...(options.meta ?? {}), agentPreset: WORKER_FILE_PRESET };
389
- options.setup = workerFileSetup(ctx, WORKER_FILE_PRESET);
424
+ const preset = spec.canvas ? CANVAS_WORKER_PRESET : WORKER_FILE_PRESET;
425
+ options.meta = { ...(options.meta ?? {}), agentPreset: preset };
426
+ options.setup = workerFileSetup(ctx, preset);
390
427
  }
391
428
  const handle = await ctx.agents.create(options);
392
- workerHandles.set(spec.sessionId, handle);
429
+ rememberWorker(spec.sessionId, handle);
393
430
  return spec.sessionId;
394
431
  },
432
+ recordCard: input => {
433
+ cards.record(ctx, input);
434
+ },
435
+ flushCards: () => {
436
+ cards.flush(ctx);
437
+ },
395
438
  push: (sessionId, messageId, text) => followupDurable(ctx, sessionId, messageId, text),
439
+ steer: (sessionId, messageId, text) => steerDurable(ctx, sessionId, messageId, text),
396
440
  logHas: (sessionId, messageId) => logHasDurable(ctx, sessionId, messageId),
397
441
  remove: (sessionId, messageId) => removePending(ctx, sessionId, messageId),
398
442
  pendingIds: async (sessionId) => {
@@ -423,9 +467,17 @@ function startWork(ctx, store, engine, config) {
423
467
  childPresent: sessionId => liveAgent(ctx, sessionId) != null,
424
468
  });
425
469
  publishWorkRuntime(store.root, work);
470
+ publishSessionDrop(store.root, sessionIds => {
471
+ onDrop(sessionIds);
472
+ for (const sessionId of sessionIds) {
473
+ engine.openViews.delete(sessionId);
474
+ engine.surface.delete(sessionId);
475
+ void forgetWorker(sessionId);
476
+ }
477
+ });
426
478
  ctx.effect(() => () => {
427
479
  publishWorkRuntime(store.root, null);
428
- workerHandles.clear();
480
+ publishSessionDrop(store.root, null);
429
481
  });
430
482
  ctx.on('agent/inbox/claimed', (payload) => {
431
483
  if (payload == null)
package/dist/questions.js CHANGED
@@ -323,6 +323,15 @@ export function createQuestionAnswerer() {
323
323
  matched.entry.reject(questionRejection('ASK_CANCELLED', 'The user requested changes or cancelled the question.'));
324
324
  return { ok: true, path: 'cancelled' };
325
325
  }
326
+ function cancelSession(sessionId) {
327
+ for (const entry of [...pending]) {
328
+ if (entry.sessionId !== sessionId)
329
+ continue;
330
+ if (!detach(entry))
331
+ continue;
332
+ entry.reject(questionRejection('ASK_CANCELLED', 'This session is being deleted.'));
333
+ }
334
+ }
326
335
  function timeout(input) {
327
336
  if (typeof input.sessionId !== 'string' || input.sessionId === '') {
328
337
  return toolError('VALIDATION', 'sessionId is required.');
@@ -397,6 +406,7 @@ export function createQuestionAnswerer() {
397
406
  handle,
398
407
  submit,
399
408
  cancel,
409
+ cancelSession,
400
410
  timeout,
401
411
  takeTime,
402
412
  snapshot,
@@ -34,3 +34,23 @@ export function publishWorkRuntime(dataDir, runtime) {
34
34
  export function workRuntimeFor(dataDir) {
35
35
  return workRuntimes.get(dataDir) ?? null;
36
36
  }
37
+ /** @type {Map<string, (sessionIds: readonly string[]) => void>} */
38
+ const sessionDrops = new Map();
39
+ /**
40
+ * The main plugin drops in-memory views when the HTTP plugin deletes a bot.
41
+ * @param {string} dataDir
42
+ * @param {((sessionIds: readonly string[]) => void) | null} drop
43
+ */
44
+ export function publishSessionDrop(dataDir, drop) {
45
+ if (drop)
46
+ sessionDrops.set(dataDir, drop);
47
+ else
48
+ sessionDrops.delete(dataDir);
49
+ }
50
+ /**
51
+ * @param {string} dataDir
52
+ * @param {readonly string[]} sessionIds
53
+ */
54
+ export function dropSessions(dataDir, sessionIds) {
55
+ sessionDrops.get(dataDir)?.(sessionIds);
56
+ }