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

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 (160) hide show
  1. package/README.md +109 -1
  2. package/client.js +646 -621
  3. package/dist/approvals.js +160 -0
  4. package/dist/authorization.js +225 -0
  5. package/dist/canvas-http.js +248 -0
  6. package/dist/canvas-skills.js +56 -0
  7. package/dist/canvas-store.js +794 -0
  8. package/dist/canvas-tools.js +211 -0
  9. package/dist/cli.js +32 -12
  10. package/dist/context.js +60 -17
  11. package/dist/cron.js +1 -1
  12. package/dist/cua-access.js +79 -0
  13. package/dist/desk.js +314 -37
  14. package/dist/engine.js +178 -84
  15. package/dist/fs-safe.js +1 -1
  16. package/dist/host.js +1 -0
  17. package/dist/http-plugin.js +14 -4
  18. package/dist/http.js +402 -85
  19. package/dist/inbox.js +51 -40
  20. package/dist/index.js +201 -47
  21. package/dist/live-diff.js +3 -1
  22. package/dist/live-snapshot.js +2 -13
  23. package/dist/log/canonical.js +37 -0
  24. package/dist/log/plan.js +62 -0
  25. package/dist/log/routes.js +144 -0
  26. package/dist/log/snapshot-service.js +76 -0
  27. package/dist/log/source.js +173 -0
  28. package/dist/memory-catalog.js +798 -0
  29. package/dist/permissions.js +86 -0
  30. package/dist/provision.js +2 -0
  31. package/dist/questions.js +407 -0
  32. package/dist/runtime-registry.js +4 -4
  33. package/dist/session-files.js +2 -2
  34. package/dist/session-previews.js +5 -1
  35. package/dist/store.js +20 -5
  36. package/dist/tools.js +150 -32
  37. package/dist/triggers.js +83 -39
  38. package/dist/work-admit.js +222 -25
  39. package/dist/work-child.js +17 -9
  40. package/dist/work-http.js +52 -2
  41. package/dist/work-ledger.js +256 -16
  42. package/dist/work-mock-host.js +9 -6
  43. package/dist/work-mock.js +29 -19
  44. package/dist/work-tickets.js +423 -96
  45. package/dist/work-tools.js +43 -6
  46. package/dist/work-worker.js +1033 -207
  47. package/dist/workspace-files.js +319 -0
  48. package/dist/workspace-image.js +91 -0
  49. package/fixtures/mock-llm.mjs +17 -2
  50. package/package.json +16 -5
  51. package/public/assets/SourceEditor-CJwK846Z.css +1 -0
  52. package/public/assets/SourceEditor-uu0G7jsM.js +669 -0
  53. package/public/assets/abap-CRCWOmpq.js +1 -0
  54. package/public/assets/apex-DnsZk_dE.js +1 -0
  55. package/public/assets/azcli-1IWB1ccx.js +1 -0
  56. package/public/assets/bat-DPkNLes8.js +1 -0
  57. package/public/assets/bicep-Corcdgou.js +2 -0
  58. package/public/assets/cameligo-CGrWLZr3.js +1 -0
  59. package/public/assets/clojure-D9WOWImG.js +1 -0
  60. package/public/assets/codicon-DCmgc-ay.ttf +0 -0
  61. package/public/assets/coffee-B7EJu28W.js +1 -0
  62. package/public/assets/cpp-SEyurbux.js +1 -0
  63. package/public/assets/csharp-BoL64M5l.js +1 -0
  64. package/public/assets/csp-C46ZqvIl.js +1 -0
  65. package/public/assets/css-DQU6DXDx.js +3 -0
  66. package/public/assets/css.worker-DYpkewsP.js +79 -0
  67. package/public/assets/cssMode-C5DAFF5H.js +4 -0
  68. package/public/assets/cypher-D84EuPTj.js +1 -0
  69. package/public/assets/dart-D8lhlL1r.js +1 -0
  70. package/public/assets/dockerfile-DLk6rpji.js +1 -0
  71. package/public/assets/ecl-BO6FnfXk.js +1 -0
  72. package/public/assets/editor.worker-B4pQIWZD.js +12 -0
  73. package/public/assets/elixir-BRjLKONM.js +1 -0
  74. package/public/assets/flow9-Cac8vKd7.js +1 -0
  75. package/public/assets/freemarker2-DExNwSiZ.js +3 -0
  76. package/public/assets/fsharp-fd1GTHhf.js +1 -0
  77. package/public/assets/go-O9LJTZXk.js +1 -0
  78. package/public/assets/graphql-LQdxqEYJ.js +1 -0
  79. package/public/assets/handlebars-BK7YAvpQ.js +1 -0
  80. package/public/assets/hcl-DxDQ3s82.js +1 -0
  81. package/public/assets/html-CdDm_zae.js +1 -0
  82. package/public/assets/html.worker-tnXziJOq.js +456 -0
  83. package/public/assets/htmlMode-CLdn9oa1.js +4 -0
  84. package/public/assets/index-BB-QDSf2.css +1 -0
  85. package/public/assets/index-CsX-_qbo.js +62 -0
  86. package/public/assets/ini-BvajGCUy.js +1 -0
  87. package/public/assets/java-SYsfObOQ.js +1 -0
  88. package/public/assets/javascript-mLl83_3W.js +1 -0
  89. package/public/assets/json.worker-aFakAbRR.js +44 -0
  90. package/public/assets/jsonMode-B1-bihFd.js +10 -0
  91. package/public/assets/julia-DQXNmw_w.js +1 -0
  92. package/public/assets/kotlin-qQ0MG-9I.js +1 -0
  93. package/public/assets/less-GGFNNJHn.js +2 -0
  94. package/public/assets/lexon-Canl7DCW.js +1 -0
  95. package/public/assets/liquid-Cv8m0HUb.js +1 -0
  96. package/public/assets/lua-D28Ae8-K.js +1 -0
  97. package/public/assets/m3-DPitgjJI.js +1 -0
  98. package/public/assets/markdown-B811l8j2.js +1 -0
  99. package/public/assets/mdx-Q12b91rL.js +1 -0
  100. package/public/assets/mips-CdjsipkG.js +1 -0
  101. package/public/assets/msdax-CYqgjx_P.js +1 -0
  102. package/public/assets/mysql-BHd6q0vd.js +1 -0
  103. package/public/assets/objective-c-B1aVtJYH.js +1 -0
  104. package/public/assets/pascal-BhNW15KB.js +1 -0
  105. package/public/assets/pascaligo-5jv8CcQD.js +1 -0
  106. package/public/assets/perl-DlYyT36c.js +1 -0
  107. package/public/assets/pgsql-Dy0bjov7.js +1 -0
  108. package/public/assets/php-120yhfDK.js +1 -0
  109. package/public/assets/pla-CjnFlu4u.js +1 -0
  110. package/public/assets/postiats-CQpG440k.js +1 -0
  111. package/public/assets/powerquery-DdJtto1Z.js +1 -0
  112. package/public/assets/powershell-Bu_VLpJB.js +1 -0
  113. package/public/assets/protobuf-IBS6jZEB.js +2 -0
  114. package/public/assets/pug-kFxLfcjb.js +1 -0
  115. package/public/assets/python-Kda811W0.js +1 -0
  116. package/public/assets/qsharp-q7JyzKFN.js +1 -0
  117. package/public/assets/r-BIFz-_sK.js +1 -0
  118. package/public/assets/razor-CRuCpdOW.js +1 -0
  119. package/public/assets/redis-CHOsPHWR.js +1 -0
  120. package/public/assets/redshift-CBifECDb.js +1 -0
  121. package/public/assets/restructuredtext-CghPJEOS.js +1 -0
  122. package/public/assets/ruby-CYWGW-b1.js +1 -0
  123. package/public/assets/rust-DMDD0SHb.js +1 -0
  124. package/public/assets/sb-BYAiYHFx.js +1 -0
  125. package/public/assets/scala-Bqvq8jcR.js +1 -0
  126. package/public/assets/scheme-Dhb-2j9p.js +1 -0
  127. package/public/assets/scss-CTwUZ5N7.js +3 -0
  128. package/public/assets/shell-CsDZo4DB.js +1 -0
  129. package/public/assets/solidity-CME5AdoB.js +1 -0
  130. package/public/assets/sophia-RYC1BQQz.js +1 -0
  131. package/public/assets/sparql-KEyrF7De.js +1 -0
  132. package/public/assets/sql-BdTr02Mf.js +1 -0
  133. package/public/assets/st-C7iG7M4S.js +1 -0
  134. package/public/assets/swift-D7IUmUK8.js +1 -0
  135. package/public/assets/systemverilog-DgMryOEJ.js +1 -0
  136. package/public/assets/tcl-PloMZuKG.js +1 -0
  137. package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
  138. package/public/assets/tsMode-BGHcz-M3.js +11 -0
  139. package/public/assets/twig-BfRIq3la.js +1 -0
  140. package/public/assets/typescript-Db1e0DCT.js +1 -0
  141. package/public/assets/typespec-CzxlYoT_.js +1 -0
  142. package/public/assets/vb-BwAE3J76.js +1 -0
  143. package/public/assets/wgsl-B_1kOXbF.js +298 -0
  144. package/public/assets/xml-H3zzFmnd.js +1 -0
  145. package/public/assets/yaml-BQrKvmTF.js +1 -0
  146. package/public/index.html +2 -2
  147. package/skills/ui/baseline-ui/SKILL.md +85 -0
  148. package/skills/ui/bencium-innovative-ux-designer/SKILL.md +227 -0
  149. package/skills/ui/better-ui/SKILL.md +133 -0
  150. package/skills/ui/design-lab/SKILL.md +920 -0
  151. package/skills/ui/frontend-design/SKILL.md +71 -0
  152. package/skills/ui/impeccable/SKILL.md +93 -0
  153. package/skills/ui/interface-design/SKILL.md +320 -0
  154. package/skills/ui/sources.json +66 -0
  155. package/skills/ui/ui-design/SKILL.md +35 -0
  156. package/skills/ui/ui-skills-root/SKILL.md +59 -0
  157. package/skills/ui/visual-design-foundations/SKILL.md +318 -0
  158. package/skills/ui/web-design-guidelines/SKILL.md +39 -0
  159. package/public/assets/index-Be82iGwe.css +0 -1
  160. package/public/assets/index-ByU9a3Lh.js +0 -61
