@phren/cli 0.3.11 → 0.3.13
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/account-usage.d.ts +124 -0
- package/dist/bridge/account-usage.js +258 -0
- 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 +162 -5
- package/dist/bridge/agent-hooks.js +682 -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-hook-trust.d.ts +27 -0
- package/dist/bridge/codex-hook-trust.js +237 -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 +97 -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 +82 -12
- package/dist/bridge/dispatch-returns.d.ts +128 -19
- package/dist/bridge/dispatch-returns.js +371 -54
- package/dist/bridge/dispatch.d.ts +128 -3
- package/dist/bridge/dispatch.js +303 -42
- 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-queue.d.ts +74 -0
- package/dist/bridge/hand-off-queue.js +235 -0
- package/dist/bridge/hand-off.d.ts +30 -10
- package/dist/bridge/hand-off.js +79 -46
- 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 +102 -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/pane-status.d.ts +12 -0
- package/dist/bridge/pane-status.js +50 -1
- 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 +11 -4
- package/dist/bridge/push.js +27 -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 +27 -53
- package/dist/bridge/schedule-watch.d.ts +24 -1
- package/dist/bridge/schedule-watch.js +89 -2
- package/dist/bridge/server-launch.d.ts +22 -5
- package/dist/bridge/server-launch.js +238 -32
- package/dist/bridge/server-overview.d.ts +10 -3
- package/dist/bridge/server-overview.js +32 -15
- package/dist/bridge/server-pane-routes.d.ts +3 -0
- package/dist/bridge/server-pane-routes.js +150 -18
- package/dist/bridge/server-routes.d.ts +11 -0
- package/dist/bridge/server-routes.js +214 -36
- 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 +58 -13
- package/dist/bridge/session-activity.d.ts +93 -0
- package/dist/bridge/session-activity.js +139 -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/stalls.d.ts +22 -0
- package/dist/bridge/stalls.js +57 -0
- package/dist/bridge/sudo.d.ts +209 -0
- package/dist/bridge/sudo.js +501 -0
- package/dist/bridge/terminal-herdr.js +9 -3
- package/dist/bridge/terminal-tmux.d.ts +15 -3
- package/dist/bridge/terminal-tmux.js +103 -13
- package/dist/bridge/terminal.d.ts +27 -4
- package/dist/bridge/terminal.js +8 -1
- package/dist/bridge/transcript-claude.d.ts +4 -0
- package/dist/bridge/transcript-claude.js +186 -16
- 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 +56 -10
- package/dist/bridge/usage.js +190 -45
- package/dist/bridge-hook.mjs +27975 -20636
- 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 +31 -6
- 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 +17 -16
- 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 +52 -4
- package/dist/tools/tasks.js +10 -1
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +87 -4
- package/starter/global/AGENTS.md +4 -0
- package/starter/global/skills/conductor/SKILL.md +51 -4
package/dist/bridge/server.js
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { handOff } from "./hand-off.js";
|
|
2
|
+
import { sessionStalls } from "./stalls.js";
|
|
3
|
+
import { HandOffQueue } from "./hand-off-queue.js";
|
|
4
|
+
import { paneRouteOnce } from "./server-pane-routes.js";
|
|
1
5
|
import { FanoutMessages } from "./fanout-messages.js";
|
|
2
6
|
import { activateModules as moduleSnapshot } from "../modules/runtime.js";
|
|
3
7
|
import { disabledHint } from "../modules/registry.js";
|
|
@@ -17,7 +21,7 @@ import { startChangeRetention } from "./changes.js";
|
|
|
17
21
|
import { CodeReindexer, CodeRoutes } from "./code-routes.js";
|
|
18
22
|
import { WorkspaceContextUsage } from "./context.js";
|
|
19
23
|
import { DispatchService } from "./dispatch.js";
|
|
20
|
-
import { DispatchReturns } from "./dispatch-returns.js";
|
|
24
|
+
import { DispatchReturns, hookWorkers } from "./dispatch-returns.js";
|
|
21
25
|
import { findPane, paneChatState, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
|
|
22
26
|
import { LaunchLimiter } from "./limits.js";
|
|
23
27
|
import { locateProject } from "./locate.js";
|
|
@@ -27,6 +31,7 @@ import { TabActivityStore } from "./tab-activity.js";
|
|
|
27
31
|
import { childAgentTree } from "./transcripts.js";
|
|
28
32
|
import { ModelCatalog } from "./models.js";
|
|
29
33
|
import { ModelSwitcher } from "./model-switch.js";
|
|
34
|
+
import { SettingsSwitcher } from "./settings-switch.js";
|
|
30
35
|
import { SideQuestions } from "./side-questions.js";
|
|
31
36
|
import { AccountUsageReader } from "./usage.js";
|
|
32
37
|
import { ResourceMonitor } from "./resources.js";
|
|
@@ -34,14 +39,17 @@ import { createScheduleLauncher, Scheduler, scheduleRunsFile } from "./schedules
|
|
|
34
39
|
import { dailyCanaryDue, runCanary } from "./canary.js";
|
|
35
40
|
import { defaultPhrenPath } from "../shared.js";
|
|
36
41
|
import { capabilitiesForModules, createRouteHandler, requireRoute, selectedServer, workspacesReader } from "./server-routes.js";
|
|
42
|
+
import { typedMuxRequest } from "./mux-wire.js";
|
|
37
43
|
import { overviewStream } from "./server-overview.js";
|
|
38
44
|
import { transcriptStreams } from "./server-stream.js";
|
|
39
45
|
import { launchSession } from "./server-launch.js";
|
|
46
|
+
import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
|
|
47
|
+
import { CodexAuthKeeper, codexAuthRefreshEnabled } from "./codex-auth-refresh.js";
|
|
40
48
|
import { localNames } from "./computer-names.js";
|
|
41
49
|
export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
|
|
42
50
|
export { streamCloseReason } from "./server-stream.js";
|
|
43
51
|
export { herdrAgentName, launchSession } from "./server-launch.js";
|
|
44
|
-
export async function serve(version) {
|
|
52
|
+
export async function serve(version, options = {}) {
|
|
45
53
|
process.umask(0o077);
|
|
46
54
|
const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
|
|
47
55
|
if (!modules.has("hook"))
|
|
@@ -68,26 +76,44 @@ export async function serve(version) {
|
|
|
68
76
|
return agent.success && typeof pane?.terminal_id === "string" ? { agent: agent.data, terminal: pane.terminal_id } : undefined;
|
|
69
77
|
} })
|
|
70
78
|
: undefined;
|
|
71
|
-
// Follows what dispatched workers do and tells the dispatching agent.
|
|
72
|
-
const returns = dispatches ? new DispatchReturns() : undefined;
|
|
73
79
|
const locatedDirectories = new Set();
|
|
74
80
|
const journal = new ActivityJournal();
|
|
75
81
|
const agentHooks = new AgentHooks(undefined, modules);
|
|
82
|
+
// Follows what dispatched workers do and tells the dispatching agent.
|
|
83
|
+
const returns = dispatches ? new DispatchReturns({
|
|
84
|
+
localWorkers: hookWorkers(agentHooks),
|
|
85
|
+
localAnswer: (target, actionId, decision) => agentHooks.answer(target, actionId, decision),
|
|
86
|
+
// A worker's request the worker's own Hook did not push reaches this Hook's phone.
|
|
87
|
+
onApproval: (receipt, approval) => {
|
|
88
|
+
if (approval.pushed || !agentHooks.push.available)
|
|
89
|
+
return;
|
|
90
|
+
agentHooks.pushForwarded({ provider: receipt.harness, computer: receipt.computer, project: receipt.project,
|
|
91
|
+
request: approval.request ?? approval.title ?? approval.tool, ...(approval.requestKind ? { requestKind: approval.requestKind } : {}) }, decision => returns.answerApproval(receipt.id, decision, approval.actionId));
|
|
92
|
+
return true;
|
|
93
|
+
},
|
|
94
|
+
}) : undefined;
|
|
76
95
|
// Push is offered only once an APNs sender loaded; phones may still register.
|
|
77
96
|
if ("approvalPush" in activeCapabilities) {
|
|
78
97
|
Object.defineProperty(activeCapabilities, "approvalPush", { enumerable: true, get: () => approvalPushCapability(agentHooks.push.status) });
|
|
79
98
|
}
|
|
80
|
-
const modelCatalog = new ModelCatalog();
|
|
99
|
+
const modelCatalog = options.modelCatalog ?? new ModelCatalog();
|
|
81
100
|
const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
|
|
101
|
+
const settingsSwitcher = new SettingsSwitcher(agentHooks);
|
|
82
102
|
const sideQuestions = new SideQuestions();
|
|
103
|
+
const handOffs = dispatches ? new HandOffQueue({
|
|
104
|
+
validate: target => validateTarget(target, false, true),
|
|
105
|
+
notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false }),
|
|
106
|
+
send: async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing),
|
|
107
|
+
}) : undefined;
|
|
83
108
|
const contextUsage = new WorkspaceContextUsage();
|
|
84
|
-
const accountUsage = new AccountUsageReader();
|
|
109
|
+
const accountUsage = options.accountUsage ?? new AccountUsageReader();
|
|
85
110
|
const resources = new ResourceMonitor();
|
|
86
111
|
const tabActivity = new TabActivityStore();
|
|
87
|
-
const codexQuestions = new CodexQuestions();
|
|
112
|
+
const codexQuestions = new CodexQuestions(undefined, codexServers);
|
|
88
113
|
const scheduleStore = defaultPhrenPath();
|
|
89
114
|
const scheduler = modules.has("schedules") ? new Scheduler({ now: () => new Date(), store: scheduleStore, runsFile: scheduleRunsFile(),
|
|
90
|
-
|
|
115
|
+
// A schedule starts in its project's folder, which the Hook resolved itself.
|
|
116
|
+
launch: createScheduleLauncher((server, data) => launchSession(server, data, { trustFolder: true }), scheduleStore),
|
|
91
117
|
push: { notify: value => agentHooks.push.notifySchedule(value) },
|
|
92
118
|
locateProject: async (project) => (await locateProject(project, await journal.recent()))[0]?.directory }) : undefined;
|
|
93
119
|
const fanoutMessages = new FanoutMessages({ ...process.env, PHREN_PATH: scheduleStore }, {
|
|
@@ -134,7 +160,7 @@ export async function serve(version) {
|
|
|
134
160
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => { };
|
|
135
161
|
if (modules.has("git"))
|
|
136
162
|
await rm(path.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
137
|
-
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
|
|
163
|
+
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
|
|
138
164
|
const { stream } = streams;
|
|
139
165
|
// The phone's overview, pushed over a WebSocket when it changes.
|
|
140
166
|
const overview = overviewStream({
|
|
@@ -142,10 +168,11 @@ export async function serve(version) {
|
|
|
142
168
|
info: () => ({ ...info, capabilities: info.capabilities }),
|
|
143
169
|
renew: server => agentHooks.overview.renew(server),
|
|
144
170
|
resources: () => resources.read(),
|
|
171
|
+
sudo: agentHooks.sudo,
|
|
145
172
|
});
|
|
146
173
|
const http = createServer(createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
|
|
147
|
-
journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
|
|
148
|
-
fanoutMessages, canary, streams, returns }));
|
|
174
|
+
journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
|
|
175
|
+
fanoutMessages, canary, streams, returns, handOffs }));
|
|
149
176
|
http.requestTimeout = 20_000;
|
|
150
177
|
http.headersTimeout = 10_000;
|
|
151
178
|
http.maxHeadersCount = 32;
|
|
@@ -168,7 +195,7 @@ export async function serve(version) {
|
|
|
168
195
|
ws.clients.delete(oldest);
|
|
169
196
|
}
|
|
170
197
|
if (overviewServer !== undefined) {
|
|
171
|
-
overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1", url.searchParams.get("resources") === "1");
|
|
198
|
+
overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1", url.searchParams.get("resources") === "1", typedMuxRequest(url), url.searchParams.get("sudo") === "1");
|
|
172
199
|
return;
|
|
173
200
|
}
|
|
174
201
|
if (url.pathname === "/v1/speech/transcribe") {
|
|
@@ -185,13 +212,25 @@ export async function serve(version) {
|
|
|
185
212
|
await new Promise((resolve, reject) => { http.once("error", reject); http.listen(socketPath(), () => resolve()); });
|
|
186
213
|
await chmod(socketPath(), 0o600);
|
|
187
214
|
await agentHooks.start();
|
|
215
|
+
// Codex panes on the Hook's own app-servers: their requests become
|
|
216
|
+
// approval cards, and servers a previous Hook started are rejoined.
|
|
217
|
+
codexServers.setSink({ request: (target, request, answer) => agentHooks.codexRequest(target, request, answer),
|
|
218
|
+
resolved: (target, requestId) => agentHooks.codexResolved(target, requestId) });
|
|
219
|
+
await codexServers.adopt().catch(() => { });
|
|
188
220
|
void scheduler?.tick().catch(() => { });
|
|
189
221
|
const scheduleTimer = scheduler ? setInterval(() => { countTick("schedules"); void scheduler.tick().catch(() => { }); }, 30_000) : undefined;
|
|
190
222
|
// Off unless PHREN_CANARY_DAILY=1 or `phren canary --daily on`.
|
|
223
|
+
// Refresh the shared Codex sign-in before its workers each try to at once.
|
|
224
|
+
const codexAuth = codexAppServerEnabled() && codexAuthRefreshEnabled() ? new CodexAuthKeeper(codexServers) : undefined;
|
|
225
|
+
const codexAuthTimer = codexAuth ? setInterval(() => { void codexAuth.tick().catch(() => { }); }, 60 * 60_000) : undefined;
|
|
226
|
+
if (codexAuth)
|
|
227
|
+
setTimeout(() => { void codexAuth.tick().catch(() => { }); }, 60_000).unref();
|
|
191
228
|
const canaryTimer = setInterval(() => { countTick("canary"); void dailyCanaryDue().then(due => due ? canary("daily") : undefined).catch(() => { }); }, 10 * 60_000);
|
|
192
229
|
let recording = false;
|
|
193
230
|
const activityTimer = setInterval(() => {
|
|
194
231
|
countTick("activity");
|
|
232
|
+
// Served OpenCode panes: follow new ones, drop those whose process is gone.
|
|
233
|
+
agentHooks.paneServers.tick();
|
|
195
234
|
if (recording)
|
|
196
235
|
return;
|
|
197
236
|
recording = true;
|
|
@@ -207,23 +246,29 @@ export async function serve(version) {
|
|
|
207
246
|
const name = String(server.session), current = await sharedSnapshot(name, 4000);
|
|
208
247
|
await tabActivity.observe(name, current);
|
|
209
248
|
await journal.record(name, objects(current.panes));
|
|
249
|
+
// A Codex app-server whose pane closed is stopped; a dead one forgotten.
|
|
250
|
+
await codexServers.reap(name, current).catch(() => { });
|
|
210
251
|
// Approvals drawn in a terminal reach a phone with phren closed.
|
|
211
252
|
await agentHooks.observeWaitingPanes(name, objects(current.panes), async (pane) => {
|
|
212
253
|
const state = await paneChatState(name, pane, { tokenWhenIdentified: false });
|
|
213
254
|
const parsed = targetSchema.safeParse({ server: name, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id,
|
|
214
255
|
source: pane.agent, session: state.sessionId });
|
|
256
|
+
if (parsed.success)
|
|
257
|
+
await sessionStalls.observe(parsed.data, pane);
|
|
215
258
|
return parsed.success ? parsed.data : undefined;
|
|
216
259
|
});
|
|
217
260
|
}
|
|
218
261
|
catch { /* A disconnected computer keeps its previous local activity. */ }
|
|
219
262
|
}
|
|
263
|
+
await codexServers.sweep(live.map(server => String(server.session))).catch(() => { });
|
|
220
264
|
// Dispatch returns ride this tick and its shared snapshots. The returns
|
|
221
265
|
// loop throttles its own peer polls and never holds up activity.
|
|
266
|
+
void handOffs?.tick().catch(() => { });
|
|
222
267
|
void returns?.tick();
|
|
223
268
|
})().finally(() => { recording = false; }).catch(() => { });
|
|
224
269
|
}, 5000);
|
|
225
270
|
await new Promise(resolve => {
|
|
226
|
-
const stop = () => { fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
|
|
271
|
+
const stop = () => { fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
|
|
227
272
|
process.once("SIGTERM", stop);
|
|
228
273
|
process.once("SIGINT", stop);
|
|
229
274
|
});
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { type Json } from "./protocol.js";
|
|
2
|
+
import type { FinalTurn } from "./schedule-watch.js";
|
|
3
|
+
import { type TurnRecord } from "./turn-records.js";
|
|
4
|
+
/**
|
|
5
|
+
* What a live session's row says about itself beyond Herdr's own status and
|
|
6
|
+
* title, from the pane's turn record (turn-records.ts) and the dispatch label
|
|
7
|
+
* (launch-brief.ts):
|
|
8
|
+
*
|
|
9
|
+
* - A session whose turn ended while work it started still runs is still
|
|
10
|
+
* working: running sub-agents, teammates, workflow agents and fan-out jobs
|
|
11
|
+
* (its child tree, Claude and Codex alike), and for Claude the background
|
|
12
|
+
* shells and monitors started since the owner's last prompt that are not
|
|
13
|
+
* endless streams (`FinalTurn.awaited`, bounded by its Stop's count less the
|
|
14
|
+
* tasks finished since, for at most BACKGROUND_STALE_MS). A log tail, a
|
|
15
|
+
* watcher or a shell left over from an earlier exchange runs on without
|
|
16
|
+
* anyone waiting for it, so it does not count. Herdr reports such a session
|
|
17
|
+
* idle, so the phone listed it under IDLE with a moon badge. The tab keeps
|
|
18
|
+
* `agentStatus: "working"` and gains `backgroundTasks`, the count.
|
|
19
|
+
* - A dispatched worker is named by its dispatch label. Claude and Codex title
|
|
20
|
+
* a session after its first prompt, which for a brief launch is
|
|
21
|
+
* "Read and follow the brief in <path>" (or "Brief d35c6189" once they
|
|
22
|
+
* shorten it), so those titles are never shown.
|
|
23
|
+
*/
|
|
24
|
+
/** The record, only when it belongs to this pane's terminal and conversation
|
|
25
|
+
* (the guard dispatch returns use): a leftover record of an earlier terminal
|
|
26
|
+
* or session in the same pane must not speak for this one. */
|
|
27
|
+
export declare function ownRecord(record: TurnRecord | undefined, pane: Json, source: unknown, session: string | undefined): TurnRecord | undefined;
|
|
28
|
+
/** The pane's own turn record. OpenCode has no Stop hook to report background work or a dispatch id here. */
|
|
29
|
+
export declare function paneRecord(server: string, pane: Json, session: string | undefined): Promise<TurnRecord | undefined>;
|
|
30
|
+
/** How long after its Stop a background count may keep a row working. A task
|
|
31
|
+
* whose finish the transcript never shows (a dev server left running, a
|
|
32
|
+
* persistent monitor, a notification the tail no longer holds) would
|
|
33
|
+
* otherwise keep it working forever. Matches dispatch returns' wait. */
|
|
34
|
+
export declare const BACKGROUND_STALE_MS: number;
|
|
35
|
+
/** Background tasks the recorded turn ended with that are still running:
|
|
36
|
+
* the Stop's count less those `finishedTasks` (FinalTurn's) says finished
|
|
37
|
+
* after it. Undefined once none are left or the Stop is BACKGROUND_STALE_MS old. */
|
|
38
|
+
export declare function recordedBackground(record: TurnRecord | undefined, finishedTasks?: readonly string[], now?: number): number | undefined;
|
|
39
|
+
/** The background shells and monitors a pane's ended Claude turn is waiting
|
|
40
|
+
* on (`FinalTurn.awaited`), at most `recordedBackground`. Reads the transcript
|
|
41
|
+
* (`readFinalTurn`, passed in: schedule-watch imports herdr, which imports
|
|
42
|
+
* this) only when the Stop left background work; only Claude's Stop reports
|
|
43
|
+
* a count. Sub-agents are not in it: the overview adds its running children.
|
|
44
|
+
* An unreadable transcript counts nothing, since the Stop's count alone
|
|
45
|
+
* cannot tell a build from a log tail. */
|
|
46
|
+
export declare function liveBackground(record: TurnRecord | undefined, readFinal: (source: "claude", session: string) => Promise<FinalTurn | undefined>, now?: number): Promise<number | undefined>;
|
|
47
|
+
/**
|
|
48
|
+
* Marks a tab whose main turn ended but whose background work continues:
|
|
49
|
+
* an idle or done tab becomes `working` with `backgroundTasks: count`. Called
|
|
50
|
+
* again with a fuller count (the awaited shells plus the running children,
|
|
51
|
+
* once the child tree is read), it keeps the larger. A tab that is working,
|
|
52
|
+
* blocked or waiting on its own is left alone, so `backgroundTasks` never
|
|
53
|
+
* sits on a tab with a live turn.
|
|
54
|
+
*/
|
|
55
|
+
export declare function markBackground(tab: Json, count: number | undefined): void;
|
|
56
|
+
/** A tab or workspace label worth showing as a name: not empty, not Herdr's bare numbering, not an id. */
|
|
57
|
+
export declare function meaningfulLabel(value: unknown): string | undefined;
|
|
58
|
+
/** A terminal title without the spinner or status glyphs around it, nor the
|
|
59
|
+
* separator they leave dangling (Codex's "⠸ | phren" before its thread has a
|
|
60
|
+
* title); undefined when nothing else is left. */
|
|
61
|
+
export declare function plainTitle(value: unknown): string | undefined;
|
|
62
|
+
/** A harness title made from the brief launch's first prompt rather than the work: the prompt itself, the brief path, or "Brief <id>". */
|
|
63
|
+
export declare function isBriefTitle(title: string): boolean;
|
|
64
|
+
/**
|
|
65
|
+
* The name a session is shown under, first that applies:
|
|
66
|
+
* 1. the agent pane's own label, when meaningful (a rename from the phone or
|
|
67
|
+
* from Herdr or tmux itself; a pane has none until someone sets one);
|
|
68
|
+
* 2. the dispatch label its dispatcher gave it;
|
|
69
|
+
* 3. for a dispatch with no stored label (sent before labels were kept), the
|
|
70
|
+
* tab label, else the workspace label, when meaningful;
|
|
71
|
+
* 4. the harness's own title, unless it is brief boilerplate, which is
|
|
72
|
+
* replaced by a meaningful tab or workspace label or dropped (the phone
|
|
73
|
+
* then falls back to the label).
|
|
74
|
+
* Never leaves a row blank: when none applies and `fallbackLabel` (passed, even
|
|
75
|
+
* if undefined) is the label the phone shows without a title and is blank, the raw harness title stands.
|
|
76
|
+
*/
|
|
77
|
+
export declare function sessionTitle(input: {
|
|
78
|
+
dispatched: boolean;
|
|
79
|
+
paneLabel?: unknown;
|
|
80
|
+
dispatchLabel?: string;
|
|
81
|
+
harnessTitle?: unknown;
|
|
82
|
+
tabLabel?: unknown;
|
|
83
|
+
workspaceLabel?: unknown;
|
|
84
|
+
fallbackLabel?: unknown;
|
|
85
|
+
}): string | undefined;
|
|
86
|
+
/** `sessionTitle` for a pane, given its own turn record (the guarded one from `paneRecord`). */
|
|
87
|
+
export declare function recordTitle(record: TurnRecord | undefined, input: {
|
|
88
|
+
paneLabel?: unknown;
|
|
89
|
+
harnessTitle?: unknown;
|
|
90
|
+
tabLabel?: unknown;
|
|
91
|
+
workspaceLabel?: unknown;
|
|
92
|
+
fallbackLabel?: unknown;
|
|
93
|
+
}): Promise<string | undefined>;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { briefLabel } from "./launch-brief.js";
|
|
2
|
+
import { provider } from "./protocol.js";
|
|
3
|
+
import { backgroundLeft, readTurn, turnPhase } from "./turn-records.js";
|
|
4
|
+
/**
|
|
5
|
+
* What a live session's row says about itself beyond Herdr's own status and
|
|
6
|
+
* title, from the pane's turn record (turn-records.ts) and the dispatch label
|
|
7
|
+
* (launch-brief.ts):
|
|
8
|
+
*
|
|
9
|
+
* - A session whose turn ended while work it started still runs is still
|
|
10
|
+
* working: running sub-agents, teammates, workflow agents and fan-out jobs
|
|
11
|
+
* (its child tree, Claude and Codex alike), and for Claude the background
|
|
12
|
+
* shells and monitors started since the owner's last prompt that are not
|
|
13
|
+
* endless streams (`FinalTurn.awaited`, bounded by its Stop's count less the
|
|
14
|
+
* tasks finished since, for at most BACKGROUND_STALE_MS). A log tail, a
|
|
15
|
+
* watcher or a shell left over from an earlier exchange runs on without
|
|
16
|
+
* anyone waiting for it, so it does not count. Herdr reports such a session
|
|
17
|
+
* idle, so the phone listed it under IDLE with a moon badge. The tab keeps
|
|
18
|
+
* `agentStatus: "working"` and gains `backgroundTasks`, the count.
|
|
19
|
+
* - A dispatched worker is named by its dispatch label. Claude and Codex title
|
|
20
|
+
* a session after its first prompt, which for a brief launch is
|
|
21
|
+
* "Read and follow the brief in <path>" (or "Brief d35c6189" once they
|
|
22
|
+
* shorten it), so those titles are never shown.
|
|
23
|
+
*/
|
|
24
|
+
/** The record, only when it belongs to this pane's terminal and conversation
|
|
25
|
+
* (the guard dispatch returns use): a leftover record of an earlier terminal
|
|
26
|
+
* or session in the same pane must not speak for this one. */
|
|
27
|
+
export function ownRecord(record, pane, source, session) {
|
|
28
|
+
return record && session && record.terminal === pane.terminal_id && record.source === source && record.session === session ? record : undefined;
|
|
29
|
+
}
|
|
30
|
+
/** The pane's own turn record. OpenCode has no Stop hook to report background work or a dispatch id here. */
|
|
31
|
+
export async function paneRecord(server, pane, session) {
|
|
32
|
+
if (!session || pane.agent === "opencode" || !provider.safeParse(pane.agent).success)
|
|
33
|
+
return undefined;
|
|
34
|
+
return ownRecord(await readTurn(server, String(pane.pane_id)).catch(() => undefined), pane, pane.agent, session);
|
|
35
|
+
}
|
|
36
|
+
/** How long after its Stop a background count may keep a row working. A task
|
|
37
|
+
* whose finish the transcript never shows (a dev server left running, a
|
|
38
|
+
* persistent monitor, a notification the tail no longer holds) would
|
|
39
|
+
* otherwise keep it working forever. Matches dispatch returns' wait. */
|
|
40
|
+
export const BACKGROUND_STALE_MS = 2 * 60 * 60 * 1000;
|
|
41
|
+
/** Background tasks the recorded turn ended with that are still running:
|
|
42
|
+
* the Stop's count less those `finishedTasks` (FinalTurn's) says finished
|
|
43
|
+
* after it. Undefined once none are left or the Stop is BACKGROUND_STALE_MS old. */
|
|
44
|
+
export function recordedBackground(record, finishedTasks, now = Date.now()) {
|
|
45
|
+
if (!record)
|
|
46
|
+
return undefined;
|
|
47
|
+
const phase = turnPhase(record);
|
|
48
|
+
if (phase.phase !== "ended" || !(now - Date.parse(phase.at) < BACKGROUND_STALE_MS))
|
|
49
|
+
return undefined;
|
|
50
|
+
return backgroundLeft(phase.background, phase.at, finishedTasks) || undefined;
|
|
51
|
+
}
|
|
52
|
+
/** The background shells and monitors a pane's ended Claude turn is waiting
|
|
53
|
+
* on (`FinalTurn.awaited`), at most `recordedBackground`. Reads the transcript
|
|
54
|
+
* (`readFinalTurn`, passed in: schedule-watch imports herdr, which imports
|
|
55
|
+
* this) only when the Stop left background work; only Claude's Stop reports
|
|
56
|
+
* a count. Sub-agents are not in it: the overview adds its running children.
|
|
57
|
+
* An unreadable transcript counts nothing, since the Stop's count alone
|
|
58
|
+
* cannot tell a build from a log tail. */
|
|
59
|
+
export async function liveBackground(record, readFinal, now = Date.now()) {
|
|
60
|
+
if (!record || record.source !== "claude" || !recordedBackground(record, [], now))
|
|
61
|
+
return undefined;
|
|
62
|
+
const final = await readFinal("claude", record.session).catch(() => undefined);
|
|
63
|
+
const left = recordedBackground(record, final?.finishedTasks, now);
|
|
64
|
+
return left && final?.awaited ? Math.min(left, final.awaited) : undefined;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Marks a tab whose main turn ended but whose background work continues:
|
|
68
|
+
* an idle or done tab becomes `working` with `backgroundTasks: count`. Called
|
|
69
|
+
* again with a fuller count (the awaited shells plus the running children,
|
|
70
|
+
* once the child tree is read), it keeps the larger. A tab that is working,
|
|
71
|
+
* blocked or waiting on its own is left alone, so `backgroundTasks` never
|
|
72
|
+
* sits on a tab with a live turn.
|
|
73
|
+
*/
|
|
74
|
+
export function markBackground(tab, count) {
|
|
75
|
+
if (!count || count < 1)
|
|
76
|
+
return;
|
|
77
|
+
if (tab.agentStatus === "idle" || tab.agentStatus === "done") {
|
|
78
|
+
tab.agentStatus = "working";
|
|
79
|
+
tab.backgroundTasks = count;
|
|
80
|
+
}
|
|
81
|
+
else if (typeof tab.backgroundTasks === "number")
|
|
82
|
+
tab.backgroundTasks = Math.max(tab.backgroundTasks, count);
|
|
83
|
+
}
|
|
84
|
+
/** A tab or workspace label worth showing as a name: not empty, not Herdr's bare numbering, not an id. */
|
|
85
|
+
export function meaningfulLabel(value) {
|
|
86
|
+
if (typeof value !== "string")
|
|
87
|
+
return undefined;
|
|
88
|
+
const text = value.trim();
|
|
89
|
+
return text && !/^\d+$/.test(text) && !/^\S*:\S*$/.test(text) && !/^[A-Za-z]{1,2}[_-]?\d+[A-Za-z]?$/.test(text) ? text : undefined;
|
|
90
|
+
}
|
|
91
|
+
/** Spinner and status glyphs a harness puts around its terminal title while it
|
|
92
|
+
* works: Braille spinner frames (Codex), dingbat stars and checks (Claude's
|
|
93
|
+
* ✳), bullets, circles and hourglasses. */
|
|
94
|
+
const GLYPHS_AROUND = /^[\u2800-\u28ff\u2700-\u27bf\u25a0-\u25ff\u23f0-\u23ff\u2022\u00b7\u2219\u22c5\u2605\u2606\s]+|[\s\u2800-\u28ff\u2700-\u27bf\u25a0-\u25ff\u23f0-\u23ff\u2022\u00b7\u2219\u22c5\u2605\u2606]+$/gu;
|
|
95
|
+
/** A terminal title without the spinner or status glyphs around it, nor the
|
|
96
|
+
* separator they leave dangling (Codex's "⠸ | phren" before its thread has a
|
|
97
|
+
* title); undefined when nothing else is left. */
|
|
98
|
+
export function plainTitle(value) {
|
|
99
|
+
if (typeof value !== "string")
|
|
100
|
+
return undefined;
|
|
101
|
+
const text = value.replace(GLYPHS_AROUND, "").replace(/^\|\s+|\s+\|$/g, "").replace(GLYPHS_AROUND, "").trim();
|
|
102
|
+
return text || undefined;
|
|
103
|
+
}
|
|
104
|
+
/** A harness title made from the brief launch's first prompt rather than the work: the prompt itself, the brief path, or "Brief <id>". */
|
|
105
|
+
export function isBriefTitle(title) {
|
|
106
|
+
return /^\s*read and follow the brief/i.test(title) || title.includes("/briefs/")
|
|
107
|
+
|| /^\s*brief\s+[0-9a-f]{8}[0-9a-f-]*\s*(…|\.\.\.)?\s*$/i.test(title);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The name a session is shown under, first that applies:
|
|
111
|
+
* 1. the agent pane's own label, when meaningful (a rename from the phone or
|
|
112
|
+
* from Herdr or tmux itself; a pane has none until someone sets one);
|
|
113
|
+
* 2. the dispatch label its dispatcher gave it;
|
|
114
|
+
* 3. for a dispatch with no stored label (sent before labels were kept), the
|
|
115
|
+
* tab label, else the workspace label, when meaningful;
|
|
116
|
+
* 4. the harness's own title, unless it is brief boilerplate, which is
|
|
117
|
+
* replaced by a meaningful tab or workspace label or dropped (the phone
|
|
118
|
+
* then falls back to the label).
|
|
119
|
+
* Never leaves a row blank: when none applies and `fallbackLabel` (passed, even
|
|
120
|
+
* if undefined) is the label the phone shows without a title and is blank, the raw harness title stands.
|
|
121
|
+
*/
|
|
122
|
+
export function sessionTitle(input) {
|
|
123
|
+
const renamed = meaningfulLabel(input.paneLabel);
|
|
124
|
+
if (renamed)
|
|
125
|
+
return renamed;
|
|
126
|
+
if (input.dispatchLabel)
|
|
127
|
+
return input.dispatchLabel;
|
|
128
|
+
const named = meaningfulLabel(input.tabLabel) ?? meaningfulLabel(input.workspaceLabel);
|
|
129
|
+
const title = plainTitle(input.harnessTitle);
|
|
130
|
+
const chosen = input.dispatched ? named : !title ? undefined : isBriefTitle(title) ? named : title;
|
|
131
|
+
const label = input.fallbackLabel;
|
|
132
|
+
const blank = "fallbackLabel" in input && (typeof label !== "string" || !label.trim());
|
|
133
|
+
return chosen ?? (blank ? title : undefined);
|
|
134
|
+
}
|
|
135
|
+
/** `sessionTitle` for a pane, given its own turn record (the guarded one from `paneRecord`). */
|
|
136
|
+
export async function recordTitle(record, input) {
|
|
137
|
+
const dispatch = record?.dispatch;
|
|
138
|
+
return sessionTitle({ ...input, dispatched: !!dispatch, dispatchLabel: dispatch ? await briefLabel(dispatch) : undefined });
|
|
139
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { PaneClient } from "./opencode-pane-server.js";
|
|
3
|
+
import { type Json, type Target } from "./protocol.js";
|
|
4
|
+
import { type TerminalProvider } from "./terminal.js";
|
|
5
|
+
/** Renaming a session from the phone: the pane's and tab's terminal labels,
|
|
6
|
+
* then the harness's own rename where one can be driven remotely. */
|
|
7
|
+
/** What the phone may send as a session name: 1 to 80 characters, no control characters. */
|
|
8
|
+
export declare const renameLabel: z.ZodString;
|
|
9
|
+
export declare const renameRequest: z.ZodObject<{
|
|
10
|
+
workspaceId: z.ZodString;
|
|
11
|
+
tabId: z.ZodString;
|
|
12
|
+
paneId: z.ZodOptional<z.ZodString>;
|
|
13
|
+
label: z.ZodString;
|
|
14
|
+
}, z.core.$strip>;
|
|
15
|
+
export type NativeMechanism = "slash-command" | "app-server" | "opencode-api" | "none";
|
|
16
|
+
export interface NativeResult {
|
|
17
|
+
harness: string;
|
|
18
|
+
mechanism: NativeMechanism;
|
|
19
|
+
applied: boolean;
|
|
20
|
+
reason?: string;
|
|
21
|
+
}
|
|
22
|
+
/** Everything the rename touches outside this file; tests pass their own. */
|
|
23
|
+
export interface RenameDeps {
|
|
24
|
+
snapshot(server: string): Promise<Json>;
|
|
25
|
+
identity(server: string, pane: Json): Promise<string | undefined>;
|
|
26
|
+
terminal(): TerminalProvider;
|
|
27
|
+
codexRename(target: Target, label: string): Promise<boolean | undefined>;
|
|
28
|
+
opencodeClient(server: string, pane: string): PaneClient | undefined;
|
|
29
|
+
/** The name Claude's transcript for `target` last carries as its `custom-title`. */
|
|
30
|
+
claudeTitle(target: Target): Promise<string | undefined>;
|
|
31
|
+
/** The name Codex's `session_index.jsonl` last holds for a thread. */
|
|
32
|
+
codexIndexTitle(thread: string): Promise<string | undefined>;
|
|
33
|
+
sleep(ms: number): Promise<void>;
|
|
34
|
+
/** How long a typed rename may take to show in the harness's own records. */
|
|
35
|
+
verifyMs: number;
|
|
36
|
+
}
|
|
37
|
+
/** The last `custom-title` in the tail of a Claude transcript. */
|
|
38
|
+
export declare function lastCustomTitle(text: string): string | undefined;
|
|
39
|
+
/** The last `thread_name` written for `thread` in a Codex `session_index.jsonl`. */
|
|
40
|
+
export declare function lastIndexedName(text: string, thread: string): string | undefined;
|
|
41
|
+
export declare const defaultRenameDeps: RenameDeps;
|
|
42
|
+
/** The agent pane a rename addresses: the named pane, else the tab's only agent pane, else its only pane. */
|
|
43
|
+
export declare function renamePane(panes: Json[], paneId: string | undefined): {
|
|
44
|
+
pane: Json;
|
|
45
|
+
renameTab: boolean;
|
|
46
|
+
};
|
|
47
|
+
/** `POST /v1/sessions/rename`: terminal labels first, then the harness's own name. */
|
|
48
|
+
export declare function renameSession(server: string, data: Json, deps?: RenameDeps): Promise<Json>;
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { open } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { codexHome } from "../home-paths.js";
|
|
5
|
+
import { stripTerminal } from "../terminal-text.js";
|
|
6
|
+
import { codexServers } from "./codex-servers.js";
|
|
7
|
+
import { paneIdentity, snapshot } from "./herdr.js";
|
|
8
|
+
import { emptyComposer } from "./model-switch.js";
|
|
9
|
+
import { paneClient, servedPane } from "./opencode-panes.js";
|
|
10
|
+
import { BridgeError, id, objects } from "./protocol.js";
|
|
11
|
+
import { terminalProvider } from "./terminal.js";
|
|
12
|
+
import { visibleTerminalChoice } from "./terminal-choice.js";
|
|
13
|
+
import { targetTranscriptPath } from "./transcripts.js";
|
|
14
|
+
/** Renaming a session from the phone: the pane's and tab's terminal labels,
|
|
15
|
+
* then the harness's own rename where one can be driven remotely. */
|
|
16
|
+
/** What the phone may send as a session name: 1 to 80 characters, no control characters. */
|
|
17
|
+
export const renameLabel = z.string().trim().min(1).max(80).refine(t => !/[\x00-\x1f\x7f]/.test(t));
|
|
18
|
+
export const renameRequest = z.object({ workspaceId: id, tabId: id, paneId: id.optional(), label: renameLabel });
|
|
19
|
+
const TAIL_BYTES = 262_144;
|
|
20
|
+
/** The last `custom-title` in the tail of a Claude transcript. */
|
|
21
|
+
export function lastCustomTitle(text) {
|
|
22
|
+
for (const line of text.split("\n").reverse()) {
|
|
23
|
+
if (!line.includes('"custom-title"'))
|
|
24
|
+
continue;
|
|
25
|
+
try {
|
|
26
|
+
const row = JSON.parse(line);
|
|
27
|
+
if (row.type === "custom-title" && typeof row.customTitle === "string")
|
|
28
|
+
return row.customTitle;
|
|
29
|
+
}
|
|
30
|
+
catch { /* a line cut by the tail window */ }
|
|
31
|
+
}
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
/** The last `thread_name` written for `thread` in a Codex `session_index.jsonl`. */
|
|
35
|
+
export function lastIndexedName(text, thread) {
|
|
36
|
+
for (const line of text.split("\n").reverse()) {
|
|
37
|
+
if (!line.includes(thread))
|
|
38
|
+
continue;
|
|
39
|
+
try {
|
|
40
|
+
const row = JSON.parse(line);
|
|
41
|
+
if (row.id === thread && typeof row.thread_name === "string")
|
|
42
|
+
return row.thread_name;
|
|
43
|
+
}
|
|
44
|
+
catch { /* a line cut by the tail window */ }
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
async function tail(file) {
|
|
49
|
+
const handle = await open(file, "r").catch(() => undefined);
|
|
50
|
+
if (!handle)
|
|
51
|
+
return undefined;
|
|
52
|
+
try {
|
|
53
|
+
const { size } = await handle.stat();
|
|
54
|
+
const length = Math.min(size, TAIL_BYTES), buffer = Buffer.alloc(length);
|
|
55
|
+
await handle.read(buffer, 0, length, size - length);
|
|
56
|
+
return buffer.toString("utf8");
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
await handle.close();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export const defaultRenameDeps = {
|
|
63
|
+
snapshot,
|
|
64
|
+
identity: (server, pane) => paneIdentity(server, pane, true),
|
|
65
|
+
terminal: terminalProvider,
|
|
66
|
+
async codexRename(target, label) {
|
|
67
|
+
const entry = codexServers.forTarget(target);
|
|
68
|
+
if (!entry)
|
|
69
|
+
return undefined;
|
|
70
|
+
await codexServers.renameThread(entry, label);
|
|
71
|
+
return true;
|
|
72
|
+
},
|
|
73
|
+
opencodeClient(server, pane) {
|
|
74
|
+
const entry = servedPane(server, pane);
|
|
75
|
+
return entry ? paneClient(entry) : undefined;
|
|
76
|
+
},
|
|
77
|
+
async claudeTitle(target) {
|
|
78
|
+
const text = await tail(await targetTranscriptPath({ ...target, source: "claude" }));
|
|
79
|
+
return text === undefined ? undefined : lastCustomTitle(text);
|
|
80
|
+
},
|
|
81
|
+
async codexIndexTitle(thread) {
|
|
82
|
+
const text = await tail(path.join(codexHome(), "session_index.jsonl"));
|
|
83
|
+
return text === undefined ? undefined : lastIndexedName(text, thread);
|
|
84
|
+
},
|
|
85
|
+
sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
|
|
86
|
+
verifyMs: 4_000,
|
|
87
|
+
};
|
|
88
|
+
/** The agent pane a rename addresses: the named pane, else the tab's only agent pane, else its only pane. */
|
|
89
|
+
export function renamePane(panes, paneId) {
|
|
90
|
+
if (!panes.length)
|
|
91
|
+
throw new BridgeError(409, "The tab changed.");
|
|
92
|
+
const agents = panes.filter(p => p.agent);
|
|
93
|
+
if (paneId) {
|
|
94
|
+
const pane = panes.find(p => p.pane_id === paneId);
|
|
95
|
+
if (!pane)
|
|
96
|
+
throw new BridgeError(409, "The pane changed.");
|
|
97
|
+
return { pane, renameTab: agents.length ? agents.length === 1 && !!pane.agent : panes.length === 1 };
|
|
98
|
+
}
|
|
99
|
+
if (agents.length === 1)
|
|
100
|
+
return { pane: agents[0], renameTab: true };
|
|
101
|
+
if (!agents.length && panes.length === 1)
|
|
102
|
+
return { pane: panes[0], renameTab: true };
|
|
103
|
+
throw new BridgeError(400, "Choose a pane to rename.");
|
|
104
|
+
}
|
|
105
|
+
/** Types a slash command into an agent pane that is showing an empty composer. */
|
|
106
|
+
async function typeCommand(deps, server, pane, text) {
|
|
107
|
+
const terminal = deps.terminal();
|
|
108
|
+
const before = await terminal.readScreen(server, String(pane.pane_id), { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 }).catch(() => "");
|
|
109
|
+
const composer = before.split(/\r?\n/).reverse().find(line => /^\s*[›❯>]/.test(stripTerminal(line)));
|
|
110
|
+
if (!composer || !emptyComposer(composer) || visibleTerminalChoice(stripTerminal(before)))
|
|
111
|
+
return "the terminal has a draft or an open menu";
|
|
112
|
+
await terminal.prompt(server, String(pane.pane_id), text);
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
/** Polls `seen` until it holds or the deadline passes. */
|
|
116
|
+
async function confirmed(deps, seen) {
|
|
117
|
+
const deadline = Date.now() + deps.verifyMs;
|
|
118
|
+
do {
|
|
119
|
+
if (await seen().catch(() => false))
|
|
120
|
+
return true;
|
|
121
|
+
await deps.sleep(150);
|
|
122
|
+
} while (Date.now() < deadline);
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
/** The harness's own rename for the pane's session, never failing the request: a refusal is reported as `reason`. */
|
|
126
|
+
async function nativeRename(deps, server, workspace, tab, pane, label) {
|
|
127
|
+
const harness = typeof pane.agent === "string" && pane.agent ? pane.agent : "none";
|
|
128
|
+
const skip = (mechanism, reason) => ({ harness, mechanism, applied: false, reason });
|
|
129
|
+
if (!["claude", "codex", "opencode"].includes(harness))
|
|
130
|
+
return skip("none", "This harness has no remote rename.");
|
|
131
|
+
const paneId = String(pane.pane_id), status = String(pane.agent_status);
|
|
132
|
+
let session;
|
|
133
|
+
try {
|
|
134
|
+
session = await deps.identity(server, pane);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
session = undefined;
|
|
138
|
+
}
|
|
139
|
+
if (!session && harness !== "opencode")
|
|
140
|
+
return skip("none", "The session is not identified yet.");
|
|
141
|
+
const target = { server, workspace, tab, pane: paneId, source: harness, session: session ?? "" };
|
|
142
|
+
let mechanism = harness === "opencode" ? "opencode-api" : "slash-command";
|
|
143
|
+
try {
|
|
144
|
+
if (harness === "opencode") {
|
|
145
|
+
const client = deps.opencodeClient(server, paneId);
|
|
146
|
+
if (!client)
|
|
147
|
+
return skip("none", "This OpenCode was not started by the Hook.");
|
|
148
|
+
const chosen = session ?? (await client.currentSession())?.id;
|
|
149
|
+
if (!chosen)
|
|
150
|
+
return skip("opencode-api", "OpenCode has no session yet.");
|
|
151
|
+
const title = await client.setTitle(chosen, label);
|
|
152
|
+
return title === label ? { harness, mechanism: "opencode-api", applied: true } : skip("opencode-api", "OpenCode did not confirm the new name.");
|
|
153
|
+
}
|
|
154
|
+
if (harness === "codex") {
|
|
155
|
+
mechanism = "app-server";
|
|
156
|
+
const served = await deps.codexRename(target, label);
|
|
157
|
+
if (served)
|
|
158
|
+
return { harness, mechanism, applied: true };
|
|
159
|
+
mechanism = "slash-command";
|
|
160
|
+
}
|
|
161
|
+
// A typed command runs only where the harness reads it as one: never over a dialog.
|
|
162
|
+
if (["blocked", "waiting", "unknown"].includes(status))
|
|
163
|
+
return skip("slash-command", "The agent needs input in the terminal first.");
|
|
164
|
+
if (harness === "codex" && status === "working")
|
|
165
|
+
return skip("slash-command", "The agent is working.");
|
|
166
|
+
const refused = await typeCommand(deps, server, pane, `/rename ${label}`);
|
|
167
|
+
if (refused)
|
|
168
|
+
return skip("slash-command", `Not typed: ${refused}.`);
|
|
169
|
+
const applied = await confirmed(deps, harness === "claude" ? async () => (await deps.claudeTitle(target)) === label
|
|
170
|
+
: async () => (await deps.codexIndexTitle(session)) === label);
|
|
171
|
+
return applied ? { harness, mechanism: "slash-command", applied: true } : skip("slash-command", "The harness did not confirm the new name.");
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
return skip(mechanism, error instanceof Error ? error.message.slice(0, 200) : "The rename failed.");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/** `POST /v1/sessions/rename`: terminal labels first, then the harness's own name. */
|
|
178
|
+
export async function renameSession(server, data, deps = defaultRenameDeps) {
|
|
179
|
+
const { workspaceId, tabId, paneId, label } = renameRequest.parse(data);
|
|
180
|
+
const s = await deps.snapshot(server);
|
|
181
|
+
if (!objects(s.tabs).some(t => t.tab_id === tabId && t.workspace_id === workspaceId))
|
|
182
|
+
throw new BridgeError(409, "The tab changed.");
|
|
183
|
+
const { pane, renameTab } = renamePane(objects(s.panes).filter(p => p.tab_id === tabId && p.workspace_id === workspaceId), paneId);
|
|
184
|
+
const terminal = deps.terminal();
|
|
185
|
+
await terminal.renamePane(server, String(pane.pane_id), label);
|
|
186
|
+
if (renameTab)
|
|
187
|
+
await terminal.groupAction(server, "rename", { workspace: workspaceId, tab: tabId }, label);
|
|
188
|
+
const native = await nativeRename(deps, server, workspaceId, tabId, pane, label);
|
|
189
|
+
return { ok: true, label, pane: pane.pane_id, native };
|
|
190
|
+
}
|