@phren/cli 0.3.58 → 0.3.61
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 +29 -4
- package/dist/bridge/account-usage.js +117 -8
- 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 +8 -2
- package/dist/bridge/claude-credits.js +52 -31
- package/dist/bridge/codex-threads.js +50 -2
- package/dist/bridge/command.js +12 -3
- package/dist/bridge/continuation-launch.d.ts +32 -0
- package/dist/bridge/continuation-launch.js +112 -1
- 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/git-hosts.d.ts +8 -0
- package/dist/bridge/git-hosts.js +16 -2
- package/dist/bridge/git-publish.js +18 -2
- package/dist/bridge/git.d.ts +8 -0
- package/dist/bridge/git.js +24 -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/owner-inbox-sources.d.ts +12 -1
- package/dist/bridge/owner-inbox-sources.js +127 -49
- package/dist/bridge/peers.d.ts +2 -0
- package/dist/bridge/peers.js +35 -4
- package/dist/bridge/prompt-deliveries.d.ts +69 -2
- package/dist/bridge/prompt-deliveries.js +342 -28
- package/dist/bridge/schedule-watch.js +17 -3
- package/dist/bridge/server-routes.d.ts +6 -0
- package/dist/bridge/server-routes.js +98 -14
- package/dist/bridge/server-stream.js +6 -4
- package/dist/bridge/server.js +2 -1
- package/dist/bridge/session-move.d.ts +70 -1
- package/dist/bridge/session-move.js +311 -19
- package/dist/bridge/simulators.d.ts +19 -0
- package/dist/bridge/simulators.js +93 -13
- 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/usage.d.ts +17 -0
- package/dist/bridge/usage.js +3 -2
- package/dist/bridge-hook.mjs +11964 -10084
- 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 +5 -5
- package/dist/project-config.d.ts +14 -0
- package/dist/project-config.js +40 -1
- package/dist/tools/dispatch.js +1 -1
- package/dist/tools/helper.d.ts +3 -0
- package/dist/tools/helper.js +44 -0
- package/package.json +1 -1
|
@@ -2,14 +2,15 @@
|
|
|
2
2
|
// ~/.claude is the "default" account and is launched without CLAUDE_CONFIG_DIR,
|
|
3
3
|
// so its keychain item and ~/.claude.json stay where Claude Code put them.
|
|
4
4
|
// Every ~/.claude-<slug> holding a .claude.json is another account. See docs/accounts.md.
|
|
5
|
-
import { createHash } from "node:crypto";
|
|
6
|
-
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
7
|
-
import { mkdir
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { mkdir } from "node:fs/promises";
|
|
8
8
|
import { spawn } from "node:child_process";
|
|
9
9
|
import path from "node:path";
|
|
10
10
|
import { dump, load } from "js-yaml";
|
|
11
|
+
import { withFileLock } from "../governance/locks.js";
|
|
11
12
|
import { claudeConfigDir, homeDir } from "../home-paths.js";
|
|
12
|
-
import {
|
|
13
|
+
import { bridgeRoot } from "./protocol.js";
|
|
13
14
|
import { claudePlan, monthlyAnniversary, subscriptionDate } from "./subscription.js";
|
|
14
15
|
export const DEFAULT_ACCOUNT = "default";
|
|
15
16
|
const SLUG = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
@@ -75,6 +76,50 @@ export function claudeHomeOfEnv(value, env = process.env) {
|
|
|
75
76
|
}
|
|
76
77
|
// ── labels (<bridge>/accounts.yaml) ─────────────────────────────────────────
|
|
77
78
|
export const accountsFile = () => path.join(bridgeRoot(), "accounts.yaml");
|
|
79
|
+
/** `accounts.yaml` as an object: empty when there is none (or it is blank), an error when it is there but is
|
|
80
|
+
* not a mapping, so a write never replaces what it couldn't read. */
|
|
81
|
+
export function parseAccountsYaml(text) {
|
|
82
|
+
if (text === undefined || !text.trim())
|
|
83
|
+
return {};
|
|
84
|
+
const parsed = load(text);
|
|
85
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
86
|
+
return parsed;
|
|
87
|
+
throw new Error(`${accountsFile()} is not a mapping; fix or remove it first.`);
|
|
88
|
+
}
|
|
89
|
+
let accountsWrites = Promise.resolve();
|
|
90
|
+
/**
|
|
91
|
+
* The one way `accounts.yaml` is changed (labels, credits, pools): reads it, applies `change`, and writes it back
|
|
92
|
+
* atomically. Writes in this process run one at a time, and each holds the file's lock against other processes
|
|
93
|
+
* (the CLI beside the Hook), so no write drops another's change. A file that can't be read is never replaced.
|
|
94
|
+
*/
|
|
95
|
+
export function updateAccountsFile(change) {
|
|
96
|
+
const run = accountsWrites.then(async () => {
|
|
97
|
+
await mkdir(bridgeRoot(), { recursive: true, mode: 0o700 });
|
|
98
|
+
const file = accountsFile();
|
|
99
|
+
withFileLock(file, () => {
|
|
100
|
+
let text;
|
|
101
|
+
try {
|
|
102
|
+
text = readFileSync(file, "utf8");
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (error.code !== "ENOENT")
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
const parsed = parseAccountsYaml(text);
|
|
109
|
+
change(parsed);
|
|
110
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
111
|
+
try {
|
|
112
|
+
writeFileSync(temporary, dump(parsed), { mode: 0o600, flag: "wx" });
|
|
113
|
+
renameSync(temporary, file);
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
rmSync(temporary, { force: true });
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
accountsWrites = run.catch(() => undefined);
|
|
121
|
+
return run;
|
|
122
|
+
}
|
|
78
123
|
function readLabels() {
|
|
79
124
|
try {
|
|
80
125
|
const parsed = load(readFileSync(accountsFile(), "utf8"));
|
|
@@ -102,17 +147,10 @@ export async function setAccountLabel(id, label) {
|
|
|
102
147
|
const clean = label.trim();
|
|
103
148
|
if (!clean || clean.length > 40 || /[\u0000-\u001f]/.test(clean))
|
|
104
149
|
throw new Error("A label is 1 to 40 printable characters.");
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
parsed = raw;
|
|
110
|
-
}
|
|
111
|
-
catch { /* First label. */ }
|
|
112
|
-
const claude = parsed.claude && typeof parsed.claude === "object" ? parsed.claude : {};
|
|
113
|
-
parsed.claude = { ...claude, [id]: clean };
|
|
114
|
-
await mkdir(bridgeRoot(), { recursive: true, mode: 0o700 });
|
|
115
|
-
await atomic(accountsFile(), dump(parsed), 0o600);
|
|
150
|
+
await updateAccountsFile(parsed => {
|
|
151
|
+
const claude = parsed.claude && typeof parsed.claude === "object" ? parsed.claude : {};
|
|
152
|
+
parsed.claude = { ...claude, [id]: clean };
|
|
153
|
+
});
|
|
116
154
|
}
|
|
117
155
|
const identityCache = new Map();
|
|
118
156
|
function oauthIdentity(configFile) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ClaudeHome } from "./claude-accounts.js";
|
|
2
|
-
import type { UsageWindow } from "./usage.js";
|
|
2
|
+
import type { ApiCredit, UsageWindow } from "./usage.js";
|
|
3
3
|
export interface ClaudeCredit {
|
|
4
4
|
/** Short id derived from the entry, for `--remove`. */
|
|
5
5
|
id: string;
|
|
@@ -26,7 +26,11 @@ export declare function addClaudeCredit(home: string, entry: {
|
|
|
26
26
|
export declare function removeClaudeCredit(home: string, id: string): Promise<boolean>;
|
|
27
27
|
/** Per-session costs from the status line, kept only for homes with a credit. */
|
|
28
28
|
export declare const costLedgerFile: (home: ClaudeHome) => string;
|
|
29
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Record one status-line render or helper run: the session's running total only grows, so the largest seen
|
|
31
|
+
* stands. Writes run one at a time in this process and under the ledger's lock across processes (the status
|
|
32
|
+
* line and the helper tool both write it), so none drops another's session.
|
|
33
|
+
*/
|
|
30
34
|
export declare function recordSessionCost(home: ClaudeHome, payload: unknown, now?: Date): Promise<void>;
|
|
31
35
|
/**
|
|
32
36
|
* Every session cost known for a home: the status-line ledger, plus the
|
|
@@ -41,3 +45,5 @@ export declare function homeSessionCosts(home: ClaudeHome): Record<string, Sessi
|
|
|
41
45
|
* Expired credits are left out. The window's `resetsAt` is the expiry.
|
|
42
46
|
*/
|
|
43
47
|
export declare function creditWindows(credits: readonly ClaudeCredit[], sessions: Record<string, SessionCost>, now?: Date): UsageWindow[];
|
|
48
|
+
/** The credit windows added up: dollars left and the soonest expiry among those with money left. None: undefined. */
|
|
49
|
+
export declare function creditSummary(windows: ReadonlyArray<Pick<UsageWindow, "id" | "usedUSD" | "limitUSD" | "remainingUSD" | "expiresAt">>): ApiCredit | undefined;
|
|
@@ -5,11 +5,12 @@
|
|
|
5
5
|
// The estimate never reads billing; it can drift from the Console's balance.
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
7
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
8
|
-
import { mkdir
|
|
8
|
+
import { mkdir } from "node:fs/promises";
|
|
9
9
|
import path from "node:path";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
10
|
+
import { load } from "js-yaml";
|
|
11
|
+
import { withFileLock } from "../governance/locks.js";
|
|
12
|
+
import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
|
|
13
|
+
import { accountsFile, isAccountSlug, updateAccountsFile } from "./claude-accounts.js";
|
|
13
14
|
const MAX_CREDITS = 16;
|
|
14
15
|
const MAX_SESSIONS = 4000;
|
|
15
16
|
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
@@ -56,23 +57,18 @@ export function claudeCredits(home) {
|
|
|
56
57
|
async function updateCredits(home, change) {
|
|
57
58
|
if (!isAccountSlug(home))
|
|
58
59
|
throw new Error(`"${home}" is not an account name: use lowercase letters, digits and dashes.`);
|
|
59
|
-
let
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
credits
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
parsed.credits = credits;
|
|
72
|
-
if (!Object.keys(credits).length)
|
|
73
|
-
delete parsed.credits;
|
|
74
|
-
await mkdir(bridgeRoot(), { recursive: true, mode: 0o700 });
|
|
75
|
-
await atomic(accountsFile(), dump(parsed), 0o600);
|
|
60
|
+
let next = [];
|
|
61
|
+
await updateAccountsFile(parsed => {
|
|
62
|
+
next = change(creditsOf(parsed, home));
|
|
63
|
+
const credits = { ...object(parsed.credits) };
|
|
64
|
+
if (next.length)
|
|
65
|
+
credits[home] = next;
|
|
66
|
+
else
|
|
67
|
+
delete credits[home];
|
|
68
|
+
parsed.credits = credits;
|
|
69
|
+
if (!Object.keys(credits).length)
|
|
70
|
+
delete parsed.credits;
|
|
71
|
+
});
|
|
76
72
|
return next;
|
|
77
73
|
}
|
|
78
74
|
/** `phren bridge accounts credit <id> --amount <usd> [--expires <date>] [--since <date>] [--label <name>]`. */
|
|
@@ -123,7 +119,12 @@ function readLedger(file) {
|
|
|
123
119
|
return {};
|
|
124
120
|
}
|
|
125
121
|
}
|
|
126
|
-
|
|
122
|
+
let ledgerWrites = Promise.resolve();
|
|
123
|
+
/**
|
|
124
|
+
* Record one status-line render or helper run: the session's running total only grows, so the largest seen
|
|
125
|
+
* stands. Writes run one at a time in this process and under the ledger's lock across processes (the status
|
|
126
|
+
* line and the helper tool both write it), so none drops another's session.
|
|
127
|
+
*/
|
|
127
128
|
export async function recordSessionCost(home, payload, now = new Date()) {
|
|
128
129
|
if (!claudeCredits(home.id).length)
|
|
129
130
|
return;
|
|
@@ -133,13 +134,20 @@ export async function recordSessionCost(home, payload, now = new Date()) {
|
|
|
133
134
|
if (!session || typeof cost !== "number" || !Number.isFinite(cost) || cost < 0 || cost > 100_000)
|
|
134
135
|
return;
|
|
135
136
|
const file = costLedgerFile(home);
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
137
|
+
const run = ledgerWrites.then(async () => {
|
|
138
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
139
|
+
await withFileLock(file, async () => {
|
|
140
|
+
const sessions = readLedger(file);
|
|
141
|
+
const seen = sessions[session];
|
|
142
|
+
if (seen && seen.costUSD >= cost)
|
|
143
|
+
return;
|
|
144
|
+
sessions[session] = { costUSD: cost, startedAt: seen?.startedAt ?? now.toISOString() };
|
|
145
|
+
const kept = Object.entries(sessions).sort(([, a], [, b]) => b.startedAt.localeCompare(a.startedAt)).slice(0, MAX_SESSIONS);
|
|
146
|
+
await atomicInPrivateDir(file, JSON.stringify({ sessions: Object.fromEntries(kept) }));
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
ledgerWrites = run.catch(() => undefined);
|
|
150
|
+
return run;
|
|
143
151
|
}
|
|
144
152
|
/**
|
|
145
153
|
* Every session cost known for a home: the status-line ledger, plus the
|
|
@@ -229,8 +237,21 @@ export function creditWindows(credits, sessions, now = new Date()) {
|
|
|
229
237
|
const usedUSD = round(used.get(credit.id));
|
|
230
238
|
return {
|
|
231
239
|
id: `credit:${credit.id}`, name: `API credit${credit.label ? ` · ${credit.label}` : ""}, estimate`,
|
|
232
|
-
usedUSD, limitUSD: credit.amountUSD,
|
|
233
|
-
|
|
240
|
+
usedUSD, limitUSD: credit.amountUSD, remainingUSD: round(Math.max(0, credit.amountUSD - usedUSD)),
|
|
241
|
+
usedPercent: Math.min(100, Math.round(usedUSD / credit.amountUSD * 100)),
|
|
242
|
+
...(credit.expiresAt ? { resetsAt: credit.expiresAt, expiresAt: credit.expiresAt } : {}), asOf: now.toISOString(),
|
|
234
243
|
};
|
|
235
244
|
});
|
|
236
245
|
}
|
|
246
|
+
/** The credit windows added up: dollars left and the soonest expiry among those with money left. None: undefined. */
|
|
247
|
+
export function creditSummary(windows) {
|
|
248
|
+
const credit = windows.filter(window => window.id.startsWith("credit:") && typeof window.limitUSD === "number" && typeof window.usedUSD === "number");
|
|
249
|
+
if (!credit.length)
|
|
250
|
+
return undefined;
|
|
251
|
+
const round = (value) => Math.round(value * 100) / 100;
|
|
252
|
+
const sum = (pick) => round(credit.reduce((total, window) => total + pick(window), 0));
|
|
253
|
+
const expiresAt = credit.filter(window => window.expiresAt && (window.remainingUSD ?? window.limitUSD - window.usedUSD) > 0)
|
|
254
|
+
.map(window => window.expiresAt).sort()[0];
|
|
255
|
+
return { remainingUSD: sum(window => Math.max(0, window.remainingUSD ?? window.limitUSD - window.usedUSD)), limitUSD: sum(window => window.limitUSD),
|
|
256
|
+
usedUSD: sum(window => window.usedUSD), ...(expiresAt ? { expiresAt } : {}), estimate: true };
|
|
257
|
+
}
|
|
@@ -145,7 +145,8 @@ async function materializeThread(session) {
|
|
|
145
145
|
&& state.turnSignature === turnSignature)
|
|
146
146
|
return file;
|
|
147
147
|
const pending = pendingMessage(history, session);
|
|
148
|
-
const rows =
|
|
148
|
+
const rows = itemRows(history, session);
|
|
149
|
+
const stamps = turnStarts(history, session);
|
|
149
150
|
const lines = [];
|
|
150
151
|
if (fresh) {
|
|
151
152
|
const meta = await threadMeta(session);
|
|
@@ -191,7 +192,8 @@ async function materializeThread(session) {
|
|
|
191
192
|
continue;
|
|
192
193
|
}
|
|
193
194
|
else if (messageRow(item)) {
|
|
194
|
-
const
|
|
195
|
+
const at = rowTime(row, item, stamps);
|
|
196
|
+
const message = { ...messageRow(item), ...(at ? { timestamp: at } : {}) };
|
|
195
197
|
const queued = item.type === "userMessage" && item.status === "queued";
|
|
196
198
|
lines.push(JSON.stringify(queued ? { ...message, phrenQueued: true, phrenQueueKey: queueKey(session, id) } : message));
|
|
197
199
|
// A question the agent asked (delivered async) rides along as the
|
|
@@ -243,6 +245,52 @@ async function materializeThread(session) {
|
|
|
243
245
|
history.close();
|
|
244
246
|
}
|
|
245
247
|
}
|
|
248
|
+
/** The thread's items in order, with when each was created where the store records it (`created_at_ms`, absent
|
|
249
|
+
* from some stores) and its turn. */
|
|
250
|
+
function itemRows(history, session) {
|
|
251
|
+
try {
|
|
252
|
+
return objects(history.prepare("select rollout_ordinal, item_type, item_json, updated_at_ordinal, turn_id, created_at_ms from thread_items where thread_id = ? order by rollout_ordinal limit ?").all(session, MAX_ITEMS));
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
try {
|
|
256
|
+
return objects(history.prepare("select rollout_ordinal, item_type, item_json, updated_at_ordinal, turn_id from thread_items where thread_id = ? order by rollout_ordinal limit ?").all(session, MAX_ITEMS));
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return objects(history.prepare("select rollout_ordinal, item_type, item_json, updated_at_ordinal from thread_items where thread_id = ? order by rollout_ordinal limit ?").all(session, MAX_ITEMS));
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/** When each of the thread's turns started, in milliseconds; empty when the store cannot say. */
|
|
264
|
+
function turnStarts(history, session) {
|
|
265
|
+
const starts = new Map();
|
|
266
|
+
try {
|
|
267
|
+
for (const turn of objects(history.prepare("select turn_id, started_at from thread_turns where thread_id = ?").all(session))) {
|
|
268
|
+
const started = epochMs(turn.started_at);
|
|
269
|
+
if (started)
|
|
270
|
+
starts.set(String(turn.turn_id), started);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
catch { /* no turns table */ }
|
|
274
|
+
return starts;
|
|
275
|
+
}
|
|
276
|
+
/** Seconds or milliseconds since the epoch, as milliseconds; undefined for anything else. */
|
|
277
|
+
function epochMs(value) {
|
|
278
|
+
const number = Number(value);
|
|
279
|
+
if (value === null || value === undefined || !Number.isFinite(number) || number <= 0)
|
|
280
|
+
return undefined;
|
|
281
|
+
return number > 1e12 ? number : number * 1000;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* A materialized row's `timestamp`, as a rollout row carries one: when its item was created. The Hook settles a
|
|
285
|
+
* phone message only from rows stamped after it was typed, so an older identical message (an earlier "yes") is
|
|
286
|
+
* never taken for a new one. A user row the store keeps no creation time for has no stamp: its turn's start
|
|
287
|
+
* would be older than a steer typed during the turn, which the scan would then drop; unstamped, its position
|
|
288
|
+
* after the message's cursor decides, as before. An assistant row falls back to its turn's start.
|
|
289
|
+
*/
|
|
290
|
+
function rowTime(row, item, turns) {
|
|
291
|
+
const at = epochMs(row.created_at_ms) ?? (item.type === "userMessage" || row.turn_id === undefined ? undefined : turns.get(String(row.turn_id)));
|
|
292
|
+
return at ? new Date(at).toISOString() : undefined;
|
|
293
|
+
}
|
|
246
294
|
/** Codex 0.155 stores a child agent's lifecycle as `subAgentActivity` items
|
|
247
295
|
* with camelCase fields; the rollout shape the child tree parses is the
|
|
248
296
|
* `SubAgentActivity` event with snake_case fields. */
|
package/dist/bridge/command.js
CHANGED
|
@@ -18,7 +18,8 @@ import { addPeerFromLink, discoverComputers, linkComputer } from "./link.js";
|
|
|
18
18
|
import { ARCHIVE_MAX_FOLDERS, archiveFinishedFanouts, FANOUTS_ARCHIVE_USAGE, parseFanoutArchiveFlags } from "./fanouts.js";
|
|
19
19
|
import { harnessInventory } from "./harnesses.js";
|
|
20
20
|
import { addClaudeAccount } from "./claude-account-setup.js";
|
|
21
|
-
import { setAccountLabel } from "./claude-accounts.js";
|
|
21
|
+
import { claudeHome, setAccountLabel } from "./claude-accounts.js";
|
|
22
|
+
import { accountPoolsCommand, computerAllowedPools } from "./account-pools.js";
|
|
22
23
|
import { addClaudeCredit, claudeCredits, removeClaudeCredit } from "./claude-credits.js";
|
|
23
24
|
import { ModelCatalog } from "./models.js";
|
|
24
25
|
const CREDIT_USAGE = "Usage: phren bridge accounts credit <id> [--amount <usd> [--expires <yyyy-mm-dd>] [--since <yyyy-mm-dd>] [--label <name>] | --remove <credit>]";
|
|
@@ -43,8 +44,16 @@ export async function runBridge(args, version) {
|
|
|
43
44
|
for (const harness of (await harnessInventory()).harnesses) {
|
|
44
45
|
console.log(`${harness.source}: ${harness.installed ? `installed ${harness.version ?? ""}`.trim() : "not installed"}, ${harness.usable ? "usable" : `not usable (${harness.reason ?? "unknown"})`}`);
|
|
45
46
|
for (const account of harness.accounts ?? [])
|
|
46
|
-
console.log(` ${account.id} ${account.label} ${account.signedIn ? "signed in" : "not signed in"} ${account.usable ? "usable" : `not usable (${account.reason ?? "unknown"})`}${account.plan ? ` plan ${account.plan}` : ""}`);
|
|
47
|
+
console.log(` ${account.id} ${account.label} ${account.signedIn ? "signed in" : "not signed in"} ${account.usable ? "usable" : `not usable (${account.reason ?? "unknown"})`}${account.plan ? ` plan ${account.plan}` : ""}${account.pool ? ` pool ${account.pool}` : ""}${account.role ? ` role ${account.role}` : ""}`);
|
|
47
48
|
}
|
|
49
|
+
const allowed = computerAllowedPools();
|
|
50
|
+
if (allowed)
|
|
51
|
+
console.log(`This computer's accounts work for pools: ${allowed.join(", ")}`);
|
|
52
|
+
}
|
|
53
|
+
else if (args[1] === "pool" || args[1] === "role" || args[1] === "allowed-pools") {
|
|
54
|
+
const { phrenStoreRoot } = await import("./transcripts.js");
|
|
55
|
+
for (const line of await accountPoolsCommand(args.slice(1), phrenStoreRoot, slug => !!claudeHome(slug)))
|
|
56
|
+
console.log(line);
|
|
48
57
|
}
|
|
49
58
|
else if (args[1] === "add" && args[2] && !args[2].startsWith("-")) {
|
|
50
59
|
const at = args.indexOf("--label");
|
|
@@ -78,7 +87,7 @@ export async function runBridge(args, version) {
|
|
|
78
87
|
}
|
|
79
88
|
}
|
|
80
89
|
else
|
|
81
|
-
throw new Error("Usage: phren bridge accounts [add <slug> [--label <name>] | label <id> <label> | credit <id> [--amount <usd> [--expires <date>] [--since <date>] [--label <name>] | --remove <credit>]]");
|
|
90
|
+
throw new Error("Usage: phren bridge accounts [add <slug> [--label <name>] | label <id> <label> | credit <id> [--amount <usd> [--expires <date>] [--since <date>] [--label <name>] | --remove <credit>] | pool <id> <tag>|--clear | role <id> helpers|last-resort|off|--clear | allowed-pools [--project <name>] [<tag>… | --clear]]");
|
|
82
91
|
break;
|
|
83
92
|
}
|
|
84
93
|
case "discover": {
|
|
@@ -51,4 +51,36 @@ export declare function launchContinuation(input: unknown, launch: (data: z.infe
|
|
|
51
51
|
}): Promise<Json>;
|
|
52
52
|
export declare function saveContinuationIntent(input: Json): Promise<void>;
|
|
53
53
|
export declare function continuationIntent(id: string): Promise<Json>;
|
|
54
|
+
/**
|
|
55
|
+
* The whole conversation a summary-by-target move copies to the receiving Hook, beside its intent: the source's
|
|
56
|
+
* prompts and replies, already redacted the way a peer hand-off is. The brief only has room for its newest turns;
|
|
57
|
+
* the receiving launch pulls this through the same intent route, in pages, and puts it in the new agent's brief
|
|
58
|
+
* folder. A Hook that predates it ignores the page parameter and answers with the intent, which has no
|
|
59
|
+
* `conversation`, so either side being older leaves the excerpt alone.
|
|
60
|
+
*/
|
|
61
|
+
export declare const CONVERSATION_LIMIT = 2000000;
|
|
62
|
+
export declare const CONVERSATION_FILE = "conversation.md";
|
|
63
|
+
/** In a summary-by-target brief's opening line, so the receiving launch asks for a copy only for those moves. */
|
|
64
|
+
export declare const CONVERSATION_MARKER = "Phren copied its conversation instead";
|
|
65
|
+
/**
|
|
66
|
+
* Removes the saved conversations no move needs any more, as `done` decides from the move id and the copy's age
|
|
67
|
+
* (the move moved or failed, or it has no record at all), and any older than `maxAgeMs` whatever `done` says.
|
|
68
|
+
* A destination reads a copy only while its launch runs, which is over once the move is moved or failed. A write
|
|
69
|
+
* a crash left behind (`<copy>.<uuid>.tmp`) goes after an hour. Returns the move ids whose copy was removed.
|
|
70
|
+
*/
|
|
71
|
+
export declare function pruneContinuationConversations(done: (id: string, ageMs: number) => boolean | Promise<boolean>, now?: number, maxAgeMs?: number): Promise<string[]>;
|
|
72
|
+
/** How long a copy with no move record (or a write a crash left) is kept: a move in another process records itself first. */
|
|
73
|
+
export declare const ORPHAN_GRACE_MS: number;
|
|
74
|
+
/** Saved once per move: a run of the move that starts again keeps the first copy, which a destination may be part way through reading. */
|
|
75
|
+
export declare function saveContinuationConversation(id: string, text: string): Promise<void>;
|
|
76
|
+
/** One page of the saved conversation from character `offset`, with its whole length and hash to check against. */
|
|
77
|
+
export declare function continuationConversationPage(id: string, offset: number): Promise<Json>;
|
|
78
|
+
/**
|
|
79
|
+
* The receiving side: every page of the source's conversation through `page(offset)`, checked against its length
|
|
80
|
+
* and hash and redacted again here, or undefined when the source has none (an older Hook, a move that never
|
|
81
|
+
* built one) or it does not arrive whole. Never fails the launch: the brief's excerpt stands on its own.
|
|
82
|
+
*/
|
|
83
|
+
export declare function fetchContinuationConversation(page: (offset: number) => Promise<Json>, redact: (text: string) => string): Promise<string | undefined>;
|
|
84
|
+
/** Where the copied conversation is, to tell the new agent; appended only when the brief has room for it. */
|
|
85
|
+
export declare function withConversationPointer(text: string, file: string, limit?: number): string;
|
|
54
86
|
export {};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { lstat, readdir, readFile, rm, stat } from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { atomicInPrivateDir, BridgeError, bridgeRoot } from "./protocol.js";
|
|
@@ -104,3 +104,114 @@ export async function continuationIntent(id) {
|
|
|
104
104
|
throw new BridgeError(404, "No owner-admitted continuation intent is recorded.");
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* The whole conversation a summary-by-target move copies to the receiving Hook, beside its intent: the source's
|
|
109
|
+
* prompts and replies, already redacted the way a peer hand-off is. The brief only has room for its newest turns;
|
|
110
|
+
* the receiving launch pulls this through the same intent route, in pages, and puts it in the new agent's brief
|
|
111
|
+
* folder. A Hook that predates it ignores the page parameter and answers with the intent, which has no
|
|
112
|
+
* `conversation`, so either side being older leaves the excerpt alone.
|
|
113
|
+
*/
|
|
114
|
+
export const CONVERSATION_LIMIT = 2_000_000;
|
|
115
|
+
const CONVERSATION_PAGE = 262_144;
|
|
116
|
+
/** Under the 1 MiB a Hook reads of one peer answer (client.ts), escaped as JSON. */
|
|
117
|
+
const PAGE_BYTES = 900_000;
|
|
118
|
+
const conversationFile = (id) => path.join(bridgeRoot(), "move-intents", `${z.string().uuid().parse(id)}.conversation.md`);
|
|
119
|
+
export const CONVERSATION_FILE = "conversation.md";
|
|
120
|
+
/** In a summary-by-target brief's opening line, so the receiving launch asks for a copy only for those moves. */
|
|
121
|
+
export const CONVERSATION_MARKER = "Phren copied its conversation instead";
|
|
122
|
+
/**
|
|
123
|
+
* Removes the saved conversations no move needs any more, as `done` decides from the move id and the copy's age
|
|
124
|
+
* (the move moved or failed, or it has no record at all), and any older than `maxAgeMs` whatever `done` says.
|
|
125
|
+
* A destination reads a copy only while its launch runs, which is over once the move is moved or failed. A write
|
|
126
|
+
* a crash left behind (`<copy>.<uuid>.tmp`) goes after an hour. Returns the move ids whose copy was removed.
|
|
127
|
+
*/
|
|
128
|
+
export async function pruneContinuationConversations(done, now = Date.now(), maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
|
|
129
|
+
const root = path.join(bridgeRoot(), "move-intents");
|
|
130
|
+
const names = await readdir(root).catch(() => []);
|
|
131
|
+
const removed = [];
|
|
132
|
+
for (const name of names) {
|
|
133
|
+
const match = /^([0-9a-f-]{36})\.conversation\.md(\.[0-9a-f-]{36}\.tmp)?$/i.exec(name);
|
|
134
|
+
if (!match)
|
|
135
|
+
continue;
|
|
136
|
+
const file = path.join(root, name);
|
|
137
|
+
const info = await lstat(file).catch(() => undefined);
|
|
138
|
+
if (!info?.isFile())
|
|
139
|
+
continue;
|
|
140
|
+
const age = now - info.mtimeMs;
|
|
141
|
+
const remove = match[2] ? age > ORPHAN_GRACE_MS : age > maxAgeMs || await done(match[1], age);
|
|
142
|
+
if (remove)
|
|
143
|
+
await rm(file, { force: true }).then(() => { if (!match[2])
|
|
144
|
+
removed.push(match[1]); }, () => undefined);
|
|
145
|
+
}
|
|
146
|
+
return removed;
|
|
147
|
+
}
|
|
148
|
+
/** How long a copy with no move record (or a write a crash left) is kept: a move in another process records itself first. */
|
|
149
|
+
export const ORPHAN_GRACE_MS = 60 * 60 * 1000;
|
|
150
|
+
/** Saved once per move: a run of the move that starts again keeps the first copy, which a destination may be part way through reading. */
|
|
151
|
+
export async function saveContinuationConversation(id, text) {
|
|
152
|
+
if (text.length > CONVERSATION_LIMIT)
|
|
153
|
+
throw new BridgeError(413, "The conversation is too long to copy.");
|
|
154
|
+
if (await stat(conversationFile(id)).catch(() => undefined))
|
|
155
|
+
return;
|
|
156
|
+
await atomicInPrivateDir(conversationFile(id), text);
|
|
157
|
+
}
|
|
158
|
+
/** One page of the saved conversation from character `offset`, with its whole length and hash to check against. */
|
|
159
|
+
export async function continuationConversationPage(id, offset) {
|
|
160
|
+
let text;
|
|
161
|
+
try {
|
|
162
|
+
text = await readFile(conversationFile(id), "utf8");
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
throw new BridgeError(404, "No conversation is recorded for this move.");
|
|
166
|
+
}
|
|
167
|
+
if (!Number.isInteger(offset) || offset < 0 || offset > text.length)
|
|
168
|
+
throw new BridgeError(400, "Invalid conversation offset.");
|
|
169
|
+
let size = Math.min(CONVERSATION_PAGE, text.length - offset);
|
|
170
|
+
// Escaping can grow text several times; a page always fits one answer and always moves forward.
|
|
171
|
+
while (size > 1 && Buffer.byteLength(JSON.stringify(text.slice(offset, offset + size))) > PAGE_BYTES)
|
|
172
|
+
size = Math.floor(size / 2);
|
|
173
|
+
const end = offset + size;
|
|
174
|
+
return { conversation: { text: text.slice(offset, end), offset, next: end < text.length ? end : null, total: text.length,
|
|
175
|
+
sha256: createHash("sha256").update(text).digest("hex") } };
|
|
176
|
+
}
|
|
177
|
+
const pageSchema = z.object({ text: z.string(), offset: z.number().int().nonnegative(), next: z.number().int().positive().nullable(),
|
|
178
|
+
total: z.number().int().nonnegative().max(CONVERSATION_LIMIT), sha256: z.string().regex(/^[0-9a-f]{64}$/) });
|
|
179
|
+
/**
|
|
180
|
+
* The receiving side: every page of the source's conversation through `page(offset)`, checked against its length
|
|
181
|
+
* and hash and redacted again here, or undefined when the source has none (an older Hook, a move that never
|
|
182
|
+
* built one) or it does not arrive whole. Never fails the launch: the brief's excerpt stands on its own.
|
|
183
|
+
*/
|
|
184
|
+
export async function fetchContinuationConversation(page, redact) {
|
|
185
|
+
const parts = [];
|
|
186
|
+
let offset = 0, total, hash;
|
|
187
|
+
for (let pages = 0; pages < 64; pages++) {
|
|
188
|
+
let answer;
|
|
189
|
+
try {
|
|
190
|
+
answer = await page(offset);
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
const parsed = pageSchema.safeParse(answer.conversation);
|
|
196
|
+
if (!parsed.success || parsed.data.offset !== offset)
|
|
197
|
+
return undefined;
|
|
198
|
+
if ((total ??= parsed.data.total) !== parsed.data.total || (hash ??= parsed.data.sha256) !== parsed.data.sha256)
|
|
199
|
+
return undefined;
|
|
200
|
+
parts.push(parsed.data.text);
|
|
201
|
+
offset += parsed.data.text.length;
|
|
202
|
+
if (parsed.data.next === null) {
|
|
203
|
+
const text = parts.join("");
|
|
204
|
+
if (text.length !== total || createHash("sha256").update(text).digest("hex") !== hash)
|
|
205
|
+
return undefined;
|
|
206
|
+
return redact(text);
|
|
207
|
+
}
|
|
208
|
+
if (parsed.data.next !== offset || offset > total)
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
return undefined;
|
|
212
|
+
}
|
|
213
|
+
/** Where the copied conversation is, to tell the new agent; appended only when the brief has room for it. */
|
|
214
|
+
export function withConversationPointer(text, file, limit = 32768) {
|
|
215
|
+
const pointer = `\n\nThe previous agent's conversation, more of it than the excerpt above, is in ${file}. Read what you need of it, from the end back, before you write your hand-off.`;
|
|
216
|
+
return text.length + pointer.length <= limit ? `${text}${pointer}` : text;
|
|
217
|
+
}
|
|
@@ -34,6 +34,28 @@ export async function runDispatch(args) {
|
|
|
34
34
|
console.log(JSON.stringify(await hookRequest("/v1/dispatch/returns", { ...(origin ? { origin } : {}) }), null, 2));
|
|
35
35
|
return 0;
|
|
36
36
|
}
|
|
37
|
+
if (args[0] === "returns" && args.length <= 4 && args.slice(1).every(arg => ["--watch", "--json", "--consume"].includes(arg))) {
|
|
38
|
+
const origin = await terminalPaneFromEnv();
|
|
39
|
+
// The watch peeks (an agent conductor on this Hook still takes its returns) unless told to take them.
|
|
40
|
+
const peek = args.includes("--watch") && !args.includes("--consume");
|
|
41
|
+
const read = async () => {
|
|
42
|
+
const answer = await hookRequest(peek ? "/v1/dispatch/returns?peek=1" : "/v1/dispatch/returns", { ...(origin ? { origin } : {}) });
|
|
43
|
+
return Array.isArray(answer.returns) ? answer.returns : [];
|
|
44
|
+
};
|
|
45
|
+
// `returns --json` is `returns`, whose answer is JSON already.
|
|
46
|
+
if (!args.includes("--watch")) {
|
|
47
|
+
console.log(JSON.stringify({ returns: await read() }, null, 2));
|
|
48
|
+
return 0;
|
|
49
|
+
}
|
|
50
|
+
const { watchReturns } = await import("./dispatch-returns.js");
|
|
51
|
+
const stop = new AbortController();
|
|
52
|
+
// The first Ctrl-C ends the watch after the read in flight (which still prints; with --consume its
|
|
53
|
+
// returns are already marked read); a second one leaves at once.
|
|
54
|
+
process.on("SIGINT", () => { if (stop.signal.aborted)
|
|
55
|
+
process.exit(130); stop.abort(); });
|
|
56
|
+
await watchReturns(read, line => console.log(line), { signal: stop.signal, json: args.includes("--json"), warn: line => console.error(line) });
|
|
57
|
+
return 130;
|
|
58
|
+
}
|
|
37
59
|
if (args[0] === "usage" && args.slice(1).every(arg => arg === "--json")) {
|
|
38
60
|
const { readAccountUsage, formatAccountUsage } = await import("./account-usage.js");
|
|
39
61
|
const view = await readAccountUsage();
|
|
@@ -204,6 +204,29 @@ export declare function observe(receipt: Receipt, value: unknown, now: number, p
|
|
|
204
204
|
export declare function noticeLine(receipts: readonly Receipt[]): string;
|
|
205
205
|
/** What `dispatch_returns` lists for one unread return. */
|
|
206
206
|
export declare function returnRow(receipt: Receipt): Json;
|
|
207
|
+
/** How much of a worker's final reply a watched return line shows. */
|
|
208
|
+
export declare const RETURN_LINE_TAIL = 120;
|
|
209
|
+
/**
|
|
210
|
+
* One return as a terminal line for `phren dispatch returns --watch`: when it landed (local time), the
|
|
211
|
+
* dispatch label, the computer, the state, and a short tail of what it ended with (the final reply, the
|
|
212
|
+
* question it asks, or why it failed or is blocked), on one line.
|
|
213
|
+
*/
|
|
214
|
+
export declare function formatReturnLine(row: Json, timeZone?: string): string;
|
|
215
|
+
/**
|
|
216
|
+
* `phren dispatch returns --watch`: the returns this Hook's DispatchReturns has collected, printed as they
|
|
217
|
+
* land, until `signal` aborts. `read` peeks by default (the unread returns, left unread for an agent
|
|
218
|
+
* conductor), so each return is printed once by its id and version (a worker that returns again after
|
|
219
|
+
* more work is printed again); with `--consume` it takes them as `returns` does. Peers are polled by the
|
|
220
|
+
* Hook alone. `json` prints each return as one JSON object per line. A read that fails is said on `warn`
|
|
221
|
+
* once, until a read works again.
|
|
222
|
+
*/
|
|
223
|
+
export declare function watchReturns(read: () => Promise<Json[]>, print: (line: string) => void, options: {
|
|
224
|
+
signal: AbortSignal;
|
|
225
|
+
json?: boolean;
|
|
226
|
+
intervalMs?: number;
|
|
227
|
+
timeZone?: string;
|
|
228
|
+
warn?: (line: string) => void;
|
|
229
|
+
}): Promise<void>;
|
|
207
230
|
export interface DispatchReturnsOptions {
|
|
208
231
|
/** This Hook's stable identity, for a worker moving back home. */
|
|
209
232
|
localComputer?: {
|
|
@@ -4,6 +4,7 @@ import { prsSchema } from "./return-contract.js";
|
|
|
4
4
|
import { sessionStalls } from "./stalls.js";
|
|
5
5
|
import { execFile } from "node:child_process";
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
7
8
|
import { promisify } from "node:util";
|
|
8
9
|
import { z } from "zod";
|
|
9
10
|
import { logger } from "../logger.js";
|
|
@@ -546,6 +547,62 @@ export function returnRow(receipt) {
|
|
|
546
547
|
...(receipt.continued ? { continued: receipt.continued } : {}), ...(receipt.continues ? { continues: receipt.continues } : {}),
|
|
547
548
|
...(receipt.moves ? { moves: receipt.moves } : {}), ...(receipt.target ? { target: receipt.target } : {}) };
|
|
548
549
|
}
|
|
550
|
+
/** How much of a worker's final reply a watched return line shows. */
|
|
551
|
+
export const RETURN_LINE_TAIL = 120;
|
|
552
|
+
/**
|
|
553
|
+
* One return as a terminal line for `phren dispatch returns --watch`: when it landed (local time), the
|
|
554
|
+
* dispatch label, the computer, the state, and a short tail of what it ended with (the final reply, the
|
|
555
|
+
* question it asks, or why it failed or is blocked), on one line.
|
|
556
|
+
*/
|
|
557
|
+
export function formatReturnLine(row, timeZone) {
|
|
558
|
+
const at = typeof row.at === "string" && Number.isFinite(Date.parse(row.at))
|
|
559
|
+
? new Date(row.at).toLocaleTimeString("en-GB", { hour12: false, ...(timeZone ? { timeZone } : {}) }) : "--:--:--";
|
|
560
|
+
const approval = row.approval && typeof row.approval === "object" ? row.approval : undefined;
|
|
561
|
+
const said = [row.question, row.error, approval ? `waiting on ${String(approval.title ?? approval.tool ?? "an approval")}` : undefined, row.reply]
|
|
562
|
+
.find((value) => typeof value === "string" && value.trim() !== "");
|
|
563
|
+
// A worker's words reach the owner's terminal: no escape sequences (a title, the clipboard, the cursor).
|
|
564
|
+
const flat = (said ?? "").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim();
|
|
565
|
+
// Whole characters, so a cut never splits one.
|
|
566
|
+
const chars = Array.from(flat);
|
|
567
|
+
const tail = chars.length > RETURN_LINE_TAIL ? `…${chars.slice(-(RETURN_LINE_TAIL - 1)).join("")}` : flat;
|
|
568
|
+
return [at, String(row.label ?? row.id ?? "worker"), String(row.computer ?? "?"), String(row.state ?? "?")].join(" ") + (tail ? ` ${tail}` : "");
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* `phren dispatch returns --watch`: the returns this Hook's DispatchReturns has collected, printed as they
|
|
572
|
+
* land, until `signal` aborts. `read` peeks by default (the unread returns, left unread for an agent
|
|
573
|
+
* conductor), so each return is printed once by its id and version (a worker that returns again after
|
|
574
|
+
* more work is printed again); with `--consume` it takes them as `returns` does. Peers are polled by the
|
|
575
|
+
* Hook alone. `json` prints each return as one JSON object per line. A read that fails is said on `warn`
|
|
576
|
+
* once, until a read works again.
|
|
577
|
+
*/
|
|
578
|
+
export async function watchReturns(read, print, options) {
|
|
579
|
+
const interval = options.intervalMs ?? 5_000;
|
|
580
|
+
let failing;
|
|
581
|
+
// The returns already printed that are still unread; one taken by the conductor drops out with its read.
|
|
582
|
+
let printed = new Set();
|
|
583
|
+
const key = (row) => `${String(row.id)}@${String(row.at)}`;
|
|
584
|
+
while (!options.signal.aborted) {
|
|
585
|
+
try {
|
|
586
|
+
const rows = await read();
|
|
587
|
+
if (failing !== undefined) {
|
|
588
|
+
options.warn?.("Phren Hook answers again.");
|
|
589
|
+
failing = undefined;
|
|
590
|
+
}
|
|
591
|
+
for (const row of rows)
|
|
592
|
+
if (!printed.has(key(row)))
|
|
593
|
+
print(options.json ? JSON.stringify(row) : formatReturnLine(row, options.timeZone));
|
|
594
|
+
printed = new Set(rows.map(key));
|
|
595
|
+
}
|
|
596
|
+
catch (error) {
|
|
597
|
+
// A Hook that is restarting answers again on a later read; its first sentence is enough.
|
|
598
|
+
const why = (error instanceof Error ? error.message : String(error)).split(/(?<=\.)\s/)[0];
|
|
599
|
+
if (why !== failing)
|
|
600
|
+
options.warn?.(`Phren Hook did not answer: ${why}`);
|
|
601
|
+
failing = why;
|
|
602
|
+
}
|
|
603
|
+
await sleep(interval, undefined, { signal: options.signal }).catch(() => undefined);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
549
606
|
const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
|
|
550
607
|
/** The same returns to the same origin keep their id on retry. A role
|
|
551
608
|
* hand-over gets a fresh delivery instead of reusing the old chat's receipt. */
|