@phren/cli 0.3.13 → 0.3.15
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-usage.d.ts +2 -1
- package/dist/bridge/account-usage.js +8 -1
- package/dist/bridge/claude-accounts.d.ts +3 -0
- package/dist/bridge/claude-accounts.js +13 -1
- package/dist/bridge/codex-app-server.d.ts +6 -0
- package/dist/bridge/codex-app-server.js +3 -1
- package/dist/bridge/codex-servers.d.ts +25 -1
- package/dist/bridge/codex-servers.js +78 -14
- package/dist/bridge/command.js +1 -1
- package/dist/bridge/conductor-group.d.ts +2 -0
- package/dist/bridge/conductor-group.js +17 -5
- package/dist/bridge/conductor-sets.js +23 -3
- package/dist/bridge/dispatch-command.d.ts +1 -0
- package/dist/bridge/dispatch-command.js +40 -2
- package/dist/bridge/dispatch-returns.d.ts +24 -1
- package/dist/bridge/dispatch-returns.js +125 -12
- package/dist/bridge/dispatch.d.ts +76 -0
- package/dist/bridge/dispatch.js +7 -0
- package/dist/bridge/hand-off-queue.d.ts +3 -0
- package/dist/bridge/hand-off-queue.js +9 -0
- package/dist/bridge/install.d.ts +8 -1
- package/dist/bridge/install.js +44 -5
- package/dist/bridge/owner-inbox-view.d.ts +6 -0
- package/dist/bridge/owner-inbox-view.js +32 -0
- package/dist/bridge/owner-inbox.d.ts +117 -0
- package/dist/bridge/owner-inbox.js +120 -0
- package/dist/bridge/return-contract.d.ts +35 -0
- package/dist/bridge/return-contract.js +10 -0
- package/dist/bridge/server-launch.js +12 -1
- package/dist/bridge/server-routes.d.ts +5 -0
- package/dist/bridge/server-routes.js +22 -1
- package/dist/bridge/server.js +37 -1
- package/dist/bridge/subscription.d.ts +13 -0
- package/dist/bridge/subscription.js +24 -0
- package/dist/bridge/terminal-herdr.js +1 -0
- package/dist/bridge/terminal-tmux.js +1 -0
- package/dist/bridge/terminal.d.ts +1 -0
- package/dist/bridge/terminal.js +1 -0
- package/dist/bridge/usage.d.ts +6 -0
- package/dist/bridge/usage.js +57 -10
- package/dist/bridge/worker-close.d.ts +10 -0
- package/dist/bridge/worker-close.js +77 -0
- package/dist/bridge/worker-reports.d.ts +10 -0
- package/dist/bridge/worker-reports.js +63 -0
- package/dist/bridge-hook.mjs +5158 -4480
- package/dist/cli-registry.js +9 -2
- package/dist/modules/registry.js +5 -5
- package/dist/test-global-setup.js +7 -0
- package/dist/tools/dispatch.js +33 -1
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +35 -0
|
@@ -111,6 +111,7 @@ export interface TerminalProvider {
|
|
|
111
111
|
}): Record<string, string> | undefined;
|
|
112
112
|
focusPane(server: string, pane: string): Promise<void>;
|
|
113
113
|
/** Sets the pane's own label (Herdr's pane label, a tmux pane option), shown by the Hook as the session's name. */
|
|
114
|
+
closePane(server: string, pane: string): Promise<void>;
|
|
114
115
|
renamePane(server: string, pane: string, label: string): Promise<void>;
|
|
115
116
|
/** Focuses, renames or closes a whole tab (when `tab` is set) or workspace. */
|
|
116
117
|
groupAction(server: string, operation: "focus" | "rename" | "close", group: {
|
package/dist/bridge/terminal.js
CHANGED
|
@@ -53,6 +53,7 @@ export const routedTerminal = {
|
|
|
53
53
|
startAgent: (server, pane, agent) => route(server).startAgent(server, pane, agent),
|
|
54
54
|
paneEnv: (server, place) => route(server).paneEnv?.(server, place),
|
|
55
55
|
focusPane: (server, pane) => route(server).focusPane(server, pane),
|
|
56
|
+
closePane: (server, pane) => route(server).closePane(server, pane),
|
|
56
57
|
renamePane: (server, pane, label) => route(server).renamePane(server, pane, label),
|
|
57
58
|
groupAction: (server, operation, group, label) => route(server).groupAction(server, operation, group, label),
|
|
58
59
|
};
|
package/dist/bridge/usage.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { type AccountRef, type ClaudeHome } from "./claude-accounts.js";
|
|
3
|
+
import { type Subscription } from "./subscription.js";
|
|
4
|
+
export type { Subscription } from "./subscription.js";
|
|
3
5
|
export interface UsageWindow {
|
|
4
6
|
id: string;
|
|
5
7
|
name: string;
|
|
@@ -29,6 +31,7 @@ export interface AccountUsage {
|
|
|
29
31
|
updatedAt?: string;
|
|
30
32
|
message?: string;
|
|
31
33
|
spend?: UsageSpend;
|
|
34
|
+
subscription?: Subscription;
|
|
32
35
|
/** Opaque key identity used only to avoid counting one OpenRouter key twice. */
|
|
33
36
|
accountId?: string;
|
|
34
37
|
/** Which Claude report fed this account: the status-line rate_limits payload
|
|
@@ -39,6 +42,9 @@ export interface AccountUsage {
|
|
|
39
42
|
account?: AccountRef;
|
|
40
43
|
}
|
|
41
44
|
export declare function codexUsage(value: unknown, now?: Date): AccountUsage;
|
|
45
|
+
/** Display metadata from the ID token's claims only, never an authentication decision. */
|
|
46
|
+
export declare function codexSubscription(idToken: unknown, now?: Date): Subscription | undefined;
|
|
47
|
+
export declare function readCodexSubscription(file?: string, now?: Date): Promise<Subscription | undefined>;
|
|
42
48
|
/** Parse OpenCode's own cost ledger. `stats --days 7` is a rolling local view. */
|
|
43
49
|
export declare function openCodeUsage(output: string, now?: Date): AccountUsage;
|
|
44
50
|
/** Read the authoritative cost that OpenCode records for its local sessions. */
|
package/dist/bridge/usage.js
CHANGED
|
@@ -3,14 +3,15 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
import { statSync } from "node:fs";
|
|
4
4
|
import { lstat, open, readFile, readdir } from "node:fs/promises";
|
|
5
5
|
import { homedir } from "node:os";
|
|
6
|
-
import { claudeConfigDir } from "../home-paths.js";
|
|
6
|
+
import { claudeConfigDir, codexHome } from "../home-paths.js";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { promisify } from "node:util";
|
|
9
9
|
import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
|
|
10
10
|
import { stripTerminal } from "../terminal-text.js";
|
|
11
11
|
import { codexExecutable } from "./codex-binary.js";
|
|
12
12
|
import { readSpeechKey } from "./speech-key.js";
|
|
13
|
-
import { CODEX_ACCOUNT, claudeAccountEmail, claudeAccountRef, claudeHomeOfEnv, claudeHomes } from "./claude-accounts.js";
|
|
13
|
+
import { CODEX_ACCOUNT, claudeAccountSubscription, claudeAccountEmail, claudeAccountRef, claudeHomeOfEnv, claudeHomes } from "./claude-accounts.js";
|
|
14
|
+
import { planName, subscriptionDate } from "./subscription.js";
|
|
14
15
|
const exec = promisify(execFile);
|
|
15
16
|
/** The status-line snapshot: `usage/claude.json` for the default home, `usage/claude-<id>.json` for others. */
|
|
16
17
|
const claudeFile = (home) => path.join(bridgeRoot(), "usage", home && !home.isDefault ? `claude-${home.id}.json` : "claude.json");
|
|
@@ -49,6 +50,44 @@ export function codexUsage(value, now = new Date()) {
|
|
|
49
50
|
return { source: "codex", windows, updatedAt: now.toISOString(),
|
|
50
51
|
...(!windows.length ? { message: "Codex has not reported account limits. Sign in with your ChatGPT account in Codex on this computer." } : {}) };
|
|
51
52
|
}
|
|
53
|
+
/** Display metadata from the ID token's claims only, never an authentication decision. */
|
|
54
|
+
export function codexSubscription(idToken, now = new Date()) {
|
|
55
|
+
if (typeof idToken !== "string" || idToken.length > 65_536)
|
|
56
|
+
return undefined;
|
|
57
|
+
const parts = idToken.split(".");
|
|
58
|
+
if (parts.length !== 3 || !/^[A-Za-z0-9_-]+$/.test(parts[1]))
|
|
59
|
+
return undefined;
|
|
60
|
+
try {
|
|
61
|
+
const claims = object(JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")));
|
|
62
|
+
const auth = object(claims["https://api.openai.com/auth"]);
|
|
63
|
+
const plan = planName(auth.chatgpt_plan_type);
|
|
64
|
+
if (!plan)
|
|
65
|
+
return undefined;
|
|
66
|
+
const startedAt = subscriptionDate(auth.chatgpt_subscription_active_start);
|
|
67
|
+
const renewsAt = subscriptionDate(auth.chatgpt_subscription_active_until);
|
|
68
|
+
return { plan, ...(startedAt ? { startedAt } : {}), ...(renewsAt ? { renewsAt } : {}), checkedAt: now.toISOString() };
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export async function readCodexSubscription(file = path.join(codexHome(), "auth.json"), now = new Date()) {
|
|
75
|
+
try {
|
|
76
|
+
const handle = await open(file, "r");
|
|
77
|
+
try {
|
|
78
|
+
const stat = await handle.stat();
|
|
79
|
+
if (!stat.isFile() || stat.size > 131_072)
|
|
80
|
+
return undefined;
|
|
81
|
+
return codexSubscription(object(object(JSON.parse(await handle.readFile("utf8"))).tokens).id_token, now);
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
await handle.close();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
52
91
|
/** Parse OpenCode's own cost ledger. `stats --days 7` is a rolling local view. */
|
|
53
92
|
export function openCodeUsage(output, now = new Date()) {
|
|
54
93
|
const plain = stripTerminal(output);
|
|
@@ -224,7 +263,9 @@ export function openCodeGoUsage(windows, refusals, now, hasKey, planError) {
|
|
|
224
263
|
reached.length ? `Go is refusing requests: the ${reached.join(" and ")} limit is reached.` : undefined,
|
|
225
264
|
refused,
|
|
226
265
|
].filter(Boolean).join(" ");
|
|
227
|
-
|
|
266
|
+
const renewsAt = windows.find(w => w.id === "opencode-go:plan:30d")?.resetsAt;
|
|
267
|
+
const subscription = hasKey ? { plan: "Go", ...(renewsAt ? { renewsAt } : {}), checkedAt: now.toISOString() } : undefined;
|
|
268
|
+
return { source: "opencode-go", windows, ...(subscription ? { subscription } : {}), updatedAt: now.toISOString(), ...(message ? { message } : {}) };
|
|
228
269
|
}
|
|
229
270
|
/** The accounts one caller can read: the sources it names, and Go's plan
|
|
230
271
|
* windows only for a caller that asked for them (`goPlan=1`). */
|
|
@@ -299,12 +340,16 @@ async function liveOpenRouterUsage(now) {
|
|
|
299
340
|
export function elevenLabsUsage(value, now = new Date()) {
|
|
300
341
|
const sub = object(value);
|
|
301
342
|
const used = sub.character_count, limit = sub.character_limit;
|
|
343
|
+
const plan = planName(sub.tier);
|
|
344
|
+
const renewsAt = subscriptionDate(object(sub.next_invoice).next_payment_attempt_unix);
|
|
345
|
+
const subscription = plan ? { plan, ...(renewsAt ? { renewsAt } : {}), checkedAt: now.toISOString() } : undefined;
|
|
346
|
+
const metadata = subscription ? { subscription } : {};
|
|
302
347
|
const count = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
|
|
303
348
|
if (!count(used) || !count(limit) || limit === 0) {
|
|
304
|
-
return { source: "elevenlabs", windows: [], updatedAt: now.toISOString(), message: "ElevenLabs did not report a character limit for this key." };
|
|
349
|
+
return { source: "elevenlabs", ...metadata, windows: [], updatedAt: now.toISOString(), message: "ElevenLabs did not report a character limit for this key." };
|
|
305
350
|
}
|
|
306
351
|
const entry = window("elevenlabs:characters", "Characters this period", Math.min(100, Math.round(used / limit * 1000) / 10), sub.next_character_count_reset_unix);
|
|
307
|
-
return { source: "elevenlabs", windows: entry ? [{ ...entry, usedCharacters: used, limitCharacters: limit }] : [], updatedAt: now.toISOString() };
|
|
352
|
+
return { source: "elevenlabs", ...metadata, windows: entry ? [{ ...entry, usedCharacters: used, limitCharacters: limit }] : [], updatedAt: now.toISOString() };
|
|
308
353
|
}
|
|
309
354
|
/** The key the Hook already uses for /v1/speech, sent only to ElevenLabs; the answer carries counts, never the key. */
|
|
310
355
|
export async function fetchElevenLabsUsage(key, fetchImpl = fetch, now = new Date()) {
|
|
@@ -596,9 +641,10 @@ export function copilotUsage(value, now = new Date()) {
|
|
|
596
641
|
continue;
|
|
597
642
|
windows.push({ id: key, name: names[key] ?? key, usedPercent: Math.round((100 - remaining) * 10) / 10, ...(reset ? { resetsAt: reset } : {}) });
|
|
598
643
|
}
|
|
599
|
-
const plan =
|
|
600
|
-
const notes = [
|
|
644
|
+
const plan = planName(result.copilot_plan);
|
|
645
|
+
const notes = [safeText(result.copilot_plan) ? `Plan: ${safeText(result.copilot_plan)}.` : "", unlimited.length ? `Unlimited: ${unlimited.join(", ")}.` : ""].filter(Boolean).join(" ");
|
|
601
646
|
return { source: "copilot", windows, updatedAt: now.toISOString(),
|
|
647
|
+
...(plan ? { subscription: { plan, ...(reset ? { renewsAt: reset } : {}), checkedAt: now.toISOString() } } : {}),
|
|
602
648
|
...(notes || !windows.length ? { message: notes || "GitHub reported no Copilot quotas for this account." } : {}) };
|
|
603
649
|
}
|
|
604
650
|
/** The first GitHub CLI found; the Hook's service PATH may not include Homebrew. */
|
|
@@ -724,10 +770,11 @@ export class AccountUsageReader {
|
|
|
724
770
|
const homes = allAccounts ? claudeHomes() : claudeHomes().slice(0, 1);
|
|
725
771
|
const claudeRow = async (home) => {
|
|
726
772
|
const email = claudeAccountEmail(home);
|
|
727
|
-
|
|
773
|
+
const subscription = claudeAccountSubscription(home, new Date(this.now()));
|
|
774
|
+
return { ...settleClaudeUsage(await this.claude(home), this.now()), ...(subscription ? { subscription } : {}), account: { ...claudeAccountRef(home), ...(email ? { email } : {}) } };
|
|
728
775
|
};
|
|
729
|
-
const [codexValue, claude] = await Promise.all([codex, Promise.all(homes.map(claudeRow))]);
|
|
730
|
-
return [{ ...codexValue, account: CODEX_ACCOUNT }, ...claude];
|
|
776
|
+
const [codexValue, claude, subscription] = await Promise.all([codex, Promise.all(homes.map(claudeRow)), readCodexSubscription(undefined, new Date(this.now()))]);
|
|
777
|
+
return [{ ...codexValue, ...(subscription ? { subscription } : {}), account: CODEX_ACCOUNT }, ...claude];
|
|
731
778
|
}
|
|
732
779
|
/** ElevenLabs is read only when the caller shows it: every read spends a request against the key's quota. */
|
|
733
780
|
async spending(includeCopilot, includeElevenLabs) {
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Json, type Target, type StartingTarget } from "./protocol.js";
|
|
2
|
+
import type { HandOffQueue } from "./hand-off-queue.js";
|
|
3
|
+
type ClosedTarget = Target | StartingTarget;
|
|
4
|
+
export declare function markWorkerClosed(target: ClosedTarget, terminal: string): Promise<void>;
|
|
5
|
+
export declare function intentionallyClosed(target: ClosedTarget): Promise<boolean>;
|
|
6
|
+
export declare function markPaneClosed(server: string, pane: Json): Promise<void>;
|
|
7
|
+
/** Called on the worker's computer only after the sender read the done return.
|
|
8
|
+
* Recheck this exact ended turn and skip any new work, background work or inbox. */
|
|
9
|
+
export declare function closeFinishedWorker(input: unknown, queue?: HandOffQueue): Promise<Json>;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, readFile, rm } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema, startingTargetSchema } from "./protocol.js";
|
|
6
|
+
import { validateTarget, paneChatState } from "./herdr.js";
|
|
7
|
+
import { terminalProvider } from "./terminal.js";
|
|
8
|
+
import { paneTurn, workerStates, workerTurnKey } from "./dispatch-returns.js";
|
|
9
|
+
const closedTargetSchema = z.union([targetSchema, startingTargetSchema]);
|
|
10
|
+
const file = (target) => path.join(bridgeRoot(), "closed-workers", `${createHash("sha256").update(JSON.stringify([target.server, target.workspace, target.tab, target.pane, target.source, "session" in target ? target.session : target.startingToken])).digest("hex")}.json`);
|
|
11
|
+
export async function markWorkerClosed(target, terminal) {
|
|
12
|
+
await atomicInPrivateDir(file(target), { target, terminal, at: new Date().toISOString() });
|
|
13
|
+
}
|
|
14
|
+
export async function intentionallyClosed(target) {
|
|
15
|
+
try {
|
|
16
|
+
const info = await lstat(file(target));
|
|
17
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 4096)
|
|
18
|
+
return false;
|
|
19
|
+
const row = JSON.parse(await readFile(file(target), "utf8"));
|
|
20
|
+
return closedTargetSchema.safeParse(row.target).success;
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
if (error.code !== "ENOENT")
|
|
24
|
+
throw error;
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export async function markPaneClosed(server, pane) {
|
|
29
|
+
const chat = await paneChatState(server, pane);
|
|
30
|
+
const target = closedTargetSchema.safeParse({ server, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id, source: pane.agent,
|
|
31
|
+
...(chat.sessionId ? { session: chat.sessionId } : { starting: true, startingToken: chat.startingToken }) });
|
|
32
|
+
if (target.success)
|
|
33
|
+
await markWorkerClosed(target.data, String(pane.terminal_id));
|
|
34
|
+
// A dispatch may still hold the launch token before its first identity poll.
|
|
35
|
+
const starting = startingTargetSchema.safeParse({ server, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id,
|
|
36
|
+
source: pane.agent, starting: true, startingToken: chat.startingToken });
|
|
37
|
+
if (starting.success)
|
|
38
|
+
await markWorkerClosed(starting.data, String(pane.terminal_id));
|
|
39
|
+
}
|
|
40
|
+
/** Called on the worker's computer only after the sender read the done return.
|
|
41
|
+
* Recheck this exact ended turn and skip any new work, background work or inbox. */
|
|
42
|
+
export async function closeFinishedWorker(input, queue) {
|
|
43
|
+
const data = z.object({ target: targetSchema, turn: z.string().regex(/^[a-f0-9]{16}$/), dispatch: z.string().uuid() }).strict().parse(input);
|
|
44
|
+
if (queue)
|
|
45
|
+
return queue.whenNoPending(data.target, () => closeFinishedWorker(input));
|
|
46
|
+
const { snapshot, findPane } = await import("./herdr.js");
|
|
47
|
+
if (await intentionallyClosed(data.target) && !findPane(await snapshot(data.target.server), data.target))
|
|
48
|
+
return { ok: true, closed: true, replayed: true };
|
|
49
|
+
const pane = await validateTarget(data.target, false, true);
|
|
50
|
+
if (!["idle", "done"].includes(String(pane.agent_status)))
|
|
51
|
+
return { ok: true, closed: false };
|
|
52
|
+
const seen = (await workerStates({ targets: [{ ...data.target, dispatch: data.dispatch }] })).workers[0];
|
|
53
|
+
const turn = workerTurnKey(seen);
|
|
54
|
+
if (!seen.completed || seen.background || seen.error || turn !== data.turn)
|
|
55
|
+
return { ok: true, closed: false };
|
|
56
|
+
// One final fresh binding before the terminal mutation.
|
|
57
|
+
const current = await validateTarget(data.target, false, true);
|
|
58
|
+
if (current.terminal_id !== pane.terminal_id || !["idle", "done"].includes(String(current.agent_status)))
|
|
59
|
+
throw new BridgeError(409, "The worker resumed before it could close.");
|
|
60
|
+
const record = await paneTurn(data.target.server, current, data.target.source);
|
|
61
|
+
if (record?.prompt && (!record.stop || record.stop.seq <= record.prompt.seq || record.terminal !== current.terminal_id
|
|
62
|
+
|| record.session !== data.target.session || workerTurnKey({ endedAt: record.stop.at, stopSeq: record.stop.seq }) !== data.turn))
|
|
63
|
+
return { ok: true, closed: false };
|
|
64
|
+
await markWorkerClosed(data.target, String(pane.terminal_id));
|
|
65
|
+
try {
|
|
66
|
+
await terminalProvider().closePane(data.target.server, data.target.pane);
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
// A refused close must not suppress a later genuine disappearance. Keep
|
|
70
|
+
// the marker on an ambiguous transport failure if the pane is now gone.
|
|
71
|
+
const remaining = await snapshot(data.target.server).catch(() => undefined);
|
|
72
|
+
if (remaining && findPane(remaining, data.target)?.terminal_id === pane.terminal_id)
|
|
73
|
+
await rm(file(data.target), { force: true });
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
return { ok: true, closed: true };
|
|
77
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Json, type Target } from "./protocol.js";
|
|
2
|
+
import type { TurnRecord } from "./turn-records.js";
|
|
3
|
+
import { type Integrator, type PullRequest } from "./return-contract.js";
|
|
4
|
+
export { integratorSchema, prsSchema, pullRequestSchema } from "./return-contract.js";
|
|
5
|
+
/** The worker reports PR evidence to its own Hook, without direct messaging or
|
|
6
|
+
* GitHub comments. Bound to this terminal and submitted turn, not the next one. */
|
|
7
|
+
export declare function reportWorker(input: unknown): Promise<Json>;
|
|
8
|
+
export declare function workerPrs(target: Target, record: TurnRecord): Promise<PullRequest[] | undefined>;
|
|
9
|
+
export declare function readIntegrator(): Promise<Integrator | undefined>;
|
|
10
|
+
export declare function setIntegrator(input: unknown): Promise<Json>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema } from "./protocol.js";
|
|
6
|
+
import { paneIdentity, findPane, snapshot, validateTarget } from "./herdr.js";
|
|
7
|
+
import { originPaneSchema } from "./dispatch.js";
|
|
8
|
+
import { paneTurn } from "./dispatch-returns.js";
|
|
9
|
+
import { integratorSchema, prsSchema, reportText as text } from "./return-contract.js";
|
|
10
|
+
export { integratorSchema, prsSchema, pullRequestSchema } from "./return-contract.js";
|
|
11
|
+
const reportSchema = z.object({ target: targetSchema, terminal: text(200), promptSeq: z.number().int(), prs: prsSchema, at: z.string().datetime() }).strict();
|
|
12
|
+
const key = (target) => createHash("sha256").update(JSON.stringify([target.server, target.workspace, target.tab, target.pane, target.source, target.session])).digest("hex");
|
|
13
|
+
const reportFile = (target) => path.join(bridgeRoot(), "worker-reports", `${key(target)}.json`);
|
|
14
|
+
/** The worker reports PR evidence to its own Hook, without direct messaging or
|
|
15
|
+
* GitHub comments. Bound to this terminal and submitted turn, not the next one. */
|
|
16
|
+
export async function reportWorker(input) {
|
|
17
|
+
const data = z.object({ origin: originPaneSchema, prs: prsSchema }).strict().parse(input);
|
|
18
|
+
const pane = findPane(await snapshot(data.origin.server), data.origin);
|
|
19
|
+
if (!pane)
|
|
20
|
+
throw new BridgeError(409, "The worker pane changed.");
|
|
21
|
+
const session = await paneIdentity(data.origin.server, pane, true);
|
|
22
|
+
const target = targetSchema.parse({ ...data.origin, source: pane.agent, session });
|
|
23
|
+
await validateTarget(target, false, true);
|
|
24
|
+
const record = await paneTurn(target.server, pane, target.source);
|
|
25
|
+
if (!record?.prompt || record.session !== session || record.terminal !== pane.terminal_id)
|
|
26
|
+
throw new BridgeError(409, "The Hook has not recorded this worker's submitted turn yet.");
|
|
27
|
+
await atomicInPrivateDir(reportFile(target), reportSchema.parse({ target, terminal: record.terminal, promptSeq: record.prompt.seq, prs: data.prs, at: new Date().toISOString() }));
|
|
28
|
+
return { ok: true, target, prs: data.prs };
|
|
29
|
+
}
|
|
30
|
+
export async function workerPrs(target, record) {
|
|
31
|
+
try {
|
|
32
|
+
const file = reportFile(target), info = await lstat(file);
|
|
33
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 131072)
|
|
34
|
+
return undefined;
|
|
35
|
+
const report = reportSchema.parse(JSON.parse(await readFile(file, "utf8")));
|
|
36
|
+
return report.terminal === record.terminal && report.promptSeq === record.prompt?.seq ? report.prs : undefined;
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error.code !== "ENOENT")
|
|
40
|
+
throw error;
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export async function readIntegrator() {
|
|
45
|
+
try {
|
|
46
|
+
return integratorSchema.parse(JSON.parse(await readFile(path.join(bridgeRoot(), "integrator.json"), "utf8")));
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (error.code !== "ENOENT")
|
|
50
|
+
throw error;
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export async function setIntegrator(input) {
|
|
55
|
+
if (input === null) {
|
|
56
|
+
const { rm } = await import("node:fs/promises");
|
|
57
|
+
await rm(path.join(bridgeRoot(), "integrator.json"), { force: true });
|
|
58
|
+
return { ok: true, integrator: null };
|
|
59
|
+
}
|
|
60
|
+
const data = integratorSchema.parse(input);
|
|
61
|
+
await atomicInPrivateDir(path.join(bridgeRoot(), "integrator.json"), data);
|
|
62
|
+
return { ok: true, integrator: data };
|
|
63
|
+
}
|