@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
package/dist/tools.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { toolError, asStoreFailure } from "./errors.js";
3
3
  import { syncFactFts, syncMemoryFts, EMPTY_STATE } from "./engine.js";
4
+ import { queryMemory, readMemoryEntity } from "./memory-catalog.js";
5
+ const SHARED = ' A worker uses the main bot memory, not a private copy.';
6
+ const TYPES = ['persona', 'profile', 'fact', 'episodic', 'procedural', 'state', 'skill'];
4
7
  const OUTPUT = {
5
8
  schema: {
6
9
  type: 'object',
@@ -21,7 +24,7 @@ export function toolDefinitions(engine, viewRevision = () => 0) {
21
24
  return injected > 0 ? injected : currentRevision(engine, hostId);
22
25
  };
23
26
  return [
24
- tool('foundations_recall', 'Search facts and long-term memories that are still active in this session. Forgotten, superseded, and unconfirmed rows are omitted.', {
27
+ tool('foundations_recall', `Search facts and long-term memories that are still active in this session. Forgotten, superseded, and unconfirmed rows are omitted.${SHARED}`, {
25
28
  type: 'object',
26
29
  properties: {
27
30
  query: { type: 'string', description: 'Search text' },
@@ -30,13 +33,14 @@ export function toolDefinitions(engine, viewRevision = () => 0) {
30
33
  },
31
34
  required: ['query'],
32
35
  }, async (args, hostId) => {
33
- const limit = Math.min(20, Math.max(1, Number.isInteger(args.limit) ? args.limit : 5));
36
+ const requested = args.limit;
37
+ const limit = Math.min(20, Math.max(1, typeof requested === 'number' && Number.isInteger(requested) ? requested : 5));
34
38
  if (typeof args.query !== 'string' || args.query.trim() === '')
35
39
  return toolError('VALIDATION', 'query is required.');
36
40
  const found = engine.recall(hostId, args.query.trim(), limit);
37
41
  return ok(revision(hostId), 0, found);
38
42
  }),
39
- tool('foundations_remember', 'Store one fact or long-term memory as active. An idempotency key is required.', {
43
+ tool('foundations_remember', `Store one fact or long-term memory as active. An idempotency key is required.${SHARED}`, {
40
44
  type: 'object',
41
45
  properties: {
42
46
  target: { type: 'string', enum: ['fact', 'memory'] },
@@ -59,25 +63,29 @@ export function toolDefinitions(engine, viewRevision = () => 0) {
59
63
  const created = nowIso();
60
64
  if (args.target === 'fact') {
61
65
  const priority = Number.isInteger(args.priority) ? args.priority : 100;
62
- const info = engine.store.db.prepare(`
66
+ const info = engine.store.db
67
+ .prepare(`
63
68
  INSERT INTO facts (
64
69
  session_id, kind, content, status, source_event_id, source_type, revision, priority, created_at, updated_at
65
70
  ) VALUES (?, 'user_fact', ?, 'active', ?, 'explicit_tool', 1, ?, ?, ?)
66
- `).run(hostId, args.content, args.sourceEventId ?? null, priority, created, created);
71
+ `)
72
+ .run(hostId, args.content, args.sourceEventId ?? null, priority, created, created);
67
73
  const id = Number(info.lastInsertRowid);
68
74
  syncFactFts(engine.store.db, id, args.content, true);
69
75
  return ok(revision(hostId), 1, { id, target: 'fact', revision: 1 });
70
76
  }
71
- const info = engine.store.db.prepare(`
77
+ const info = engine.store.db
78
+ .prepare(`
72
79
  INSERT INTO memories (
73
80
  session_id, title, content, status, source_event_id, source_type, revision, created_at, updated_at
74
81
  ) VALUES (?, ?, ?, 'active', ?, 'explicit_tool', 1, ?, ?)
75
- `).run(hostId, typeof args.title === 'string' ? args.title : null, args.content, args.sourceEventId ?? null, created, created);
82
+ `)
83
+ .run(hostId, typeof args.title === 'string' ? args.title : null, args.content, args.sourceEventId ?? null, created, created);
76
84
  const id = Number(info.lastInsertRowid);
77
85
  syncMemoryFts(engine.store.db, id, typeof args.title === 'string' ? args.title : '', args.content, true);
78
86
  return ok(revision(hostId), 1, { id, target: 'memory', revision: 1 });
79
87
  })),
80
- tool('foundations_correct', 'Replace one still-active fact or memory with a new row. expectedRevision is required.', {
88
+ tool('foundations_correct', `Replace one still-active fact or memory with a new row. expectedRevision is required.${SHARED}`, {
81
89
  type: 'object',
82
90
  properties: {
83
91
  target: { type: 'string', enum: ['fact', 'memory'] },
@@ -90,7 +98,7 @@ export function toolDefinitions(engine, viewRevision = () => 0) {
90
98
  },
91
99
  required: ['target', 'id', 'content', 'expectedRevision', 'idempotencyKey'],
92
100
  }, async (args, hostId) => write(engine, hostId, 'foundations_correct', args, () => revision(hostId), () => correct(engine, hostId, args))),
93
- tool('foundations_forget', 'Mark one fact or memory forgotten and drop it from search. The original log is not deleted.', {
101
+ tool('foundations_forget', `Mark one fact or memory forgotten and drop it from search. The original log is not deleted.${SHARED}`, {
94
102
  type: 'object',
95
103
  properties: {
96
104
  target: { type: 'string', enum: ['fact', 'memory'] },
@@ -101,7 +109,7 @@ export function toolDefinitions(engine, viewRevision = () => 0) {
101
109
  },
102
110
  required: ['target', 'id', 'expectedRevision', 'idempotencyKey'],
103
111
  }, async (args, hostId) => write(engine, hostId, 'foundations_forget', args, () => revision(hostId), () => forget(engine, hostId, args))),
104
- tool('foundations_state_update', 'Patch the working draft for this session. expectedRevision is required.', {
112
+ tool('foundations_state_update', `Patch the working draft for this session. expectedRevision is required.${SHARED}`, {
105
113
  type: 'object',
106
114
  properties: {
107
115
  expectedRevision: { type: 'integer' },
@@ -111,7 +119,7 @@ export function toolDefinitions(engine, viewRevision = () => 0) {
111
119
  },
112
120
  required: ['expectedRevision', 'patch', 'idempotencyKey'],
113
121
  }, async (args, hostId) => write(engine, hostId, 'foundations_state_update', args, () => revision(hostId), () => updateState(engine, hostId, args))),
114
- tool('foundations_skill_load', 'Read the text of an enabled, non-revoked skill in this session. This does not grant tools.', {
122
+ tool('foundations_skill_load', `Read the text of an enabled, non-revoked skill in this session. This does not grant tools.${SHARED}`, {
115
123
  type: 'object',
116
124
  properties: {
117
125
  skillId: { type: 'string' },
@@ -132,13 +140,83 @@ export function toolDefinitions(engine, viewRevision = () => 0) {
132
140
  data: loaded.data,
133
141
  };
134
142
  }),
143
+ tool('foundations_memory_list', `List persona, profile, facts, episodes, working state, and skills in this session. Forgotten rows are tombstones without their text. This is not a search; use foundations_recall to find active facts and memories by words.${SHARED}`, {
144
+ type: 'object',
145
+ properties: {
146
+ type: { type: 'string', enum: [...TYPES], description: 'Omit to list every type.' },
147
+ limit: { type: 'integer', description: 'Default 20, maximum 50' },
148
+ cursor: { type: 'string', description: 'Offset returned as nextCursor.' },
149
+ sessionId: { type: 'string', description: 'Ignored. The host binds the session.' },
150
+ },
151
+ }, async (args, hostId) => {
152
+ const type = args.type == null || args.type === '' ? null : args.type;
153
+ if (type != null && (typeof type !== 'string' || !TYPES.includes(type))) {
154
+ return toolError('VALIDATION', 'type is invalid.');
155
+ }
156
+ const requested = args.limit;
157
+ const limit = Math.min(50, Math.max(1, typeof requested === 'number' && Number.isInteger(requested) ? requested : 20));
158
+ const cursor = args.cursor == null || args.cursor === '' ? 0 : Number(args.cursor);
159
+ if (!Number.isInteger(cursor) || cursor < 0)
160
+ return toolError('VALIDATION', 'cursor is invalid.');
161
+ const page = queryMemory(engine, hostId, { type: type, limit, offset: cursor });
162
+ return ok(revision(hostId), 0, page);
163
+ }),
164
+ tool('foundations_memory_read', `Read one memory entity by id, such as fact:1, episodic:2, persona:1, state:current, or skill:guide. Forgotten text stays hidden.${SHARED}`, {
165
+ type: 'object',
166
+ properties: {
167
+ id: { type: 'string' },
168
+ sessionId: { type: 'string', description: 'Ignored. The host binds the session.' },
169
+ },
170
+ required: ['id'],
171
+ }, async (args, hostId) => {
172
+ if (typeof args.id !== 'string' || args.id.trim() === '')
173
+ return toolError('VALIDATION', 'id is required.');
174
+ const entity = readMemoryEntity(engine, hostId, args.id.trim());
175
+ if (!entity)
176
+ return toolError('NOT_FOUND', 'No memory entity was found in this session.');
177
+ return ok(revision(hostId), 0, { entity: publicEntity(entity) });
178
+ }),
135
179
  ];
136
180
  }
181
+ /**
182
+ * The bot's own session, or the main bot that owns this worker. Anyone else has no memory.
183
+ * @param {(sessionId: string) => boolean} isBot
184
+ * @param {string} sessionId
185
+ * @param {(sessionId: string) => string | null} ownerOf
186
+ */
187
+ export function memorySessionFor(isBot, sessionId, ownerOf) {
188
+ if (isBot(sessionId))
189
+ return sessionId;
190
+ const owner = ownerOf(sessionId);
191
+ if (!owner || owner === sessionId || !isBot(owner))
192
+ return null;
193
+ return owner;
194
+ }
195
+ /**
196
+ * Run a memory tool against the resolved session. Workers are forwarded to the main bot.
197
+ * @param {(args: Record<string, unknown>, exec: { agent?: { id?: string } } | null | undefined) => Promise<ToolPayload>} execute
198
+ * @param {Record<string, unknown>} args
199
+ * @param {{ agent?: { id?: string } } | null | undefined} exec
200
+ * @param {(sessionId: string) => string | null} resolve
201
+ */
202
+ export async function callMemoryTool(execute, args, exec, resolve) {
203
+ const sessionId = exec?.agent?.id;
204
+ if (typeof sessionId !== 'string' || sessionId === '')
205
+ return toolError('UNAVAILABLE', 'The host did not bind a sessionId.');
206
+ const memoryId = resolve(sessionId);
207
+ if (!memoryId)
208
+ return toolError('FORBIDDEN', 'This session is not a bot and not a worker of one, so persona and memory do not apply here.');
209
+ const forwarded = memoryId === sessionId ? exec : { ...exec, agent: { ...(exec?.agent ?? {}), id: memoryId } };
210
+ const result = await execute(args, forwarded);
211
+ if (result?.ok === true && memoryId !== sessionId)
212
+ return { ...result, memorySessionId: memoryId };
213
+ return result;
214
+ }
137
215
  /**
138
216
  * @param {string} name
139
217
  * @param {string} description
140
218
  * @param {Record<string, unknown>} parameters
141
- * @param {(args: Record<string, unknown>, hostId: string) => Promise<unknown>} run
219
+ * @param {(args: Record<string, unknown>, hostId: string) => Promise<ToolPayload>} run
142
220
  */
143
221
  function tool(name, description, parameters, run) {
144
222
  return {
@@ -168,17 +246,18 @@ function tool(name, description, parameters, run) {
168
246
  * @param {string} name
169
247
  * @param {Record<string, unknown>} args
170
248
  * @param {() => number} viewRevision
171
- * @param {() => Record<string, unknown>} apply
249
+ * @param {() => ToolPayload} apply
172
250
  */
173
251
  async function write(engine, hostId, name, args, viewRevision, apply) {
174
252
  const binding = engine.ensureSession(hostId);
175
253
  if (binding.status === 'error')
176
254
  return toolError('UNAVAILABLE', `Binding is ${binding.error_code ?? 'error'}.`);
177
- if (typeof args.idempotencyKey !== 'string' || args.idempotencyKey.trim() === '') {
255
+ const idempotencyKey = args.idempotencyKey;
256
+ if (typeof idempotencyKey !== 'string' || idempotencyKey.trim() === '') {
178
257
  return toolError('VALIDATION', 'idempotencyKey is required.');
179
258
  }
180
259
  const payloadHash = createHash('sha256').update(stable(args)).digest('hex');
181
- const result = await engine.store.write(hostId, () => (engine.mutate(hostId, args.idempotencyKey, payloadHash, name, args, apply, viewRevision())));
260
+ const result = await engine.store.write(hostId, () => engine.mutate(hostId, idempotencyKey, payloadHash, name, args, apply, viewRevision()));
182
261
  if (result.ok === true && result.outcome === 'applied') {
183
262
  const exported = await engine.exportOne({ id: result.mutationId, session_id: hostId, attempts: 0 });
184
263
  const final = {
@@ -186,7 +265,9 @@ async function write(engine, hostId, name, args, viewRevision, apply) {
186
265
  export: exported.ok ? 'done' : 'failed',
187
266
  ...(exported.ok ? {} : { exportError: exported.error }),
188
267
  };
189
- engine.store.db.prepare('UPDATE mutations SET result_json = ? WHERE id = ?').run(JSON.stringify(final), result.mutationId);
268
+ engine.store.db
269
+ .prepare('UPDATE mutations SET result_json = ? WHERE id = ?')
270
+ .run(JSON.stringify(final), result.mutationId);
190
271
  return final;
191
272
  }
192
273
  return result;
@@ -213,7 +294,10 @@ function publish(result) {
213
294
  * @param {Record<string, unknown>} args
214
295
  */
215
296
  function correct(engine, hostId, args) {
216
- if ((args.target !== 'fact' && args.target !== 'memory') || typeof args.content !== 'string' || !Number.isInteger(args.id) || !Number.isInteger(args.expectedRevision)) {
297
+ if ((args.target !== 'fact' && args.target !== 'memory') ||
298
+ typeof args.content !== 'string' ||
299
+ !Number.isInteger(args.id) ||
300
+ !Number.isInteger(args.expectedRevision)) {
217
301
  return toolError('VALIDATION', 'correct arguments are incomplete.');
218
302
  }
219
303
  const table = args.target === 'fact' ? 'facts' : 'memories';
@@ -226,23 +310,31 @@ function correct(engine, hostId, args) {
226
310
  const created = nowIso();
227
311
  let inserted;
228
312
  if (args.target === 'fact') {
229
- inserted = engine.store.db.prepare(`
313
+ inserted = engine.store.db
314
+ .prepare(`
230
315
  INSERT INTO facts (
231
316
  session_id, kind, content, status, source_type, supersedes, revision, priority, created_at, updated_at
232
317
  ) VALUES (?, 'user_fact', ?, 'active', 'explicit_tool', ?, 1, ?, ?, ?)
233
- `).run(hostId, args.content, row.id, row.priority, created, created);
234
- engine.store.db.prepare(`UPDATE facts SET status = 'superseded', revision = ?, updated_at = ? WHERE id = ?`).run(row.revision + 1, created, row.id);
318
+ `)
319
+ .run(hostId, args.content, row.id, row.priority, created, created);
320
+ engine.store.db
321
+ .prepare(`UPDATE facts SET status = 'superseded', revision = ?, updated_at = ? WHERE id = ?`)
322
+ .run(row.revision + 1, created, row.id);
235
323
  syncFactFts(engine.store.db, row.id, row.content, false);
236
324
  syncFactFts(engine.store.db, Number(inserted.lastInsertRowid), args.content, true);
237
325
  }
238
326
  else {
239
327
  const title = typeof args.title === 'string' ? args.title : row.title;
240
- inserted = engine.store.db.prepare(`
328
+ inserted = engine.store.db
329
+ .prepare(`
241
330
  INSERT INTO memories (
242
331
  session_id, title, content, status, source_type, supersedes, revision, created_at, updated_at
243
332
  ) VALUES (?, ?, ?, 'active', 'explicit_tool', ?, 1, ?, ?)
244
- `).run(hostId, title, args.content, row.id, created, created);
245
- engine.store.db.prepare(`UPDATE memories SET status = 'superseded', revision = ?, updated_at = ? WHERE id = ?`).run(row.revision + 1, created, row.id);
333
+ `)
334
+ .run(hostId, title, args.content, row.id, created, created);
335
+ engine.store.db
336
+ .prepare(`UPDATE memories SET status = 'superseded', revision = ?, updated_at = ? WHERE id = ?`)
337
+ .run(row.revision + 1, created, row.id);
246
338
  syncMemoryFts(engine.store.db, row.id, row.title, row.content, false);
247
339
  syncMemoryFts(engine.store.db, Number(inserted.lastInsertRowid), title, args.content, true);
248
340
  }
@@ -254,7 +346,9 @@ function correct(engine, hostId, args) {
254
346
  * @param {Record<string, unknown>} args
255
347
  */
256
348
  function forget(engine, hostId, args) {
257
- if ((args.target !== 'fact' && args.target !== 'memory') || !Number.isInteger(args.id) || !Number.isInteger(args.expectedRevision)) {
349
+ if ((args.target !== 'fact' && args.target !== 'memory') ||
350
+ !Number.isInteger(args.id) ||
351
+ !Number.isInteger(args.expectedRevision)) {
258
352
  return toolError('VALIDATION', 'forget arguments are incomplete.');
259
353
  }
260
354
  const table = args.target === 'fact' ? 'facts' : 'memories';
@@ -264,7 +358,9 @@ function forget(engine, hostId, args) {
264
358
  if (row.revision !== args.expectedRevision)
265
359
  return toolError('CAS_CONFLICT', 'The revision has changed.', { actualRevision: row.revision });
266
360
  const updated = nowIso();
267
- engine.store.db.prepare(`UPDATE ${table} SET status = 'forgotten', revision = ?, updated_at = ? WHERE id = ?`).run(row.revision + 1, updated, row.id);
361
+ engine.store.db
362
+ .prepare(`UPDATE ${table} SET status = 'forgotten', revision = ?, updated_at = ? WHERE id = ?`)
363
+ .run(row.revision + 1, updated, row.id);
268
364
  if (args.target === 'fact')
269
365
  syncFactFts(engine.store.db, row.id, row.content, false);
270
366
  else
@@ -277,7 +373,10 @@ function forget(engine, hostId, args) {
277
373
  * @param {Record<string, unknown>} args
278
374
  */
279
375
  function updateState(engine, hostId, args) {
280
- if (!Number.isInteger(args.expectedRevision) || args.patch == null || typeof args.patch !== 'object' || Array.isArray(args.patch)) {
376
+ if (!Number.isInteger(args.expectedRevision) ||
377
+ args.patch == null ||
378
+ typeof args.patch !== 'object' ||
379
+ Array.isArray(args.patch)) {
281
380
  return toolError('VALIDATION', 'state_update arguments are incomplete.');
282
381
  }
283
382
  const current = engine.statePayload(hostId);
@@ -314,14 +413,18 @@ function updateState(engine, hostId, args) {
314
413
  const revision = current.revision + 1;
315
414
  const updated = nowIso();
316
415
  if (current.revision === 0) {
317
- engine.store.db.prepare(`
416
+ engine.store.db
417
+ .prepare(`
318
418
  INSERT INTO working_state (session_id, revision, payload_json, updated_at) VALUES (?, ?, ?, ?)
319
- `).run(hostId, revision, JSON.stringify(next), updated);
419
+ `)
420
+ .run(hostId, revision, JSON.stringify(next), updated);
320
421
  }
321
422
  else {
322
- engine.store.db.prepare(`
423
+ engine.store.db
424
+ .prepare(`
323
425
  UPDATE working_state SET revision = ?, payload_json = ?, updated_at = ? WHERE session_id = ?
324
- `).run(revision, JSON.stringify(next), updated, hostId);
426
+ `)
427
+ .run(revision, JSON.stringify(next), updated, hostId);
325
428
  }
326
429
  return ok(0, revision, { revision, payload: next });
327
430
  }
@@ -330,6 +433,15 @@ function updateState(engine, hostId, args) {
330
433
  * @param {number} storeRevision
331
434
  * @param {unknown} data
332
435
  */
436
+ function publicEntity(entity) {
437
+ const visible = entity.bodyState === 'visible' && !entity.tombstone;
438
+ return {
439
+ ...entity,
440
+ title: entity.tombstone && entity.type !== 'skill' ? '' : entity.title,
441
+ summary: entity.tombstone ? '' : entity.summary,
442
+ body: visible ? (entity.body ?? null) : null,
443
+ };
444
+ }
333
445
  function ok(viewRevision, storeRevision, data) {
334
446
  return { ok: true, viewRevision, storeRevision, data };
335
447
  }
@@ -339,11 +451,17 @@ function ok(viewRevision, storeRevision, data) {
339
451
  function stable(value) {
340
452
  if (Array.isArray(value))
341
453
  return `[${value.map(item => stable(item)).join(',')}]`;
342
- if (value && typeof value === 'object') {
343
- return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${stable(value[key])}`).join(',')}}`;
454
+ if (isRecord(value)) {
455
+ return `{${Object.keys(value)
456
+ .sort()
457
+ .map(key => `${JSON.stringify(key)}:${stable(value[key])}`)
458
+ .join(',')}}`;
344
459
  }
345
460
  return JSON.stringify(value);
346
461
  }
462
+ function isRecord(value) {
463
+ return value != null && typeof value === 'object' && !Array.isArray(value);
464
+ }
347
465
  function nowIso() {
348
466
  return new Date().toISOString();
349
467
  }
package/dist/triggers.js CHANGED
@@ -68,7 +68,9 @@ export function createTriggers(store, options) {
68
68
  observeUserMessage,
69
69
  observeTurnEnd,
70
70
  hasOpen(sessionId) {
71
- const row = db.prepare(`SELECT 1 AS ok FROM deliveries WHERE target_session_id = ? AND status IN ('intent','flushing','accepted','claimed','started') LIMIT 1`).get(sessionId);
71
+ const row = db
72
+ .prepare(`SELECT 1 AS ok FROM deliveries WHERE target_session_id = ? AND status IN ('intent','flushing','accepted','claimed','started') LIMIT 1`)
73
+ .get(sessionId);
72
74
  return row != null;
73
75
  },
74
76
  };
@@ -111,10 +113,14 @@ export function createTriggers(store, options) {
111
113
  * @param {string} senderSessionId
112
114
  */
113
115
  function pairBlocked(targetSessionId, senderSessionId) {
114
- return db.prepare('SELECT 1 AS ok FROM delivery_block WHERE target_session_id = ? AND sender_session_id = ?').get(targetSessionId, senderSessionId) != null;
116
+ return (db
117
+ .prepare('SELECT 1 AS ok FROM delivery_block WHERE target_session_id = ? AND sender_session_id = ?')
118
+ .get(targetSessionId, senderSessionId) != null);
115
119
  }
116
120
  function listAcl() {
117
- return db.prepare('SELECT target_session_id, sender_session_id, created_at FROM delivery_block ORDER BY created_at').all();
121
+ return db
122
+ .prepare('SELECT target_session_id, sender_session_id, created_at FROM delivery_block ORDER BY created_at')
123
+ .all();
118
124
  }
119
125
  /**
120
126
  * @param {string} senderSessionId host-bound sender
@@ -173,17 +179,21 @@ export function createTriggers(store, options) {
173
179
  async function reply(senderSessionId, args) {
174
180
  if (!checkSession(senderSessionId, true))
175
181
  return toolError('VALIDATION', 'The sender session is invalid.');
176
- if (typeof args.correlationId !== 'string' || typeof args.text !== 'string' || typeof args.idempotencyKey !== 'string') {
182
+ if (typeof args.correlationId !== 'string' ||
183
+ typeof args.text !== 'string' ||
184
+ typeof args.idempotencyKey !== 'string') {
177
185
  return toolError('VALIDATION', 'reply arguments are incomplete.');
178
186
  }
179
187
  const blocked = requireBot(senderSessionId);
180
188
  if (blocked)
181
189
  return blocked;
182
- const prior = db.prepare(`
190
+ const prior = db
191
+ .prepare(`
183
192
  SELECT * FROM deliveries
184
193
  WHERE correlation_id = ? AND target_session_id = ? AND kind = 'message'
185
194
  ORDER BY created_at DESC LIMIT 1
186
- `).get(args.correlationId, senderSessionId);
195
+ `)
196
+ .get(args.correlationId, senderSessionId);
187
197
  if (!prior)
188
198
  return toolError('NOT_FOUND', 'No correlated message to this session was found.');
189
199
  if (!checkSession(prior.sender_session_id, true))
@@ -214,19 +224,23 @@ export function createTriggers(store, options) {
214
224
  */
215
225
  function listDeliveries(sessionId, correlationId) {
216
226
  if (correlationId) {
217
- return db.prepare(`
227
+ return db
228
+ .prepare(`
218
229
  SELECT id, kind, sender_session_id, target_session_id, correlation_id, causation_id, hop, status,
219
230
  splice_seq, turn_number, attempts, last_error, expires_at, created_at, updated_at
220
231
  FROM deliveries WHERE correlation_id = ? ORDER BY created_at
221
- `).all(correlationId);
232
+ `)
233
+ .all(correlationId);
222
234
  }
223
- return db.prepare(`
235
+ return db
236
+ .prepare(`
224
237
  SELECT id, kind, sender_session_id, target_session_id, correlation_id, causation_id, hop, status,
225
238
  splice_seq, turn_number, attempts, last_error, expires_at, created_at, updated_at
226
239
  FROM deliveries
227
240
  WHERE target_session_id = ? OR sender_session_id = ?
228
241
  ORDER BY created_at
229
- `).all(sessionId ?? '', sessionId ?? '');
242
+ `)
243
+ .all(sessionId ?? '', sessionId ?? '');
230
244
  }
231
245
  /**
232
246
  * @param {{ sessionId: string, kind: 'one-shot' | 'cron', cron?: string, runAt?: string, timezone?: string, note?: string }} input
@@ -271,10 +285,12 @@ export function createTriggers(store, options) {
271
285
  return { ok: true, schedule: publicSchedule(id) };
272
286
  }
273
287
  function listSchedules() {
274
- return db.prepare(`
288
+ return db
289
+ .prepare(`
275
290
  SELECT id, session_id, kind, cron_expr, timezone, run_at, next_due, enabled, deleted, note, created_at, updated_at
276
291
  FROM schedules WHERE deleted = 0 ORDER BY created_at
277
- `).all();
292
+ `)
293
+ .all();
278
294
  }
279
295
  /**
280
296
  * @param {string} id
@@ -325,9 +341,11 @@ export function createTriggers(store, options) {
325
341
  return { ok: true };
326
342
  }
327
343
  function listWebhooks() {
328
- return db.prepare(`
344
+ return db
345
+ .prepare(`
329
346
  SELECT id, target_session_id, enabled, created_at, revoked_at FROM webhook_hooks ORDER BY created_at
330
- `).all();
347
+ `)
348
+ .all();
331
349
  }
332
350
  /**
333
351
  * @param {string} hookId
@@ -346,12 +364,16 @@ export function createTriggers(store, options) {
346
364
  const verdict = verifyWebhook(hook.secret, raw, headers, now().getTime());
347
365
  if (verdict.ok === false)
348
366
  return { http: 401, body: verdict };
349
- const recent = db.prepare(`
367
+ const recent = db
368
+ .prepare(`
350
369
  SELECT COUNT(*) AS n FROM webhook_receipts WHERE hook_id = ? AND received_at > ?
351
- `).get(hookId, new Date(now().getTime() - RATE_WINDOW_MS).toISOString());
370
+ `)
371
+ .get(hookId, new Date(now().getTime() - RATE_WINDOW_MS).toISOString());
352
372
  if (recent.n >= RATE_LIMIT)
353
373
  return { http: 429, body: toolError('RATE_LIMIT', 'The webhook is firing too often.') };
354
- const existing = db.prepare('SELECT delivery_id FROM webhook_receipts WHERE hook_id = ? AND event_id = ?').get(hookId, headers.eventId);
374
+ const existing = db
375
+ .prepare('SELECT delivery_id FROM webhook_receipts WHERE hook_id = ? AND event_id = ?')
376
+ .get(hookId, headers.eventId);
355
377
  if (existing)
356
378
  return { http: 202, body: { ok: true, status: 'accepted', duplicate: true, deliveryId: existing.delivery_id } };
357
379
  const body = raw.toString('utf8').slice(0, MAX_BODY);
@@ -375,9 +397,11 @@ export function createTriggers(store, options) {
375
397
  return { http: 202, body: { ok: true, status: 'accepted', deliveryId: queued.deliveryId } };
376
398
  }
377
399
  async function tick() {
378
- const due = db.prepare(`
400
+ const due = db
401
+ .prepare(`
379
402
  SELECT * FROM schedules WHERE deleted = 0 AND enabled = 1 AND next_due IS NOT NULL AND next_due <= ? ORDER BY next_due
380
- `).all(iso());
403
+ `)
404
+ .all(iso());
381
405
  for (const row of due) {
382
406
  try {
383
407
  await fireSchedule(row);
@@ -390,9 +414,11 @@ export function createTriggers(store, options) {
390
414
  await reconcile();
391
415
  }
392
416
  async function reconcile() {
393
- const rows = db.prepare(`
417
+ const rows = db
418
+ .prepare(`
394
419
  SELECT * FROM deliveries WHERE status IN ('intent','flushing','ambiguous') AND attempts < ? ORDER BY created_at
395
- `).all(MAX_ATTEMPTS);
420
+ `)
421
+ .all(MAX_ATTEMPTS);
396
422
  for (const row of rows) {
397
423
  if (inflight.has(row.id))
398
424
  continue;
@@ -474,9 +500,11 @@ export function createTriggers(store, options) {
474
500
  if (obs.sessionId === sessionId && (obs.claimedTurn === turn || obs.startedTurn === turn))
475
501
  notePending(id, { endKind: reasonKind });
476
502
  }
477
- const rows = db.prepare(`
503
+ const rows = db
504
+ .prepare(`
478
505
  SELECT id, status FROM deliveries WHERE target_session_id = ? AND turn_number = ? AND status IN ('claimed','started')
479
- `).all(sessionId, turn);
506
+ `)
507
+ .all(sessionId, turn);
480
508
  for (const row of rows) {
481
509
  if (row.status === 'started' && reasonKind === 'completed')
482
510
  mark(row.id, 'completed', '');
@@ -491,10 +519,12 @@ export function createTriggers(store, options) {
491
519
  */
492
520
  async function enqueueNew(input) {
493
521
  const hash = sha(String(input.body));
494
- const existing = db.prepare(`
522
+ const existing = db
523
+ .prepare(`
495
524
  SELECT * FROM deliveries
496
525
  WHERE kind = ? AND sender_session_id = ? AND target_session_id = ? AND idempotency_key = ?
497
- `).get(input.kind, input.sender, input.target, input.idempotencyKey);
526
+ `)
527
+ .get(input.kind, input.sender, input.target, input.idempotencyKey);
498
528
  if (existing) {
499
529
  if (existing.body_hash !== hash)
500
530
  return toolError('IDEMPOTENCY_KEY_REUSE', 'The same idempotency key was reused for different content.');
@@ -566,11 +596,13 @@ export function createTriggers(store, options) {
566
596
  db.prepare('UPDATE schedules SET enabled = 0, updated_at = ? WHERE id = ?').run(iso(), row.id);
567
597
  return;
568
598
  }
569
- const pending = db.prepare(`
599
+ const pending = db
600
+ .prepare(`
570
601
  SELECT 1 AS ok FROM deliveries
571
602
  WHERE target_session_id = ? AND kind = 'timer' AND status IN ('intent','flushing','accepted','claimed','started')
572
603
  LIMIT 1
573
- `).get(row.session_id);
604
+ `)
605
+ .get(row.session_id);
574
606
  const slot = row.next_due;
575
607
  const occurrence = `${row.id}:${slot}`;
576
608
  let nextDue = null;
@@ -620,14 +652,18 @@ export function createTriggers(store, options) {
620
652
  try {
621
653
  db.exec('ROLLBACK');
622
654
  }
623
- catch { /* closed by the failed statement */ }
655
+ catch {
656
+ /* closed by the failed statement */
657
+ }
624
658
  throw error;
625
659
  }
626
660
  }
627
661
  async function expirePending() {
628
- const rows = db.prepare(`
662
+ const rows = db
663
+ .prepare(`
629
664
  SELECT * FROM deliveries WHERE status = 'accepted' AND expires_at IS NOT NULL AND expires_at <= ?
630
- `).all(iso());
665
+ `)
666
+ .all(iso());
631
667
  for (const row of rows) {
632
668
  if (options.removePending) {
633
669
  const removed = await options.removePending(row.target_session_id, row.id);
@@ -647,21 +683,25 @@ export function createTriggers(store, options) {
647
683
  * @param {string} sessionId
648
684
  */
649
685
  function activeInbound(sessionId) {
650
- return db.prepare(`
686
+ return (db
687
+ .prepare(`
651
688
  SELECT * FROM deliveries
652
689
  WHERE target_session_id = ? AND kind = 'message' AND status IN ('claimed','started')
653
690
  ORDER BY updated_at DESC LIMIT 1
654
- `).get(sessionId) ?? null;
691
+ `)
692
+ .get(sessionId) ?? null);
655
693
  }
656
694
  /**
657
695
  * @param {string} sessionId
658
696
  * @param {string} correlationId
659
697
  */
660
698
  function ownedCorrelation(sessionId, correlationId) {
661
- const row = db.prepare(`
699
+ const row = db
700
+ .prepare(`
662
701
  SELECT 1 AS ok FROM deliveries
663
702
  WHERE correlation_id = ? AND (sender_session_id = ? OR target_session_id = ?)
664
- `).get(correlationId, sessionId, sessionId);
703
+ `)
704
+ .get(correlationId, sessionId, sessionId);
665
705
  return row ? correlationId : null;
666
706
  }
667
707
  /**
@@ -669,10 +709,12 @@ export function createTriggers(store, options) {
669
709
  * @param {string} target
670
710
  */
671
711
  function rateLimited(sender, target) {
672
- const row = db.prepare(`
712
+ const row = db
713
+ .prepare(`
673
714
  SELECT COUNT(*) AS n FROM deliveries
674
715
  WHERE sender_session_id = ? AND target_session_id = ? AND created_at > ? AND status != 'rejected'
675
- `).get(sender, target, new Date(now().getTime() - RATE_WINDOW_MS).toISOString());
716
+ `)
717
+ .get(sender, target, new Date(now().getTime() - RATE_WINDOW_MS).toISOString());
676
718
  return row.n >= RATE_LIMIT;
677
719
  }
678
720
  /**
@@ -771,7 +813,7 @@ export function createTriggers(store, options) {
771
813
  */
772
814
  function publicSchedule(id) {
773
815
  const row = schedule(id);
774
- return row && {
816
+ return (row && {
775
817
  id: row.id,
776
818
  sessionId: row.session_id,
777
819
  kind: row.kind,
@@ -781,7 +823,7 @@ export function createTriggers(store, options) {
781
823
  nextDue: row.next_due,
782
824
  enabled: row.enabled === 1,
783
825
  note: row.note,
784
- };
826
+ });
785
827
  }
786
828
  function iso() {
787
829
  return now().toISOString();
@@ -835,7 +877,9 @@ export function verifyWebhook(secret, raw, headers, nowMs) {
835
877
  const ts = Number(headers.timestamp) * 1000;
836
878
  if (Math.abs(nowMs - ts) > 5 * 60 * 1000)
837
879
  return toolError('TTL_EXPIRED', 'The timestamp is outside the 5 minute window.');
838
- const expected = createHmac('sha256', secret).update(`${headers.timestamp}.${raw.toString('utf8')}`).digest('hex');
880
+ const expected = createHmac('sha256', secret)
881
+ .update(`${headers.timestamp}.${raw.toString('utf8')}`)
882
+ .digest('hex');
839
883
  const given = headers.signature ?? '';
840
884
  const left = Buffer.from(expected);
841
885
  const right = Buffer.from(given);