@phren/cli 0.3.67 → 0.3.69
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-callback.js +11 -2
- package/dist/bridge/agent-hooks.d.ts +11 -1
- package/dist/bridge/agent-hooks.js +259 -40
- package/dist/bridge/changes.d.ts +2 -2
- package/dist/bridge/changes.js +11 -9
- package/dist/bridge/checkpoints.d.ts +24 -0
- package/dist/bridge/checkpoints.js +423 -0
- package/dist/bridge/claude-input-state.d.ts +14 -0
- package/dist/bridge/claude-input-state.js +58 -0
- package/dist/bridge/claude-queue.js +5 -2
- package/dist/bridge/claude-suggestion.d.ts +3 -0
- package/dist/bridge/claude-suggestion.js +10 -0
- package/dist/bridge/codex-threads.d.ts +7 -1
- package/dist/bridge/codex-threads.js +185 -56
- package/dist/bridge/conversation-search.d.ts +20 -0
- package/dist/bridge/conversation-search.js +928 -0
- package/dist/bridge/git-watch.d.ts +46 -0
- package/dist/bridge/git-watch.js +351 -0
- package/dist/bridge/git-worktree-remove.d.ts +44 -0
- package/dist/bridge/git-worktree-remove.js +140 -0
- package/dist/bridge/git-worktrees.d.ts +14 -0
- package/dist/bridge/git-worktrees.js +7 -3
- package/dist/bridge/git-write-policy.js +1 -1
- package/dist/bridge/gitboy-webhooks.d.ts +3 -1
- package/dist/bridge/gitboy-webhooks.js +26 -2
- package/dist/bridge/herdr.d.ts +6 -1
- package/dist/bridge/herdr.js +56 -10
- package/dist/bridge/hook-fast.js +13 -1
- package/dist/bridge/input-classification.d.ts +33 -0
- package/dist/bridge/input-classification.js +84 -0
- package/dist/bridge/pane-status.d.ts +3 -3
- package/dist/bridge/pane-status.js +16 -8
- package/dist/bridge/prompt-deliveries.d.ts +30 -4
- package/dist/bridge/prompt-deliveries.js +365 -13
- package/dist/bridge/prompt-identity.d.ts +8 -0
- package/dist/bridge/prompt-identity.js +15 -0
- package/dist/bridge/request-origin.js +2 -1
- package/dist/bridge/schedule-events.d.ts +17 -0
- package/dist/bridge/schedule-events.js +53 -0
- package/dist/bridge/schedule-format.d.ts +22 -2
- package/dist/bridge/schedule-format.js +40 -5
- package/dist/bridge/schedule-update.js +2 -1
- package/dist/bridge/schedule-watch.js +15 -5
- package/dist/bridge/schedules.d.ts +9 -0
- package/dist/bridge/schedules.js +120 -7
- package/dist/bridge/server-pane-routes.d.ts +7 -8
- package/dist/bridge/server-pane-routes.js +186 -82
- package/dist/bridge/server-routes.d.ts +26 -2
- package/dist/bridge/server-routes.js +180 -56
- package/dist/bridge/server-stream.js +66 -15
- package/dist/bridge/server.js +25 -7
- package/dist/bridge/session-activity.d.ts +49 -4
- package/dist/bridge/session-activity.js +47 -0
- package/dist/bridge/session-evidence.d.ts +18 -0
- package/dist/bridge/session-evidence.js +72 -0
- package/dist/bridge/session-seen.d.ts +23 -0
- package/dist/bridge/session-seen.js +69 -0
- package/dist/bridge/tab-activity.d.ts +26 -1
- package/dist/bridge/tab-activity.js +64 -9
- package/dist/bridge/terminal-resolve.d.ts +20 -0
- package/dist/bridge/terminal-resolve.js +145 -0
- package/dist/bridge/terminal-tmux.d.ts +8 -3
- package/dist/bridge/terminal-tmux.js +59 -7
- package/dist/bridge/transcript-claude.d.ts +12 -2
- package/dist/bridge/transcript-claude.js +91 -13
- package/dist/bridge/transcript-index.d.ts +4 -2
- package/dist/bridge/transcript-index.js +6 -5
- package/dist/bridge/transcript-preview.d.ts +16 -1
- package/dist/bridge/transcript-preview.js +171 -27
- package/dist/bridge/transcripts.d.ts +41 -1
- package/dist/bridge/transcripts.js +181 -23
- package/dist/bridge/turn-queue-pane.d.ts +6 -0
- package/dist/bridge/turn-queue-pane.js +30 -0
- package/dist/bridge/turn-queue.d.ts +86 -0
- package/dist/bridge/turn-queue.js +280 -0
- package/dist/bridge/turn-records.d.ts +18 -0
- package/dist/bridge/turn-records.js +77 -5
- package/dist/bridge-hook.mjs +7074 -3173
- package/dist/cli/config-shared.js +2 -1
- package/dist/cli/schedules.js +6 -1
- package/dist/content/secrets.js +1 -1
- package/dist/modules/registry.js +12 -11
- package/package.json +1 -1
|
@@ -40,19 +40,24 @@ import { resolveFilePath } from "./file-resolve.js";
|
|
|
40
40
|
import { storeRoute } from "./memory-store.js";
|
|
41
41
|
import { memoryForFiles, memorySearch, PROJECT_MEMORY_ROUTE, projectMemory, saveFinding, tasksForBranch, completeProjectTask } from "./project-memory.js";
|
|
42
42
|
import { PROJECT_GIT_ROUTE, projectGit, projectHostToken } from "./project-git.js";
|
|
43
|
-
import {
|
|
43
|
+
import { availablePaneEvidence, childActivity, effectivePaneEvidence } from "./session-evidence.js";
|
|
44
|
+
import { liveWork, markBackground, ownRecord, paneRecord, recordTitle, replyExcerpt, resolveEffectiveStatus, turnCompletion } from "./session-activity.js";
|
|
45
|
+
import { markSessionSeen, readSessionSeen } from "./session-seen.js";
|
|
46
|
+
import { opencodeTurn, turnPhase } from "./turn-records.js";
|
|
44
47
|
import { paneAccountField, paneChatState, panes, rpc, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
|
|
45
48
|
import { locateProject } from "./locate.js";
|
|
46
49
|
import { gitStatus } from "./git.js";
|
|
47
50
|
import { gitRoot, launchDirectory, repositoryBranch, webServers, withGitReadDeadline } from "./projects.js";
|
|
48
|
-
import { approvalDecisions, atomicInPrivateDir, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
|
|
51
|
+
import { approvalDecisions, atomicInPrivateDir, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema, sessionId } from "./protocol.js";
|
|
49
52
|
import { bootedSimulators, simulatorAct, simulatorApps, simulatorDevices, simulatorScreenshot } from "./simulators.js";
|
|
50
|
-
import {
|
|
53
|
+
import { tabActivityKey } from "./tab-activity.js";
|
|
54
|
+
import { childAgentTree, completionEntry, historicalImage, publicChildAgents, refreshTranscript, targetTranscriptPath, transcriptPath, TranscriptReader } from "./transcripts.js";
|
|
55
|
+
import { conversationSearch } from "./conversation-search.js";
|
|
51
56
|
import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
|
|
52
57
|
import { currentModel, currentStep } from "./steps.js";
|
|
53
58
|
import { capacityRoom, usageForCaller } from "./usage.js";
|
|
59
|
+
import { SCHEDULE_EVENT_BODY_CAP } from "./schedule-events.js";
|
|
54
60
|
import { updateScheduleRoute } from "./schedule-update.js";
|
|
55
|
-
import { readFinalTurn } from "./schedule-watch.js";
|
|
56
61
|
import { cachedStoreWarnings, healthDetails, listsCaller } from "./health.js";
|
|
57
62
|
import { defaultPhrenPath } from "../shared.js";
|
|
58
63
|
import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
|
|
@@ -67,32 +72,50 @@ import { SPEECH_FORMATS, streamSpeech } from "./speech.js";
|
|
|
67
72
|
import { readSpeechKey } from "./speech-key.js";
|
|
68
73
|
import { DEFAULT_SPEECH_VOICE, listSpeechVoices, resolveSpeechVoice } from "./speech-voice.js";
|
|
69
74
|
import { terminalKind, terminalMux } from "./terminal.js";
|
|
75
|
+
import { resolveTerminalReference } from "./terminal-resolve.js";
|
|
70
76
|
import { muxListForClient, muxReplyForClient, typedMuxRequest } from "./mux-wire.js";
|
|
71
|
-
const CHILD_ACTIVITY_CACHE_MS = 5_000;
|
|
72
77
|
/** How long the overview waits for per-tab git and transcript reads; the phone gives up at 20 s. */
|
|
73
78
|
export const OVERVIEW_ENRICH_BUDGET_MS = 5_000;
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if (
|
|
80
|
-
return
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
childActivityCache.delete(childActivityCache.keys().next().value);
|
|
90
|
-
return result;
|
|
79
|
+
/** How long activity sampling may spend resolving background work before it
|
|
80
|
+
* leaves an unresolved row at its last known status. */
|
|
81
|
+
export const STATUS_ENRICH_BUDGET_MS = 2_000;
|
|
82
|
+
async function effectiveStatus(server, s, row, hooks) {
|
|
83
|
+
const panes = objects(s.panes).filter(p => p.tab_id === row.tab && p.workspace_id === row.workspace && p.agent);
|
|
84
|
+
if (panes.length !== 1 || !provider.safeParse(panes[0].agent).success)
|
|
85
|
+
return row;
|
|
86
|
+
const pane = panes[0];
|
|
87
|
+
const chat = await paneChatState(server, pane, { tokenWhenIdentified: false }).catch(() => ({}));
|
|
88
|
+
const session = typeof chat.sessionId === "string" ? chat.sessionId : undefined;
|
|
89
|
+
if (!session)
|
|
90
|
+
return row;
|
|
91
|
+
const evidence = await effectivePaneEvidence(server, { ...pane, agent_status: row.status }, session, hooks);
|
|
92
|
+
const resolved = resolveEffectiveStatus(evidence);
|
|
93
|
+
return !resolved || resolved === row.status ? row : { ...row, status: resolved };
|
|
91
94
|
}
|
|
92
|
-
|
|
93
|
-
|
|
95
|
+
/** The status each tab's row sends after the same background-work rules the
|
|
96
|
+
* overview applies: an idle or done tab whose ended turn still awaits shells or
|
|
97
|
+
* running children is working. The activity timer uses this while no overview
|
|
98
|
+
* is open, so its status clock still moves. A row whose background reads do not
|
|
99
|
+
* finish inside `budgetMs` is left out, which preserves its last known status. */
|
|
100
|
+
export async function effectiveStatusRows(server, s, budgetMs = STATUS_ENRICH_BUDGET_MS, hooks) {
|
|
101
|
+
const deadline = Date.now() + budgetMs;
|
|
102
|
+
const rows = await Promise.all(objects(s.tabs).map(async (tab) => {
|
|
103
|
+
const row = { workspace: tab.workspace_id, tab: tab.tab_id, status: tab.agent_status };
|
|
104
|
+
let timer;
|
|
105
|
+
const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), Math.max(0, deadline - Date.now())); timer.unref(); });
|
|
106
|
+
try {
|
|
107
|
+
return await Promise.race([effectiveStatus(server, s, row, hooks).catch(() => row), late]);
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
}
|
|
112
|
+
}));
|
|
113
|
+
return rows.filter((row) => row !== undefined);
|
|
114
|
+
}
|
|
115
|
+
export const capabilities = { turnCheckpoints: true, transcript: true, progress: true, images: true, prompt: true, stop: true,
|
|
116
|
+
terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, sessionSeen: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
|
|
94
117
|
approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
|
|
95
|
-
files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, queuedMessageActions: ["claude"], deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true };
|
|
118
|
+
files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, afterTurnQueue: true, queuedMessageActions: ["claude"], deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true, gitWatch: true, worktreeRemove: true, terminalResolve: true, conversationSearch: true };
|
|
96
119
|
export function capabilitiesForModules(snapshot) {
|
|
97
120
|
const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
|
|
98
121
|
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
|
|
@@ -104,6 +127,7 @@ export function capabilitiesForModules(snapshot) {
|
|
|
104
127
|
if (snapshot.has("schedules")) {
|
|
105
128
|
result.scheduleProjects = true;
|
|
106
129
|
result.scheduleUpdate = true;
|
|
130
|
+
result.scheduleEvents = true;
|
|
107
131
|
}
|
|
108
132
|
if (snapshot.has("tasks")) {
|
|
109
133
|
result.taskDependencies = true;
|
|
@@ -128,12 +152,12 @@ async function codePackageStatus(store, enabled) {
|
|
|
128
152
|
const from = loadedFrom();
|
|
129
153
|
return code && from ? { loadedFrom: from } : { missing: true };
|
|
130
154
|
}
|
|
131
|
-
async function body(request) {
|
|
155
|
+
async function body(request, cap = 11_500_000) {
|
|
132
156
|
let size = 0;
|
|
133
157
|
const chunks = [];
|
|
134
158
|
for await (const chunk of request) {
|
|
135
159
|
size += chunk.length;
|
|
136
|
-
if (size >
|
|
160
|
+
if (size > cap)
|
|
137
161
|
throw new BridgeError(413, "Request is too large.");
|
|
138
162
|
chunks.push(chunk);
|
|
139
163
|
}
|
|
@@ -155,10 +179,20 @@ export function selectedServer(url) {
|
|
|
155
179
|
}
|
|
156
180
|
return server;
|
|
157
181
|
}
|
|
182
|
+
/** The pane's turn record for its session row. OpenCode's plugin stamps its
|
|
183
|
+
* turns per PID instead of writing a lifecycle record. */
|
|
184
|
+
async function paneTurnRecord(server, pane, session) {
|
|
185
|
+
if (pane.agent !== "opencode")
|
|
186
|
+
return paneRecord(server, pane, session);
|
|
187
|
+
if (typeof pane.terminal_id !== "string")
|
|
188
|
+
return undefined;
|
|
189
|
+
const pids = (await terminalProvider().processes(server, String(pane.pane_id))).foregroundPids;
|
|
190
|
+
return ownRecord(await opencodeTurn(pids, pane.terminal_id), pane, "opencode", session);
|
|
191
|
+
}
|
|
158
192
|
export function workspacesReader(ctx) {
|
|
159
193
|
const { modules, info, agentHooks, journal, tabActivity, contextUsage } = ctx;
|
|
160
194
|
return async (server, s, watchApprovals) => {
|
|
161
|
-
const lastChanged = await tabActivity.observe(server, s);
|
|
195
|
+
const { generation, stamps: lastChanged } = await tabActivity.observe(server, s);
|
|
162
196
|
if (watchApprovals)
|
|
163
197
|
agentHooks.overview.renew(server);
|
|
164
198
|
const context = await contextUsage.read(server, s);
|
|
@@ -184,6 +218,7 @@ export function workspacesReader(ctx) {
|
|
|
184
218
|
// chat states; everything below it is decoration.
|
|
185
219
|
for (const { group, tab } of tabs) {
|
|
186
220
|
const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
|
|
221
|
+
tab.queuedPrompts = agents.reduce((count, pane) => count + (ctx.turnQueue?.count(server, String(pane.pane_id)) ?? 0), 0);
|
|
187
222
|
if (agents.length !== 1)
|
|
188
223
|
continue;
|
|
189
224
|
const chat = chatStates.get(agents[0]);
|
|
@@ -206,37 +241,76 @@ export function workspacesReader(ctx) {
|
|
|
206
241
|
// turn still has background work, and which dispatch it is. It runs
|
|
207
242
|
// alongside the slower reads so a stuck transcript cannot hide children, but
|
|
208
243
|
// inside the budget, so a stuck disk cannot hold the overview either.
|
|
209
|
-
const
|
|
244
|
+
const recordEnrichment = [];
|
|
210
245
|
const records = Promise.all(tabs.map(async ({ group, tab }) => {
|
|
211
246
|
const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
|
|
212
|
-
const
|
|
213
|
-
const
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
247
|
+
const pane = agents.length === 1 ? agents[0] : undefined;
|
|
248
|
+
const session = pane ? object(tab.target).session : undefined;
|
|
249
|
+
const record = typeof session === "string" && pane ? await paneTurnRecord(server, pane, session).catch(() => undefined) : undefined;
|
|
250
|
+
if (expired)
|
|
251
|
+
return;
|
|
252
|
+
if (pane && typeof session === "string") {
|
|
253
|
+
const available = availablePaneEvidence(server, pane, session, record, agentHooks);
|
|
254
|
+
if (available.held || ["blocked", "waiting"].includes(String(available.paneStatus)) || (record && turnPhase(record).phase === "working")) {
|
|
255
|
+
const status = resolveEffectiveStatus(available);
|
|
256
|
+
if (status)
|
|
257
|
+
tab.agentStatus = status;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
const seen = pane ? await readSessionSeen(server, String(pane.pane_id)) : undefined;
|
|
218
261
|
if (expired)
|
|
219
262
|
return;
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
263
|
+
const completion = turnCompletion(record);
|
|
264
|
+
if (completion)
|
|
265
|
+
tab.completion = completion;
|
|
266
|
+
if (seen)
|
|
267
|
+
tab.seenCompletion = seen;
|
|
268
|
+
const title = await recordTitle(record, { paneLabel: tab.paneLabel, harnessTitle: tab.title, tabLabel: tab.label, workspaceLabel: group.label, fallbackLabel: tab.label });
|
|
226
269
|
if (expired)
|
|
227
270
|
return;
|
|
228
|
-
Object.assign(tab, stall);
|
|
229
271
|
tab.title = title;
|
|
230
|
-
if (target.success) {
|
|
231
|
-
const moves = await movesRead;
|
|
232
|
-
if (expired)
|
|
233
|
-
return;
|
|
234
|
-
Object.assign(tab, moveSessionFields(moves, target.data, title));
|
|
235
|
-
}
|
|
236
|
-
// What a finished turn said last; a row still working (background work) has no last word yet.
|
|
237
272
|
const reply = tab.agentStatus === "working" ? undefined : replyExcerpt(record);
|
|
238
273
|
if (reply)
|
|
239
274
|
tab.lastReply = reply;
|
|
275
|
+
// Apply every row's small-file metadata before starting transcript reads.
|
|
276
|
+
// A stalled lookup must not hide another row's completion or pane label.
|
|
277
|
+
if (completion && record && pane)
|
|
278
|
+
recordEnrichment.push(async () => {
|
|
279
|
+
const file = await targetTranscriptPath({ server, pane: String(pane.pane_id), source: record.source, session: record.session });
|
|
280
|
+
await refreshTranscript(file, record.source, record.session);
|
|
281
|
+
const entry = await completionEntry(file, record.source, record.prompt.at, completion.at, record.stop);
|
|
282
|
+
if (!expired && entry !== undefined)
|
|
283
|
+
completion.entry = entry;
|
|
284
|
+
});
|
|
285
|
+
recordEnrichment.push(async () => {
|
|
286
|
+
const evidence = pane && typeof session === "string" ? await effectivePaneEvidence(server, pane, session, agentHooks, undefined, record) : undefined;
|
|
287
|
+
const background = evidence ? liveWork(record, evidence.final, evidence.runningChildren) : undefined;
|
|
288
|
+
if (expired)
|
|
289
|
+
return;
|
|
290
|
+
if (evidence) {
|
|
291
|
+
Object.assign(tab, evidence.children);
|
|
292
|
+
const resolved = resolveEffectiveStatus(evidence);
|
|
293
|
+
if (background && ["idle", "done"].includes(String(tab.agentStatus)))
|
|
294
|
+
tab.backgroundTasks = background;
|
|
295
|
+
if (resolved)
|
|
296
|
+
tab.agentStatus = resolved;
|
|
297
|
+
}
|
|
298
|
+
markBackground(tab, background);
|
|
299
|
+
if (tab.agentStatus === "working")
|
|
300
|
+
delete tab.lastReply;
|
|
301
|
+
const target = targetSchema.safeParse(tab.target);
|
|
302
|
+
const stall = target.success && agents.length === 1
|
|
303
|
+
? await sessionStalls.observe(target.data, { ...agents[0], agent_status: tab.agentStatus }, async () => background) : {};
|
|
304
|
+
if (expired)
|
|
305
|
+
return;
|
|
306
|
+
Object.assign(tab, stall);
|
|
307
|
+
if (target.success) {
|
|
308
|
+
const moves = await movesRead;
|
|
309
|
+
if (expired)
|
|
310
|
+
return;
|
|
311
|
+
Object.assign(tab, moveSessionFields(moves, target.data, title));
|
|
312
|
+
}
|
|
313
|
+
});
|
|
240
314
|
}));
|
|
241
315
|
// Separate bounded queues: a stalled git/model/step read cannot prevent
|
|
242
316
|
// the child tree from reaching the phone. Apply each answer as it arrives.
|
|
@@ -249,13 +323,16 @@ export function workspacesReader(ctx) {
|
|
|
249
323
|
};
|
|
250
324
|
const identified = (group, tab) => {
|
|
251
325
|
const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
return typeof session === "string" ? { source: agents[0].agent, session, pane: agents[0] } : undefined;
|
|
326
|
+
const session = agents.length === 1 ? chatStates.get(agents[0])?.sessionId : undefined;
|
|
327
|
+
return agents.length === 1 && provider.safeParse(agents[0].agent).success && typeof session === "string"
|
|
328
|
+
? { source: agents[0].agent, session, pane: agents[0] } : undefined;
|
|
256
329
|
};
|
|
257
330
|
const enrich = Promise.all([
|
|
258
|
-
records
|
|
331
|
+
records.then(() => {
|
|
332
|
+
if (expired)
|
|
333
|
+
return;
|
|
334
|
+
return Promise.all(recordEnrichment.map(read => read().catch(() => { })));
|
|
335
|
+
}),
|
|
259
336
|
eachTab(async ({ tab }) => {
|
|
260
337
|
if (!modules.has("git") || typeof tab.cwd !== "string" || !tab.agent)
|
|
261
338
|
return;
|
|
@@ -263,6 +340,9 @@ export function workspacesReader(ctx) {
|
|
|
263
340
|
if (!expired && branch !== undefined)
|
|
264
341
|
tab.branch = branch;
|
|
265
342
|
}),
|
|
343
|
+
// Child decoration must not wait for record I/O, final-turn reads or
|
|
344
|
+
// dialogs. Share the resolver's cached trees, but publish ready counts
|
|
345
|
+
// independently while the overview still owns this response.
|
|
266
346
|
eachTab(async ({ group, tab }) => {
|
|
267
347
|
const identity = identified(group, tab);
|
|
268
348
|
if (!identity)
|
|
@@ -271,7 +351,9 @@ export function workspacesReader(ctx) {
|
|
|
271
351
|
if (expired)
|
|
272
352
|
return;
|
|
273
353
|
Object.assign(tab, children);
|
|
274
|
-
markBackground(tab,
|
|
354
|
+
markBackground(tab, children.runningChildren);
|
|
355
|
+
if (tab.agentStatus === "working")
|
|
356
|
+
delete tab.lastReply;
|
|
275
357
|
}),
|
|
276
358
|
eachTab(async ({ group, tab }) => {
|
|
277
359
|
const identity = identified(group, tab);
|
|
@@ -293,6 +375,16 @@ export function workspacesReader(ctx) {
|
|
|
293
375
|
await Promise.race([enrich, budget]);
|
|
294
376
|
expired = true;
|
|
295
377
|
clearTimeout(timer);
|
|
378
|
+
// The row's status may have changed above (background work turns idle into
|
|
379
|
+
// working): stamp what this reply sends, not the raw snapshot.
|
|
380
|
+
const activity = await tabActivity.recordStatus(server, tabs.map(({ group, tab }) => ({ workspace: group.id, tab: tab.id, status: tab.agentStatus })), generation);
|
|
381
|
+
for (const { group, tab } of tabs) {
|
|
382
|
+
const stamp = activity.get(tabActivityKey(group.id, tab.id));
|
|
383
|
+
if (stamp) {
|
|
384
|
+
tab.lastChangedAt = stamp.lastChangedAt;
|
|
385
|
+
tab.statusSince = stamp.statusSince;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
296
388
|
const mux = terminalMux(server);
|
|
297
389
|
// A diverged or long-unsynced store, for the computer list (health.ts storeWarning).
|
|
298
390
|
const storeWarnings = cachedStoreWarnings(defaultPhrenPath());
|
|
@@ -432,6 +524,10 @@ export function createRouteHandler(ctx) {
|
|
|
432
524
|
case "/v1/owner-inbox":
|
|
433
525
|
result = await ownerInboxView(ctx.inbox, { action: "list", includeResolved: url.searchParams.get("includeResolved") === "true" }, url.searchParams.get("local") === "1");
|
|
434
526
|
break;
|
|
527
|
+
// A terminal reference from chat text (alaarab/phren-apps#676): this computer's pane or tab, or a linked peer's.
|
|
528
|
+
case "/v1/terminals/resolve":
|
|
529
|
+
result = await resolveTerminalReference(url.searchParams.get("ref"), { computer: info.computer, from: url.searchParams.get("from") });
|
|
530
|
+
break;
|
|
435
531
|
case "/v1/conductor/integrator":
|
|
436
532
|
result = { integrator: await readIntegrator() ?? null };
|
|
437
533
|
break;
|
|
@@ -617,6 +713,9 @@ export function createRouteHandler(ctx) {
|
|
|
617
713
|
case "/v1/activity":
|
|
618
714
|
result = { events: await journal.recent() };
|
|
619
715
|
break;
|
|
716
|
+
case "/v1/conversations/search":
|
|
717
|
+
result = await conversationSearch(url.searchParams.get("q"), url.searchParams.get("limit"), url.searchParams.get("cursor"));
|
|
718
|
+
break;
|
|
620
719
|
case "/v1/web-servers":
|
|
621
720
|
result = { servers: await webServers() };
|
|
622
721
|
break;
|
|
@@ -772,6 +871,25 @@ export function createRouteHandler(ctx) {
|
|
|
772
871
|
return;
|
|
773
872
|
}
|
|
774
873
|
case "/v1/transcripts/history": {
|
|
874
|
+
// Finished conversations use the same bounded history reader, but
|
|
875
|
+
// have no live pane to validate. Only the owner's gateway may read
|
|
876
|
+
// by identity; transcriptPath validates IDs and resolves known roots.
|
|
877
|
+
if (url.searchParams.get("historical") === "1") {
|
|
878
|
+
if (!ownerRequest(request, {}))
|
|
879
|
+
throw new BridgeError(403, "Only the owner can read historical conversations.");
|
|
880
|
+
if (["server", "workspace", "tab", "pane", "child"].some(key => url.searchParams.has(key)))
|
|
881
|
+
throw new BridgeError(400, "Historical reads cannot name a live target.");
|
|
882
|
+
const source = provider.parse(url.searchParams.get("source"));
|
|
883
|
+
const session = sessionId.parse(url.searchParams.get("session"));
|
|
884
|
+
const before = z.coerce.number().int().positive().safe().parse(url.searchParams.get("beforeLine"));
|
|
885
|
+
const abort = new AbortController();
|
|
886
|
+
response.once("close", () => { if (!response.writableEnded)
|
|
887
|
+
abort.abort(); });
|
|
888
|
+
const reader = new TranscriptReader(await transcriptPath(source, session), source);
|
|
889
|
+
await refreshTranscript(reader.file, source, session);
|
|
890
|
+
result = { ...await reader.read(before, abort.signal), type: "older", source, session };
|
|
891
|
+
break;
|
|
892
|
+
}
|
|
775
893
|
const target = targetFromURL(url);
|
|
776
894
|
const before = z.coerce.number().int().positive().parse(url.searchParams.get("beforeLine"));
|
|
777
895
|
const abort = new AbortController();
|
|
@@ -870,7 +988,7 @@ export function createRouteHandler(ctx) {
|
|
|
870
988
|
}
|
|
871
989
|
}
|
|
872
990
|
else if (request.method === "POST") {
|
|
873
|
-
const data = await body(request);
|
|
991
|
+
const data = await body(request, url.pathname === "/v1/schedules/events" ? SCHEDULE_EVENT_BODY_CAP : undefined);
|
|
874
992
|
if (url.pathname.startsWith("/v1/conductor/move/"))
|
|
875
993
|
await ctx.succession.authorize(z.string().uuid().parse(data.id), requestPeer(request), url.pathname.endsWith("/prepare") ? z.string().uuid().parse(data.originId) : undefined);
|
|
876
994
|
const executeConductor = async (action, payload, origin, remote = false) => {
|
|
@@ -1070,6 +1188,9 @@ export function createRouteHandler(ctx) {
|
|
|
1070
1188
|
else if (url.pathname === "/v1/sessions/rename") {
|
|
1071
1189
|
result = await renameSession(selectedServer(url), data);
|
|
1072
1190
|
}
|
|
1191
|
+
else if (url.pathname === "/v1/sessions/seen") {
|
|
1192
|
+
result = await markSessionSeen(data);
|
|
1193
|
+
}
|
|
1073
1194
|
else if (url.pathname === "/v1/jobs/cleanup") {
|
|
1074
1195
|
// Ends only registered worker process groups whose pane is gone.
|
|
1075
1196
|
result = { ok: true, ...await ctx.resources.cleanupJobs() };
|
|
@@ -1083,6 +1204,9 @@ export function createRouteHandler(ctx) {
|
|
|
1083
1204
|
const runs = await scheduler.launchNow(input.project, input.id, false, input.expectedUpdatedAt);
|
|
1084
1205
|
result = { ok: runs.every(run => run.status !== "failed"), run: runs[0], runs };
|
|
1085
1206
|
}
|
|
1207
|
+
else if (url.pathname === "/v1/schedules/events") {
|
|
1208
|
+
result = await scheduler.ingestEvent(data);
|
|
1209
|
+
}
|
|
1086
1210
|
else if (url.pathname === "/v1/schedules/update") {
|
|
1087
1211
|
result = await updateScheduleRoute(scheduleStore, data);
|
|
1088
1212
|
}
|
|
@@ -5,6 +5,10 @@ import { queuedQuestion, threadHealth } from "./codex-threads.js";
|
|
|
5
5
|
import { SNAPSHOT_SHARE_MS, trustedDirectory, validateTarget } from "./herdr.js";
|
|
6
6
|
import { repositoryBranch } from "./projects.js";
|
|
7
7
|
import { BridgeError, MAX_FRAME, object, targetFromURL } from "./protocol.js";
|
|
8
|
+
import { claudeInputState } from "./claude-input-state.js";
|
|
9
|
+
import { effectivePaneEvidence } from "./session-evidence.js";
|
|
10
|
+
import { resolveEffectiveStatus } from "./session-activity.js";
|
|
11
|
+
import { turnPhase } from "./turn-records.js";
|
|
8
12
|
import { TranscriptPreviewStream } from "./transcript-preview.js";
|
|
9
13
|
import { childAgent, childAgentTree, refreshTranscript, targetTranscriptPath, TranscriptReader } from "./transcripts.js";
|
|
10
14
|
import { countTick } from "./metrics.js";
|
|
@@ -46,7 +50,10 @@ export function transcriptStreams(ctx) {
|
|
|
46
50
|
* missing one: `reader` stays undefined until the file appears. */
|
|
47
51
|
async function conversationReader(target) {
|
|
48
52
|
try {
|
|
49
|
-
const
|
|
53
|
+
const file = await targetTranscriptPath(target);
|
|
54
|
+
// A Claude queue row crosses with the phone id the Hook bound to it, so a
|
|
55
|
+
// sent message and its queued transcript copy join by identity, not text.
|
|
56
|
+
const reader = new TranscriptReader(file, target.source, undefined, modules.has("git") ? agentHooks.changes.view(`${target.source}:${target.session}`) : undefined, false, undefined, target.source === "claude" ? () => agentHooks.deliveries.claudeQueueBindings(target, file) : undefined);
|
|
50
57
|
return { reader, source: target.source, session: target.session };
|
|
51
58
|
}
|
|
52
59
|
catch (error) {
|
|
@@ -95,8 +102,12 @@ export function transcriptStreams(ctx) {
|
|
|
95
102
|
// pushed as it changes to a stream opened with `deliveries=1`.
|
|
96
103
|
const deliveryFrames = url.pathname === "/v1/transcripts" && child === null && url.searchParams.get("deliveries") === "1";
|
|
97
104
|
const sentDelivery = new Map();
|
|
105
|
+
// Prompt identities this stream already delivered. A later duplicate makes
|
|
106
|
+
// one or more of them ambiguous, which needs a replacement backlog so the
|
|
107
|
+
// client cannot keep matching its checkpoint.
|
|
108
|
+
const sentPromptIds = new Set();
|
|
98
109
|
// The first frame stays a backlog for protocol compatibility, but a
|
|
99
|
-
// reconnect
|
|
110
|
+
// reconnect normally reads rows beyond the phone's retained raw-line cursor.
|
|
100
111
|
let resumeAfterLine = cursor === null ? undefined : z.coerce.number().int().nonnegative().max(4_294_967_295).parse(cursor);
|
|
101
112
|
let conversation = { source: target.source, session: target.session };
|
|
102
113
|
// The transcript file of a fresh conversation appears with its first
|
|
@@ -119,6 +130,12 @@ export function transcriptStreams(ctx) {
|
|
|
119
130
|
try {
|
|
120
131
|
if (first || pending.length === 0) {
|
|
121
132
|
const pane = first ? initialPane : await validateTarget(target, false, false, SNAPSHOT_SHARE_MS);
|
|
133
|
+
// One resolved status for every surface on this tick. A notification
|
|
134
|
+
// or a stale idle snapshot cannot end an unanswered foreground turn.
|
|
135
|
+
if (child === null)
|
|
136
|
+
void agentHooks.reconcileSubmissions?.(target);
|
|
137
|
+
const evidence = child === null ? await effectivePaneEvidence(target.server, pane, conversation.session, agentHooks, codexQuestions) : { paneStatus: pane.agent_status, record: undefined };
|
|
138
|
+
const resolvedStatus = resolveEffectiveStatus(evidence);
|
|
122
139
|
if (awaitingTranscript)
|
|
123
140
|
await findTranscript();
|
|
124
141
|
if (awaitingTranscript) {
|
|
@@ -127,23 +144,50 @@ export function transcriptStreams(ctx) {
|
|
|
127
144
|
}
|
|
128
145
|
else if (reader) {
|
|
129
146
|
await refreshTranscript(reader.file, conversation.source, conversation.session);
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
// Seed only ephemeral turn state from the bounded recent tail.
|
|
133
|
-
previews.observe((await new TranscriptReader(reader.file, conversation.source).read(undefined, abort.signal)).entries);
|
|
134
|
-
}
|
|
135
|
-
const page = resumeAfterLine === undefined
|
|
147
|
+
const resumingClaude = first && conversation.source === "claude" && resumeAfterLine !== undefined;
|
|
148
|
+
let page = resumeAfterLine === undefined
|
|
136
149
|
? await reader.read(undefined, abort.signal)
|
|
137
150
|
: await reader.readAfter(resumeAfterLine, abort.signal);
|
|
138
151
|
resumeAfterLine = undefined;
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
152
|
+
const ambiguous = reader.ambiguousPromptIds;
|
|
153
|
+
if (!page.reset && ambiguous.size && (resumingClaude || [...sentPromptIds].some(id => ambiguous.has(id)))) {
|
|
154
|
+
// A reconnect cannot know which identities the phone retains:
|
|
155
|
+
// the fresh tail already omits any that became ambiguous offline.
|
|
156
|
+
// Replace its backlog on any ambiguity, or when a live append
|
|
157
|
+
// invalidates an identity this stream delivered.
|
|
158
|
+
page = await reader.snapshot(abort.signal);
|
|
159
|
+
sentPromptIds.clear();
|
|
160
|
+
}
|
|
161
|
+
if (child === null) {
|
|
162
|
+
if (page.reset)
|
|
163
|
+
previews.observe([], true);
|
|
164
|
+
if ((first || page.reset) && target.source === "claude") {
|
|
165
|
+
const recovered = await claudeInputState(reader.file).catch(() => undefined);
|
|
166
|
+
if (recovered?.owner) {
|
|
167
|
+
previews.seedTurn(recovered.owner.at, recovered.owner.text);
|
|
168
|
+
previews.observe(recovered.recovery);
|
|
169
|
+
}
|
|
170
|
+
// Cursor reconnects also need landed/final evidence omitted by
|
|
171
|
+
// the cursor. This reader uses the same normalization path.
|
|
172
|
+
if (cursor !== null)
|
|
173
|
+
previews.observe((await new TranscriptReader(reader.file, conversation.source).read(undefined, abort.signal)).entries);
|
|
174
|
+
}
|
|
175
|
+
previews.observe(page.entries);
|
|
176
|
+
}
|
|
177
|
+
const preview = child === null
|
|
178
|
+
? await previews.update(resolvedStatus, reader.file, undefined, { ended: evidence.record ? turnPhase(evidence.record).phase === "ended" : false })
|
|
179
|
+
: undefined;
|
|
142
180
|
// `activityVerb` stays for phones that predate `activity`.
|
|
143
181
|
const activity = previews.activity ? { activityVerb: previews.activity.verb, activity: { ...previews.activity } }
|
|
144
182
|
: previews.verb ? { activityVerb: previews.verb } : {};
|
|
145
|
-
if (first || page.entries.length || page.reset)
|
|
183
|
+
if (first || page.entries.length || page.reset) {
|
|
184
|
+
if (page.reset)
|
|
185
|
+
sentPromptIds.clear();
|
|
186
|
+
for (const entry of page.entries)
|
|
187
|
+
if (entry.promptEntryId)
|
|
188
|
+
sentPromptIds.add(entry.promptEntryId);
|
|
146
189
|
send(client, { ...page, ...preview, ...activity, type: first || page.reset ? "backlog" : "append", ...conversation });
|
|
190
|
+
}
|
|
147
191
|
else if (preview)
|
|
148
192
|
send(client, { type: "preview", ...conversation, ...preview, ...activity });
|
|
149
193
|
}
|
|
@@ -152,7 +196,7 @@ export function transcriptStreams(ctx) {
|
|
|
152
196
|
const pendingQuestions = target.source === "codex" ? await codexQuestions.pending(target).catch(() => undefined) : undefined;
|
|
153
197
|
const cwd = await trustedDirectory(pane).catch(() => undefined);
|
|
154
198
|
const branch = modules.has("git") && cwd ? await repositoryBranch(cwd) : undefined;
|
|
155
|
-
const waiting = !pendingApproval && ["blocked", "waiting"].includes(String(
|
|
199
|
+
const waiting = !pendingApproval && ["blocked", "waiting"].includes(String(resolvedStatus));
|
|
156
200
|
// Claude Code's auto-mode fallback, opencode and Codex draw a
|
|
157
201
|
// numbered dialog in the pane with no PermissionRequest hook
|
|
158
202
|
// behind it: read the pane (at most once per three seconds) and
|
|
@@ -186,13 +230,13 @@ export function transcriptStreams(ctx) {
|
|
|
186
230
|
// Claude's suggested next prompt, only between turns. The footer
|
|
187
231
|
// read can be a throttle old, so one from before a turn this
|
|
188
232
|
// stream saw start is stale: the turn cleared it.
|
|
189
|
-
const between = ["idle", "done"].includes(String(
|
|
233
|
+
const between = ["idle", "done"].includes(String(resolvedStatus)) && !pendingApproval && !servedQuestion;
|
|
190
234
|
if (!between)
|
|
191
235
|
busyAt = Date.now();
|
|
192
236
|
const nextPrompt = between && suggestion && suggestion.readAt > busyAt ? suggestion.text : undefined;
|
|
193
237
|
const historyHealth = target.source === "codex" ? await threadHealth(target.session, pane.agent_status) : { stalled: false };
|
|
194
238
|
send(client, { agentStatus: { source: target.source, session: target.session,
|
|
195
|
-
status: pendingApproval || servedQuestion ? "waiting" :
|
|
239
|
+
status: pendingApproval || servedQuestion ? "waiting" : resolvedStatus, pendingApproval, pendingQuestions, terminalPrompt,
|
|
196
240
|
...(waiting && agentHooks.passwordPrompt(target) ? { passwordPrompt: true } : {}),
|
|
197
241
|
compacting: agentHooks.compacting(target),
|
|
198
242
|
...(nextPrompt ? { suggestion: nextPrompt } : {}),
|
|
@@ -236,8 +280,15 @@ export function transcriptStreams(ctx) {
|
|
|
236
280
|
const before = pending.shift();
|
|
237
281
|
await validateTarget(target, false, false, SNAPSHOT_SHARE_MS);
|
|
238
282
|
const page = await reader.read(before, abort.signal);
|
|
283
|
+
for (const entry of page.entries)
|
|
284
|
+
if (entry.promptEntryId)
|
|
285
|
+
sentPromptIds.add(entry.promptEntryId);
|
|
239
286
|
send(client, { ...page, type: "older", ...conversation });
|
|
240
287
|
}
|
|
288
|
+
// A transcript the agent has not written yet has no older pages; a
|
|
289
|
+
// queued request must not keep rescheduling the tick.
|
|
290
|
+
if (!reader)
|
|
291
|
+
pending.length = 0;
|
|
241
292
|
}
|
|
242
293
|
catch (error) {
|
|
243
294
|
const reason = streamCloseReason(error);
|