@thready-web/dsh-bot-plugin 0.1.0-beta.2 → 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/README.md CHANGED
@@ -37,6 +37,37 @@ In `cordis.patch.yml` every new entry must be wrapped in `- insert:`:
37
37
 
38
38
  Start the host with `dsh --profile <name> --host 127.0.0.1 --port <port> --no-open` after the patch lists these entries. The official client is `/`. The workbench is `/dsh-bot/`. From the `dsh-plugins` repository, `npx dsh-bot` writes that patch and starts the process.
39
39
 
40
+ ## Main-session budget
41
+
42
+ A bot main session may do the work itself (bash, write, ...) or hand it to a worker with `foundations_dispatch`. The host keeps a runaway guard on each main turn:
43
+
44
+ | Field | Default | Meaning |
45
+ | --- | --- | --- |
46
+ | `chatMaxSteps` / `chatWallMs` | 80 / 30 min | Cap for every main turn |
47
+ | `mainMaxSteps` / `mainWallMs` | 80 / 30 min | Cap after a dispatch or a host tool. It can only tighten the chat cap; with the defaults it changes nothing. Set it lower to push long work onto workers. |
48
+
49
+ - The step cap is checked in `agent/pre-step`: the next step is refused and the turn ends `blocked`. A step that already ended is never cancelled, so a turn whose last step answered the user ends `completed`.
50
+ - The wall cap stops a still-running step with `agent.cancel({ kind: 'hook', reason: 'main-budget:wall' })`. Host cancels never use `{ kind: 'user' }` (worker caps use `worker-budget:*`, ticket cancels `ticket-cancel`).
51
+ - Each trip is written to stderr (`session-foundations: main budget main-budget:steps session=… turn=… steps=…`) and posts one `[foundations:budget]` next-turn message. The model then tells the user the turn was cut off and may dispatch the rest to a worker. Set `budgetNotice: false` to skip the message.
52
+
53
+ Override in the patch (`config.work`) or with the `DSH_BOT_WORK_BUDGET` environment variable (the launcher's `--work-budget`). Config wins over the environment. Both accept `steps` / `wall` shorthands and duration strings:
54
+
55
+ ```yaml
56
+ - insert:
57
+ - id: session-foundations
58
+ name: "@thready-web/dsh-bot-plugin"
59
+ config:
60
+ work: { steps: 120, wall: 45m }
61
+ ```
62
+
63
+ ```bash
64
+ DSH_BOT_WORK_BUDGET='steps=120,wall=45m,mainMaxSteps=10'
65
+ ```
66
+
67
+ ## Session working directory
68
+
69
+ Workbench sessions start in `THREADY_SESSION_CWD` when set, otherwise in `<DSH_HOME>/workspace` (created on first use), never in `DSH_HOME` itself, which holds the owner token and profiles.
70
+
40
71
  DSH loads `dist/`. Rebuild after changing `src/`. Until `npm --prefix ui run build` has run, `/dsh-bot/` is 404.
41
72
 
42
73
  Host integration needs Node `>= 24.9` and `DSH_BIN`:
package/dist/desk.js CHANGED
@@ -1,9 +1,31 @@
1
1
  /** Workbench routes inside the DSH process. The browser calls /dsh-bot/api. */
2
- import { readFileSync } from 'node:fs';
3
- import { dirname, join } from 'node:path';
2
+ import { mkdirSync, readFileSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
4
  import { openLedger, validIdempotencyKey } from "./desk-ledger.js";
5
5
  import { openSessionPreviews } from "./session-previews.js";
6
6
  import { purgeSessionFiles, sessionDirectory, writeBotMarker } from "./session-files.js";
7
+ /**
8
+ * Working directory for workbench-created sessions. THREADY_SESSION_CWD wins;
9
+ * otherwise <DSH_HOME>/workspace, so the model does not start inside DSH_HOME
10
+ * (owner-token, profiles/, persona.sqlite). Empty only when neither is set,
11
+ * which keeps DSH's own default (the server process cwd).
12
+ * @param {Record<string, string | undefined>} env
13
+ * @param {{ mkdir?: boolean }} [options]
14
+ */
15
+ export function defaultSessionCwd(env, options = {}) {
16
+ const explicit = (env.THREADY_SESSION_CWD ?? '').trim();
17
+ const home = (env.DSH_HOME ?? '').trim();
18
+ const cwd = explicit !== '' ? resolve(explicit) : home !== '' ? join(resolve(home), 'workspace') : '';
19
+ if (cwd !== '' && options.mkdir !== false) {
20
+ try {
21
+ mkdirSync(cwd, { recursive: true, mode: 0o700 });
22
+ }
23
+ catch {
24
+ /* session/create reports a bad cwd */
25
+ }
26
+ }
27
+ return cwd;
28
+ }
7
29
  const API = '/session-foundations/api';
8
30
  const PREVIEW_SESSION = /^(?:session|worker)-[A-Za-z0-9-]+$/;
9
31
  const SECRET_KEY = /token|secret|password|authorization|api[-_]?key|cookie/i;
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";
@@ -24,7 +24,7 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
24
24
  : createDesk({
25
25
  ledgerFile: join(storeDir, 'desk-ledger.json'),
26
26
  profileDir,
27
- sessionCwd: (process.env.THREADY_SESSION_CWD ?? '').trim(),
27
+ sessionCwd: defaultSessionCwd(process.env),
28
28
  isBot: sessionId => engine.isBot(sessionId),
29
29
  mark: sessionId => engine.markBot(sessionId),
30
30
  hold: sessionId => {
package/dist/index.js CHANGED
@@ -8,9 +8,9 @@ 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
16
  // Cordis throws if a plugin reads a service it did not inject. Crash recovery reads the session log through this one.
@@ -197,6 +197,22 @@ export function apply(ctx, config = {}) {
197
197
  if (work) {
198
198
  for (const definition of workToolDefinitions(work, engine))
199
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
+ });
200
216
  }
201
217
  if (triggers || work) {
202
218
  const timer = setInterval(() => {
@@ -257,8 +273,28 @@ function startWork(ctx, store, engine, config) {
257
273
  /** @type {Map<string, { dispose?: () => Promise<void> }>} */
258
274
  const workerHandles = new Map();
259
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);
260
281
  const work = createWorkRuntime(store, engine, {
261
- 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
+ },
262
298
  createChild: async (spec) => {
263
299
  let cwd = '';
264
300
  let model = null;
@@ -306,7 +342,9 @@ function startWork(ctx, store, engine, config) {
306
342
  const agent = liveAgent(ctx, sessionId);
307
343
  if (!agent)
308
344
  return;
309
- 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 });
310
348
  },
311
349
  snapshot: async (sessionId) => {
312
350
  try {
@@ -332,6 +370,40 @@ function startWork(ctx, store, engine, config) {
332
370
  });
333
371
  return work;
334
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
+ }
335
407
  /**
336
408
  * @param {ReturnType<typeof createTriggers>} triggers
337
409
  * @param {import('./src/engine.js').Engine} engine
@@ -1,9 +1,15 @@
1
1
  /** Admission and host budgets. Neither function calls a model or reorders an inbox. */
2
+ /**
3
+ * Main-session caps. The main bot may do real work itself (bash, write, ...),
4
+ * so the caps are a runaway guard, not a "dispatch first" policy. `main*` is
5
+ * the cap after a dispatch or a host tool and is never looser than `chat*`;
6
+ * set it lower in config to bring back the old "hand long work to a worker" squeeze.
7
+ */
2
8
  export const DEFAULT_WORK_BUDGET = Object.freeze({
3
- mainMaxSteps: 2,
4
- mainWallMs: 20_000,
5
- chatMaxSteps: 4,
6
- chatWallMs: 120_000,
9
+ mainMaxSteps: 80,
10
+ mainWallMs: 30 * 60 * 1000,
11
+ chatMaxSteps: 80,
12
+ chatWallMs: 30 * 60 * 1000,
7
13
  holdMs: 15_000,
8
14
  workerMaxSteps: 8,
9
15
  workerWallMs: 10 * 60 * 1000,
@@ -14,6 +20,110 @@ export const DEFAULT_WORK_BUDGET = Object.freeze({
14
20
  starveMs: 30_000,
15
21
  mergeWindowMs: 1_000,
16
22
  });
23
+ const BUDGET_KEYS = Object.keys(DEFAULT_WORK_BUDGET);
24
+ /** Environment variable the launcher uses to pass `--work-budget` to the plugin. */
25
+ export const WORK_BUDGET_ENV = 'DSH_BOT_WORK_BUDGET';
26
+ /**
27
+ * Milliseconds from a number or a `90s` / `30m` / `2h` / `1500ms` string.
28
+ * @param {unknown} value
29
+ */
30
+ function durationMs(value) {
31
+ if (typeof value === 'number')
32
+ return value;
33
+ if (typeof value !== 'string')
34
+ return Number.NaN;
35
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h)?\s*$/i.exec(value);
36
+ if (!match)
37
+ return Number.NaN;
38
+ const unit = (match[2] ?? 'ms').toLowerCase();
39
+ const scale = unit === 'h' ? 3_600_000 : unit === 'm' ? 60_000 : unit === 's' ? 1000 : 1;
40
+ return Number(match[1]) * scale;
41
+ }
42
+ /**
43
+ * Keep only known, positive, finite budget fields. Unknown keys and bad values
44
+ * are dropped (and listed in `ignored`) so a typo never zeroes a cap.
45
+ * Shorthands: `steps` sets mainMaxSteps and chatMaxSteps; `wall` sets mainWallMs and chatWallMs.
46
+ * Fields ending in `Ms` accept duration strings such as `30m`.
47
+ * @param {unknown} input
48
+ */
49
+ export function normalizeWorkBudget(input) {
50
+ const budget = {};
51
+ const ignored = [];
52
+ if (input == null || typeof input !== 'object' || Array.isArray(input))
53
+ return { budget, ignored };
54
+ const raw = { ...input };
55
+ const expanded = {};
56
+ if ('steps' in raw) {
57
+ expanded.mainMaxSteps = raw.steps;
58
+ expanded.chatMaxSteps = raw.steps;
59
+ delete raw.steps;
60
+ }
61
+ if ('wall' in raw) {
62
+ expanded.mainWallMs = raw.wall;
63
+ expanded.chatWallMs = raw.wall;
64
+ delete raw.wall;
65
+ }
66
+ Object.assign(expanded, raw);
67
+ for (const [key, value] of Object.entries(expanded)) {
68
+ if (!BUDGET_KEYS.includes(key)) {
69
+ ignored.push(key);
70
+ continue;
71
+ }
72
+ const number = key.endsWith('Ms') ? durationMs(value) : Number(value);
73
+ if (!Number.isFinite(number) || number <= 0) {
74
+ ignored.push(key);
75
+ continue;
76
+ }
77
+ budget[key] = Math.floor(number);
78
+ }
79
+ return { budget, ignored };
80
+ }
81
+ /**
82
+ * Parse `--work-budget` / DSH_BOT_WORK_BUDGET: JSON (`{"steps":80,"wall":"30m"}`)
83
+ * or comma-separated `key=value` (`steps=80,wall=30m,mainMaxSteps=10`).
84
+ * @param {string | undefined} text
85
+ */
86
+ export function parseWorkBudget(text) {
87
+ const source = typeof text === 'string' ? text.trim() : '';
88
+ if (source === '')
89
+ return { budget: {}, ignored: [] };
90
+ if (source.startsWith('{')) {
91
+ try {
92
+ return normalizeWorkBudget(JSON.parse(source));
93
+ }
94
+ catch {
95
+ return { budget: {}, ignored: [source] };
96
+ }
97
+ }
98
+ const object = {};
99
+ const ignored = [];
100
+ for (const part of source.split(',')) {
101
+ const piece = part.trim();
102
+ if (piece === '')
103
+ continue;
104
+ const eq = piece.indexOf('=');
105
+ if (eq <= 0) {
106
+ ignored.push(piece);
107
+ continue;
108
+ }
109
+ object[piece.slice(0, eq).trim()] = piece.slice(eq + 1).trim();
110
+ }
111
+ const normalized = normalizeWorkBudget(object);
112
+ return { budget: normalized.budget, ignored: [...ignored, ...normalized.ignored] };
113
+ }
114
+ /**
115
+ * Defaults, then the environment (launcher `--work-budget`), then plugin config `work`.
116
+ * @param {unknown} config
117
+ * @param {string | undefined} envText
118
+ */
119
+ export function resolveWorkBudget(config, envText) {
120
+ const fromEnv = parseWorkBudget(envText);
121
+ const fromConfig = normalizeWorkBudget(config);
122
+ return {
123
+ budget: { ...DEFAULT_WORK_BUDGET, ...fromEnv.budget, ...fromConfig.budget },
124
+ ignored: [...fromEnv.ignored, ...fromConfig.ignored],
125
+ };
126
+ }
17
127
  /**
18
128
  * Pending next-turn ids whose source is not a ticket notice and not a delivery.
19
129
  * @param {string[]} pendingIds
package/dist/work-mock.js CHANGED
@@ -97,7 +97,11 @@ export function createMockWorld() {
97
97
  return true;
98
98
  },
99
99
  async cancel(sessionId, options) {
100
- cancels.push({ sessionId, keepInbox: options?.keepInbox === true });
100
+ cancels.push({
101
+ sessionId,
102
+ keepInbox: options?.keepInbox === true,
103
+ ...(typeof options?.reason === 'string' ? { reason: options.reason } : {}),
104
+ });
101
105
  },
102
106
  async snapshot(sessionId) {
103
107
  return session(sessionId).events.map(event => ({ ...event, data: event.data }));
@@ -15,6 +15,8 @@ const LABEL = {
15
15
  cancelled: 'cancelled',
16
16
  failed: 'failed',
17
17
  };
18
+ /** Message id prefix of the inbox notice sent after a main-session budget trip. */
19
+ export const BUDGET_NOTICE_PREFIX = 'foundations-budget:';
18
20
  /**
19
21
  * Host-side ticket protocol. The model is not called from here.
20
22
  * Native inbox delivery stays in `options.push` / `options.pendingIds`.
@@ -75,6 +77,7 @@ export function createWorkRuntime(store, engine, options = {}) {
75
77
  admit,
76
78
  observeSession,
77
79
  observeClaimed,
80
+ gateStep,
78
81
  isWorkerSession,
79
82
  summaries: (owner) => book.summaries(owner),
80
83
  detail: (id) => book.detail(id),
@@ -218,7 +221,7 @@ export function createWorkRuntime(store, engine, options = {}) {
218
221
  return toolError(cancelled.error, cancelled.message ?? 'Cancel failed.');
219
222
  const child = cancelled.ticket.child_session_id;
220
223
  if (resident && child && options.cancel) {
221
- await options.cancel(child, { keepInbox: note !== '' });
224
+ await options.cancel(child, { keepInbox: note !== '', reason: 'ticket-cancel' });
222
225
  }
223
226
  if (resident && note !== '' && cancelled.input)
224
227
  await pushInput(book, cancelled.input, deps);
@@ -249,7 +252,7 @@ export function createWorkRuntime(store, engine, options = {}) {
249
252
  state.clear?.();
250
253
  }
251
254
  if (resident && child && options.cancel)
252
- await options.cancel(child, { keepInbox: false });
255
+ await options.cancel(child, { keepInbox: false, reason: 'grant-denied' });
253
256
  return { ok: true, ticketId: found.ticket.id, ticketStatus: 'failed', denied: true };
254
257
  }
255
258
  const added = await store.write('work', () => book.extendBudget(found.ticket.id, {
@@ -855,6 +858,13 @@ export function createWorkRuntime(store, engine, options = {}) {
855
858
  return;
856
859
  }
857
860
  const state = arms.get(sessionId);
861
+ if (role === 'main' &&
862
+ state &&
863
+ (event.type === 'user/message' || event.type === 'agent/inbox/claimed') &&
864
+ (messageIdOf(event) ?? '').startsWith(BUDGET_NOTICE_PREFIX)) {
865
+ state.budgetNotice = true;
866
+ return;
867
+ }
858
868
  if (event.type === 'assistant/message' && role === 'worker' && state) {
859
869
  const seq = typeof event.seq === 'number' ? event.seq : null;
860
870
  if (seq != null && state.lastSeq != null && seq <= state.lastSeq)
@@ -873,8 +883,72 @@ export function createWorkRuntime(store, engine, options = {}) {
873
883
  const live = state ?? arm(sessionId, event.data?.turn ?? 0, role);
874
884
  const step = Number(event.data?.step);
875
885
  live.steps = Number.isFinite(step) ? Math.max(live.steps, step) : live.steps + 1;
876
- if (role === 'main')
877
- consider(sessionId, live, false);
886
+ // The main step cap is enforced in gateStep (agent/pre-step), before the next
887
+ // step starts. Cancelling here would abort a turn whose last step already
888
+ // ended naturally and record it as aborted.
889
+ }
890
+ /**
891
+ * `agent/pre-step` gate for a bot main session. Refuses the next step once the
892
+ * turn has used its step or wall budget. A turn whose last step ended without
893
+ * a tool call never reaches this gate, so it still ends `completed`.
894
+ * Messages claimed for this step (a user steer) always enter: dropping them on
895
+ * a refusal would lose user input.
896
+ * @param {string} sessionId
897
+ * @param {{ turn?: number, step?: number, claimed?: number }} position
898
+ */
899
+ function gateStep(sessionId, position = {}) {
900
+ if (budgetRole(sessionId) !== 'main')
901
+ return { kind: 'enter' };
902
+ const state = arms.get(sessionId);
903
+ if (!state || state.role !== 'main' || state.closing)
904
+ return { kind: 'enter' };
905
+ if ((position.claimed ?? 0) > 0)
906
+ return { kind: 'enter' };
907
+ const elapsed = Math.max(0, now().getTime() - state.startedAt);
908
+ const reason = budgetTrip({
909
+ steps: state.steps,
910
+ elapsedMs: elapsed,
911
+ maxSteps: state.limits.maxSteps,
912
+ wallMs: state.limits.wallMs,
913
+ });
914
+ if (reason !== 'steps' && reason !== 'wall')
915
+ return { kind: 'enter' };
916
+ const trip = tripMain(sessionId, state, reason, elapsed, 'pre-step');
917
+ return { kind: 'reject', trip };
918
+ }
919
+ /**
920
+ * Record, log, and announce one main-session budget trip.
921
+ * @param {string} sessionId
922
+ * @param {BudgetArm} state
923
+ * @param {'steps' | 'wall'} reason
924
+ * @param {number} elapsed
925
+ * @param {'pre-step' | 'timer'} via
926
+ */
927
+ function tripMain(sessionId, state, reason, elapsed, via) {
928
+ const trip = {
929
+ reason,
930
+ cause: `main-budget:${reason}`,
931
+ turn: state.turn,
932
+ steps: state.steps,
933
+ elapsedMs: elapsed,
934
+ maxSteps: state.limits.maxSteps,
935
+ wallMs: state.limits.wallMs,
936
+ via,
937
+ notify: !state.budgetNotice,
938
+ };
939
+ if (state.tripped)
940
+ return { ...trip, notify: false };
941
+ state.tripped = true;
942
+ options.log?.('warn', `session-foundations: main budget ${trip.cause} session=${sessionId} turn=${trip.turn} steps=${trip.steps}/${trip.maxSteps} elapsedMs=${trip.elapsedMs}/${trip.wallMs} via=${via}`, { sessionId, ...trip });
943
+ if (trip.notify) {
944
+ try {
945
+ options.onMainBudget?.(sessionId, trip);
946
+ }
947
+ catch {
948
+ /* the notice is best effort; the log line above stays */
949
+ }
950
+ }
951
+ return trip;
878
952
  }
879
953
  /**
880
954
  * @param {string} sessionId
@@ -906,7 +980,8 @@ export function createWorkRuntime(store, engine, options = {}) {
906
980
  return { ok: true };
907
981
  }
908
982
  /**
909
- * A dispatch or a host tool leaves the chat budget and uses the short cap.
983
+ * A dispatch or a host tool moves the turn onto the `main*` cap. The cap can
984
+ * only tighten: with the defaults (main == chat) this changes nothing.
910
985
  * @param {string} sessionId
911
986
  */
912
987
  function tightenMain(sessionId) {
@@ -914,11 +989,15 @@ export function createWorkRuntime(store, engine, options = {}) {
914
989
  if (!state || state.role !== 'main' || state.tight || state.closing || state.tripped)
915
990
  return;
916
991
  state.tight = true;
992
+ const maxSteps = Math.min(state.limits.maxSteps, limits.mainMaxSteps);
993
+ const wallMs = Math.min(state.limits.wallMs, limits.mainWallMs);
994
+ if (maxSteps === state.limits.maxSteps && wallMs === state.limits.wallMs)
995
+ return;
917
996
  state.limits = {
918
997
  ...state.limits,
919
- maxSteps: limits.mainMaxSteps,
920
- wallMs: limits.mainWallMs,
921
- ceilingWall: limits.mainWallMs,
998
+ maxSteps,
999
+ wallMs,
1000
+ ceilingWall: wallMs,
922
1001
  };
923
1002
  state.clear?.();
924
1003
  const elapsed = Math.max(0, now().getTime() - state.startedAt);
@@ -958,6 +1037,7 @@ export function createWorkRuntime(store, engine, options = {}) {
958
1037
  tight: false,
959
1038
  limits: caps,
960
1039
  tripped: false,
1040
+ budgetNotice: false,
961
1041
  extensionOpen: false,
962
1042
  closing: false,
963
1043
  clear: () => { },
@@ -1014,17 +1094,14 @@ export function createWorkRuntime(store, engine, options = {}) {
1014
1094
  if (state.closing)
1015
1095
  return;
1016
1096
  if (state.role === 'main') {
1017
- const elapsed = fromTimer ? state.limits.wallMs : now().getTime() - state.startedAt;
1018
- const reason = budgetTrip({
1019
- steps: state.steps,
1020
- elapsedMs: elapsed,
1021
- maxSteps: state.limits.maxSteps,
1022
- wallMs: state.limits.wallMs,
1023
- });
1024
- if (!reason || state.tripped)
1097
+ // Step caps are enforced by gateStep before the next step. Only the wall
1098
+ // timer stops a step that is still running; the arm is cleared on
1099
+ // turn/end, so a finished turn is never cancelled here.
1100
+ if (!fromTimer || state.tripped)
1025
1101
  return;
1026
- state.tripped = true;
1027
- Promise.resolve(options.cancel?.(sessionId, { keepInbox: true })).catch(() => { });
1102
+ const elapsed = Math.max(state.limits.wallMs, now().getTime() - state.startedAt);
1103
+ const trip = tripMain(sessionId, state, 'wall', elapsed, 'timer');
1104
+ Promise.resolve(options.cancel?.(sessionId, { keepInbox: true, reason: trip.cause })).catch(() => { });
1028
1105
  return;
1029
1106
  }
1030
1107
  const elapsed = Math.max(0, now().getTime() - state.startedAt);
@@ -1118,7 +1195,7 @@ export function createWorkRuntime(store, engine, options = {}) {
1118
1195
  return;
1119
1196
  state.closing = true;
1120
1197
  state.clear?.();
1121
- Promise.resolve(options.cancel?.(sessionId, { keepInbox: false })).catch(() => { });
1198
+ Promise.resolve(options.cancel?.(sessionId, { keepInbox: false, reason: `worker-budget:${reason}` })).catch(() => { });
1122
1199
  const attempt = book.attemptForChild(sessionId);
1123
1200
  if (attempt)
1124
1201
  book.failRunning(attempt.ticket_id, reason);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thready-web/dsh-bot-plugin",
3
- "version": "0.1.0-beta.2",
3
+ "version": "0.1.0-beta.3",
4
4
  "type": "module",
5
5
  "description": "DSH bot plugin: session persona, memory, work, hash routing, and the workbench. Pinned to @deepseek-ai/dsh 0.2.2-rc.1.",
6
6
  "license": "MIT",
@@ -32,7 +32,7 @@
32
32
  "build": "node build.mjs",
33
33
  "type-check": "tsc -p tsconfig.typecheck.json --noEmit && tsc -p tsconfig.client.json --noEmit",
34
34
  "test": "node scripts/unit-tests.mjs",
35
- "test:host": "npm run build && node --test test/host-integration.test.ts && node --test test/triggers-host.test.ts",
35
+ "test:host": "npm run build && node --test test/host-integration.test.ts && node --test test/triggers-host.test.ts && node --test test/budget-host.test.ts",
36
36
  "format": "biome format --write src test ui/src client.js scripts",
37
37
  "format:check": "biome check src test ui/src client.js scripts"
38
38
  },