worktrust 0.10.38 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +43 -18
- package/README.md +55 -2
- package/SECURITY.md +25 -0
- package/engine-release.json +1 -1
- package/log-session.mjs +6 -6
- package/package-release.json +1 -1
- package/package.json +43 -2
- package/remote-adapter-claude-code.mjs +113 -0
- package/remote-adapter-codex.mjs +159 -0
- package/remote-adapter-terminal.mjs +248 -0
- package/remote-approval-bridge.mjs +145 -0
- package/remote-approvals.mjs +134 -0
- package/remote-attachments.mjs +129 -0
- package/remote-cdp.mjs +60 -0
- package/remote-changes.mjs +94 -0
- package/remote-claude-events.mjs +212 -0
- package/remote-claude-progress.mjs +328 -0
- package/remote-cli.mjs +330 -0
- package/remote-coalesce.mjs +40 -0
- package/remote-codex-events.mjs +153 -0
- package/remote-daemon.mjs +220 -0
- package/remote-inventory.mjs +143 -0
- package/remote-journal.mjs +155 -0
- package/remote-live-preview.mjs +205 -0
- package/remote-pairing.mjs +104 -0
- package/remote-pipeline-config.mjs +177 -0
- package/remote-pipeline-parsers.mjs +121 -0
- package/remote-pipeline.mjs +234 -0
- package/remote-policy.mjs +199 -0
- package/remote-preview.mjs +146 -0
- package/remote-projects.mjs +87 -0
- package/remote-protocol.mjs +4010 -0
- package/remote-qr.mjs +175 -0
- package/remote-release-plans.mjs +88 -0
- package/remote-releases.mjs +297 -0
- package/remote-run.mjs +189 -0
- package/remote-screen-approvals.mjs +79 -0
- package/remote-screen-push.mjs +76 -0
- package/remote-screen-states.mjs +113 -0
- package/remote-service.mjs +101 -0
- package/remote-session-list.mjs +48 -0
- package/remote-sessions.mjs +337 -0
- package/remote-steered.mjs +114 -0
- package/remote-steering.mjs +97 -0
- package/remote-store.mjs +124 -0
- package/remote-terminal-cli.mjs +85 -0
- package/remote-terminal-sessions.mjs +291 -0
- package/remote-transport.mjs +88 -0
- package/worktrust.mjs +11 -4
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SEVERAL AGENT SESSIONS ON ONE COMPUTER (2026-11-07; owner: the phone prompts and manages several sessions). Each remote
|
|
3
|
+
* session has its own session_id, project, agent and process; they run side by side up to a maximum (settings
|
|
4
|
+
* max_sessions, default 4), are listed in device.inventory and status.report, can be attached (their journal replayed),
|
|
5
|
+
* stopped and closed, and resume by the agent's own session id.
|
|
6
|
+
*
|
|
7
|
+
* Order inside a start, held by tests: the steered ledger names the agent's session id BEFORE the agent is spawned (owner
|
|
8
|
+
* decision 1: a remote-steered session is never the person's AI Hours), then session.created, then the agent. A command
|
|
9
|
+
* that starts a turn is AGENT_ACCEPTED only when Claude Code begins that turn (its init line), never when the prompt went in.
|
|
10
|
+
*/
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
12
|
+
import { basename, join } from "node:path";
|
|
13
|
+
import * as P from "./remote-protocol.mjs";
|
|
14
|
+
import { appendSteered } from "./remote-steered.mjs";
|
|
15
|
+
import { adapterOf } from "./remote-inventory.mjs";
|
|
16
|
+
import { claudeArgs, isClaudeSessionId, removeQuietly, startClaude, writeMcpConfig } from "./remote-adapter-claude-code.mjs";
|
|
17
|
+
import { backgroundJobs, emptyClaudeState, endClaudeRun, mapClaudeLine } from "./remote-claude-events.mjs";
|
|
18
|
+
import { collectChanges, snapshotChanges } from "./remote-changes.mjs";
|
|
19
|
+
import { isCodexThreadId, startCodex, writeBridgeSession } from "./remote-adapter-codex.mjs";
|
|
20
|
+
import { emptyCodexState, mapCodexMessage, unwrapShell } from "./remote-codex-events.mjs";
|
|
21
|
+
import { createCoalescer } from "./remote-coalesce.mjs";
|
|
22
|
+
import { accept, announceQueue, claudeReplay, codexLanded, dropWaiting, interruptedEnd, interruptOf, steerLive, steerModeOf } from "./remote-steering.mjs";
|
|
23
|
+
import { classifyAction } from "./remote-policy.mjs";
|
|
24
|
+
import { activeRows, listSessions, statusReport } from "./remote-session-list.mjs";
|
|
25
|
+
|
|
26
|
+
export const DEFAULT_MAX_SESSIONS = 4;
|
|
27
|
+
const LEDGER_EVERY_MS = 10 * 60_000;
|
|
28
|
+
|
|
29
|
+
export { createCoalescer } from "./remote-coalesce.mjs"; // kept here for the modules that import it from sessions
|
|
30
|
+
|
|
31
|
+
export function createSessions(ctx) {
|
|
32
|
+
const live = new Map(); // session_id -> session
|
|
33
|
+
|
|
34
|
+
const attention = (s, activity, needs = null, finished = false) => {
|
|
35
|
+
const prev = s.attention;
|
|
36
|
+
const next = { activity, needs, state_change_seq: (prev?.state_change_seq ?? 0) + 1, completion_seq: finished ? (prev?.completion_seq ?? 0) + 1 : prev?.completion_seq ?? null };
|
|
37
|
+
s.attention = next;
|
|
38
|
+
ctx.emit(s.session_id, "agent.attention", next, s.command_id, P.notifyHint(prev, next));
|
|
39
|
+
};
|
|
40
|
+
const mark = (s) => s.agent_ref && appendSteered({ v: 1, steered: "remote", adapter: s.adapter, agent_session_ref: s.agent_ref, remote_session_id: s.session_id, project_id: s.project_id, how: s.how, first_steered_at: s.first, last_steered_at: ctx.now() });
|
|
41
|
+
const advance = (s, kind) => { if (s.command_id) ctx.journal.advance(s.command_id, { kind }, ctx.now()); };
|
|
42
|
+
|
|
43
|
+
function nextTurn(s) {
|
|
44
|
+
// A Claude Code steer not yet read may become a turn of its own: the next prompt waits until it was (P3-7).
|
|
45
|
+
if (s.turnOpen || s.queue.length === 0 || !s.run?.alive() || (s.adapter !== "codex" && s.steers.length > 0)) return;
|
|
46
|
+
const item = s.queue.shift();
|
|
47
|
+
s.waiting = item;
|
|
48
|
+
s.turnOpen = true;
|
|
49
|
+
s.run.write(item.text);
|
|
50
|
+
announceQueue(ctx, s); // the ones still waiting moved up
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A release's task ends with its turn (remote-releases.mjs), once. */
|
|
54
|
+
const taskEnded = (s, outcome) => { if (s.task && !s.taskEnded) { s.taskEnded = true; ctx.onTaskEnded?.(s.session_id, outcome); } };
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* THE SESSION'S ACTIVE TIME (owner, 2026-11-08: Hours in the phone's session details): each turn's span from its start
|
|
58
|
+
* (turnStartedAt, the clock the turn's own duration_ms is read from) to its end, summed over the session's turns, counted
|
|
59
|
+
* once per turn and kept with the session in the journal. A turn that ended without a measured start makes the sum
|
|
60
|
+
* unknown (null) from then on, and the field is left out: a part is never sent as the whole.
|
|
61
|
+
*/
|
|
62
|
+
function withActive(s, body) {
|
|
63
|
+
if (s.active !== null && s.countedTurn !== s.turnStartedAt) {
|
|
64
|
+
const span = typeof body.duration_ms === "number" ? body.duration_ms : s.turnStartedAt !== null ? Math.max(0, ctx.now() - s.turnStartedAt) : s.turnOpen ? null : 0;
|
|
65
|
+
s.active = span === null ? null : s.active + span;
|
|
66
|
+
s.countedTurn = s.turnStartedAt;
|
|
67
|
+
ctx.journal.recordSession({ session_id: s.session_id, active_ms: s.active });
|
|
68
|
+
}
|
|
69
|
+
return s.active === null ? body : { ...body, session_active_ms: s.active };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function send(s, event) {
|
|
73
|
+
event = interruptedEnd(ctx, s, event); // a turn the person interrupted was stopped, not failed
|
|
74
|
+
if (event.type === "agent.stopped" && s.stopping) return; // stop() sends its own
|
|
75
|
+
if (event.type === "agent.completed" || event.type === "agent.failed" || event.type === "agent.stopped") event = { ...event, body: withActive(s, event.body) };
|
|
76
|
+
if (event.type === "agent.stopped") taskEnded(s, "stopped");
|
|
77
|
+
if (event.type === "agent.usage") s.tokens = event.body.session;
|
|
78
|
+
if (event.type === "agent.subagent") s.subagents.set(event.body.subagent_id, { subagent_id: event.body.subagent_id, parent_id: event.body.parent_id, label: event.body.label, state: event.body.state, tokens_total: event.body.tokens.total });
|
|
79
|
+
if (event.type === "agent.completed" && event.body.result) Object.assign(event.body.result, collectChanges(s.snapshot ?? { source: "agent_tools" }, s.projectPath, s.agentFiles ?? [], ctx.runDir));
|
|
80
|
+
if (event.type === "agent.step_started") advance(s, "running");
|
|
81
|
+
if (event.type === "agent.completed") advance(s, "completed");
|
|
82
|
+
if (event.type === "agent.failed") advance(s, "failed");
|
|
83
|
+
ctx.emit(s.session_id, event.type, event.body, s.command_id, event.type === "agent.completed" ? "finished" : "none");
|
|
84
|
+
if (event.type === "agent.completed") taskEnded(s, "completed");
|
|
85
|
+
if (event.type === "agent.failed") taskEnded(s, "failed");
|
|
86
|
+
ctx.onActivity?.();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Tokens and a running subagent's counts at most once per two seconds (the latest wins); an end goes at once. */
|
|
90
|
+
function deliver(s, event) {
|
|
91
|
+
const go = () => send(s, event);
|
|
92
|
+
if (event.type === "agent.usage") return event.body.turn_final ? s.coalesce.now("usage", go) : s.coalesce.offer("usage", go);
|
|
93
|
+
if (event.type === "agent.subagent") return event.body.state === "working" ? s.coalesce.offer(`sag:${event.body.subagent_id}`, go) : s.coalesce.now(`sag:${event.body.subagent_id}`, go);
|
|
94
|
+
if (event.type === "agent.completed" || event.type === "agent.failed") s.coalesce.flush();
|
|
95
|
+
go();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What still waits goes out, then every subagent still open is stopped: the map never shows one working forever. */
|
|
99
|
+
function endRun(s) {
|
|
100
|
+
s.coalesce.flush();
|
|
101
|
+
if (s.adapter === "codex") return; // Codex reports no subagents to close
|
|
102
|
+
const end = endClaudeRun(s.state, ctx.now());
|
|
103
|
+
s.state = end.state;
|
|
104
|
+
for (const e of end.events) deliver(s, e);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function onLine(s, line) {
|
|
108
|
+
claudeReplay(ctx, s, line); // a live steer Claude Code read: accepted now
|
|
109
|
+
// Background jobs the agent reports (2026-11-08): a change in the count re-sends the project tree, nothing else.
|
|
110
|
+
const jobs = backgroundJobs(s.jobs ?? null, line);
|
|
111
|
+
if (jobs !== (s.jobs ?? null)) { const was = s.jobs?.size ?? null; s.jobs = jobs; if (jobs.size !== was) ctx.onSessionsChanged?.(); }
|
|
112
|
+
const mapped = mapClaudeLine(s.state, line, (prefix = "stp") => P.mintId(prefix, ctx.random), ctx.now());
|
|
113
|
+
s.state = mapped.state;
|
|
114
|
+
// Claude Code wrote under another id than the ledger names (a forked resume, a new version): the ledger names that one
|
|
115
|
+
// too before the turn is accepted, so its log is never read as the person's (review 2026-11-07, P2-c).
|
|
116
|
+
if (mapped.state.sessionRef && mapped.state.sessionRef !== s.agent_ref) { s.agent_ref = mapped.state.sessionRef; mark(s); ctx.journal.recordSession({ session_id: s.session_id, agent_session_ref: s.agent_ref }); }
|
|
117
|
+
if (line.type === "assistant") for (const b of line.message?.content ?? []) if (b?.type === "tool_use" && /^(Edit|MultiEdit|Write|NotebookEdit)$/.test(b.name) && typeof (b.input?.file_path ?? b.input?.notebook_path) === "string") s.agentFiles.push(b.input.file_path ?? b.input.notebook_path);
|
|
118
|
+
afterMapped(s, mapped);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Codex's app-server stream (remote-codex-events.mjs), through the same turn handling as Claude Code's. Codex runs the
|
|
123
|
+
* reads it deems safe without asking, so a command that reads a secret path ends the turn here, on the computer, as it
|
|
124
|
+
* starts (review 2026-11-07, P1-3; the person accepted that gap when they turned Codex on).
|
|
125
|
+
*/
|
|
126
|
+
function onCodex(s, msg) {
|
|
127
|
+
if (msg?.method === "item/started" && msg.params?.item?.type === "commandExecution" && classifyAction("codex", "Bash", { command: unwrapShell(msg.params.item.command ?? "") }, s.projectPath).action.class === "secret_read") {
|
|
128
|
+
s.run.interrupt();
|
|
129
|
+
ctx.emit(s.session_id, "agent.output_delta", { stream: "tool", offset: 0, text: "Stopped on the computer: the agent began to read a secret path (keys, .env, credentials)." }, s.command_id);
|
|
130
|
+
}
|
|
131
|
+
const mapped = mapCodexMessage(s.state, msg, (prefix = "stp") => P.mintId(prefix, ctx.random), ctx.now());
|
|
132
|
+
s.state = mapped.state;
|
|
133
|
+
if (mapped.landed) codexLanded(ctx, s);
|
|
134
|
+
afterMapped(s, mapped);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function afterMapped(s, mapped) {
|
|
138
|
+
if (mapped.turn === "started") s.ownTurn = Boolean(s.waiting);
|
|
139
|
+
if (mapped.turn === "started" && !s.waiting && s.adapter === "codex" && s.steers.length > 0) { const item = s.steers.shift(); s.command_id = item.command_id; accept(ctx, s, item, "new_turn"); }
|
|
140
|
+
if (mapped.turn === "started" && s.waiting) {
|
|
141
|
+
const item = s.waiting;
|
|
142
|
+
s.command_id = item.command_id; s.waiting = null;
|
|
143
|
+
accept(ctx, s, item, "new_turn", mapped.state.turnStartedAt ?? null);
|
|
144
|
+
attention(s, "working");
|
|
145
|
+
}
|
|
146
|
+
if (mapped.turn === "started") { s.turnOpen = true; s.snapshot = snapshotChanges(s.projectPath); s.agentFiles = []; s.turnStartedAt = mapped.state.turnStartedAt ?? ctx.now(); }
|
|
147
|
+
for (const event of mapped.events) deliver(s, event);
|
|
148
|
+
if (mapped.turn === "ended") {
|
|
149
|
+
s.interrupting = false;
|
|
150
|
+
s.turnOpen = false;
|
|
151
|
+
if (s.jobs?.size) ctx.onSessionsChanged?.(); // "ready, but a job is still running": the tree hears the turn ended
|
|
152
|
+
mark(s);
|
|
153
|
+
attention(s, "idle", null, true);
|
|
154
|
+
nextTurn(s);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function onExit(s, how) {
|
|
159
|
+
clearInterval(s.ledgerTimer);
|
|
160
|
+
if (s.jobs?.size) { s.jobs = new Set(); ctx.onSessionsChanged?.(); } // its jobs ended with the agent's process group
|
|
161
|
+
endRun(s);
|
|
162
|
+
ctx.journal.recordSession({ session_id: s.session_id, pid: null });
|
|
163
|
+
ctx.approvals.unregister(s.token);
|
|
164
|
+
removeQuietly(s.mcpFile);
|
|
165
|
+
if (s.turnOpen && !s.stopping) { advance(s, "failed"); ctx.emit(s.session_id, "agent.failed", { reason: "agent_exited", message: how.code === null ? null : `Claude Code exited (${how.code}).` }, s.command_id); taskEnded(s, "failed"); }
|
|
166
|
+
if (!s.stopping) taskEnded(s, "failed"); // an agent that exits before its task's turn ended did not do the task
|
|
167
|
+
s.turnOpen = false;
|
|
168
|
+
s.run = null;
|
|
169
|
+
dropWaiting(ctx, s); // a revived session never runs words sent to the agent that died
|
|
170
|
+
ctx.onActivity?.();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Codex: the thread id reaches the ledger before its first turn (startCodex calls onThread before turn/start). Its
|
|
175
|
+
* planning tools are the session's own bridge, its token in a 0600 file beside Claude Code's MCP config (2026-11-09).
|
|
176
|
+
*/
|
|
177
|
+
function spawnCodex(s, resume) {
|
|
178
|
+
s.token = ctx.approvals.register(s); // so its open approvals are denied when it ends (P3-8)
|
|
179
|
+
const plans = ctx.bridgePath && ctx.socket ? { node: ctx.node, bridge: ctx.bridgePath, session: s.mcpFile = writeBridgeSession(join(ctx.runDir, `${s.session_id}.codex.json`), { socket: ctx.socket(), token: s.token }) } : null;
|
|
180
|
+
s.run = startCodex({ file: ctx.inventory().files.codex, cwd: s.projectPath, env: ctx.agentEnv(), model: s.model, mode: s.mode, resume, plans,
|
|
181
|
+
onMessage: (msg) => onCodex(s, msg), onExit: (how) => onExit(s, how),
|
|
182
|
+
onThread: (id) => { s.agent_ref = id; mark(s); ctx.journal.recordSession({ session_id: s.session_id, agent_session_ref: id }); },
|
|
183
|
+
approve: async (tool, input) => (await ctx.approvals.request(s, tool, input))?.behavior === "allow" });
|
|
184
|
+
ctx.journal.recordSession({ session_id: s.session_id, pid: s.run.pid ?? null });
|
|
185
|
+
s.ledgerTimer = setInterval(() => { if (s.turnOpen) mark(s); }, LEDGER_EVERY_MS);
|
|
186
|
+
s.ledgerTimer.unref?.();
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function spawnAgent(s, resume) {
|
|
190
|
+
if (s.adapter === "codex") return spawnCodex(s, resume);
|
|
191
|
+
const features = ctx.inventory().features["claude-code"];
|
|
192
|
+
s.token = ctx.approvals.register(s);
|
|
193
|
+
s.mcpFile = writeMcpConfig(join(ctx.runDir, `${s.session_id}.mcp.json`), { node: ctx.node, bridge: ctx.bridgePath, socket: ctx.socket(), token: s.token });
|
|
194
|
+
const args = claudeArgs({ features, mode: s.mode, model: s.model, resume, sessionRef: s.agent_ref, mcpConfig: s.mcpFile });
|
|
195
|
+
mark(s); // the ledger names the session before the agent writes a line
|
|
196
|
+
s.run = startClaude({ file: ctx.inventory().files["claude-code"], cwd: s.projectPath, env: ctx.agentEnv(), args, onLine: (line) => onLine(s, line), onExit: (how) => onExit(s, how) });
|
|
197
|
+
ctx.journal.recordSession({ session_id: s.session_id, pid: s.run.pid ?? null, agent_session_ref: s.agent_ref }); // a later daemon ends it if this one dies (P2-b)
|
|
198
|
+
s.ledgerTimer = setInterval(() => { if (s.turnOpen) mark(s); }, LEDGER_EVERY_MS);
|
|
199
|
+
s.ledgerTimer.unref?.();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function start(env, payload) {
|
|
203
|
+
if (live.has(env.session_id) || ctx.journal.session(env.session_id)) return "conflict";
|
|
204
|
+
if ([...live.values()].filter((s) => s.run).length >= (ctx.settings().max_sessions ?? DEFAULT_MAX_SESSIONS)) return "busy";
|
|
205
|
+
const project = ctx.projects().find((p) => p.project_id === env.project_id);
|
|
206
|
+
if (!project) return "not_found";
|
|
207
|
+
const refused = P.checkStart(payload, adapterOf(ctx.inventory(), payload.adapter));
|
|
208
|
+
if (refused) return refused;
|
|
209
|
+
if (payload.adapter !== "claude-code" && payload.adapter !== "codex") return "unsupported";
|
|
210
|
+
if (payload.resume !== null && !(payload.adapter === "codex" ? isCodexThreadId : isClaudeSessionId)(payload.resume)) return "unsupported";
|
|
211
|
+
const s = { session_id: env.session_id, project_id: project.project_id, projectPath: project.path, adapter: payload.adapter, model: payload.model, mode: payload.permission_mode,
|
|
212
|
+
agent_ref: payload.resume ?? (payload.adapter === "codex" ? null : randomUUID()), how: "started", first: ctx.now(), queue: [], state: payload.adapter === "codex" ? emptyCodexState() : emptyClaudeState(),
|
|
213
|
+
coalesce: createCoalescer({ now: ctx.now }), attention: null, command_id: null, waiting: null, turnOpen: false, run: null, steers: [], interrupting: false, ownTurn: null, task: env.task === true, tokens: P.NO_TOKENS, subagents: new Map(), turnStartedAt: null, name: payload.name ?? null, active: 0, countedTurn: null };
|
|
214
|
+
live.set(s.session_id, s);
|
|
215
|
+
ctx.journal.recordSession({ session_id: s.session_id, adapter: s.adapter, project_id: s.project_id, agent_session_ref: s.agent_ref, model: s.model, mode: s.mode, at: ctx.now(), name: s.name, active_ms: 0 });
|
|
216
|
+
ctx.emit(s.session_id, "session.created", { adapter: s.adapter, model: s.model, origin: "phone", title: null, project_label: basename(project.path).slice(0, 256) || null, name: s.name }, env.command_id);
|
|
217
|
+
spawnAgent(s, payload.resume);
|
|
218
|
+
if (payload.prompt) s.queue.push({ text: payload.prompt, command_id: env.command_id, received_at: ctx.now() });
|
|
219
|
+
else { ctx.journal.advance(env.command_id, { kind: "agent_accepted" }, ctx.now()); ctx.emit(s.session_id, "command.agent_accepted", {}, env.command_id); attention(s, "idle"); }
|
|
220
|
+
nextTurn(s);
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** A known session whose agent is gone (a daemon restart) resumes by the agent's own id. */
|
|
225
|
+
function revive(sessionId) {
|
|
226
|
+
let s = live.get(sessionId);
|
|
227
|
+
if (s?.run) return s;
|
|
228
|
+
const saved = s ?? ctx.journal.session(sessionId);
|
|
229
|
+
if (!saved || saved.closed) return null;
|
|
230
|
+
const project = ctx.projects().find((p) => p.project_id === saved.project_id);
|
|
231
|
+
const ref = s?.agent_ref ?? saved.agent_session_ref;
|
|
232
|
+
if (!project || !(saved.adapter === "codex" ? isCodexThreadId : isClaudeSessionId)(ref)) return null;
|
|
233
|
+
if ([...live.values()].filter((x) => x.run).length >= (ctx.settings().max_sessions ?? DEFAULT_MAX_SESSIONS)) return null;
|
|
234
|
+
s = s ?? { session_id: sessionId, project_id: saved.project_id, projectPath: project.path, adapter: saved.adapter, model: saved.model ?? null, mode: saved.mode ?? "ask", agent_ref: ref, how: "started", first: ctx.now(), queue: [], state: saved.adapter === "codex" ? emptyCodexState() : emptyClaudeState(),
|
|
235
|
+
coalesce: createCoalescer({ now: ctx.now }), attention: null, command_id: null, waiting: null, turnOpen: false, run: null, steers: [], interrupting: false, ownTurn: null, task: false, tokens: P.NO_TOKENS, subagents: new Map(), turnStartedAt: null, name: saved.name ?? null, active: saved.active_ms ?? null, countedTurn: null };
|
|
236
|
+
live.set(sessionId, s);
|
|
237
|
+
spawnAgent(s, s.agent_ref);
|
|
238
|
+
return s;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function stop(s) {
|
|
242
|
+
if (!s.run) return;
|
|
243
|
+
s.stopping = true;
|
|
244
|
+
const command = s.command_id;
|
|
245
|
+
await s.run.stop();
|
|
246
|
+
endRun(s);
|
|
247
|
+
s.stopping = false;
|
|
248
|
+
if (command) ctx.journal.advance(command, { kind: "cancelled" }, ctx.now());
|
|
249
|
+
ctx.emit(s.session_id, "agent.stopped", withActive(s, {}), command);
|
|
250
|
+
taskEnded(s, "stopped");
|
|
251
|
+
ctx.emit(s.session_id, "agent.output_delta", { stream: "tool", offset: 0, text: "Stopped. What the agent changed before the stop stays in the project: review it at the computer." }, command);
|
|
252
|
+
dropWaiting(ctx, s);
|
|
253
|
+
attention(s, "idle");
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* A prompt or a steer (remote-steering.mjs): a live steer into the running turn; a prompt with interrupt ends that turn
|
|
258
|
+
* and runs next; anything else waits its turn, and the phone is told its place (command.queued).
|
|
259
|
+
*/
|
|
260
|
+
async function words(s, type, payload, command_id) {
|
|
261
|
+
if (s.task) return "unsupported"; // a release task's session takes no words: add a task to the release instead (P2-2)
|
|
262
|
+
const report = adapterOf(ctx.inventory(), s.adapter);
|
|
263
|
+
const named = ctx.attachments ? ctx.attachments.referenceText(s.session_id, payload.attachments) : payload.attachments?.length ? null : ""; // null: refused, never ""
|
|
264
|
+
if (named === null) return "not_found"; // a file it names is not here whole: never a prompt without its file
|
|
265
|
+
const item = { text: payload.text + named, command_id, received_at: ctx.now() };
|
|
266
|
+
if (type === "agent.steer" && steerModeOf(report) === "none") return "unsupported";
|
|
267
|
+
mark(s);
|
|
268
|
+
if (type === "agent.steer" && s.turnOpen && steerModeOf(report) === "live" && (await steerLive(ctx, s, item))) return null;
|
|
269
|
+
if (type === "agent.prompt" && payload.interrupt === true && s.turnOpen) {
|
|
270
|
+
if (!interruptOf(report)) return "unsupported";
|
|
271
|
+
s.queue.unshift(item);
|
|
272
|
+
s.interrupting = true;
|
|
273
|
+
announceQueue(ctx, s, "interrupting");
|
|
274
|
+
if (!(await s.run.interrupt())) s.interrupting = false; // nothing to end: it simply runs next (P3-6)
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
s.queue.push(item);
|
|
278
|
+
if (s.turnOpen) announceQueue(ctx, s);
|
|
279
|
+
nextTurn(s);
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const statusOf = (s) => statusReport(ctx, s);
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
list: () => [...live.values()].filter((s) => !s.closed).map((s) => ({ session_id: s.session_id, project_id: s.project_id, adapter: s.adapter, origin: "phone", attention: s.attention ?? { activity: "unknown", needs: null, state_change_seq: 0, completion_seq: null }, title: null })),
|
|
287
|
+
get: (id) => live.get(id) ?? null,
|
|
288
|
+
statusOf,
|
|
289
|
+
onApprovalOpened: (id) => { const s = live.get(id); if (s) { advance(s, "waiting_approval"); attention(s, "needs_you", "approval"); } },
|
|
290
|
+
onApprovalSettled: (id) => { const s = live.get(id); if (s && s.turnOpen) { advance(s, "approval_resolved"); attention(s, "working"); } },
|
|
291
|
+
/** One session command → null when it was taken, or the reject reason. */
|
|
292
|
+
async handle(env, payload) {
|
|
293
|
+
const type = env.type;
|
|
294
|
+
if (type === "agent.start") return start(env, payload);
|
|
295
|
+
if (type === "agent.pause" || type === "agent.resume" || type === "session.focus" || type === "screen.read" || type === "question.answer") return type === "question.answer" ? "not_found" : "unsupported";
|
|
296
|
+
if (type === "session.rename" && !live.has(env.session_id)) {
|
|
297
|
+
// A session from the journal (closed, or before a restart) keeps its history and takes a new name all the same.
|
|
298
|
+
if (!ctx.journal.session(env.session_id)) return "not_found";
|
|
299
|
+
ctx.journal.recordSession({ session_id: env.session_id, name: payload.name });
|
|
300
|
+
ctx.onSessionsChanged?.();
|
|
301
|
+
return "taken";
|
|
302
|
+
}
|
|
303
|
+
const s = type === "agent.prompt" || type === "agent.steer" ? revive(env.session_id) : live.get(env.session_id);
|
|
304
|
+
if (!s) return "not_found";
|
|
305
|
+
if (type === "agent.prompt" || type === "agent.steer") return words(s, type, payload, env.command_id);
|
|
306
|
+
if (type === "agent.stop") { await stop(s); return "taken"; }
|
|
307
|
+
if (type === "status.get") { ctx.emit(s.session_id, "status.report", statusOf(s), env.command_id); return "taken"; }
|
|
308
|
+
if (type === "session.attach") { ctx.replay(s.session_id, 0); return "taken"; }
|
|
309
|
+
if (type === "session.rename") { s.name = payload.name; ctx.journal.recordSession({ session_id: s.session_id, name: s.name }); ctx.onSessionsChanged?.(); return "taken"; }
|
|
310
|
+
if (type === "session.close") { await stop(s); s.closed = true; live.delete(s.session_id); ctx.journal.recordSession({ session_id: s.session_id, closed: true }); return "taken"; }
|
|
311
|
+
return "unsupported";
|
|
312
|
+
},
|
|
313
|
+
/**
|
|
314
|
+
* A release's task, started by the scheduler (remote-releases.mjs): the same start as the phone's agent.start (the
|
|
315
|
+
* steered ledger before the agent, checkStart, the cap), with no command of its own. → null, or a reject reason.
|
|
316
|
+
*/
|
|
317
|
+
startTask: (t) => start({ session_id: t.session_id, project_id: t.project_id, command_id: null, task: true }, { adapter: t.adapter, model: t.model, permission_mode: t.permission_mode, resume: t.resume, prompt: t.prompt, name: t.name ?? null }),
|
|
318
|
+
/** The project tree (2026-11-07): every session this computer knows, as remote-session-list.mjs lists them. */
|
|
319
|
+
listAll: () => listSessions(ctx, live),
|
|
320
|
+
/** Stop a running task's turn (release.cancel_task) → false when its agent was already gone. */
|
|
321
|
+
async stopTask(sessionId) { const s = live.get(sessionId); if (!s?.run) return false; await stop(s); return true; },
|
|
322
|
+
/** A task's session ends with its task: the agent exits and the slot frees. Nothing more is sent on its stream. */
|
|
323
|
+
async closeTask(sessionId) {
|
|
324
|
+
const s = live.get(sessionId);
|
|
325
|
+
if (!s) return;
|
|
326
|
+
s.closed = true;
|
|
327
|
+
dropWaiting(ctx, s);
|
|
328
|
+
if (s.run) { s.stopping = true; await s.run.stop(); }
|
|
329
|
+
live.delete(sessionId);
|
|
330
|
+
ctx.journal.recordSession({ session_id: sessionId, closed: true });
|
|
331
|
+
},
|
|
332
|
+
runningCount: () => [...live.values()].filter((s) => s.run).length,
|
|
333
|
+
/** The live feed's rows (live.ts), without the release mapping the scheduler adds. */
|
|
334
|
+
activeList: () => activeRows(live),
|
|
335
|
+
async stopAll() { for (const s of live.values()) if (s.run) { s.stopping = true; await s.run.stop(500); } },
|
|
336
|
+
};
|
|
337
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* REMOTE-STEERED SESSIONS, MARKED (2026-11-07; owner decision 1, binding: a session steered from a phone is NEVER the
|
|
3
|
+
* person's AI Hours; agent work in it counts only under the existing headless rules).
|
|
4
|
+
*
|
|
5
|
+
* The daemon (`worktrust remote`) writes one record per agent session it started or steered to
|
|
6
|
+
* ~/.worktrust/remote/steered.jsonl (mode 0600), the protocol's STEERED_RECORD_SPEC as canonical JSON, BEFORE the agent
|
|
7
|
+
* runs: it chooses Claude Code's session id itself (--session-id) or resumes a known one, so the ledger names the session
|
|
8
|
+
* before its first line is written. The measurement readers (log-session.mjs) ask `remoteSteeredOf(file, messages)` for
|
|
9
|
+
* each day of each session they read; a day that overlaps a steered window is measured as a headless session and sent
|
|
10
|
+
* with steered_from "remote", so none of its seconds is the person's.
|
|
11
|
+
*
|
|
12
|
+
* Self-contained on purpose: the session hook imports it on every run, and a measurement that fails open because a
|
|
13
|
+
* larger module did not load would count remote work as a person's. scripts/test-remote-steered-hours.mjs holds this
|
|
14
|
+
* reader to the protocol's validateSteeredRecord, line for line, and proves the hours rule end to end.
|
|
15
|
+
*/
|
|
16
|
+
import { closeSync, existsSync, fsyncSync, lstatSync, openSync, readFileSync, writeSync, constants, chmodSync, mkdirSync } from "node:fs";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import { join } from "node:path";
|
|
19
|
+
|
|
20
|
+
export const steeredFile = () => join(homedir(), ".worktrust", "remote", "steered.jsonl");
|
|
21
|
+
const ADAPTERS = new Set(["claude-code", "codex", "cursor-agent", "opencode", "local"]);
|
|
22
|
+
const REF = /^[A-Za-z0-9._:-]{1,256}$/;
|
|
23
|
+
const ID = (prefix) => new RegExp(`^${prefix}_[A-Za-z0-9_-]{22}$`);
|
|
24
|
+
const KEYS = "adapter,agent_session_ref,first_steered_at,how,last_steered_at,project_id,remote_session_id,steered,v";
|
|
25
|
+
const time = (n) => Number.isSafeInteger(n) && n >= 0;
|
|
26
|
+
/** A message's time may lead or trail the daemon's own stamps by this much and still be the steered run. */
|
|
27
|
+
export const STEERED_SLACK_MS = 5 * 60_000;
|
|
28
|
+
|
|
29
|
+
/** The protocol's validateSteeredRecord, without the protocol module (held equal by the test). */
|
|
30
|
+
export function steeredRecordOk(r) {
|
|
31
|
+
if (!r || typeof r !== "object" || Array.isArray(r) || Object.keys(r).sort().join(",") !== KEYS) return false;
|
|
32
|
+
return r.v === 1 && r.steered === "remote" && ADAPTERS.has(r.adapter) && typeof r.agent_session_ref === "string" && REF.test(r.agent_session_ref)
|
|
33
|
+
&& ID("ses").test(r.remote_session_id) && (r.project_id === null || ID("prj").test(r.project_id)) && (r.how === "started" || r.how === "attached")
|
|
34
|
+
&& time(r.first_steered_at) && time(r.last_steered_at) && r.last_steered_at >= r.first_steered_at;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const PIPELINE_KEYS = "agent,ended_at,pipeline_run_id,project_id,release_id,started_at,steered,v";
|
|
38
|
+
/**
|
|
39
|
+
* A pipeline run (2026-11-07): `steered: "pipeline"`, `agent: false`. Builds, tests and scanners the daemon ran for a
|
|
40
|
+
* release, never agent work and never hours; the reader knows it and skips it (the protocol's validatePipelineLedgerRecord,
|
|
41
|
+
* held equal by the test).
|
|
42
|
+
*/
|
|
43
|
+
export function pipelineRecordOk(r) {
|
|
44
|
+
if (!r || typeof r !== "object" || Array.isArray(r) || Object.keys(r).sort().join(",") !== PIPELINE_KEYS) return false;
|
|
45
|
+
return r.v === 1 && r.steered === "pipeline" && r.agent === false && ID("plr").test(r.pipeline_run_id) && (r.release_id === null || ID("rel").test(r.release_id))
|
|
46
|
+
&& (r.project_id === null || ID("prj").test(r.project_id)) && time(r.started_at) && (r.ended_at === null || (time(r.ended_at) && r.ended_at >= r.started_at));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Canonical JSON for a flat record of strings, integers and null: keys sorted, no whitespace. */
|
|
50
|
+
const canonical = (r) => `{${Object.keys(r).sort().map((k) => `${JSON.stringify(k)}:${JSON.stringify(r[k])}`).join(",")}}`;
|
|
51
|
+
|
|
52
|
+
/** Every valid record by agent_session_ref, the widest window kept; unreadable lines counted, never fatal. */
|
|
53
|
+
export function readSteered(file = steeredFile()) {
|
|
54
|
+
const byRef = new Map();
|
|
55
|
+
let unreadable = 0, pipelines = 0;
|
|
56
|
+
let text = "";
|
|
57
|
+
try { if (existsSync(file) && !lstatSync(file).isSymbolicLink()) text = readFileSync(file, "utf8"); } catch { text = ""; }
|
|
58
|
+
for (const line of text.split("\n")) {
|
|
59
|
+
if (line.trim() === "") continue;
|
|
60
|
+
let record = null;
|
|
61
|
+
try { record = JSON.parse(line); } catch { record = null; }
|
|
62
|
+
if (pipelineRecordOk(record)) { pipelines += 1; continue; } // not agent work: no session for a reader to match
|
|
63
|
+
if (!steeredRecordOk(record)) { unreadable += 1; continue; }
|
|
64
|
+
const prior = byRef.get(record.agent_session_ref);
|
|
65
|
+
byRef.set(record.agent_session_ref, prior
|
|
66
|
+
? { ...record, first_steered_at: Math.min(prior.first_steered_at, record.first_steered_at), last_steered_at: Math.max(prior.last_steered_at, record.last_steered_at) }
|
|
67
|
+
: record);
|
|
68
|
+
}
|
|
69
|
+
return { byRef, unreadable, pipelines };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The daemon's write: one canonical line, appended and flushed to disk before the agent is started. */
|
|
73
|
+
export function appendSteered(record, file = steeredFile()) {
|
|
74
|
+
if (!steeredRecordOk(record)) throw new TypeError("not a steered record");
|
|
75
|
+
const dir = join(file, "..");
|
|
76
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
77
|
+
const fd = openSync(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
78
|
+
try { writeSync(fd, `${canonical(record)}\n`); fsyncSync(fd); } finally { closeSync(fd); }
|
|
79
|
+
try { chmodSync(file, 0o600); } catch { /* Windows */ }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** A pipeline run's mark (remote-pipeline.mjs), written at its start and again at its end. */
|
|
83
|
+
export function appendPipelineMark(record, file = steeredFile()) {
|
|
84
|
+
if (!pipelineRecordOk(record)) throw new TypeError("not a pipeline record");
|
|
85
|
+
const dir = join(file, "..");
|
|
86
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
87
|
+
const fd = openSync(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
88
|
+
try { writeSync(fd, `${canonical(record)}\n`); fsyncSync(fd); } finally { closeSync(fd); }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The agent's own session id a reader file names: Claude Code's <uuid>.jsonl, a Codex rollout's trailing uuid, a database session's id. */
|
|
92
|
+
export function sessionRefsOf(file) {
|
|
93
|
+
const name = String(file).split(/[\\/]/).at(-1).replace(/\.jsonl$/, "");
|
|
94
|
+
const refs = new Set([name]);
|
|
95
|
+
const uuid = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.exec(name)?.[1];
|
|
96
|
+
if (uuid) refs.add(uuid);
|
|
97
|
+
const colon = name.lastIndexOf(":");
|
|
98
|
+
if (colon > 0) refs.add(name.slice(colon + 1));
|
|
99
|
+
return [...refs].filter((ref) => REF.test(ref));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let cached = null;
|
|
103
|
+
/**
|
|
104
|
+
* True when this day's messages of this session fall inside a window the daemon steered from a phone. Read once per
|
|
105
|
+
* process (the hook is short-lived); `ledger` may be passed for a test.
|
|
106
|
+
*/
|
|
107
|
+
export function remoteSteeredOf(file, messages, ledger = null) {
|
|
108
|
+
const { byRef } = ledger ?? (cached ??= readSteered());
|
|
109
|
+
if (byRef.size === 0 || !Array.isArray(messages) || messages.length === 0) return false;
|
|
110
|
+
const record = sessionRefsOf(file).map((ref) => byRef.get(ref)).find(Boolean);
|
|
111
|
+
if (!record) return false;
|
|
112
|
+
const from = record.first_steered_at - STEERED_SLACK_MS, to = record.last_steered_at + STEERED_SLACK_MS;
|
|
113
|
+
return messages.some((m) => Number.isFinite(m?.at) && m.at >= from && m.at <= to);
|
|
114
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WORDS SENT WHILE A TURN RUNS (owner, 2026-11-07: "when I send a message while the agent is still busy, it is only picked
|
|
3
|
+
* up minutes later; this must be visible in the app"). docs/remote-agents/PROTOCOL.md "Steering a running turn".
|
|
4
|
+
*
|
|
5
|
+
* agent.prompt during a turn waits in the session's queue; `command.queued { position, reason }` is sent when it
|
|
6
|
+
* starts waiting and whenever its place changes, until command.agent_accepted (with
|
|
7
|
+
* `received_at`, so the phone shows how long it waited on the computer).
|
|
8
|
+
* agent.prompt, interrupt (only where the adapter reports `interrupt`) goes first in the queue and the running
|
|
9
|
+
* turn is ended; that turn ends `agent.stopped`, never failed, and this prompt runs next.
|
|
10
|
+
* agent.steer, live adapter goes INTO the running turn now: Claude Code reads a stream-json user message at its next
|
|
11
|
+
* tool boundary (accepted when it replays the message, `isReplay`); Codex takes
|
|
12
|
+
* `turn/steer` against the running turn's id (accepted on its answer). Both measured on this
|
|
13
|
+
* computer (Claude Code 2.1.286, Codex 0.154.0). A steer that finds no running turn waits
|
|
14
|
+
* as the next prompt.
|
|
15
|
+
* Pure helpers over a session record `s`; the sessions module owns the agent processes.
|
|
16
|
+
*/
|
|
17
|
+
import * as P from "./remote-protocol.mjs";
|
|
18
|
+
|
|
19
|
+
/** Tell the phone where each waiting command stands, once per change of place. */
|
|
20
|
+
export function announceQueue(ctx, s, reason = "turn_running") {
|
|
21
|
+
s.queue.forEach((item, i) => {
|
|
22
|
+
if (item.position === i + 1 && item.reason === reason) return;
|
|
23
|
+
item.position = i + 1; item.reason = reason;
|
|
24
|
+
ctx.emit(s.session_id, "command.queued", { position: i + 1, reason }, item.command_id);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A command is taken by the agent: the journal first, then the receipt with when it arrived and where it went. */
|
|
29
|
+
export function accept(ctx, s, item, landed, startedAt = null) {
|
|
30
|
+
if (!item.command_id) return; // a release task's own turn: no command of the phone's to answer
|
|
31
|
+
ctx.journal.advance(item.command_id, { kind: "agent_accepted" }, ctx.now());
|
|
32
|
+
ctx.emit(s.session_id, "command.agent_accepted", { ...(startedAt !== null ? { started_at: startedAt } : {}), ...(Number.isSafeInteger(item.received_at) ? { received_at: item.received_at } : {}), landed }, item.command_id);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A live steer into the running turn. → true when it went in (or is on its way), false when it must wait as a prompt.
|
|
37
|
+
* It is accepted only when the agent shows it read the words (review 2026-11-07, P3-7): Claude Code's replay, Codex's
|
|
38
|
+
* user-message item inside the turn (codexLanded), never the RPC's answer alone.
|
|
39
|
+
*/
|
|
40
|
+
export async function steerLive(ctx, s, item) {
|
|
41
|
+
if (s.adapter === "codex") {
|
|
42
|
+
s.steers.push(item);
|
|
43
|
+
const r = await s.run.steer(item.text);
|
|
44
|
+
if (!r.ok) s.steers.splice(s.steers.indexOf(item), 1);
|
|
45
|
+
return r.ok;
|
|
46
|
+
}
|
|
47
|
+
s.steers.push(item); // Claude Code: accepted when it replays the message (claudeReplay)
|
|
48
|
+
s.run.write(item.text);
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Codex put a steer's words into the turn (a later userMessage item): the oldest waiting steer is accepted. */
|
|
53
|
+
export function codexLanded(ctx, s) {
|
|
54
|
+
const item = s.steers.shift();
|
|
55
|
+
if (item) accept(ctx, s, item, "running_turn");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Every command still waiting on this session is settled when its turn can no longer come (a stop, the agent's exit, a
|
|
60
|
+
* task's session closing): journaled cancelled and told agent.stopped, so the phone never shows a place in a queue that
|
|
61
|
+
* will not move (review 2026-11-07, P2-2).
|
|
62
|
+
*/
|
|
63
|
+
export function dropWaiting(ctx, s) {
|
|
64
|
+
const items = [...s.queue.splice(0), ...s.steers.splice(0), ...(s.waiting ? [s.waiting] : [])];
|
|
65
|
+
s.waiting = null;
|
|
66
|
+
for (const item of items) {
|
|
67
|
+
if (!item.command_id) continue;
|
|
68
|
+
ctx.journal.advance(item.command_id, { kind: "cancelled" }, ctx.now());
|
|
69
|
+
ctx.emit(s.session_id, "agent.stopped", {}, item.command_id);
|
|
70
|
+
}
|
|
71
|
+
return items.length;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Claude Code's replay of a user message (--replay-user-messages): the first waiting steer with these words landed. */
|
|
75
|
+
export function claudeReplay(ctx, s, line) {
|
|
76
|
+
if (line?.type !== "user" || line.isReplay !== true || line.parent_tool_use_id) return;
|
|
77
|
+
const words = (line.message?.content ?? []).filter((b) => b?.type === "text").map((b) => b.text).join("");
|
|
78
|
+
const at = s.steers.findIndex((x) => x.text === words);
|
|
79
|
+
if (at < 0) return;
|
|
80
|
+
const [item] = s.steers.splice(at, 1);
|
|
81
|
+
// A turn this computer did not start (no prompt was waiting for it) is the steer's own new turn: Claude Code read the
|
|
82
|
+
// words after the turn they were sent into had ended (review 2026-11-07, P3-7).
|
|
83
|
+
if (s.ownTurn === false) { s.command_id = item.command_id; accept(ctx, s, item, "new_turn"); return; }
|
|
84
|
+
accept(ctx, s, item, "running_turn");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The end of a turn the person interrupted: it was stopped, not failed. → the event to send instead, or the event itself. */
|
|
88
|
+
export function interruptedEnd(ctx, s, event) {
|
|
89
|
+
if (!s.interrupting || (event.type !== "agent.failed" && event.type !== "agent.stopped")) return event;
|
|
90
|
+
s.interrupting = false;
|
|
91
|
+
if (s.command_id) ctx.journal.advance(s.command_id, { kind: "cancelled" }, ctx.now());
|
|
92
|
+
return { type: "agent.stopped", body: {} };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** What the adapter reports for words sent mid-turn (the phone offers only this). */
|
|
96
|
+
export const steerModeOf = (report) => (report ? P.steerOffered(report.capabilities) : "none");
|
|
97
|
+
export const interruptOf = (report) => Boolean(report && P.interruptOffered(report.capabilities));
|