durable-chat 0.0.0-stage → 1.0.0

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/tasks.js ADDED
@@ -0,0 +1,466 @@
1
+ import { configure, defineDoc, defineTask } from "@earendil-works/pi-durable";
2
+ import { withAbortSignal } from "@earendil-works/chord/context";
3
+ import { ensureWorkspace, JobWorkspaceDoc } from "./workspaces.js";
4
+ export const JOB_KIND = "durable-chat.job";
5
+ export const MAX_BRIEF_CHARS = 4000;
6
+ export const HANDOFF_MAX_DEPTH = 8;
7
+ export const JOB_INSTRUCTIONS = [
8
+ "You are a background job agent working for a coordinator.",
9
+ "Complete the brief in the assigned working directory with read, write, edit, and bash.",
10
+ "With `codemode`, a script calls this job's tools as `tools.<name>(args)` and only the script's output comes back; use it for parallel reads and for filtering large output before it reaches you.",
11
+ "A context fork inherits earlier investigation as background; the newest brief defines your assignment. Main alone creates forks.",
12
+ "Keep changes in your assigned workspace. Report its branch and useful commits/diff with your result; main decides integration.",
13
+ "When Substrate MCP is available, you also have substrate_search, substrate_describe, and substrate_call:",
14
+ "search for the noun or verb, describe the exact tool, then call it with a JSON args object. Never print secrets.",
15
+ "Use the handoff tool only when the remaining work belongs to another job or should return to the coordinator:",
16
+ "give a self-contained brief and a short summary of verified progress. A handoff ends this job.",
17
+ "Inspect real files and live state instead of guessing. Make the smallest change that satisfies the brief.",
18
+ "Finish with a concise result: what you changed, what you verified, and anything still open. Never claim a check you did not run.",
19
+ ].join("\n");
20
+ const ANSWER_TAIL_CHARS = 6000;
21
+ /** Legacy session index, read only so jobs created before JobLink can still resume. */
22
+ export const JobsIndex = defineDoc({
23
+ kind: "durable-chat.jobs",
24
+ version: 1,
25
+ scope: "session",
26
+ initial: () => ({ byTask: {} }),
27
+ checkpointWhen: () => false,
28
+ });
29
+ /** Task-scoped native link to the conversation this job owns, plus the config a successor inherits. */
30
+ export const JobLink = defineDoc({
31
+ kind: "durable-chat.job-link",
32
+ version: 1,
33
+ scope: "task",
34
+ initial: () => ({ conversationId: 0 }),
35
+ checkpointWhen: () => false,
36
+ });
37
+ /** A job's recorded intent to hand its work to a new job or back to main. */
38
+ export const JobHandoffDoc = defineDoc({
39
+ kind: "app.job-handoff",
40
+ version: 1,
41
+ scope: "conversation",
42
+ history: "latest",
43
+ fork: "initial",
44
+ initial: () => ({ target: "main", brief: "", summary: "", at: 0 }),
45
+ checkpointWhen: () => false,
46
+ });
47
+ export const JOB_NOTICE_KIND = "app.job-notice";
48
+ /** Native write entry that makes a job visible to the main model. */
49
+ export function jobNoticeEntry(text, data) {
50
+ return {
51
+ kind: JOB_NOTICE_KIND,
52
+ data,
53
+ model: [{ role: "user", content: `[host] ${text}`, timestamp: Date.now() }],
54
+ };
55
+ }
56
+ function textOf(message) {
57
+ return (message?.content ?? []).flatMap((part) => part.type === "text" ? [part.text] : []).join("");
58
+ }
59
+ function tailText(text) {
60
+ return text.length <= ANSWER_TAIL_CHARS ? text : `[...answer truncated...]\n${text.slice(-ANSWER_TAIL_CHARS)}`;
61
+ }
62
+ async function linkOf(read, taskId, context) {
63
+ const link = await read.snapshot(JobLink, taskId, context);
64
+ if (link !== undefined && link.conversationId > 0)
65
+ return link;
66
+ // Jobs created before JobLink used the session index.
67
+ const index = await read.snapshot(JobsIndex, context);
68
+ const entry = index?.byTask[String(taskId)];
69
+ return entry === undefined ? undefined : { conversationId: Number(entry.conversationId) };
70
+ }
71
+ async function conversationOf(read, taskId, context) {
72
+ return (await linkOf(read, taskId, context))?.conversationId;
73
+ }
74
+ async function handoffOf(read, conversationId, context) {
75
+ const handoff = await read.snapshot(JobHandoffDoc, conversationId, context);
76
+ return handoff === undefined || handoff.brief.length === 0
77
+ ? undefined
78
+ : { target: handoff.target, brief: handoff.brief, summary: handoff.summary };
79
+ }
80
+ function successorBrief(taskId, brief, summary) {
81
+ const text = `Handoff from job #${taskId}.\n\nVerified progress:\n${summary}\n\nNext brief:\n${brief}`;
82
+ return text.length <= MAX_BRIEF_CHARS ? text : `${text.slice(0, MAX_BRIEF_CHARS - 1)}…`;
83
+ }
84
+ export const JobTask = defineTask({
85
+ name: JOB_KIND,
86
+ version: 1,
87
+ initial: () => ({ phase: "run" }),
88
+ phases: {
89
+ run: async (task, runtime, context) => {
90
+ const conversationId = await conversationOf(runtime, Number(task.id), context);
91
+ if (conversationId === undefined) {
92
+ await runtime.commit(() => ({
93
+ status: "terminal",
94
+ outcome: {
95
+ status: "failed",
96
+ error: { message: "The job has no recorded conversation." },
97
+ result: { conversationId: 0, brief: task.input.brief, status: "unanswered" },
98
+ },
99
+ }), context);
100
+ return;
101
+ }
102
+ const handle = await runtime.conversation(conversationId, context);
103
+ if (handle === undefined) {
104
+ await runtime.commit(() => ({
105
+ status: "terminal",
106
+ outcome: {
107
+ status: "failed",
108
+ error: { message: "The job conversation is not available." },
109
+ result: { conversationId, brief: task.input.brief, status: "unanswered" },
110
+ },
111
+ }), context);
112
+ return;
113
+ }
114
+ if (task.input.workspace !== undefined) {
115
+ try {
116
+ await ensureWorkspace(task.input.workspace, runtime.signal);
117
+ }
118
+ catch (error) {
119
+ if (runtime.signal.aborted)
120
+ return;
121
+ await runtime.commit(() => ({
122
+ status: "running",
123
+ checkpoint: { phase: "report", status: "unanswered", reason: `Workspace setup failed: ${error instanceof Error ? error.message : String(error)}` },
124
+ }), context);
125
+ return;
126
+ }
127
+ }
128
+ const steering = (await runtime.snapshot(JobLink, task.id, context))?.steering;
129
+ let settled;
130
+ try {
131
+ const submission = await handle.submit({
132
+ type: "input",
133
+ content: steering?.message ?? task.input.brief,
134
+ // Reacquire the latest admitted input rather than duplicating it after a restart.
135
+ requestId: steering?.requestId ?? `job:${task.id}:run`,
136
+ ...(steering === undefined ? {} : { whenBusy: "steer", whenIdle: "reject" }),
137
+ }, context);
138
+ settled = await submission.wait(context);
139
+ }
140
+ catch (error) {
141
+ if (runtime.signal.aborted)
142
+ return; // The abort handler commits the terminal state.
143
+ throw error;
144
+ }
145
+ if (runtime.signal.aborted)
146
+ return;
147
+ const handoff = await handoffOf(runtime, conversationId, context);
148
+ let checkpoint;
149
+ if (handoff !== undefined) {
150
+ checkpoint = handoff.target === "main"
151
+ ? { phase: "handoffMain", brief: handoff.brief, summary: handoff.summary }
152
+ : { phase: "handoffJob", brief: handoff.brief, summary: handoff.summary };
153
+ }
154
+ else if (settled.status === "done" && settled.type === "input") {
155
+ // The answer is in the child conversation, not in the task's own (main) conversation.
156
+ const view = await runtime.context(conversationId, context);
157
+ const entry = view.entries.find((item) => Number(item.id) === Number(settled.answer));
158
+ const assistant = (entry?.model ?? []).filter((message) => message.role === "assistant");
159
+ checkpoint = {
160
+ phase: "report",
161
+ status: "answered",
162
+ answerEntry: Number(settled.answer),
163
+ answer: tailText(textOf(assistant.at(-1))),
164
+ };
165
+ }
166
+ else {
167
+ const reason = settled.status === "unanswered" ? String(settled.reason) : "not_answered";
168
+ checkpoint = { phase: "report", status: "unanswered", reason };
169
+ }
170
+ if (runtime.signal.aborted)
171
+ return;
172
+ await runtime.commit(async (tx) => {
173
+ const latest = await tx.doc(JobLink, task.id);
174
+ // A steer can arrive during the final model request and start a subsequent native run.
175
+ // Keep this job live until the latest steering submission has also settled.
176
+ return {
177
+ status: "running",
178
+ checkpoint: latest.steering?.requestId === steering?.requestId ? checkpoint : {
179
+ phase: "run",
180
+ ...(latest.steering === undefined ? {} : { steeringRequestId: latest.steering.requestId }),
181
+ },
182
+ };
183
+ }, context);
184
+ },
185
+ handoffMain: async (task, runtime, context) => {
186
+ const { brief, summary } = task.state.checkpoint;
187
+ const conversationId = await conversationOf(runtime, Number(task.id), context) ?? 0;
188
+ const main = await runtime.conversation(runtime.conversationId, context);
189
+ if (main === undefined) {
190
+ await runtime.commit(() => ({
191
+ status: "terminal",
192
+ outcome: {
193
+ status: "failed",
194
+ error: { message: "The main conversation is not available for the handoff." },
195
+ result: { conversationId, brief: task.input.brief, status: "unanswered" },
196
+ },
197
+ }), context);
198
+ return;
199
+ }
200
+ const content = `[job #${task.id} handoff] ${summary}\n\nContinue with: ${brief}`;
201
+ let delivered = false;
202
+ await runtime.commit(async (tx) => {
203
+ try {
204
+ await main.submit(tx, {
205
+ type: "input",
206
+ content,
207
+ whenBusy: "followUp",
208
+ requestId: `job-handoff:${task.id}`,
209
+ entry: { kind: "app.job-handoff", data: { fromJob: Number(task.id), brief, summary } },
210
+ });
211
+ delivered = true;
212
+ }
213
+ catch (error) {
214
+ runtime.report(error);
215
+ }
216
+ if (!delivered) {
217
+ return {
218
+ status: "terminal",
219
+ outcome: {
220
+ status: "failed",
221
+ error: { message: "The handoff to main could not be admitted." },
222
+ result: { conversationId, brief: task.input.brief, status: "unanswered" },
223
+ },
224
+ };
225
+ }
226
+ return {
227
+ status: "terminal",
228
+ outcome: {
229
+ status: "completed",
230
+ result: {
231
+ conversationId,
232
+ brief: task.input.brief,
233
+ status: "handed_off",
234
+ answer: summary,
235
+ handoff: { target: "main" },
236
+ },
237
+ },
238
+ };
239
+ }, context);
240
+ },
241
+ handoffJob: async (task, runtime, context) => {
242
+ const { brief, summary } = task.state.checkpoint;
243
+ const link = await linkOf(runtime, Number(task.id), context);
244
+ const template = link?.template;
245
+ const depth = task.input.handoffDepth ?? 0;
246
+ const fail = (message) => runtime.commit(() => ({
247
+ status: "running",
248
+ checkpoint: { phase: "report", status: "unanswered", reason: message },
249
+ }), context);
250
+ if (template === undefined) {
251
+ await fail("This job has no agent template for a successor; it cannot hand off to another job.");
252
+ return;
253
+ }
254
+ if (depth >= HANDOFF_MAX_DEPTH) {
255
+ await fail(`Handoff chain limit (${HANDOFF_MAX_DEPTH}) reached.`);
256
+ return;
257
+ }
258
+ const extensions = runtime.registry.installed().filter((extension) => template.extensionNames.includes(extension.name));
259
+ if (extensions.length === 0) {
260
+ await fail("No registered extension matches this job's agent template.");
261
+ return;
262
+ }
263
+ let successorId = 0;
264
+ let successorConversationId = 0;
265
+ const notify = task.input.notifyMain === true;
266
+ await runtime.commit(async (tx) => {
267
+ const newTaskId = await tx.createTask(JobTask, {
268
+ brief: successorBrief(Number(task.id), brief, summary),
269
+ ...(notify ? { notifyMain: true } : {}),
270
+ autoContinue: task.input.autoContinue === true,
271
+ handoffDepth: depth + 1,
272
+ handoffFrom: Number(task.id),
273
+ ...(template.workspace === undefined ? {} : { workspace: template.workspace }),
274
+ }, { ownership: { kind: "conversation" }, background: true, conversationId: runtime.conversationId });
275
+ const conversation = await tx.createConversation({ ownership: { kind: "task", taskId: newTaskId } });
276
+ await configure(tx, conversation.id, {
277
+ model: template.model,
278
+ thinkingLevel: template.thinkingLevel,
279
+ cwd: template.cwd,
280
+ maxTurns: template.maxTurns,
281
+ instructions: JOB_INSTRUCTIONS,
282
+ extensions,
283
+ tools: null,
284
+ modelTools: null,
285
+ });
286
+ const successor = await tx.doc(JobLink, newTaskId);
287
+ successor.conversationId = Number(conversation.id);
288
+ successor.template = template;
289
+ if (template.workspace !== undefined)
290
+ (await tx.doc(JobWorkspaceDoc, conversation.id)).workspace = template.workspace;
291
+ successorId = Number(newTaskId);
292
+ successorConversationId = Number(conversation.id);
293
+ return {
294
+ status: "running",
295
+ checkpoint: {
296
+ phase: "handoffJobNotify",
297
+ successorId,
298
+ successorConversationId,
299
+ brief,
300
+ summary,
301
+ notify,
302
+ },
303
+ };
304
+ }, context);
305
+ },
306
+ handoffJobNotify: async (task, runtime, context) => {
307
+ const { successorId, successorConversationId, brief, summary, notify } = task.state.checkpoint;
308
+ const conversationId = await conversationOf(runtime, Number(task.id), context) ?? 0;
309
+ const main = notify ? await runtime.conversation(runtime.conversationId, context) : undefined;
310
+ const entry = jobNoticeEntry(`Job #${task.id} handed off to job #${successorId}: "${brief}". The successor continues in its own conversation.`, {
311
+ taskId: Number(task.id),
312
+ conversationId: successorConversationId,
313
+ brief,
314
+ phase: "handed_off",
315
+ summary,
316
+ });
317
+ await runtime.commit(async (tx) => {
318
+ if (main !== undefined) {
319
+ try {
320
+ await main.submit(tx, { type: "write", entry });
321
+ }
322
+ catch (error) {
323
+ runtime.report(error);
324
+ }
325
+ }
326
+ return {
327
+ status: "terminal",
328
+ outcome: {
329
+ status: "completed",
330
+ result: {
331
+ conversationId,
332
+ brief: task.input.brief,
333
+ status: "handed_off",
334
+ answer: summary,
335
+ handoff: { target: "job", id: successorId },
336
+ },
337
+ },
338
+ };
339
+ }, context);
340
+ },
341
+ report: async (task, runtime, context) => {
342
+ const checkpoint = task.state.checkpoint;
343
+ const conversationId = await conversationOf(runtime, Number(task.id), context) ?? 0;
344
+ const base = { conversationId, brief: task.input.brief };
345
+ const main = task.input.notifyMain === true
346
+ ? await runtime.conversation(runtime.conversationId, context)
347
+ : undefined;
348
+ const answered = checkpoint.status === "answered";
349
+ const summary = checkpoint.answer === undefined ? undefined : checkpoint.answer.slice(0, 800);
350
+ const continueMain = task.input.autoContinue === true;
351
+ const continuation = continueMain
352
+ ? " Continue the work: review the result, decide the next step, and tell the user what changed."
353
+ : "";
354
+ const origin = task.input.fork;
355
+ const provenance = origin === undefined ? "" : ` Forked from ${origin.jobId === undefined ? "main" : `job #${origin.jobId}`} at entry #${origin.entryId}.`;
356
+ const workspace = task.input.workspace;
357
+ const placement = workspace === undefined ? "" : ` Workspace: ${workspace.cwd}${workspace.kind === "worktree" ? `; branch ${workspace.branch}; base ${workspace.baseCommit}` : " (shared)"}.`;
358
+ const text = (answered
359
+ ? `Background job #${task.id} completed: "${task.input.brief}". ` +
360
+ `Answer: ${summary === undefined || summary.length === 0 ? "(no text)" : summary}.`
361
+ : `Background job #${task.id} failed: ${checkpoint.reason ?? "unknown"}.`) + provenance + placement + continuation;
362
+ const data = {
363
+ taskId: Number(task.id),
364
+ conversationId,
365
+ brief: task.input.brief,
366
+ phase: answered ? "completed" : "failed",
367
+ ...(summary === undefined ? {} : { summary }),
368
+ };
369
+ await runtime.commit(async (tx) => {
370
+ if (main !== undefined) {
371
+ try {
372
+ await main.submit(tx, continueMain
373
+ ? {
374
+ type: "input",
375
+ content: `[host] ${text}`,
376
+ whenBusy: "followUp",
377
+ entry: { kind: JOB_NOTICE_KIND, data },
378
+ }
379
+ : { type: "write", entry: jobNoticeEntry(text, data) });
380
+ }
381
+ catch (error) {
382
+ runtime.report(error);
383
+ }
384
+ }
385
+ if (checkpoint.status === "answered") {
386
+ return {
387
+ status: "terminal",
388
+ outcome: {
389
+ status: "completed",
390
+ result: {
391
+ ...base,
392
+ status: "answered",
393
+ ...(checkpoint.answer === undefined ? {} : { answer: checkpoint.answer }),
394
+ ...(checkpoint.answerEntry === undefined ? {} : { answerEntry: checkpoint.answerEntry }),
395
+ },
396
+ },
397
+ };
398
+ }
399
+ return {
400
+ status: "terminal",
401
+ outcome: {
402
+ status: "failed",
403
+ error: { message: `Job did not answer: ${checkpoint.reason ?? "unknown"}` },
404
+ result: {
405
+ ...base,
406
+ status: "unanswered",
407
+ ...(checkpoint.reason === undefined ? {} : { reason: checkpoint.reason }),
408
+ },
409
+ },
410
+ };
411
+ }, context);
412
+ },
413
+ },
414
+ abort: async (task, runtime, context) => {
415
+ const conversationId = await conversationOf(runtime, Number(task.id), context) ?? 0;
416
+ if (conversationId > 0) {
417
+ const handle = await runtime.conversation(conversationId, context);
418
+ if (handle !== undefined) {
419
+ // Bound cleanup: a job whose model call ignores cancellation must still settle.
420
+ try {
421
+ await handle.abort(withAbortSignal(AbortSignal.timeout(15_000), context), { background: true });
422
+ }
423
+ catch {
424
+ // The terminal receipt below remains the authority.
425
+ }
426
+ }
427
+ }
428
+ const main = task.input.notifyMain === true
429
+ ? await runtime.conversation(runtime.conversationId, context)
430
+ : undefined;
431
+ const continueMain = task.input.autoContinue === true;
432
+ const text = `Background job #${task.id} was aborted. Its transcript is retained.` +
433
+ (continueMain ? " Decide whether to retry, replan, or tell the user." : "");
434
+ const data = {
435
+ taskId: Number(task.id),
436
+ conversationId,
437
+ brief: task.input.brief,
438
+ phase: "aborted",
439
+ };
440
+ await runtime.commit(async (tx) => {
441
+ if (main !== undefined) {
442
+ try {
443
+ await main.submit(tx, continueMain
444
+ ? {
445
+ type: "input",
446
+ content: `[host] ${text}`,
447
+ whenBusy: "followUp",
448
+ entry: { kind: JOB_NOTICE_KIND, data },
449
+ }
450
+ : { type: "write", entry: jobNoticeEntry(text, data) });
451
+ }
452
+ catch (error) {
453
+ runtime.report(error);
454
+ }
455
+ }
456
+ return {
457
+ status: "terminal",
458
+ outcome: {
459
+ status: "aborted",
460
+ reason: "Aborted by the host.",
461
+ result: { conversationId, brief: task.input.brief, status: "aborted" },
462
+ },
463
+ };
464
+ }, context);
465
+ },
466
+ });
package/dist/tool.js ADDED
@@ -0,0 +1,205 @@
1
+ import { arr, obj, oneOf, opt, str } from "@earendil-works/pi-schema";
2
+ import { AgentDoc, ConversationIdle, defineExtension, defineTool, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
3
+ import { formatJobDetail, formatJobList } from "./format.js";
4
+ import { createJobInCommit, jobConversationId, jobInputDraft, normalizeBrief } from "./jobs.js";
5
+ import { JobLink, JOB_KIND } from "./tasks.js";
6
+ import { selectForkSource } from "./forks.js";
7
+ import { planWorkspace } from "./workspaces.js";
8
+ import { JobTags, normalizeTags, resolveTaggedSource, setJobTags, taggedJob } from "./tags.js";
9
+ function textReply(text, isError = false) {
10
+ return {
11
+ ...(isError ? { isError: true } : {}),
12
+ output: [{ type: "text", text }],
13
+ };
14
+ }
15
+ /**
16
+ * The coordinator's task/fork tools. Creating a job is a real external effect: each tool is
17
+ * unsafe on replay so a restart cannot admit a duplicate job.
18
+ */
19
+ export function createTaskExtension(options) {
20
+ // Presentation guards, not durable state: a model that ignores the prompt must
21
+ // not burn its run polling a live job. The first read is allowed; repeats end
22
+ // the run with a clear tool result.
23
+ const listedAt = new Map();
24
+ const shownAt = new Map();
25
+ const LIST_COOLDOWN_MS = 10_000;
26
+ const LIVE_SHOW_COOLDOWN_MS = 30_000;
27
+ const tagsSchema = arr(str({ minLength: 1, maxLength: 48 }), { maxItems: 8 });
28
+ const taskTool = defineTool({
29
+ name: "task",
30
+ description: "Start a background job. A job is a separate durable agent conversation with read/write/edit/bash " +
31
+ "and the Substrate MCP gateway; it runs while you stay responsive. Use `create` for work that takes more than " +
32
+ "a couple of steps, then report the job id. Do not poll: completion notices arrive automatically. " +
33
+ "`list` and `show` are for an explicit user request or a specific detail. Tag reusable prepared contexts at creation; " +
34
+ "`tag` replaces a job's tags (an empty array clears them), including completed jobs. Fork from tag:reviewer to reuse context. " +
35
+ "`steer` queues `message` for running job `id` and returns immediately. The worker receives it at its next boundary; " +
36
+ "stay responsive and wait for its normal completion notice.",
37
+ parameters: obj({
38
+ action: oneOf(["create", "list", "show", "tag", "steer"]),
39
+ brief: opt(str({ minLength: 1, maxLength: 4000 })),
40
+ message: opt(str({ minLength: 1, maxLength: 4000 })),
41
+ id: opt(str({ pattern: "^[0-9]+$" })),
42
+ tags: opt(tagsSchema),
43
+ }),
44
+ replay: "unsafe",
45
+ execute: async (args, api, context) => {
46
+ if (args.action === "steer") {
47
+ if (api.conversationId !== ROOT_CONVERSATION_ID)
48
+ return textReply("Only main may steer jobs.", true);
49
+ const id = Number(args.id);
50
+ if (!Number.isSafeInteger(id) || id <= 0)
51
+ return textReply("Provide a valid positive job id.", true);
52
+ try {
53
+ const draft = jobInputDraft(args.message ?? "", true);
54
+ const job = await api.getTask(id, context);
55
+ if (job === undefined || job.kind !== JOB_KIND)
56
+ return textReply(`No job #${id}.`, true);
57
+ if (job.state.status === "terminal")
58
+ return textReply(`Job #${id} is no longer running. Start or fork a job for new work.`, true);
59
+ const conversationId = await jobConversationId(api, id, context);
60
+ const conversation = conversationId === undefined ? undefined : await api.conversation(conversationId, context);
61
+ if (conversation === undefined)
62
+ return textReply(`Job #${id} has no conversation.`, true);
63
+ const requestId = `job:${id}:steer:${api.taskId}`;
64
+ await api.commit(async (tx) => {
65
+ const current = await tx.task(id);
66
+ if (current === undefined || current.kind !== JOB_KIND || current.state.status === "terminal"
67
+ || current.state.checkpoint.phase !== "run")
68
+ throw new Error(`Job #${id} is no longer running.`);
69
+ const link = await tx.doc(JobLink, id);
70
+ // Admission and tracking are atomic; the job cannot finish between them.
71
+ await conversation.submit(tx, { ...draft, requestId, whenIdle: "reject" });
72
+ link.steering = { requestId, message: draft.content };
73
+ }, context);
74
+ return textReply(`Steering queued for job #${id}. It will receive the message at its next boundary; work continues. Wait for its completion notice; do not poll.`);
75
+ }
76
+ catch (error) {
77
+ return textReply(error instanceof ConversationIdle
78
+ ? `Job #${id} has no active run to steer; it may have just finished.`
79
+ : error instanceof Error ? error.message : String(error), true);
80
+ }
81
+ }
82
+ if (args.action === "tag") {
83
+ if (api.conversationId !== ROOT_CONVERSATION_ID)
84
+ return textReply("Only main may assign job tags.", true);
85
+ if (args.id === undefined || args.tags === undefined)
86
+ return textReply("Provide a job id and tags array; [] clears the tags.", true);
87
+ try {
88
+ const tags = await api.commit((tx) => setJobTags(tx, Number(args.id), args.tags), context);
89
+ return textReply(`Job #${args.id} tags: ${tags.join(", ") || "(none)"}.`);
90
+ }
91
+ catch (error) {
92
+ return textReply(error instanceof Error ? error.message : String(error), true);
93
+ }
94
+ }
95
+ if (args.action === "list") {
96
+ const now = Date.now();
97
+ const previous = listedAt.get(Number(api.conversationId)) ?? 0;
98
+ if (now - previous < LIST_COOLDOWN_MS) {
99
+ return {
100
+ output: [{
101
+ type: "text",
102
+ text: "You just listed jobs. Do not poll; end this turn and wait for a completion notice.",
103
+ }],
104
+ control: { terminate: true },
105
+ };
106
+ }
107
+ listedAt.set(Number(api.conversationId), now);
108
+ const page = await api.commit((tx) => tx.scanTasks({ kind: JOB_KIND }, 100), context);
109
+ const labels = await api.snapshot(JobTags, context);
110
+ return textReply(formatJobList(page.items.map((record) => taggedJob(record, labels)), Date.now()));
111
+ }
112
+ if (args.action === "show") {
113
+ if (args.id === undefined)
114
+ return textReply("Provide a job id.", true);
115
+ const raw = await api.getTask(args.id, context);
116
+ if (raw === undefined)
117
+ return textReply(`No job #${args.id}.`, true);
118
+ const record = taggedJob(raw, await api.snapshot(JobTags, context));
119
+ const live = record.state.status !== "terminal";
120
+ if (live) {
121
+ const key = `${Number(api.conversationId)}:${args.id}`;
122
+ const now = Date.now();
123
+ const previous = shownAt.get(key) ?? 0;
124
+ if (now - previous < LIVE_SHOW_COOLDOWN_MS) {
125
+ return {
126
+ output: [{
127
+ type: "text",
128
+ text: `Job #${args.id} is still running. You already checked it; do not poll. ` +
129
+ `End this turn; a completion notice will start the next turn.`,
130
+ }],
131
+ control: { terminate: true },
132
+ };
133
+ }
134
+ shownAt.set(key, now);
135
+ return textReply(`${formatJobDetail(record, Date.now())}\n\n` +
136
+ `Still running. Do not poll; a completion notice will arrive automatically.`);
137
+ }
138
+ return textReply(formatJobDetail(record, Date.now()));
139
+ }
140
+ let brief;
141
+ let tags;
142
+ try {
143
+ brief = normalizeBrief(args.brief);
144
+ tags = normalizeTags(args.tags ?? []);
145
+ }
146
+ catch (error) {
147
+ return textReply(error instanceof Error ? error.message : String(error), true);
148
+ }
149
+ const cwd = (await api.agent(context)).cwd ?? options.cwd;
150
+ const started = await api.commit((tx) => createJobInCommit(tx, brief, options.model, options.jobExtensions, cwd, {
151
+ ...options.jobOptions,
152
+ notifyMain: true,
153
+ tags,
154
+ }), context);
155
+ return textReply(`Started job #${started.taskId} in conversation #${started.conversationId}${tags.length === 0 ? "" : ` with tags ${tags.join(", ")}`}. It runs in the background. ` +
156
+ `A completion notice will arrive automatically; do not poll.`);
157
+ },
158
+ });
159
+ const forkTool = defineTool({
160
+ name: "fork",
161
+ description: "Main only: fork prepared conversation context into a new background job with a new brief. " +
162
+ "source is main, a numeric job id, or tag:reviewer for a uniquely tagged job. The latest completed assistant turn is the cutoff; running tasks are not copied. " +
163
+ "Prime one scouting job, then fork it into variants. Choose shared to use the source directory, or worktree " +
164
+ "for a host-managed branch from its clean Git HEAD. Worktrees persist for review/resume; all variants report to main. " +
165
+ "The active session model is used for every job. Completion notices arrive automatically; do not poll.",
166
+ parameters: obj({
167
+ source: str({ pattern: "^(main|[1-9][0-9]*|tag:[A-Za-z0-9][A-Za-z0-9._-]{0,47})$" }),
168
+ brief: str({ minLength: 1, maxLength: 4000 }),
169
+ workspace: opt(oneOf(["shared", "worktree"])),
170
+ tags: opt(tagsSchema),
171
+ }),
172
+ callers: ["model"],
173
+ replay: "unsafe",
174
+ execute: async (args, api, context) => {
175
+ if (api.conversationId !== ROOT_CONVERSATION_ID)
176
+ return textReply("Only main may fork context into jobs.", true);
177
+ try {
178
+ const brief = normalizeBrief(args.brief);
179
+ const tags = normalizeTags(args.tags ?? []);
180
+ const source = resolveTaggedSource(args.source, await api.snapshot(JobTags, context));
181
+ const origin = await api.commit((tx) => selectForkSource(tx, source), context);
182
+ const agent = await api.snapshotAsOf(AgentDoc, origin.conversationId, origin.entryId, context);
183
+ const workspace = await planWorkspace(agent?.cwd ?? options.cwd, args.workspace ?? "shared", context.abortSignal);
184
+ const started = await api.commit((tx) => createJobInCommit(tx, brief, options.model, options.jobExtensions, workspace.cwd, {
185
+ ...options.jobOptions,
186
+ notifyMain: true,
187
+ fork: origin,
188
+ workspace,
189
+ tags,
190
+ }), context);
191
+ return textReply(`Forked ${origin.jobId === undefined ? "main" : `job #${origin.jobId}`} (${args.source}) at entry #${origin.entryId} into job #${started.taskId} ` +
192
+ `(conversation #${started.conversationId}). Brief: ${brief}. Tags: ${tags.join(", ") || "none"}. Workspace: ${workspace.cwd}` +
193
+ `${workspace.kind === "worktree" ? `; branch ${workspace.branch}; base ${workspace.baseCommit}. Setup finishes before the job starts.` : " (shared)."} ` +
194
+ "It reports back to main automatically. Do not poll.");
195
+ }
196
+ catch (error) {
197
+ return textReply(error instanceof Error ? error.message : String(error), true);
198
+ }
199
+ },
200
+ });
201
+ return defineExtension({
202
+ name: "durable-chat.tasks",
203
+ tools: [taskTool, forkTool],
204
+ });
205
+ }