@phren/cli 0.3.35 → 0.3.37
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/account-choice.d.ts +82 -0
- package/dist/bridge/account-choice.js +173 -0
- package/dist/bridge/account-failover.d.ts +57 -0
- package/dist/bridge/account-failover.js +181 -0
- package/dist/bridge/account-usage.d.ts +2 -0
- package/dist/bridge/account-usage.js +17 -2
- package/dist/bridge/agent-hooks.d.ts +11 -1
- package/dist/bridge/agent-hooks.js +56 -19
- package/dist/bridge/changes.js +18 -9
- package/dist/bridge/dispatch-command.js +3 -1
- package/dist/bridge/dispatch-returns.d.ts +12 -0
- package/dist/bridge/dispatch-returns.js +37 -6
- package/dist/bridge/dispatch.d.ts +31 -3
- package/dist/bridge/dispatch.js +68 -10
- package/dist/bridge/hand-off.d.ts +23 -1
- package/dist/bridge/hand-off.js +36 -3
- package/dist/bridge/health.js +3 -1
- package/dist/bridge/host-key.d.ts +16 -0
- package/dist/bridge/host-key.js +35 -0
- package/dist/bridge/launch-brief.d.ts +5 -0
- package/dist/bridge/launch-brief.js +21 -0
- package/dist/bridge/link.js +11 -4
- package/dist/bridge/owner-inbox-sources.d.ts +5 -0
- package/dist/bridge/owner-inbox-sources.js +94 -0
- package/dist/bridge/owner-inbox-view.js +20 -1
- package/dist/bridge/owner-inbox.d.ts +7 -3
- package/dist/bridge/owner-inbox.js +113 -69
- package/dist/bridge/pair.js +3 -2
- package/dist/bridge/peers.js +4 -2
- package/dist/bridge/schedule-launch.js +5 -1
- package/dist/bridge/schedule-watch.d.ts +3 -0
- package/dist/bridge/schedule-watch.js +27 -1
- package/dist/bridge/server-launch.js +6 -2
- package/dist/bridge/server-routes.js +5 -1
- package/dist/bridge/server.js +9 -23
- package/dist/bridge/sudo.d.ts +36 -6
- package/dist/bridge/sudo.js +180 -37
- package/dist/bridge/usage.d.ts +4 -2
- package/dist/bridge/usage.js +4 -2
- package/dist/bridge/worker-reports.d.ts +8 -1
- package/dist/bridge/worker-reports.js +28 -7
- package/dist/bridge-hook.mjs +7120 -6298
- package/dist/clanker.d.ts +54 -0
- package/dist/clanker.js +188 -0
- package/dist/cli/config.js +56 -0
- package/dist/cli/hooks-output.d.ts +1 -1
- package/dist/cli/hooks-output.js +28 -21
- package/dist/cli/hooks.js +1 -1
- package/dist/cli/namespaces-skills.js +2 -2
- package/dist/cli/namespaces-tasks.js +46 -7
- package/dist/cli/session-start.js +12 -3
- package/dist/cli/session-stop.js +9 -0
- package/dist/cli/team.js +3 -0
- package/dist/cli-handlers.js +7 -0
- package/dist/cli-registry.js +1 -0
- package/dist/data/task-format.d.ts +5 -1
- package/dist/data/task-format.js +13 -5
- package/dist/index.js +82 -50
- package/dist/init/init-configure.d.ts +2 -0
- package/dist/init/init-configure.js +12 -0
- package/dist/init/init-uninstall.js +21 -2
- package/dist/init/init.d.ts +2 -0
- package/dist/init/init.js +11 -3
- package/dist/init/preferences.d.ts +12 -0
- package/dist/init/teardown.js +18 -4
- package/dist/link/doctor.js +2 -2
- package/dist/link/link.js +9 -0
- package/dist/link/refresh.d.ts +10 -0
- package/dist/link/refresh.js +34 -0
- package/dist/mcp/local-index.d.ts +20 -0
- package/dist/mcp/local-index.js +39 -1
- package/dist/modules/registry.js +1 -1
- package/dist/shared/index.d.ts +14 -0
- package/dist/shared/index.js +88 -74
- package/dist/shared/retrieval.js +1 -1
- package/dist/skill/files.js +40 -11
- package/dist/skill/registry.d.ts +6 -0
- package/dist/skill/registry.js +21 -5
- package/dist/task/lifecycle.js +3 -1
- package/dist/tools/dispatch.js +7 -4
- package/dist/tools/finding.js +20 -11
- package/dist/tools/graph.d.ts +2 -0
- package/dist/tools/graph.js +2 -0
- package/dist/tools/search.d.ts +2 -0
- package/dist/tools/search.js +88 -6
- package/dist/tools/tasks.js +45 -0
- package/dist/tools/types.d.ts +3 -1
- package/dist/tools/types.js +3 -2
- package/package.json +1 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { type
|
|
2
|
+
import { type WindowRoom } from "./account-choice.js";
|
|
3
|
+
import { type Json, type Target } from "./protocol.js";
|
|
3
4
|
import { computerLabel, type PeerFacts } from "./computer-identity.js";
|
|
4
5
|
export { computerLabel };
|
|
5
6
|
export declare const handOffSchema: z.ZodObject<{
|
|
@@ -65,7 +66,26 @@ export interface LiveSession {
|
|
|
65
66
|
stalled?: boolean;
|
|
66
67
|
stallFor?: number;
|
|
67
68
|
stalledSince?: string;
|
|
69
|
+
/** A Claude session's account room: its 5-hour and weekly windows. */
|
|
70
|
+
quota?: ClaudeQuota;
|
|
68
71
|
}
|
|
72
|
+
/** One window's room as live_sessions shows it. */
|
|
73
|
+
export type QuotaWindow = WindowRoom & {
|
|
74
|
+
resetsIn?: string;
|
|
75
|
+
};
|
|
76
|
+
export interface ClaudeQuota {
|
|
77
|
+
fiveHour?: QuotaWindow;
|
|
78
|
+
week?: QuotaWindow;
|
|
79
|
+
}
|
|
80
|
+
/** One signed-in Claude account on one computer, with its room. */
|
|
81
|
+
export interface ClaudeAccountRoom extends ClaudeQuota {
|
|
82
|
+
computer: string;
|
|
83
|
+
account: string;
|
|
84
|
+
label?: string;
|
|
85
|
+
email?: string;
|
|
86
|
+
}
|
|
87
|
+
/** Each Claude account's room in one computer's usage answer. */
|
|
88
|
+
export declare function claudeAccountRooms(answer: Json, computer: string, now?: number): ClaudeAccountRoom[];
|
|
69
89
|
/** A registered computer this Hook cannot see, with the other names the store
|
|
70
90
|
* registers it under. */
|
|
71
91
|
export interface NotLinkedComputer {
|
|
@@ -90,6 +110,8 @@ export interface LiveSessions {
|
|
|
90
110
|
/** Registered in the store but not linked in hooks.yaml: unknown, not idle. */
|
|
91
111
|
notLinked: NotLinkedComputer[];
|
|
92
112
|
enrolled: number;
|
|
113
|
+
/** Every signed-in Claude account on each computer that answered, with its 5-hour and weekly room. */
|
|
114
|
+
claudeAccounts?: ClaudeAccountRoom[];
|
|
93
115
|
peerError?: string;
|
|
94
116
|
}
|
|
95
117
|
/** Every live agent the conductor could hand work to: this computer's Herdr
|
package/dist/bridge/hand-off.js
CHANGED
|
@@ -7,6 +7,8 @@ import { hookRequest } from "./client.js";
|
|
|
7
7
|
import { projectName } from "./dispatch.js";
|
|
8
8
|
import { paneProject } from "./approval-summary.js";
|
|
9
9
|
import { isAccountSlug } from "./claude-accounts.js";
|
|
10
|
+
import { accountWindows } from "./account-choice.js";
|
|
11
|
+
import { resetsIn } from "../computers/read.js";
|
|
10
12
|
import { grantLabel, findGrant } from "./grants.js";
|
|
11
13
|
import { hookPeers, optionalHookPeers, peerRequest } from "./peers.js";
|
|
12
14
|
import { BridgeError, errorCode, object, objects, sessionId, targetSchema } from "./protocol.js";
|
|
@@ -117,6 +119,23 @@ export async function handOff(input, options = {}) {
|
|
|
117
119
|
...(result.unsubmitted === true ? { unsubmitted: true } : {}),
|
|
118
120
|
...(label ? { label } : {}), ...(grant ? { granted: grantLabel(grant) } : {}) };
|
|
119
121
|
}
|
|
122
|
+
const CLAUDE_USAGE_ROUTE = "/v1/usage?sources=claude&accounts=all";
|
|
123
|
+
/** Each Claude account's room in one computer's usage answer. */
|
|
124
|
+
export function claudeAccountRooms(answer, computer, now = Date.now()) {
|
|
125
|
+
const window = (room) => {
|
|
126
|
+
if (!room)
|
|
127
|
+
return undefined;
|
|
128
|
+
const until = room.resetsAt ? resetsIn(room.resetsAt, now) : undefined;
|
|
129
|
+
return { ...room, ...(until ? { resetsIn: until } : {}) };
|
|
130
|
+
};
|
|
131
|
+
return objects(answer.accounts).filter(row => row.source === "claude" && Array.isArray(row.windows)).map(row => {
|
|
132
|
+
const usage = row;
|
|
133
|
+
const { fiveHour, week } = accountWindows(usage, now);
|
|
134
|
+
const five = window(fiveHour), seven = window(week);
|
|
135
|
+
return { computer, account: usage.account?.id ?? "default", ...(usage.account?.label ? { label: usage.account.label } : {}),
|
|
136
|
+
...(usage.account?.email ? { email: usage.account.email } : {}), ...(five ? { fiveHour: five } : {}), ...(seven ? { week: seven } : {}) };
|
|
137
|
+
});
|
|
138
|
+
}
|
|
120
139
|
function sessionsFrom(overview, computer, local, now = Date.now()) {
|
|
121
140
|
const sessions = [];
|
|
122
141
|
for (const group of objects(overview.groups))
|
|
@@ -165,7 +184,9 @@ export function notLinkedComputers(store, here, linked) {
|
|
|
165
184
|
export async function listLiveSessions(options = {}) {
|
|
166
185
|
const health = await hookRequest("/v1/health");
|
|
167
186
|
const here = typeof object(health.computer).name === "string" ? String(object(health.computer).name) : "this computer";
|
|
168
|
-
const
|
|
187
|
+
const [overview, localUsage] = await Promise.all([hookRequest("/v1/workspaces"), hookRequest(CLAUDE_USAGE_ROUTE, undefined, undefined, 10_000).catch(() => undefined)]);
|
|
188
|
+
const sessions = sessionsFrom(overview, here, true);
|
|
189
|
+
const claudeAccounts = localUsage ? claudeAccountRooms(localUsage, here) : [];
|
|
169
190
|
const { peers, peerError } = await optionalHookPeers();
|
|
170
191
|
const unreachable = [];
|
|
171
192
|
// Names each peer answers to (its hostname, Bonjour name), so a computer
|
|
@@ -174,8 +195,11 @@ export async function listLiveSessions(options = {}) {
|
|
|
174
195
|
await Promise.all(peers.map(async (peer) => {
|
|
175
196
|
try {
|
|
176
197
|
const route = peer.server && peer.server !== "default" ? `/v1/workspaces?server=${encodeURIComponent(peer.server)}` : "/v1/workspaces";
|
|
177
|
-
const [overview, health] = await Promise.all([peerRequest(peer, route), peerRequest(peer, "/v1/health").catch(() => ({}))
|
|
198
|
+
const [overview, health, usage] = await Promise.all([peerRequest(peer, route), peerRequest(peer, "/v1/health").catch(() => ({})),
|
|
199
|
+
peerRequest(peer, CLAUDE_USAGE_ROUTE, undefined, 10_000).catch(() => undefined)]);
|
|
178
200
|
sessions.push(...sessionsFrom(overview, peer.name, false));
|
|
201
|
+
if (usage)
|
|
202
|
+
claudeAccounts.push(...claudeAccountRooms(usage, peer.name));
|
|
179
203
|
const computer = object(object(health).computer);
|
|
180
204
|
peerNames.set(peer.name, [computer.name, ...(Array.isArray(computer.aliases) ? computer.aliases : [])].filter((name) => typeof name === "string"));
|
|
181
205
|
}
|
|
@@ -186,5 +210,14 @@ export async function listLiveSessions(options = {}) {
|
|
|
186
210
|
}));
|
|
187
211
|
const store = options.store !== undefined ? options.store : findPhrenPath();
|
|
188
212
|
const notLinked = notLinkedFrom(store, here, peers.map(peer => ({ name: peer.name, address: peer.address, names: peerNames.get(peer.name) })));
|
|
189
|
-
|
|
213
|
+
// Each Claude session carries its account's room, so the conductor and phone see how long it can keep working.
|
|
214
|
+
for (const session of sessions) {
|
|
215
|
+
if (session.agent !== "claude")
|
|
216
|
+
continue;
|
|
217
|
+
const room = claudeAccounts.find(item => item.computer === session.computer && item.account === (session.account ?? "default"));
|
|
218
|
+
if (room?.fiveHour || room?.week)
|
|
219
|
+
session.quota = { ...(room.fiveHour ? { fiveHour: room.fiveHour } : {}), ...(room.week ? { week: room.week } : {}) };
|
|
220
|
+
}
|
|
221
|
+
claudeAccounts.sort((a, b) => a.computer.localeCompare(b.computer) || a.account.localeCompare(b.account));
|
|
222
|
+
return { sessions, unreachable, notLinked, enrolled: peers.length, ...(claudeAccounts.length ? { claudeAccounts } : {}), ...(peerError ? { peerError } : {}) };
|
|
190
223
|
}
|
package/dist/bridge/health.js
CHANGED
|
@@ -7,6 +7,7 @@ import { assessSyncOutage, FAILED_PUSH_STATUSES, getRuntimeHealth } from "../gov
|
|
|
7
7
|
import { getProjectDirs } from "../phren-paths.js";
|
|
8
8
|
import { resolveAllStores } from "../store-registry.js";
|
|
9
9
|
import { publicComputerKey } from "./computers.js";
|
|
10
|
+
import { localHostKeyLine } from "./host-key.js";
|
|
10
11
|
import { hookPeers, peerRequest } from "./peers.js";
|
|
11
12
|
import { BridgeError, bridgeRoot, errorCode } from "./protocol.js";
|
|
12
13
|
import { canonicalComputer, latestScheduleBatch, readScheduleDocument, readScheduleRuns, scheduleRunsFile } from "./schedules.js";
|
|
@@ -150,8 +151,9 @@ export async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
|
150
151
|
}
|
|
151
152
|
/** This computer's public SSH host key, the pin a peer's hooks.yaml holds for it. */
|
|
152
153
|
export async function ownHostKey() {
|
|
154
|
+
const line = await localHostKeyLine();
|
|
153
155
|
try {
|
|
154
|
-
return publicComputerKey(
|
|
156
|
+
return line ? publicComputerKey(line) : undefined;
|
|
155
157
|
}
|
|
156
158
|
catch {
|
|
157
159
|
return undefined;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { BridgeError } from "./protocol.js";
|
|
2
|
+
/**
|
|
3
|
+
* Finding a computer's sshd ed25519 host key. sshd keeps it in /etc/ssh on
|
|
4
|
+
* most systems, but Asustor ADM uses /usr/etc/ssh and Homebrew or Entware
|
|
5
|
+
* builds use their own prefix, so ask sshd first and search the usual
|
|
6
|
+
* directories after.
|
|
7
|
+
*/
|
|
8
|
+
export declare const HOST_KEY_DIRS: string[];
|
|
9
|
+
/** A POSIX sh script that prints the first ssh-ed25519 host public key line,
|
|
10
|
+
* from sshd -T's hostkey entries then `dirs`; it prints nothing when there is none. */
|
|
11
|
+
export declare function hostKeyScript(dirs?: string[], sshd?: string): string;
|
|
12
|
+
export declare function noHostKey(where: string, dirs?: string[]): BridgeError;
|
|
13
|
+
/** The first ed25519 host public key line out of hostKeyScript's output. */
|
|
14
|
+
export declare function hostKeyLine(stdout: string): string | undefined;
|
|
15
|
+
/** This computer's ed25519 host public key line, or undefined when it has none. */
|
|
16
|
+
export declare function localHostKeyLine(dirs?: string[], sshd?: string): Promise<string | undefined>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { BridgeError } from "./protocol.js";
|
|
3
|
+
/**
|
|
4
|
+
* Finding a computer's sshd ed25519 host key. sshd keeps it in /etc/ssh on
|
|
5
|
+
* most systems, but Asustor ADM uses /usr/etc/ssh and Homebrew or Entware
|
|
6
|
+
* builds use their own prefix, so ask sshd first and search the usual
|
|
7
|
+
* directories after.
|
|
8
|
+
*/
|
|
9
|
+
export const HOST_KEY_DIRS = ["/etc/ssh", "/usr/etc/ssh", "/usr/local/etc/ssh", "/opt/etc/ssh"];
|
|
10
|
+
const quote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
|
|
11
|
+
/** A POSIX sh script that prints the first ssh-ed25519 host public key line,
|
|
12
|
+
* from sshd -T's hostkey entries then `dirs`; it prints nothing when there is none. */
|
|
13
|
+
export function hostKeyScript(dirs = HOST_KEY_DIRS, sshd = "sshd") {
|
|
14
|
+
const candidates = dirs.map(dir => quote(`${dir}/ssh_host_ed25519_key`)).join(" ");
|
|
15
|
+
return `keys=$( (PATH="$PATH:/usr/sbin:/sbin:/usr/local/sbin:/opt/sbin" ${quote(sshd)} -T 2>/dev/null) | awk '$1 == "hostkey" { print $2 }')
|
|
16
|
+
for k in $keys ${candidates}; do
|
|
17
|
+
[ -r "$k.pub" ] || continue
|
|
18
|
+
line=$(head -n 1 "$k.pub")
|
|
19
|
+
case "$line" in "ssh-ed25519 "*) printf '%s\\n' "$line"; exit 0;; esac
|
|
20
|
+
done
|
|
21
|
+
true`;
|
|
22
|
+
}
|
|
23
|
+
export function noHostKey(where, dirs = HOST_KEY_DIRS) {
|
|
24
|
+
return new BridgeError(409, `${where} has no ssh-ed25519 host key: none in sshd -T's hostkey entries or ${dirs.join(", ")}. Generate one with sudo ssh-keygen -A and restart sshd.`);
|
|
25
|
+
}
|
|
26
|
+
/** The first ed25519 host public key line out of hostKeyScript's output. */
|
|
27
|
+
export function hostKeyLine(stdout) {
|
|
28
|
+
return stdout.split("\n").map(line => line.trim()).find(line => line.startsWith("ssh-ed25519 "));
|
|
29
|
+
}
|
|
30
|
+
/** This computer's ed25519 host public key line, or undefined when it has none. */
|
|
31
|
+
export function localHostKeyLine(dirs, sshd) {
|
|
32
|
+
return new Promise(resolve => {
|
|
33
|
+
execFile("sh", ["-c", hostKeyScript(dirs, sshd)], { timeout: 10_000 }, (error, stdout) => resolve(hostKeyLine(stdout ?? "")));
|
|
34
|
+
});
|
|
35
|
+
}
|
|
@@ -25,6 +25,8 @@ export declare const launchBriefSchema: z.ZodObject<{
|
|
|
25
25
|
export type LaunchBrief = z.infer<typeof launchBriefSchema>;
|
|
26
26
|
/** The variable a launched agent's hooks read its brief id from. */
|
|
27
27
|
export declare const DISPATCH_ID_ENV = "PHREN_DISPATCH_ID";
|
|
28
|
+
/** The dispatch this process's agent was launched for, when its environment names a valid one. */
|
|
29
|
+
export declare function dispatchIdFromEnv(env?: NodeJS.ProcessEnv): string | undefined;
|
|
28
30
|
export declare function briefRoot(): string;
|
|
29
31
|
/** The harnesses whose TUI takes a first prompt as an argument, and the
|
|
30
32
|
* arguments that carry it. Claude reads outside its working directory only
|
|
@@ -49,6 +51,9 @@ export declare function briefLabel(id: string): Promise<string | undefined>;
|
|
|
49
51
|
* it in place left a moment where the folder was there and the file was not.
|
|
50
52
|
*/
|
|
51
53
|
export declare function writeLaunchBrief(brief: LaunchBrief, now?: number, label?: string): Promise<string>;
|
|
54
|
+
/** The text of a brief this computer wrote, for the dispatch that continues its worker on another
|
|
55
|
+
* account (account-failover.ts); undefined once pruned or for an id it never wrote. */
|
|
56
|
+
export declare function readLaunchBrief(id: string): Promise<string | undefined>;
|
|
52
57
|
export declare const arrivalSchema: z.ZodObject<{
|
|
53
58
|
started: z.ZodOptional<z.ZodObject<{
|
|
54
59
|
at: z.ZodString;
|
|
@@ -27,6 +27,11 @@ export const launchBriefSchema = z.object({
|
|
|
27
27
|
}).strict();
|
|
28
28
|
/** The variable a launched agent's hooks read its brief id from. */
|
|
29
29
|
export const DISPATCH_ID_ENV = "PHREN_DISPATCH_ID";
|
|
30
|
+
/** The dispatch this process's agent was launched for, when its environment names a valid one. */
|
|
31
|
+
export function dispatchIdFromEnv(env = process.env) {
|
|
32
|
+
const id = env[DISPATCH_ID_ENV];
|
|
33
|
+
return id && briefId.safeParse(id).success ? id : undefined;
|
|
34
|
+
}
|
|
30
35
|
/** Briefs older than this are removed when the next one is written; a worker
|
|
31
36
|
* may re-read its brief after a compaction, so it is not removed on arrival. */
|
|
32
37
|
const KEEP_MS = 7 * 24 * 60 * 60 * 1000;
|
|
@@ -123,6 +128,22 @@ export async function writeLaunchBrief(brief, now = Date.now(), label) {
|
|
|
123
128
|
}
|
|
124
129
|
return file;
|
|
125
130
|
}
|
|
131
|
+
/** The text of a brief this computer wrote, for the dispatch that continues its worker on another
|
|
132
|
+
* account (account-failover.ts); undefined once pruned or for an id it never wrote. */
|
|
133
|
+
export async function readLaunchBrief(id) {
|
|
134
|
+
if (!briefId.safeParse(id).success)
|
|
135
|
+
return undefined;
|
|
136
|
+
const file = path.join(briefDirectory(id), "brief.md");
|
|
137
|
+
try {
|
|
138
|
+
const info = await lstat(file);
|
|
139
|
+
if (!info.isFile() || info.size > 65_536)
|
|
140
|
+
return undefined;
|
|
141
|
+
return await readFile(file, "utf8");
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
126
147
|
const arrivalEvent = z.object({ at: z.string().datetime(), target: targetSchema }).strict();
|
|
127
148
|
export const arrivalSchema = z.object({ started: arrivalEvent.optional(), accepted: arrivalEvent.optional() }).strict();
|
|
128
149
|
/** What the worker's own hooks have said about its brief: `started` at its
|
package/dist/bridge/link.js
CHANGED
|
@@ -8,6 +8,7 @@ import { findPhrenPath } from "../phren-paths.js";
|
|
|
8
8
|
import { computerLabel } from "./hand-off.js";
|
|
9
9
|
import { localNames } from "./computer-names.js";
|
|
10
10
|
import { acceptComputer, computerName, enrollComputer, publicComputerKey } from "./computers.js";
|
|
11
|
+
import { hostKeyLine, hostKeyScript, localHostKeyLine, noHostKey } from "./host-key.js";
|
|
11
12
|
import { addHookPeer, optionalHookPeers, peerRequest } from "./peers.js";
|
|
12
13
|
import { BridgeError, bridgeRoot, object } from "./protocol.js";
|
|
13
14
|
/**
|
|
@@ -16,8 +17,8 @@ import { BridgeError, bridgeRoot, object } from "./protocol.js";
|
|
|
16
17
|
* linked until the owner runs `phren bridge link <host>`.
|
|
17
18
|
*/
|
|
18
19
|
const exec = promisify(execFile);
|
|
19
|
-
// A non-login ssh shell often lacks Homebrew's node (macOS) or ~/.local/bin.
|
|
20
|
-
const REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"';
|
|
20
|
+
// A non-login ssh shell often lacks Homebrew's node (macOS), Entware's /opt/bin (NAS) or ~/.local/bin.
|
|
21
|
+
const REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/opt/bin:$PATH"';
|
|
21
22
|
const GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
|
|
22
23
|
/** Concrete Host aliases from an ssh config: no patterns, no Git hosting services. */
|
|
23
24
|
export function sshConfigHosts(text) {
|
|
@@ -111,8 +112,14 @@ export async function linkComputer(host, options = {}) {
|
|
|
111
112
|
// The address the Hook dials skips ~/.ssh/config, so resolve the alias the way ssh does.
|
|
112
113
|
const resolved = Object.fromEntries((await exec("ssh", ["-G", "--", host], { timeout: 5_000 })).stdout.split("\n")
|
|
113
114
|
.map(line => line.split(" ")).filter(parts => parts.length >= 2).map(([key, ...rest]) => [key, rest.join(" ")]));
|
|
114
|
-
const
|
|
115
|
-
|
|
115
|
+
const remoteKeyLine = hostKeyLine(await ssh(host, hostKeyScript()));
|
|
116
|
+
if (!remoteKeyLine)
|
|
117
|
+
throw noHostKey(host);
|
|
118
|
+
const localLine = await localHostKeyLine();
|
|
119
|
+
if (!localLine)
|
|
120
|
+
throw noHostKey("This computer");
|
|
121
|
+
const remoteHostKey = publicComputerKey(remoteKeyLine.split(/\s+/).slice(0, 2).join(" "));
|
|
122
|
+
const localHostKey = publicComputerKey(localLine.split(/\s+/).slice(0, 2).join(" "));
|
|
116
123
|
const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
|
|
117
124
|
await ssh(host, `f=$(mktemp) && cat > "$f" && ${REMOTE_PATH} phren bridge enroll-computer ${as} --accept "$f"; s=$?; rm -f "$f"; exit $s`, await enrollComputer(as));
|
|
118
125
|
await acceptComputer(name, remoteLine);
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AgentHooks } from "./agent-hooks.js";
|
|
2
|
+
import { type InboxSnapshot } from "./owner-inbox.js";
|
|
3
|
+
/** Read the actual panes and pending asks, never a stored inbox's live flag.
|
|
4
|
+
* Called on reads and on the Hook's five-second activity tick. */
|
|
5
|
+
export declare function ownerInboxSources(hooks: AgentHooks): Promise<InboxSnapshot>;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { dispatchStatus } from "./dispatch.js";
|
|
2
|
+
import { isLocalComputer } from "./dispatch-hosts.js";
|
|
3
|
+
import { workerReaders, workerStates } from "./dispatch-returns.js";
|
|
4
|
+
import { paneChatState, recentServers, snapshot } from "./herdr.js";
|
|
5
|
+
import { inboxTargetSchema } from "./owner-inbox.js";
|
|
6
|
+
import { hookPeers, peerRequest } from "./peers.js";
|
|
7
|
+
import { ownerQuestion } from "./schedule-watch.js";
|
|
8
|
+
import { objects, object } from "./protocol.js";
|
|
9
|
+
const clean = (text) => String(text).replace(/[\x00-\x1f\x7f]+/g, " ").trim().slice(0, 500);
|
|
10
|
+
/** Read the actual panes and pending asks, never a stored inbox's live flag.
|
|
11
|
+
* Called on reads and on the Hook's five-second activity tick. */
|
|
12
|
+
export async function ownerInboxSources(hooks) {
|
|
13
|
+
const sources = [], unavailableDispatches = [];
|
|
14
|
+
for (const server of await recentServers()) {
|
|
15
|
+
const name = String(server.session), state = await snapshot(name);
|
|
16
|
+
for (const pane of objects(state.panes)) {
|
|
17
|
+
const chat = await paneChatState(name, pane, { tokenWhenIdentified: false });
|
|
18
|
+
const parsed = inboxTargetSchema.safeParse({ server: name, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id, source: pane.agent,
|
|
19
|
+
...(chat.sessionId ? { session: chat.sessionId } : { starting: true, startingToken: chat.startingToken }) });
|
|
20
|
+
if (!parsed.success)
|
|
21
|
+
continue;
|
|
22
|
+
const target = parsed.data, waiting = ["blocked", "waiting"].includes(String(pane.agent_status));
|
|
23
|
+
if ("session" in target) {
|
|
24
|
+
// Refresh terminal-derived questions even with no phone chat open.
|
|
25
|
+
await hooks.syncTerminalDialog(target, waiting);
|
|
26
|
+
if (!waiting)
|
|
27
|
+
hooks.clearTerminalPrompt(target);
|
|
28
|
+
}
|
|
29
|
+
const approval = "session" in target ? hooks.workerApproval(target) : undefined;
|
|
30
|
+
const question = "session" in target ? hooks.servedQuestion(target) : undefined;
|
|
31
|
+
const terminal = waiting && "session" in target ? hooks.terminalPrompt(target) : undefined;
|
|
32
|
+
const request = approval?.request ?? question?.message ?? terminal?.request ?? terminal?.message
|
|
33
|
+
?? (waiting ? `${pane.agent} needs terminal input.` : undefined);
|
|
34
|
+
if (!request)
|
|
35
|
+
continue;
|
|
36
|
+
const actionId = approval?.actionId ?? (typeof question?.actionId === "string" ? question.actionId : undefined);
|
|
37
|
+
sources.push({ source: `prompt:${JSON.stringify(target)}:${actionId ?? "waiting"}`, kind: "blocked", title: clean(request), target,
|
|
38
|
+
...(actionId ? { actionId } : {}) });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
// A saved return/approval is only a candidate: re-observe its worker. In
|
|
42
|
+
// particular a closed pane must not stay live because its last return waits.
|
|
43
|
+
const candidates = (await dispatchStatus()).filter(receipt => !receipt.closedAt && receipt.target
|
|
44
|
+
&& receipt.returned && ["needs-you", "blocked"].includes(receipt.returned.state));
|
|
45
|
+
const groups = new Map();
|
|
46
|
+
for (const receipt of candidates) {
|
|
47
|
+
const computer = isLocalComputer(receipt.computer) ? "local" : receipt.computer;
|
|
48
|
+
groups.set(computer, [...(groups.get(computer) ?? []), receipt]);
|
|
49
|
+
}
|
|
50
|
+
const peers = groups.size && [...groups.keys()].some(name => name !== "local") ? await hookPeers() : [];
|
|
51
|
+
for (const [computer, receipts] of groups) {
|
|
52
|
+
for (let offset = 0; offset < receipts.length; offset += 64) {
|
|
53
|
+
const batch = receipts.slice(offset, offset + 64);
|
|
54
|
+
const input = { targets: batch.map(receipt => ({ ...receipt.target, dispatch: receipt.id })) };
|
|
55
|
+
let workers;
|
|
56
|
+
try {
|
|
57
|
+
const peer = peers.find(peer => peer.name === computer);
|
|
58
|
+
const result = computer === "local"
|
|
59
|
+
? await workerStates(input, { ...workerReaders(target => hooks.workerApproval(target)), snapshot })
|
|
60
|
+
: peer ? await peerRequest(peer, "/v1/dispatch/workers", input) : undefined;
|
|
61
|
+
workers = objects(result?.workers);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
workers = [];
|
|
65
|
+
}
|
|
66
|
+
for (const [index, receipt] of batch.entries()) {
|
|
67
|
+
const seen = workers[index];
|
|
68
|
+
if (!seen || ["unavailable", "unknown"].includes(String(seen.state))) {
|
|
69
|
+
unavailableDispatches.push(receipt.id);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (["gone", "closed"].includes(String(seen.state)))
|
|
73
|
+
continue;
|
|
74
|
+
const approval = object(seen.approval);
|
|
75
|
+
const actionId = typeof approval.actionId === "string" ? approval.actionId : undefined;
|
|
76
|
+
const question = ["idle", "done"].includes(String(seen.state)) && seen.completed && !seen.error && !seen.interrupted
|
|
77
|
+
? (typeof seen.reply === "string" ? ownerQuestion(seen.reply) : undefined) ?? seen.unfinished : undefined;
|
|
78
|
+
if (!actionId && seen.state !== "blocked" && !question)
|
|
79
|
+
continue;
|
|
80
|
+
const source = { source: `dispatch:${receipt.id}:${actionId ?? "waiting"}`, kind: actionId || seen.state === "blocked" ? "blocked" : "needs-you",
|
|
81
|
+
title: clean(approval.request ?? question ?? `${receipt.label} needs input`),
|
|
82
|
+
project: receipt.project, ...(computer !== "local" ? { computer } : {}), target: receipt.target, dispatch: receipt.id,
|
|
83
|
+
...(actionId ? { actionId } : {}) };
|
|
84
|
+
// The local prompt and dispatch return describe the same wait. Keep
|
|
85
|
+
// the dispatch's project/receipt metadata as well as its live target.
|
|
86
|
+
const local = sources.findIndex(row => JSON.stringify(row.target) === JSON.stringify(source.target) && !row.computer);
|
|
87
|
+
if (computer === "local" && local >= 0)
|
|
88
|
+
sources.splice(local, 1);
|
|
89
|
+
sources.push(source);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return { sources, unavailableDispatches };
|
|
94
|
+
}
|
|
@@ -28,5 +28,24 @@ export async function ownerInboxView(inbox, input, localOnly = false) {
|
|
|
28
28
|
unreachable.push({ computer: peer.name, error: error instanceof Error ? error.message : "Unreachable." });
|
|
29
29
|
}
|
|
30
30
|
}));
|
|
31
|
-
|
|
31
|
+
// Older peers can still send stale automatic rows during a rolling upgrade.
|
|
32
|
+
// A dispatching Hook and the worker's Hook may also describe the same ask.
|
|
33
|
+
const seen = new Set();
|
|
34
|
+
const current = items.filter(item => {
|
|
35
|
+
if (data.includeResolved || item.kind === "manual")
|
|
36
|
+
return true;
|
|
37
|
+
if (item.live !== true || item.state !== "open")
|
|
38
|
+
return false;
|
|
39
|
+
const t = item.target;
|
|
40
|
+
if (!t)
|
|
41
|
+
return true;
|
|
42
|
+
const computer = String(item.computer ?? item.inboxComputer);
|
|
43
|
+
const key = JSON.stringify([isLocalComputer(computer) ? "local" : computer, t.server, t.workspace, t.tab, t.pane,
|
|
44
|
+
t.source, t.session ?? t.startingToken, item.actionId ?? "waiting"]);
|
|
45
|
+
if (seen.has(key))
|
|
46
|
+
return false;
|
|
47
|
+
seen.add(key);
|
|
48
|
+
return true;
|
|
49
|
+
});
|
|
50
|
+
return { ok: true, items: current, unreachable };
|
|
32
51
|
}
|
|
@@ -103,13 +103,17 @@ export interface InboxSource {
|
|
|
103
103
|
dispatch?: string;
|
|
104
104
|
actionId?: string;
|
|
105
105
|
}
|
|
106
|
-
|
|
107
|
-
|
|
106
|
+
export interface InboxSnapshot {
|
|
107
|
+
sources: InboxSource[];
|
|
108
|
+
unavailableDispatches?: string[];
|
|
109
|
+
}
|
|
110
|
+
/** Reconcile automatic work against current sources; manual work is owner-owned.
|
|
111
|
+
* The first reconciliation also migrates old stale/duplicate automatic rows. */
|
|
108
112
|
export declare class OwnerInbox {
|
|
109
113
|
private readonly sources;
|
|
110
114
|
private readonly file;
|
|
111
115
|
private pending;
|
|
112
|
-
constructor(sources?: () => Promise<InboxSource[]>, file?: string);
|
|
116
|
+
constructor(sources?: () => Promise<InboxSource[] | InboxSnapshot>, file?: string);
|
|
113
117
|
private read;
|
|
114
118
|
run(input: unknown): Promise<Json>;
|
|
115
119
|
tick(): Promise<void>;
|