@phren/cli 0.3.10 → 0.3.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/agent-hook-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +5 -0
- package/dist/bridge/agent-hooks.d.ts +159 -5
- package/dist/bridge/agent-hooks.js +663 -49
- package/dist/bridge/approval-summary.d.ts +16 -0
- package/dist/bridge/approval-summary.js +133 -0
- package/dist/bridge/authority-command.d.ts +20 -0
- package/dist/bridge/authority-command.js +120 -0
- package/dist/bridge/authority.d.ts +223 -0
- package/dist/bridge/authority.js +231 -0
- package/dist/bridge/claude-account-setup.d.ts +14 -0
- package/dist/bridge/claude-account-setup.js +69 -0
- package/dist/bridge/claude-accounts.d.ts +49 -0
- package/dist/bridge/claude-accounts.js +195 -0
- package/dist/bridge/code-routes.js +2 -2
- package/dist/bridge/codex-app-server.d.ts +144 -0
- package/dist/bridge/codex-app-server.js +319 -0
- package/dist/bridge/codex-auth-refresh.d.ts +33 -0
- package/dist/bridge/codex-auth-refresh.js +71 -0
- package/dist/bridge/codex-question-reply.d.ts +16 -0
- package/dist/bridge/codex-question-reply.js +57 -0
- package/dist/bridge/codex-review-mode.d.ts +10 -0
- package/dist/bridge/codex-review-mode.js +74 -0
- package/dist/bridge/codex-servers.d.ts +217 -0
- package/dist/bridge/codex-servers.js +636 -0
- package/dist/bridge/command.js +94 -4
- package/dist/bridge/computer-identity.d.ts +75 -0
- package/dist/bridge/computer-identity.js +166 -0
- package/dist/bridge/conductor-group.d.ts +91 -8
- package/dist/bridge/conductor-group.js +105 -9
- package/dist/bridge/conductor-role.d.ts +94 -0
- package/dist/bridge/conductor-role.js +176 -0
- package/dist/bridge/conductor-sets.d.ts +20 -0
- package/dist/bridge/conductor-sets.js +59 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +75 -11
- package/dist/bridge/dispatch-returns.d.ts +123 -19
- package/dist/bridge/dispatch-returns.js +357 -50
- package/dist/bridge/dispatch.d.ts +103 -2
- package/dist/bridge/dispatch.js +272 -40
- package/dist/bridge/fanout-messages.js +2 -2
- package/dist/bridge/fanouts.d.ts +7 -1
- package/dist/bridge/fanouts.js +40 -5
- package/dist/bridge/folder-trust.d.ts +56 -0
- package/dist/bridge/folder-trust.js +195 -0
- package/dist/bridge/grants.d.ts +22 -1
- package/dist/bridge/grants.js +57 -9
- package/dist/bridge/hand-off.d.ts +21 -9
- package/dist/bridge/hand-off.js +58 -45
- package/dist/bridge/harness-status.d.ts +11 -0
- package/dist/bridge/harness-status.js +32 -0
- package/dist/bridge/harnesses.d.ts +39 -0
- package/dist/bridge/harnesses.js +65 -0
- package/dist/bridge/health.d.ts +2 -0
- package/dist/bridge/health.js +1 -1
- package/dist/bridge/herdr.d.ts +11 -2
- package/dist/bridge/herdr.js +98 -23
- package/dist/bridge/hook-fast.d.ts +4 -0
- package/dist/bridge/hook-fast.js +68 -0
- package/dist/bridge/install.d.ts +16 -1
- package/dist/bridge/install.js +88 -21
- package/dist/bridge/launch-brief.d.ts +96 -0
- package/dist/bridge/launch-brief.js +164 -0
- package/dist/bridge/model-switch.d.ts +3 -0
- package/dist/bridge/model-switch.js +17 -1
- package/dist/bridge/models.d.ts +8 -4
- package/dist/bridge/models.js +24 -8
- package/dist/bridge/mux-wire.d.ts +9 -0
- package/dist/bridge/mux-wire.js +19 -0
- package/dist/bridge/opencode-pane-server.d.ts +113 -0
- package/dist/bridge/opencode-pane-server.js +332 -0
- package/dist/bridge/opencode-panes.d.ts +111 -0
- package/dist/bridge/opencode-panes.js +295 -0
- package/dist/bridge/pane-accounts.d.ts +8 -0
- package/dist/bridge/pane-accounts.js +46 -0
- package/dist/bridge/prompt-startup.d.ts +5 -0
- package/dist/bridge/prompt-startup.js +24 -0
- package/dist/bridge/protocol.d.ts +5 -0
- package/dist/bridge/protocol.js +4 -0
- package/dist/bridge/push.d.ts +5 -4
- package/dist/bridge/push.js +6 -4
- package/dist/bridge/questions.d.ts +37 -2
- package/dist/bridge/questions.js +158 -15
- package/dist/bridge/resources.d.ts +125 -0
- package/dist/bridge/resources.js +314 -0
- package/dist/bridge/schedule-format.d.ts +2 -0
- package/dist/bridge/schedule-format.js +3 -0
- package/dist/bridge/schedule-launch.d.ts +2 -1
- package/dist/bridge/schedule-launch.js +23 -53
- package/dist/bridge/schedule-watch.d.ts +10 -1
- package/dist/bridge/schedule-watch.js +54 -2
- package/dist/bridge/server-launch.d.ts +22 -5
- package/dist/bridge/server-launch.js +225 -29
- package/dist/bridge/server-overview.d.ts +8 -2
- package/dist/bridge/server-overview.js +26 -5
- package/dist/bridge/server-pane-routes.d.ts +2 -0
- package/dist/bridge/server-pane-routes.js +145 -15
- package/dist/bridge/server-routes.d.ts +11 -1
- package/dist/bridge/server-routes.js +195 -36
- package/dist/bridge/server-stream.d.ts +2 -0
- package/dist/bridge/server-stream.js +22 -8
- package/dist/bridge/server.d.ts +6 -1
- package/dist/bridge/server.js +47 -12
- package/dist/bridge/session-activity.d.ts +81 -0
- package/dist/bridge/session-activity.js +117 -0
- package/dist/bridge/session-rename.d.ts +48 -0
- package/dist/bridge/session-rename.js +190 -0
- package/dist/bridge/session-servers.js +2 -2
- package/dist/bridge/settings-switch.d.ts +60 -0
- package/dist/bridge/settings-switch.js +287 -0
- package/dist/bridge/speech-voice.d.ts +55 -0
- package/dist/bridge/speech-voice.js +132 -0
- package/dist/bridge/speech.d.ts +70 -11
- package/dist/bridge/speech.js +169 -41
- package/dist/bridge/terminal-herdr.js +9 -3
- package/dist/bridge/terminal-tmux.d.ts +3 -3
- package/dist/bridge/terminal-tmux.js +24 -9
- package/dist/bridge/terminal.d.ts +27 -4
- package/dist/bridge/terminal.js +8 -1
- package/dist/bridge/transcript-claude.js +62 -12
- package/dist/bridge/transcript-codex.d.ts +0 -2
- package/dist/bridge/transcript-codex.js +29 -4
- package/dist/bridge/transcript-preview.d.ts +1 -0
- package/dist/bridge/transcript-preview.js +24 -4
- package/dist/bridge/transcripts.d.ts +15 -2
- package/dist/bridge/transcripts.js +47 -16
- package/dist/bridge/turn-records.d.ts +85 -0
- package/dist/bridge/turn-records.js +143 -0
- package/dist/bridge/uploads.d.ts +3 -0
- package/dist/bridge/uploads.js +14 -0
- package/dist/bridge/usage.d.ts +73 -28
- package/dist/bridge/usage.js +313 -340
- package/dist/bridge-hook.mjs +24624 -18450
- package/dist/cli/claude-unmanaged.d.ts +12 -0
- package/dist/cli/claude-unmanaged.js +105 -0
- package/dist/cli/schedules.js +2 -1
- package/dist/cli/session-start.js +10 -1
- package/dist/cli/session-stop.js +9 -1
- package/dist/cli-registry.d.ts +2 -0
- package/dist/cli-registry.js +37 -5
- package/dist/computers/command.d.ts +6 -0
- package/dist/computers/command.js +152 -0
- package/dist/computers/mcp.d.ts +1 -0
- package/dist/computers/mcp.js +97 -0
- package/dist/computers/read.d.ts +85 -0
- package/dist/computers/read.js +177 -0
- package/dist/data/task-receipts.d.ts +19 -0
- package/dist/data/task-receipts.js +68 -0
- package/dist/data/tasks.js +4 -1
- package/dist/entrypoint.js +10 -0
- package/dist/fanout/adapters/claude.js +15 -2
- package/dist/fanout/adapters/types.d.ts +6 -0
- package/dist/fanout/launcher.d.ts +5 -1
- package/dist/fanout/launcher.js +34 -3
- package/dist/fanout/picker.js +3 -2
- package/dist/fanout/usage.js +1 -1
- package/dist/generated/memory-ui-graph.browser.js +63 -63
- package/dist/graph-core/model.js +24 -3
- package/dist/graph-core/types.d.ts +4 -1
- package/dist/graph-core/types.js +1 -0
- package/dist/init/init-preset.js +7 -3
- package/dist/init/init-uninstall.js +2 -11
- package/dist/init/teardown.d.ts +3 -0
- package/dist/init/teardown.js +47 -0
- package/dist/link/context.js +21 -9
- package/dist/mcp/plugin-mode.js +1 -1
- package/dist/memory-ui-graph.runtime.js +63 -63
- package/dist/modules/code-package.d.ts +1 -0
- package/dist/modules/code-package.js +36 -7
- package/dist/modules/registry.js +14 -13
- package/dist/profile-store.d.ts +6 -0
- package/dist/profile-store.js +25 -1
- package/dist/shell/graph/glyphs.js +4 -0
- package/dist/shell/graph/graph-view.js +2 -0
- package/dist/status.js +7 -1
- package/dist/sync/task-claim.js +3 -2
- package/dist/task/lifecycle.js +25 -4
- package/dist/test-global-setup.js +5 -0
- package/dist/tools/dispatch.js +35 -2
- package/dist/tools/tasks.js +10 -1
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +87 -4
- package/starter/global/skills/conductor/SKILL.md +17 -2
- package/starter/global/skills/fanout/SKILL.md +3 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
import { hookRequest } from "../bridge/client.js";
|
|
3
|
+
/** Every harness the Hook reads usage for, in the order people look for them. */
|
|
4
|
+
export const USAGE_SOURCES = ["claude", "codex", "copilot", "opencode", "opencode-go", "openrouter"];
|
|
5
|
+
export const HARNESS_NAMES = {
|
|
6
|
+
claude: "Claude", codex: "Codex", copilot: "GitHub Copilot",
|
|
7
|
+
opencode: "OpenCode (local spend, any provider incl. DeepSeek)", "opencode-go": "OpenCode Go", openrouter: "OpenRouter",
|
|
8
|
+
};
|
|
9
|
+
const defaultRequest = route => hookRequest(route, undefined, undefined, 30_000);
|
|
10
|
+
function hookMissing(error) {
|
|
11
|
+
const code = error?.code;
|
|
12
|
+
if (code === "ENOENT" || code === "ECONNREFUSED")
|
|
13
|
+
return "Phren Hook is not running on this computer (phren bridge status).";
|
|
14
|
+
if (error?.status === 404)
|
|
15
|
+
return "This computer's Phren Hook predates this report; update it with phren bridge update.";
|
|
16
|
+
return error instanceof Error ? error.message.slice(0, 300) : "Phren Hook did not answer.";
|
|
17
|
+
}
|
|
18
|
+
function computerName(value, fallback) {
|
|
19
|
+
const name = value?.name;
|
|
20
|
+
return typeof name === "string" && name ? name : fallback;
|
|
21
|
+
}
|
|
22
|
+
export async function readComputers(options = {}) {
|
|
23
|
+
const request = options.request ?? defaultRequest;
|
|
24
|
+
let answer;
|
|
25
|
+
try {
|
|
26
|
+
answer = await request(`/v1/resources${options.peers === false ? "" : "?peers=1"}`);
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
const hookError = hookMissing(error);
|
|
30
|
+
// Without a Hook this computer can still report itself; peers need the Hook.
|
|
31
|
+
const fallback = options.localFallback ?? (async () => new (await import("../bridge/resources.js")).ResourceMonitor().read());
|
|
32
|
+
const resources = await fallback().catch(() => undefined);
|
|
33
|
+
return { hookError, computers: [{ name: hostname(), local: true, online: Boolean(resources), ...(resources ? { resources } : { error: hookError }) }] };
|
|
34
|
+
}
|
|
35
|
+
const computers = [{ name: computerName(answer.computer, hostname()), local: true, online: true, resources: answer.resources }];
|
|
36
|
+
for (const peer of Array.isArray(answer.peers) ? answer.peers : []) {
|
|
37
|
+
const name = computerName(peer.computer, String(peer.name ?? "peer"));
|
|
38
|
+
computers.push(peer.resources && !peer.error
|
|
39
|
+
? { name, local: false, online: true, resources: peer.resources }
|
|
40
|
+
: { name, local: false, online: false, error: typeof peer.error === "string" ? peer.error : "Unavailable" });
|
|
41
|
+
}
|
|
42
|
+
return { computers, ...(typeof answer.peerError === "string" ? { peerError: answer.peerError } : {}) };
|
|
43
|
+
}
|
|
44
|
+
export function findComputer(computers, name) {
|
|
45
|
+
if (!name || name === "local" || name === "this")
|
|
46
|
+
return computers.find(c => c.local);
|
|
47
|
+
const wanted = name.toLowerCase().replace(/\.local$/, "");
|
|
48
|
+
return computers.find(c => c.name.toLowerCase().replace(/\.local$/, "") === wanted)
|
|
49
|
+
?? computers.find(c => c.name.toLowerCase().startsWith(wanted));
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The least-loaded online computer: stressed ones last, then by overall
|
|
53
|
+
* pressure, then load per core, then free disk. Each candidate carries why.
|
|
54
|
+
*/
|
|
55
|
+
export function pickComputer(computers, platform = "mac", exclude = []) {
|
|
56
|
+
const skip = new Set(exclude.map(name => name.toLowerCase()));
|
|
57
|
+
const wanted = (r) => platform === "any" || (platform === "mac" ? r.platform === "darwin" : r.platform === platform);
|
|
58
|
+
const candidates = computers.filter(c => c.online && c.resources && wanted(c.resources) && !skip.has(c.name.toLowerCase()));
|
|
59
|
+
const rank = (c) => {
|
|
60
|
+
const r = c.resources;
|
|
61
|
+
return [r.level === "stressed" ? 1 : 0, r.pressure.overall, r.cpu.loadPerCore, -(r.disk?.freeBytes ?? 0)];
|
|
62
|
+
};
|
|
63
|
+
candidates.sort((a, b) => {
|
|
64
|
+
const x = rank(a), y = rank(b);
|
|
65
|
+
for (let i = 0; i < x.length; i++)
|
|
66
|
+
if (x[i] !== y[i])
|
|
67
|
+
return x[i] - y[i];
|
|
68
|
+
return 0;
|
|
69
|
+
});
|
|
70
|
+
const ranked = candidates.map(c => ({ name: c.name, score: c.resources.pressure.overall, level: c.resources.level, why: describe(c.resources) }));
|
|
71
|
+
const pick = candidates[0];
|
|
72
|
+
const label = platform === "mac" ? "Mac" : platform === "linux" ? "Linux computer" : "computer";
|
|
73
|
+
if (!pick)
|
|
74
|
+
return { reason: `No online ${label} reported resources.`, ranked };
|
|
75
|
+
const stressedNote = pick.resources.level === "stressed" ? " Every candidate is stressed; expect slow runs." : "";
|
|
76
|
+
return { pick, reason: `${pick.name} is the least-loaded ${label}: ${describe(pick.resources)}.${stressedNote}`, ranked };
|
|
77
|
+
}
|
|
78
|
+
const GB = 1024 ** 3;
|
|
79
|
+
export function describe(r) {
|
|
80
|
+
const parts = [`load ${r.cpu.load1} on ${r.cpu.cores} cores`];
|
|
81
|
+
if (r.memory.availablePercent !== undefined)
|
|
82
|
+
parts.push(`${r.memory.availablePercent}% memory free`);
|
|
83
|
+
if (r.disk)
|
|
84
|
+
parts.push(`${(r.disk.freeBytes / GB).toFixed(0)} GB disk free`);
|
|
85
|
+
if (r.warnings.length)
|
|
86
|
+
parts.push(`warnings: ${r.warnings.join(", ")}`);
|
|
87
|
+
return parts.join(", ");
|
|
88
|
+
}
|
|
89
|
+
export function resetsIn(resetsAt, now = Date.now()) {
|
|
90
|
+
const at = resetsAt ? Date.parse(resetsAt) : NaN;
|
|
91
|
+
if (!Number.isFinite(at))
|
|
92
|
+
return undefined;
|
|
93
|
+
const minutes = Math.max(0, Math.round((at - now) / 60_000));
|
|
94
|
+
const days = Math.floor(minutes / 1440), hours = Math.floor(minutes % 1440 / 60), rest = minutes % 60;
|
|
95
|
+
return days ? `${days}d ${hours}h` : hours ? `${hours}h ${rest}m` : `${rest}m`;
|
|
96
|
+
}
|
|
97
|
+
function harness(account, now) {
|
|
98
|
+
return { source: account.source, harness: HARNESS_NAMES[account.source] ?? account.source,
|
|
99
|
+
// Only the numbers a person budgets by; no key identity, no origin.
|
|
100
|
+
windows: account.windows.map(({ id, name, usedPercent, usedUSD, limitUSD, usedTokens, resetsAt, asOf }) => {
|
|
101
|
+
const window = { id, name };
|
|
102
|
+
if (usedPercent !== undefined)
|
|
103
|
+
window.usedPercent = usedPercent;
|
|
104
|
+
if (usedUSD !== undefined)
|
|
105
|
+
window.usedUSD = usedUSD;
|
|
106
|
+
if (limitUSD !== undefined)
|
|
107
|
+
window.limitUSD = limitUSD;
|
|
108
|
+
if (usedTokens !== undefined)
|
|
109
|
+
window.usedTokens = usedTokens;
|
|
110
|
+
if (resetsAt) {
|
|
111
|
+
window.resetsAt = resetsAt;
|
|
112
|
+
const left = resetsIn(resetsAt, now);
|
|
113
|
+
if (left)
|
|
114
|
+
window.resetsIn = left;
|
|
115
|
+
}
|
|
116
|
+
if (asOf)
|
|
117
|
+
window.asOf = asOf;
|
|
118
|
+
return window;
|
|
119
|
+
}),
|
|
120
|
+
...(account.spend ? { spend: account.spend } : {}),
|
|
121
|
+
...(account.updatedAt ? { updatedAt: account.updatedAt } : {}),
|
|
122
|
+
...(account.message ? { message: account.message } : !account.windows.length && !account.spend ? { message: "No usage data reported." } : {}) };
|
|
123
|
+
}
|
|
124
|
+
const NOT_REPORTED = "This computer's Hook did not report this harness; it may predate it (phren bridge update).";
|
|
125
|
+
function harnesses(accounts, now) {
|
|
126
|
+
const list = Array.isArray(accounts) ? accounts : [];
|
|
127
|
+
const bySource = new Map(list.map(account => [account.source, account]));
|
|
128
|
+
// Every harness the Hook knows appears, saying so when it had nothing.
|
|
129
|
+
return USAGE_SOURCES.map(source => bySource.get(source) ? harness(bySource.get(source), now)
|
|
130
|
+
: { source, harness: HARNESS_NAMES[source], windows: [], message: source === "openrouter"
|
|
131
|
+
? "No OpenRouter key is configured on this computer." : NOT_REPORTED });
|
|
132
|
+
}
|
|
133
|
+
const fresher = (a, b) => Date.parse(b.updatedAt ?? "") > Date.parse(a.updatedAt ?? "") ? b : a;
|
|
134
|
+
/**
|
|
135
|
+
* Account limits are the same account seen from each computer, so the
|
|
136
|
+
* freshest report with windows stands. OpenCode's cost ledger is per
|
|
137
|
+
* computer, so its spend adds up; OpenRouter's is one key, reported once.
|
|
138
|
+
*/
|
|
139
|
+
export function combineUsage(perComputer) {
|
|
140
|
+
return USAGE_SOURCES.map(source => {
|
|
141
|
+
const reports = perComputer.map(list => list.find(item => item.source === source)).filter((item) => Boolean(item));
|
|
142
|
+
const withData = reports.filter(item => item.windows.length || item.spend);
|
|
143
|
+
// With no numbers anywhere, a Hook's own explanation beats "did not report".
|
|
144
|
+
if (!withData.length)
|
|
145
|
+
return reports.find(item => item.message !== NOT_REPORTED) ?? reports[0] ?? { source, harness: HARNESS_NAMES[source], windows: [], message: "No usage data reported." };
|
|
146
|
+
if (source === "opencode") {
|
|
147
|
+
const spends = withData.filter(item => item.spend);
|
|
148
|
+
const amount = spends.reduce((sum, item) => sum + item.spend.amountUSD, 0);
|
|
149
|
+
return { ...withData.reduce(fresher), ...(spends.length ? { spend: { amountUSD: Math.round(amount * 100) / 100, period: spends[0].spend.period } } : {}),
|
|
150
|
+
message: `Local spend summed across ${spends.length} computer${spends.length === 1 ? "" : "s"}.` };
|
|
151
|
+
}
|
|
152
|
+
const best = withData.filter(item => item.windows.length).reduce((a, b) => a ? fresher(a, b) : b, undefined) ?? withData.reduce(fresher);
|
|
153
|
+
return best;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
export async function readUsage(options = {}) {
|
|
157
|
+
const request = options.request ?? defaultRequest, now = options.now ?? Date.now();
|
|
158
|
+
const query = new URLSearchParams({ sources: USAGE_SOURCES.join(","), goPlan: "1" });
|
|
159
|
+
if (options.peers !== false)
|
|
160
|
+
query.set("peers", "1");
|
|
161
|
+
let answer;
|
|
162
|
+
try {
|
|
163
|
+
answer = await request(`/v1/usage?${query}`);
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
return { hookError: hookMissing(error), computers: [{ name: hostname(), local: true, error: hookMissing(error) }], combined: [] };
|
|
167
|
+
}
|
|
168
|
+
const computers = [{ name: computerName(answer.computer, hostname()), local: true, harnesses: harnesses(answer.accounts, now) }];
|
|
169
|
+
for (const peer of Array.isArray(answer.peers) ? answer.peers : []) {
|
|
170
|
+
const name = computerName(peer.computer, String(peer.name ?? "peer"));
|
|
171
|
+
computers.push(peer.error || !Array.isArray(peer.accounts)
|
|
172
|
+
? { name, local: false, error: typeof peer.error === "string" ? peer.error : "Unavailable" }
|
|
173
|
+
: { name, local: false, harnesses: harnesses(peer.accounts, now) });
|
|
174
|
+
}
|
|
175
|
+
const combined = combineUsage(computers.flatMap(c => c.harnesses ? [c.harnesses] : []));
|
|
176
|
+
return { computers, combined, ...(typeof answer.peerError === "string" ? { peerError: answer.peerError } : {}) };
|
|
177
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { RunStoreGit } from "../sync/store-merge.js";
|
|
2
|
+
export interface TaskWriteReceipt {
|
|
3
|
+
path: string;
|
|
4
|
+
/** A verified commit containing this write, or null if none was observed. */
|
|
5
|
+
commit: string | null;
|
|
6
|
+
}
|
|
7
|
+
/** Scope receipts to one queued mutation, including its asynchronous claim sync. */
|
|
8
|
+
export declare function captureTaskWrites<T>(fn: () => Promise<T>): Promise<{
|
|
9
|
+
result: T;
|
|
10
|
+
write: TaskWriteReceipt | null;
|
|
11
|
+
}>;
|
|
12
|
+
/** Called only after the task file's atomic rename succeeds. */
|
|
13
|
+
export declare function recordTaskWrite(file: string, content: string): void;
|
|
14
|
+
/**
|
|
15
|
+
* Observe commits made by task claim sync without changing when it commits.
|
|
16
|
+
* Keep the autosave's hash even if a later fetch/merge moves HEAD or push fails.
|
|
17
|
+
* Reading HEAD alone would also acknowledge unrelated or failed commits.
|
|
18
|
+
*/
|
|
19
|
+
export declare function trackTaskWriteCommits(git: RunStoreGit): RunStoreGit;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
const writes = new AsyncLocalStorage();
|
|
5
|
+
/** Scope receipts to one queued mutation, including its asynchronous claim sync. */
|
|
6
|
+
export async function captureTaskWrites(fn) {
|
|
7
|
+
const state = {};
|
|
8
|
+
return writes.run(state, async () => ({ result: await fn(), write: state.write?.receipt ?? null }));
|
|
9
|
+
}
|
|
10
|
+
/** Called only after the task file's atomic rename succeeds. */
|
|
11
|
+
export function recordTaskWrite(file, content) {
|
|
12
|
+
const state = writes.getStore();
|
|
13
|
+
if (state)
|
|
14
|
+
state.write = { receipt: { path: path.resolve(file), commit: null }, content };
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Observe commits made by task claim sync without changing when it commits.
|
|
18
|
+
* Keep the autosave's hash even if a later fetch/merge moves HEAD or push fails.
|
|
19
|
+
* Reading HEAD alone would also acknowledge unrelated or failed commits.
|
|
20
|
+
*/
|
|
21
|
+
export function trackTaskWriteCommits(git) {
|
|
22
|
+
return async (cwd, args) => {
|
|
23
|
+
const write = writes.getStore()?.write;
|
|
24
|
+
const committing = args[0] === "commit" || (args[0] === "-c" && args[2] === "commit");
|
|
25
|
+
if (!write || !committing)
|
|
26
|
+
return git(cwd, args);
|
|
27
|
+
let before;
|
|
28
|
+
try {
|
|
29
|
+
before = await git(cwd, ["rev-parse", "--verify", "HEAD"]);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return git(cwd, args);
|
|
33
|
+
}
|
|
34
|
+
const result = await git(cwd, args);
|
|
35
|
+
if (!result.ok)
|
|
36
|
+
return result;
|
|
37
|
+
// Verification is best effort and must never turn a completed write into a failure.
|
|
38
|
+
try {
|
|
39
|
+
const relative = path.relative(path.resolve(cwd), write.receipt.path).split(path.sep).join("/");
|
|
40
|
+
if (relative.startsWith("../") || path.isAbsolute(relative))
|
|
41
|
+
return result;
|
|
42
|
+
const head = await git(cwd, ["rev-list", "--parents", "-n", "1", "HEAD"]);
|
|
43
|
+
if (!head.ok)
|
|
44
|
+
return result;
|
|
45
|
+
const [commit, ...parents] = head.output.trim().split(/\s+/);
|
|
46
|
+
if (!/^[0-9a-f]{40,64}$/.test(commit))
|
|
47
|
+
return result;
|
|
48
|
+
if (before.ok ? parents.length !== 1 || parents[0] !== before.output.trim() : parents.length !== 0)
|
|
49
|
+
return result;
|
|
50
|
+
const tree = await git(cwd, ["ls-tree", commit, "--", relative]);
|
|
51
|
+
const blob = tree.ok && /^\d+ blob ([0-9a-f]+)\t/.exec(tree.output)?.[1];
|
|
52
|
+
if (!blob)
|
|
53
|
+
return result;
|
|
54
|
+
const expected = createHash(blob.length === 64 ? "sha256" : "sha1")
|
|
55
|
+
.update(`blob ${Buffer.byteLength(write.content)}\0`).update(write.content).digest("hex");
|
|
56
|
+
if (blob !== expected)
|
|
57
|
+
return result;
|
|
58
|
+
if (parents.length) {
|
|
59
|
+
const prior = await git(cwd, ["ls-tree", parents[0], "--", relative]);
|
|
60
|
+
if (!prior.ok || /^\d+ blob ([0-9a-f]+)\t/.exec(prior.output)?.[1] === blob)
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
write.receipt.commit = commit;
|
|
64
|
+
}
|
|
65
|
+
catch { /* Leave the receipt uncommitted when verification is unavailable. */ }
|
|
66
|
+
return result;
|
|
67
|
+
};
|
|
68
|
+
}
|
package/dist/data/tasks.js
CHANGED
|
@@ -9,6 +9,7 @@ import { withSafeLock, ensureProject } from "../shared/data-utils.js";
|
|
|
9
9
|
import { getNonPrimaryStores, getStoreProjectDirs } from "../store-registry.js";
|
|
10
10
|
import { storeAwareProjectPath } from "../store-routing.js";
|
|
11
11
|
import { TASKS_FILENAME } from "../filenames.js";
|
|
12
|
+
import { recordTaskWrite } from "./task-receipts.js";
|
|
12
13
|
const ACTIVE_HEADINGS = new Set(["active", "in progress", "in-progress", "current", "wip"]);
|
|
13
14
|
const QUEUE_HEADINGS = new Set(["queue", "queued", "task", "todo", "upcoming", "next"]);
|
|
14
15
|
const DONE_HEADINGS = new Set(["done", "completed", "finished", "archived"]);
|
|
@@ -348,8 +349,10 @@ function taskItemNotFound(project, match) {
|
|
|
348
349
|
}
|
|
349
350
|
function writeTaskDoc(doc) {
|
|
350
351
|
const tmpPath = `${doc.path}.tmp-${randomUUID()}`;
|
|
351
|
-
|
|
352
|
+
const content = renderTask(doc);
|
|
353
|
+
fs.writeFileSync(tmpPath, content);
|
|
352
354
|
fs.renameSync(tmpPath, doc.path);
|
|
355
|
+
recordTaskWrite(doc.path, content);
|
|
353
356
|
}
|
|
354
357
|
function taskArchivePath(phrenPath, project) {
|
|
355
358
|
return path.join(phrenPath, ".config", "task-archive", `${project}.md`);
|
package/dist/entrypoint.js
CHANGED
|
@@ -148,6 +148,16 @@ export async function runTopLevelCommand(argv, opts = {}) {
|
|
|
148
148
|
const cmd = lookupCommand(argvCommand);
|
|
149
149
|
if (!cmd)
|
|
150
150
|
return false;
|
|
151
|
+
// Hook-only commands never find, activate or track a store.
|
|
152
|
+
if (cmd.standalone && !argv.includes("--help") && !argv.includes("-h")) {
|
|
153
|
+
try {
|
|
154
|
+
return finish(await cmd.run(argv.slice(1), buildCliContext()) ?? undefined);
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
console.error(errorMessage(err));
|
|
158
|
+
return finish(1);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
151
161
|
let snapshot;
|
|
152
162
|
try {
|
|
153
163
|
const store = findPhrenPath() ?? defaultPhrenPath();
|
|
@@ -1,7 +1,20 @@
|
|
|
1
1
|
import { uuid } from "./types.js";
|
|
2
|
+
// `claude -p` asks nothing headless: a build worker accepts edits, and a
|
|
3
|
+
// command the brief needs comes through `--extra --allowedTools`. A manifest
|
|
4
|
+
// model of "default" means the configured one, so no --model is passed.
|
|
2
5
|
export const claude = {
|
|
3
6
|
command: "claude",
|
|
4
|
-
argv: o => ["-p", "--output-format", "stream-json", "--verbose", "--model", o.model,
|
|
5
|
-
|
|
7
|
+
argv: o => ["-p", "--output-format", "stream-json", "--verbose", ...(o.model && o.model !== "default" ? ["--model", o.model] : []),
|
|
8
|
+
"--permission-mode", o.review ? "plan" : "acceptEdits", ...(o.resume ? ["--resume", o.resume] : []), ...(o.extra ?? [])],
|
|
6
9
|
session: event => uuid(event.session_id),
|
|
10
|
+
// It exits 0 after refusing a tool; the result row lists what it refused.
|
|
11
|
+
refusal: event => {
|
|
12
|
+
const denials = event.type === "result" && Array.isArray(event.permission_denials) ? event.permission_denials : [];
|
|
13
|
+
const first = denials[0] && typeof denials[0] === "object" ? denials[0] : undefined;
|
|
14
|
+
if (!first)
|
|
15
|
+
return undefined;
|
|
16
|
+
const tool = String(first.tool_name ?? "tool").slice(0, 200), input = (first.tool_input && typeof first.tool_input === "object" ? first.tool_input : {});
|
|
17
|
+
const target = String(input.command ?? input.file_path ?? input.path ?? "").slice(0, 500);
|
|
18
|
+
return { type: "permission", pattern: `${tool} ${target}`.trim(), message: `${denials.length} tool call(s) refused; first: ${tool}` };
|
|
19
|
+
},
|
|
7
20
|
};
|
|
@@ -14,6 +14,12 @@ export interface Adapter {
|
|
|
14
14
|
command: Provider;
|
|
15
15
|
argv(options: LaunchOptions): string[];
|
|
16
16
|
session(event: Record<string, unknown>): string | undefined;
|
|
17
|
+
/** A tool the worker was refused, when the harness reports it in its events. */
|
|
18
|
+
refusal?(event: Record<string, unknown>): {
|
|
19
|
+
type: string;
|
|
20
|
+
pattern: string;
|
|
21
|
+
message: string;
|
|
22
|
+
} | undefined;
|
|
17
23
|
/** A harness that serves an API instead of printing events: the launcher
|
|
18
24
|
* spawns `argv` and this drives the worker, returning its exit code. */
|
|
19
25
|
drive?(child: ChildProcess, options: DriveOptions): Promise<number>;
|
|
@@ -16,8 +16,12 @@ export declare function jobsRoot(store: string): string;
|
|
|
16
16
|
export declare function readJob(store: string, id: string): FanoutManifest;
|
|
17
17
|
export declare function listJobs(store: string): FanoutManifest[];
|
|
18
18
|
export declare function swiftBuildCount(): number;
|
|
19
|
+
/** The nearest codex or claude process above this one. Each agent sets its
|
|
20
|
+
* own id for the commands it runs and inherits the other's, so a Claude
|
|
21
|
+
* started from Codex has both; the process tree says which one launched. */
|
|
22
|
+
export declare function nearestAgent(pid?: number): "codex" | "claude" | undefined;
|
|
19
23
|
export declare function writeManifest(job: string, manifest: FanoutManifest): void;
|
|
20
|
-
export declare function createJob(options: JobOptions, env?: NodeJS.ProcessEnv): {
|
|
24
|
+
export declare function createJob(options: JobOptions, env?: NodeJS.ProcessEnv, nearest?: typeof nearestAgent): {
|
|
21
25
|
job: string;
|
|
22
26
|
manifest: FanoutManifest;
|
|
23
27
|
};
|
package/dist/fanout/launcher.js
CHANGED
|
@@ -39,11 +39,37 @@ export function swiftBuildCount() {
|
|
|
39
39
|
const output = execFileSync("ps", ["-axo", "comm="], { encoding: "utf8", timeout: 5_000 });
|
|
40
40
|
return output.split("\n").filter(line => path.basename(line.trim()) === "xcodebuild").length;
|
|
41
41
|
}
|
|
42
|
+
/** The nearest codex or claude process above this one. Each agent sets its
|
|
43
|
+
* own id for the commands it runs and inherits the other's, so a Claude
|
|
44
|
+
* started from Codex has both; the process tree says which one launched. */
|
|
45
|
+
export function nearestAgent(pid = process.ppid) {
|
|
46
|
+
if (process.platform === "win32")
|
|
47
|
+
return undefined;
|
|
48
|
+
for (let depth = 0; depth < 16 && pid > 1; depth++) {
|
|
49
|
+
let row;
|
|
50
|
+
try {
|
|
51
|
+
row = execFileSync("ps", ["-o", "ppid=,comm=", "-p", String(pid)], { encoding: "utf8", timeout: 2_000 }).trim();
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
const match = /^(\d+)\s+(.+)$/.exec(row);
|
|
57
|
+
if (!match)
|
|
58
|
+
return undefined;
|
|
59
|
+
const name = path.basename(match[2].trim());
|
|
60
|
+
if (name === "claude")
|
|
61
|
+
return "claude";
|
|
62
|
+
if (name === "codex" || name.startsWith("codex-"))
|
|
63
|
+
return "codex";
|
|
64
|
+
pid = Number(match[1]);
|
|
65
|
+
}
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
42
68
|
export function writeManifest(job, manifest) {
|
|
43
69
|
atomicWriteText(path.join(job, "manifest.json"), JSON.stringify(manifestSchema.parse(manifest)) + "\n");
|
|
44
70
|
fs.chmodSync(path.join(job, "manifest.json"), 0o600);
|
|
45
71
|
}
|
|
46
|
-
export function createJob(options, env = process.env) {
|
|
72
|
+
export function createJob(options, env = process.env, nearest = nearestAgent) {
|
|
47
73
|
if (!options.label.trim() || options.label.length > 200)
|
|
48
74
|
throw new Error("Choose a label of 1 to 200 characters.");
|
|
49
75
|
const worktree = fs.realpathSync(options.worktree);
|
|
@@ -53,7 +79,10 @@ export function createJob(options, env = process.env) {
|
|
|
53
79
|
const root = jobsRoot(options.store), job = path.join(root, id);
|
|
54
80
|
fs.mkdirSync(job, { recursive: true, mode: 0o700 });
|
|
55
81
|
fs.chmodSync(root, 0o700);
|
|
56
|
-
const
|
|
82
|
+
const claudeParent = uuid(env.CLAUDE_CODE_SESSION_ID);
|
|
83
|
+
let codexParent = uuid(env.CODEX_THREAD_ID || env.CODEX_SESSION_ID);
|
|
84
|
+
if (codexParent && claudeParent && nearest() === "claude")
|
|
85
|
+
codexParent = undefined;
|
|
57
86
|
const now = new Date().toISOString();
|
|
58
87
|
const manifest = { schemaVersion: 1, id, provider: options.provider, taskLabel: options.label,
|
|
59
88
|
cwd: worktree, worktree, model: options.model, eventLog: "events.jsonl", createdAt: now, startedAt: now, updatedAt: now,
|
|
@@ -77,6 +106,7 @@ export async function launch(options, reservation = createJob(options)) {
|
|
|
77
106
|
stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32",
|
|
78
107
|
});
|
|
79
108
|
let pending = "", stderr = "", cancelled = false;
|
|
109
|
+
let refused;
|
|
80
110
|
const watchdog = new LoopWatchdog();
|
|
81
111
|
const kill = () => { try {
|
|
82
112
|
if (process.platform !== "win32" && child.pid)
|
|
@@ -103,6 +133,7 @@ export async function launch(options, reservation = createJob(options)) {
|
|
|
103
133
|
const event = JSON.parse(line);
|
|
104
134
|
watchdog.observe(event);
|
|
105
135
|
record(adapter.session(event));
|
|
136
|
+
refused ??= adapter.refusal?.(event);
|
|
106
137
|
}
|
|
107
138
|
catch { /* Partial or non-JSON provider output. */ }
|
|
108
139
|
}
|
|
@@ -143,7 +174,7 @@ export async function launch(options, reservation = createJob(options)) {
|
|
|
143
174
|
process.off(signal, cancel);
|
|
144
175
|
fs.closeSync(out);
|
|
145
176
|
fs.closeSync(err);
|
|
146
|
-
const blockedFile = path.join(job, "blocked.json"), refusal = stderrRefusal(stderr);
|
|
177
|
+
const blockedFile = path.join(job, "blocked.json"), refusal = refused ?? stderrRefusal(stderr);
|
|
147
178
|
if (refusal && !fs.existsSync(blockedFile))
|
|
148
179
|
atomicWriteText(blockedFile, JSON.stringify({ ...refusal, at: new Date().toISOString() }));
|
|
149
180
|
const blocked = fs.existsSync(blockedFile);
|
package/dist/fanout/picker.js
CHANGED
|
@@ -39,8 +39,9 @@ export function pick(options) {
|
|
|
39
39
|
const account = options.usage.find(a => a.source === key);
|
|
40
40
|
const model = candidate.model.split("/").slice(1).join("/");
|
|
41
41
|
const windowPrefix = `opencode-go:${model.replace(/[^A-Za-z0-9]+/g, "_").replace(/^_|_$/g, "")}:`;
|
|
42
|
-
|
|
43
|
-
const
|
|
42
|
+
// Go's plan windows (`opencode-go:plan:*`) bind every Go model.
|
|
43
|
+
const windows = account?.windows.filter(w => key !== "opencode-go" || !model || w.id.startsWith("opencode-go:plan:") || w.id.startsWith(windowPrefix) || w.id.startsWith(`${model}/`) || w.id === model) ?? [];
|
|
44
|
+
const exhausted = windows.find(w => (w.limited || (w.usedPercent ?? 0) >= policy.threshold) && (!w.resetsAt || !Number.isFinite(Date.parse(w.resetsAt)) || Date.parse(w.resetsAt) > now));
|
|
44
45
|
if (exhausted) {
|
|
45
46
|
rejected.push(`${key} ${exhausted.name} at ${exhausted.usedPercent} percent`);
|
|
46
47
|
continue;
|
package/dist/fanout/usage.js
CHANGED
|
@@ -5,7 +5,7 @@ import { hookRequest } from "../bridge/client.js";
|
|
|
5
5
|
import { AccountUsageReader } from "../bridge/usage.js";
|
|
6
6
|
export async function readUsage() {
|
|
7
7
|
try {
|
|
8
|
-
const value = await hookRequest("/v1/usage?sources=codex,claude,opencode,opencode-go,openrouter", undefined, undefined, 2_000);
|
|
8
|
+
const value = await hookRequest("/v1/usage?sources=codex,claude,opencode,opencode-go,openrouter&goPlan=1", undefined, undefined, 2_000);
|
|
9
9
|
if (Array.isArray(value.accounts))
|
|
10
10
|
return value.accounts;
|
|
11
11
|
}
|