durable-chat 0.0.0-stage → 1.0.1

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/faux.js ADDED
@@ -0,0 +1,89 @@
1
+ import { fauxAssistantMessage, fauxText, fauxToolCall } from "@earendil-works/pi-ai/providers/faux";
2
+ function blockText(content) {
3
+ if (typeof content === "string")
4
+ return content;
5
+ if (!Array.isArray(content))
6
+ return "";
7
+ return content.flatMap((block) => {
8
+ if (typeof block !== "object" || block === null)
9
+ return [];
10
+ const value = block;
11
+ return value.type === "text" && typeof value.text === "string" ? [value.text] : [];
12
+ }).join("");
13
+ }
14
+ function latestUserText(messages) {
15
+ for (let index = messages.length - 1; index >= 0; index--) {
16
+ const message = messages[index];
17
+ if (message.role === "user")
18
+ return blockText(message.content).trim();
19
+ }
20
+ return "";
21
+ }
22
+ function toolResultSinceUser(messages) {
23
+ for (let index = messages.length - 1; index >= 0; index--) {
24
+ const message = messages[index];
25
+ if (message.role === "user")
26
+ return undefined;
27
+ if (message.role === "toolResult" && (message.toolName === "task" || message.toolName === "handoff" || message.toolName === "fork"))
28
+ return message.toolName;
29
+ }
30
+ return undefined;
31
+ }
32
+ /**
33
+ * Offline stand-in for a real model. It scripts one deterministic turn per request:
34
+ * `task: <objective>` becomes a real call to the task tool, so the durable path can be
35
+ * exercised without credentials. It is not a model and makes no claim to be one.
36
+ */
37
+ export function createFauxResponder(faux) {
38
+ const script = (context) => {
39
+ // Keep exactly one scripted turn queued: the tool round asks for a second generation.
40
+ faux.appendResponses([script]);
41
+ const messages = context.messages;
42
+ const completedTool = toolResultSinceUser(messages);
43
+ if (completedTool !== undefined) {
44
+ return fauxAssistantMessage([
45
+ fauxText(completedTool === "task"
46
+ ? "Task created by the offline faux model. Use /tasks (or `durable-chat tasks`) to follow it."
47
+ : completedTool === "fork" ? "Fork request handled by the offline faux model; watch its job notice."
48
+ : "Handoff recorded by the offline faux model. This job ends here."),
49
+ ]);
50
+ }
51
+ const userText = latestUserText(messages);
52
+ const fork = /^fork\s*:\s*(main|[1-9][0-9]*|tag:[a-z0-9][a-z0-9._-]{0,47})\s+([\s\S]+)$/i.exec(userText);
53
+ if (fork !== null) {
54
+ return fauxAssistantMessage([fauxToolCall("fork", { source: fork[1].toLowerCase(), brief: fork[2].trim(), workspace: "shared" })], { stopReason: "toolUse" });
55
+ }
56
+ const handoff = /^handoff\s*:\s*(main|job)\s+([\s\S]+)$/i.exec(userText);
57
+ if (handoff !== null) {
58
+ return fauxAssistantMessage([
59
+ fauxToolCall("handoff", {
60
+ target: handoff[1].toLowerCase(),
61
+ brief: handoff[2].trim(),
62
+ summary: "Offline faux handoff: verified progress recorded from the previous step.",
63
+ }),
64
+ ], { stopReason: "toolUse" });
65
+ }
66
+ const taskRequest = /^(?:task|job)\s*:\s*([\s\S]+)$/i.exec(userText);
67
+ if (taskRequest !== null) {
68
+ return fauxAssistantMessage([
69
+ fauxToolCall("task", {
70
+ action: "create",
71
+ brief: taskRequest[1].trim(),
72
+ }),
73
+ ], { stopReason: "toolUse" });
74
+ }
75
+ const text = latestUserText(messages);
76
+ return fauxAssistantMessage([
77
+ fauxText(`Offline faux model. You said: ${text || "(nothing)"}\n\n` +
78
+ `Set DURABLE_PROVIDER=openai and DURABLE_MODEL_ID for a real model, or send "task: <objective>" to create a durable task.`),
79
+ ]);
80
+ };
81
+ return {
82
+ ensure() {
83
+ // Keep a small burst buffer: a job generation and a main generation can start together.
84
+ const pending = faux.getPendingResponseCount();
85
+ if (pending < 4)
86
+ faux.appendResponses(Array.from({ length: 4 - pending }, () => script));
87
+ },
88
+ };
89
+ }
package/dist/forks.js ADDED
@@ -0,0 +1,33 @@
1
+ import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
2
+ import { JOB_KIND } from "./tasks.js";
3
+ /** Read a stable completed-turn cutoff. An in-flight tool round is never inherited as the fork point. */
4
+ export async function selectForkSource(tx, source) {
5
+ let conversationId = ROOT_CONVERSATION_ID;
6
+ let jobId;
7
+ if (source !== "main") {
8
+ if (!/^[1-9][0-9]*$/.test(source) || !Number.isSafeInteger(Number(source)))
9
+ throw new Error("Fork source must be main or a positive job id.");
10
+ jobId = Number(source);
11
+ const task = await tx.task(jobId);
12
+ if (task?.kind !== JOB_KIND)
13
+ throw new Error(`No source job #${jobId}.`);
14
+ const owned = await tx.scanConversations({ ownerTaskId: task.id }, 2);
15
+ if (owned.items.length !== 1)
16
+ throw new Error(`Source job #${jobId} has no unique conversation.`);
17
+ conversationId = owned.items[0].id;
18
+ }
19
+ const head = await tx.latestHeadMarker(conversationId);
20
+ let cursor;
21
+ do {
22
+ const page = await tx.scanEntries({ conversationId, order: "descending" }, 100, cursor);
23
+ for (const entry of page.items) {
24
+ if (head !== undefined && entry.id < head.head)
25
+ break;
26
+ if (entry.kind === "pi.assistant" && entry.model?.some((message) => message.role === "assistant" && message.stopReason === "stop")) {
27
+ return { conversationId: Number(conversationId), entryId: Number(entry.id), ...(jobId === undefined ? {} : { jobId }) };
28
+ }
29
+ }
30
+ cursor = head !== undefined && page.items.some((entry) => entry.id < head.head) ? undefined : page.next;
31
+ } while (cursor !== undefined);
32
+ throw new Error(`${source === "main" ? "Main" : `Job #${jobId}`} has no completed assistant turn to fork. Prime its context first.`);
33
+ }
package/dist/format.js ADDED
@@ -0,0 +1,144 @@
1
+ function asObject(value) {
2
+ return typeof value === "object" && value !== null ? value : undefined;
3
+ }
4
+ export function jobInput(record) {
5
+ const input = asObject(record.input);
6
+ return { brief: typeof input?.brief === "string" ? input.brief : "(no brief)" };
7
+ }
8
+ export function jobView(record) {
9
+ const state = asObject(record.state);
10
+ const checkpoint = asObject(state?.checkpoint);
11
+ const outcome = asObject(state?.outcome);
12
+ const result = asObject(outcome?.result);
13
+ const status = typeof state?.status === "string" ? state.status : "unknown";
14
+ let display = status;
15
+ let answer;
16
+ let reason;
17
+ let conversationId;
18
+ let handoff;
19
+ if (status === "running" && checkpoint?.phase === "report")
20
+ display = "reporting";
21
+ if (status === "running" && typeof checkpoint?.phase === "string" && checkpoint.phase.startsWith("handoff"))
22
+ display = "handing off";
23
+ if (status === "terminal" && outcome !== undefined) {
24
+ display = String(outcome.status);
25
+ const failure = asObject(outcome.error);
26
+ reason = typeof failure?.message === "string"
27
+ ? failure.message
28
+ : typeof outcome.reason === "string" ? outcome.reason : undefined;
29
+ }
30
+ if (typeof result?.answer === "string")
31
+ answer = result.answer;
32
+ if (typeof result?.reason === "string")
33
+ reason = reason ?? result.reason;
34
+ const rawHandoff = asObject(result?.handoff);
35
+ if (result?.status === "handed_off" && (rawHandoff?.target === "job" || rawHandoff?.target === "main")) {
36
+ const id = typeof rawHandoff.id === "number" ? rawHandoff.id : undefined;
37
+ handoff = { target: rawHandoff.target, ...(id === undefined ? {} : { id }) };
38
+ display = handoff.target === "main" ? "handed off → main" : `handed off → #${id ?? "?"}`;
39
+ }
40
+ const input = asObject(record.input);
41
+ const origin = asObject(input?.fork);
42
+ const fork = origin !== undefined && typeof origin.conversationId === "number" && typeof origin.entryId === "number"
43
+ ? { conversationId: origin.conversationId, entryId: origin.entryId, ...(typeof origin.jobId === "number" ? { jobId: origin.jobId } : {}) }
44
+ : undefined;
45
+ const rawWorkspace = asObject(input?.workspace);
46
+ const workspace = rawWorkspace !== undefined && typeof rawWorkspace.cwd === "string" &&
47
+ (rawWorkspace.kind === "shared" || (rawWorkspace.kind === "worktree" &&
48
+ ["repository", "gitDirectory", "baseCommit", "path", "branch"].every((key) => typeof rawWorkspace[key] === "string")))
49
+ ? rawWorkspace : undefined;
50
+ const rawConversation = result?.conversationId;
51
+ if (typeof rawConversation === "number" && rawConversation > 0)
52
+ conversationId = rawConversation;
53
+ if (record.abortRequested && status !== "terminal")
54
+ display = `${display} (abort requested)`;
55
+ return {
56
+ id: Number(record.id),
57
+ brief: jobInput(record).brief,
58
+ tags: record.tags ?? [],
59
+ status: display,
60
+ ...(conversationId === undefined ? {} : { conversationId }),
61
+ ...(answer === undefined ? {} : { answer }),
62
+ ...(reason === undefined ? {} : { reason }),
63
+ ...(handoff === undefined ? {} : { handoff }),
64
+ abortRequested: record.abortRequested,
65
+ ...(fork === undefined ? {} : { fork }),
66
+ ...(workspace === undefined ? {} : { workspace }),
67
+ ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),
68
+ ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),
69
+ };
70
+ }
71
+ export function formatDuration(ms) {
72
+ if (!Number.isFinite(ms) || ms < 0)
73
+ return "?";
74
+ if (ms < 1000)
75
+ return `${Math.round(ms)}ms`;
76
+ const seconds = Math.round(ms / 1000);
77
+ if (seconds < 60)
78
+ return `${seconds}s`;
79
+ const minutes = Math.floor(seconds / 60);
80
+ if (minutes < 60)
81
+ return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`;
82
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
83
+ }
84
+ function age(view, now) {
85
+ return formatDuration(Math.max(0, (view.endedAt ?? now) - (view.startedAt ?? now)));
86
+ }
87
+ export function truncate(text, width) {
88
+ const flat = text.replace(/\s+/g, " ").trim();
89
+ return flat.length <= width ? flat : `${flat.slice(0, Math.max(0, width - 1))}…`;
90
+ }
91
+ export function formatJobRow(record, now) {
92
+ const view = jobView(record);
93
+ const id = `#${view.id}`.padEnd(5);
94
+ const status = truncate(view.status, 18).padEnd(18);
95
+ const label = view.fork === undefined ? view.brief : `fork ${view.fork.jobId === undefined ? "main" : `#${view.fork.jobId}`} · ${view.brief}`;
96
+ const brief = truncate(`${view.tags.length === 0 ? "" : `[${view.tags.join(", ")}] `}${label}`, 52).padEnd(54);
97
+ return `${id}${status}${brief}${age(view, now)}`;
98
+ }
99
+ export function formatJobList(records, now) {
100
+ if (records.length === 0) {
101
+ return "No jobs yet. Start one with `durable-chat task add \"<brief>\"` or ask the agent.";
102
+ }
103
+ const sorted = [...records].sort((a, b) => Number(a.id) - Number(b.id));
104
+ const header = `${"ID".padEnd(5)}${"STATUS".padEnd(18)}${"BRIEF".padEnd(54)}AGE`;
105
+ return [header, ...sorted.map((record) => formatJobRow(record, now))].join("\n");
106
+ }
107
+ export function formatJobDetail(record, now) {
108
+ const view = jobView(record);
109
+ const lines = [];
110
+ lines.push(`Job #${view.id} ${view.status} (${age(view, now)})`);
111
+ lines.push(`Brief: ${view.brief}`);
112
+ if (view.tags.length > 0)
113
+ lines.push(`Tags: ${view.tags.join(", ")}`);
114
+ if (view.conversationId !== undefined)
115
+ lines.push(`Conversation: #${view.conversationId}`);
116
+ if (view.fork !== undefined)
117
+ lines.push(`Context fork: ${view.fork.jobId === undefined ? "main" : `job #${view.fork.jobId}`} (conversation #${view.fork.conversationId}), through entry #${view.fork.entryId}`);
118
+ if (view.workspace !== undefined) {
119
+ lines.push(`Workspace: ${view.workspace.cwd} (${view.workspace.kind})`);
120
+ if (view.workspace.kind === "worktree")
121
+ lines.push(`Branch: ${view.workspace.branch}`, `Base commit: ${view.workspace.baseCommit}`);
122
+ }
123
+ if (view.answer !== undefined && view.answer.trim().length > 0) {
124
+ lines.push("");
125
+ lines.push("Answer:");
126
+ for (const line of view.answer.trimEnd().split("\n"))
127
+ lines.push(` ${line}`);
128
+ }
129
+ if (view.handoff !== undefined) {
130
+ lines.push("");
131
+ lines.push(`Handoff: ${view.handoff.target === "main" ? "main" : `job #${view.handoff.id ?? "?"}`}`);
132
+ }
133
+ if (view.reason !== undefined) {
134
+ lines.push("");
135
+ lines.push(`Reason: ${view.reason}`);
136
+ }
137
+ if (record.restarts !== undefined && record.restarts > 0)
138
+ lines.push(`Restarts: ${record.restarts}`);
139
+ return lines.join("\n");
140
+ }
141
+ export function formatLiveJobLine(record, now) {
142
+ const view = jobView(record);
143
+ return `#${view.id} ${view.status} — ${truncate(view.brief, 70)} (${age(view, now)})`;
144
+ }
@@ -0,0 +1,56 @@
1
+ import { defineExtension, defineTool } from "@earendil-works/pi-durable";
2
+ import { obj, oneOf, str } from "@earendil-works/pi-schema";
3
+ import { JobHandoffDoc } from "./tasks.js";
4
+ const handoffTool = defineTool({
5
+ name: "handoff",
6
+ description: "Hand this job's remaining work to a new job or back to the coordinator (main). Provide a self-contained " +
7
+ "brief and a short summary of verified progress. The handoff ends this job after the current tool round.",
8
+ parameters: obj({
9
+ target: oneOf(["job", "main"]),
10
+ brief: str({ minLength: 1, maxLength: 2000 }),
11
+ summary: str({ minLength: 1, maxLength: 4000 }),
12
+ }),
13
+ // Recording a handoff changes control flow; do not rerun it after a cut.
14
+ replay: "unsafe",
15
+ execute: async (args, api, context) => {
16
+ const target = args.target;
17
+ const brief = args.brief.trim();
18
+ const summary = args.summary.trim();
19
+ if (brief.length === 0 || summary.length === 0) {
20
+ return { isError: true, output: [{ type: "text", text: "A handoff needs a brief and a summary." }] };
21
+ }
22
+ const existing = await api.snapshot(JobHandoffDoc, api.conversationId, context);
23
+ if (existing !== undefined && existing.brief.length > 0) {
24
+ if (existing.target === target && existing.brief === brief && existing.summary === summary) {
25
+ return {
26
+ output: [{ type: "text", text: "This handoff was already recorded; the job ends here." }],
27
+ control: { terminate: true },
28
+ };
29
+ }
30
+ return {
31
+ isError: true,
32
+ output: [{ type: "text", text: "A different handoff is already recorded for this job." }],
33
+ };
34
+ }
35
+ await api.commit(async (tx) => {
36
+ const doc = await tx.doc(JobHandoffDoc, api.conversationId);
37
+ doc.target = target;
38
+ doc.brief = brief;
39
+ doc.summary = summary;
40
+ doc.at = Date.now();
41
+ }, context);
42
+ return {
43
+ output: [{
44
+ type: "text",
45
+ text: target === "main"
46
+ ? "Handoff to main recorded. The coordinator receives the summary and continuation brief; this job ends."
47
+ : "Handoff to a successor job recorded. The successor receives the summary and continuation brief; this job ends.",
48
+ }],
49
+ control: { terminate: true },
50
+ };
51
+ },
52
+ });
53
+ export const JobHandoffTools = defineExtension({
54
+ name: "durable-chat.handoff",
55
+ tools: [handoffTool],
56
+ });