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

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.
package/dist/http.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createReadStream, statSync } from 'node:fs';
2
2
  import { dirname, extname, join, resolve, sep } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { createDesk } from "./desk.js";
4
+ import { createDesk, defaultSessionCwd } from "./desk.js";
5
5
  import { toolError } from "./errors.js";
6
6
  import { sessionEvents } from "./inbox.js";
7
7
  import { createSessionSnapshots, eventsBefore, eventsWindow, followTailStart } from "./live-snapshot.js";
@@ -11,25 +11,31 @@ import { handleWorkApi, openPageLive, openWorkLive } from "./work-http.js";
11
11
  * Local management routes. Model tools cannot confirm a persona or change revocation.
12
12
  * @param {import('@deepseek-ai/cordis').Context} ctx
13
13
  * @param {import('./engine.js').Engine} engine
14
- * @param {() => import('./triggers.js').ReturnType<import('./triggers.js').createTriggers> | null} [getRuntime]
15
- * @param {() => import('./work-worker.js').ReturnType<import('./work-worker.js').createWorkRuntime> | null} [getWork]
14
+ * @param {() => import('./triggers.js').ReturnType<typeof import('./triggers.js').createTriggers> | null} [getRuntime]
15
+ * @param {() => import('./work-worker.js').ReturnType<typeof import('./work-worker.js').createWorkRuntime> | null} [getWork]
16
16
  */
17
17
  export function registerHttp(ctx, engine, getRuntime = () => null, getWork = () => null, dataDir = '') {
18
18
  const webServer = ctx.webServer;
19
19
  const storeDir = dataDir || (ctx.profileContext?.dir ? join(ctx.profileContext.dir, 'session-foundations') : '');
20
20
  const profileDir = ctx.profileContext?.dir || (storeDir !== '' ? dirname(storeDir) : '');
21
21
  const sessionSnapshots = createSessionSnapshots();
22
- const desk = profileDir === '' ? null : createDesk({
23
- ledgerFile: join(storeDir, 'desk-ledger.json'),
24
- profileDir,
25
- sessionCwd: (process.env.THREADY_SESSION_CWD ?? '').trim(),
26
- isBot: (sessionId) => engine.isBot(sessionId),
27
- mark: (sessionId) => engine.markBot(sessionId),
28
- hold: (sessionId) => { getWork()?.holdNotices(sessionId); },
29
- release: (sessionId) => { getWork()?.releaseHold(sessionId); },
30
- rpc: (endpoint, args, req) => hostRpc(req, endpoint, args),
31
- usage: (req) => hostUsage(req),
32
- });
22
+ const desk = profileDir === ''
23
+ ? null
24
+ : createDesk({
25
+ ledgerFile: join(storeDir, 'desk-ledger.json'),
26
+ profileDir,
27
+ sessionCwd: defaultSessionCwd(process.env),
28
+ isBot: sessionId => engine.isBot(sessionId),
29
+ mark: sessionId => engine.markBot(sessionId),
30
+ hold: sessionId => {
31
+ getWork()?.holdNotices(sessionId);
32
+ },
33
+ release: sessionId => {
34
+ getWork()?.releaseHold(sessionId);
35
+ },
36
+ rpc: (endpoint, args, req) => hostRpc(req, endpoint, args),
37
+ usage: req => hostUsage(req),
38
+ });
33
39
  /**
34
40
  * @param {import('node:http').IncomingMessage} req
35
41
  */
@@ -217,7 +223,10 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
217
223
  const body = await readJson(req);
218
224
  return send(res, 200, runtime.revokeWebhook(body.id));
219
225
  }