@@ -0,0 +1,211 @@
1
+ import { bindCanvasSkills } from "./canvas-skills.js";
2
+ import { CANVAS_MAX_FILE_BYTES } from "./canvas-store.js";
3
+ import { toolError } from "./errors.js";
4
+ const BRIEFING_MAX = 16000;
5
+ const OUTPUT = {
6
+ schema: {
7
+ type: 'object',
8
+ properties: { ok: { type: 'boolean' } },
9
+ required: ['ok'],
10
+ },
11
+ render(_args, value) {
12
+ return [{ type: 'text', text: JSON.stringify(value) }];
13
+ },
14
+ };
15
+ /**
16
+ * Canvas generation tools. The host shows one tool list to every session;
17
+ * execute rejects the main bot and any worker that does not own this canvas.
18
+ * A budget wait never comes through these tools, and they do not mark a preview failed.
19
+ */
20
+ export function canvasToolDefinitions(canvas, work, engine) {
21
+ 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.', {
23
+ type: 'object',
24
+ properties: {
25
+ 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
+ },
33
+ },
34
+ correlationId: { type: 'string' },
35
+ },
36
+ required: ['briefing'],
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.', {
39
+ type: 'object',
40
+ properties: {
41
+ files: {
42
+ type: 'array',
43
+ items: {
44
+ type: 'object',
45
+ properties: {
46
+ path: { type: 'string' },
47
+ type: { type: 'string' },
48
+ text: { type: 'string' },
49
+ body: { type: 'string' },
50
+ },
51
+ required: ['path', 'type'],
52
+ },
53
+ },
54
+ remove: { type: 'array', items: { type: 'string' } },
55
+ },
56
+ }, async (args, hostId) => {
57
+ const canvasId = ownedCanvas(canvas, work, engine, hostId);
58
+ if (typeof canvasId !== 'string')
59
+ return canvasId;
60
+ const files = decodeFiles(args.files);
61
+ if (!Array.isArray(files))
62
+ return files;
63
+ const remove = decodeRemove(args.remove);
64
+ if (!Array.isArray(remove))
65
+ return remove;
66
+ return canvas.writeDraft(canvasId, files, remove);
67
+ }),
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) => {
69
+ const canvasId = ownedCanvas(canvas, work, engine, hostId);
70
+ if (typeof canvasId !== 'string')
71
+ return canvasId;
72
+ return canvas.publishDraft(canvasId);
73
+ }),
74
+ ];
75
+ }
76
+ export function canvasBriefing(canvasId, request, skills) {
77
+ const catalog = skills.filter(id => id !== 'ui-design').join(', ');
78
+ const head = [
79
+ `Canvas preview ${canvasId}.`,
80
+ '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.',
83
+ 'The entry file is index.html. Output is static HTML and CSS plus local images and fonts.',
84
+ 'No script, SVG, iframe, external URL, data URL, or inline event handler.',
85
+ 'Load foundations_skill_load for ui-design before writing. Catalog skills are taste only and cannot override this contract.',
86
+ catalog ? `Catalog skills on this bot: ${catalog}. Load at most two that match the request.` : '',
87
+ '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.',
89
+ 'User request:',
90
+ ]
91
+ .filter(line => line !== '')
92
+ .join('\n');
93
+ const room = BRIEFING_MAX - head.length - 1;
94
+ const body = room > 0 ? request.slice(0, room) : '';
95
+ return `${head}\n${body}`.slice(0, BRIEFING_MAX);
96
+ }
97
+ async function dispatchCanvas(canvas, work, engine, hostId, args) {
98
+ if (!engine.isBot(hostId))
99
+ return toolError('FORBIDDEN', 'Only the main bot can open a canvas worker.');
100
+ const briefing = typeof args.briefing === 'string' ? args.briefing.trim() : '';
101
+ if (briefing.length < 1 || briefing.length > 12000)
102
+ return toolError('VALIDATION', 'briefing is required.');
103
+ const key = args.idempotencyKey;
104
+ if (key != null && (typeof key !== 'string' || key.length < 8 || key.length > 128))
105
+ return toolError('VALIDATION', 'idempotencyKey is not allowed.');
106
+ const title = briefing.split('\n')[0]?.trim().slice(0, 80) ?? '';
107
+ let canvasId = typeof key === 'string' ? canvas.findIdempotent(hostId, key) : null;
108
+ if (!canvasId) {
109
+ const created = canvas.create({
110
+ sessionId: hostId,
111
+ title,
112
+ createdBy: 'bot',
113
+ idempotencyKey: typeof key === 'string' ? key : null,
114
+ });
115
+ if (created.ok === false)
116
+ return created;
117
+ canvasId = created.canvas?.id;
118
+ }
119
+ if (typeof canvasId !== 'string')
120
+ return toolError('STORE_FAILURE', 'The canvas was not created.');
121
+ let skills = [];
122
+ try {
123
+ skills = bindCanvasSkills(engine, hostId).bound;
124
+ }
125
+ catch (error) {
126
+ return toolError('STORE_FAILURE', error instanceof Error ? error.message : 'Canvas skills could not be bound.');
127
+ }
128
+ const forwarded = {
129
+ briefing: canvasBriefing(canvasId, briefing, skills),
130
+ };
131
+ if (typeof key === 'string')
132
+ forwarded.idempotencyKey = key;
133
+ if (args.budget != null)
134
+ forwarded.budget = args.budget;
135
+ if (typeof args.correlationId === 'string')
136
+ forwarded.correlationId = args.correlationId;
137
+ const dispatched = await work.dispatch(hostId, forwarded);
138
+ if (dispatched.ok === true && typeof dispatched.ticketId === 'string')
139
+ canvas.attachTicket(canvasId, dispatched.ticketId);
140
+ return { ...dispatched, canvasId };
141
+ }
142
+ function ownedCanvas(canvas, work, engine, hostId) {
143
+ if (engine.isBot(hostId))
144
+ return toolError('FORBIDDEN', 'The main bot cannot write a canvas preview.');
145
+ const canvasId = canvas.canvasIdForTicket(work.ticketIdOf(hostId));
146
+ if (!canvasId)
147
+ return toolError('FORBIDDEN', 'Only the canvas worker for this preview can write it.');
148
+ return canvasId;
149
+ }
150
+ function decodeFiles(input) {
151
+ if (input == null)
152
+ return [];
153
+ if (!Array.isArray(input))
154
+ return toolError('VALIDATION', 'files are not allowed.');
155
+ const files = [];
156
+ for (const item of input) {
157
+ if (!item || typeof item !== 'object')
158
+ return toolError('VALIDATION', 'A canvas file is not allowed.');
159
+ const record = item;
160
+ if (typeof record.path !== 'string' || typeof record.type !== 'string')
161
+ return toolError('VALIDATION', 'A canvas file is not allowed.');
162
+ const text = record.text;
163
+ const body = record.body;
164
+ if (typeof text === 'string' && typeof body === 'string')
165
+ return toolError('VALIDATION', 'A canvas file has both text and body.');
166
+ if (typeof text === 'string') {
167
+ if (record.type !== 'text/html' && record.type !== 'text/css')
168
+ return toolError('VALIDATION', 'text is only for HTML and CSS.');
169
+ const bytes = Buffer.from(text, 'utf8');
170
+ if (bytes.length > CANVAS_MAX_FILE_BYTES)
171
+ return toolError('VALIDATION', `${record.path} exceeds the 1.5 MiB file cap.`);
172
+ files.push({ path: record.path, type: record.type, bytes });
173
+ continue;
174
+ }
175
+ if (typeof body === 'string') {
176
+ const packed = body.replace(/\s/g, '');
177
+ if (packed.length === 0 || packed.length > CANVAS_MAX_FILE_BYTES * 2 || !/^[A-Za-z0-9+/=]+$/.test(packed))
178
+ return toolError('VALIDATION', `${record.path} body is not base64.`);
179
+ files.push({ path: record.path, type: record.type, bytes: Buffer.from(packed, 'base64') });
180
+ continue;
181
+ }
182
+ return toolError('VALIDATION', 'A canvas file needs text or body.');
183
+ }
184
+ return files;
185
+ }
186
+ function decodeRemove(input) {
187
+ if (input == null)
188
+ return [];
189
+ if (!Array.isArray(input) || input.some(item => typeof item !== 'string'))
190
+ return toolError('VALIDATION', 'remove is not allowed.');
191
+ return input;
192
+ }
193
+ function tool(name, description, parameters, run) {
194
+ return {
195
+ name,
196
+ description,
197
+ parameters,
198
+ output: OUTPUT,
199
+ async execute(args, exec) {
200
+ const hostId = exec?.agent?.id;
201
+ if (typeof hostId !== 'string' || hostId === '')
202
+ return toolError('UNAVAILABLE', 'The host did not bind a sessionId.');
203
+ try {
204
+ return await run(args ?? {}, hostId);
205
+ }
206
+ catch (error) {
207
+ return toolError('STORE_FAILURE', error instanceof Error ? error.message : String(error));
208
+ }
209
+ },
210
+ };
211
+ }
package/dist/cli.js CHANGED
@@ -105,7 +105,7 @@ export async function run(argv, options = {}) {
105
105
  }
