@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
@@ -1,7 +1,10 @@
1
+ import { lstatSync, readFileSync, realpathSync } from 'node:fs';
2
+ import { isAbsolute, resolve, sep } from 'node:path';
1
3
  import { bindCanvasSkills } from "./canvas-skills.js";
2
4
  import { CANVAS_MAX_FILE_BYTES } from "./canvas-store.js";
3
5
  import { toolError } from "./errors.js";
4
6
  const BRIEFING_MAX = 16000;
7
+ const EDIT_TEXT_MAX = 8000;
5
8
  const OUTPUT = {
6
9
  schema: {
7
10
  type: 'object',
@@ -17,25 +20,58 @@ const OUTPUT = {
17
20
  * execute rejects the main bot and any worker that does not own this canvas.
18
21
  * A budget wait never comes through these tools, and they do not mark a preview failed.
19
22
  */
20
- export function canvasToolDefinitions(canvas, work, engine) {
23
+ export function canvasToolDefinitions(canvas, work, engine, filesApi = {}) {
21
24
  return [
22
- tool('foundations_dispatch_canvas', 'Open a canvas design worker for an HTML/CSS preview. Use this instead of foundations_dispatch, write, or edit when the user wants a visual design, page mock, or preview. The main session must not build the preview. A returned canvasId has no revision until the worker publishes. A budget pause is not a failed preview.', {
25
+ tool('foundations_dispatch_canvas', 'Open a canvas design worker for an HTML/CSS preview. Use this instead of foundations_dispatch, write, or edit when the user wants a visual design, page mock, or preview. The main session must not build the preview. The canvas worker has no workspace write or edit tool; it stages files with canvas_write and publishes with canvas_publish. A returned canvasId has no revision until the worker publishes. A budget pause is not a failed preview.', {
23
26
  type: 'object',
24
27
  properties: {
25
28
  briefing: { type: 'string', description: 'What to design. The host wraps this with the canvas contract.' },
26
- idempotencyKey: { type: 'string' },
27
- budget: {
28
- type: 'object',
29
- properties: {
30
- wallMs: { type: 'integer' },
31
- maxTokens: { type: 'integer' },
32
- },
29
+ canvasId: {
30
+ type: 'string',
31
+ description: 'An existing canvas to revise. Omit to open a new preview. Copy it from a canvas-target block.',
33
32
  },
33
+ idempotencyKey: { type: 'string' },
34
34
  correlationId: { type: 'string' },
35
35
  },
36
36
  required: ['briefing'],
37
37
  }, (args, hostId) => dispatchCanvas(canvas, work, engine, hostId, args)),
38
- tool('canvas_write', 'Stage HTML, CSS, images, or fonts for the canvas bound to this worker. The main bot and every other worker are rejected. text is for HTML and CSS. body is standard base64 for images and fonts. This does not publish and does not mark the preview failed.', {
38
+ tool('canvas_read', 'Read the current preview bound to this worker. HTML and CSS include text. Images and fonts return path, type, and bytes (the size only). Do not search the disk for cnv_ or a canvas store. This does not publish.', {
39
+ type: 'object',
40
+ properties: {
41
+ path: { type: 'string', description: 'One file. Omit to list the whole preview.' },
42
+ },
43
+ }, async (args, hostId) => {
44
+ const canvasId = ownedCanvas(canvas, work, engine, hostId);
45
+ if (typeof canvasId !== 'string')
46
+ return canvasId;
47
+ const listing = canvas.previewListing(canvasId);
48
+ if (listing.ok === false)
49
+ return listing;
50
+ const path = args.path;
51
+ if (path == null || path === '')
52
+ return listing;
53
+ if (typeof path !== 'string')
54
+ return toolError('VALIDATION', 'path is not allowed.');
55
+ const file = listing.files.find((item) => item.path === path);
56
+ if (!file)
57
+ return toolError('NOT_FOUND', 'That file is not in the current preview.');
58
+ return { ok: true, canvasId, revision: listing.revision, files: [file] };
59
+ }),
60
+ tool('canvas_edit', 'Replace one exact span in an existing HTML or CSS file on this canvas. old must match once. Do not send the whole file. This stages the file and does not publish.', {
61
+ type: 'object',
62
+ properties: {
63
+ path: { type: 'string' },
64
+ old: { type: 'string', description: 'Exact text to replace. It must occur once.' },
65
+ replacement: { type: 'string' },
66
+ },
67
+ required: ['path', 'old', 'replacement'],
68
+ }, async (args, hostId) => {
69
+ const canvasId = ownedCanvas(canvas, work, engine, hostId);
70
+ if (typeof canvasId !== 'string')
71
+ return canvasId;
72
+ return editCanvas(canvas, canvasId, args);
73
+ }),
74
+ tool('canvas_write', 'Stage files for the canvas bound to this worker. Pass HTML and CSS as text, up to the 1.5 MiB file cap. Pass images and fonts as body (standard base64), or as source when that file is already in the workspace. This worker has no write or edit tool. A file on disk is not this preview. This does not publish and does not mark the preview failed.', {
39
75
  type: 'object',
40
76
  properties: {
41
77
  files: {
@@ -44,7 +80,8 @@ export function canvasToolDefinitions(canvas, work, engine) {
44
80
  type: 'object',
45
81
  properties: {
46
82
  path: { type: 'string' },
47
- type: { type: 'string' },
83
+ type: { type: 'string', description: 'text/html, text/css, or an image or font type.' },
84
+ source: { type: 'string', description: 'Workspace-relative file. The host reads it.' },
48
85
  text: { type: 'string' },
49
86
  body: { type: 'string' },
50
87
  },
@@ -57,7 +94,10 @@ export function canvasToolDefinitions(canvas, work, engine) {
57
94
  const canvasId = ownedCanvas(canvas, work, engine, hostId);
58
95
  if (typeof canvasId !== 'string')
59
96
  return canvasId;
60
- const files = decodeFiles(args.files);
97
+ const decoded = decodeFiles(args.files);
98
+ if (!Array.isArray(decoded))
99
+ return decoded;
100
+ const files = materialize(decoded, hostId, filesApi);
61
101
  if (!Array.isArray(files))
62
102
  return files;
63
103
  const remove = decodeRemove(args.remove);
@@ -65,27 +105,46 @@ export function canvasToolDefinitions(canvas, work, engine) {
65
105
  return remove;
66
106
  return canvas.writeDraft(canvasId, files, remove);
67
107
  }),
68
- tool('canvas_publish', 'Publish the staged files for the canvas bound to this worker. The first publish is a snapshot. Later publishes are deltas of the current preview. The main bot and every other worker are rejected. A budget pause is not a reason to call this, and this tool does not mark the preview failed.', { type: 'object', properties: {} }, async (_args, hostId) => {
108
+ tool('canvas_publish', 'Publish the staged files once, after every file for this task is staged. This also files the result report, so do not call foundations_report afterward and do not keep editing. A second call on the same ticket is rejected. The first publish is a snapshot. Later tickets publish a delta of the current preview. Do not publish after each file or after a partial write. The main bot and every other worker are rejected. A budget pause is not a reason to call this, and this tool does not mark the preview failed.', { type: 'object', properties: {} }, async (_args, hostId) => {
69
109
  const canvasId = ownedCanvas(canvas, work, engine, hostId);
70
110
  if (typeof canvasId !== 'string')
71
111
  return canvasId;
72
- return canvas.publishDraft(canvasId);
112
+ const published = await canvas.publishDraft(canvasId, work.ticketIdOf(hostId));
113
+ if (published.ok !== true || typeof work.report !== 'function')
114
+ return published;
115
+ const revision = typeof published.revision === 'number' ? String(published.revision) : '';
116
+ const reported = await work.report(hostId, {
117
+ kind: 'result',
118
+ text: `Published ${canvasId} revision ${revision}. The preview is ready for the workbench card.`,
119
+ });
120
+ return reported.ok === true ? published : { ...published, report: reported };
73
121
  }),
74
122
  ];
75
123
  }
76
- export function canvasBriefing(canvasId, request, skills) {
124
+ export function isCanvasWorkerBriefing(text) {
125
+ return /^Canvas preview cnv_[A-Za-z0-9_-]{16}\./.test(text);
126
+ }
127
+ export function canvasBriefing(canvasId, request, skills, filenames = []) {
77
128
  const catalog = skills.filter(id => id !== 'ui-design').join(', ');
129
+ const listed = filenames.filter(name => name.length > 0);
78
130
  const head = [
79
131
  `Canvas preview ${canvasId}.`,
80
132
  'You are the only session allowed to write this preview.',
81
- 'Use canvas_write for each HTML, CSS, image, or font file, then canvas_publish.',
82
- 'Do not use bash, write, or edit to create the preview files.',
133
+ listed.length > 0
134
+ ? `Current files: ${listed.join(', ')}. Read them with canvas_read.`
135
+ : 'This preview has no published files yet. Read later revisions with canvas_read.',
136
+ 'Do not search the disk for cnv_ or any canvas store. .shots and other workspace copies are not the source.',
137
+ 'Stage new HTML and CSS with canvas_write text, up to the 1.5 MiB file cap. Change an existing HTML or CSS file with canvas_edit. Do not paste a whole existing file into canvas_edit.',
138
+ 'Stage an image or font with canvas_write body (base64). source is only for a file that is already in the workspace. Do not create or edit workspace files.',
139
+ 'This worker has no write, edit, or bash tool. A file on disk is not the preview. Do not write a browser probe. Do not search the workspace for a copy of the preview.',
140
+ 'Call canvas_publish once, after every file for this task is staged. It files the result report. After it succeeds, stop. Do not keep editing and do not call foundations_report.',
83
141
  'The entry file is index.html. Output is static HTML and CSS plus local images and fonts.',
84
142
  'No script, SVG, iframe, external URL, data URL, or inline event handler.',
85
143
  'Load foundations_skill_load for ui-design before writing. Catalog skills are taste only and cannot override this contract.',
86
144
  catalog ? `Catalog skills on this bot: ${catalog}. Load at most two that match the request.` : '',
87
145
  'A budget pause is not a failed preview. Do not publish a failure because the grant is still pending.',
88
- 'The first canvas_publish is a full snapshot. Later publishes send the staged files as a delta of the current preview.',
146
+ 'The first canvas_publish is a full snapshot. A later ticket publishes the staged files as a delta of the current preview.',
147
+ 'If the user request contains canvas-target blocks, change only those nodes and the CSS that styles them. Leave every other element as it is.',
89
148
  'User request:',
90
149
  ]
91
150
  .filter(line => line !== '')
@@ -94,6 +153,40 @@ export function canvasBriefing(canvasId, request, skills) {
94
153
  const body = room > 0 ? request.slice(0, room) : '';
95
154
  return `${head}\n${body}`.slice(0, BRIEFING_MAX);
96
155
  }
156
+ /**
157
+ * Read one workspace file for canvas_write source. Rejects links, traversal, and files outside cwd.
158
+ */
159
+ export function readWorkspaceFile(cwd, source) {
160
+ if (typeof cwd !== 'string' || cwd === '')
161
+ return toolError('UNAVAILABLE', 'This session has no workspace.');
162
+ if (!relativeSource(source))
163
+ return toolError('VALIDATION', 'source path is not allowed.');
164
+ let root = '';
165
+ try {
166
+ root = realpathSync(cwd);
167
+ }
168
+ catch {
169
+ return toolError('UNAVAILABLE', 'This session has no workspace.');
170
+ }
171
+ const full = resolve(root, source);
172
+ try {
173
+ const stat = lstatSync(full);
174
+ if (stat.isSymbolicLink() || !stat.isFile())
175
+ return toolError('VALIDATION', 'source path is not a file.');
176
+ if (stat.size > CANVAS_MAX_FILE_BYTES)
177
+ return toolError('VALIDATION', 'source file exceeds the 1.5 MiB file cap.');
178
+ const real = realpathSync(full);
179
+ if (real !== root && !real.startsWith(root + sep))
180
+ return toolError('VALIDATION', 'source path is not allowed.');
181
+ return readFileSync(real);
182
+ }
183
+ catch (error) {
184
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : '';
185
+ if (code === 'ENOENT')
186
+ return toolError('NOT_FOUND', 'source file was not found.');
187
+ return toolError('VALIDATION', 'source path is not allowed.');
188
+ }
189
+ }
97
190
  async function dispatchCanvas(canvas, work, engine, hostId, args) {
98
191
  if (!engine.isBot(hostId))
99
192
  return toolError('FORBIDDEN', 'Only the main bot can open a canvas worker.');
@@ -104,8 +197,13 @@ async function dispatchCanvas(canvas, work, engine, hostId, args) {
104
197
  if (key != null && (typeof key !== 'string' || key.length < 8 || key.length > 128))
105
198
  return toolError('VALIDATION', 'idempotencyKey is not allowed.');
106
199
  const title = briefing.split('\n')[0]?.trim().slice(0, 80) ?? '';
107
- let canvasId = typeof key === 'string' ? canvas.findIdempotent(hostId, key) : null;
108
- if (!canvasId) {
200
+ const requested = typeof args.canvasId === 'string' ? args.canvasId : '';
201
+ let canvasId = requested !== '' ? requested : typeof key === 'string' ? canvas.findIdempotent(hostId, key) : null;
202
+ if (requested !== '') {
203
+ if (!canvas.ownedBy(hostId, requested))
204
+ return toolError('FORBIDDEN', 'That canvas is not in this session.');
205
+ }
206
+ else if (!canvasId) {
109
207
  const created = canvas.create({
110
208
  sessionId: hostId,
111
209
  title,
@@ -126,17 +224,19 @@ async function dispatchCanvas(canvas, work, engine, hostId, args) {
126
224
  return toolError('STORE_FAILURE', error instanceof Error ? error.message : 'Canvas skills could not be bound.');
127
225
  }
128
226
  const forwarded = {
129
- briefing: canvasBriefing(canvasId, briefing, skills),
227
+ briefing: canvasBriefing(canvasId, briefing, skills, canvas.previewPaths(canvasId)),
130
228
  };
131
229
  if (typeof key === 'string')
132
230
  forwarded.idempotencyKey = key;
133
- if (args.budget != null)
134
- forwarded.budget = args.budget;
135
231
  if (typeof args.correlationId === 'string')
136
232
  forwarded.correlationId = args.correlationId;
137
233
  const dispatched = await work.dispatch(hostId, forwarded);
138
- if (dispatched.ok === true && typeof dispatched.ticketId === 'string')
139
- canvas.attachTicket(canvasId, dispatched.ticketId);
234
+ if (dispatched.ok === true && typeof dispatched.ticketId === 'string') {
235
+ if (requested !== '')
236
+ canvas.attachWriter(canvasId, dispatched.ticketId);
237
+ else
238
+ canvas.attachTicket(canvasId, dispatched.ticketId);
239
+ }
140
240
  return { ...dispatched, canvasId };
141
241
  }
142
242
  function ownedCanvas(canvas, work, engine, hostId) {
@@ -147,6 +247,28 @@ function ownedCanvas(canvas, work, engine, hostId) {
147
247
  return toolError('FORBIDDEN', 'Only the canvas worker for this preview can write it.');
148
248
  return canvasId;
149
249
  }
250
+ function editCanvas(canvas, canvasId, args) {
251
+ const path = typeof args.path === 'string' ? args.path : '';
252
+ const old = args.old;
253
+ const replacement = args.replacement;
254
+ if (typeof old !== 'string' || typeof replacement !== 'string')
255
+ return toolError('VALIDATION', 'canvas_edit needs old and replacement text.');
256
+ if (old.length < 1 || old.length > EDIT_TEXT_MAX || replacement.length > EDIT_TEXT_MAX)
257
+ return toolError('VALIDATION', 'canvas_edit text must be between 1 and 8000 characters.');
258
+ const current = canvas.currentFile(canvasId, path);
259
+ if (!current)
260
+ return toolError('NOT_FOUND', `${path} is not in the current preview. Use canvas_write for a new file.`);
261
+ if (current.type !== 'text/html' && current.type !== 'text/css')
262
+ return toolError('VALIDATION', 'canvas_edit is only for HTML and CSS.');
263
+ const text = current.bytes.toString('utf8');
264
+ const count = countExact(text, old);
265
+ if (count === 0)
266
+ return toolError('VALIDATION', `old text was not found in ${path}.`);
267
+ if (count > 1)
268
+ return toolError('VALIDATION', `old text matched ${count} times in ${path}.`);
269
+ const next = text.replace(old, replacement);
270
+ return canvas.writeDraft(canvasId, [{ path, type: current.type, bytes: Buffer.from(next, 'utf8') }]);
271
+ }
150
272
  function decodeFiles(input) {
151
273
  if (input == null)
152
274
  return [];
@@ -159,30 +281,77 @@ function decodeFiles(input) {
159
281
  const record = item;
160
282
  if (typeof record.path !== 'string' || typeof record.type !== 'string')
161
283
  return toolError('VALIDATION', 'A canvas file is not allowed.');
284
+ if (record.type === 'text')
285
+ return toolError('VALIDATION', 'type must be text/html or text/css.');
162
286
  const text = record.text;
163
287
  const body = record.body;
164
- if (typeof text === 'string' && typeof body === 'string')
165
- return toolError('VALIDATION', 'A canvas file has both text and body.');
288
+ const source = record.source;
289
+ const present = [typeof text === 'string', typeof body === 'string', typeof source === 'string'].filter(Boolean);
290
+ if (present.length > 1)
291
+ return toolError('VALIDATION', 'A canvas file has more than one of text, body, and source.');
292
+ if (typeof source === 'string') {
293
+ if (!relativeSource(source))
294
+ return toolError('VALIDATION', 'source path is not allowed.');
295
+ files.push({ path: record.path, type: record.type, source });
296
+ continue;
297
+ }
166
298
  if (typeof text === 'string') {
167
299
  if (record.type !== 'text/html' && record.type !== 'text/css')
168
- return toolError('VALIDATION', 'text is only for HTML and CSS.');
300
+ return toolError('VALIDATION', 'text is only for text/html and text/css.');
169
301
  const bytes = Buffer.from(text, 'utf8');
170
302
  if (bytes.length > CANVAS_MAX_FILE_BYTES)
171
- return toolError('VALIDATION', `${record.path} exceeds the 1.5 MiB file cap.`);
303
+ return toolError('VALIDATION', `${record.path} exceeds the 1.5 MiB file cap. Pass a smaller HTML or CSS file.`);
172
304
  files.push({ path: record.path, type: record.type, bytes });
173
305
  continue;
174
306
  }
175
307
  if (typeof body === 'string') {
308
+ if (record.type === 'text/html' || record.type === 'text/css')
309
+ return toolError('VALIDATION', 'HTML/CSS 用 text,base64 只给图片和字体。');
176
310
  const packed = body.replace(/\s/g, '');
177
311
  if (packed.length === 0 || packed.length > CANVAS_MAX_FILE_BYTES * 2 || !/^[A-Za-z0-9+/=]+$/.test(packed))
178
312
  return toolError('VALIDATION', `${record.path} body is not base64.`);
179
313
  files.push({ path: record.path, type: record.type, bytes: Buffer.from(packed, 'base64') });
180
314
  continue;
181
315
  }
182
- return toolError('VALIDATION', 'A canvas file needs text or body.');
316
+ return toolError('VALIDATION', 'A canvas file needs text, body, or source.');
183
317
  }
184
318
  return files;
185
319
  }
320
+ function materialize(files, sessionId, filesApi) {
321
+ const ready = [];
322
+ for (const file of files) {
323
+ if ('bytes' in file) {
324
+ ready.push(file);
325
+ continue;
326
+ }
327
+ const cwd = filesApi.workspaceCwd?.(sessionId) ?? '';
328
+ const bytes = readWorkspaceFile(cwd, file.source);
329
+ if (!Buffer.isBuffer(bytes))
330
+ return bytes;
331
+ ready.push({ path: file.path, type: file.type, bytes });
332
+ }
333
+ return ready;
334
+ }
335
+ function relativeSource(source) {
336
+ if (typeof source !== 'string' || source.length === 0 || source.length > 200)
337
+ return false;
338
+ if (isAbsolute(source) || source.includes('\0') || source.includes('\\'))
339
+ return false;
340
+ const parts = source.split('/');
341
+ return parts.every(part => part !== '' && part !== '..');
342
+ }
343
+ function countExact(text, needle) {
344
+ let count = 0;
345
+ let from = 0;
346
+ while (from <= text.length) {
347
+ const at = text.indexOf(needle, from);
348
+ if (at < 0)
349
+ return count;
350
+ count += 1;
351
+ from = at + needle.length;
352
+ }
353
+ return count;
354
+ }
186
355
  function decodeRemove(input) {
187
356
  if (input == null)
188
357
  return [];
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Chat cards are plugin records on the owner session.
3
+ * appendPluginRecord assigns the seq and does not wake a turn.
4
+ * A session that is not entered keeps a pending row until flush.
5
+ *
6
+ * The desk and this plugin can each load @deepseek-ai/dsh-session.
7
+ * appendPluginRecord only accepts a Session from its own module, so the
8
+ * append below is taken from the module that constructed the live session.
9
+ */
10
+ import { createRequire } from 'node:module';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { appendPluginRecord } from '@deepseek-ai/dsh-session';
13
+ export const WORKER_CARD = 'plugin:foundations/worker';
14
+ export const CANVAS_CARD = 'plugin:foundations/canvas';
15
+ export const APPROVAL_CARD = 'plugin:foundations/approval';
16
+ const RECORD_TYPE = {
17
+ worker: WORKER_CARD,
18
+ canvas: CANVAS_CARD,
19
+ approval: APPROVAL_CARD,
20
+ };
21
+ const logs = new Map();
22
+ export function publishCardLog(dataDir, log) {
23
+ if (log)
24
+ logs.set(dataDir, log);
25
+ else
26
+ logs.delete(dataDir);
27
+ }
28
+ export function cardLogFor(dataDir) {
29
+ return logs.get(dataDir) ?? null;
30
+ }
31
+ export function createCardLog(db, appender = hostAppender) {
32
+ return new CardLog(db, appender);
33
+ }
34
+ export function bindCanvasCards(canvas, ctx, dataDir) {
35
+ return canvas.onPublished(event => {
36
+ const cards = cardLogFor(dataDir);
37
+ if (!cards)
38
+ return;
39
+ cards.record(ctx, canvasRequest(event));
40
+ });
41
+ }
42
+ export function backlogCanvases(canvas, ctx, dataDir) {
43
+ const cards = cardLogFor(dataDir);
44
+ if (!cards)
45
+ return;
46
+ for (const event of canvas.publishedPreviews()) {
47
+ if (event.sessionId === '')
48
+ continue;
49
+ cards.record(ctx, canvasRequest(event));
50
+ }
51
+ }
52
+ export function canvasRequest(event) {
53
+ return {
54
+ kind: 'canvas',
55
+ key: `${event.canvasId}:${event.revision}`,
56
+ sessionId: event.sessionId,
57
+ payload: {
58
+ canvasId: event.canvasId,
59
+ revision: event.revision,
60
+ kind: event.kind,
61
+ title: event.title,
62
+ ticketId: event.ticketId,
63
+ },
64
+ };
65
+ }
66
+ const localAppend = appendPluginRecord;
67
+ const appendByClass = new WeakMap();
68
+ let appendFailureLogged = false;
69
+ /** Append with the dsh-session module that owns this Session instance. */
70
+ export function appendCardRecord(session, type, data) {
71
+ return appenderFor(session)(session, type, data);
72
+ }
73
+ const hostAppender = {
74
+ session: liveSession,
75
+ append: appendCardRecord,
76
+ };
77
+ export class CardLog {
78
+ db;
79
+ appender;
80
+ constructor(db, appender) {
81
+ this.db = db;
82
+ this.appender = appender;
83
+ }
84
+ /** One record per key. A later call returns the seq already stored. */
85
+ record(ctx, request) {
86
+ const existing = this.db
87
+ .prepare('SELECT seq FROM card_log WHERE kind = ? AND key = ?')
88
+ .get(request.kind, request.key);
89
+ if (typeof existing?.seq === 'number')
90
+ return existing.seq;
91
+ this.db
92
+ .prepare(`INSERT INTO card_log (kind, key, session_id, payload, seq) VALUES (?, ?, ?, ?, NULL)
93
+ ON CONFLICT(kind, key) DO UPDATE SET
94
+ session_id = excluded.session_id,
95
+ payload = excluded.payload
96
+ WHERE card_log.seq IS NULL`)
97
+ .run(request.kind, request.key, request.sessionId, JSON.stringify(request.payload));
98
+ return this.commit(ctx, request.kind, request.key, request.sessionId);
99
+ }
100
+ flush(ctx) {
101
+ const rows = this.db.prepare('SELECT kind, key, session_id FROM card_log WHERE seq IS NULL').all();
102
+ for (const row of rows) {
103
+ if (row.kind !== 'worker' && row.kind !== 'canvas' && row.kind !== 'approval')
104
+ continue;
105
+ this.commit(ctx, row.kind, row.key, row.session_id);
106
+ }
107
+ }
108
+ commit(ctx, kind, key, sessionId) {
109
+ const row = this.db.prepare('SELECT payload, seq FROM card_log WHERE kind = ? AND key = ?').get(kind, key);
110
+ if (!row)
111
+ return null;
112
+ if (typeof row.seq === 'number')
113
+ return row.seq;
114
+ const session = this.appender.session(ctx, sessionId);
115
+ if (!session || typeof row.payload !== 'string')
116
+ return null;
117
+ let payload;
118
+ try {
119
+ payload = JSON.parse(row.payload);
120
+ }
121
+ catch {
122
+ return null;
123
+ }
124
+ let seq;
125
+ try {
126
+ seq = this.appender.append(session, RECORD_TYPE[kind], payload);
127
+ }
128
+ catch (error) {
129
+ logAppendFailure(ctx, error);
130
+ return null;
131
+ }
132
+ if (!Number.isInteger(seq) || seq < 0)
133
+ return null;
134
+ this.db.prepare('UPDATE card_log SET seq = ? WHERE kind = ? AND key = ? AND seq IS NULL').run(seq, kind, key);
135
+ return seq;
136
+ }
137
+ }
138
+ function appenderFor(session) {
139
+ const ctor = session.constructor;
140
+ if (typeof ctor !== 'function')
141
+ return localAppend;
142
+ const cached = appendByClass.get(ctor);
143
+ if (cached)
144
+ return cached;
145
+ const append = appendFromSessionModule(session) ?? localAppend;
146
+ appendByClass.set(ctor, append);
147
+ return append;
148
+ }
149
+ function appendFromSessionModule(session) {
150
+ const file = sessionModuleFile(session);
151
+ if (!file)
152
+ return null;
153
+ try {
154
+ const loaded = createRequire(file)(file);
155
+ if (typeof loaded.appendPluginRecord !== 'function')
156
+ return null;
157
+ return loaded.appendPluginRecord;
158
+ }
159
+ catch {
160
+ return null;
161
+ }
162
+ }
163
+ function sessionModuleFile(session) {
164
+ const getter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(session), 'seq')?.get;
165
+ if (typeof getter !== 'function')
166
+ return null;
167
+ const previous = Error.prepareStackTrace;
168
+ Error.prepareStackTrace = (_error, sites) => sites;
169
+ let file = null;
170
+ try {
171
+ getter.call(new Proxy(Object.create(Object.getPrototypeOf(session)), {
172
+ get() {
173
+ throw new Error('session-module');
174
+ },
175
+ }));
176
+ }
177
+ catch (error) {
178
+ const sites = error.stack;
179
+ if (!Array.isArray(sites))
180
+ return file;
181
+ const owner = sites.find(site => site.getFileName()?.includes('dsh-session'));
182
+ const found = owner?.getFileName();
183
+ if (typeof found === 'string')
184
+ file = found.startsWith('file:') ? fileURLToPath(found) : found;
185
+ }
186
+ finally {
187
+ Error.prepareStackTrace = previous;
188
+ }
189
+ return file;
190
+ }
191
+ function logAppendFailure(ctx, error) {
192
+ if (appendFailureLogged || !(error instanceof TypeError))
193
+ return;
194
+ appendFailureLogged = true;
195
+ const message = error.message;
196
+ ctx.logger?.warn?.('session-foundations: card record was not appended: %s', message);
197
+ }
198
+ function liveSession(ctx, sessionId) {
199
+ try {
200
+ const session = ctx.sessions?.get?.(sessionId);
201
+ if (session)
202
+ return session;
203
+ }
204
+ catch {
205
+ /* not entered */
206
+ }
207
+ try {
208
+ const agent = ctx.agents?.get?.(sessionId);
209
+ if (agent?.session)
210
+ return agent.session;
211
+ }
212
+ catch {
213
+ /* not entered */
214
+ }
215
+ return null;
216
+ }
package/dist/context.js CHANGED
@@ -18,11 +18,13 @@ export const CHAT = [
18
18
  'A user message that arrives after an assistant message in the same turn is an interjection. The in-flight step is not cancelled. On the next step, add only what the new message asks, in a few sentences. "Do not drop the earlier text" means leave the earlier message where it is, not paste it into the new reply.',
19
19
  'Example, same turn. Step 1 already delivered the recursive DNS path. The user then interjects: add the difference between recursive and iterative resolution, and do not drop the recursive path. Step 2 is only the difference: recursive resolution means you run the whole lookup for the client; iterative resolution means you say whom to ask next. A recursive resolver is recursive toward the client and iterative toward the root, the TLD, and the authoritative servers. Step 2 does not repeat the path.',
20
20
  'When the user did not ask you to look something up, edit files, dispatch work, or contact another bot, do not call tools and do not mention steps or system state.',
21
- 'Default: hand every non-trivial task to a worker with foundations_dispatch. The main session plans, estimates budget, waits for ticket notices, reviews results, and replies to the user.',
21
+ 'Default: hand every non-trivial task to a worker with foundations_dispatch. The main session plans, waits for ticket notices, grants budget when a worker asks, reviews results, and replies to the user.',
22
22
  'A visual design, HTML preview, or page mock goes to foundations_dispatch_canvas. Do not use foundations_dispatch, write, or edit in the main session to build that preview.',
23
+ 'When the user message contains [canvas-target canvas=… rev=… path=… tag=…] blocks, call foundations_dispatch_canvas with that canvasId and copy those blocks into the briefing unchanged. The worker changes only those nodes.',
24
+ 'When a reply names a canvas, write a markdown link [label](canvas:cnv_…@revision/page.html#anchor). revision, page, and anchor may be omitted. page is an HTML file in that canvas, such as tea.html. anchor is an element id on that page. A different canvas uses its own id. A revision of the same canvas is @N.',
23
25
  'Direct execution is allowed only for a short reply that needs no tools; a tiny read-only check (one or two reads) needed to write a briefing or answer a simple question; or when the user clearly asked you to do the work yourself in this session and no worker owns that work. Do not run a multi-step shell, edit, or write chain in the main session without one of those exceptions. A task already handed to a worker stays with that worker.',
24
26
  "Prefer foundations_dispatch over bash, write, edit, and any official subagent tool for this bot's work. Official subagent is not the ticket worker.",
25
- 'If an unfinished ticket can take the new work, call foundations_redirect and reuse that worker. Independent tasks may run in parallel up to the host slot cap. Dependent steps stay serial on the same ticket. Workers share the workspace: state file boundaries in the briefing, or run those tasks one after another. There is no filesystem isolation between workers.',
27
+ 'If an unfinished ticket can take the new work, call foundations_redirect and reuse that worker. foundations_redirect queues a later turn and does not stop the worker. When a running worker is on the wrong path, call foundations_steer: that aborts the current turn and the text is what it does next. Independent tasks may run in parallel up to the host slot cap. Dependent steps stay serial on the same ticket. Workers share the workspace: state file boundaries in the briefing, or run those tasks one after another. There is no filesystem isolation between workers.',
26
28
  '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.',
27
29
  "Workers usually have file tools (read, write, edit, working_directory), foundations_report, and this bot's memory tools. 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.",
28
30
  "A derived worker already receives this bot's persona, facts, working state, and skill index, and its memory tools read and write this same store. Do not paste that memory into the briefing.",
@@ -299,7 +301,7 @@ export function renderTickets(rows) {
299
301
  '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.',
300
302
  'accepted can mean the ticket is waiting for an execution slot. enqueued means it entered the execution queue. started is the only status that means work has begun. needs_user means the worker is waiting for the user and does not occupy a running slot.',
301
303
  'A failed ticket that already had a published result is not an undelivered result. Ignore reports whose ticket, attempt, fencing token, or briefing revision does not match the current ticket.',
302
- `When you open a ticket, set foundations_dispatch budget to one standard slice: wallMs ${DEFAULT_WORK_BUDGET.workerWallMs}, maxTokens ${DEFAULT_WORK_BUDGET.workerMaxTokens}. Do not estimate a smaller budget. When the worker uses that up, the notice asks you to call foundations_grant with another full slice. Grant every time, with no limit on the number of grants. Do not call the ticket a failure before that grant. If the ticket fails, tell the user and stop. Do not take over the unfinished task.`,
304
+ `The host assigns the opening budget: one standard slice, wallMs ${DEFAULT_WORK_BUDGET.workerWallMs}, maxTokens ${DEFAULT_WORK_BUDGET.workerMaxTokens}. Do not pass a budget on foundations_dispatch. When the worker uses that up, the notice asks you to call foundations_grant with another full slice. Grant every time, with no limit on the number of grants. Do not call the ticket a failure before that grant. If the ticket fails, tell the user and stop. Do not take over the unfinished task.`,
303
305
  ...lines,
304
306
  ].join('\n');
305
307
  }
@@ -0,0 +1,54 @@
1
+ /** Sessions whose turns must not start. A failed delete keeps the fence. */
2
+ const fenced = new Set();
3
+ export function isFenced(sessionId) {
4
+ return sessionId !== '' && fenced.has(sessionId);
5
+ }
6
+ export function fence(sessionIds) {
7
+ for (const id of sessionIds)
8
+ if (id !== '')
9
+ fenced.add(id);
10
+ }
11
+ export function unfence(sessionIds) {
12
+ for (const id of sessionIds)
13
+ fenced.delete(id);
14
+ }
15
+ const jobs = new Map();
16
+ /**
17
+ * Start a delete, or join the one already running for this bot.
18
+ * A finished job is replayed. A failed job starts again.
19
+ * The run is deferred so the caller can listen before the first event.
20
+ */
21
+ export function beginDelete(ownerId, run) {
22
+ const existing = jobs.get(ownerId);
23
+ if (existing && existing.latest.phase !== 'error' && existing.latest.phase !== 'done')
24
+ return existing;
25
+ if (existing?.latest.phase === 'done')
26
+ return existing;
27
+ const listeners = existing?.listeners ?? new Set();
28
+ const job = {
29
+ ownerId,
30
+ latest: { phase: 'fence', percent: 10 },
31
+ listeners,
32
+ promise: Promise.resolve(),
33
+ listen(listener) {
34
+ listeners.add(listener);
35
+ },
36
+ unlisten(listener) {
37
+ listeners.delete(listener);
38
+ },
39
+ };
40
+ const publish = (event) => {
41
+ job.latest = event;
42
+ for (const listener of listeners)
43
+ listener(event);
44
+ };
45
+ job.promise = Promise.resolve().then(() => run(publish).catch((error) => {
46
+ const message = error instanceof Error ? error.message : 'delete failed';
47
+ publish({ phase: 'error', percent: job.latest.percent, error: message });
48
+ }));
49
+ jobs.set(ownerId, job);
50
+ return job;
51
+ }
52
+ export function deleteStatus(ownerId) {
53
+ return jobs.get(ownerId)?.latest ?? null;
54
+ }