@phren/cli 0.2.15 → 0.2.16
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 +2 -2
- package/dist/agent-instructions.d.ts +12 -0
- package/dist/agent-instructions.js +52 -0
- package/dist/bridge/agent-hook-stores.d.ts +32 -0
- package/dist/bridge/agent-hook-stores.js +67 -0
- package/dist/bridge/agent-hooks.d.ts +193 -2
- package/dist/bridge/agent-hooks.js +1045 -38
- package/dist/bridge/canary.d.ts +27 -0
- package/dist/bridge/canary.js +189 -0
- package/dist/bridge/changes.d.ts +57 -0
- package/dist/bridge/changes.js +403 -0
- package/dist/bridge/client.d.ts +3 -0
- package/dist/bridge/client.js +36 -0
- package/dist/bridge/code-note.d.ts +22 -0
- package/dist/bridge/code-note.js +42 -0
- package/dist/bridge/code-routes.d.ts +133 -0
- package/dist/bridge/code-routes.js +319 -0
- package/dist/bridge/codex-threads.d.ts +27 -0
- package/dist/bridge/codex-threads.js +442 -0
- package/dist/bridge/command.d.ts +7 -0
- package/dist/bridge/command.js +50 -5
- package/dist/bridge/computer-names.d.ts +4 -0
- package/dist/bridge/computer-names.js +16 -0
- package/dist/bridge/computers.d.ts +9 -0
- package/dist/bridge/computers.js +111 -0
- package/dist/bridge/context.d.ts +14 -0
- package/dist/bridge/context.js +149 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +93 -0
- package/dist/bridge/dispatch-hosts.d.ts +23 -0
- package/dist/bridge/dispatch-hosts.js +25 -0
- package/dist/bridge/dispatch-returns.d.ts +123 -0
- package/dist/bridge/dispatch-returns.js +279 -0
- package/dist/bridge/dispatch-tree.d.ts +54 -0
- package/dist/bridge/dispatch-tree.js +198 -0
- package/dist/bridge/dispatch.d.ts +207 -0
- package/dist/bridge/dispatch.js +261 -0
- package/dist/bridge/enroll.d.ts +31 -0
- package/dist/bridge/enroll.js +236 -0
- package/dist/bridge/fanout-messages.d.ts +74 -0
- package/dist/bridge/fanout-messages.js +230 -0
- package/dist/bridge/fanouts.d.ts +160 -0
- package/dist/bridge/fanouts.js +702 -0
- package/dist/bridge/file-range.d.ts +16 -0
- package/dist/bridge/file-range.js +90 -0
- package/dist/bridge/files.d.ts +20 -0
- package/dist/bridge/files.js +54 -0
- package/dist/bridge/git-publish.d.ts +23 -0
- package/dist/bridge/git-publish.js +145 -0
- package/dist/bridge/git-worktrees.d.ts +21 -0
- package/dist/bridge/git-worktrees.js +150 -0
- package/dist/bridge/git.d.ts +54 -0
- package/dist/bridge/git.js +552 -0
- package/dist/bridge/grants.d.ts +31 -0
- package/dist/bridge/grants.js +181 -0
- package/dist/bridge/hand-off.d.ts +79 -0
- package/dist/bridge/hand-off.js +151 -0
- package/dist/bridge/health.d.ts +128 -0
- package/dist/bridge/health.js +260 -0
- package/dist/bridge/herdr.d.ts +79 -6
- package/dist/bridge/herdr.js +292 -27
- package/dist/bridge/hook-main.js +2 -0
- package/dist/bridge/install.d.ts +32 -1
- package/dist/bridge/install.js +225 -38
- package/dist/bridge/launch-worktree.d.ts +21 -0
- package/dist/bridge/launch-worktree.js +70 -0
- package/dist/bridge/limits.d.ts +20 -0
- package/dist/bridge/limits.js +65 -0
- package/dist/bridge/locate.d.ts +16 -0
- package/dist/bridge/locate.js +75 -0
- package/dist/bridge/metrics.d.ts +29 -0
- package/dist/bridge/metrics.js +71 -0
- package/dist/bridge/model-switch.d.ts +35 -0
- package/dist/bridge/model-switch.js +250 -0
- package/dist/bridge/models.d.ts +46 -0
- package/dist/bridge/models.js +257 -0
- package/dist/bridge/opencode-approvals.d.ts +6 -0
- package/dist/bridge/opencode-approvals.js +60 -0
- package/dist/bridge/pane-text.d.ts +15 -0
- package/dist/bridge/pane-text.js +23 -0
- package/dist/bridge/peers.d.ts +27 -0
- package/dist/bridge/peers.js +130 -0
- package/dist/bridge/projects.d.ts +12 -1
- package/dist/bridge/projects.js +268 -20
- package/dist/bridge/protocol.d.ts +35 -2
- package/dist/bridge/protocol.js +42 -7
- package/dist/bridge/push.d.ts +83 -0
- package/dist/bridge/push.js +199 -0
- package/dist/bridge/questions.d.ts +38 -0
- package/dist/bridge/questions.js +205 -0
- package/dist/bridge/schedule-format.d.ts +103 -0
- package/dist/bridge/schedule-format.js +266 -0
- package/dist/bridge/schedule-launch.d.ts +11 -0
- package/dist/bridge/schedule-launch.js +169 -0
- package/dist/bridge/schedule-watch.d.ts +52 -0
- package/dist/bridge/schedule-watch.js +242 -0
- package/dist/bridge/schedules.d.ts +48 -0
- package/dist/bridge/schedules.js +205 -0
- package/dist/bridge/server-launch.d.ts +14 -0
- package/dist/bridge/server-launch.js +218 -0
- package/dist/bridge/server-overview.d.ts +45 -0
- package/dist/bridge/server-overview.js +102 -0
- package/dist/bridge/server-pane-routes.d.ts +29 -0
- package/dist/bridge/server-pane-routes.js +400 -0
- package/dist/bridge/server-routes.d.ts +106 -0
- package/dist/bridge/server-routes.js +538 -0
- package/dist/bridge/server-stream.d.ts +46 -0
- package/dist/bridge/server-stream.js +253 -0
- package/dist/bridge/server.d.ts +3 -15
- package/dist/bridge/server.js +162 -264
- package/dist/bridge/session-servers.d.ts +24 -0
- package/dist/bridge/session-servers.js +136 -0
- package/dist/bridge/side-questions.d.ts +74 -0
- package/dist/bridge/side-questions.js +252 -0
- package/dist/bridge/simulators.d.ts +28 -0
- package/dist/bridge/simulators.js +198 -0
- package/dist/bridge/speech-transcribe.d.ts +24 -0
- package/dist/bridge/speech-transcribe.js +124 -0
- package/dist/bridge/speech.d.ts +35 -0
- package/dist/bridge/speech.js +98 -0
- package/dist/bridge/steps.d.ts +13 -0
- package/dist/bridge/steps.js +222 -0
- package/dist/bridge/tab-activity.d.ts +18 -0
- package/dist/bridge/tab-activity.js +99 -0
- package/dist/bridge/terminal-choice.d.ts +64 -0
- package/dist/bridge/terminal-choice.js +281 -0
- package/dist/bridge/transcript-claude.d.ts +22 -0
- package/dist/bridge/transcript-claude.js +353 -0
- package/dist/bridge/transcript-codex.d.ts +30 -0
- package/dist/bridge/transcript-codex.js +282 -0
- package/dist/bridge/transcript-copilot.d.ts +4 -0
- package/dist/bridge/transcript-copilot.js +14 -0
- package/dist/bridge/transcript-opencode.d.ts +5 -0
- package/dist/bridge/transcript-opencode.js +26 -0
- package/dist/bridge/transcript-preview.d.ts +94 -0
- package/dist/bridge/transcript-preview.js +476 -0
- package/dist/bridge/transcripts.d.ts +81 -4
- package/dist/bridge/transcripts.js +332 -67
- package/dist/bridge/transport.d.ts +3 -0
- package/dist/bridge/transport.js +96 -15
- package/dist/bridge/uploads.d.ts +15 -0
- package/dist/bridge/uploads.js +44 -2
- package/dist/bridge/usage.d.ts +124 -0
- package/dist/bridge/usage.js +859 -0
- package/dist/bridge-hook.mjs +41246 -21385
- package/dist/cli/actions.js +14 -1
- package/dist/cli/config-proactivity.d.ts +3 -1
- package/dist/cli/config-proactivity.js +35 -3
- package/dist/cli/config.js +4 -1
- package/dist/cli/extract.js +3 -6
- package/dist/cli/govern.js +5 -2
- package/dist/cli/hooks-globs.js +1 -1
- package/dist/cli/hooks.d.ts +1 -1
- package/dist/cli/hooks.js +9 -7
- package/dist/cli/namespaces-projects.js +12 -6
- package/dist/cli/namespaces-store.js +37 -6
- package/dist/cli/namespaces-tasks.js +1 -1
- package/dist/cli/schedules.d.ts +1 -0
- package/dist/cli/schedules.js +164 -0
- package/dist/cli/session-background.js +1 -1
- package/dist/cli/session-git.d.ts +8 -5
- package/dist/cli/session-git.js +45 -120
- package/dist/cli/session-start.js +3 -1
- package/dist/cli/session-stop.js +19 -8
- package/dist/cli/team.js +13 -10
- package/dist/cli-handlers.d.ts +1 -1
- package/dist/cli-handlers.js +8 -4
- package/dist/cli-help.d.ts +5 -4
- package/dist/cli-help.js +15 -15
- package/dist/cli-registry.d.ts +4 -1
- package/dist/cli-registry.js +119 -6
- package/dist/content/archive.js +2 -2
- package/dist/content/citation.d.ts +11 -0
- package/dist/content/citation.js +18 -0
- package/dist/content/learning.js +2 -0
- package/dist/content/summarize.d.ts +14 -15
- package/dist/content/summarize.js +60 -5
- package/dist/content/validate.d.ts +3 -1
- package/dist/content/validate.js +26 -8
- package/dist/core/project-registry.d.ts +26 -0
- package/dist/core/project-registry.js +573 -0
- package/dist/core/project.js +2 -3
- package/dist/data/access.d.ts +7 -1
- package/dist/data/access.js +13 -3
- package/dist/data/tasks.d.ts +18 -3
- package/dist/data/tasks.js +8 -7
- package/dist/entrypoint.js +44 -10
- package/dist/fanout/adapters/claude.d.ts +2 -0
- package/dist/fanout/adapters/claude.js +7 -0
- package/dist/fanout/adapters/codex.d.ts +2 -0
- package/dist/fanout/adapters/codex.js +9 -0
- package/dist/fanout/adapters/opencode.d.ts +4 -0
- package/dist/fanout/adapters/opencode.js +9 -0
- package/dist/fanout/adapters/types.d.ts +21 -0
- package/dist/fanout/adapters/types.js +3 -0
- package/dist/fanout/command.d.ts +2 -0
- package/dist/fanout/command.js +78 -0
- package/dist/fanout/launcher.d.ts +27 -0
- package/dist/fanout/launcher.js +156 -0
- package/dist/fanout/opencode-serve.d.ts +24 -0
- package/dist/fanout/opencode-serve.js +191 -0
- package/dist/fanout/picker.d.ts +91 -0
- package/dist/fanout/picker.js +51 -0
- package/dist/fanout/usage.d.ts +5 -0
- package/dist/fanout/usage.js +51 -0
- package/dist/fanout/watchdog.d.ts +10 -0
- package/dist/fanout/watchdog.js +27 -0
- package/dist/filenames.d.ts +9 -0
- package/dist/filenames.js +11 -0
- package/dist/finding/context.js +4 -22
- package/dist/generated/memory-ui-graph.browser.js +279 -283
- package/dist/governance/policy-constants.d.ts +11 -0
- package/dist/governance/policy-constants.js +9 -0
- package/dist/governance/policy.d.ts +5 -8
- package/dist/governance/policy.js +7 -5
- package/dist/graph-core/camera.d.ts +24 -0
- package/dist/graph-core/camera.js +18 -0
- package/dist/graph-core/index.d.ts +2 -0
- package/dist/graph-core/index.js +2 -0
- package/dist/graph-core/labels.d.ts +77 -0
- package/dist/graph-core/labels.js +124 -0
- package/dist/graph-core/model.d.ts +13 -0
- package/dist/graph-core/model.js +33 -0
- package/dist/graph-core/types.d.ts +2 -0
- package/dist/home-paths.d.ts +7 -0
- package/dist/home-paths.js +21 -0
- package/dist/hooks.d.ts +3 -0
- package/dist/hooks.js +13 -0
- package/dist/index.js +24 -2
- package/dist/init/guard-globals.d.ts +1 -1
- package/dist/init/guard-globals.js +4 -4
- package/dist/init/init-configure.js +3 -3
- package/dist/init/init-uninstall.js +2 -2
- package/dist/init/init-walkthrough.js +1 -1
- package/dist/init/init.js +26 -6
- package/dist/init/management-preset.d.ts +1 -1
- package/dist/init/management-preset.js +2 -2
- package/dist/init/preferences.js +1 -1
- package/dist/init/self-wiring.js +1 -1
- package/dist/init/setup.d.ts +3 -26
- package/dist/init/setup.js +49 -588
- package/dist/init/shared.js +2 -0
- package/dist/init/store-gitignore.d.ts +1 -1
- package/dist/init/store-gitignore.js +2 -0
- package/dist/init/teardown.d.ts +1 -1
- package/dist/init/teardown.js +2 -2
- package/dist/link/context.js +1 -1
- package/dist/link/doctor.d.ts +22 -1
- package/dist/link/doctor.js +100 -54
- package/dist/link/link.js +29 -61
- package/dist/link/refresh.js +2 -2
- package/dist/link/skills.js +26 -5
- package/dist/machine-identity.d.ts +3 -0
- package/dist/machine-identity.js +6 -0
- package/dist/mcp/profile.d.ts +2 -15
- package/dist/mcp/profile.js +64 -9
- package/dist/memory-ui-graph.runtime.js +279 -283
- package/dist/modules/code-package.d.ts +16 -0
- package/dist/modules/code-package.js +152 -0
- package/dist/modules/command.d.ts +2 -0
- package/dist/modules/command.js +67 -0
- package/dist/modules/config.d.ts +4 -0
- package/dist/modules/config.js +70 -0
- package/dist/modules/manifest.d.ts +41 -0
- package/dist/modules/manifest.js +1 -0
- package/dist/modules/provision.d.ts +3 -0
- package/dist/modules/provision.js +84 -0
- package/dist/modules/registry.d.ts +16 -0
- package/dist/modules/registry.js +250 -0
- package/dist/modules/runtime.d.ts +15 -0
- package/dist/modules/runtime.js +59 -0
- package/dist/package-metadata.js +10 -2
- package/dist/phren-dotenv.js +4 -2
- package/dist/phren-paths.d.ts +3 -2
- package/dist/phren-paths.js +4 -5
- package/dist/profile-store.js +4 -5
- package/dist/project-config.d.ts +19 -1
- package/dist/project-config.js +29 -3
- package/dist/project-topics.js +4 -4
- package/dist/provider-adapters.js +1 -4
- package/dist/query-correlation.js +6 -6
- package/dist/session/artifacts.js +5 -5
- package/dist/session/checkpoints.js +5 -0
- package/dist/session/utils.d.ts +2 -2
- package/dist/session/utils.js +6 -6
- package/dist/shared/content.d.ts +1 -1
- package/dist/shared/content.js +1 -1
- package/dist/shared/data-utils.js +1 -1
- package/dist/shared/fragment-graph.d.ts +1 -1
- package/dist/shared/fragment-graph.js +5 -5
- package/dist/shared/index.js +48 -7
- package/dist/shared/retrieval.d.ts +18 -1
- package/dist/shared/retrieval.js +100 -11
- package/dist/shared/search-fallback.js +4 -6
- package/dist/shared/sqljs.d.ts +2 -0
- package/dist/shared/sqljs.js +4 -2
- package/dist/shared.d.ts +0 -1
- package/dist/shared.js +0 -1
- package/dist/shell/input.d.ts +1 -5
- package/dist/shell/input.js +16 -10
- package/dist/shell/palette.d.ts +2 -2
- package/dist/shell/palette.js +3 -7
- package/dist/shell/render.d.ts +3 -1
- package/dist/shell/render.js +4 -4
- package/dist/shell/shell.js +4 -1
- package/dist/shell/types.d.ts +1 -0
- package/dist/shell/types.js +4 -0
- package/dist/shell/view.d.ts +0 -4
- package/dist/shell/view.js +19 -27
- package/dist/skill/registry.js +25 -17
- package/dist/skill/state.d.ts +3 -0
- package/dist/skill/state.js +13 -7
- package/dist/status.js +38 -17
- package/dist/store-registry.d.ts +44 -18
- package/dist/store-registry.js +169 -60
- package/dist/store-weight.d.ts +1 -6
- package/dist/store-weight.js +4 -2
- package/dist/sync/auth-doctor.d.ts +8 -0
- package/dist/sync/auth-doctor.js +27 -0
- package/dist/sync/auth.d.ts +27 -0
- package/dist/sync/auth.js +114 -0
- package/dist/sync/conflict-resolve.d.ts +9 -0
- package/dist/sync/conflict-resolve.js +146 -0
- package/dist/sync/git-state.d.ts +4 -0
- package/dist/sync/git-state.js +49 -0
- package/dist/sync/outcome.d.ts +34 -0
- package/dist/sync/outcome.js +57 -0
- package/dist/sync/pull.d.ts +15 -7
- package/dist/sync/pull.js +84 -35
- package/dist/sync/store-merge.d.ts +29 -0
- package/dist/sync/store-merge.js +137 -0
- package/dist/sync/task-merge.d.ts +22 -0
- package/dist/sync/task-merge.js +158 -0
- package/dist/task/github.js +1 -1
- package/dist/task/lifecycle.d.ts +5 -0
- package/dist/task/lifecycle.js +67 -23
- package/dist/terminal-text.d.ts +5 -0
- package/dist/terminal-text.js +11 -0
- package/dist/test-global-setup.js +7 -0
- package/dist/tool-registry.d.ts +1 -1
- package/dist/tool-registry.js +3 -1
- package/dist/tools/code.d.ts +3 -0
- package/dist/tools/code.js +178 -0
- package/dist/tools/config.js +5 -0
- package/dist/tools/data.js +14 -7
- package/dist/tools/dispatch.d.ts +2 -0
- package/dist/tools/dispatch.js +66 -0
- package/dist/tools/finding.js +43 -41
- package/dist/tools/ops.js +5 -2
- package/dist/tools/search.js +21 -8
- package/dist/tools/session.js +21 -22
- package/dist/tools/tasks.js +8 -2
- package/dist/tools/types.d.ts +2 -2
- package/dist/tools/types.js +2 -2
- package/dist/ui/assets.js +1 -1
- package/dist/ui/data.js +14 -15
- package/dist/ui/deep-void.d.ts +1 -1
- package/dist/ui/deep-void.js +0 -1
- package/dist/ui/graph-chrome.d.ts +1 -1
- package/dist/ui/graph-chrome.js +51 -0
- package/dist/ui/page.js +5 -5
- package/dist/ui/scripts.js +67 -30
- package/dist/ui/server.js +34 -6
- package/dist/update.js +1 -1
- package/dist/utils-fts.js +1 -0
- package/dist/utils-helpers.d.ts +7 -0
- package/dist/utils-helpers.js +17 -0
- package/dist/utils.d.ts +1 -1
- package/dist/utils.js +1 -1
- package/package.json +45 -3
- package/plugins/opencode/phren-transcript.js +340 -0
- package/starter/README.md +4 -4
- package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
- package/starter/global/skills/conductor/SKILL.md +106 -0
- package/starter/global/skills/fanout/SKILL.md +20 -0
- package/starter/global/skills/phren-discover/SKILL.md +6 -6
- package/starter/global/skills/phren-init/SKILL.md +4 -4
- package/starter/global/skills/phren-sync/SKILL.md +3 -3
- package/starter/templates/frontend/reference/README.md +1 -1
- package/starter/templates/library/reference/README.md +1 -1
- package/starter/templates/monorepo/reference/README.md +1 -1
- package/starter/templates/python-project/reference/README.md +1 -1
- /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { claudeConfigDir } from "../home-paths.js";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { object, objects } from "./protocol.js";
|
|
7
|
+
/** Only initialize and list. Never a thread, a prompt, or a login. */
|
|
8
|
+
export function readCodexModels(executable = "codex") {
|
|
9
|
+
return new Promise(resolve => {
|
|
10
|
+
const child = spawn(executable, ["app-server"], { cwd: homedir(), stdio: ["pipe", "pipe", "ignore"] });
|
|
11
|
+
let pending = "", bytes = 0, initialized = false, done = false;
|
|
12
|
+
const finish = (result = []) => {
|
|
13
|
+
if (done)
|
|
14
|
+
return;
|
|
15
|
+
done = true;
|
|
16
|
+
clearTimeout(timer);
|
|
17
|
+
child.stdin.destroy();
|
|
18
|
+
child.stdout.destroy();
|
|
19
|
+
child.kill("SIGTERM");
|
|
20
|
+
const kill = setTimeout(() => { if (child.exitCode === null)
|
|
21
|
+
child.kill("SIGKILL"); }, 1000);
|
|
22
|
+
kill.unref();
|
|
23
|
+
child.once("exit", () => clearTimeout(kill));
|
|
24
|
+
resolve(result);
|
|
25
|
+
};
|
|
26
|
+
const timer = setTimeout(() => finish(), 12_000);
|
|
27
|
+
const send = (value) => { if (!done)
|
|
28
|
+
child.stdin.write(JSON.stringify(value) + "\n"); };
|
|
29
|
+
child.on("error", () => finish());
|
|
30
|
+
child.on("exit", () => finish());
|
|
31
|
+
child.stdin.on("error", () => finish());
|
|
32
|
+
child.stdout.setEncoding("utf8");
|
|
33
|
+
child.stdout.on("data", (chunk) => {
|
|
34
|
+
bytes += Buffer.byteLength(chunk);
|
|
35
|
+
if (bytes > 1_048_576) {
|
|
36
|
+
finish();
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
pending += chunk;
|
|
40
|
+
let newline;
|
|
41
|
+
while (!done && (newline = pending.indexOf("\n")) >= 0) {
|
|
42
|
+
const line = pending.slice(0, newline);
|
|
43
|
+
pending = pending.slice(newline + 1);
|
|
44
|
+
try {
|
|
45
|
+
const response = object(JSON.parse(line));
|
|
46
|
+
if (response.id === 0 && !initialized) {
|
|
47
|
+
if (response.error || !response.result) {
|
|
48
|
+
finish();
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
initialized = true;
|
|
52
|
+
send({ method: "initialized", params: {} });
|
|
53
|
+
send({ id: 1, method: "model/list", params: {} });
|
|
54
|
+
}
|
|
55
|
+
else if (response.id === 1 && initialized) {
|
|
56
|
+
finish(response.error ? [] : codexModels(object(response.result)));
|
|
57
|
+
}
|
|
58
|
+
else if (response.method && response.id !== undefined) {
|
|
59
|
+
send({ id: response.id, error: { code: -32601, message: "Unsupported request" } });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
finish();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
send({ id: 0, method: "initialize", params: { clientInfo: { name: "phren_models", title: "Phren Models", version: "1" } } });
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
export function codexModels(result) {
|
|
71
|
+
return objects(result.data).filter(entry => entry.hidden !== true && typeof entry.id === "string" && entry.id).slice(0, 32).map(entry => ({
|
|
72
|
+
id: String(entry.id).slice(0, 100),
|
|
73
|
+
name: String(entry.displayName || entry.id).slice(0, 100),
|
|
74
|
+
...(typeof entry.description === "string" && entry.description ? { description: entry.description.slice(0, 300) } : {}),
|
|
75
|
+
...(entry.isDefault === true ? { isDefault: true } : {}),
|
|
76
|
+
...(typeof entry.defaultReasoningEffort === "string" ? { defaultReasoningEffort: entry.defaultReasoningEffort } : {}),
|
|
77
|
+
supportedReasoningEfforts: objects(entry.supportedReasoningEfforts).flatMap(value => typeof value.reasoningEffort === "string" ? [value.reasoningEffort] : []),
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
/** The menu used only when Claude Code's own catalogue cannot be read (it has
|
|
81
|
+
* never run on this computer, or the cache is unreadable). Normally the phone
|
|
82
|
+
* shows the live catalogue below, so a new model appears without anyone
|
|
83
|
+
* editing this table. Exported so a parity test can hold the phone's built-in
|
|
84
|
+
* offline fallback and the chat fixture to it. */
|
|
85
|
+
export const CLAUDE_MENU = [
|
|
86
|
+
{ id: "claude-fable-5-1", name: "Fable 5.1", description: "Most intelligent.", isDefault: true },
|
|
87
|
+
{ id: "claude-opus-5", name: "Opus 5", description: "Most capable for long work." },
|
|
88
|
+
{ id: "claude-sonnet-5", name: "Sonnet 5", description: "Fast and capable." },
|
|
89
|
+
{ id: "claude-haiku-4-5-20251001", name: "Haiku 4.5", description: "Fastest and lightest." },
|
|
90
|
+
{ id: "claude-fable-5-1[1m]", name: "Fable 5.1 (1M context)", description: "Fable 5.1 with a 1M context window." },
|
|
91
|
+
];
|
|
92
|
+
/** Claude Code fetches its `/model` catalogue from Anthropic and caches it as
|
|
93
|
+
* `<config>/cache/model-catalog/<account>-...-cc.json`, refreshing it itself:
|
|
94
|
+
* `catalog.config.models` is the menu in the terminal's order (`section`
|
|
95
|
+
* "main" first, older models under "overflow"), each row gated by
|
|
96
|
+
* `min_claude_code_version`, and `catalog.state.model` is the selected
|
|
97
|
+
* default. Reading that file keeps the phone's picker identical to the
|
|
98
|
+
* terminal's with nothing to maintain here. */
|
|
99
|
+
export async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
|
|
100
|
+
const directory = path.join(configDir, "cache", "model-catalog");
|
|
101
|
+
let newest;
|
|
102
|
+
try {
|
|
103
|
+
for (const name of await readdir(directory)) {
|
|
104
|
+
if (!name.endsWith("-cc.json"))
|
|
105
|
+
continue;
|
|
106
|
+
const file = path.join(directory, name), at = (await stat(file)).mtimeMs;
|
|
107
|
+
if (!newest || at > newest.at)
|
|
108
|
+
newest = { file, at };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return [];
|
|
113
|
+
}
|
|
114
|
+
if (!newest)
|
|
115
|
+
return [];
|
|
116
|
+
let parsed;
|
|
117
|
+
try {
|
|
118
|
+
parsed = JSON.parse(await readFile(newest.file, "utf8"));
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return [];
|
|
122
|
+
}
|
|
123
|
+
const catalog = object(object(parsed).catalog);
|
|
124
|
+
const selected = typeof object(catalog.state).model === "string" ? String(object(catalog.state).model) : undefined;
|
|
125
|
+
const rows = objects(object(catalog.config).models).filter(row => typeof row.id === "string" && /^[a-z0-9.[\]-]{1,100}$/i.test(row.id));
|
|
126
|
+
const usable = rows.filter(row => !installed || typeof row.min_claude_code_version !== "string" || !olderVersion(installed, row.min_claude_code_version));
|
|
127
|
+
const ordered = [...usable.filter(row => row.section !== "overflow"), ...usable.filter(row => row.section === "overflow")];
|
|
128
|
+
const models = ordered.map(row => ({
|
|
129
|
+
id: String(row.id),
|
|
130
|
+
name: typeof row.name === "string" && row.name.trim() ? row.name.trim().slice(0, 100) : claudeName(String(row.id)),
|
|
131
|
+
...(typeof row.description === "string" && row.description.trim() ? { description: row.description.trim().slice(0, 300) } : {}),
|
|
132
|
+
...(String(row.id) === selected ? { isDefault: true } : {}),
|
|
133
|
+
...claudeEfforts(row),
|
|
134
|
+
}));
|
|
135
|
+
// The terminal offers the selected model with a 1M context window as its
|
|
136
|
+
// own row; the catalogue does not list that variant, so add it after the
|
|
137
|
+
// main section the way the menu draws it.
|
|
138
|
+
const chosen = models.find(model => model.isDefault);
|
|
139
|
+
if (chosen && !models.some(model => model.id === `${chosen.id}[1m]`)) {
|
|
140
|
+
const main = models.filter(model => ordered.find(row => row.id === model.id)?.section !== "overflow").length;
|
|
141
|
+
models.splice(main, 0, { id: `${chosen.id}[1m]`, name: `${chosen.name} (1M context)`, description: `${chosen.name} with a 1M context window.`,
|
|
142
|
+
...(chosen.supportedReasoningEfforts ? { supportedReasoningEfforts: chosen.supportedReasoningEfforts } : {}),
|
|
143
|
+
...(chosen.defaultReasoningEffort ? { defaultReasoningEffort: chosen.defaultReasoningEffort } : {}) });
|
|
144
|
+
}
|
|
145
|
+
return models;
|
|
146
|
+
}
|
|
147
|
+
/** A catalogue row's `thinking.effort_options`, the levels `--effort` takes for that model. */
|
|
148
|
+
function claudeEfforts(row) {
|
|
149
|
+
const options = objects(object(row.thinking).effort_options).filter(option => typeof option.id === "string" && /^[a-z]{1,16}$/.test(option.id));
|
|
150
|
+
if (!options.length)
|
|
151
|
+
return {};
|
|
152
|
+
const fallback = options.find(option => object(option.badge).message === "Default");
|
|
153
|
+
return { supportedReasoningEfforts: options.map(option => String(option.id)),
|
|
154
|
+
...(fallback ? { defaultReasoningEffort: String(fallback.id) } : {}) };
|
|
155
|
+
}
|
|
156
|
+
/** "2.1.279" is older than "2.1.280"; anything unparseable is not. */
|
|
157
|
+
function olderVersion(installed, required) {
|
|
158
|
+
const parse = (value) => /^(\d+)\.(\d+)\.(\d+)/.exec(value.trim())?.slice(1).map(Number);
|
|
159
|
+
const have = parse(installed), need = parse(required);
|
|
160
|
+
if (!have || !need)
|
|
161
|
+
return false;
|
|
162
|
+
for (let index = 0; index < 3; index++)
|
|
163
|
+
if (have[index] !== need[index])
|
|
164
|
+
return have[index] < need[index];
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
/** The installed client's version, so a model it cannot run is not offered. */
|
|
168
|
+
function claudeVersion(executable = "claude") {
|
|
169
|
+
return new Promise(resolve => {
|
|
170
|
+
const child = spawn(executable, ["--version"], { cwd: homedir(), stdio: ["ignore", "pipe", "ignore"] });
|
|
171
|
+
let out = "";
|
|
172
|
+
// A version probe has no work to save. Terminate it even if a wrapper
|
|
173
|
+
// ignores SIGTERM, so timed-out catalogue refreshes cannot leak children.
|
|
174
|
+
const timer = setTimeout(() => { child.kill("SIGKILL"); resolve(undefined); }, 5_000);
|
|
175
|
+
child.stdout.setEncoding("utf8");
|
|
176
|
+
child.stdout.on("data", (chunk) => { if (out.length < 4_096)
|
|
177
|
+
out += chunk; });
|
|
178
|
+
child.on("error", () => { clearTimeout(timer); resolve(undefined); });
|
|
179
|
+
child.on("exit", () => { clearTimeout(timer); resolve(/\d+\.\d+\.\d+/.exec(out)?.[0]); });
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
/** The live catalogue when Claude Code has one cached on this computer,
|
|
183
|
+
* otherwise the offline fallback, copied per call so a caller cannot mutate it. */
|
|
184
|
+
export async function readClaudeModels(configDir, installed) {
|
|
185
|
+
const version = installed === null ? undefined : installed ?? await claudeVersion();
|
|
186
|
+
const live = await readClaudeCatalog(configDir, version).catch(() => []);
|
|
187
|
+
return live.length ? live : CLAUDE_MENU.map(model => ({ ...model }));
|
|
188
|
+
}
|
|
189
|
+
/** `opencode models` prints one `provider/model` id per line. The Go plan's
|
|
190
|
+
* models sit under `opencode-go/`, Zen's under `opencode/`, and everything
|
|
191
|
+
* else under the gateway it came from; the configured default is marked. */
|
|
192
|
+
export async function readOpenCodeModels(executable = "opencode", configDir = path.join(homedir(), ".config/opencode")) {
|
|
193
|
+
const listed = await new Promise(resolve => {
|
|
194
|
+
const child = spawn(executable, ["models"], { cwd: homedir(), stdio: ["ignore", "pipe", "ignore"] });
|
|
195
|
+
let out = "", done = false;
|
|
196
|
+
const finish = () => { if (!done) {
|
|
197
|
+
done = true;
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
resolve(out);
|
|
200
|
+
} };
|
|
201
|
+
const timer = setTimeout(() => { child.kill("SIGTERM"); finish(); }, 12_000);
|
|
202
|
+
child.stdout.setEncoding("utf8");
|
|
203
|
+
child.stdout.on("data", (chunk) => { if (out.length < 262_144)
|
|
204
|
+
out += chunk; });
|
|
205
|
+
child.on("error", finish);
|
|
206
|
+
child.on("exit", finish);
|
|
207
|
+
});
|
|
208
|
+
const ids = [...new Set(listed.split(/\r?\n/).map(line => line.trim()).filter(line => /^[a-z0-9~.-]+\/[^\s]+$/i.test(line)))].slice(0, 400);
|
|
209
|
+
if (!ids.length)
|
|
210
|
+
return [];
|
|
211
|
+
let configured;
|
|
212
|
+
for (const file of ["opencode.json", "opencode.jsonc"]) {
|
|
213
|
+
try {
|
|
214
|
+
const text = await readFile(path.join(configDir, file), "utf8");
|
|
215
|
+
const model = /"model"\s*:\s*"([^"]+)"/.exec(text)?.[1];
|
|
216
|
+
if (model) {
|
|
217
|
+
configured = model.slice(0, 200);
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
catch { /* No config means no default to mark. */ }
|
|
222
|
+
}
|
|
223
|
+
const rank = (id) => id.startsWith("opencode-go/") ? 0 : id.startsWith("opencode/") ? 1 : 2;
|
|
224
|
+
return ids.sort((a, b) => rank(a) - rank(b) || a.localeCompare(b)).map(id => {
|
|
225
|
+
const provider = id.slice(0, id.indexOf("/")), name = id.slice(id.indexOf("/") + 1);
|
|
226
|
+
const description = provider === "opencode-go" ? "OpenCode Go plan." : provider === "opencode" ? (name.endsWith("-free") ? "OpenCode Zen, free." : "OpenCode Zen, per token.") : `Through ${provider}.`;
|
|
227
|
+
return { id, name, description, ...(id === configured ? { isDefault: true } : {}) };
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/** "claude-fable-5-1" reads as "Fable 5.1"; a date suffix is dropped. */
|
|
231
|
+
export function claudeName(id) {
|
|
232
|
+
const parts = id.replace(/^claude-/, "").replace(/-\d{8}$/, "").replace(/\[1m\]$/, "").split("-");
|
|
233
|
+
const family = parts.shift() ?? id;
|
|
234
|
+
const version = parts.filter(part => /^\d+$/.test(part)).join(".");
|
|
235
|
+
const name = family.charAt(0).toUpperCase() + family.slice(1) + (version ? ` ${version}` : "");
|
|
236
|
+
return id.endsWith("[1m]") ? `${name} (1M context)` : name;
|
|
237
|
+
}
|
|
238
|
+
/** Catalogues change rarely and app-server takes seconds to start. */
|
|
239
|
+
export class ModelCatalog {
|
|
240
|
+
codex;
|
|
241
|
+
claude;
|
|
242
|
+
opencode;
|
|
243
|
+
cache = new Map();
|
|
244
|
+
constructor(codex = () => readCodexModels(), claude = () => readClaudeModels(), opencode = () => readOpenCodeModels()) {
|
|
245
|
+
this.codex = codex;
|
|
246
|
+
this.claude = claude;
|
|
247
|
+
this.opencode = opencode;
|
|
248
|
+
}
|
|
249
|
+
list(source) {
|
|
250
|
+
const cached = this.cache.get(source);
|
|
251
|
+
if (cached && Date.now() - cached.at < 600_000)
|
|
252
|
+
return cached.value;
|
|
253
|
+
const value = (source === "codex" ? this.codex() : source === "claude" ? this.claude() : source === "opencode" ? this.opencode() : Promise.resolve([])).catch(() => []);
|
|
254
|
+
this.cache.set(source, { at: Date.now(), value });
|
|
255
|
+
return value;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type Json } from "./protocol.js";
|
|
2
|
+
export declare function opencodeApprovalFile(session: string, kind: "request" | "answer", store?: string): string | undefined;
|
|
3
|
+
export declare function directoryNames(directory: string, limit: number): AsyncGenerator<string>;
|
|
4
|
+
export declare function opencodeRequest(session: string): Json | undefined;
|
|
5
|
+
/** `opencodeRequest` without blocking the event loop, for the background sweep. */
|
|
6
|
+
export declare function readOpencodeRequest(session: string, store?: string): Promise<Json | undefined>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { lstatSync, readFileSync } from "node:fs";
|
|
2
|
+
import { lstat, opendir, readFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { object } from "./protocol.js";
|
|
5
|
+
import { phrenStoreRoot } from "./transcripts.js";
|
|
6
|
+
/** The request and answer files the opencode plugin and the Hook exchange for
|
|
7
|
+
* an opencode permission ask, under the store's `.runtime/approvals`. */
|
|
8
|
+
const opencodeSession = /^ses_[0-9A-Za-z]{1,64}$/;
|
|
9
|
+
export function opencodeApprovalFile(session, kind, store = phrenStoreRoot()) {
|
|
10
|
+
if (!opencodeSession.test(session))
|
|
11
|
+
return undefined;
|
|
12
|
+
return path.join(store, ".runtime", "approvals", `opencode-${session}.${kind}.json`);
|
|
13
|
+
}
|
|
14
|
+
export async function* directoryNames(directory, limit) {
|
|
15
|
+
const entries = await opendir(directory).catch(() => undefined);
|
|
16
|
+
if (!entries)
|
|
17
|
+
return;
|
|
18
|
+
let count = 0;
|
|
19
|
+
for await (const entry of entries) {
|
|
20
|
+
if (count++ >= limit)
|
|
21
|
+
break;
|
|
22
|
+
yield entry.name;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function validRequest(value, session) {
|
|
26
|
+
if (typeof value.id !== "string" || !value.id || value.sessionID !== session)
|
|
27
|
+
return undefined;
|
|
28
|
+
if (typeof value.expiresAt !== "string" || !Number.isFinite(Date.parse(value.expiresAt)) || Date.parse(value.expiresAt) <= Date.now())
|
|
29
|
+
return undefined;
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
export function opencodeRequest(session) {
|
|
33
|
+
const file = opencodeApprovalFile(session, "request");
|
|
34
|
+
if (!file)
|
|
35
|
+
return undefined;
|
|
36
|
+
try {
|
|
37
|
+
const info = lstatSync(file);
|
|
38
|
+
if (!info.isFile() || info.size > 65_536)
|
|
39
|
+
return undefined;
|
|
40
|
+
return validRequest(object(JSON.parse(readFileSync(file, "utf8"))), session);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** `opencodeRequest` without blocking the event loop, for the background sweep. */
|
|
47
|
+
export async function readOpencodeRequest(session, store) {
|
|
48
|
+
const file = opencodeApprovalFile(session, "request", store);
|
|
49
|
+
if (!file)
|
|
50
|
+
return undefined;
|
|
51
|
+
try {
|
|
52
|
+
const info = await lstat(file);
|
|
53
|
+
if (!info.isFile() || info.size > 65_536)
|
|
54
|
+
return undefined;
|
|
55
|
+
return validRequest(object(JSON.parse(await readFile(file, "utf8"))), session);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface PaneTextRequest {
|
|
2
|
+
/** `agent.read` addresses the pane's agent; `pane.read` reads any pane,
|
|
3
|
+
* including one whose agent is still starting. */
|
|
4
|
+
method: "agent.read" | "pane.read";
|
|
5
|
+
source: "visible" | "recent";
|
|
6
|
+
lines: number;
|
|
7
|
+
stripAnsi?: boolean;
|
|
8
|
+
/** Herdr 0.9 answers plain text whatever `strip_ansi` says; "ansi" keeps the styles. */
|
|
9
|
+
format?: "ansi";
|
|
10
|
+
timeoutMs?: number;
|
|
11
|
+
/** Names the read in the once-per-target warning; without it a failure is silent. */
|
|
12
|
+
what?: string;
|
|
13
|
+
}
|
|
14
|
+
/** What a pane draws, or "" when Herdr cannot say: callers treat the text as optional. */
|
|
15
|
+
export declare function readPaneText(server: string, pane: string, request: PaneTextRequest): Promise<string>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// The one reader of pane text. It sits beside herdr.ts rather than inside it so
|
|
2
|
+
// it calls Herdr through herdr.ts's exported rpc, the seam the bridge tests fake.
|
|
3
|
+
import { noteOptionalReadFailure, rpc } from "./herdr.js";
|
|
4
|
+
import { object } from "./protocol.js";
|
|
5
|
+
/** `pane.read` and `agent.read` both answer with a `read` object carrying the text. */
|
|
6
|
+
function readText(result) {
|
|
7
|
+
const read = object(result.read ?? result);
|
|
8
|
+
return typeof read.text === "string" ? read.text : "";
|
|
9
|
+
}
|
|
10
|
+
/** What a pane draws, or "" when Herdr cannot say: callers treat the text as optional. */
|
|
11
|
+
export async function readPaneText(server, pane, request) {
|
|
12
|
+
const params = { ...(request.method === "agent.read" ? { target: pane } : { pane_id: pane }),
|
|
13
|
+
source: request.source, lines: request.lines, strip_ansi: request.stripAnsi ?? true,
|
|
14
|
+
...(request.format ? { format: request.format } : {}) };
|
|
15
|
+
try {
|
|
16
|
+
return readText(await rpc(server, request.method, params, undefined, request.timeoutMs));
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
if (request.what)
|
|
20
|
+
noteOptionalReadFailure(request.what, `${server}/${pane}`, error);
|
|
21
|
+
return "";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { type Json } from "./protocol.js";
|
|
3
|
+
declare const peerSchema: z.ZodObject<{
|
|
4
|
+
name: z.ZodString;
|
|
5
|
+
address: z.ZodString;
|
|
6
|
+
username: z.ZodString;
|
|
7
|
+
port: z.ZodDefault<z.ZodNumber>;
|
|
8
|
+
hostKey: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
9
|
+
server: z.ZodDefault<z.ZodString>;
|
|
10
|
+
}, z.core.$strict>;
|
|
11
|
+
export type HookPeer = z.infer<typeof peerSchema>;
|
|
12
|
+
export declare function hookPeers(root?: string): Promise<HookPeer[]>;
|
|
13
|
+
/**
|
|
14
|
+
* Peers for reads that keep working without them. No hooks.yaml means no
|
|
15
|
+
* peers; a broken one is logged and returned as `peerError` so the response
|
|
16
|
+
* can say why remote agents are missing instead of hiding them.
|
|
17
|
+
*/
|
|
18
|
+
export declare function optionalHookPeers(root?: string): Promise<{
|
|
19
|
+
peers: HookPeer[];
|
|
20
|
+
peerError?: string;
|
|
21
|
+
}>;
|
|
22
|
+
export declare function peerSSHArgs(peer: HookPeer, knownHosts: string, key: string): string[];
|
|
23
|
+
/** Keeps ssh's own first stderr line (one line, bounded) and its exit code. */
|
|
24
|
+
export declare function peerOfflineMessage(diagnostic: string, exitCode: number | null | undefined): string;
|
|
25
|
+
/** A pin is supplied out of band; dispatch never learns or replaces host keys. */
|
|
26
|
+
export declare function peerRequest(peer: HookPeer, route: string, data?: Json, timeout?: number): Promise<Json>;
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { lstat, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { Duplex } from "node:stream";
|
|
5
|
+
import { load } from "js-yaml";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { logger } from "../logger.js";
|
|
8
|
+
import { hookRequest } from "./client.js";
|
|
9
|
+
import { computerName, dispatchKeyPath, publicComputerKey } from "./computers.js";
|
|
10
|
+
import { BridgeError, bridgeRoot, serverName } from "./protocol.js";
|
|
11
|
+
const peerSchema = z.object({
|
|
12
|
+
name: computerName,
|
|
13
|
+
address: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9.:-]{0,252}$/),
|
|
14
|
+
username: z.string().regex(/^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/),
|
|
15
|
+
port: z.number().int().min(1).max(65535).default(22),
|
|
16
|
+
hostKey: z.string().transform(publicComputerKey),
|
|
17
|
+
server: serverName.default("default"),
|
|
18
|
+
}).strict();
|
|
19
|
+
export async function hookPeers(root = bridgeRoot()) {
|
|
20
|
+
const file = path.join(root, "hooks.yaml");
|
|
21
|
+
const info = await lstat(file).catch(error => {
|
|
22
|
+
if (error.code === "ENOENT")
|
|
23
|
+
return undefined;
|
|
24
|
+
throw new BridgeError(409, `hooks.yaml could not be read (${error.code ?? "unknown error"}).`);
|
|
25
|
+
});
|
|
26
|
+
if (!info)
|
|
27
|
+
throw new BridgeError(409, "Configure peers and verified host keys in the Hook's hooks.yaml first.", { hooksYaml: "missing" });
|
|
28
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 65_536 || (info.mode & 0o077))
|
|
29
|
+
throw new BridgeError(409, "hooks.yaml must be a private regular file (0600), at most 64 KiB.");
|
|
30
|
+
const { computers } = z.object({ version: z.literal(1), computers: z.array(peerSchema).max(32) }).strict().parse(load(await readFile(file, "utf8")));
|
|
31
|
+
if (new Set(computers.map(peer => peer.name)).size !== computers.length)
|
|
32
|
+
throw new BridgeError(409, "hooks.yaml has duplicate computer names.");
|
|
33
|
+
return computers;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Peers for reads that keep working without them. No hooks.yaml means no
|
|
37
|
+
* peers; a broken one is logged and returned as `peerError` so the response
|
|
38
|
+
* can say why remote agents are missing instead of hiding them.
|
|
39
|
+
*/
|
|
40
|
+
export async function optionalHookPeers(root = bridgeRoot()) {
|
|
41
|
+
try {
|
|
42
|
+
return { peers: await hookPeers(root) };
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (error instanceof BridgeError && error.details?.hooksYaml === "missing")
|
|
46
|
+
return { peers: [] };
|
|
47
|
+
const peerError = hooksYamlError(error);
|
|
48
|
+
// Polled routes call this often; log each distinct problem once.
|
|
49
|
+
if (peerError !== lastPeerError)
|
|
50
|
+
logger.warn("peers", peerError);
|
|
51
|
+
lastPeerError = peerError;
|
|
52
|
+
return { peers: [], peerError };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
let lastPeerError;
|
|
56
|
+
function hooksYamlError(error) {
|
|
57
|
+
if (error instanceof BridgeError)
|
|
58
|
+
return error.message;
|
|
59
|
+
if (error instanceof z.ZodError) {
|
|
60
|
+
const issue = error.issues[0];
|
|
61
|
+
return `hooks.yaml is invalid${issue?.path.length ? ` at ${issue.path.join(".")}` : ""}: ${issue?.message ?? "unexpected shape"}`.slice(0, 300);
|
|
62
|
+
}
|
|
63
|
+
const first = (error instanceof Error ? error.message : String(error)).split("\n")[0].replace(/[\x00-\x1f\x7f]/g, " ");
|
|
64
|
+
return `hooks.yaml could not be parsed: ${first}`.slice(0, 300);
|
|
65
|
+
}
|
|
66
|
+
export function peerSSHArgs(peer, knownHosts, key) {
|
|
67
|
+
return ["-F", "/dev/null", "-T", "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none",
|
|
68
|
+
"-o", "StrictHostKeyChecking=yes", "-o", "HostKeyAlias=phren-peer", "-o", `UserKnownHostsFile=${knownHosts}`,
|
|
69
|
+
"-o", "GlobalKnownHostsFile=/dev/null", "-o", "UpdateHostKeys=no", "-o", "HostKeyAlgorithms=ssh-ed25519",
|
|
70
|
+
"-o", "PasswordAuthentication=no", "-o", "KbdInteractiveAuthentication=no", "-o", "ForwardAgent=no",
|
|
71
|
+
"-o", "ClearAllForwardings=yes", "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=10",
|
|
72
|
+
"-i", key, "-p", String(peer.port), "-l", peer.username, "--", peer.address, "phren-hook v1 pipe"];
|
|
73
|
+
}
|
|
74
|
+
/** Keeps ssh's own first stderr line (one line, bounded) and its exit code. */
|
|
75
|
+
export function peerOfflineMessage(diagnostic, exitCode) {
|
|
76
|
+
const line = diagnostic.split(/\r?\n/).map(text => text.replace(/[\x00-\x1f\x7f]/g, " ").trim().replace(/^ssh:\s*/, "")).find(Boolean)?.slice(0, 200);
|
|
77
|
+
const details = [line ? `ssh: ${line}` : "", typeof exitCode === "number" ? `exit ${exitCode}` : ""].filter(Boolean).join("; ");
|
|
78
|
+
return `The remote Hook is offline or SSH did not confirm the request${details ? ` (${details})` : ""}.`;
|
|
79
|
+
}
|
|
80
|
+
/** A pin is supplied out of band; dispatch never learns or replaces host keys. */
|
|
81
|
+
export async function peerRequest(peer, route, data, timeout) {
|
|
82
|
+
const root = bridgeRoot(), key = dispatchKeyPath(root);
|
|
83
|
+
const info = await lstat(key).catch(() => undefined);
|
|
84
|
+
if (!info?.isFile() || info.isSymbolicLink() || (info.mode & 0o077))
|
|
85
|
+
throw new BridgeError(409, "Run phren bridge enroll-computer on this computer first (private key mode 0600).");
|
|
86
|
+
const temporary = await mkdtemp(path.join(root, "peer-"));
|
|
87
|
+
let child, stream;
|
|
88
|
+
try {
|
|
89
|
+
const knownHosts = path.join(temporary, "known_hosts");
|
|
90
|
+
await writeFile(knownHosts, `phren-peer ${peer.hostKey}\n`, { mode: 0o600 });
|
|
91
|
+
const ssh = spawn("ssh", peerSSHArgs(peer, knownHosts, key), { stdio: ["pipe", "pipe", "pipe"] });
|
|
92
|
+
child = ssh;
|
|
93
|
+
stream = new Duplex({
|
|
94
|
+
read() { ssh.stdout.resume(); },
|
|
95
|
+
write(chunk, encoding, callback) { ssh.stdin.write(chunk, encoding, callback); },
|
|
96
|
+
final(callback) { ssh.stdin.end(callback); },
|
|
97
|
+
destroy(error, callback) { ssh.kill(); callback(error); },
|
|
98
|
+
});
|
|
99
|
+
ssh.stdout.on("data", chunk => { if (!stream.push(chunk))
|
|
100
|
+
ssh.stdout.pause(); });
|
|
101
|
+
ssh.stdout.on("end", () => stream.push(null));
|
|
102
|
+
ssh.stdout.on("error", error => stream?.destroy(error));
|
|
103
|
+
ssh.stdin.on("error", error => stream?.destroy(error));
|
|
104
|
+
let diagnostic = "";
|
|
105
|
+
child.stderr.on("data", bytes => { diagnostic = (diagnostic + bytes.toString()).slice(-4096); });
|
|
106
|
+
const exited = new Promise(resolve => ssh.once("exit", code => resolve(code)));
|
|
107
|
+
child.on("error", error => stream?.destroy(new BridgeError(503, `SSH is unavailable (${error.code ?? "spawn failed"}).`)));
|
|
108
|
+
try {
|
|
109
|
+
return await hookRequest(route, data, { createConnection: () => stream }, timeout ?? (data === undefined ? 15_000 : 65_000));
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
if (!(error instanceof BridgeError)) {
|
|
113
|
+
// ssh's stderr and exit status usually land just after the stream ends.
|
|
114
|
+
const exitCode = await Promise.race([exited, new Promise(resolve => { setTimeout(() => resolve(undefined), 250).unref(); })]);
|
|
115
|
+
if (!/Permission denied|Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(diagnostic))
|
|
116
|
+
throw new BridgeError(503, peerOfflineMessage(diagnostic, exitCode));
|
|
117
|
+
}
|
|
118
|
+
if (/Permission denied/i.test(diagnostic))
|
|
119
|
+
throw new BridgeError(403, "The remote computer has not enrolled this dispatch key.");
|
|
120
|
+
if (/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(diagnostic))
|
|
121
|
+
throw new BridgeError(403, "The remote SSH host key does not match its pin.");
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
stream?.destroy();
|
|
127
|
+
child?.kill();
|
|
128
|
+
await rm(temporary, { recursive: true, force: true });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
import { type Json } from "./protocol.js";
|
|
2
|
-
export declare function
|
|
2
|
+
export declare function git(cwd: string, ...args: string[]): Promise<string>;
|
|
3
|
+
export declare function gitRoot(dir: string): Promise<string | undefined>;
|
|
4
|
+
/** The pane's working tree, plus anything the command named: files in the
|
|
5
|
+
* same repository that a hook already committed, and files in other
|
|
6
|
+
* repositories — the phren store, a sibling checkout — grouped by root. */
|
|
7
|
+
export declare function repositoryDiff(cwd: string, touched?: unknown[], allowedPaths?: string[]): Promise<Json>;
|
|
8
|
+
/** The HEAD file of the repository holding `cwd` (`.git/HEAD`, or a linked
|
|
9
|
+
* worktree's through its `.git` file), found without spawning git. */
|
|
10
|
+
export declare function headFile(cwd: string): Promise<string | undefined>;
|
|
11
|
+
export declare function repositoryBranch(cwd: string): Promise<string | undefined>;
|
|
3
12
|
export interface LocalServer {
|
|
4
13
|
name: string;
|
|
5
14
|
port: number;
|
|
@@ -8,3 +17,5 @@ export interface LocalServer {
|
|
|
8
17
|
pid?: number;
|
|
9
18
|
}
|
|
10
19
|
export declare function webServers(): Promise<LocalServer[]>;
|
|
20
|
+
/** Launch only in real local directories under home or a locator candidate. */
|
|
21
|
+
export declare function launchDirectory(raw: unknown, activity?: Json[], located?: Iterable<string>): Promise<string>;
|