@thready-web/dsh-bot-plugin 0.1.0-beta.0 → 0.1.0-beta.10

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 (144) 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/cli.js +32 -12
  6. package/dist/context.js +59 -17
  7. package/dist/cron.js +1 -1
  8. package/dist/cua-access.js +79 -0
  9. package/dist/desk.js +314 -37
  10. package/dist/engine.js +178 -84
  11. package/dist/fs-safe.js +1 -1
  12. package/dist/host.js +1 -0
  13. package/dist/http-plugin.js +14 -4
  14. package/dist/http.js +383 -85
  15. package/dist/inbox.js +51 -40
  16. package/dist/index.js +190 -47
  17. package/dist/live-diff.js +3 -1
  18. package/dist/live-snapshot.js +2 -13
  19. package/dist/log/canonical.js +37 -0
  20. package/dist/log/plan.js +62 -0
  21. package/dist/log/routes.js +144 -0
  22. package/dist/log/snapshot-service.js +76 -0
  23. package/dist/log/source.js +173 -0
  24. package/dist/memory-catalog.js +798 -0
  25. package/dist/permissions.js +86 -0
  26. package/dist/provision.js +2 -0
  27. package/dist/questions.js +407 -0
  28. package/dist/runtime-registry.js +4 -4
  29. package/dist/session-files.js +2 -2
  30. package/dist/session-previews.js +5 -1
  31. package/dist/store.js +20 -5
  32. package/dist/tools.js +150 -32
  33. package/dist/triggers.js +83 -39
  34. package/dist/work-admit.js +222 -25
  35. package/dist/work-child.js +17 -9
  36. package/dist/work-http.js +33 -2
  37. package/dist/work-ledger.js +256 -16
  38. package/dist/work-mock-host.js +9 -6
  39. package/dist/work-mock.js +29 -19
  40. package/dist/work-tickets.js +423 -96
  41. package/dist/work-tools.js +43 -6
  42. package/dist/work-worker.js +1028 -207
  43. package/dist/workspace-files.js +319 -0
  44. package/dist/workspace-image.js +91 -0
  45. package/fixtures/mock-llm.mjs +17 -2
  46. package/package.json +15 -5
  47. package/public/assets/SourceEditor-BEQaScgR.js +669 -0
  48. package/public/assets/SourceEditor-CJwK846Z.css +1 -0
  49. package/public/assets/abap-CRCWOmpq.js +1 -0
  50. package/public/assets/apex-DnsZk_dE.js +1 -0
  51. package/public/assets/azcli-1IWB1ccx.js +1 -0
  52. package/public/assets/bat-DPkNLes8.js +1 -0
  53. package/public/assets/bicep-Corcdgou.js +2 -0
  54. package/public/assets/cameligo-CGrWLZr3.js +1 -0
  55. package/public/assets/clojure-D9WOWImG.js +1 -0
  56. package/public/assets/codicon-DCmgc-ay.ttf +0 -0
  57. package/public/assets/coffee-B7EJu28W.js +1 -0
  58. package/public/assets/cpp-SEyurbux.js +1 -0
  59. package/public/assets/csharp-BoL64M5l.js +1 -0
  60. package/public/assets/csp-C46ZqvIl.js +1 -0
  61. package/public/assets/css-DQU6DXDx.js +3 -0
  62. package/public/assets/css.worker-DYpkewsP.js +79 -0
  63. package/public/assets/cssMode-gpcjCFFS.js +4 -0
  64. package/public/assets/cypher-D84EuPTj.js +1 -0
  65. package/public/assets/dart-D8lhlL1r.js +1 -0
  66. package/public/assets/dockerfile-DLk6rpji.js +1 -0
  67. package/public/assets/ecl-BO6FnfXk.js +1 -0
  68. package/public/assets/editor.worker-B4pQIWZD.js +12 -0
  69. package/public/assets/elixir-BRjLKONM.js +1 -0
  70. package/public/assets/flow9-Cac8vKd7.js +1 -0
  71. package/public/assets/freemarker2-C1qemGIt.js +3 -0
  72. package/public/assets/fsharp-fd1GTHhf.js +1 -0
  73. package/public/assets/go-O9LJTZXk.js +1 -0
  74. package/public/assets/graphql-LQdxqEYJ.js +1 -0
  75. package/public/assets/handlebars-sZqIfAlP.js +1 -0
  76. package/public/assets/hcl-DxDQ3s82.js +1 -0
  77. package/public/assets/html-Bn1WXB8L.js +1 -0
  78. package/public/assets/html.worker-tnXziJOq.js +456 -0
  79. package/public/assets/htmlMode-CvQyXnaW.js +4 -0
  80. package/public/assets/index-DRNkUrer.css +1 -0
  81. package/public/assets/index-DhL5Kdlz.js +63 -0
  82. package/public/assets/ini-BvajGCUy.js +1 -0
  83. package/public/assets/java-SYsfObOQ.js +1 -0
  84. package/public/assets/javascript-Ox4Jg12j.js +1 -0
  85. package/public/assets/json.worker-aFakAbRR.js +44 -0
  86. package/public/assets/jsonMode-DMR7R2dQ.js +10 -0
  87. package/public/assets/julia-DQXNmw_w.js +1 -0
  88. package/public/assets/kotlin-qQ0MG-9I.js +1 -0
  89. package/public/assets/less-GGFNNJHn.js +2 -0
  90. package/public/assets/lexon-Canl7DCW.js +1 -0
  91. package/public/assets/liquid-B6HxtpBd.js +1 -0
  92. package/public/assets/lua-D28Ae8-K.js +1 -0
  93. package/public/assets/m3-DPitgjJI.js +1 -0
  94. package/public/assets/markdown-B811l8j2.js +1 -0
  95. package/public/assets/mdx--jDhmrXq.js +1 -0
  96. package/public/assets/mips-CdjsipkG.js +1 -0
  97. package/public/assets/msdax-CYqgjx_P.js +1 -0
  98. package/public/assets/mysql-BHd6q0vd.js +1 -0
  99. package/public/assets/objective-c-B1aVtJYH.js +1 -0
  100. package/public/assets/pascal-BhNW15KB.js +1 -0
  101. package/public/assets/pascaligo-5jv8CcQD.js +1 -0
  102. package/public/assets/perl-DlYyT36c.js +1 -0
  103. package/public/assets/pgsql-Dy0bjov7.js +1 -0
  104. package/public/assets/php-120yhfDK.js +1 -0
  105. package/public/assets/pla-CjnFlu4u.js +1 -0
  106. package/public/assets/postiats-CQpG440k.js +1 -0
  107. package/public/assets/powerquery-DdJtto1Z.js +1 -0
  108. package/public/assets/powershell-Bu_VLpJB.js +1 -0
  109. package/public/assets/protobuf-IBS6jZEB.js +2 -0
  110. package/public/assets/pug-kFxLfcjb.js +1 -0
  111. package/public/assets/python-YjG50skX.js +1 -0
  112. package/public/assets/qsharp-q7JyzKFN.js +1 -0
  113. package/public/assets/r-BIFz-_sK.js +1 -0
  114. package/public/assets/razor-CEcFE3UK.js +1 -0
  115. package/public/assets/redis-CHOsPHWR.js +1 -0
  116. package/public/assets/redshift-CBifECDb.js +1 -0
  117. package/public/assets/restructuredtext-CghPJEOS.js +1 -0
  118. package/public/assets/ruby-CYWGW-b1.js +1 -0
  119. package/public/assets/rust-DMDD0SHb.js +1 -0
  120. package/public/assets/sb-BYAiYHFx.js +1 -0
  121. package/public/assets/scala-Bqvq8jcR.js +1 -0
  122. package/public/assets/scheme-Dhb-2j9p.js +1 -0
  123. package/public/assets/scss-CTwUZ5N7.js +3 -0
  124. package/public/assets/shell-CsDZo4DB.js +1 -0
  125. package/public/assets/solidity-CME5AdoB.js +1 -0
  126. package/public/assets/sophia-RYC1BQQz.js +1 -0
  127. package/public/assets/sparql-KEyrF7De.js +1 -0
  128. package/public/assets/sql-BdTr02Mf.js +1 -0
  129. package/public/assets/st-C7iG7M4S.js +1 -0
  130. package/public/assets/swift-D7IUmUK8.js +1 -0
  131. package/public/assets/systemverilog-DgMryOEJ.js +1 -0
  132. package/public/assets/tcl-PloMZuKG.js +1 -0
  133. package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
  134. package/public/assets/tsMode-g4kTQl09.js +11 -0
  135. package/public/assets/twig-BfRIq3la.js +1 -0
  136. package/public/assets/typescript-CnHeFmPW.js +1 -0
  137. package/public/assets/typespec-CzxlYoT_.js +1 -0
  138. package/public/assets/vb-BwAE3J76.js +1 -0
  139. package/public/assets/wgsl-B_1kOXbF.js +298 -0
  140. package/public/assets/xml-BFXMY9nb.js +1 -0
  141. package/public/assets/yaml-DNm87nSf.js +1 -0
  142. package/public/index.html +2 -2
  143. package/public/assets/index-Be82iGwe.css +0 -1
  144. package/public/assets/index-ByU9a3Lh.js +0 -61
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Official tool-permission answerer for the desk UI.
3
+ *
4
+ * `approval/request` is a distinct waterfall from user-questions. This
5
+ * listener is prepended so typtert `$events` cannot intercept first. The
6
+ * workbench claims every request it can show; anything it cannot identify
7
+ * fails closed as `unavailable`. There is no always-allow on this card.
8
+ */
9
+ import { toolError } from "./errors.js";
10
+ const answerers = new Map();
11
+ export function publishApprovalAnswerer(dataDir, answerer) {
12
+ if (answerer)
13
+ answerers.set(dataDir, answerer);
14
+ else
15
+ answerers.delete(dataDir);
16
+ }
17
+ export function approvalAnswererFor(dataDir) {
18
+ return answerers.get(dataDir) ?? null;
19
+ }
20
+ export function approvalSessionIdOf(agent) {
21
+ if (!agent || typeof agent !== 'object')
22
+ return '';
23
+ if (typeof agent.session === 'string' && agent.session !== '')
24
+ return agent.session;
25
+ if (typeof agent.id === 'string' && agent.id !== '')
26
+ return agent.id;
27
+ return '';
28
+ }
29
+ function textOf(value) {
30
+ return typeof value === 'string' ? value : '';
31
+ }
32
+ function displayReasonOf(value) {
33
+ if (!value || typeof value !== 'object')
34
+ return undefined;
35
+ const en = textOf(value.en);
36
+ if (en === '')
37
+ return undefined;
38
+ const display = { en };
39
+ for (const [locale, message] of Object.entries(value)) {
40
+ if (typeof message === 'string' && message !== '')
41
+ display[locale] = message;
42
+ }
43
+ return display;
44
+ }
45
+ export function createApprovalAnswerer() {
46
+ const pending = new Set();
47
+ const settled = [];
48
+ let nextId = 1;
49
+ function detach(entry) {
50
+ if (!pending.has(entry))
51
+ return false;
52
+ pending.delete(entry);
53
+ if (entry.onAbort && entry.request.signal) {
54
+ entry.request.signal.removeEventListener('abort', entry.onAbort);
55
+ }
56
+ return true;
57
+ }
58
+ function remember(entry, outcome) {
59
+ settled.unshift({
60
+ requestId: entry.requestId,
61
+ sessionId: entry.sessionId,
62
+ toolName: entry.toolName,
63
+ callId: entry.callId,
64
+ reason: textOf(entry.request.reason),
65
+ displayReason: displayReasonOf(entry.request.displayReason),
66
+ state: outcome,
67
+ });
68
+ if (settled.length > 50)
69
+ settled.length = 50;
70
+ }
71
+ async function handle(request, _next) {
72
+ const sessionId = approvalSessionIdOf(request.agent);
73
+ const toolName = textOf(request.toolName);
74
+ if (sessionId === '' || toolName === '')
75
+ return 'unavailable';
76
+ return new Promise(resolve => {
77
+ const callId = textOf(request.callId);
78
+ const entry = {
79
+ requestId: `approval-${nextId++}`,
80
+ request,
81
+ sessionId,
82
+ toolName,
83
+ callId: callId === '' ? undefined : callId,
84
+ resolve,
85
+ };
86
+ const onAbort = () => {
87
+ if (!detach(entry))
88
+ return;
89
+ remember(entry, 'cancelled');
90
+ resolve('cancelled');
91
+ };
92
+ entry.onAbort = onAbort;
93
+ pending.add(entry);
94
+ if (request.signal?.aborted) {
95
+ onAbort();
96
+ return;
97
+ }
98
+ request.signal?.addEventListener('abort', onAbort, { once: true });
99
+ });
100
+ }
101
+ function submit(input) {
102
+ if (typeof input.sessionId !== 'string' || input.sessionId === '') {
103
+ return toolError('VALIDATION', 'sessionId is required.');
104
+ }
105
+ if (typeof input.requestId !== 'string' || input.requestId === '') {
106
+ return toolError('VALIDATION', 'requestId is required.');
107
+ }
108
+ if (input.outcome !== 'allowed-once' && input.outcome !== 'rejected') {
109
+ return toolError('VALIDATION', 'Tool approval only accepts allow-once or reject.');
110
+ }
111
+ const matches = [...pending].filter(entry => entry.sessionId === input.sessionId && entry.requestId === input.requestId);
112
+ if (matches.length > 1)
113
+ return toolError('CONFLICT', 'Multiple open approvals match this request.');
114
+ const entry = matches[0];
115
+ if (!entry)
116
+ return toolError('NOT_FOUND', 'No open tool-approval request matches this session.');
117
+ if (!detach(entry))
118
+ return toolError('CONFLICT', 'This approval was already answered.');
119
+ remember(entry, input.outcome);
120
+ entry.resolve(input.outcome);
121
+ return { ok: true, path: 'approval', outcome: input.outcome, requestId: entry.requestId };
122
+ }
123
+ function snapshot(sessionId) {
124
+ const open = [...pending]
125
+ .filter(entry => !sessionId || entry.sessionId === sessionId)
126
+ .map(entry => ({
127
+ requestId: entry.requestId,
128
+ sessionId: entry.sessionId,
129
+ toolName: entry.toolName,
130
+ callId: entry.callId,
131
+ reason: textOf(entry.request.reason),
132
+ displayReason: displayReasonOf(entry.request.displayReason),
133
+ state: 'open',
134
+ }));
135
+ const done = settled.filter(entry => !sessionId || entry.sessionId === sessionId);
136
+ return [...open, ...done];
137
+ }
138
+ function listen(ctx) {
139
+ const dispose = ctx.on?.('approval/request', handle, true);
140
+ return () => {
141
+ if (typeof dispose === 'function')
142
+ dispose();
143
+ for (const entry of [...pending]) {
144
+ if (!detach(entry))
145
+ continue;
146
+ remember(entry, 'unavailable');
147
+ entry.resolve('unavailable');
148
+ }
149
+ };
150
+ }
151
+ return {
152
+ listen,
153
+ handle,
154
+ submit,
155
+ snapshot,
156
+ pendingCount() {
157
+ return pending.size;
158
+ },
159
+ };
160
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Official `ctx.authorization` surface for the desk settings UI.
3
+ *
4
+ * Authorization is config-time, never part of the transcript or model
5
+ * context. The desk supplies the official interaction: notices, prompts,
6
+ * and cancel. Secret prompts are answered with the exact submitted value;
7
+ * the UI must not use a password input.
8
+ */
9
+ import { toolError } from "./errors.js";
10
+ class DeclinedError extends Error {
11
+ code = 'DECLINED';
12
+ constructor(message = 'The authorization prompt was declined.') {
13
+ super(message);
14
+ this.name = 'AuthorizationDeclinedError';
15
+ }
16
+ }
17
+ const controllers = new Map();
18
+ export function publishAuthorization(dataDir, controller) {
19
+ if (controller)
20
+ controllers.set(dataDir, controller);
21
+ else
22
+ controllers.delete(dataDir);
23
+ }
24
+ export function authorizationFor(dataDir) {
25
+ return controllers.get(dataDir) ?? null;
26
+ }
27
+ export function createAuthorizationController() {
28
+ const prompts = new Map();
29
+ const notices = [];
30
+ let host = null;
31
+ let nextId = 1;
32
+ let catalogRevision = 0;
33
+ const active = new Map();
34
+ function service() {
35
+ return host?.get?.('authorization');
36
+ }
37
+ function declined(message) {
38
+ const ctor = service()?.constructor?.AuthorizationDeclinedError;
39
+ if (typeof ctor === 'function') {
40
+ try {
41
+ return new ctor(message);
42
+ }
43
+ catch {
44
+ /* fall through */
45
+ }
46
+ }
47
+ const AuthorizationDeclinedError = service()?.AuthorizationDeclinedError;
48
+ if (typeof AuthorizationDeclinedError === 'function') {
49
+ try {
50
+ return new AuthorizationDeclinedError(message);
51
+ }
52
+ catch {
53
+ /* fall through */
54
+ }
55
+ }
56
+ return new DeclinedError(message);
57
+ }
58
+ function list() {
59
+ const entries = service()?.list?.();
60
+ if (!Array.isArray(entries))
61
+ return [];
62
+ return entries.flatMap(entry => {
63
+ if (!entry || typeof entry !== 'object')
64
+ return [];
65
+ const row = entry;
66
+ const methods = Array.isArray(row.methods)
67
+ ? row.methods.flatMap(method => {
68
+ if (!method || typeof method !== 'object')
69
+ return [];
70
+ const item = method;
71
+ if (typeof item.id !== 'string' || item.id === '')
72
+ return [];
73
+ return [
74
+ {
75
+ id: item.id,
76
+ label: typeof item.label === 'string' && item.label !== '' ? item.label : item.id,
77
+ },
78
+ ];
79
+ })
80
+ : [];
81
+ return [
82
+ {
83
+ key: row.key,
84
+ label: typeof row.label === 'string' ? row.label : '',
85
+ methods,
86
+ inFlight: row.inFlight === true,
87
+ },
88
+ ];
89
+ });
90
+ }
91
+ function snapshot(options = {}) {
92
+ return {
93
+ available: Boolean(service()),
94
+ ...(options.catalog === false ? { catalogRevision, inFlight: [...active.values()] } : { entries: list() }),
95
+ notices: [...notices],
96
+ prompts: [...prompts.values()].map(entry => entry.prompt),
97
+ };
98
+ }
99
+ async function begin(input) {
100
+ const auth = service();
101
+ if (!auth || typeof auth.begin !== 'function') {
102
+ return toolError('UNAVAILABLE', 'Official authorization is not composed on this host.');
103
+ }
104
+ if (input.key == null)
105
+ return toolError('VALIDATION', 'A credential key is required.');
106
+ const activeKey = Symbol();
107
+ active.set(activeKey, input.key);
108
+ catalogRevision++;
109
+ try {
110
+ const outcome = await auth.begin({
111
+ key: input.key,
112
+ method: typeof input.method === 'string' && input.method !== '' ? input.method : undefined,
113
+ interaction: {
114
+ notify(notice) {
115
+ const view = {
116
+ key: input.key,
117
+ message: typeof notice?.message === 'string' ? notice.message : '',
118
+ };
119
+ if (typeof notice?.url === 'string' && notice.url !== '')
120
+ view.url = notice.url;
121
+ if (typeof notice?.code === 'string' && notice.code !== '')
122
+ view.code = notice.code;
123
+ notices.push(view);
124
+ if (notices.length > 20)
125
+ notices.shift();
126
+ },
127
+ prompt(prompt) {
128
+ return new Promise((resolve, reject) => {
129
+ const kind = prompt?.kind === 'secret' || prompt?.kind === 'select' ? prompt.kind : 'text';
130
+ const view = {
131
+ promptId: `auth-${nextId++}`,
132
+ key: input.key,
133
+ kind,
134
+ message: typeof prompt?.message === 'string' ? prompt.message : '',
135
+ };
136
+ if (typeof prompt?.placeholder === 'string' && prompt.placeholder !== '') {
137
+ view.placeholder = prompt.placeholder;
138
+ }
139
+ if (kind === 'select' && Array.isArray(prompt?.options)) {
140
+ view.options = prompt.options.flatMap(option => {
141
+ if (!option || typeof option !== 'object')
142
+ return [];
143
+ const row = option;
144
+ if (typeof row.id !== 'string' || row.id === '')
145
+ return [];
146
+ const item = {
147
+ id: row.id,
148
+ label: typeof row.label === 'string' && row.label !== '' ? row.label : row.id,
149
+ };
150
+ if (typeof row.description === 'string' && row.description !== '')
151
+ item.description = row.description;
152
+ return [item];
153
+ });
154
+ }
155
+ prompts.set(view.promptId, { promptId: view.promptId, key: input.key, prompt: view, resolve, reject });
156
+ });
157
+ },
158
+ },
159
+ });
160
+ return { ok: true, outcome };
161
+ }
162
+ catch (error) {
163
+ const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
164
+ ? error.code
165
+ : 'UNAVAILABLE';
166
+ const message = error instanceof Error ? error.message : 'Authorization could not be started.';
167
+ if (code === 'DECLINED')
168
+ return { ok: true, outcome: { status: 'cancelled' } };
169
+ return toolError(code === 'NO_FLOW' || code === 'UNKNOWN_METHOD' || code === 'ALREADY_IN_FLIGHT' ? code : 'UNAVAILABLE', message);
170
+ }
171
+ finally {
172
+ active.delete(activeKey);
173
+ catalogRevision++;
174
+ }
175
+ }
176
+ function answer(input) {
177
+ if (typeof input.promptId !== 'string' || input.promptId === '') {
178
+ return toolError('VALIDATION', 'promptId is required.');
179
+ }
180
+ const entry = prompts.get(input.promptId);
181
+ if (!entry)
182
+ return toolError('NOT_FOUND', 'No open authorization prompt matches this request.');
183
+ prompts.delete(input.promptId);
184
+ if (input.declined) {
185
+ entry.reject(declined());
186
+ return { ok: true, path: 'declined' };
187
+ }
188
+ if (typeof input.value !== 'string')
189
+ return toolError('VALIDATION', 'A prompt answer is required.');
190
+ entry.resolve(input.value);
191
+ return { ok: true, path: 'answered' };
192
+ }
193
+ function cancel(input) {
194
+ const auth = service();
195
+ if (!auth || typeof auth.cancel !== 'function') {
196
+ return toolError('UNAVAILABLE', 'Official authorization is not composed on this host.');
197
+ }
198
+ if (input.key == null)
199
+ return toolError('VALIDATION', 'A credential key is required.');
200
+ for (const [id, entry] of [...prompts]) {
201
+ if (entry.key === input.key || JSON.stringify(entry.key) === JSON.stringify(input.key)) {
202
+ prompts.delete(id);
203
+ entry.reject(declined());
204
+ }
205
+ }
206
+ catalogRevision++;
207
+ auth.cancel(input.key);
208
+ return { ok: true, path: 'cancelled' };
209
+ }
210
+ function bind(ctx) {
211
+ host = ctx;
212
+ catalogRevision++;
213
+ return () => {
214
+ if (host === ctx)
215
+ host = null;
216
+ catalogRevision++;
217
+ active.clear();
218
+ for (const entry of [...prompts.values()]) {
219
+ prompts.delete(entry.promptId);
220
+ entry.reject(declined());
221
+ }
222
+ };
223
+ }
224
+ return { bind, list, snapshot, begin, answer, cancel };
225
+ }
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,27 @@ 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
+ '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.',
23
+ "Prefer foundations_dispatch over bash, write, edit, and any official subagent tool for this bot's work. Official subagent is not the ticket worker.",
24
+ '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.',
25
+ 'The host attaches recent main-session dialogue to the ticket, and the worker reads that log directly with no authorization prompt. Write the task in the briefing. Do not paste the transcript.',
26
+ "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.",
27
+ "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.",
28
+ '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.',
29
+ "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.",
30
+ "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.",
31
+ '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.',
32
+ `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
33
  ].join('\n');
19
34
  export const DEFAULT_WINDOW = 128000;
35
+ /** Shown only in a worker prompt, after the shared memory rules. */
36
+ 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
37
  /**
21
38
  * Unmeasured character/4 estimate. Real provider windows are not assumed.
22
39
  * @param {string} text
@@ -47,9 +64,18 @@ export function budgets(window) {
47
64
  * @param {string} sessionId
48
65
  * @param {number} [window]
49
66
  */
50
- export function renderSession(engine, sessionId, window = DEFAULT_WINDOW) {
51
- const binding = engine.ensureSession(sessionId);
52
- const view = engine.viewForTurn(sessionId);
67
+ export function renderSession(engine, sessionId, window = DEFAULT_WINDOW, options = {}) {
68
+ const persist = options.persist !== false;
69
+ const live = persist ? null : engine.liveSelection(sessionId);
70
+ const binding = persist ? engine.ensureSession(sessionId) : live.binding;
71
+ const view = persist
72
+ ? engine.viewForTurn(sessionId)
73
+ : {
74
+ revision: binding.last_view_revision ?? 0,
75
+ snapshot_hash: null,
76
+ presence: 'unknown',
77
+ selected: live.selected,
78
+ };
53
79
  const cap = budgets(window);
54
80
  const selected = view.selected;
55
81
  const persona = selected.personaVersionId == null ? null : engine.persona(selected.personaVersionId);
@@ -67,7 +93,7 @@ export function renderSession(engine, sessionId, window = DEFAULT_WINDOW) {
67
93
  if (soul && estimateTokens(soul) > cap.soul.hard)
68
94
  soulCode = 'BUDGET_OVERFLOW';
69
95
  if (soulCode === 'HASH_MISMATCH' || soulCode === 'BUDGET_OVERFLOW') {
70
- if (binding.status !== 'error')
96
+ if (persist && binding.status !== 'error')
71
97
  engine.markError(sessionId, soulCode);
72
98
  soul = '';
73
99
  }
@@ -98,14 +124,18 @@ export function renderSession(engine, sessionId, window = DEFAULT_WINDOW) {
98
124
  if (estimateTokens(stateText) > cap.state.soft)
99
125
  stateText = renderState(frozenState, true);
100
126
  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');
127
+ let skillText = skills
128
+ .filter((skill) => skill.enabled && !skill.revoked)
129
+ .map((skill) => `- ${skill.skill_id} ${skill.version} ${skill.scope} ${skill.summary ?? ''}`.trimEnd())
130
+ .join('\n');
102
131
  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');
132
+ skillText = skills
133
+ .filter((skill) => skill.enabled && !skill.revoked)
134
+ .map((skill) => `- ${skill.skill_id} ${skill.version} enabled`)
135
+ .join('\n');
104
136
  }
105
137
  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(', ')}`;
138
+ const notice = revoked.length === 0 ? '' : `Revoked. Later loads will refuse: ${revoked.map(skill => skill.skill_id).join(', ')}`;
109
139
  const blocks = {
110
140
  chat: CHAT,
111
141
  soul: soulCode
@@ -130,20 +160,27 @@ export function renderSession(engine, sessionId, window = DEFAULT_WINDOW) {
130
160
  'foundations:soul': blocks.soul,
131
161
  'foundations:chat': CHAT,
132
162
  '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}` : '',
163
+ 'foundations:user': blocks.user
164
+ ? `[foundations:user]\nThese are facts about the user. They are not your name, and they are not your persona.\n${blocks.user}`
165
+ : '',
166
+ 'foundations:facts': blocks.facts
167
+ ? `[foundations:facts]\nThese are also facts about the user, not your name.\n${blocks.facts}`
168
+ : '',
135
169
  'foundations:state': blocks.state ? `[foundations:state]\n${blocks.state}` : '',
136
170
  'foundations:skills': blocks.skills ? `[foundations:skills]\n${blocks.skills}` : '',
137
171
  'foundations:revocation': blocks.notice ? `[foundations:revocation]\n${blocks.notice}` : '',
138
172
  };
139
- const snapshotHash = sha256(Object.entries(rendered).map(([name, text]) => `${name}\n${text}`).join('\n'));
173
+ const snapshotHash = sha256(Object.entries(rendered)
174
+ .map(([name, text]) => `${name}\n${text}`)
175
+ .join('\n'));
140
176
  const previous = view.snapshot_hash;
141
177
  let presence = view.presence;
142
178
  if (previous === 'pending')
143
179
  presence = view.presence === 'needs_reinject' ? 'needs_reinject' : 'unknown';
144
180
  else if (previous !== snapshotHash)
145
181
  presence = 'unknown';
146
- engine.recordSnapshot(sessionId, view.revision, snapshotHash, presence);
182
+ if (persist)
183
+ engine.recordSnapshot(sessionId, view.revision, snapshotHash, presence);
147
184
  return {
148
185
  sessionId,
149
186
  viewRevision: view.revision,
@@ -181,7 +218,9 @@ export function frameSoul(soul) {
181
218
  const { name, body } = splitPersona(soul);
182
219
  if (name === '' && body === '')
183
220
  return '';
184
- const lines = ['The persona below is your identity. Enter this role in the first person and keep it for the whole conversation.'];
221
+ const lines = [
222
+ 'The persona below is your identity. Enter this role in the first person and keep it for the whole conversation.',
223
+ ];
185
224
  if (name !== '') {
186
225
  lines.push(`Your name is "${name}". This is your name, not the user's name, and not a nickname for the user.`);
187
226
  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 +292,13 @@ export function renderTickets(rows) {
253
292
  return [
254
293
  '[foundations:tickets]',
255
294
  'These are ticket summaries, not the execution transcript, and not a reply the user has already been given.',
295
+ 'Ticket summaries are not the execution record. To see how far a worker has gotten, call foundations_worker_history.',
256
296
  'accepted means received. enqueued means placed on the execution queue. started is the only status that means work has begun.',
257
297
  'A ticket notice is not something the user said. accepted is not enqueued, and enqueued is not started.',
258
298
  '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.',
299
+ '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.',
300
+ '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.',
301
+ `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
302
  ...lines,
261
303
  ].join('\n');
262
304
  }
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
  }