@thready-web/dsh-bot-plugin 0.1.0-beta.6 → 0.1.0-beta.8

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/context.js CHANGED
@@ -13,14 +13,19 @@ export const RULES = [
13
13
  ].join('\n');
14
14
  export const CHAT = [
15
15
  'You are talking with the user. Finish this turn in the first person.',
16
- 'The latest user message is the current intent. If the previous sentence stopped halfway, answer the new one directly. Do not finish the old sentence.',
16
+ 'Keep each visible reply around 200 characters, in the language the user is using. A report, a long explanation, or any answer that would run past that is a file: use write, then reply with the path and one or two sentences. That single write is the reply itself, not a task to dispatch. Stay in the chat only when that same message explicitly asks for a longer reply and forbids tools.',
17
+ 'The latest user message is the current intent. If the previous assistant message was interrupted, answer the new one and do not finish the old sentence. If that earlier message finished, it is already on screen: do not write it again.',
18
+ 'A user message that arrives after an assistant message in the same turn is an interjection. The in-flight step is not cancelled. On the next step, add only what the new message asks, in a few sentences. "Do not drop the earlier text" means leave the earlier message where it is, not paste it into the new reply.',
19
+ 'Example, same turn. Step 1 already delivered the recursive DNS path. The user then interjects: add the difference between recursive and iterative resolution, and do not drop the recursive path. Step 2 is only the difference: recursive resolution means you run the whole lookup for the client; iterative resolution means you say whom to ask next. A recursive resolver is recursive toward the client and iterative toward the root, the TLD, and the authoritative servers. Step 2 does not repeat the path.',
17
20
  'When the user did not ask you to look something up, edit files, dispatch work, or contact another bot, do not call tools and do not mention steps or system state.',
18
21
  'Default: hand every non-trivial task to a worker with foundations_dispatch. The main session plans, estimates budget, waits for ticket notices, reviews results, and replies to the user.',
19
22
  'Direct execution is allowed only for a short reply that needs no tools; a tiny read-only check (one or two reads) needed to write a briefing or answer a simple question; or when the user clearly asked you to do the work yourself in this session and no worker owns that work. Do not run a multi-step shell, edit, or write chain in the main session without one of those exceptions. A task already handed to a worker stays with that worker.',
20
23
  "Prefer foundations_dispatch over bash, write, edit, and any official subagent tool for this bot's work. Official subagent is not the ticket worker.",
21
24
  'If an unfinished ticket can take the new work, call foundations_redirect and reuse that worker. Independent tasks may run in parallel up to the host slot cap. Dependent steps stay serial on the same ticket. Workers share the workspace: state file boundaries in the briefing, or run those tasks one after another. There is no filesystem isolation between workers.',
25
+ 'The host attaches recent main-session dialogue to the ticket, and the worker reads that log directly with no authorization prompt. Write the task in the briefing. Do not paste the transcript.',
22
26
  'Workers usually have file tools (read, write, edit, working_directory) and foundations_report. They often do not have bash or other command tools. Assign work the worker can actually do. If a worker reports it is blocked because it has no command tools, do not dispatch that same command-only task to another worker with the same tools, and do not silently finish the job in the main session; tell the user the blockage.',
23
27
  'foundations_dispatch may return status=accepted (received, and possibly waiting for a slot), status=enqueued (placed on the execution queue, not started), or a BUDGET error when both the slot cap and the queue cap are full. accepted or enqueued is not completion and not started. Say in one sentence that the work is in the background, then end the turn. Do not sleep, poll, or keep calling tools while waiting.',
28
+ "When the user asks how an unfinished ticket is progressing, call foundations_worker_history once and answer from that excerpt. Do not call it in a loop and do not sleep. The excerpt is not a result: do not call foundations_publish from it, and do not read, edit, or build the worker's files or finish the task. If the excerpt is empty, say there is no execution record yet.",
24
29
  "A ticket notice is not something the user said. On progress or artifact notices, do not take over the work and do not poll. On a question, answer or call foundations_supply. On a budget-extension notice, call foundations_grant with enough to exceed current usage, then end the turn. You cannot refuse a worker budget. Do not take over the worker's task: do not inspect, edit, or build its files, and do not run its commands. On a successful result, call foundations_publish, then write the user-visible reply. On a failed result, tell the user the reason and stop. Do not take over the task. Do not treat a later failed status after a published result as if the worker never delivered. Do not invent a final answer or accept the work on the user's behalf before a result. Do not call foundations_retry unless the user explicitly asks.",
25
30
  'If dispatch returns BUDGET, do not start the job yourself and do not keep opening tickets to bypass the cap. Tell the user the host is at its limit.',
26
31
  `On a budget-wait notice, call foundations_grant and add at least one standard slice (${DEFAULT_WORK_BUDGET.workerMaxTokens} tokens and ${DEFAULT_WORK_BUDGET.workerWallMs} ms), or more when current usage is already past granted plus that slice. Grant every time the notice arrives. There is no limit on how many grants and no cumulative ceiling. Do not refuse because earlier grants were many or large. A grant that does not exceed current usage leaves the worker paused, so do not add a token or two. A terminal failed or cancelled ticket cannot be revived by a grant. Do not foundations_dispatch a replacement ticket for the same work. Do not cancel unless the user asks to stop.`,
@@ -274,6 +279,7 @@ export function renderTickets(rows) {
274
279
  return [
275
280
  '[foundations:tickets]',
276
281
  'These are ticket summaries, not the execution transcript, and not a reply the user has already been given.',
282
+ 'Ticket summaries are not the execution record. To see how far a worker has gotten, call foundations_worker_history.',
277
283
  'accepted means received. enqueued means placed on the execution queue. started is the only status that means work has begun.',
278
284
  'A ticket notice is not something the user said. accepted is not enqueued, and enqueued is not started.',
279
285
  'publish only records an intent to deliver. The words you write next are the reply to the user. Tell the user the result. Do not say accepted, enqueued, or publish.',
package/dist/desk.js CHANGED
@@ -33,11 +33,16 @@ const SECRET_KEY = /token|secret|password|authorization|api[-_]?key|cookie/i;
33
33
  * @param {object} options
34
34
  * @param {string} options.ledgerFile
35
35
  * @param {string} options.profileDir
36
+ * @param {string} [options.sessionsRoot] JSONL persistence root. Defaults to <profileDir>/sessions.
37
+ * @param {string} [options.stateRoot] Directory that holds storages/. Defaults to profileDir.
36
38
  * @param {string} options.sessionCwd
37
39
  * @param {(sessionId: string) => boolean} options.isBot
38
40
  * @param {(sessionId: string) => { kind?: string } | null | undefined} options.mark
39
41
  * @param {(sessionId: string) => void | Promise<void>} options.hold
40
42
  * @param {(sessionId: string) => void | Promise<void>} options.release
43
+ * @param {(sessionId: string) => void | Promise<void>} [options.releaseLoaded]
44
+ * @param {(sessionId: string) => void | Promise<void>} [options.releaseAttached]
45
+ * @param {(sessionId: string) => boolean} [options.stillAttached]
41
46
  * @param {(endpoint: string, args: Record<string, unknown>, req: DeskRequest) => Promise<{ status: number, body: RpcEnvelope }>} options.rpc
42
47
  * @param {(req: DeskRequest) => Promise<Record<string, unknown>>} options.usage
43
48
  */
@@ -46,7 +51,10 @@ export function createDesk(options) {
46
51
  const sessionPreviews = openSessionPreviews(join(dirname(options.ledgerFile), 'session-previews.json'));
47
52
  /** @type {Map<string, Promise<void>>} */
48
53
  const promptLocks = new Map();
49
- const sessionsRoot = join(options.profileDir, 'sessions');
54
+ const sessionsRoot = options.sessionsRoot !== undefined && options.sessionsRoot !== ''
55
+ ? options.sessionsRoot
56
+ : join(options.profileDir, 'sessions');
57
+ const stateRoot = options.stateRoot !== undefined && options.stateRoot !== '' ? options.stateRoot : options.profileDir;
50
58
  return {
51
59
  /**
52
60
  * @param {string} method
@@ -61,7 +69,7 @@ export function createDesk(options) {
61
69
  return true;
62
70
  if (method === 'POST' && (sub === '/sessions' || sub === '/sessions/previews' || sub === '/tasks'))
63
71
  return true;
64
- if (method === 'POST' && /^\/sessions\/session-[A-Za-z0-9-]+\/(?:archive|purge)$/.test(sub))
72
+ if (method === 'POST' && /^\/sessions\/session-[A-Za-z0-9-]+\/(?:archive|purge|delete)$/.test(sub))
65
73
  return true;
66
74
  if (method === 'POST' && /^\/tasks\/[0-9a-f-]{36}\/cancel$/.test(sub))
67
75
  return true;
@@ -92,6 +100,9 @@ export function createDesk(options) {
92
100
  const purge = sub.match(/^\/sessions\/(session-[A-Za-z0-9-]+)\/purge$/);
93
101
  if (method === 'POST' && purge)
94
102
  return purgeBlank(req, purge[1]);
103
+ const remove = sub.match(/^\/sessions\/(session-[A-Za-z0-9-]+)\/delete$/);
104
+ if (method === 'POST' && remove)
105
+ return deleteSession(req, remove[1]);
95
106
  if (method === 'GET' && sub === '/tasks')
96
107
  return { status: 200, body: { items: ledger.tasks() } };
97
108
  if (method === 'POST' && sub === '/tasks')
@@ -214,24 +225,84 @@ export function createDesk(options) {
214
225
  * @param {string} sessionId
215
226
  */
216
227
  async function purgeBlank(req, sessionId) {
228
+ const found = await findListedSession(req, sessionId);
229
+ if (found.error)
230
+ return found.error;
231
+ const item = found.item;
232
+ if (item.blank !== true || item.running === true || typeof item.cwd !== 'string' || item.cwd === '') {
233
+ return { status: 409, body: { error: 'not_blank' } };
234
+ }
235
+ const erased = await eraseSession(sessionId, item.cwd);
236
+ if (erased)
237
+ return erased;
238
+ return { status: 200, body: { sessionId, purged: true } };
239
+ }
240
+ /**
241
+ * Hard-delete any listed session, including one that already has messages.
242
+ * An idle session still open in this process is detached first, then its log
243
+ * is removed. A running turn is refused so its writer cannot recreate the log.
244
+ * @param {DeskRequest} req
245
+ * @param {string} sessionId
246
+ */
247
+ async function deleteSession(req, sessionId) {
248
+ const found = await findListedSession(req, sessionId);
249
+ if (found.error)
250
+ return found.error;
251
+ const item = found.item;
252
+ if (item.running === true)
253
+ return { status: 409, body: { error: 'running' } };
254
+ if (typeof item.cwd !== 'string' || item.cwd === '')
255
+ return { status: 409, body: { error: 'no_cwd' } };
256
+ try {
257
+ await options.releaseLoaded?.(sessionId);
258
+ if (options.stillAttached?.(sessionId) === true)
259
+ await options.releaseAttached?.(sessionId);
260
+ }
261
+ catch (error) {
262
+ return {
263
+ status: 500,
264
+ body: { error: 'delete_failed', message: error instanceof Error ? error.message : 'delete failed' },
265
+ };
266
+ }
267
+ if (options.stillAttached?.(sessionId) === true)
268
+ return { status: 409, body: { error: 'attached' } };
269
+ const erased = await eraseSession(sessionId, item.cwd);
270
+ if (erased)
271
+ return erased;
272
+ return { status: 200, body: { sessionId, deleted: true } };
273
+ }
274
+ /**
275
+ * @param {DeskRequest} req
276
+ * @param {string} sessionId
277
+ */
278
+ async function findListedSession(req, sessionId) {
217
279
  const listed = await options.rpc('session/list', { _request: {} }, req);
218
280
  const items = listed.body?.result?.value?.items;
219
281
  if (listed.body?.result?.ok !== true || !Array.isArray(items)) {
220
- return { status: 502, body: { error: 'session_list_failed', upstream: listed.body?.result?.error ?? null } };
282
+ return {
283
+ error: {
284
+ status: 502,
285
+ body: { error: 'session_list_failed', upstream: listed.body?.result?.error ?? null },
286
+ },
287
+ };
221
288
  }
222
289
  const item = items.find(entry => entry?.sessionId === sessionId);
223
290
  if (!item)
224
- return { status: 404, body: { error: 'session_not_found' } };
225
- if (item.blank !== true || item.running === true || typeof item.cwd !== 'string' || item.cwd === '') {
226
- return { status: 409, body: { error: 'not_blank' } };
227
- }
291
+ return { error: { status: 404, body: { error: 'session_not_found' } } };
292
+ return { item, error: undefined };
293
+ }
294
+ /**
295
+ * @param {string} sessionId
296
+ * @param {string} cwd
297
+ */
298
+ async function eraseSession(sessionId, cwd) {
228
299
  try {
229
300
  purgeSessionFiles({
230
301
  sessionsRoot,
231
- cacheFile: join(options.profileDir, 'storages', 'session_projcache', 'sessions', `${sessionId}.json`),
232
- workspaceFile: join(options.profileDir, 'storages', 'workspace.json'),
302
+ cacheFile: join(stateRoot, 'storages', 'session_projcache', 'sessions', `${sessionId}.json`),
303
+ workspaceFile: join(stateRoot, 'storages', 'workspace.json'),
233
304
  sessionId,
234
- cwd: item.cwd,
305
+ cwd,
235
306
  });
236
307
  }
237
308
  catch (error) {
@@ -241,7 +312,7 @@ export function createDesk(options) {
241
312
  };
242
313
  }
243
314
  sessionPreviews.forget(sessionId);
244
- return { status: 200, body: { sessionId, purged: true } };
315
+ return null;
245
316
  }
246
317
  /**
247
318
  * @param {unknown} body
@@ -8,7 +8,7 @@ import { approvalAnswererFor } from "./approvals.js";
8
8
  import { authorizationFor } from "./authorization.js";
9
9
  import { runtimeFor, workRuntimeFor } from "./runtime-registry.js";
10
10
  export const name = 'session-foundations-http';
11
- export const inject = ['webServer', 'agents', 'sessionPersistence', 'sessionQuery'];
11
+ export const inject = ['webServer', 'agents', 'sessionPersistence', 'sessionQuery', 'sessions'];
12
12
  /**
13
13
  * Local management routes for the same SQLite the main plugin uses.
14
14
  * Loaded only on profiles that have a web server, so headless does not need it.
package/dist/http.js CHANGED
@@ -8,6 +8,7 @@ import { permissionView, setPermission } from "./permissions.js";
8
8
  import { cuaAction, cuaSnapshot } from "./cua-access.js";
9
9
  import { provisionSession } from "./provision.js";
10
10
  import { handleWorkApi, openPageLive, openWorkLive } from "./work-http.js";
11
+ import { releaseLoadedAgent } from "./inbox.js";
11
12
  import { createLogSource } from "./log/source.js";
12
13
  import { createLogSnapshotService } from "./log/snapshot-service.js";
13
14
  import { dispatchLogRequest, probeConnection, registerLogRoutes } from "./log/routes.js";
@@ -26,11 +27,14 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
26
27
  const profileDir = ctx.profileContext?.dir || (storeDir !== '' ? dirname(storeDir) : '');
27
28
  const logService = createLogSnapshotService(createLogSource(ctx));
28
29
  const logOnConnection = registerLogRoutes(ctx, logService);
30
+ const persistence = ctx.sessionPersistence;
31
+ const sessionsRoot = typeof persistence?.root === 'string' ? persistence.root : '';
29
32
  const desk = profileDir === ''
30
33
  ? null
31
34
  : createDesk({
32
35
  ledgerFile: join(storeDir, 'desk-ledger.json'),
33
36
  profileDir,
37
+ ...(sessionsRoot !== '' ? { sessionsRoot, stateRoot: dirname(sessionsRoot) } : {}),
34
38
  sessionCwd: defaultSessionCwd(process.env),
35
39
  isBot: sessionId => engine.isBot(sessionId),
36
40
  mark: sessionId => engine.markBot(sessionId),
@@ -40,6 +44,9 @@ export function registerHttp(ctx, engine, getRuntime = () => null, getWork = ()
40
44
  release: sessionId => {
41
45
  getWork()?.releaseHold(sessionId);
42
46
  },
47
+ releaseLoaded: sessionId => releaseLoadedAgent(sessionId),
48
+ releaseAttached: sessionId => unloadAttachedSession(ctx, sessionId),
49
+ stillAttached: sessionId => attachedSession(ctx, sessionId),
43
50
  rpc: (endpoint, args, req) => hostRpc(req, endpoint, args),
44
51
  usage: req => hostUsage(req),
45
52
  });
@@ -500,6 +507,84 @@ export function memoryView(engine, sessionId) {
500
507
  state: engine.statePayload(sessionId),
501
508
  };
502
509
  }
510
+ /**
511
+ * A live store entry means some fiber still has the session open.
512
+ * The caller must inject `sessions`. Reading it without inject throws.
513
+ * @param {import('./host.ts').HostContext} ctx
514
+ * @param {string} sessionId
515
+ */
516
+ export function attachedSession(ctx, sessionId) {
517
+ const sessions = ctx.sessions;
518
+ return typeof sessions?.get === 'function' && sessions.get(sessionId) != null;
519
+ }
520
+ /**
521
+ * Drop an idle session another fiber still has open, then let the caller delete its log.
522
+ * The host has no delete RPC. The store entry's detach is the same disposer `enter` keeps,
523
+ * and it emits `session/disposed`, which closes the JSONL writer.
524
+ * @param {import('./host.ts').HostContext} ctx
525
+ * @param {string} sessionId
526
+ */
527
+ export async function unloadAttachedSession(ctx, sessionId) {
528
+ const agent = liveAgentOf(ctx, sessionId);
529
+ if (agent && typeof agent.cancel === 'function') {
530
+ try {
531
+ agent.cancel({ kind: 'hook', reason: 'session-delete' }, { keepInbox: false });
532
+ }
533
+ catch {
534
+ /* already idle */
535
+ }
536
+ }
537
+ if (agent && typeof agent.whenIdle === 'function')
538
+ await agent.whenIdle();
539
+ const writer = sessionWriter(ctx, sessionId);
540
+ if (writer && typeof writer.close === 'function')
541
+ await writer.close();
542
+ detachAgentEntry(ctx, sessionId);
543
+ detachSessionEntry(ctx, sessionId);
544
+ }
545
+ /**
546
+ * @param {import('./host.ts').HostContext} ctx
547
+ * @param {string} sessionId
548
+ */
549
+ function liveAgentOf(ctx, sessionId) {
550
+ try {
551
+ return ctx.agents?.get?.(sessionId) ?? null;
552
+ }
553
+ catch {
554
+ return null;
555
+ }
556
+ }
557
+ /**
558
+ * @param {import('./host.ts').HostContext} ctx
559
+ * @param {string} sessionId
560
+ */
561
+ function sessionWriter(ctx, sessionId) {
562
+ const writers = ctx.sessionPersistence?.tracker?.writers;
563
+ if (!writers || typeof writers.get !== 'function')
564
+ return null;
565
+ const writer = writers.get(sessionId);
566
+ return writer && typeof writer === 'object' ? writer : null;
567
+ }
568
+ /**
569
+ * @param {import('./host.ts').HostContext} ctx
570
+ * @param {string} sessionId
571
+ */
572
+ function detachAgentEntry(ctx, sessionId) {
573
+ const agents = ctx.agents;
574
+ const entry = agents?.store?.get?.(sessionId);
575
+ if (!entry || typeof agents.detachEntered !== 'function')
576
+ return;
577
+ agents.detachEntered(entry);
578
+ }
579
+ /**
580
+ * @param {import('./host.ts').HostContext} ctx
581
+ * @param {string} sessionId
582
+ */
583
+ function detachSessionEntry(ctx, sessionId) {
584
+ const entry = ctx.sessions?.store?.get?.(sessionId);
585
+ if (entry && typeof entry.detach === 'function')
586
+ entry.detach();
587
+ }
503
588
  /**
504
589
  * @param {import('@deepseek-ai/cordis').Context} ctx
505
590
  * @param {import('node:http').IncomingMessage} req
package/dist/inbox.js CHANGED
@@ -25,6 +25,28 @@ export function liveAgent(ctx, sessionId) {
25
25
  }
26
26
  return handles.get(sessionId)?.agent ?? null;
27
27
  }
28
+ /**
29
+ * Close a session this module resumed, so its writer drains before a hard delete.
30
+ * A session owned by another fiber is left alone.
31
+ * @param {string} sessionId
32
+ */
33
+ export async function releaseLoadedAgent(sessionId) {
34
+ const pending = loading.get(sessionId);
35
+ if (pending) {
36
+ try {
37
+ await pending;
38
+ }
39
+ catch {
40
+ return;
41
+ }
42
+ }
43
+ const owned = handles.get(sessionId);
44
+ if (!owned || typeof owned.dispose !== 'function')
45
+ return;
46
+ await owned.dispose();
47
+ if (handles.get(sessionId) === owned)
48
+ handles.delete(sessionId);
49
+ }
28
50
  /**
29
51
  * @param {import('@deepseek-ai/cordis').Context} ctx
30
52
  * @param {string} sessionId
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ import { createQuestionAnswerer, publishQuestionAnswerer, questionAnswererFor }
12
12
  import { createApprovalAnswerer, publishApprovalAnswerer, approvalAnswererFor } from "./approvals.js";
13
13
  import { createAuthorizationController, publishAuthorization, authorizationFor } from "./authorization.js";
14
14
  import { publishRuntime, publishWorkRuntime, runtimeFor } from "./runtime-registry.js";
15
- import { childCreateOptions, effectiveWorkLimits, resolveWorkBudget, WORK_BUDGET_ENV, } from "./work-admit.js";
15
+ import { childCreateOptions, effectiveWorkLimits, pinMainReasoning, resolveWorkBudget, workerModelSelection, WORK_BUDGET_ENV, } from "./work-admit.js";
16
16
  import { ensureWorkerFilePreset, WORKER_FILE_PRESET, workerFileSetup } from "./work-child.js";
17
17
  import { BUDGET_NOTICE_PREFIX, createWorkRuntime } from "./work-worker.js";
18
18
  import { workToolDefinitions } from "./work-tools.js";
@@ -187,6 +187,7 @@ export function apply(ctx, config = {}) {
187
187
  });
188
188
  ctx.on('agent/created', (payload) => {
189
189
  const agent = payload?.agent;
190
+ pinMainReasoning(agent, id => engine.isBot(id));
190
191
  if (!agent?.id || !engine.isBot(agent.id))
191
192
  return;
192
193
  let session = null;
@@ -201,6 +202,9 @@ export function apply(ctx, config = {}) {
201
202
  seeded: session?.header?.isSeeded === true,
202
203
  });
203
204
  });
205
+ ctx.on('agent/inbox/inserted', (payload) => {
206
+ pinMainReasoning(payload?.agent, id => engine.isBot(id));
207
+ });
204
208
  triggers = ctx.agents ? startTriggers(ctx, store, engine) : null;
205
209
  work = ctx.agents ? startWork(ctx, store, engine, config) : null;
206
210
  if (triggers) {
@@ -345,7 +349,7 @@ function startWork(ctx, store, engine, config) {
345
349
  try {
346
350
  const owner = ctx.agents?.get(spec.ownerSessionId);
347
351
  cwd = owner?.session?.header?.cwd ?? ctx.sessions?.get(spec.ownerSessionId)?.header?.cwd ?? '';
348
- model = owner?.model?.current?.() ?? null;
352
+ model = workerModelSelection(owner?.model?.current?.() ?? null);
349
353
  }
350
354
  catch {
351
355
  cwd = '';
@@ -353,7 +357,7 @@ function startWork(ctx, store, engine, config) {
353
357
  }
354
358
  if (!model?.provider || !model?.model) {
355
359
  try {
356
- model = ctx.agentDefaultModel?.currentSelection?.() ?? null;
360
+ model = workerModelSelection(ctx.agentDefaultModel?.currentSelection?.() ?? null);
357
361
  }
358
362
  catch {
359
363
  model = null;
@@ -1,4 +1,4 @@
1
- /** Remove one blank session's on-disk log. DSH has no delete RPC; session/list rescans these directories. */
1
+ /** Remove one session's on-disk log. DSH has no delete RPC; session/list rescans these directories. */
2
2
  import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { join, resolve, sep } from 'node:path';
4
4
  const SESSION_ID = /^session-[A-Za-z0-9-]+$/;
@@ -261,6 +261,39 @@ export function estimateWorkerBudget(_briefing, suggestion, defaults = DEFAULT_W
261
261
  globalQueue: defaults.globalQueue,
262
262
  };
263
263
  }
264
+ /** Main-session reasoning effort. `off` skips thinking so the reply starts sooner. */
265
+ export const MAIN_REASONING_EFFORT = 'off';
266
+ /**
267
+ * Record `off` on a bot main session before the next step is prepared.
268
+ * A matching selection is left alone. Ordinary sessions are left alone.
269
+ * Call this outside an open session append: `model.select` appends `model/selection`.
270
+ * @param {{ id?: string, model?: { current?: () => ModelSelection, select?: (selection: { provider: string, model: string, reasoningEffort: string }) => void } } | null | undefined} agent
271
+ * @param {(sessionId: string) => boolean} isBot
272
+ */
273
+ export function pinMainReasoning(agent, isBot) {
274
+ if (!agent || typeof agent.id !== 'string' || agent.id === '' || !isBot(agent.id))
275
+ return false;
276
+ const current = agent.model?.current?.();
277
+ if (!current?.provider || !current.model || current.reasoningEffort === MAIN_REASONING_EFFORT)
278
+ return false;
279
+ agent.model?.select?.({
280
+ provider: current.provider,
281
+ model: current.model,
282
+ reasoningEffort: MAIN_REASONING_EFFORT,
283
+ });
284
+ return true;
285
+ }
286
+ /**
287
+ * Worker route copied from the main session. Thinking stays at the adapter
288
+ * default: the main session's `off` is for reply latency and is not copied.
289
+ * @param {ModelSelection} model
290
+ */
291
+ export function workerModelSelection(model) {
292
+ if (!model || model.reasoningEffort !== MAIN_REASONING_EFFORT)
293
+ return model;
294
+ const { reasoningEffort: _effort, ...rest } = model;
295
+ return rest;
296
+ }
264
297
  /**
265
298
  * Child creation options. parentAgent and meta.parentSession are omitted on purpose:
266
299
  * the parent link lives only on the ticket row.