@phren/cli 0.3.11 → 0.3.12
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/bridge/agent-hook-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +5 -0
- package/dist/bridge/agent-hooks.d.ts +159 -5
- package/dist/bridge/agent-hooks.js +663 -49
- package/dist/bridge/approval-summary.d.ts +16 -0
- package/dist/bridge/approval-summary.js +133 -0
- package/dist/bridge/authority-command.d.ts +20 -0
- package/dist/bridge/authority-command.js +120 -0
- package/dist/bridge/authority.d.ts +223 -0
- package/dist/bridge/authority.js +231 -0
- package/dist/bridge/claude-account-setup.d.ts +14 -0
- package/dist/bridge/claude-account-setup.js +69 -0
- package/dist/bridge/claude-accounts.d.ts +49 -0
- package/dist/bridge/claude-accounts.js +195 -0
- package/dist/bridge/code-routes.js +2 -2
- package/dist/bridge/codex-app-server.d.ts +144 -0
- package/dist/bridge/codex-app-server.js +319 -0
- package/dist/bridge/codex-auth-refresh.d.ts +33 -0
- package/dist/bridge/codex-auth-refresh.js +71 -0
- package/dist/bridge/codex-question-reply.d.ts +16 -0
- package/dist/bridge/codex-question-reply.js +57 -0
- package/dist/bridge/codex-review-mode.d.ts +10 -0
- package/dist/bridge/codex-review-mode.js +74 -0
- package/dist/bridge/codex-servers.d.ts +217 -0
- package/dist/bridge/codex-servers.js +636 -0
- package/dist/bridge/command.js +94 -4
- package/dist/bridge/computer-identity.d.ts +75 -0
- package/dist/bridge/computer-identity.js +166 -0
- package/dist/bridge/conductor-group.d.ts +91 -8
- package/dist/bridge/conductor-group.js +105 -9
- package/dist/bridge/conductor-role.d.ts +94 -0
- package/dist/bridge/conductor-role.js +176 -0
- package/dist/bridge/conductor-sets.d.ts +20 -0
- package/dist/bridge/conductor-sets.js +59 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +75 -11
- package/dist/bridge/dispatch-returns.d.ts +123 -19
- package/dist/bridge/dispatch-returns.js +357 -50
- package/dist/bridge/dispatch.d.ts +103 -2
- package/dist/bridge/dispatch.js +272 -40
- package/dist/bridge/fanouts.d.ts +7 -1
- package/dist/bridge/fanouts.js +39 -4
- package/dist/bridge/folder-trust.d.ts +56 -0
- package/dist/bridge/folder-trust.js +195 -0
- package/dist/bridge/grants.d.ts +22 -1
- package/dist/bridge/grants.js +57 -9
- package/dist/bridge/hand-off.d.ts +21 -9
- package/dist/bridge/hand-off.js +58 -45
- package/dist/bridge/harness-status.d.ts +11 -0
- package/dist/bridge/harness-status.js +32 -0
- package/dist/bridge/harnesses.d.ts +39 -0
- package/dist/bridge/harnesses.js +65 -0
- package/dist/bridge/health.d.ts +2 -0
- package/dist/bridge/health.js +1 -1
- package/dist/bridge/herdr.d.ts +11 -2
- package/dist/bridge/herdr.js +98 -23
- package/dist/bridge/hook-fast.d.ts +4 -0
- package/dist/bridge/hook-fast.js +68 -0
- package/dist/bridge/install.d.ts +16 -1
- package/dist/bridge/install.js +88 -21
- package/dist/bridge/launch-brief.d.ts +96 -0
- package/dist/bridge/launch-brief.js +164 -0
- package/dist/bridge/model-switch.d.ts +3 -0
- package/dist/bridge/model-switch.js +17 -1
- package/dist/bridge/models.d.ts +8 -4
- package/dist/bridge/models.js +24 -8
- package/dist/bridge/mux-wire.d.ts +9 -0
- package/dist/bridge/mux-wire.js +19 -0
- package/dist/bridge/opencode-pane-server.d.ts +113 -0
- package/dist/bridge/opencode-pane-server.js +332 -0
- package/dist/bridge/opencode-panes.d.ts +111 -0
- package/dist/bridge/opencode-panes.js +295 -0
- package/dist/bridge/pane-accounts.d.ts +8 -0
- package/dist/bridge/pane-accounts.js +46 -0
- package/dist/bridge/prompt-startup.d.ts +5 -0
- package/dist/bridge/prompt-startup.js +24 -0
- package/dist/bridge/protocol.d.ts +5 -0
- package/dist/bridge/protocol.js +4 -0
- package/dist/bridge/push.d.ts +5 -4
- package/dist/bridge/push.js +6 -4
- package/dist/bridge/questions.d.ts +37 -2
- package/dist/bridge/questions.js +158 -15
- package/dist/bridge/resources.d.ts +9 -3
- package/dist/bridge/resources.js +24 -8
- package/dist/bridge/schedule-format.d.ts +2 -0
- package/dist/bridge/schedule-format.js +3 -0
- package/dist/bridge/schedule-launch.d.ts +2 -1
- package/dist/bridge/schedule-launch.js +23 -53
- package/dist/bridge/schedule-watch.d.ts +10 -1
- package/dist/bridge/schedule-watch.js +54 -2
- package/dist/bridge/server-launch.d.ts +22 -5
- package/dist/bridge/server-launch.js +225 -29
- package/dist/bridge/server-overview.d.ts +3 -3
- package/dist/bridge/server-overview.js +22 -14
- package/dist/bridge/server-pane-routes.d.ts +2 -0
- package/dist/bridge/server-pane-routes.js +145 -15
- package/dist/bridge/server-routes.d.ts +7 -0
- package/dist/bridge/server-routes.js +163 -35
- package/dist/bridge/server-stream.d.ts +2 -0
- package/dist/bridge/server-stream.js +22 -8
- package/dist/bridge/server.d.ts +6 -1
- package/dist/bridge/server.js +44 -12
- package/dist/bridge/session-activity.d.ts +81 -0
- package/dist/bridge/session-activity.js +117 -0
- package/dist/bridge/session-rename.d.ts +48 -0
- package/dist/bridge/session-rename.js +190 -0
- package/dist/bridge/session-servers.js +2 -2
- package/dist/bridge/settings-switch.d.ts +60 -0
- package/dist/bridge/settings-switch.js +287 -0
- package/dist/bridge/speech-voice.d.ts +55 -0
- package/dist/bridge/speech-voice.js +132 -0
- package/dist/bridge/speech.d.ts +70 -11
- package/dist/bridge/speech.js +169 -41
- package/dist/bridge/terminal-herdr.js +9 -3
- package/dist/bridge/terminal-tmux.d.ts +3 -3
- package/dist/bridge/terminal-tmux.js +24 -9
- package/dist/bridge/terminal.d.ts +27 -4
- package/dist/bridge/terminal.js +8 -1
- package/dist/bridge/transcript-claude.js +57 -12
- package/dist/bridge/transcript-codex.d.ts +0 -2
- package/dist/bridge/transcript-codex.js +29 -4
- package/dist/bridge/transcript-preview.d.ts +1 -0
- package/dist/bridge/transcript-preview.js +24 -4
- package/dist/bridge/transcripts.d.ts +15 -2
- package/dist/bridge/transcripts.js +47 -16
- package/dist/bridge/turn-records.d.ts +85 -0
- package/dist/bridge/turn-records.js +143 -0
- package/dist/bridge/uploads.d.ts +3 -0
- package/dist/bridge/uploads.js +14 -0
- package/dist/bridge/usage.d.ts +39 -10
- package/dist/bridge/usage.js +155 -44
- package/dist/bridge-hook.mjs +19169 -13176
- package/dist/cli/claude-unmanaged.d.ts +12 -0
- package/dist/cli/claude-unmanaged.js +105 -0
- package/dist/cli/schedules.js +2 -1
- package/dist/cli/session-start.js +10 -1
- package/dist/cli/session-stop.js +9 -1
- package/dist/cli-registry.js +24 -5
- package/dist/data/task-receipts.d.ts +19 -0
- package/dist/data/task-receipts.js +68 -0
- package/dist/data/tasks.js +4 -1
- package/dist/generated/memory-ui-graph.browser.js +63 -63
- package/dist/graph-core/model.js +24 -3
- package/dist/graph-core/types.d.ts +4 -1
- package/dist/graph-core/types.js +1 -0
- package/dist/init/init-preset.js +7 -3
- package/dist/init/init-uninstall.js +2 -11
- package/dist/init/teardown.d.ts +3 -0
- package/dist/init/teardown.js +47 -0
- package/dist/link/context.js +21 -9
- package/dist/mcp/plugin-mode.js +1 -1
- package/dist/memory-ui-graph.runtime.js +63 -63
- package/dist/modules/code-package.d.ts +1 -0
- package/dist/modules/code-package.js +36 -7
- package/dist/modules/registry.js +14 -13
- package/dist/profile-store.d.ts +6 -0
- package/dist/profile-store.js +25 -1
- package/dist/shell/graph/glyphs.js +4 -0
- package/dist/shell/graph/graph-view.js +2 -0
- package/dist/status.js +7 -1
- package/dist/sync/task-claim.js +3 -2
- package/dist/task/lifecycle.js +25 -4
- package/dist/test-global-setup.js +5 -0
- package/dist/tools/dispatch.js +35 -2
- package/dist/tools/tasks.js +10 -1
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +87 -4
- package/starter/global/skills/conductor/SKILL.md +17 -2
|
@@ -92,6 +92,7 @@ export async function claudeChildAgents(file, session) {
|
|
|
92
92
|
return cached.relations;
|
|
93
93
|
}
|
|
94
94
|
const launches = new Map();
|
|
95
|
+
const stops = new Map();
|
|
95
96
|
// Named teammates (the Agent tool with a `name`) run as their own session
|
|
96
97
|
// and never post a task-notification: they announce themselves idle in a
|
|
97
98
|
// teammate-message instead, and may be woken again later. Their file is
|
|
@@ -101,15 +102,21 @@ export async function claudeChildAgents(file, session) {
|
|
|
101
102
|
for await (const line of lines) {
|
|
102
103
|
try {
|
|
103
104
|
const raw = object(JSON.parse(line)), result = object(raw.toolUseResult);
|
|
105
|
+
const blocks = objects(object(raw.message).content);
|
|
104
106
|
const agentId = String(result.agentId ?? ""), status = String(result.status ?? "");
|
|
105
107
|
if (/^[A-Za-z0-9._-]{1,128}$/.test(agentId) && ["async_launched", "running"].includes(status)) {
|
|
106
|
-
const
|
|
108
|
+
const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
|
|
107
109
|
if (callId)
|
|
108
110
|
launches.set(agentId, { path: String(result.description || result.name || "Agent").slice(0, 200), callId, state: "running" });
|
|
109
111
|
}
|
|
110
112
|
if (raw.type === "assistant") {
|
|
111
|
-
for (const block of
|
|
112
|
-
if (block.type !== "tool_use"
|
|
113
|
+
for (const block of blocks) {
|
|
114
|
+
if (block.type !== "tool_use")
|
|
115
|
+
continue;
|
|
116
|
+
if (block.name === "TaskStop" && typeof block.id === "string" && typeof object(block.input).task_id === "string") {
|
|
117
|
+
stops.set(block.id, String(object(block.input).task_id));
|
|
118
|
+
}
|
|
119
|
+
if (block.name !== "Agent")
|
|
113
120
|
continue;
|
|
114
121
|
const input = object(block.input), name = String(input.name ?? "");
|
|
115
122
|
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name) || typeof block.id !== "string")
|
|
@@ -117,14 +124,35 @@ export async function claudeChildAgents(file, session) {
|
|
|
117
124
|
teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
|
|
118
125
|
}
|
|
119
126
|
}
|
|
127
|
+
// A stop request alone proves nothing. Its successful, matching result
|
|
128
|
+
// ends the child even when no later task notification is recorded.
|
|
129
|
+
if (raw.type === "user") {
|
|
130
|
+
for (const block of blocks) {
|
|
131
|
+
if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
|
|
132
|
+
continue;
|
|
133
|
+
const task = stops.get(block.tool_use_id);
|
|
134
|
+
if (!task)
|
|
135
|
+
continue;
|
|
136
|
+
stops.delete(block.tool_use_id);
|
|
137
|
+
const previous = launches.get(task);
|
|
138
|
+
if (previous && block.is_error !== true && result.task_id === task && typeof result.message === "string"
|
|
139
|
+
&& /^Successfully stopped task\b/i.test(result.message))
|
|
140
|
+
previous.state = "completed";
|
|
141
|
+
}
|
|
142
|
+
}
|
|
120
143
|
const content = typeof raw.content === "string" ? raw.content : typeof object(raw.message).content === "string" ? String(object(raw.message).content) : "";
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
144
|
+
const attachment = object(raw.attachment);
|
|
145
|
+
const notices = [raw.type === "queue-operation" || raw.type === "user" ? content : "",
|
|
146
|
+
...(raw.type === "user" ? blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)) : []),
|
|
147
|
+
raw.type === "attachment" && attachment.type === "queued_command" && attachment.commandMode === "task-notification" && typeof attachment.prompt === "string" ? attachment.prompt : ""];
|
|
148
|
+
for (const notice of notices) {
|
|
149
|
+
for (const match of notice.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
|
|
150
|
+
const child = /<task-id>([^<>]{1,128})<\/task-id>/.exec(match[1])?.[1], taskStatus = /<status>([^<>]+)<\/status>/.exec(match[1])?.[1].trim();
|
|
151
|
+
// Terminal notifications end only the child named in that envelope.
|
|
152
|
+
const previous = child && launches.get(child);
|
|
153
|
+
if (previous && ["completed", "failed", "cancelled", "canceled", "killed", "stopped"].includes(taskStatus ?? ""))
|
|
154
|
+
previous.state = "completed";
|
|
155
|
+
}
|
|
128
156
|
}
|
|
129
157
|
if (content.includes("<teammate-message")) {
|
|
130
158
|
const from = /<teammate-message teammate_id="([A-Za-z0-9][A-Za-z0-9_-]{0,63})"/.exec(content)?.[1];
|
|
@@ -199,7 +227,10 @@ async function claudeChildBelongsTo(file, parent, agentId) {
|
|
|
199
227
|
return false;
|
|
200
228
|
}
|
|
201
229
|
}
|
|
202
|
-
|
|
230
|
+
// `effort` rides on each assistant row (Claude Code 2.1): with `message.model`
|
|
231
|
+
// it is what the phone's model chip shows as in effect. `permissionMode` on a
|
|
232
|
+
// user row is the mode that turn ran in (the phone's permission chip).
|
|
233
|
+
const CLAUDE_KEYS = new Set(["type", "uuid", "parentUuid", "timestamp", "message", "gitBranch", "cwd", "requestId", "isMeta", "isSidechain", "isCompactSummary", "phrenQueued", "phrenQueueKey", "phrenBackground", "phrenCompacted", "effort", "permissionMode"]);
|
|
203
234
|
export const harnessPreamble = (text) => /^<(?:environment_context>|user_instructions>|permission_profile|system-reminder>|turn_context>)/.test(text.trimStart());
|
|
204
235
|
function taskNotification(content) {
|
|
205
236
|
const envelope = /<task-notification>([\s\S]*?)<\/task-notification>/.exec(content)?.[1];
|
|
@@ -273,6 +304,11 @@ export function skillBody(raw) {
|
|
|
273
304
|
return { type: "user", timestamp: raw.timestamp, ...(typeof raw.uuid === "string" ? { uuid: raw.uuid } : {}),
|
|
274
305
|
message: { role: "user", content: [{ type: "tool_result", tool_use_id: raw.sourceToolUseID, content: text.slice(0, 32_768), phrenSkillBody: true }] } };
|
|
275
306
|
}
|
|
307
|
+
/** Claude Code's label where a pasted picture path was, and the footer the
|
|
308
|
+
* phone puts above the paths of the files it attached. */
|
|
309
|
+
const QUEUED_IMAGE_LABEL = /\[Image #\d+\]/;
|
|
310
|
+
const QUEUED_IMAGE_LABELS = /\[Image #\d+\]/g;
|
|
311
|
+
const ATTACHED_FILES_FOOTER = /Attached files on this computer:\s*$/;
|
|
276
312
|
/** A phren UserPromptSubmit injection, as `{ type: "phren_hook_context",
|
|
277
313
|
* parentUuid, content }`, or undefined for any other row. */
|
|
278
314
|
export function phrenHookContext(raw, includeSidechain = false) {
|
|
@@ -336,8 +372,13 @@ export function visibleClaudeEvent(raw, includeSidechain = false) {
|
|
|
336
372
|
// tool envelope, private metadata, or reasoning is exported.
|
|
337
373
|
if (raw.operation === "remove")
|
|
338
374
|
return { type: "phren_queue_consumed", key, timestamp: raw.timestamp };
|
|
375
|
+
// A picture sent mid-turn queues as "[Image #7]Attached files on this
|
|
376
|
+
// computer:": the pixels never reach this row. Words-free, it matched no
|
|
377
|
+
// receipt, and the phone warned "Not confirmed in chat" about a picture
|
|
378
|
+
// the agent had taken. Name it the way a picture-only turn reads.
|
|
379
|
+
const pictureOnly = QUEUED_IMAGE_LABEL.test(text) && !text.replace(QUEUED_IMAGE_LABELS, "").replace(ATTACHED_FILES_FOOTER, "").trim();
|
|
339
380
|
return { type: "user", phrenQueued: true, phrenQueueKey: key, timestamp: raw.timestamp,
|
|
340
|
-
message: { role: "user", content: text } };
|
|
381
|
+
message: { role: "user", content: pictureOnly ? "[Image attachment]" : text } };
|
|
341
382
|
}
|
|
342
383
|
// Claude Code appends a boundary marker and then the summary it hands the
|
|
343
384
|
// model as a user turn. The phone shows the marker and a bounded preview,
|
|
@@ -359,6 +400,10 @@ export function visibleClaudeEvent(raw, includeSidechain = false) {
|
|
|
359
400
|
const skill = skillBody(raw);
|
|
360
401
|
if (skill)
|
|
361
402
|
return skill;
|
|
403
|
+
// The row Claude writes when the permission mode changes; nothing else of it.
|
|
404
|
+
if (raw.type === "permission-mode" && typeof raw.permissionMode === "string" && /^[A-Za-z]{1,30}$/.test(raw.permissionMode)) {
|
|
405
|
+
return { type: "permission-mode", permissionMode: raw.permissionMode, ...(typeof raw.timestamp === "string" ? { timestamp: raw.timestamp } : {}) };
|
|
406
|
+
}
|
|
362
407
|
if (raw.isMeta || (raw.isSidechain && !includeSidechain) || !["user", "assistant", "system"].includes(String(raw.type)))
|
|
363
408
|
return undefined;
|
|
364
409
|
raw = Object.fromEntries(Object.entries(raw).filter(([key]) => CLAUDE_KEYS.has(key)));
|
|
@@ -5,8 +5,6 @@ import type { Entry, LocalChildAgentRelation } from "./transcripts.js";
|
|
|
5
5
|
export type DirectRelation = Pick<LocalChildAgentRelation, "session" | "path" | "callId" | "state">;
|
|
6
6
|
export declare function directChildAgents(file: string): Promise<DirectRelation[]>;
|
|
7
7
|
export declare function childTranscriptBelongsTo(file: string, parent: string): Promise<boolean>;
|
|
8
|
-
/** Codex rows the phone may see: public messages, tool calls and their
|
|
9
|
-
* outputs, the answering model, and turn/usage events. */
|
|
10
8
|
export declare function visibleCodexEvent(raw: Json): Json | undefined;
|
|
11
9
|
export interface CodeModeWrapper {
|
|
12
10
|
callId: string;
|
|
@@ -3,6 +3,7 @@ import { stat } from "node:fs/promises";
|
|
|
3
3
|
import { object, objects, sessionId } from "./protocol.js";
|
|
4
4
|
import { visibleCodexExecEvent } from "./fanouts.js";
|
|
5
5
|
import { harnessPreamble } from "./transcript-claude.js";
|
|
6
|
+
import { readableQuestionReply } from "./codex-question-reply.js";
|
|
6
7
|
const childRelationCache = new Map();
|
|
7
8
|
function addChildRelation(line, found) {
|
|
8
9
|
if (!line.includes("SubAgentActivity"))
|
|
@@ -73,6 +74,15 @@ export async function childTranscriptBelongsTo(file, parent) {
|
|
|
73
74
|
}
|
|
74
75
|
/** Codex rows the phone may see: public messages, tool calls and their
|
|
75
76
|
* outputs, the answering model, and turn/usage events. */
|
|
77
|
+
/** The approval policy (a granular one as its kind), reviewer, sandbox kind and
|
|
78
|
+
* collaboration mode of a turn_context, each only when short and plain. */
|
|
79
|
+
function turnSettings(p) {
|
|
80
|
+
const word = (value) => typeof value === "string" && /^[A-Za-z_-]{1,30}$/.test(value) ? value : undefined;
|
|
81
|
+
const policy = word(p.approval_policy) ?? (p.approval_policy && typeof p.approval_policy === "object" ? Object.keys(p.approval_policy).find(key => word(key)) : undefined);
|
|
82
|
+
const reviewer = word(p.approvals_reviewer), sandbox = word(object(p.sandbox_policy).type), mode = word(object(p.collaboration_mode).mode);
|
|
83
|
+
return { ...(policy ? { approval_policy: policy } : {}), ...(reviewer ? { approvals_reviewer: reviewer } : {}),
|
|
84
|
+
...(sandbox ? { sandbox_policy: { type: sandbox } } : {}), ...(mode ? { collaboration_mode: { mode } } : {}) };
|
|
85
|
+
}
|
|
76
86
|
export function visibleCodexEvent(raw) {
|
|
77
87
|
if (raw.type === "phren_queue_consumed" && typeof raw.key === "string" && /^[a-f0-9]{64}$/.test(raw.key)) {
|
|
78
88
|
return { type: raw.type, key: raw.key };
|
|
@@ -81,10 +91,12 @@ export function visibleCodexEvent(raw) {
|
|
|
81
91
|
if (execEvent)
|
|
82
92
|
return execEvent;
|
|
83
93
|
const p = object(raw.payload);
|
|
84
|
-
// The model answering this turn
|
|
85
|
-
//
|
|
94
|
+
// The model answering this turn, its effort and the permission and plan
|
|
95
|
+
// settings are the only fields of turn_context the phone shows; its
|
|
96
|
+
// instructions, paths and rules stay on the computer.
|
|
86
97
|
if (raw.type === "turn_context")
|
|
87
|
-
return typeof p.model === "string" ? { type: "turn_context", timestamp: raw.timestamp,
|
|
98
|
+
return typeof p.model === "string" ? { type: "turn_context", timestamp: raw.timestamp,
|
|
99
|
+
payload: { model: p.model, ...(typeof p.effort === "string" && p.effort.length <= 20 ? { effort: p.effort } : {}), ...turnSettings(p) } } : undefined;
|
|
88
100
|
if (raw.type === "event_msg" && p.type === "error")
|
|
89
101
|
return { type: raw.type, timestamp: raw.timestamp,
|
|
90
102
|
payload: { type: "error", ...(typeof p.message === "string" ? { message: p.message } : {}) } };
|
|
@@ -99,7 +111,20 @@ export function visibleCodexEvent(raw) {
|
|
|
99
111
|
return wrapper.images.length ? imageCall(raw, wrapper) : undefined;
|
|
100
112
|
if (p.type === "message" && ["user", "assistant"].includes(String(p.role)) && p.channel !== "analysis") {
|
|
101
113
|
const text = typeof p.content === "string" ? p.content : objects(p.content).map(b => typeof b.text === "string" ? b.text : "").join("\n");
|
|
102
|
-
|
|
114
|
+
if (p.role === "user" && harnessPreamble(text))
|
|
115
|
+
return undefined;
|
|
116
|
+
// An answer to an async question reads as the question and its answer,
|
|
117
|
+
// not as the envelope Codex's TUI (or the Hook) sent it in.
|
|
118
|
+
// Only the reply's own block changes: attached files and images that
|
|
119
|
+
// came with the answer stay as their own blocks.
|
|
120
|
+
if (p.role === "user" && Array.isArray(p.content) && readableQuestionReply(text) !== undefined) {
|
|
121
|
+
return { ...raw, payload: { ...p, content: objects(p.content).map(block => {
|
|
122
|
+
const readable = typeof block.text === "string" ? readableQuestionReply(block.text) : undefined;
|
|
123
|
+
return readable === undefined ? block : { ...block, text: readable };
|
|
124
|
+
}) } };
|
|
125
|
+
}
|
|
126
|
+
const answered = p.role === "user" && typeof p.content === "string" ? readableQuestionReply(p.content) : undefined;
|
|
127
|
+
return answered ? { ...raw, payload: { ...p, content: answered } } : raw;
|
|
103
128
|
}
|
|
104
129
|
if (["function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output"].includes(String(p.type)))
|
|
105
130
|
return raw;
|
|
@@ -92,6 +92,7 @@ export declare class TranscriptPreviewStream {
|
|
|
92
92
|
private current;
|
|
93
93
|
private observedLine;
|
|
94
94
|
private wasWorking;
|
|
95
|
+
private readonly codexCompleted;
|
|
95
96
|
private readonly rollout;
|
|
96
97
|
constructor(target: Target, pane?: () => Promise<string>, delta?: (file?: string) => Promise<TranscriptPreview | null>);
|
|
97
98
|
observe(entries: Entry[], reset?: boolean): void;
|
|
@@ -402,6 +402,7 @@ export class TranscriptPreviewStream {
|
|
|
402
402
|
current = null;
|
|
403
403
|
observedLine = -1;
|
|
404
404
|
wasWorking = false;
|
|
405
|
+
codexCompleted = new Set();
|
|
405
406
|
rollout = new CodexRolloutPreview();
|
|
406
407
|
constructor(target, pane = () => readPreviewPane(target), delta = file => readDeltaPreview(target, file, this.rollout)) {
|
|
407
408
|
this.target = target;
|
|
@@ -415,19 +416,33 @@ export class TranscriptPreviewStream {
|
|
|
415
416
|
this.landed = false;
|
|
416
417
|
this.ended = false;
|
|
417
418
|
this.wasWorking = false;
|
|
419
|
+
this.codexCompleted.clear();
|
|
418
420
|
}
|
|
419
421
|
for (const { raw, line } of entries) {
|
|
420
422
|
if (line <= this.observedLine)
|
|
421
423
|
continue;
|
|
422
424
|
this.observedLine = line;
|
|
423
425
|
if (this.target.source === "codex") {
|
|
424
|
-
//
|
|
425
|
-
//
|
|
426
|
+
// A completed commentary message can land before task_complete while
|
|
427
|
+
// Codex keeps working on a tool call.
|
|
426
428
|
const payload = object(raw.payload);
|
|
427
|
-
if (raw.type === "event_msg" && payload.type === "task_started")
|
|
429
|
+
if (raw.type === "event_msg" && payload.type === "task_started") {
|
|
428
430
|
this.ended = false;
|
|
429
|
-
|
|
431
|
+
this.codexCompleted.clear();
|
|
432
|
+
}
|
|
433
|
+
else if (raw.type === "response_item" && payload.type === "message" && payload.role === "user" && !raw.phrenQueued) {
|
|
430
434
|
this.ended = false;
|
|
435
|
+
this.codexCompleted.clear();
|
|
436
|
+
}
|
|
437
|
+
else if (raw.type === "response_item" && payload.type === "message" && payload.role === "assistant") {
|
|
438
|
+
const text = (typeof payload.content === "string" ? payload.content
|
|
439
|
+
: objects(payload.content).map(block => typeof block.text === "string" ? block.text : "").join("\n")).trim();
|
|
440
|
+
if (text) {
|
|
441
|
+
this.codexCompleted.add(text);
|
|
442
|
+
if (this.codexCompleted.size > 32)
|
|
443
|
+
this.codexCompleted.delete(this.codexCompleted.values().next().value);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
431
446
|
else if (raw.type === "event_msg" && ["task_complete", "task_completed", "turn_aborted", "task_aborted"].includes(String(payload.type)))
|
|
432
447
|
this.ended = true;
|
|
433
448
|
continue;
|
|
@@ -487,6 +502,11 @@ export class TranscriptPreviewStream {
|
|
|
487
502
|
// when the source is temporarily empty or unavailable.
|
|
488
503
|
if (!this.ended)
|
|
489
504
|
next = await this.delta(file);
|
|
505
|
+
if (this.target.source === "codex" && next) {
|
|
506
|
+
const text = next.text.trim();
|
|
507
|
+
if (text && [...this.codexCompleted].some(completed => completed.startsWith(text)))
|
|
508
|
+
next = null;
|
|
509
|
+
}
|
|
490
510
|
}
|
|
491
511
|
else if (this.target.source === "claude" && this.startedAt && !this.ended) {
|
|
492
512
|
if (readAt - this.lastRead < PREVIEW_INTERVAL_MS)
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type AccountRef } from "./claude-accounts.js";
|
|
1
2
|
import { type Json, type Provider, type Target } from "./protocol.js";
|
|
2
3
|
import { type ChangeLookup } from "./changes.js";
|
|
3
4
|
export { isNarration, unwrapPastedContent } from "./transcript-claude.js";
|
|
@@ -14,9 +15,11 @@ export interface ChildAgentRelation {
|
|
|
14
15
|
provider: Provider;
|
|
15
16
|
path: string;
|
|
16
17
|
callId: string;
|
|
17
|
-
state: "running" | "completed" | "failed" | "unavailable";
|
|
18
|
+
state: "running" | "completed" | "failed" | "gone" | "unavailable";
|
|
18
19
|
/** Why a fan-out worker did not finish: `blocked: <type> <pattern>`. */
|
|
19
20
|
reason?: string;
|
|
21
|
+
/** Present only when a source supplies a validated worker launch time. */
|
|
22
|
+
startedAt?: string;
|
|
20
23
|
finishedAt?: string;
|
|
21
24
|
/** Fan-out manifests and Claude child transcripts can name a model. */
|
|
22
25
|
model?: string;
|
|
@@ -60,7 +63,17 @@ export declare function childAgent(tree: ChildAgentRelation[], id: string): Loca
|
|
|
60
63
|
* yaml and the data layer, and this bundle is budgeted for cold start.
|
|
61
64
|
*/
|
|
62
65
|
export declare function phrenStoreRoot(env?: NodeJS.ProcessEnv): string;
|
|
63
|
-
|
|
66
|
+
/** The account a resolved Claude transcript belongs to, by the home holding it. */
|
|
67
|
+
export declare function transcriptAccount(file: string): AccountRef | undefined;
|
|
68
|
+
/** A pane's transcript: the pane's known Claude account settles a session id found in more than one home. */
|
|
69
|
+
export declare function targetTranscriptPath(target: {
|
|
70
|
+
server: string;
|
|
71
|
+
pane: string;
|
|
72
|
+
source: Provider;
|
|
73
|
+
session: string;
|
|
74
|
+
}): Promise<string>;
|
|
75
|
+
/** `account` (a Claude home id) settles a session id found in more than one home. */
|
|
76
|
+
export declare function transcriptPath(source: Provider, session: string, account?: string): Promise<string>;
|
|
64
77
|
/** Keeps a materialized Codex thread current before a read; a no-op for
|
|
65
78
|
* transcripts the agent writes itself. */
|
|
66
79
|
export declare function refreshTranscript(file: string, source: Provider, session: string): Promise<void>;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { readdir, realpath, lstat } from "node:fs/promises";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
|
-
import { codexHome
|
|
4
|
+
import { codexHome } from "../home-paths.js";
|
|
5
|
+
import { claudeAccountRef, claudeHomeOfPath, claudeHomes } from "./claude-accounts.js";
|
|
6
|
+
import { paneAccount, paneAccountKey } from "./pane-accounts.js";
|
|
5
7
|
import path from "node:path";
|
|
6
8
|
import { withTranscriptIndex } from "./transcript-index.js";
|
|
7
9
|
import { BridgeError, object, objects, sessionId } from "./protocol.js";
|
|
@@ -44,11 +46,12 @@ export async function childAgentTree(source, session, depth = 0, seen = new Set(
|
|
|
44
46
|
/** Explicit wire projection prevents a provider's private transcript identity
|
|
45
47
|
* from being returned if relation internals grow later. */
|
|
46
48
|
export function publicChildAgents(tree) {
|
|
47
|
-
return tree.map(({ id, provider, path: agentPath, callId, state, reason, finishedAt, model, worktreeName, branch, computer, remote, fanout, children }) =>
|
|
49
|
+
return tree.map(({ id, provider, path: agentPath, callId, state, reason, startedAt, finishedAt, model, worktreeName, branch, computer, remote, fanout, children }) =>
|
|
48
50
|
// A blocked worker is finished; the phone's relation contract has no failed
|
|
49
51
|
// state, so the reason carries what happened without breaking old clients.
|
|
50
|
-
({ id, provider, path: agentPath, callId, state: state === "failed" ? "completed" : state,
|
|
51
|
-
...(state === "failed" ? { failed: true } : {}),
|
|
52
|
+
({ id, provider, path: agentPath, callId, state: state === "failed" || state === "gone" ? "completed" : state,
|
|
53
|
+
...(state === "failed" || state === "gone" ? { failed: true } : {}),
|
|
54
|
+
...(startedAt ? { startedAt } : {}), ...(finishedAt ? { finishedAt } : {}),
|
|
52
55
|
...(reason !== undefined ? { reason } : {}), ...(model !== undefined ? { model } : {}),
|
|
53
56
|
...(worktreeName !== undefined ? { worktreeName } : {}), ...(branch !== undefined ? { branch } : {}),
|
|
54
57
|
...(computer !== undefined ? { computer: { id: computer.id, name: computer.name } } : {}),
|
|
@@ -185,27 +188,49 @@ async function findPatternMatches(root, pattern) {
|
|
|
185
188
|
await walk(root, 0);
|
|
186
189
|
return matches;
|
|
187
190
|
}
|
|
188
|
-
|
|
191
|
+
/** The account a resolved Claude transcript belongs to, by the home holding it. */
|
|
192
|
+
export function transcriptAccount(file) {
|
|
193
|
+
const home = claudeHomeOfPath(file);
|
|
194
|
+
return home ? claudeAccountRef(home) : undefined;
|
|
195
|
+
}
|
|
196
|
+
/** A pane's transcript: the pane's known Claude account settles a session id found in more than one home. */
|
|
197
|
+
export function targetTranscriptPath(target) {
|
|
198
|
+
const account = target.source === "claude" ? paneAccount(paneAccountKey(target.server, target.pane))?.id : undefined;
|
|
199
|
+
return transcriptPath(target.source, target.session, account);
|
|
200
|
+
}
|
|
201
|
+
/** `account` (a Claude home id) settles a session id found in more than one home. */
|
|
202
|
+
export async function transcriptPath(source, session, account) {
|
|
189
203
|
if (!sessionId.safeParse(session).success)
|
|
190
204
|
throw new BridgeError(400, "Invalid conversation identity.");
|
|
191
|
-
const
|
|
192
|
-
: source === "claude" ? path.join(
|
|
193
|
-
: source === "phren" || source === "opencode" ? path.join(phrenStoreRoot(), ".runtime", "sessions")
|
|
194
|
-
: path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "session-state");
|
|
195
|
-
const root = await realpath(base).catch(() => base);
|
|
205
|
+
const bases = source === "codex" ? [{ base: path.join(codexHome(), "sessions") }]
|
|
206
|
+
: source === "claude" ? claudeHomes().map(home => ({ id: home.id, base: path.join(home.dir, "projects") }))
|
|
207
|
+
: source === "phren" || source === "opencode" ? [{ base: path.join(phrenStoreRoot(), ".runtime", "sessions") }]
|
|
208
|
+
: [{ base: path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "session-state") }];
|
|
196
209
|
const pattern = source === "codex" ? `*/*/*/rollout-*-${session}.jsonl` : source === "claude" ? `*/${session}.jsonl`
|
|
197
210
|
: source === "phren" ? `session-${session}.events.jsonl` : source === "opencode" ? `opencode-${session}.events.jsonl` : `${session}/events.jsonl`;
|
|
198
|
-
const
|
|
199
|
-
|
|
211
|
+
const found = [];
|
|
212
|
+
for (const entry of bases) {
|
|
213
|
+
const root = await realpath(entry.base).catch(() => entry.base);
|
|
214
|
+
const matches = await findPatternMatches(root, pattern).catch(() => []);
|
|
215
|
+
for (const match of matches)
|
|
216
|
+
found.push({ id: entry.id, root, match });
|
|
217
|
+
}
|
|
218
|
+
let chosen = found;
|
|
219
|
+
if (source === "claude" && found.length > 1 && account) {
|
|
220
|
+
const preferred = found.filter(item => item.id === account);
|
|
221
|
+
if (preferred.length)
|
|
222
|
+
chosen = preferred;
|
|
223
|
+
}
|
|
224
|
+
if (chosen.length !== 1) {
|
|
200
225
|
// Codex 0.155 keeps new threads only in its sqlite store; the Hook
|
|
201
226
|
// materializes those into a rollout-shaped file of its own.
|
|
202
227
|
const materialized = source === "codex" ? await materializeCodexThread(session) : undefined;
|
|
203
228
|
if (materialized)
|
|
204
229
|
return materialized;
|
|
205
|
-
throw new BridgeError(404, "The transcript is not available for this conversation.");
|
|
230
|
+
throw new BridgeError(404, "The transcript is not available for this conversation.", { code: "transcript-unavailable" });
|
|
206
231
|
}
|
|
207
|
-
const file = await realpath(
|
|
208
|
-
if (!file.startsWith(root + path.sep))
|
|
232
|
+
const file = await realpath(chosen[0].match);
|
|
233
|
+
if (!file.startsWith(chosen[0].root + path.sep))
|
|
209
234
|
throw new BridgeError(403, "The transcript points outside its agent folder.");
|
|
210
235
|
return file;
|
|
211
236
|
}
|
|
@@ -341,8 +366,14 @@ export class TranscriptReader {
|
|
|
341
366
|
this.revision = index.revision;
|
|
342
367
|
this.nextLine = held ?? index.lines;
|
|
343
368
|
}
|
|
369
|
+
// Live reads run newest first. After a long disconnect or a burst of
|
|
370
|
+
// output, a bounded page can stop before the phone's cursor. Mark that
|
|
371
|
+
// page as a replacement so its start becomes a usable older-page cursor
|
|
372
|
+
// instead of silently merging two disjoint windows. A pending diff
|
|
373
|
+
// holds its row for a later poll and is not a completed page.
|
|
374
|
+
const skippedLiveLines = before === undefined && held === undefined && cursor > lower;
|
|
344
375
|
return { entries: entries.reverse(), totalLines: index.lines, startLine: cursor, hasMore: cursor > 0,
|
|
345
|
-
reset: resuming && !pastEnd ? false : reset };
|
|
376
|
+
reset: (resuming && !pastEnd ? false : reset) || skippedLiveLines };
|
|
346
377
|
}, signal);
|
|
347
378
|
}
|
|
348
379
|
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { type Provider } from "./protocol.js";
|
|
3
|
+
/** Longest final reply kept from a Stop payload, in UTF-8 bytes (the receipt's limit). */
|
|
4
|
+
export declare const TURN_REPLY_LIMIT = 4000;
|
|
5
|
+
declare const turnRecordSchema: z.ZodObject<{
|
|
6
|
+
terminal: z.ZodString;
|
|
7
|
+
source: z.ZodEnum<{
|
|
8
|
+
claude: "claude";
|
|
9
|
+
codex: "codex";
|
|
10
|
+
copilot: "copilot";
|
|
11
|
+
opencode: "opencode";
|
|
12
|
+
phren: "phren";
|
|
13
|
+
}>;
|
|
14
|
+
session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
|
|
15
|
+
seq: z.ZodNumber;
|
|
16
|
+
dispatch: z.ZodOptional<z.ZodString>;
|
|
17
|
+
startedAt: z.ZodOptional<z.ZodString>;
|
|
18
|
+
prompt: z.ZodOptional<z.ZodObject<{
|
|
19
|
+
seq: z.ZodNumber;
|
|
20
|
+
at: z.ZodString;
|
|
21
|
+
}, z.core.$strict>>;
|
|
22
|
+
stop: z.ZodOptional<z.ZodObject<{
|
|
23
|
+
seq: z.ZodNumber;
|
|
24
|
+
at: z.ZodString;
|
|
25
|
+
background: z.ZodOptional<z.ZodNumber>;
|
|
26
|
+
reply: z.ZodOptional<z.ZodString>;
|
|
27
|
+
truncated: z.ZodOptional<z.ZodBoolean>;
|
|
28
|
+
}, z.core.$strict>>;
|
|
29
|
+
at: z.ZodString;
|
|
30
|
+
}, z.core.$strict>;
|
|
31
|
+
export type TurnRecord = z.infer<typeof turnRecordSchema>;
|
|
32
|
+
export interface TurnEvent {
|
|
33
|
+
event: string;
|
|
34
|
+
terminal: string;
|
|
35
|
+
source: Provider;
|
|
36
|
+
session: string;
|
|
37
|
+
/** SessionStart / UserPromptSubmit: the dispatch id the worker's hook named. */
|
|
38
|
+
dispatch?: string;
|
|
39
|
+
/** Stop only: the harness's count of in-flight background tasks, when it reports one. */
|
|
40
|
+
background?: number;
|
|
41
|
+
/** Stop only: the harness's last assistant message, when it reports one. */
|
|
42
|
+
reply?: string;
|
|
43
|
+
at?: number;
|
|
44
|
+
}
|
|
45
|
+
export declare const turnPath: (server: string, pane: string) => string;
|
|
46
|
+
/** `value` cut to at most `limit` UTF-8 bytes on a character boundary. */
|
|
47
|
+
export declare function truncateUtf8(value: string, limit?: number): {
|
|
48
|
+
text: string;
|
|
49
|
+
truncated: boolean;
|
|
50
|
+
};
|
|
51
|
+
/** The record after one lifecycle event; undefined for events that say nothing about turns.
|
|
52
|
+
* Another conversation or terminal in the pane starts a fresh record. */
|
|
53
|
+
export declare function nextTurn(previous: TurnRecord | undefined, event: TurnEvent): TurnRecord | undefined;
|
|
54
|
+
export type TurnPhase = {
|
|
55
|
+
phase: "unprompted";
|
|
56
|
+
} | {
|
|
57
|
+
phase: "working";
|
|
58
|
+
since: string;
|
|
59
|
+
} | {
|
|
60
|
+
phase: "ended";
|
|
61
|
+
at: string;
|
|
62
|
+
background?: number;
|
|
63
|
+
reply?: string;
|
|
64
|
+
truncated?: boolean;
|
|
65
|
+
};
|
|
66
|
+
/** Where the recorded conversation is: no prompt yet, a prompt with no Stop
|
|
67
|
+
* after it, or a turn that stopped. A Stop with no recorded prompt (hooks
|
|
68
|
+
* installed mid-conversation) still ended a turn. */
|
|
69
|
+
export declare function turnPhase(record: TurnRecord): TurnPhase;
|
|
70
|
+
/** The background tasks of a Stop at `stoppedAt` still running: the Stop's
|
|
71
|
+
* count less the tasks whose finish the transcript recorded after it
|
|
72
|
+
* (`FinalTurn.finishedTasks`). No turn ran since that Stop, so every task
|
|
73
|
+
* finishing after it is one the count included; a finish does not always
|
|
74
|
+
* bring a new Stop (its notification can wait in an idle session's queue). */
|
|
75
|
+
export declare function backgroundLeft(count: number | undefined, stoppedAt: string, finishedTasks?: readonly string[]): number;
|
|
76
|
+
/** Record one lifecycle event for `pane`. Writes run one at a time, so a Stop
|
|
77
|
+
* and the next prompt arriving together keep their order. */
|
|
78
|
+
export declare function noteTurn(server: string, pane: string, event: TurnEvent): Promise<TurnRecord | undefined>;
|
|
79
|
+
/** The recorded turns of `pane`'s latest conversation, if its hooks reported any. */
|
|
80
|
+
export declare function readTurn(server: string, pane: string): Promise<TurnRecord | undefined>;
|
|
81
|
+
/** OpenCode's turns for a pane running `pids`, from the stamps phren's OpenCode
|
|
82
|
+
* plugin writes on session.status busy / session.idle; undefined for an older
|
|
83
|
+
* plugin that writes none. `terminal` is the pane's, since the PIDs are. */
|
|
84
|
+
export declare function opencodeTurn(pids: number[], terminal: string): Promise<TurnRecord | undefined>;
|
|
85
|
+
export {};
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// What a pane's agent last said about its own turns, from its lifecycle hooks:
|
|
2
|
+
// when a prompt was submitted, when the turn stopped, what it stopped with and
|
|
3
|
+
// whether the harness still had background work in flight. Dispatch returns
|
|
4
|
+
// answer from this record first (dispatch-returns.ts `workerStates`): a
|
|
5
|
+
// worker is done only once a Stop arrived after its prompt, never because it
|
|
6
|
+
// has looked idle for a while.
|
|
7
|
+
//
|
|
8
|
+
// Claude, Codex, Copilot and phren-agent send SessionStart, UserPromptSubmit
|
|
9
|
+
// and Stop to the Hook (agent-hooks.ts), which records them here, one small
|
|
10
|
+
// file per pane beside its binding. OpenCode has no such hooks; phren's
|
|
11
|
+
// OpenCode plugin stamps its turns into the per-PID status file instead
|
|
12
|
+
// (`opencodeTurn`).
|
|
13
|
+
//
|
|
14
|
+
// The record is keyed by pane and holds the latest conversation there, with
|
|
15
|
+
// the dispatch id (PHREN_DISPATCH_ID) its SessionStart or first prompt named,
|
|
16
|
+
// so a dispatch placed on this computer is matched by id as well as by pane
|
|
17
|
+
// and conversation.
|
|
18
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
import { z } from "zod";
|
|
21
|
+
import { opencodeTurnStamps } from "./harness-status.js";
|
|
22
|
+
import { briefId } from "./launch-brief.js";
|
|
23
|
+
import { atomicInPrivateDir, bridgeRoot, provider, serverName, sessionId } from "./protocol.js";
|
|
24
|
+
/** Longest final reply kept from a Stop payload, in UTF-8 bytes (the receipt's limit). */
|
|
25
|
+
export const TURN_REPLY_LIMIT = 4000;
|
|
26
|
+
const MAX_RECORD_BYTES = 16_384;
|
|
27
|
+
const stamp = z.object({ seq: z.number().int().min(0), at: z.string().datetime() }).strict();
|
|
28
|
+
const turnRecordSchema = z.object({
|
|
29
|
+
terminal: z.string().min(1).max(200), source: provider, session: sessionId,
|
|
30
|
+
/** Climbs with every recorded event, so prompt and stop are ordered without trusting the clock. */
|
|
31
|
+
seq: z.number().int().min(0),
|
|
32
|
+
/** The dispatch this conversation was launched for, as its hooks named it. */
|
|
33
|
+
dispatch: briefId.optional(),
|
|
34
|
+
startedAt: z.string().datetime().optional(),
|
|
35
|
+
prompt: stamp.optional(),
|
|
36
|
+
stop: stamp.extend({
|
|
37
|
+
/** Background tasks (shells, subagents, monitors) the harness still ran when the turn stopped. */
|
|
38
|
+
background: z.number().int().min(0).max(999).optional(),
|
|
39
|
+
reply: z.string().max(TURN_REPLY_LIMIT).optional(), truncated: z.boolean().optional(),
|
|
40
|
+
}).strict().optional(),
|
|
41
|
+
at: z.string().datetime(),
|
|
42
|
+
}).strict();
|
|
43
|
+
export const turnPath = (server, pane) => path.join(bridgeRoot(), "turns", encodeURIComponent(serverName.parse(server)), encodeURIComponent(pane) + ".json");
|
|
44
|
+
/** `value` cut to at most `limit` UTF-8 bytes on a character boundary. */
|
|
45
|
+
export function truncateUtf8(value, limit = TURN_REPLY_LIMIT) {
|
|
46
|
+
const bytes = Buffer.from(value);
|
|
47
|
+
if (bytes.length <= limit)
|
|
48
|
+
return { text: value, truncated: false };
|
|
49
|
+
let end = limit;
|
|
50
|
+
while (end > 0 && (bytes[end] & 0xc0) === 0x80)
|
|
51
|
+
end--;
|
|
52
|
+
return { text: bytes.subarray(0, end).toString("utf8"), truncated: true };
|
|
53
|
+
}
|
|
54
|
+
/** The record after one lifecycle event; undefined for events that say nothing about turns.
|
|
55
|
+
* Another conversation or terminal in the pane starts a fresh record. */
|
|
56
|
+
export function nextTurn(previous, event) {
|
|
57
|
+
if (!["SessionStart", "UserPromptSubmit", "Stop"].includes(event.event))
|
|
58
|
+
return undefined;
|
|
59
|
+
const at = new Date(event.at ?? Date.now()).toISOString();
|
|
60
|
+
const same = previous && previous.terminal === event.terminal && previous.source === event.source && previous.session === event.session;
|
|
61
|
+
const record = same ? structuredClone(previous) : { terminal: event.terminal, source: event.source, session: event.session, seq: 0, at };
|
|
62
|
+
record.seq++;
|
|
63
|
+
record.at = at;
|
|
64
|
+
if (event.dispatch && briefId.safeParse(event.dispatch).success)
|
|
65
|
+
record.dispatch ??= event.dispatch;
|
|
66
|
+
if (event.event === "SessionStart")
|
|
67
|
+
record.startedAt ??= at;
|
|
68
|
+
else if (event.event === "UserPromptSubmit")
|
|
69
|
+
record.prompt = { seq: record.seq, at };
|
|
70
|
+
else {
|
|
71
|
+
const reply = event.reply?.trim() ? truncateUtf8(event.reply.trim()) : undefined;
|
|
72
|
+
record.stop = { seq: record.seq, at, ...(event.background !== undefined ? { background: Math.min(999, Math.max(0, Math.floor(event.background))) } : {}),
|
|
73
|
+
...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {}) };
|
|
74
|
+
}
|
|
75
|
+
return record;
|
|
76
|
+
}
|
|
77
|
+
/** Where the recorded conversation is: no prompt yet, a prompt with no Stop
|
|
78
|
+
* after it, or a turn that stopped. A Stop with no recorded prompt (hooks
|
|
79
|
+
* installed mid-conversation) still ended a turn. */
|
|
80
|
+
export function turnPhase(record) {
|
|
81
|
+
const { prompt, stop } = record;
|
|
82
|
+
if (prompt && (!stop || stop.seq < prompt.seq))
|
|
83
|
+
return { phase: "working", since: prompt.at };
|
|
84
|
+
if (!stop)
|
|
85
|
+
return { phase: "unprompted" };
|
|
86
|
+
return { phase: "ended", at: stop.at, ...(stop.background ? { background: stop.background } : {}),
|
|
87
|
+
...(stop.reply ? { reply: stop.reply, ...(stop.truncated ? { truncated: true } : {}) } : {}) };
|
|
88
|
+
}
|
|
89
|
+
/** The background tasks of a Stop at `stoppedAt` still running: the Stop's
|
|
90
|
+
* count less the tasks whose finish the transcript recorded after it
|
|
91
|
+
* (`FinalTurn.finishedTasks`). No turn ran since that Stop, so every task
|
|
92
|
+
* finishing after it is one the count included; a finish does not always
|
|
93
|
+
* bring a new Stop (its notification can wait in an idle session's queue). */
|
|
94
|
+
export function backgroundLeft(count, stoppedAt, finishedTasks = []) {
|
|
95
|
+
if (!count)
|
|
96
|
+
return 0;
|
|
97
|
+
const stopped = Date.parse(stoppedAt);
|
|
98
|
+
return Math.max(0, count - finishedTasks.filter(at => Date.parse(at) >= stopped).length);
|
|
99
|
+
}
|
|
100
|
+
async function readRecord(file) {
|
|
101
|
+
try {
|
|
102
|
+
const info = await lstat(file);
|
|
103
|
+
if (!info.isFile() || info.size > MAX_RECORD_BYTES)
|
|
104
|
+
return undefined;
|
|
105
|
+
const parsed = turnRecordSchema.safeParse(JSON.parse(await readFile(file, "utf8")));
|
|
106
|
+
return parsed.success ? parsed.data : undefined;
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
let writes = Promise.resolve();
|
|
113
|
+
/** Record one lifecycle event for `pane`. Writes run one at a time, so a Stop
|
|
114
|
+
* and the next prompt arriving together keep their order. */
|
|
115
|
+
export function noteTurn(server, pane, event) {
|
|
116
|
+
const run = writes.then(async () => {
|
|
117
|
+
const file = turnPath(server, pane);
|
|
118
|
+
const next = nextTurn(await readRecord(file), event);
|
|
119
|
+
if (next)
|
|
120
|
+
await atomicInPrivateDir(file, turnRecordSchema.parse(next));
|
|
121
|
+
return next;
|
|
122
|
+
});
|
|
123
|
+
writes = run.catch(() => undefined);
|
|
124
|
+
return run;
|
|
125
|
+
}
|
|
126
|
+
/** The recorded turns of `pane`'s latest conversation, if its hooks reported any. */
|
|
127
|
+
export function readTurn(server, pane) {
|
|
128
|
+
return readRecord(turnPath(server, pane));
|
|
129
|
+
}
|
|
130
|
+
/** OpenCode's turns for a pane running `pids`, from the stamps phren's OpenCode
|
|
131
|
+
* plugin writes on session.status busy / session.idle; undefined for an older
|
|
132
|
+
* plugin that writes none. `terminal` is the pane's, since the PIDs are. */
|
|
133
|
+
export async function opencodeTurn(pids, terminal) {
|
|
134
|
+
const stamps = await opencodeTurnStamps(pids);
|
|
135
|
+
if (!stamps)
|
|
136
|
+
return undefined;
|
|
137
|
+
const busy = stamps.busyAt ? Date.parse(stamps.busyAt) : NaN, idle = stamps.idleAt ? Date.parse(stamps.idleAt) : NaN;
|
|
138
|
+
const parsed = turnRecordSchema.safeParse({ terminal, source: "opencode", session: stamps.session, seq: 2, at: stamps.at,
|
|
139
|
+
...(Number.isFinite(busy) ? { prompt: { seq: 1, at: stamps.busyAt } } : {}),
|
|
140
|
+
// The plugin stamps idle after busy; an idle stamp older than the busy one belongs to an earlier turn.
|
|
141
|
+
...(Number.isFinite(idle) && !(idle < busy) ? { stop: { seq: 2, at: stamps.idleAt } } : {}) });
|
|
142
|
+
return parsed.success ? parsed.data : undefined;
|
|
143
|
+
}
|