220
- if (req.method === 'GET' && (path === '/session-foundations/api/snapshot' || path === '/session-foundations/api/snapshot/chunks' || path === '/session-foundations/api/snapshot/range')) {
226
+ if (req.method === 'GET' &&
227
+ (path === '/session-foundations/api/snapshot' ||
228
+ path === '/session-foundations/api/snapshot/chunks' ||
229
+ path === '/session-foundations/api/snapshot/range')) {
221
230
  const sessionId = url.searchParams.get('sessionId') ?? '';
222
231
  if (sessionId === '')
223
232
  return send(res, 400, toolError('VALIDATION', 'sessionId is required.'));
@@ -250,7 +259,15 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
250
259
  const cut = typeof beforeSeq === 'number' ? beforeSeq : tail == null ? null : followTailStart(events, tail);
251
260
  const source = cut == null ? events : eventsBefore(events, cut);
252
261
  if (source.length === 0) {
253
- return send(res, 200, { ok: true, sessionId, epoch: '', totalSize: 0, hashes: [], count: 0, ...(cut == null ? {} : { beforeSeq: cut }) });
262
+ return send(res, 200, {
263
+ ok: true,
264
+ sessionId,
265
+ epoch: '',
266
+ totalSize: 0,
267
+ hashes: [],
268
+ count: 0,
269
+ ...(cut == null ? {} : { beforeSeq: cut }),
270
+ });
254
271
  }
255
272
  sessionSnapshots.publish(sessionId, source);
256
273
  const listed = sessionSnapshots.manifest(sessionId);
@@ -339,7 +356,11 @@ export function status(engine, sessionId) {
339
356
  view,
340
357
  persona,
341
358
  personaText: personaText(engine, persona),
342
- skills: binding ? engine.store.db.prepare('SELECT skill_id, scope, version, enabled, revoked, content_hash FROM skill_bindings WHERE session_id = ?').all(sessionId) : [],
359
+ skills: binding
360
+ ? engine.store.db
361
+ .prepare('SELECT skill_id, scope, version, enabled, revoked, content_hash FROM skill_bindings WHERE session_id = ?')
362
+ .all(sessionId)
363
+ : [],
343
364
  isolation: 'host-session-id',
344
365
  sandbox: false,
345
366
  };
@@ -360,8 +381,12 @@ function personaText(engine, persona) {
360
381
  */
361
382
  export function memoryView(engine, sessionId) {
362
383
  return {
363
- facts: engine.store.db.prepare('SELECT id, content, status, revision, priority FROM facts WHERE session_id = ? ORDER BY id').all(sessionId),
364
- memories: engine.store.db.prepare('SELECT id, title, content, status, revision FROM memories WHERE session_id = ? ORDER BY id').all(sessionId),
384
+ facts: engine.store.db
385
+ .prepare('SELECT id, content, status, revision, priority FROM facts WHERE session_id = ? ORDER BY id')
386
+ .all(sessionId),
387
+ memories: engine.store.db
388
+ .prepare('SELECT id, title, content, status, revision FROM memories WHERE session_id = ? ORDER BY id')
389
+ .all(sessionId),
365
390
  state: engine.statePayload(sessionId),
366
391
  };
367
392
  }
@@ -431,7 +456,7 @@ function readRaw(req, max) {
431
456
  return new Promise((resolve, rejectPromise) => {
432
457
  const chunks = [];
433
458
  let size = 0;
434
- req.on('data', chunk => {
459
+ req.on('data', (chunk) => {
435
460
  size += chunk.length;
436
461
  if (size > max) {
437
462
  rejectPromise(Object.assign(new Error('The body is too long.'), { code: 'VALIDATION' }));
@@ -447,7 +472,7 @@ function readRaw(req, max) {
447
472
  function readJson(req) {
448
473
  return new Promise((resolve, rejectPromise) => {
449
474
  const chunks = [];
450
- req.on('data', chunk => chunks.push(chunk));
475
+ req.on('data', (chunk) => chunks.push(chunk));
451
476
  req.on('end', () => {
452
477
  try {
453
478
  resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
@@ -470,7 +495,15 @@ async function hostRpc(req, endpoint, args) {
470
495
  const origin = localOrigin(req);
471
496
  const cookie = header(req, 'cookie') ?? '';
472
497
  if (origin === '' || cookie === '') {
473
- return { status: 503, body: { result: { ok: false, error: { code: 'primary_unready', message: 'This process has not issued a session cookie yet.' } } } };
498
+ return {
499
+ status: 503,
500
+ body: {
501
+ result: {
502
+ ok: false,
503
+ error: { code: 'primary_unready', message: 'This process has not issued a session cookie yet.' },
504
+ },
505
+ },
506
+ };
474
507
  }
475
508
  const response = await fetch(`${origin}/api/${endpoint}`, {
476
509
  method: 'POST',
@@ -526,7 +559,12 @@ async function hostUsage(req) {
526
559
  if (response.status === 404)
527
560
  return { connected: false, code: 'usage_not_installed', error: 'The usage plugin is not installed.' };
528
561
  if (!body || body.ok !== true) {
529
- return { connected: false, code: 'usage_unconfigured', status: response.status, error: typeof body?.error === 'string' ? body.error : 'The usage upstream is unavailable.' };
562
+ return {
563
+ connected: false,
564
+ code: 'usage_unconfigured',
565
+ status: response.status,
566
+ error: typeof body?.error === 'string' ? body.error : 'The usage upstream is unavailable.',
567
+ };
530
568
  }
531
569
  return { connected: true, summary: body };
532
570
  }
package/dist/inbox.js CHANGED
@@ -38,14 +38,17 @@ export async function loadAgent(ctx, sessionId) {
38
38
  const pending = loading.get(sessionId);
39
39
  if (pending)
40
40
  return pending;
41
- const job = ctx.agents.resume({
41
+ const job = ctx.agents
42
+ .resume({
42
43
  resumeSessionId: sessionId,
43
- ...sessionId.startsWith('worker-') ? { setup: workerFileSetup(ctx, null) } : {},
44
- }).then(handle => {
44
+ ...(sessionId.startsWith('worker-') ? { setup: workerFileSetup(ctx, null) } : {}),
45
+ })
46
+ .then((handle) => {
45
47
  handles.set(sessionId, handle);
46
48
  loading.delete(sessionId);
47
49
  return { agent: handle.agent, owned: true };
48
- }).catch(error => {
50
+ })
51
+ .catch((error) => {
49
52
  loading.delete(sessionId);
50
53
  throw error;
51
54
  });
@@ -80,7 +83,7 @@ export async function followupDurable(ctx, sessionId, messageId, text) {
80
83
  let flushed = false;
81
84
  let flushError = '';
82
85
  try {
83
- flushed = await ctx.sessions.flush(agent.session) === true;
86
+ flushed = (await ctx.sessions.flush(agent.session)) === true;
84
87
  }
85
88
  catch (error) {
86
89
  flushError = error instanceof Error ? error.message : String(error);
@@ -100,8 +103,8 @@ export async function followupDurable(ctx, sessionId, messageId, text) {
100
103
  */
101
104
  export function logHasMessage(session, messageId) {
102
105
  const events = session.snapshotEvents?.() ?? [];
103
- return events.some(event => event.type === 'agent/inbox/spliced' && insertedIds(event).includes(messageId))
104
- || events.some(event => event.type === 'user/message' && messageIdOf(event) === messageId);
106
+ return (events.some(event => event.type === 'agent/inbox/spliced' && insertedIds(event).includes(messageId)) ||
107
+ events.some(event => event.type === 'user/message' && messageIdOf(event) === messageId));
105
108
  }
106
109
  /**
107
110
  * Live snapshot when the agent is already entered. Otherwise a read-only
package/dist/index.js CHANGED
@@ -8,14 +8,15 @@ import { createTriggers } from "./triggers.js";
8
8
  import { followupDurable, liveAgent, logHasMessage, removePending, sessionEvents } from "./inbox.js";
9
9
  import { toolError } from "./errors.js";
10
10
  import { publishRuntime, publishWorkRuntime, runtimeFor } from "./runtime-registry.js";
11
- import { childCreateOptions } from "./work-admit.js";
11
+ import { childCreateOptions, resolveWorkBudget, WORK_BUDGET_ENV } from "./work-admit.js";
12
12
  import { ensureWorkerFilePreset, WORKER_FILE_PRESET, workerFileSetup } from "./work-child.js";
13
- import { createWorkRuntime } from "./work-worker.js";
13
+ import { BUDGET_NOTICE_PREFIX, createWorkRuntime } from "./work-worker.js";
14
14
  import { workToolDefinitions } from "./work-tools.js";
15
15
  export const name = 'session-foundations';
16
- export const inject = ['systemPrompt', 'tools', 'sessions', 'agents', 'agentPresets'];
16
+ // Cordis throws if a plugin reads a service it did not inject. Crash recovery reads the session log through this one.
17
+ export const inject = ['systemPrompt', 'tools', 'sessions', 'agents', 'agentPresets', 'sessionPersistence'];
17
18
  /**
18
- * @param {import('@deepseek-ai/cordis').Context} ctx
19
+ * @param {import('./host.ts').PluginHost} ctx
19
20
  * @param {{ dataDir?: string, contextWindow?: number, traceEvents?: boolean, timerTickMs?: number }} [config]
20
21
  */
21
22
  export function apply(ctx, config = {}) {
@@ -33,11 +34,15 @@ export function apply(ctx, config = {}) {
33
34
  if (owner.pid === process.pid)
34
35
  rmSync(ownerFile, { force: true });
35
36
  }
36
- catch { /* already gone */ }
37
+ catch {
38
+ /* already gone */
39
+ }
37
40
  try {
38
41
  store.close();
39
42
  }
40
- catch { /* closed */ }
43
+ catch {
44
+ /* closed */
45
+ }
41
46
  });
42
47
  /** @type {ReturnType<typeof createTriggers> | null} */
43
48
  let triggers = null;
@@ -60,7 +65,8 @@ export function apply(ctx, config = {}) {
60
65
  if (!sessionId || !engine.isBot(sessionId))
61
66
  return '';
62
67
  const view = rendered.get(sessionId) ?? render(sessionId);
63
- return view.texts[name] ?? '';
68
+ const texts = view.texts;
69
+ return texts[name] ?? '';
64
70
  };
65
71
  const sessionFrom = (assemble) => assemble?.agent?.id;
66
72
  const section = (name, order, pick) => {
@@ -68,7 +74,7 @@ export function apply(ctx, config = {}) {
68
74
  name,
69
75
  order,
70
76
  interpolate: false,
71
- text: (assemble) => pick(sessionFrom(assemble)),
77
+ text: (assemble) => pick(sessionFrom(assemble) ?? ''),
72
78
  });
73
79
  };
74
80
  const context = (name, order, required, pick) => {
@@ -117,8 +123,10 @@ export function apply(ctx, config = {}) {
117
123
  ctx.tools.register(definition);
118
124
  }
119
125
  ctx.on('session/event', (session, event) => {
120
- const sessionId = session?.id;
121
- if (typeof sessionId !== 'string' || event == null || typeof event.type !== 'string')
126
+ if (session == null || event == null || typeof event.type !== 'string')
127
+ return;
128
+ const sessionId = session.id;
129
+ if (typeof sessionId !== 'string')
122
130
  return;
123
131
  const bot = engine.isBot(sessionId);
124
132
  const worker = work?.isWorkerSession(sessionId) === true;
@@ -156,12 +164,12 @@ export function apply(ctx, config = {}) {
156
164
  }
157
165
  const op = event.surfaceOp;
158
166
  if (op && typeof op === 'object' && op.op === 'replace' && Array.isArray(event.sourceEventSeqs)) {
159
- engine.noteRemoval(sessionId, event.sourceEventSeqs.filter(seq => typeof seq === 'number'));
167
+ engine.noteRemoval(sessionId, event.sourceEventSeqs.filter((seq) => typeof seq === 'number'));
160
168
  }
161
169
  }
162
170
  if (triggers && event.type === 'turn/end') {
163
171
  const reason = event.data?.reason;
164
- triggers.observeTurnEnd(sessionId, event.data?.turn ?? null, reason && typeof reason === 'object' ? reason.kind ?? '' : '');
172
+ triggers.observeTurnEnd(sessionId, event.data?.turn ?? null, reason && typeof reason === 'object' ? (reason.kind ?? '') : '');
165
173
  }
166
174
  });
167
175
  ctx.on('agent/created', (payload) => {
@@ -189,6 +197,22 @@ export function apply(ctx, config = {}) {
189
197
  if (work) {
190
198
  for (const definition of workToolDefinitions(work, engine))
191
199
  ctx.tools.register(definition);
200
+ const gate = work;
201
+ // Main-session step budget: refuse the next step instead of cancelling a
202
+ // step that already ended. A refused step ends the turn as `blocked`.
203
+ ctx.on('agent/pre-step', (payload, next) => {
204
+ const sessionId = payload?.agent?.id;
205
+ if (typeof sessionId !== 'string' || sessionId === '')
206
+ return next();
207
+ const decision = gate.gateStep(sessionId, {
208
+ turn: payload?.turn,
209
+ step: payload?.step,
210
+ claimed: Array.isArray(payload?.messages) ? payload.messages.length : 0,
211
+ });
212
+ if (decision.kind === 'reject')
213
+ return Promise.resolve({ kind: 'reject' });
214
+ return next();
215
+ });
192
216
  }
193
217
  if (triggers || work) {
194
218
  const timer = setInterval(() => {
@@ -203,7 +227,7 @@ export function apply(ctx, config = {}) {
203
227
  ctx.logger?.info?.('session-foundations: ready dir=%s bindings=%s promoted=%s', dataDir, recovery.bindings, recovery.promoted.length);
204
228
  }
205
229
  /**
206
- * @param {import('@deepseek-ai/cordis').Context} ctx
230
+ * @param {import('./host.ts').PluginHost} ctx
207
231
  * @param {import('./src/store.js').Store} store
208
232
  * @param {import('./src/engine.js').Engine} engine
209
233
  */
@@ -220,14 +244,18 @@ function startTriggers(ctx, store, engine) {
220
244
  publishRuntime(store.root, null);
221
245
  });
222
246
  ctx.on('agent/inbox/claimed', (payload) => {
223
- const sessionId = payload?.agent?.id;
224
- const messageId = payload?.message?.id;
247
+ if (payload == null)
248
+ return;
249
+ const sessionId = payload.agent?.id;
250
+ const messageId = payload.message?.id;
225
251
  if (typeof sessionId === 'string' && typeof messageId === 'string')
226
252
  triggers.observeClaimed(sessionId, messageId, payload.turn ?? null);
227
253
  });
228
254
  ctx.on('agent/inbox/discarded', (payload) => {
229
- const sessionId = payload?.agent?.id;
230
- const messageId = payload?.message?.id;
255
+ if (payload == null)
256
+ return;
257
+ const sessionId = payload.agent?.id;
258
+ const messageId = payload.message?.id;
231
259
  if (typeof sessionId === 'string' && typeof messageId === 'string')
232
260
  triggers.observeDiscarded(sessionId, messageId);
233
261
  });
@@ -236,7 +264,7 @@ function startTriggers(ctx, store, engine) {
236
264
  /**
237
265
  * Bot dual-loop. Ordinary sessions never enter this runtime's tools.
238
266
  * Child agents are created without parentAgent so the main handle does not dispose them.
239
- * @param {import('@deepseek-ai/cordis').Context} ctx
267
+ * @param {import('./host.ts').PluginHost} ctx
240
268
  * @param {import('./src/store.js').Store} store
241
269
  * @param {import('./src/engine.js').Engine} engine
242
270
  * @param {{ work?: Partial<import('./src/work-admit.js').DEFAULT_WORK_BUDGET> }} config
@@ -245,16 +273,34 @@ function startWork(ctx, store, engine, config) {
245
273
  /** @type {Map<string, { dispose?: () => Promise<void> }>} */
246
274
  const workerHandles = new Map();
247
275
  const filePreset = ensureWorkerFilePreset(ctx);
276
+ const resolved = resolveWorkBudget(config.work ?? {}, process.env[WORK_BUDGET_ENV]);
277
+ if (resolved.ignored.length > 0) {
278
+ ctx.logger?.warn?.('session-foundations: ignored work budget keys %s', resolved.ignored.join(','));
279
+ }
280
+ ctx.logger?.info?.('session-foundations: main budget chat=%s steps/%sms main=%s steps/%sms', resolved.budget.chatMaxSteps, resolved.budget.chatWallMs, resolved.budget.mainMaxSteps, resolved.budget.mainWallMs);
248
281
  const work = createWorkRuntime(store, engine, {
249
- budget: config.work ?? {},
282
+ budget: resolved.budget,
283
+ log: (level, message) => {
284
+ const sink = level === 'warn' ? (ctx.logger?.warn ?? ctx.logger?.info) : ctx.logger?.info;
285
+ sink?.call(ctx.logger, message);
286
+ // DSH 0.2.2-rc.1 does not print plugin ctx.logger output by default, so a
287
+ // budget trip also goes to stderr (journald under systemd). No secrets.
288
+ if (level === 'warn')
289
+ console.warn(message);
290
+ },
291
+ onMainBudget: (sessionId, trip) => {
292
+ if (config.budgetNotice === false)
293
+ return;
294
+ postBudgetNotice(ctx, sessionId, trip).catch(error => {
295
+ ctx.logger?.warn?.('session-foundations: budget notice failed session=%s %s', sessionId, String(error));
296
+ });
297
+ },
250
298
  createChild: async (spec) => {
251
299
  let cwd = '';
252
300
  let model = null;
253
301
  try {
254
- const owner = ctx.agents.get(spec.ownerSessionId);
255
- cwd = owner?.session?.header?.cwd
256
- ?? ctx.sessions.get(spec.ownerSessionId)?.header?.cwd
257
- ?? '';
302
+ const owner = ctx.agents?.get(spec.ownerSessionId);
303
+ cwd = owner?.session?.header?.cwd ?? ctx.sessions?.get(spec.ownerSessionId)?.header?.cwd ?? '';
258
304
  model = owner?.model?.current?.() ?? null;
259
305
  }
260
306
  catch {
@@ -296,7 +342,9 @@ function startWork(ctx, store, engine, config) {
296
342
  const agent = liveAgent(ctx, sessionId);
297
343
  if (!agent)
298
344
  return;
299
- agent.cancel({ kind: 'user' }, { keepInbox: options.keepInbox === true });
345
+ // Never report a host cancel as a user cancel: the turn records
346
+ // { kind: 'aborted', reason: { kind: 'hook', reason } }.
347
+ agent.cancel({ kind: 'hook', reason: options.reason || 'session-foundations' }, { keepInbox: options.keepInbox === true });
300
348
  },
301
349
  snapshot: async (sessionId) => {
302
350
  try {
@@ -313,13 +361,49 @@ function startWork(ctx, store, engine, config) {
313
361
  workerHandles.clear();
314
362
  });
315
363
  ctx.on('agent/inbox/claimed', (payload) => {
316
- const sessionId = payload?.agent?.id;
317
- const messageId = payload?.message?.id;
364
+ if (payload == null)
365
+ return;
366
+ const sessionId = payload.agent?.id;
367
+ const messageId = payload.message?.id;
318
368
  if (typeof sessionId === 'string' && typeof messageId === 'string')
319
369
  work.observeClaimed(sessionId, messageId, payload.turn ?? null);
320
370
  });
321
371
  return work;
322
372
  }
373
+ /**
374
+ * Text of the inbox notice that follows a main-session budget trip.
375
+ * @param {MainBudgetTrip} trip
376
+ */
377
+ export function budgetNoticeText(trip) {
378
+ const seconds = Math.round(trip.elapsedMs / 1000);
379
+ const what = trip.reason === 'steps'
380
+ ? `it reached the step limit (${trip.steps}/${trip.maxSteps} steps)`
381
+ : `it reached the time limit (${seconds}s of ${Math.round(trip.wallMs / 1000)}s)`;
382
+ return [
383
+ '[foundations:budget]',
384
+ `The previous turn (turn ${trip.turn}) was stopped by the bot host because ${what}. The user did not cancel it.`,
385
+ `cause: ${trip.cause}`,
386
+ 'In one short message, tell the user the turn was cut off by the budget and what is already done.',
387
+ 'If work remains, call foundations_dispatch with a briefing for the remaining work so a worker continues it, and say so. Otherwise ask the user whether to continue.',
388
+ ].join('\n');
389
+ }
390
+ /**
391
+ * Wait until the stopped turn is idle, then post the notice as a next-turn
392
+ * message. Posting while the turn is still unwinding could leave it unclaimed.
393
+ * @param {import('./host.ts').HostContext} ctx
394
+ * @param {string} sessionId
395
+ * @param {MainBudgetTrip} trip
396
+ */
397
+ async function postBudgetNotice(ctx, sessionId, trip) {
398
+ const agent = liveAgent(ctx, sessionId);
399
+ if (!agent)
400
+ return;
401
+ await new Promise(resolve => setImmediate(resolve));
402
+ if (typeof agent.whenIdle === 'function')
403
+ await agent.whenIdle();
404
+ const messageId = `${BUDGET_NOTICE_PREFIX}${trip.turn}:${Date.now().toString(36)}`;
405
+ await followupDurable(ctx, sessionId, messageId, budgetNoticeText(trip));
406
+ }
323
407
  /**
324
408
  * @param {ReturnType<typeof createTriggers>} triggers
325
409
  * @param {import('./src/engine.js').Engine} engine
@@ -391,7 +475,7 @@ function triggerTool(name, description, parameters, run, isBot) {
391
475
  };
392
476
  }
393
477
  /**
394
- * @param {import('@deepseek-ai/cordis').Context} ctx
478
+ * @param {import('./host.ts').HostContext} ctx
395
479
  * @param {string} sessionId
396
480
  * @param {string} messageId
397
481
  */
@@ -406,6 +490,9 @@ function messageText(event) {
406
490
  const content = event.data?.message?.content ?? event.data?.content;
407
491
  if (!Array.isArray(content))
408
492
  return '';
409
- return content.filter(block => block?.type === 'text').map(block => block.text ?? '').join('\n');
493
+ return content
494
+ .filter(block => block?.type === 'text')
495
+ .map(block => block.text ?? '')
496
+ .join('\n');
410
497
  }
411
498
  export { pidAlive };
package/dist/live-diff.js CHANGED
@@ -15,7 +15,9 @@ function stable(value) {
15
15
  if (Array.isArray(value))
16
16
  return `[${value.map(item => stable(item)).join(',')}]`;
17
17
  const record = value;
18
- const keys = Object.keys(record).filter(key => record[key] !== undefined).sort();
18
+ const keys = Object.keys(record)
19
+ .filter(key => record[key] !== undefined)
20
+ .sort();
19
21
  return `{${keys.map(key => `${JSON.stringify(key)}:${stable(record[key])}`).join(',')}}`;
20
22
  }
21
23
  function isObject(value) {
@@ -19,7 +19,9 @@ export function stableStringify(value) {
19
19
  if (Array.isArray(value))
20
20
  return `[${value.map(item => stableStringify(item)).join(',')}]`;
21
21
  const record = value;
22
- const keys = Object.keys(record).filter(key => record[key] !== undefined).sort();
22
+ const keys = Object.keys(record)
23
+ .filter(key => record[key] !== undefined)
24
+ .sort();
23
25
  return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(',')}}`;
24
26
  }
25
27
  export function canonicalBytes(value) {
package/dist/provision.js CHANGED
@@ -33,6 +33,8 @@ export async function provisionSession(engine, input) {
33
33
  ? input.idempotencyKey.trim()
34
34
  : `provision:${sessionId}:${createHash('sha256').update(factText).digest('hex').slice(0, 16)}`;
35
35
  const remember = toolDefinitions(engine).find(item => item.name === 'foundations_remember');
36
+ if (!remember)
37
+ throw new Error('foundations_remember is unavailable.');
36
38
  const fact = await remember.execute({
37
39
  target: 'fact',
38
40
  content: factText,
@@ -1,8 +1,8 @@
1
- /** @type {Map<string, unknown>} */
1
+ /** @type {Map<string, any>} */
2
2
  const runtimes = new Map();
3
3
  /**
4
4
  * @param {string} dataDir
5
- * @param {unknown} runtime
5
+ * @param {any} runtime
6
6
  */
7
7
  export function publishRuntime(dataDir, runtime) {
8
8
  if (runtime)
@@ -16,11 +16,11 @@ export function publishRuntime(dataDir, runtime) {
16
16
  export function runtimeFor(dataDir) {
17
17
  return runtimes.get(dataDir) ?? null;
18
18
  }
19
- /** @type {Map<string, unknown>} */
19
+ /** @type {Map<string, any>} */
20
20
  const workRuntimes = new Map();
21
21
  /**
22
22
  * @param {string} dataDir
23
- * @param {unknown} runtime
23
+ * @param {any} runtime
24
24
  */
25
25
  export function publishWorkRuntime(dataDir, runtime) {
26
26
  if (runtime)
@@ -94,7 +94,7 @@ export function forgetWorkspaceId(workspaceFile, sessionId) {
94
94
  return;
95
95
  const data = JSON.parse(readFileSync(workspaceFile, 'utf8'));
96
96
  if (data?.global && Array.isArray(data.global.archivedSessionIds)) {
97
- data.global.archivedSessionIds = data.global.archivedSessionIds.filter(id => id !== sessionId);
97
+ data.global.archivedSessionIds = data.global.archivedSessionIds.filter((id) => id !== sessionId);
98
98
  }
99
99
  const workspaces = data?.tables?.workspaces;
100
100
  if (workspaces && typeof workspaces === 'object') {
@@ -107,5 +107,9 @@ function sanitize(parsed) {
107
107
  function cleanPreview(value) {
108
108
  if (typeof value !== 'string')
109
109
  return '';
110
- return value.replace(/[\u0000-\u001f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, MAX_PREVIEW);
110
+ return value
111
+ .replace(/[\u0000-\u001f]+/g, ' ')
112
+ .replace(/\s+/g, ' ')
113
+ .trim()
114
+ .slice(0, MAX_PREVIEW);
111
115
  }
package/dist/store.js CHANGED
@@ -346,7 +346,16 @@ CREATE TABLE IF NOT EXISTS user_deliveries (
346
346
  */
347
347
  export function openStore(dataDir) {
348
348
  const root = ensureDir(dataDir);
349
- for (const dir of ['blobs/persona', 'blobs/skills', 'src/soul', 'src/skills/public', 'src/skills/private', 'export', 'backups', 'secrets/webhooks']) {
349
+ for (const dir of [
350
+ 'blobs/persona',
351
+ 'blobs/skills',
352
+ 'src/soul',
353
+ 'src/skills/public',
354
+ 'src/skills/private',
355
+ 'export',
356
+ 'backups',
357
+ 'secrets/webhooks',
358
+ ]) {
350
359
  mkdirSync(join(root, dir), { recursive: true, mode: 0o700 });
351
360
  }
352
361
  const db = new DatabaseSync(join(root, 'persona.sqlite'));
@@ -390,12 +399,16 @@ class KeyedLock {
390
399
  async run(key, fn, timeoutMs) {
391
400
  const prev = this.tails.get(key) ?? Promise.resolve();
392
401
  let release = () => { };
393
- const current = new Promise(resolve => { release = () => resolve(); });
402
+ const current = new Promise(resolve => {
403
+ release = () => resolve();
404
+ });
394
405
  this.tails.set(key, current);
395
406
  let timer;
396
407
  const acquired = await Promise.race([
397
408
  prev.then(() => 'ok'),
398
- new Promise(resolve => { timer = setTimeout(() => resolve('busy'), timeoutMs); }),
409
+ new Promise(resolve => {
410
+ timer = setTimeout(() => resolve('busy'), timeoutMs);
411
+ }),
399
412
  ]);
400
413
  clearTimeout(timer);
401
414
  if (acquired !== 'ok') {
@@ -419,7 +432,7 @@ export class Store {
419
432
  lock;
420
433
  busyTimeoutMs;
421
434
  /**
422
- * @param {DatabaseSync} db
435
+ * @param {SqlDatabase} db
423
436
  * @param {string} root
424
437
  */
425
438
  constructor(db, root) {
@@ -447,7 +460,9 @@ export class Store {
447
460
  try {
448
461
  this.db.exec('ROLLBACK');
449
462
  }
450
- catch { /* already closed */ }
463
+ catch {
464
+ /* already closed */
465
+ }
451
466
  throw error;
452
467
  }
453
468
  }, this.busyTimeoutMs);