106
106
  else if (command === 'session' && action === 'bind') {
107
107
  const engine = openEngine();
108
- const binding = engine.bindPersona(required(flags, 'session'), flags.persona ? Number(flags.persona) : engine.latestPersona()?.id ?? null);
108
+ const binding = engine.bindPersona(required(flags, 'session'), flags.persona ? Number(flags.persona) : (engine.latestPersona()?.id ?? null));
109
109
  console.log(JSON.stringify({ ok: true, binding }, null, 2));
110
110
  engine.store.close();
111
111
  }
@@ -144,8 +144,12 @@ export async function run(argv, options = {}) {
144
144
  const sessionId = required(flags, 'session');
145
145
  engine.ensureSession(sessionId);
146
146
  console.log(JSON.stringify({
147
- facts: engine.store.db.prepare('SELECT id, status, revision, priority, content FROM facts WHERE session_id = ? ORDER BY id').all(sessionId),
148
- memories: engine.store.db.prepare('SELECT id, status, revision, title, content FROM memories WHERE session_id = ? ORDER BY id').all(sessionId),
147
+ facts: engine.store.db
148
+ .prepare('SELECT id, status, revision, priority, content FROM facts WHERE session_id = ? ORDER BY id')
149
+ .all(sessionId),
150
+ memories: engine.store.db
151
+ .prepare('SELECT id, status, revision, title, content FROM memories WHERE session_id = ? ORDER BY id')
152
+ .all(sessionId),
149
153
  state: engine.statePayload(sessionId),
150
154
  }, null, 2));
151
155
  engine.store.close();
@@ -167,7 +171,9 @@ export async function run(argv, options = {}) {
167
171
  }
168
172
  else if (command === 'skill' && action === 'list') {
169
173
  const engine = openEngine();
170
- const rows = engine.store.db.prepare('SELECT * FROM skill_bindings WHERE session_id = ? ORDER BY skill_id').all(required(flags, 'session'));
174
+ const rows = engine.store.db
175
+ .prepare('SELECT * FROM skill_bindings WHERE session_id = ? ORDER BY skill_id')
176
+ .all(required(flags, 'session'));
171
177
  console.log(JSON.stringify({ ok: true, skills: rows }, null, 2));
172
178
  engine.store.close();
173
179
  }
@@ -183,19 +189,30 @@ export async function run(argv, options = {}) {
183
189
  }
184
190
  else if (command === 'message' && action === 'list') {
185
191
  const triggers = openTriggers();
186
- console.log(JSON.stringify({ ok: true, acl: triggers.listAcl(), deliveries: triggers.listDeliveries(flags.session ?? '', flags.correlation ?? '') }, null, 2));
192
+ console.log(JSON.stringify({
193
+ ok: true,
194
+ acl: triggers.listAcl(),
195
+ deliveries: triggers.listDeliveries(flags.session ?? '', flags.correlation ?? ''),
196
+ }, null, 2));
187
197
  triggersClose();
188
198
  }
189
199
  else if (command === 'work' && action === 'dispatch') {
190
200
  const engine = openEngine();
191
201
  const sessionId = required(flags, 'session');
192
202
  if (!engine.isBot(sessionId)) {
193
- console.log(JSON.stringify({ ok: false, code: 'FORBIDDEN', message: 'An ordinary session stays on one loop and cannot dispatch work.' }, null, 2));
203
+ console.log(JSON.stringify({
204
+ ok: false,
205
+ code: 'FORBIDDEN',
206
+ message: 'An ordinary session stays on one loop and cannot dispatch work.',
207
+ }, null, 2));
194
208
  engine.store.close();
195
209
  process.exitCode = 1;
196
210
  }
197
211
  else {
198
- const work = createWorkRuntime(engine.store, engine, { resident: false, push: async () => ({ ok: false, ambiguous: true }) });
212
+ const work = createWorkRuntime(engine.store, engine, {
213
+ resident: false,
214
+ push: async () => ({ ok: false, ambiguous: true }),
215
+ });
199
216
  const result = await work.dispatch(sessionId, {
200
217
  briefing: required(flags, 'text'),
201
218
  idempotencyKey: flags.key,
@@ -215,16 +232,19 @@ export async function run(argv, options = {}) {
215
232
  });
216
233
  console.log(JSON.stringify({
217
234
  ...result,
218
- ...('status' in result && result.status === 'intent' ? {
219
- queued: false,
220
- note: 'Only the intent was written. A resident DSH host reconciles it and then followup reaches the native inbox. This process will not execute after it exits.',
221
- } : {}),
235
+ ...('status' in result && result.status === 'intent'
236
+ ? {
237
+ queued: false,
238
+ note: 'Only the intent was written. A resident DSH host reconciles it and then followup reaches the native inbox. This process will not execute after it exits.',
239
+ }
240
+ : {}),
222
241
  }, null, 2));
223
242
  triggersClose();
224
243
  if (!result.ok)
225
244
  process.exitCode = 1;
226
245
  }
227
- else if (command === 'timer' && (action === 'add' || action === 'list' || action === 'pause' || action === 'resume' || action === 'delete')) {
246
+ else if (command === 'timer' &&
247
+ (action === 'add' || action === 'list' || action === 'pause' || action === 'resume' || action === 'delete')) {
228
248
  const triggers = openTriggers();
229
249
  if (action === 'add') {
230
250
  const result = triggers.addSchedule({
package/dist/context.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { sha256 } from "./fs-safe.js";
3
+ import { DEFAULT_WORK_BUDGET } from "./work-admit.js";
3
4
  export const RULES = [
4
5
  'The name written in the persona is your name. When asked what you are called, who you are, or how to address you, answer with that name only. Do not rename yourself DeepSeek, Harness, the host product, or a model id, and do not say you have no name.',
5
6
  'Facts marked as about the user describe the user. They are not your name and they are not your persona.',
@@ -12,11 +13,28 @@ export const RULES = [
12
13
  ].join('\n');
13
14
  export const CHAT = [
14
15
  'You are talking with the user. Finish this turn in the first person.',
15
- 'The latest user message is the current intent. If the previous sentence stopped halfway, answer the new one directly. Do not finish the old sentence.',
16
+ 'Keep each visible reply around 200 characters, in the language the user is using. A report, a long explanation, or any answer that would run past that is a file: use write, then reply with the path and one or two sentences. That single write is the reply itself, not a task to dispatch. Stay in the chat only when that same message explicitly asks for a longer reply and forbids tools.',
17
+ 'The latest user message is the current intent. If the previous assistant message was interrupted, answer the new one and do not finish the old sentence. If that earlier message finished, it is already on screen: do not write it again.',
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
+ '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.',
16
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.',
17
- 'When the work will take a while, say in one sentence that it is going to the background, then call foundations_dispatch. Do not finish that long job in the main session.',
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.',
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
+ '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
+ "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.',
26
+ '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
+ "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
+ "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.",
29
+ 'foundations_dispatch may return status=accepted (received, and possibly waiting for a slot), status=enqueued (placed on the execution queue, not started), or a BUDGET error when both the slot cap and the queue cap are full. accepted or enqueued is not completion and not started. Say in one sentence that the work is in the background, then end the turn. Do not sleep, poll, or keep calling tools while waiting.',
30
+ "When the user asks how an unfinished ticket is progressing, call foundations_worker_history once and answer from that excerpt. Do not call it in a loop and do not sleep. The excerpt is not a result: do not call foundations_publish from it, and do not read, edit, or build the worker's files or finish the task. If the excerpt is empty, say there is no execution record yet.",
31
+ "A ticket notice is not something the user said. On progress or artifact notices, do not take over the work and do not poll. On a question, answer or call foundations_supply. On a budget-extension notice, call foundations_grant with enough to exceed current usage, then end the turn. You cannot refuse a worker budget. Do not take over the worker's task: do not inspect, edit, or build its files, and do not run its commands. On a successful result, call foundations_publish, then write the user-visible reply. On a failed result, tell the user the reason and stop. Do not take over the task. Do not treat a later failed status after a published result as if the worker never delivered. Do not invent a final answer or accept the work on the user's behalf before a result. Do not call foundations_retry unless the user explicitly asks.",
32
+ 'If dispatch returns BUDGET, do not start the job yourself and do not keep opening tickets to bypass the cap. Tell the user the host is at its limit.',
33
+ `On a budget-wait notice, call foundations_grant and add at least one standard slice (${DEFAULT_WORK_BUDGET.workerMaxTokens} tokens and ${DEFAULT_WORK_BUDGET.workerWallMs} ms), or more when current usage is already past granted plus that slice. Grant every time the notice arrives. There is no limit on how many grants and no cumulative ceiling. Do not refuse because earlier grants were many or large. A grant that does not exceed current usage leaves the worker paused, so do not add a token or two. A terminal failed or cancelled ticket cannot be revived by a grant. Do not foundations_dispatch a replacement ticket for the same work. Do not cancel unless the user asks to stop.`,
18
34
  ].join('\n');
19
35
  export const DEFAULT_WINDOW = 128000;
36
+ /** Shown only in a worker prompt, after the shared memory rules. */
37
+ export const WORKER_MEMORY = 'You are a worker of the main bot. The persona, facts, memories, working state, and skills in this prompt belong to that main bot. foundations_recall, foundations_memory_list, foundations_memory_read, foundations_remember, foundations_correct, foundations_forget, foundations_state_update, and foundations_skill_load read and write that same store. They are not a private copy.';
20
38
  /**
21
39
  * Unmeasured character/4 estimate. Real provider windows are not assumed.
22
40
  * @param {string} text
@@ -47,9 +65,18 @@ export function budgets(window) {
47
65
  * @param {string} sessionId
48
66
  * @param {number} [window]
49
67
  */
50
- export function renderSession(engine, sessionId, window = DEFAULT_WINDOW) {
51
- const binding = engine.ensureSession(sessionId);
52
- const view = engine.viewForTurn(sessionId);
68
+ export function renderSession(engine, sessionId, window = DEFAULT_WINDOW, options = {}) {
69
+ const persist = options.persist !== false;
70
+ const live = persist ? null : engine.liveSelection(sessionId);
71
+ const binding = persist ? engine.ensureSession(sessionId) : live.binding;
72
+ const view = persist
73
+ ? engine.viewForTurn(sessionId)
74
+ : {
75
+ revision: binding.last_view_revision ?? 0,
76
+ snapshot_hash: null,
77
+ presence: 'unknown',
78
+ selected: live.selected,
79
+ };
53
80
  const cap = budgets(window);
54
81
  const selected = view.selected;
55
82
  const persona = selected.personaVersionId == null ? null : engine.persona(selected.personaVersionId);
@@ -67,7 +94,7 @@ export function renderSession(engine, sessionId, window = DEFAULT_WINDOW) {
67
94
  if (soul && estimateTokens(soul) > cap.soul.hard)
68
95
  soulCode = 'BUDGET_OVERFLOW';
69
96
  if (soulCode === 'HASH_MISMATCH' || soulCode === 'BUDGET_OVERFLOW') {
70
- if (binding.status !== 'error')
97
+ if (persist && binding.status !== 'error')
71
98
  engine.markError(sessionId, soulCode);
72
99
  soul = '';
73
100
  }
@@ -98,14 +125,18 @@ export function renderSession(engine, sessionId, window = DEFAULT_WINDOW) {
98
125
  if (estimateTokens(stateText) > cap.state.soft)
99
126
  stateText = renderState(frozenState, true);
100
127
  const skills = Array.isArray(selected.skills) ? selected.skills : [];
101
- let skillText = skills.filter(skill => skill.enabled && !skill.revoked).map(skill => (`- ${skill.skill_id} ${skill.version} ${skill.scope} ${skill.summary ?? ''}`.trimEnd())).join('\n');
128
+ let skillText = skills
129
+ .filter((skill) => skill.enabled && !skill.revoked)
130
+ .map((skill) => `- ${skill.skill_id} ${skill.version} ${skill.scope} ${skill.summary ?? ''}`.trimEnd())
131
+ .join('\n');
102
132
  if (estimateTokens(skillText) > cap.skills.soft) {
103
- skillText = skills.filter(skill => skill.enabled && !skill.revoked).map(skill => (`- ${skill.skill_id} ${skill.version} enabled`)).join('\n');
133
+ skillText = skills
134
+ .filter((skill) => skill.enabled && !skill.revoked)
135
+ .map((skill) => `- ${skill.skill_id} ${skill.version} enabled`)
136
+ .join('\n');
104
137
  }
105
138
  const revoked = engine.revokedSkills(sessionId);
106
- const notice = revoked.length === 0
107
- ? ''
108
- : `Revoked. Later loads will refuse: ${revoked.map(skill => skill.skill_id).join(', ')}`;
139
+ const notice = revoked.length === 0 ? '' : `Revoked. Later loads will refuse: ${revoked.map(skill => skill.skill_id).join(', ')}`;
109
140
  const blocks = {
110
141
  chat: CHAT,
111
142
  soul: soulCode
@@ -130,20 +161,27 @@ export function renderSession(engine, sessionId, window = DEFAULT_WINDOW) {
130
161
  'foundations:soul': blocks.soul,
131
162
  'foundations:chat': CHAT,
132
163
  'foundations:rules': RULES,
133
- 'foundations:user': blocks.user ? `[foundations:user]\nThese are facts about the user. They are not your name, and they are not your persona.\n${blocks.user}` : '',
134
- 'foundations:facts': blocks.facts ? `[foundations:facts]\nThese are also facts about the user, not your name.\n${blocks.facts}` : '',
164
+ 'foundations:user': blocks.user
165
+ ? `[foundations:user]\nThese are facts about the user. They are not your name, and they are not your persona.\n${blocks.user}`
166
+ : '',
167
+ 'foundations:facts': blocks.facts
168
+ ? `[foundations:facts]\nThese are also facts about the user, not your name.\n${blocks.facts}`
169
+ : '',
135
170
  'foundations:state': blocks.state ? `[foundations:state]\n${blocks.state}` : '',
136
171
  'foundations:skills': blocks.skills ? `[foundations:skills]\n${blocks.skills}` : '',
137
172
  'foundations:revocation': blocks.notice ? `[foundations:revocation]\n${blocks.notice}` : '',
138
173
  };
139
- const snapshotHash = sha256(Object.entries(rendered).map(([name, text]) => `${name}\n${text}`).join('\n'));
174
+ const snapshotHash = sha256(Object.entries(rendered)
175
+ .map(([name, text]) => `${name}\n${text}`)
176
+ .join('\n'));
140
177
  const previous = view.snapshot_hash;
141
178
  let presence = view.presence;
142
179
  if (previous === 'pending')
143
180
  presence = view.presence === 'needs_reinject' ? 'needs_reinject' : 'unknown';
144
181
  else if (previous !== snapshotHash)
145
182
  presence = 'unknown';
146
- engine.recordSnapshot(sessionId, view.revision, snapshotHash, presence);
183
+ if (persist)
184
+ engine.recordSnapshot(sessionId, view.revision, snapshotHash, presence);
147
185
  return {
148
186
  sessionId,
149
187
  viewRevision: view.revision,
@@ -181,7 +219,9 @@ export function frameSoul(soul) {
181
219
  const { name, body } = splitPersona(soul);
182
220
  if (name === '' && body === '')
183
221
  return '';
184
- const lines = ['The persona below is your identity. Enter this role in the first person and keep it for the whole conversation.'];
222
+ const lines = [
223
+ 'The persona below is your identity. Enter this role in the first person and keep it for the whole conversation.',
224
+ ];
185
225
  if (name !== '') {
186
226
  lines.push(`Your name is "${name}". This is your name, not the user's name, and not a nickname for the user.`);
187
227
  lines.push('When the user asks what you are called, who you are, or how to address you, answer with this name only. Do not say you have no name. Do not substitute DeepSeek, Harness, the host product name, or a model id.');
@@ -253,10 +293,13 @@ export function renderTickets(rows) {
253
293
  return [
254
294
  '[foundations:tickets]',
255
295
  'These are ticket summaries, not the execution transcript, and not a reply the user has already been given.',
296
+ 'Ticket summaries are not the execution record. To see how far a worker has gotten, call foundations_worker_history.',
256
297
  'accepted means received. enqueued means placed on the execution queue. started is the only status that means work has begun.',
257
298
  'A ticket notice is not something the user said. accepted is not enqueued, and enqueued is not started.',
258
299
  '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.',
259
- 'When you open a ticket, estimate wallMs and maxTokens for the size of the task and put them in the foundations_dispatch budget. When the worker uses up that time or those tokens, the notice asks you to call foundations_grant. Do not call the ticket a failure before that grant.',
300
+ '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
+ '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.`,
260
303
  ...lines,
261
304
  ].join('\n');
262
305
  }
package/dist/cron.js CHANGED
@@ -33,7 +33,7 @@ export function nextCron(expr, afterMs, timeZone) {
33
33
  const weekMatch = spec.weekday.has(parts.weekday);
34
34
  const dayStar = spec.day.size === 31;
35
35
  const weekStar = spec.weekday.size === 7;
36
- const dayOk = dayStar && weekStar ? true : dayStar ? weekMatch : weekStar ? dayMatch : (dayMatch || weekMatch);
36
+ const dayOk = dayStar && weekStar ? true : dayStar ? weekMatch : weekStar ? dayMatch : dayMatch || weekMatch;
37
37
  if (dayOk)
38
38
  return new Date(cursor).toISOString();
39
39
  }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Official Computer Use access controls, exposed only when `ctx.cuaAccess`
3
+ * is composed. Runtime app consent still uses the approval-intent card in
4
+ * the session; this surface manages system permissions and saved grants.
5
+ */
6
+ import { toolError } from "./errors.js";
7
+ const SYSTEM_PERMISSIONS = new Set(['accessibility', 'screenRecording']);
8
+ function service(ctx) {
9
+ return ctx.get?.('cuaAccess');
10
+ }
11
+ export async function cuaSnapshot(ctx, locale = 'en') {
12
+ const access = service(ctx);
13
+ if (!access)
14
+ return { available: false };
15
+ try {
16
+ const [systemStatus, applications, ptcConfiguration, applicationIcons] = await Promise.all([
17
+ typeof access.systemStatus === 'function' ? access.systemStatus() : null,
18
+ typeof access.applications === 'function' ? access.applications() : null,
19
+ typeof access.ptcConfiguration === 'function' ? access.ptcConfiguration() : null,
20
+ typeof access.applicationIcons === 'function' ? access.applicationIcons() : null,
21
+ ]);
22
+ return {
23
+ available: true,
24
+ locale,
25
+ systemStatus,
26
+ applications,
27
+ ptcConfiguration,
28
+ applicationIcons,
29
+ };
30
+ }
31
+ catch (error) {
32
+ const message = error instanceof Error ? error.message : 'Computer Use access could not be read.';
33
+ return { available: true, error: message };
34
+ }
35
+ }
36
+ export async function cuaAction(ctx, input) {
37
+ const access = service(ctx);
38
+ if (!access)
39
+ return toolError('UNAVAILABLE', 'Computer Use is not installed on this host.');
40
+ const locale = typeof input.locale === 'string' && input.locale !== '' ? input.locale : 'en';
41
+ const action = input.action;
42
+ try {
43
+ if (action === 'requestPermission') {
44
+ if (!SYSTEM_PERMISSIONS.has(String(input.permission))) {
45
+ return toolError('VALIDATION', 'A supported system permission is required.');
46
+ }
47
+ const systemStatus = await access.requestPermission(input.permission, locale);
48
+ return { ok: true, systemStatus };
49
+ }
50
+ if (action === 'openSettings') {
51
+ if (!SYSTEM_PERMISSIONS.has(String(input.permission))) {
52
+ return toolError('VALIDATION', 'A supported system permission is required.');
53
+ }
54
+ await access.openSettings(input.permission, locale);
55
+ return { ok: true };
56
+ }
57
+ if (action === 'revoke') {
58
+ if (typeof input.id !== 'string' || input.id === '')
59
+ return toolError('VALIDATION', 'An application id is required.');
60
+ await access.revoke(input.id);
61
+ return { ok: true };
62
+ }
63
+ if (action === 'retryApproval') {
64
+ if (typeof input.id !== 'string' || input.id === '')
65
+ return toolError('VALIDATION', 'An application id is required.');
66
+ await access.retryApproval(input.id);
67
+ return { ok: true };
68
+ }
69
+ if (action === 'enablePersistentPtc') {
70
+ await access.enablePersistentPtc();
71
+ return { ok: true };
72
+ }
73
+ return toolError('VALIDATION', 'An official Computer Use action is required.');
74
+ }
75
+ catch (error) {
76
+ const message = error instanceof Error ? error.message : 'The Computer Use action could not be completed.';
77
+ return toolError('UNAVAILABLE', message);
78
+ }
79
+ }