@phren/cli 0.3.57 → 0.3.59
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/README.md +1 -1
- package/dist/bridge/account-add.d.ts +30 -0
- package/dist/bridge/account-add.js +125 -19
- package/dist/bridge/account-failover.d.ts +9 -2
- package/dist/bridge/account-failover.js +1 -1
- package/dist/bridge/account-policy.d.ts +44 -0
- package/dist/bridge/account-policy.js +103 -0
- package/dist/bridge/account-pools.d.ts +35 -0
- package/dist/bridge/account-pools.js +171 -0
- package/dist/bridge/account-usage.d.ts +18 -0
- package/dist/bridge/account-usage.js +57 -1
- package/dist/bridge/agent-hook-callback.d.ts +6 -0
- package/dist/bridge/agent-hook-callback.js +10 -2
- package/dist/bridge/agent-hook-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +13 -0
- package/dist/bridge/agent-hooks.d.ts +12 -2
- package/dist/bridge/agent-hooks.js +41 -4
- package/dist/bridge/claude-account-setup.d.ts +16 -0
- package/dist/bridge/claude-account-setup.js +46 -2
- package/dist/bridge/claude-accounts.d.ts +9 -0
- package/dist/bridge/claude-accounts.js +53 -15
- package/dist/bridge/claude-credits.d.ts +5 -1
- package/dist/bridge/claude-credits.js +37 -29
- package/dist/bridge/command.js +12 -3
- package/dist/bridge/computer-identity.d.ts +4 -2
- package/dist/bridge/computer-identity.js +7 -3
- package/dist/bridge/conductor-group.d.ts +1 -1
- package/dist/bridge/conductor-group.js +2 -2
- package/dist/bridge/conductor-sets.d.ts +6 -0
- package/dist/bridge/conductor-sets.js +8 -2
- package/dist/bridge/dispatch-command.js +22 -0
- package/dist/bridge/dispatch-returns.d.ts +23 -0
- package/dist/bridge/dispatch-returns.js +57 -0
- package/dist/bridge/dispatch.d.ts +26 -4
- package/dist/bridge/dispatch.js +100 -11
- package/dist/bridge/git-host-gitlab.js +2 -1
- package/dist/bridge/hand-off-queue.d.ts +71 -0
- package/dist/bridge/hand-off-queue.js +38 -0
- package/dist/bridge/harnesses.d.ts +12 -0
- package/dist/bridge/harnesses.js +20 -4
- package/dist/bridge/helper.d.ts +54 -0
- package/dist/bridge/helper.js +186 -0
- package/dist/bridge/herdr.js +6 -2
- package/dist/bridge/hook-fast.d.ts +3 -0
- package/dist/bridge/hook-fast.js +10 -2
- package/dist/bridge/move-computers.d.ts +15 -1
- package/dist/bridge/move-computers.js +123 -26
- package/dist/bridge/prompt-deliveries.d.ts +29 -1
- package/dist/bridge/prompt-deliveries.js +146 -10
- package/dist/bridge/schedule-watch.js +17 -3
- package/dist/bridge/server-routes.d.ts +4 -0
- package/dist/bridge/server-routes.js +66 -6
- package/dist/bridge/server.js +8 -2
- package/dist/bridge/session-move.d.ts +59 -1
- package/dist/bridge/session-move.js +266 -18
- package/dist/bridge/simulator-stream.d.ts +118 -0
- package/dist/bridge/simulator-stream.js +284 -0
- package/dist/bridge/simulators.d.ts +31 -0
- package/dist/bridge/simulators.js +126 -40
- package/dist/bridge/speech-live.js +132 -22
- package/dist/bridge/task-routes.d.ts +16 -16
- package/dist/bridge/terminal-herdr.js +6 -1
- package/dist/bridge/terminal-tmux.js +9 -5
- package/dist/bridge/terminal.d.ts +9 -2
- package/dist/bridge/transcript-claude.d.ts +3 -0
- package/dist/bridge/transcript-claude.js +175 -29
- package/dist/bridge/transcript-preview.d.ts +11 -2
- package/dist/bridge/transcript-preview.js +90 -8
- package/dist/bridge/turn-records.d.ts +19 -0
- package/dist/bridge/turn-records.js +78 -3
- package/dist/bridge-hook.mjs +12129 -10324
- package/dist/cli-registry.js +2 -2
- package/dist/content/citation.d.ts +4 -0
- package/dist/content/citation.js +21 -21
- package/dist/data/task-contract.d.ts +4 -4
- package/dist/governance/policy.js +5 -2
- package/dist/index.js +1 -1
- package/dist/modules/registry.js +4 -4
- package/dist/project-config.d.ts +14 -0
- package/dist/project-config.js +40 -1
- package/dist/tools/helper.d.ts +3 -0
- package/dist/tools/helper.js +44 -0
- package/package.json +1 -1
|
@@ -1,24 +1,51 @@
|
|
|
1
1
|
// Continuation destinations expose login labels and quota, never auth material.
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { dispatchProjectDirectory, PEER_COPILOT_REASON, projectName } from "./dispatch.js";
|
|
4
|
-
import {
|
|
4
|
+
import { choosePolicyAccount, computerRule, poolRefusal, projectRule, withPolicy } from "./account-policy.js";
|
|
5
|
+
import { accountPolicy } from "./account-pools.js";
|
|
5
6
|
import { harnessInventoryWithin } from "./harnesses.js";
|
|
7
|
+
import { phrenStoreRoot } from "./transcripts.js";
|
|
6
8
|
import { peerHost, isLocalComputer } from "./dispatch-hosts.js";
|
|
7
9
|
import { hookPeers, optionalHookPeers } from "./peers.js";
|
|
8
10
|
import { BridgeError } from "./protocol.js";
|
|
9
11
|
const account = z.object({ id: z.string().max(64), label: z.string().max(200), usable: z.boolean(), signedIn: z.boolean(), email: z.string().optional(), plan: z.string().optional(), current: z.boolean().default(false),
|
|
10
12
|
fiveHourResetsAt: z.string().optional(), weekResetsAt: z.string().optional(),
|
|
11
|
-
fiveHourLeft: z.number().min(0).max(100).optional(), weekLeft: z.number().min(0).max(100).optional(), resetsAt: z.string().optional()
|
|
13
|
+
fiveHourLeft: z.number().min(0).max(100).optional(), weekLeft: z.number().min(0).max(100).optional(), resetsAt: z.string().optional(),
|
|
14
|
+
// Pools and roles (account-policy.ts): `poolRefused` says why the project's or this computer's pools rule the login out.
|
|
15
|
+
pool: z.string().max(32).optional(), role: z.string().max(16).optional(), console: z.boolean().optional(), poolRefused: z.string().max(300).optional() });
|
|
12
16
|
const availability = z.object({ computerId: z.string().uuid().optional(), hasCheckout: z.boolean(), harnesses: z.array(z.object({
|
|
13
17
|
source: z.enum(["claude", "codex", "opencode", "copilot"]), usable: z.boolean(), reason: z.string().optional(), accounts: z.array(account).optional(),
|
|
14
|
-
}))
|
|
15
|
-
|
|
18
|
+
})),
|
|
19
|
+
/** The Claude usage read had not answered in time: accounts carry no room yet. */
|
|
20
|
+
usagePending: z.literal(true).optional(),
|
|
21
|
+
/** The Claude usage read failed: accounts carry no room. */
|
|
22
|
+
usageError: z.string().max(200).optional(),
|
|
23
|
+
});
|
|
24
|
+
/** How long a computer's own Claude usage read may hold its continuation facts. */
|
|
25
|
+
export const MOVE_USAGE_TIMEOUT_MS = 5_000;
|
|
26
|
+
/** The usage read, or why there is none: a read past `ms` is left running (it still warms the cache). */
|
|
27
|
+
async function usageWithin(usage, ms) {
|
|
28
|
+
let timer;
|
|
29
|
+
const late = new Promise(resolve => { timer = setTimeout(() => resolve("late"), ms); timer.unref?.(); });
|
|
30
|
+
try {
|
|
31
|
+
const limits = await Promise.race([usage(), late]);
|
|
32
|
+
return limits === "late" ? { limits: {}, usagePending: true } : { limits };
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return { limits: {}, usageError: "Claude usage could not be read on this computer." };
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
clearTimeout(timer);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export async function localMoveAvailability(project, usage, conductor = false, usageTimeoutMs = MOVE_USAGE_TIMEOUT_MS) {
|
|
16
42
|
const name = project === null || project === undefined || project === "" ? undefined : projectName.parse(project);
|
|
17
|
-
const [checkout, found,
|
|
43
|
+
const [checkout, found, read] = await Promise.all([
|
|
18
44
|
conductor ? Promise.resolve(true) : name ? dispatchProjectDirectory(name).then(() => true, () => false) : Promise.resolve(false),
|
|
19
45
|
harnessInventoryWithin(2_500),
|
|
20
|
-
usage
|
|
46
|
+
usageWithin(usage, usageTimeoutMs),
|
|
21
47
|
]);
|
|
48
|
+
const { limits } = read;
|
|
22
49
|
const { claudeMoveAccounts } = await import("./hand-off.js");
|
|
23
50
|
const rooms = claudeMoveAccounts(limits);
|
|
24
51
|
const { claudeHomes, claudeAccountRef, claudeAccountEmail, claudeAccountSubscription } = await import("./claude-accounts.js");
|
|
@@ -30,11 +57,18 @@ export async function localMoveAvailability(project, usage, conductor = false) {
|
|
|
30
57
|
const ref = claudeAccountRef(home), email = claudeAccountEmail(home), subscription = claudeAccountSubscription(home);
|
|
31
58
|
accounts.push({ ...ref, usable: false, signedIn: false, ...(email ? { email } : {}), ...(subscription?.plan ? { plan: subscription.plan } : {}) });
|
|
32
59
|
}
|
|
60
|
+
// The project's pools (a conductor move has none of its own) and this computer's.
|
|
61
|
+
const rules = [...(name && !conductor ? [projectRule(phrenStoreRoot(), name)] : []), computerRule("this computer", claude?.allowedPools, claude?.poolsUnreadable === true)];
|
|
62
|
+
const refusal = (login) => poolRefusal({ account: login.id, pool: login.pool }, rules);
|
|
33
63
|
const inventory = claude ? discovered.map(row => row.source === "claude" ? { ...row, accounts } : row) : [...discovered, { source: "claude", installed: false, usable: false, accounts }];
|
|
34
|
-
return availability.parse({ hasCheckout: checkout,
|
|
64
|
+
return availability.parse({ hasCheckout: checkout, ...(read.usagePending ? { usagePending: true } : {}), ...(read.usageError ? { usageError: read.usageError } : {}),
|
|
65
|
+
harnesses: inventory.filter(row => row.source !== "phren").map(row => ({
|
|
35
66
|
source: row.source, usable: row.usable, ...(row.accounts ? { accounts: row.accounts.map(login => {
|
|
36
67
|
const room = row.source === "claude" ? rooms.find(item => item.id === login.id) : undefined;
|
|
37
|
-
|
|
68
|
+
const listed = login;
|
|
69
|
+
const refused = row.source === "claude" ? refusal({ id: login.id, pool: listed.pool }) : undefined;
|
|
70
|
+
return { ...room, id: login.id, label: login.label ?? login.id, usable: login.usable && room?.fiveHourLeft !== 0 && room?.weekLeft !== 0, signedIn: login.signedIn, ...(login.email ? { email: login.email } : {}), ...(login.plan ? { plan: login.plan } : {}),
|
|
71
|
+
...(listed.pool ? { pool: listed.pool } : {}), ...(listed.role ? { role: listed.role } : {}), ...(listed.console ? { console: true } : {}), ...(refused ? { poolRefused: refused } : {}) };
|
|
38
72
|
}) } : {}),
|
|
39
73
|
})) });
|
|
40
74
|
}
|
|
@@ -62,11 +96,26 @@ export async function peerMoveAvailability(peer, project, conductor = false) {
|
|
|
62
96
|
throw new BridgeError(409, `Computer ${peer.name} is offline or cannot report continuation availability.`);
|
|
63
97
|
}
|
|
64
98
|
}
|
|
99
|
+
/** The login an unnamed Claude continuation takes there: most room, among those the pools allow and roles let
|
|
100
|
+
* be chosen automatically (`last-resort` only when no other fits). Without pools or roles, the most room as before. */
|
|
65
101
|
function chosenLogin(accounts) {
|
|
66
|
-
|
|
102
|
+
const refused = accounts.filter(login => login.poolRefused).map(login => `${login.id}: ${login.poolRefused}`);
|
|
103
|
+
const picked = choosePolicyAccount(accounts.filter(login => !login.poolRefused).map(login => withPolicy({ account: login.id, usable: login.usable,
|
|
67
104
|
exhausted: login.fiveHourLeft === 0 || login.weekLeft === 0,
|
|
68
105
|
fiveHour: { leftPercent: login.fiveHourLeft }, week: { leftPercent: login.weekLeft },
|
|
69
|
-
})))
|
|
106
|
+
}, login)));
|
|
107
|
+
return { ...picked, skipped: [...refused, ...picked.skipped] };
|
|
108
|
+
}
|
|
109
|
+
/** The receiving computer's logins with the project's pools checked here too: a peer on an older Hook (no pools)
|
|
110
|
+
* or with a store that has not synced the project's list can't let a login through that this side refuses. */
|
|
111
|
+
function checkedHere(accounts, project, conductor) {
|
|
112
|
+
if (conductor)
|
|
113
|
+
return accounts;
|
|
114
|
+
const rule = projectRule(phrenStoreRoot(), project);
|
|
115
|
+
return accounts.map(login => {
|
|
116
|
+
const refused = login.poolRefused ?? poolRefusal({ account: login.id, pool: login.pool }, [rule]);
|
|
117
|
+
return refused ? { ...login, poolRefused: refused } : login;
|
|
118
|
+
});
|
|
70
119
|
}
|
|
71
120
|
export async function checkMovePeer(peer, project, to, conductor = false) {
|
|
72
121
|
if (to.harness === "copilot")
|
|
@@ -74,8 +123,20 @@ export async function checkMovePeer(peer, project, to, conductor = false) {
|
|
|
74
123
|
const facts = await peerMoveAvailability(peer, project, conductor);
|
|
75
124
|
if (!facts.hasCheckout)
|
|
76
125
|
throw new BridgeError(409, `Computer ${peer.name} has no checkout of ${project}.`);
|
|
77
|
-
|
|
78
|
-
|
|
126
|
+
// Without its room an exhausted login looks usable: wait for the read, which goes on and fills the peer's cache.
|
|
127
|
+
if (to.harness === "claude" && facts.usagePending)
|
|
128
|
+
throw new BridgeError(409, `Claude usage on ${peer.name} is still being read; try again in a moment.`);
|
|
129
|
+
const found = facts.harnesses.find(row => row.source === to.harness);
|
|
130
|
+
const harness = found?.source === "claude" && found.accounts ? { ...found, accounts: checkedHere(found.accounts, project, conductor) } : found;
|
|
131
|
+
const picked = to.harness === "claude" && !to.account && harness?.accounts ? chosenLogin(harness.accounts) : undefined;
|
|
132
|
+
const choice = picked?.choice;
|
|
133
|
+
// Pools rule a login out even when it is named; with pools or roles in play an unnamed move never falls back to default.
|
|
134
|
+
const named = to.account ? harness?.accounts?.find(row => row.id === to.account) : undefined;
|
|
135
|
+
if (named?.poolRefused)
|
|
136
|
+
throw new BridgeError(409, `Claude account ${to.account} on ${peer.name} may not do this work: ${named.poolRefused}.`, { code: "account_pool" });
|
|
137
|
+
if (picked && !choice && harness?.accounts?.some(login => login.poolRefused || login.role || login.console || login.pool)) {
|
|
138
|
+
throw new BridgeError(409, `No Claude account on ${peer.name} may continue this${picked.skipped.length ? `: ${picked.skipped.join("; ")}` : ""}.`.slice(0, 500), { code: "account_pool" });
|
|
139
|
+
}
|
|
79
140
|
const login = harness?.accounts?.find(row => row.id === (to.account ?? choice?.account ?? "default"));
|
|
80
141
|
if (!harness?.usable || (harness.accounts && !login?.usable) || login?.fiveHourLeft === 0 || login?.weekLeft === 0) {
|
|
81
142
|
throw new BridgeError(409, `The harness or account is not usable on ${peer.name}.`);
|
|
@@ -86,24 +147,60 @@ export async function checkMovePeer(peer, project, to, conductor = false) {
|
|
|
86
147
|
}
|
|
87
148
|
export async function moveComputers(project, self, local, currentAccount, conductor = false) {
|
|
88
149
|
const name = project === null || project === undefined || project === "" ? "" : projectName.parse(project);
|
|
150
|
+
// This computer's facts are read beside its peers', not before them: one slow read never holds the rest.
|
|
151
|
+
const localFacts = local();
|
|
152
|
+
localFacts.catch(() => undefined); // Still thrown below; not unhandled while the peers are listed.
|
|
89
153
|
const { peers } = await optionalHookPeers();
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
154
|
+
const publicFacts = (facts, remote = false) => ({ ...(facts.computerId ? { computerId: facts.computerId } : {}), hasCheckout: facts.hasCheckout,
|
|
155
|
+
...(facts.usagePending ? { usagePending: true } : {}), ...(facts.usageError ? { usageError: facts.usageError } : {}),
|
|
156
|
+
harnesses: facts.harnesses.map(listed => {
|
|
157
|
+
// A peer's logins as checkMovePeer judges them, so the phone's pick is the one the move makes.
|
|
158
|
+
const row = remote && name && listed.source === "claude" && listed.accounts ? { ...listed, accounts: checkedHere(listed.accounts, name, conductor) } : listed;
|
|
159
|
+
return {
|
|
160
|
+
source: row.source, usable: remote && row.source === "copilot" ? false : row.usable,
|
|
161
|
+
...(remote && row.source === "copilot" ? { reason: PEER_COPILOT_REASON } : {}),
|
|
162
|
+
...(row.source === "claude" && row.accounts ? { selectedAccount: chosenLogin(row.accounts).choice?.account } : {}), ...(row.accounts ? { accounts: row.accounts.map(({ signedIn: _signedIn, ...login }) => ({ ...login, current: !remote && row.source === "claude" && login.id === currentAccount })) } : {}),
|
|
163
|
+
};
|
|
164
|
+
}) });
|
|
165
|
+
const [here, computers] = await Promise.all([localFacts, Promise.all(peers.map(async (peer) => {
|
|
166
|
+
try {
|
|
167
|
+
return { name: peer.name, self: false, online: true, ...publicFacts(await peerMoveAvailability(peerHost(peer), name, conductor), true) };
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return { name: peer.name, self: false, online: false, hasCheckout: false, harnesses: [] };
|
|
171
|
+
}
|
|
172
|
+
}))]);
|
|
104
173
|
return { computers: [{ name: self, self: true, online: true, ...publicFacts(here) }, ...computers],
|
|
105
174
|
localClaudeLogins: here.harnesses.find(row => row.source === "claude")?.accounts?.filter(login => login.signedIn).length ?? 0 };
|
|
106
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Why this computer's Claude account `account` may not take a session in `cwd` (a same-computer move or
|
|
178
|
+
* account switch), or undefined: the pools of the project whose checkout holds `cwd` and this computer's own.
|
|
179
|
+
* Roles don't apply: the account is named by hand.
|
|
180
|
+
*/
|
|
181
|
+
export async function localPoolRefusal(cwd, account) {
|
|
182
|
+
const { getProjectDirs } = await import("../phren-paths.js");
|
|
183
|
+
const { realpath } = await import("node:fs/promises");
|
|
184
|
+
const path = await import("node:path");
|
|
185
|
+
const source = await realpath(cwd).catch(() => cwd);
|
|
186
|
+
let project, longest = 0;
|
|
187
|
+
for (const directoryName of getProjectDirs(phrenStoreRoot())) {
|
|
188
|
+
const name = path.basename(directoryName);
|
|
189
|
+
const directory = await dispatchProjectDirectory(name).catch(() => undefined);
|
|
190
|
+
if (directory && directory.length > longest && (source === directory || source.startsWith(directory + path.sep))) {
|
|
191
|
+
project = name;
|
|
192
|
+
longest = directory.length;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
// An accounts.yaml that can't be read allows no pool here, as a dispatch to this computer would find.
|
|
196
|
+
let policy;
|
|
197
|
+
try {
|
|
198
|
+
policy = accountPolicy();
|
|
199
|
+
}
|
|
200
|
+
catch { /* Refused below. */ }
|
|
201
|
+
const rules = [...(project ? [projectRule(phrenStoreRoot(), project)] : []), computerRule("this computer", policy?.allowedPools, !policy)];
|
|
202
|
+
return poolRefusal({ account, pool: policy?.settings[account]?.pool }, rules);
|
|
203
|
+
}
|
|
107
204
|
/** Re-read enrollment before every request that may transmit a brief. */
|
|
108
205
|
export async function currentMovePeer(captured) {
|
|
109
206
|
const current = await movePeer(captured.name).catch(() => undefined);
|
|
@@ -55,12 +55,19 @@ export declare class PromptDeliveries {
|
|
|
55
55
|
private static open;
|
|
56
56
|
/** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
|
|
57
57
|
private static claimable;
|
|
58
|
+
/** Codex messages whose `cursor` is still being read. */
|
|
59
|
+
private cursors;
|
|
60
|
+
/** The size of a conversation's transcript: 0 before it has one, undefined when it cannot be read. */
|
|
61
|
+
private size;
|
|
58
62
|
constructor(file?: string | undefined, now?: () => number, landed?: (record: {
|
|
59
63
|
source: Provider;
|
|
60
64
|
session: string;
|
|
61
65
|
hash: string;
|
|
62
66
|
at: number;
|
|
63
|
-
}) => Promise<TranscriptEntry[]
|
|
67
|
+
}) => Promise<TranscriptEntry[]>, size?: (record: {
|
|
68
|
+
source: Provider;
|
|
69
|
+
session: string;
|
|
70
|
+
}) => Promise<number | undefined>);
|
|
64
71
|
private samePane;
|
|
65
72
|
private byId;
|
|
66
73
|
private prune;
|
|
@@ -133,6 +140,23 @@ export declare class PromptDeliveries {
|
|
|
133
140
|
* (`working` false) a user row settles too, for a hook that never came. Of several identical open
|
|
134
141
|
* messages the oldest take the entries. `pass` carries the entries still unclaimed within one observe. */
|
|
135
142
|
private taken;
|
|
143
|
+
/** Whether a Codex transcript row can be `record`'s own: written after it was registered. A row at or past
|
|
144
|
+
* its cursor was; one before it only if stamped after registration (written while the cursor was read),
|
|
145
|
+
* which a row without a timestamp, such as a materialized Codex 0.155 thread's, never is. The scan itself
|
|
146
|
+
* drops rows stamped more than `ENTRY_SLACK_MS` before registration. */
|
|
147
|
+
private static codexRowIsOwn;
|
|
148
|
+
/** Rows of `record`'s words in its conversation, oldest first, and where the scan of them began: rows
|
|
149
|
+
* before `start` are out of sight, so whether they exist cannot be told. */
|
|
150
|
+
private codexRows;
|
|
151
|
+
/** Rows with `record`'s words in its conversation claimed by other messages. */
|
|
152
|
+
private codexClaimed;
|
|
153
|
+
/** A Codex message its hook settled takes the first free row written after it was registered. */
|
|
154
|
+
private claimCodexRow;
|
|
155
|
+
/** Whether Codex took `record`'s message: a row written after it was registered (`codexRowIsOwn`) that no
|
|
156
|
+
* other message with these words claimed. An earlier message its hook settled whose row was not yet
|
|
157
|
+
* claimed holds the first such row of its own first, but only when everything written after it is still
|
|
158
|
+
* in the scanned tail: otherwise its row may be gone, and the row that is left is this message's. */
|
|
159
|
+
private takenCodex;
|
|
136
160
|
/** A turn in `target`'s pane ended: the agent now takes held input or never will. */
|
|
137
161
|
stopped(target: Target): void;
|
|
138
162
|
/** Called on the Hook's activity tick with a server's panes. A message
|
|
@@ -150,6 +174,10 @@ export declare function matchingOffsets(buffer: Buffer, start: number, record: {
|
|
|
150
174
|
hash: string;
|
|
151
175
|
at: number;
|
|
152
176
|
}): TranscriptEntry[];
|
|
177
|
+
export declare function transcriptSize(record: {
|
|
178
|
+
source: Provider;
|
|
179
|
+
session: string;
|
|
180
|
+
}): Promise<number | undefined>;
|
|
153
181
|
/** A transcript row's user-typed text: Claude's user rows, Codex's
|
|
154
182
|
* user_message events and user response items. */
|
|
155
183
|
export declare function userTexts(row: Json): string[];
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
|
-
import { open } from "node:fs/promises";
|
|
3
|
+
import { open, stat } from "node:fs/promises";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
import {
|
|
5
|
+
import { materializedPath } from "./codex-threads.js";
|
|
6
|
+
import { atomicInPrivateDir, BridgeError, object, objects, provider, sessionId } from "./protocol.js";
|
|
6
7
|
import { transcriptPath, unwrapPastedContent } from "./transcripts.js";
|
|
7
8
|
/** A delivery the agent's turn ended without: the reason the phone shows. */
|
|
8
9
|
export const TURN_ENDED_WITHOUT_IT = "The agent finished its turn without taking the message.";
|
|
@@ -17,6 +18,8 @@ const MAX_RECORDS = 512;
|
|
|
17
18
|
const LANDED_CHECK_MS = 3_000;
|
|
18
19
|
/** The transcript scan starts this long before a message was typed (clock skew), so entries up to this far back may belong to an earlier message. */
|
|
19
20
|
const ENTRY_SLACK_MS = 5_000;
|
|
21
|
+
/** A transcript is read from its last this many bytes: older rows are out of sight. */
|
|
22
|
+
const TRANSCRIPT_TAIL_BYTES = 524_288;
|
|
20
23
|
/** Claude writes a submitted row after its hooks return; a message its hook settled claims only a row stamped within this long of that. */
|
|
21
24
|
const HOOK_ROW_MS = 30_000;
|
|
22
25
|
/** Typed text holds its pane (nothing more is typed there) at most this long when the pane sends no
|
|
@@ -51,6 +54,9 @@ const recordSchema = z.object({
|
|
|
51
54
|
/** From a joined prompt (`settleJoined`): "part", a message settled inside it, claims no row of its own (the turn's
|
|
52
55
|
* row carries other words); "turn", the joined words themselves, no message of anyone's, claims that row. */
|
|
53
56
|
joined: z.enum(["part", "turn"]).optional(),
|
|
57
|
+
/** Codex: the transcript's size in bytes when the message was registered. Only a row at or past it is
|
|
58
|
+
* the message's own: position, not the clock, orders rows, and a row without a timestamp too. */
|
|
59
|
+
cursor: z.number().int().nonnegative().optional(),
|
|
54
60
|
}).strict();
|
|
55
61
|
/** One message per record, bound to the pane it was typed into (server, pane,
|
|
56
62
|
* agent kind), not to the conversation: a Codex thread or a Claude /clear can
|
|
@@ -73,10 +79,16 @@ export class PromptDeliveries {
|
|
|
73
79
|
static open(record) { return record.state === "typed" || record.state === "queued"; }
|
|
74
80
|
/** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
|
|
75
81
|
static claimable(record) { return PromptDeliveries.open(record) || (record.state === "failed" && !!record.hookClaim); }
|
|
76
|
-
|
|
82
|
+
/** Codex messages whose `cursor` is still being read. */
|
|
83
|
+
cursors = new Map();
|
|
84
|
+
/** The size of a conversation's transcript: 0 before it has one, undefined when it cannot be read. */
|
|
85
|
+
size;
|
|
86
|
+
constructor(file, now = Date.now, landed = transcriptEntries, size) {
|
|
77
87
|
this.file = file;
|
|
78
88
|
this.now = now;
|
|
79
89
|
this.landed = landed;
|
|
90
|
+
// A store reading other transcripts than the agents' own has no sizes for them.
|
|
91
|
+
this.size = size ?? (landed === transcriptEntries ? transcriptSize : async () => undefined);
|
|
80
92
|
if (!file)
|
|
81
93
|
return;
|
|
82
94
|
try {
|
|
@@ -105,7 +117,7 @@ export class PromptDeliveries {
|
|
|
105
117
|
if (!this.file)
|
|
106
118
|
return;
|
|
107
119
|
// A record without a phone id is kept once it claimed a transcript row, so after a restart that row is not offered to another message.
|
|
108
|
-
const rows = this.records.filter(record => record.id || record.entry !== undefined || record.joined === "turn").map(({ idleSince: _, checkedAt: __, hookClaim: ___, seenRow: ____, ...row }) => row);
|
|
120
|
+
const rows = this.records.filter(record => record.id || record.entry !== undefined || record.joined === "turn").map(({ idleSince: _, checkedAt: __, hookClaim: ___, seenRow: ____, awaitingRow: _____, ...row }) => row);
|
|
109
121
|
const file = this.file;
|
|
110
122
|
this.writing = this.writing.then(() => atomicInPrivateDir(file, { records: rows })).catch(() => undefined);
|
|
111
123
|
}
|
|
@@ -126,6 +138,16 @@ export class PromptDeliveries {
|
|
|
126
138
|
session: target.session, ...(typeof terminal === "string" ? { terminal } : {}), state: "typed", at: this.now() };
|
|
127
139
|
this.records.push(record);
|
|
128
140
|
this.save();
|
|
141
|
+
// Started before the caller types the message (a stat, against typing, then the agent's own write), so
|
|
142
|
+
// the row it makes lands past the cursor; a row stamped after registration counts too (`codexRowIsOwn`).
|
|
143
|
+
if (record.source === "codex") {
|
|
144
|
+
const session = record.session;
|
|
145
|
+
this.cursors.set(record, this.size(record).then(size => { if (size !== undefined && record.session === session) {
|
|
146
|
+
record.cursor = size;
|
|
147
|
+
this.save();
|
|
148
|
+
} }, () => undefined)
|
|
149
|
+
.finally(() => this.cursors.delete(record)));
|
|
150
|
+
}
|
|
129
151
|
return new Promise(resolve => {
|
|
130
152
|
const timer = setTimeout(() => this.release(record, "pending"), waitMs);
|
|
131
153
|
timer.unref?.();
|
|
@@ -313,6 +335,13 @@ export class PromptDeliveries {
|
|
|
313
335
|
}
|
|
314
336
|
this.settle(record, entry, target.session, entry !== undefined ? true : undefined);
|
|
315
337
|
this.save();
|
|
338
|
+
if (target.source === "codex") {
|
|
339
|
+
// Its row is its own from now on, so a later message with these words never takes it, even once the
|
|
340
|
+
// row has left the scanned tail. Codex writes the row after its hooks return, and this callback is one
|
|
341
|
+
// of them: not awaited (the agent waits on its answer), and claimed by the next ticks when the row appears.
|
|
342
|
+
record.awaitingRow = true;
|
|
343
|
+
void this.claimCodexRow(record).catch(() => undefined);
|
|
344
|
+
}
|
|
316
345
|
}
|
|
317
346
|
/** Claude submits the messages it held while busy as one turn, joined by newlines, so no single message's
|
|
318
347
|
* hash matches the prompt. Each open message in the pane whose words are a run of whole lines of it settles,
|
|
@@ -367,6 +396,9 @@ export class PromptDeliveries {
|
|
|
367
396
|
delete record.reason;
|
|
368
397
|
delete record.hookClaim;
|
|
369
398
|
delete record.seenRow;
|
|
399
|
+
// A cursor is a position in one conversation's transcript.
|
|
400
|
+
if (session && session !== record.session)
|
|
401
|
+
delete record.cursor;
|
|
370
402
|
if (session)
|
|
371
403
|
record.session = session;
|
|
372
404
|
if (entry !== undefined)
|
|
@@ -383,9 +415,8 @@ export class PromptDeliveries {
|
|
|
383
415
|
* (`working` false) a user row settles too, for a hook that never came. Of several identical open
|
|
384
416
|
* messages the oldest take the entries. `pass` carries the entries still unclaimed within one observe. */
|
|
385
417
|
async taken(record, pass, working = false) {
|
|
386
|
-
// Only Claude's transcript says which entry a message settled with; Codex keeps the any-match check.
|
|
387
418
|
if (record.source !== "claude")
|
|
388
|
-
return
|
|
419
|
+
return this.takenCodex(record);
|
|
389
420
|
const same = (other) => other.hash === record.hash && other.server === record.server && other.pane === record.pane && other.session === record.session;
|
|
390
421
|
const open = this.records.filter(other => same(other) && PromptDeliveries.claimable(other)).sort((a, b) => a.at - b.at);
|
|
391
422
|
if (open[0] !== record)
|
|
@@ -442,6 +473,77 @@ export class PromptDeliveries {
|
|
|
442
473
|
record.entryHook = entry.hook;
|
|
443
474
|
return true;
|
|
444
475
|
}
|
|
476
|
+
/** Whether a Codex transcript row can be `record`'s own: written after it was registered. A row at or past
|
|
477
|
+
* its cursor was; one before it only if stamped after registration (written while the cursor was read),
|
|
478
|
+
* which a row without a timestamp, such as a materialized Codex 0.155 thread's, never is. The scan itself
|
|
479
|
+
* drops rows stamped more than `ENTRY_SLACK_MS` before registration. */
|
|
480
|
+
static codexRowIsOwn(record, row) {
|
|
481
|
+
return (record.cursor !== undefined && row.offset >= record.cursor) || (row.at !== undefined && row.at >= record.at);
|
|
482
|
+
}
|
|
483
|
+
/** Rows of `record`'s words in its conversation, oldest first, and where the scan of them began: rows
|
|
484
|
+
* before `start` are out of sight, so whether they exist cannot be told. */
|
|
485
|
+
async codexRows(record) {
|
|
486
|
+
await this.cursors.get(record);
|
|
487
|
+
const rows = [...await this.landed(record).catch(() => [])].sort((a, b) => a.offset - b.offset);
|
|
488
|
+
// Read after the scan: a transcript that grew meanwhile puts `start` later than the scan's, never earlier.
|
|
489
|
+
const size = await this.size(record).catch(() => undefined);
|
|
490
|
+
return { rows, ...(size !== undefined ? { start: Math.max(0, size - TRANSCRIPT_TAIL_BYTES) } : {}) };
|
|
491
|
+
}
|
|
492
|
+
/** Rows with `record`'s words in its conversation claimed by other messages. */
|
|
493
|
+
codexClaimed(record) {
|
|
494
|
+
return new Set(this.records.filter(other => other !== record && other.hash === record.hash && this.samePane(other, record)
|
|
495
|
+
&& other.session === record.session && other.entry !== undefined).map(other => other.entry));
|
|
496
|
+
}
|
|
497
|
+
/** A Codex message its hook settled takes the first free row written after it was registered. */
|
|
498
|
+
async claimCodexRow(record) {
|
|
499
|
+
const { rows, start } = await this.codexRows(record);
|
|
500
|
+
if (!record.awaitingRow || record.entry !== undefined)
|
|
501
|
+
return;
|
|
502
|
+
// Rows written after it have left the scanned tail: its own may be one of them, so it takes none of those left.
|
|
503
|
+
if (record.cursor !== undefined && start !== undefined && record.cursor < start) {
|
|
504
|
+
delete record.awaitingRow;
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
const used = this.codexClaimed(record);
|
|
508
|
+
const row = rows.find(row => !used.has(row.offset) && PromptDeliveries.codexRowIsOwn(record, row));
|
|
509
|
+
if (!row)
|
|
510
|
+
return;
|
|
511
|
+
record.entry = row.offset;
|
|
512
|
+
record.entryHook = row.hook;
|
|
513
|
+
delete record.awaitingRow;
|
|
514
|
+
this.save();
|
|
515
|
+
}
|
|
516
|
+
/** Whether Codex took `record`'s message: a row written after it was registered (`codexRowIsOwn`) that no
|
|
517
|
+
* other message with these words claimed. An earlier message its hook settled whose row was not yet
|
|
518
|
+
* claimed holds the first such row of its own first, but only when everything written after it is still
|
|
519
|
+
* in the scanned tail: otherwise its row may be gone, and the row that is left is this message's. */
|
|
520
|
+
async takenCodex(record) {
|
|
521
|
+
const { rows, start } = await this.codexRows(record);
|
|
522
|
+
const used = this.codexClaimed(record);
|
|
523
|
+
let claimed = false;
|
|
524
|
+
for (const other of this.records.filter(other => other !== record && other.hash === record.hash && this.samePane(other, record) && other.session === record.session
|
|
525
|
+
&& other.awaitingRow && other.entry === undefined && other.at < record.at).sort((a, b) => a.at - b.at)) {
|
|
526
|
+
if (other.cursor === undefined || start === undefined || other.cursor < start)
|
|
527
|
+
continue;
|
|
528
|
+
const row = rows.find(row => !used.has(row.offset) && PromptDeliveries.codexRowIsOwn(other, row));
|
|
529
|
+
if (!row)
|
|
530
|
+
continue;
|
|
531
|
+
other.entry = row.offset;
|
|
532
|
+
other.entryHook = row.hook;
|
|
533
|
+
delete other.awaitingRow;
|
|
534
|
+
used.add(row.offset);
|
|
535
|
+
claimed = true;
|
|
536
|
+
}
|
|
537
|
+
if (claimed)
|
|
538
|
+
this.save();
|
|
539
|
+
const entry = rows.find(row => !used.has(row.offset) && PromptDeliveries.codexRowIsOwn(record, row));
|
|
540
|
+
// The record may have settled (its hook came) while the transcript was read.
|
|
541
|
+
if (!entry || !PromptDeliveries.claimable(record))
|
|
542
|
+
return false;
|
|
543
|
+
record.entry = entry.offset;
|
|
544
|
+
record.entryHook = entry.hook;
|
|
545
|
+
return true;
|
|
546
|
+
}
|
|
445
547
|
/** A turn in `target`'s pane ended: the agent now takes held input or never will. */
|
|
446
548
|
stopped(target) {
|
|
447
549
|
const at = this.now();
|
|
@@ -468,6 +570,16 @@ export class PromptDeliveries {
|
|
|
468
570
|
for (const record of this.records) {
|
|
469
571
|
if (record.server !== server)
|
|
470
572
|
continue;
|
|
573
|
+
// A Codex message its hook settled claims its row once written, before a later identical one is checked.
|
|
574
|
+
if (record.awaitingRow) {
|
|
575
|
+
if (now - (record.settledAt ?? record.at) > HOOK_ROW_MS)
|
|
576
|
+
delete record.awaitingRow;
|
|
577
|
+
else if (record.checkedAt === undefined || now - record.checkedAt >= LANDED_CHECK_MS) {
|
|
578
|
+
record.checkedAt = now;
|
|
579
|
+
await this.claimCodexRow(record);
|
|
580
|
+
}
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
471
583
|
// A failed message whose own hook came late, before its row: settled when the row appears.
|
|
472
584
|
if (record.state === "failed" && record.hookClaim) {
|
|
473
585
|
if (record.source === "claude" && (record.checkedAt === undefined || now - record.checkedAt >= LANDED_CHECK_MS)) {
|
|
@@ -535,7 +647,10 @@ export class PromptDeliveries {
|
|
|
535
647
|
/** The byte offsets (in the file, `start` being the buffer's own offset) of the rows in `buffer`
|
|
536
648
|
* whose user text has `record`'s words, newest first. One offset per row. */
|
|
537
649
|
export function matchingOffsets(buffer, start, record) {
|
|
538
|
-
const entries = [];
|
|
650
|
+
const entries = [], items = [];
|
|
651
|
+
// A Codex rollout writes each user turn twice, as a `user_message` event and a user `response_item`:
|
|
652
|
+
// the event alone is the turn. Only a thread materialized from Codex 0.155's history has items without events.
|
|
653
|
+
let events = false;
|
|
539
654
|
const lines = buffer.toString("utf8").split("\n");
|
|
540
655
|
let offset = start + buffer.length;
|
|
541
656
|
for (let index = lines.length - 1; index >= 0; index--) {
|
|
@@ -554,19 +669,40 @@ export function matchingOffsets(buffer, start, record) {
|
|
|
554
669
|
// Rows are not in time order: Claude writes a queued message's attachment rows, stamped when it was
|
|
555
670
|
// typed, after the queue removal that took it. An older row is skipped, never the end of the scan,
|
|
556
671
|
// or a message typed after an earlier queued one is never found (seen 2026-10-17: taken, reported failed).
|
|
672
|
+
const payload = object(row.payload), item = row.type === "response_item" && payload.type === "message";
|
|
673
|
+
if (row.type === "event_msg" && payload.type === "user_message")
|
|
674
|
+
events = true;
|
|
557
675
|
const stamp = Date.parse(String(row.timestamp ?? ""));
|
|
558
676
|
if (Number.isFinite(stamp) && stamp < record.at - 5_000)
|
|
559
677
|
continue;
|
|
560
678
|
// One entry per row, even when its content repeats the words.
|
|
561
679
|
if (userTexts(row).some(text => promptHash(text) === record.hash))
|
|
562
|
-
entries.push({ offset, hook: row.type === "user", ...(Number.isFinite(stamp) ? { at: stamp } : {}) });
|
|
680
|
+
(item ? items : entries).push({ offset, hook: row.type === "user", ...(Number.isFinite(stamp) ? { at: stamp } : {}) });
|
|
681
|
+
}
|
|
682
|
+
return events ? entries : [...entries, ...items].sort((a, b) => b.offset - a.offset);
|
|
683
|
+
}
|
|
684
|
+
export async function transcriptSize(record) {
|
|
685
|
+
// A Codex 0.155 thread's copy is read as it stands: finding the transcript first appends what the thread store
|
|
686
|
+
// holds now, which may already be this message, and a failed append must not read as an empty conversation.
|
|
687
|
+
const copy = record.source === "codex" && sessionId.safeParse(record.session).success
|
|
688
|
+
? await stat(materializedPath(record.session)).catch(() => undefined) : undefined;
|
|
689
|
+
if (copy)
|
|
690
|
+
return copy.size;
|
|
691
|
+
try {
|
|
692
|
+
const file = await transcriptPath(record.source, record.session);
|
|
693
|
+
// Its copy made just now holds both older messages and maybe this one: no position tells them apart,
|
|
694
|
+
// and only a timestamped row (none in a copy) can confirm it.
|
|
695
|
+
return file === materializedPath(record.session) ? undefined : (await stat(file)).size;
|
|
696
|
+
}
|
|
697
|
+
catch (error) {
|
|
698
|
+
// A conversation not written yet (a new Codex thread) has nothing before its first row.
|
|
699
|
+
return error instanceof BridgeError && object(error.details).code === "transcript-unavailable" ? 0 : undefined;
|
|
563
700
|
}
|
|
564
|
-
return entries;
|
|
565
701
|
}
|
|
566
702
|
async function transcriptEntries(record) {
|
|
567
703
|
const file = await open(await transcriptPath(record.source, record.session), "r");
|
|
568
704
|
try {
|
|
569
|
-
const size = (await file.stat()).size, start = Math.max(0, size -
|
|
705
|
+
const size = (await file.stat()).size, start = Math.max(0, size - TRANSCRIPT_TAIL_BYTES), buffer = Buffer.alloc(size - start);
|
|
570
706
|
await file.read(buffer, 0, buffer.length, start);
|
|
571
707
|
return matchingOffsets(buffer, start, record);
|
|
572
708
|
}
|
|
@@ -222,7 +222,7 @@ export function finalTurnFromLines(lines, source) {
|
|
|
222
222
|
completed = false;
|
|
223
223
|
continue;
|
|
224
224
|
}
|
|
225
|
-
const userTurn = source === "claude" ? raw.type === "user" && !raw.isMeta &&
|
|
225
|
+
const userTurn = source === "claude" ? raw.type === "user" && !raw.isMeta && claudeUserText(raw) !== undefined
|
|
226
226
|
: source === "codex" ? raw.type === "response_item" && payload.type === "message" && payload.role === "user"
|
|
227
227
|
: source === "copilot" ? raw.type === "user.message"
|
|
228
228
|
: raw.type === "user/message";
|
|
@@ -267,12 +267,26 @@ export function finalTurnFromLines(lines, source) {
|
|
|
267
267
|
/** A prompt the owner (or a dispatcher) typed, not a task's notification or
|
|
268
268
|
* a teammate's message waking the session. */
|
|
269
269
|
function ownerPrompt(raw) {
|
|
270
|
-
|
|
271
|
-
|
|
270
|
+
// Claude files "[Request interrupted by user]" as a user row too: that is a stop, not the owner moving on.
|
|
271
|
+
const content = raw.type === "user" && !raw.isMeta && !turnInterrupted(raw, "claude") ? claudeUserText(raw) : undefined;
|
|
272
|
+
if (content === undefined)
|
|
272
273
|
return false;
|
|
273
274
|
const text = content.trimStart();
|
|
274
275
|
return !text.startsWith("<task-notification>") && !text.startsWith("<teammate-message");
|
|
275
276
|
}
|
|
277
|
+
/** A Claude user row's text when it is a message someone typed: a string, or blocks of text and images (a
|
|
278
|
+
* prompt with a pasted screenshot). A tool's result, which Claude also files as a user row, is not one. */
|
|
279
|
+
function claudeUserText(raw) {
|
|
280
|
+
const content = object(raw.message).content;
|
|
281
|
+
if (typeof content === "string")
|
|
282
|
+
return content;
|
|
283
|
+
if (!Array.isArray(content) || !content.length)
|
|
284
|
+
return undefined;
|
|
285
|
+
const blocks = content.map(object);
|
|
286
|
+
if (!blocks.every(block => block.type === "text" || block.type === "image"))
|
|
287
|
+
return undefined;
|
|
288
|
+
return blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)).join("\n");
|
|
289
|
+
}
|
|
276
290
|
/** The final turn of a conversation, read from the tail of its transcript. */
|
|
277
291
|
export async function readFinalTurn(source, sessionId) {
|
|
278
292
|
if (!sessionId)
|
|
@@ -117,6 +117,9 @@ export declare const capabilities: {
|
|
|
117
117
|
queuedHandOff: boolean;
|
|
118
118
|
approvalPush: string;
|
|
119
119
|
simulators: boolean;
|
|
120
|
+
simulatorStream: boolean;
|
|
121
|
+
simulatorDevices: boolean;
|
|
122
|
+
simulatorDrag: boolean;
|
|
120
123
|
code: boolean;
|
|
121
124
|
codeFiles: boolean;
|
|
122
125
|
overviewStream: boolean;
|
|
@@ -146,6 +149,7 @@ export declare const capabilities: {
|
|
|
146
149
|
moveConductorToComputer: boolean;
|
|
147
150
|
moveResume: boolean;
|
|
148
151
|
claudeAccountAdd: boolean;
|
|
152
|
+
accountPools: boolean;
|
|
149
153
|
workerRelocation: number;
|
|
150
154
|
projectMemory: boolean;
|
|
151
155
|
fileWrite: boolean;
|