@phren/cli 0.2.14 → 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.d.ts +2 -0
- package/dist/init/init-walkthrough.js +17 -6
- 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
package/dist/bridge/install.js
CHANGED
|
@@ -1,26 +1,59 @@
|
|
|
1
|
+
import { activateModules as moduleSnapshot } from "../modules/runtime.js";
|
|
2
|
+
import { defaultPhrenPath } from "../shared.js";
|
|
3
|
+
import { disabledHint } from "../modules/registry.js";
|
|
1
4
|
import { execFile } from "node:child_process";
|
|
2
|
-
import {
|
|
5
|
+
import { usageStatusLine } from "./usage.js";
|
|
6
|
+
import { chmod, copyFile, mkdir, open, readFile, rename, symlink, unlink, lstat, writeFile } from "node:fs/promises";
|
|
3
7
|
import { homedir } from "node:os";
|
|
8
|
+
import { codexHome, claudeConfigDir } from "../home-paths.js";
|
|
4
9
|
import path from "node:path";
|
|
5
10
|
import { fileURLToPath } from "node:url";
|
|
6
11
|
import { promisify } from "node:util";
|
|
7
|
-
import { bridgeRoot, object, objects } from "./protocol.js";
|
|
12
|
+
import { bridgeRoot, object, objects, atomic, socketPath } from "./protocol.js";
|
|
13
|
+
import { herdrRoot } from "./herdr.js";
|
|
8
14
|
import { health } from "./transport.js";
|
|
9
15
|
const exec = promisify(execFile);
|
|
10
16
|
const label = "com.phren.hook";
|
|
11
17
|
const unit = "phren-hook.service";
|
|
12
18
|
export const forcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch"';
|
|
19
|
+
function keyOptions(line) {
|
|
20
|
+
const options = [];
|
|
21
|
+
let quoted = false, start = 0;
|
|
22
|
+
for (let i = 0; i < line.length; i++) {
|
|
23
|
+
const character = line[i];
|
|
24
|
+
if (quoted && character === "\\" && line[i + 1] === '"') {
|
|
25
|
+
i++;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (character === '"') {
|
|
29
|
+
quoted = !quoted;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
if (!quoted && (character === "," || /\s/.test(character))) {
|
|
33
|
+
options.push(line.slice(start, i));
|
|
34
|
+
start = i + 1;
|
|
35
|
+
if (character !== ",")
|
|
36
|
+
return { options, rest: line.slice(i) };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
13
41
|
export function upgradeKeys(text) {
|
|
14
42
|
let changed = 0;
|
|
15
43
|
const result = text.split(/(?<=\n)/).map(line => {
|
|
16
|
-
|
|
44
|
+
const parsed = keyOptions(line);
|
|
45
|
+
if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-iphone\s*$/.test(parsed.rest))
|
|
17
46
|
return line;
|
|
18
|
-
const old =
|
|
19
|
-
if (!old.test(
|
|
47
|
+
const old = /^command="(?:\/usr\/bin\/false|python3 ~\/\.local\/share\/phren\/chat-progress\.py|sh ~\/\.local\/share\/phren\/bridge\/dispatch)"$/;
|
|
48
|
+
if (!parsed.options.some(option => old.test(option)))
|
|
20
49
|
return line;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
50
|
+
// permitopen restricts TCP destinations only. Removing generic forwarding
|
|
51
|
+
// also prevents access to private Unix sockets through this device key.
|
|
52
|
+
const options = parsed.options.filter(option => option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen="))
|
|
53
|
+
.map(option => old.test(option) ? forcedCommand : option);
|
|
54
|
+
if (!options.includes("pty"))
|
|
55
|
+
options.splice(1, 0, "pty");
|
|
56
|
+
const next = options.join(",") + parsed.rest;
|
|
24
57
|
if (next !== line)
|
|
25
58
|
changed++;
|
|
26
59
|
return next;
|
|
@@ -30,43 +63,100 @@ export function upgradeKeys(text) {
|
|
|
30
63
|
const quote = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
|
|
31
64
|
const xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
32
65
|
const systemdQuote = (s) => '"' + s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%") + '"';
|
|
33
|
-
async function
|
|
34
|
-
const temporary = file + `.phren-${process.pid}`;
|
|
35
|
-
await writeFile(temporary, text, { mode, flag: "wx" });
|
|
66
|
+
async function commandOutput(file, args, env) {
|
|
36
67
|
try {
|
|
37
|
-
await
|
|
68
|
+
const { stdout, stderr } = await exec(file, args, { env, timeout: 2000 });
|
|
69
|
+
return stdout + stderr || undefined;
|
|
38
70
|
}
|
|
39
|
-
|
|
40
|
-
|
|
71
|
+
catch (error) {
|
|
72
|
+
const value = error;
|
|
73
|
+
return `${value.stdout ?? ""}${value.stderr ?? ""}` || undefined;
|
|
41
74
|
}
|
|
42
75
|
}
|
|
76
|
+
/** Pick the cheapest reliable forwarder at install time: socat, then an nc that
|
|
77
|
+
* understands Unix sockets, then the node gateway that always works. */
|
|
78
|
+
export async function detectGateway(env = process.env) {
|
|
79
|
+
if ((await commandOutput("/bin/sh", ["-c", "command -v socat"], env))?.trim())
|
|
80
|
+
return "socat";
|
|
81
|
+
const help = await commandOutput("nc", ["-h"], env);
|
|
82
|
+
if (help !== undefined && /(^|\s)-U(\s|,|$)/m.test(help))
|
|
83
|
+
return "nc";
|
|
84
|
+
return "node";
|
|
85
|
+
}
|
|
86
|
+
/** The POSIX sh forced command: the phone's byte pipe goes straight to the Hook
|
|
87
|
+
* socket through a tiny forwarder, so a loaded machine never pays for a fresh
|
|
88
|
+
* node process; every other SSH command falls through to the node gateway. */
|
|
89
|
+
export function gatewayScript(gateway, environment) {
|
|
90
|
+
const { root, herdr, store, profile, node, bundle, socket, timing } = environment;
|
|
91
|
+
const forward = gateway === "socat"
|
|
92
|
+
? ` if command -v socat >/dev/null 2>&1; then rm -f ${quote(timing)}; exec socat - UNIX-CONNECT:${quote(socket)}; fi`
|
|
93
|
+
: gateway === "nc"
|
|
94
|
+
? ` if command -v nc >/dev/null 2>&1; then rm -f ${quote(timing)}; exec nc -U ${quote(socket)}; fi`
|
|
95
|
+
: "";
|
|
96
|
+
const pipe = forward ? `if [ "$SSH_ORIGINAL_COMMAND" = "phren-hook v1 pipe" ]; then\n${forward}\nfi\n` : "";
|
|
97
|
+
return `#!/bin/sh
|
|
98
|
+
# Phren Hook gateway. The phone's byte pipe goes straight to the Hook socket
|
|
99
|
+
# through a tiny forwarder so a loaded machine does not pay for a fresh node
|
|
100
|
+
# process; every other SSH command falls through to the node gateway.
|
|
101
|
+
export PHREN_BRIDGE_HOME=${quote(root)}
|
|
102
|
+
export PHREN_HERDR_HOME=${quote(herdr)}
|
|
103
|
+
export PHREN_PATH=${quote(store)}
|
|
104
|
+
export PHREN_PROFILE=${quote(profile)}
|
|
105
|
+
${pipe}exec ${quote(node)} ${quote(bundle)} ssh
|
|
106
|
+
`;
|
|
107
|
+
}
|
|
43
108
|
async function activate(version) {
|
|
44
109
|
const root = bridgeRoot();
|
|
45
110
|
const next = path.join(root, `current-${process.pid}`);
|
|
46
111
|
await symlink(path.join("versions", version), next);
|
|
47
112
|
await rename(next, path.join(root, "current"));
|
|
48
113
|
}
|
|
114
|
+
/** The launchd domain for the LaunchAgent: the GUI session when someone is
|
|
115
|
+
* logged in at the screen, else the per-user background domain an SSH login
|
|
116
|
+
* has (gui/<uid> does not exist there, so a bootstrap into it fails). */
|
|
117
|
+
export function launchDomain(uid, guiSession) {
|
|
118
|
+
return guiSession ? `gui/${uid}` : `user/${uid}`;
|
|
119
|
+
}
|
|
120
|
+
/** The commands that restart the Hook in `domain`, printed when launchd refuses. */
|
|
121
|
+
export function launchCommands(domain, plist) {
|
|
122
|
+
return [`launchctl bootout ${domain}/${label}`, `launchctl bootstrap ${domain} ${quote(plist)}`, `launchctl kickstart -k ${domain}/${label}`];
|
|
123
|
+
}
|
|
124
|
+
const launchAgentPlist = () => path.join(homedir(), "Library/LaunchAgents", `${label}.plist`);
|
|
125
|
+
async function guiSession(uid) {
|
|
126
|
+
return exec("launchctl", ["print", `gui/${uid}`]).then(() => true, () => false);
|
|
127
|
+
}
|
|
49
128
|
async function stopService() {
|
|
50
|
-
if (process.platform === "darwin")
|
|
51
|
-
|
|
129
|
+
if (process.platform === "darwin") {
|
|
130
|
+
// Either domain may hold the job from an earlier install.
|
|
131
|
+
for (const gui of [true, false])
|
|
132
|
+
await exec("launchctl", ["bootout", `${launchDomain(process.getuid(), gui)}/${label}`]).catch(() => { });
|
|
133
|
+
}
|
|
52
134
|
else
|
|
53
135
|
await exec("systemctl", ["--user", "stop", unit]).catch(() => { });
|
|
54
136
|
}
|
|
55
137
|
async function startService() {
|
|
56
138
|
if (process.platform === "darwin") {
|
|
139
|
+
const uid = process.getuid(), gui = await guiSession(uid), domain = launchDomain(uid, gui);
|
|
57
140
|
// bootout returns before launchd finishes releasing the old job. A valid
|
|
58
141
|
// immediate bootstrap can transiently fail with EIO during an update.
|
|
59
142
|
for (let attempt = 0;; attempt++) {
|
|
60
143
|
try {
|
|
61
|
-
await exec("launchctl", ["bootstrap",
|
|
144
|
+
await exec("launchctl", ["bootstrap", domain, launchAgentPlist()]);
|
|
62
145
|
break;
|
|
63
146
|
}
|
|
64
147
|
catch (error) {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
148
|
+
const stderr = String(error.stderr ?? "");
|
|
149
|
+
if (attempt < 5 && stderr.includes("Bootstrap failed: 5:")) {
|
|
150
|
+
await new Promise(resolve => setTimeout(resolve, 200 * (attempt + 1)));
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
throw new Error(`launchctl could not start the Phren Hook in ${domain}: ${stderr.trim() || error.message}\nTo start it by hand:\n ${launchCommands(domain, launchAgentPlist()).join("\n ")}`);
|
|
68
154
|
}
|
|
69
155
|
}
|
|
156
|
+
// RunAtLoad does not always fire for a job bootstrapped from an SSH login.
|
|
157
|
+
await exec("launchctl", ["kickstart", `${domain}/${label}`]).catch(() => { });
|
|
158
|
+
if (!gui)
|
|
159
|
+
console.log(`No one is logged in at this Mac's screen, so the Phren Hook runs in ${domain}. After a screen login, run phren bridge install again to move it into gui/${uid}.`);
|
|
70
160
|
}
|
|
71
161
|
else {
|
|
72
162
|
await exec("systemctl", ["--user", "daemon-reload"]);
|
|
@@ -78,10 +168,21 @@ export async function install(version, noService = false) {
|
|
|
78
168
|
throw new Error("Phren Hook supports macOS and Linux.");
|
|
79
169
|
if (!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version))
|
|
80
170
|
throw new Error("Invalid helper version.");
|
|
81
|
-
const
|
|
171
|
+
const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
|
|
172
|
+
if (!modules.has("hook"))
|
|
173
|
+
throw new Error(disabledHint("hook"));
|
|
174
|
+
const root = bridgeRoot(), herdr = herdrRoot(), versions = path.join(root, "versions");
|
|
82
175
|
await mkdir(versions, { recursive: true, mode: 0o700 });
|
|
83
176
|
await chmod(root, 0o700);
|
|
84
|
-
const
|
|
177
|
+
const serviceLog = path.join(root, "service.log");
|
|
178
|
+
const log = await open(serviceLog, "a", 0o600);
|
|
179
|
+
try {
|
|
180
|
+
await log.chmod(0o600);
|
|
181
|
+
}
|
|
182
|
+
finally {
|
|
183
|
+
await log.close();
|
|
184
|
+
}
|
|
185
|
+
const hookEdits = await planAgentHooks(path.join(root, "current/bridge-hook.mjs"), false, modules);
|
|
85
186
|
const own = fileURLToPath(import.meta.url);
|
|
86
187
|
const bundle = own.endsWith("bridge-hook.mjs") ? own : path.join(path.dirname(own), "..", "bridge-hook.mjs");
|
|
87
188
|
const destination = path.join(versions, version);
|
|
@@ -92,19 +193,23 @@ export async function install(version, noService = false) {
|
|
|
92
193
|
await copyFile(bundle, stagedBundle);
|
|
93
194
|
await rename(stagedBundle, installedBundle);
|
|
94
195
|
const previous = await readFile(path.join(root, "installed.json"), "utf8").then(v => JSON.parse(v)).catch(() => null);
|
|
95
|
-
|
|
196
|
+
const gateway = await detectGateway();
|
|
197
|
+
await atomic(path.join(root, "dispatch"), gatewayScript(gateway, {
|
|
198
|
+
root, herdr, store: modules.store, profile: modules.profile, node: process.execPath,
|
|
199
|
+
bundle: path.join(root, "current/bridge-hook.mjs"), socket: socketPath(), timing: path.join(root, "gateway.json"),
|
|
200
|
+
}), 0o700);
|
|
96
201
|
const environmentPath = [path.dirname(process.execPath), path.join(homedir(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
|
|
97
202
|
const program = path.join(root, "current/bridge-hook.mjs");
|
|
98
203
|
if (!noService) {
|
|
99
204
|
if (process.platform === "darwin") {
|
|
100
205
|
const folder = path.join(homedir(), "Library/LaunchAgents");
|
|
101
206
|
await mkdir(folder, { recursive: true });
|
|
102
|
-
await atomic(path.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string></dict><key>StandardErrorPath</key><string>${xml(path.join(root, "service.log"))}</string></dict></plist>\n`);
|
|
207
|
+
await atomic(path.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(path.join(root, "service.log"))}</string></dict></plist>\n`);
|
|
103
208
|
}
|
|
104
209
|
else {
|
|
105
210
|
const folder = path.join(homedir(), ".config/systemd/user");
|
|
106
211
|
await mkdir(folder, { recursive: true });
|
|
107
|
-
await atomic(path.join(folder, unit), `[Unit]\nDescription=Phren Hook\n[Service]\nExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve\nEnvironment=${systemdQuote("PATH=" + environmentPath)} ${systemdQuote("PHREN_BRIDGE_HOME=" + root)}\nRestart=on-failure\nRestartSec=3\nUMask=0077\n[Install]\nWantedBy=default.target\n`);
|
|
212
|
+
await atomic(path.join(folder, unit), `[Unit]\nDescription=Phren Hook\n[Service]\nExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve\nNice=-5\nEnvironment=${systemdQuote("PATH=" + environmentPath)} ${systemdQuote("PHREN_BRIDGE_HOME=" + root)} ${systemdQuote("PHREN_HERDR_HOME=" + herdr)} ${systemdQuote("PHREN_PATH=" + modules.store)} ${systemdQuote("PHREN_PROFILE=" + modules.profile)}\nRestart=on-failure\nRestartSec=3\nUMask=0077\n[Install]\nWantedBy=default.target\n`);
|
|
108
213
|
}
|
|
109
214
|
await stopService();
|
|
110
215
|
}
|
|
@@ -123,10 +228,17 @@ export async function install(version, noService = false) {
|
|
|
123
228
|
break;
|
|
124
229
|
await new Promise(resolve => setTimeout(resolve, 200));
|
|
125
230
|
}
|
|
126
|
-
if (!ready)
|
|
127
|
-
|
|
231
|
+
if (!ready) {
|
|
232
|
+
const uid = process.getuid(), domain = process.platform === "darwin" ? launchDomain(uid, await guiSession(uid)) : undefined;
|
|
233
|
+
throw new Error(`The new Phren Hook did not become ready. See ${serviceLog}. ` + (domain
|
|
234
|
+
? `To start it by hand:\n ${launchCommands(domain, launchAgentPlist()).join("\n ")}`
|
|
235
|
+
: `Check systemctl --user status ${unit}.`));
|
|
236
|
+
}
|
|
128
237
|
}
|
|
129
238
|
await applyAgentHooks(hookEdits);
|
|
239
|
+
if (await applyOpencodePlugin()) {
|
|
240
|
+
console.log("opencode chat: restart any opencode session started before now so it loads the transcript plugin.");
|
|
241
|
+
}
|
|
130
242
|
const keys = path.join(homedir(), ".ssh/authorized_keys");
|
|
131
243
|
const keyStat = await lstat(keys).catch(() => null);
|
|
132
244
|
if (keyStat && !keyStat.isSymbolicLink() && keyStat.isFile()) {
|
|
@@ -139,8 +251,9 @@ export async function install(version, noService = false) {
|
|
|
139
251
|
}
|
|
140
252
|
console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
|
|
141
253
|
}
|
|
142
|
-
await atomic(path.join(root, "installed.json"), JSON.stringify({ version, previous: previous?.version === version ? previous.previous : previous?.version, node: process.execPath }, null, 2) + "\n");
|
|
254
|
+
await atomic(path.join(root, "installed.json"), JSON.stringify({ version, previous: previous?.version === version ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
|
|
143
255
|
console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
|
|
256
|
+
console.log(`SSH gateway: ${gateway}${gateway === "node" ? " (no socat or nc -U found)" : ""}.`);
|
|
144
257
|
console.log(`Phren Hook ${version} installed${noService ? " (service not started)" : " and running"}. Run phren bridge doctor.`);
|
|
145
258
|
}
|
|
146
259
|
catch (error) {
|
|
@@ -162,15 +275,16 @@ export async function install(version, noService = false) {
|
|
|
162
275
|
export async function uninstall() {
|
|
163
276
|
await stopService();
|
|
164
277
|
if (process.platform === "darwin")
|
|
165
|
-
await unlink(
|
|
278
|
+
await unlink(launchAgentPlist()).catch(() => { });
|
|
166
279
|
else {
|
|
167
280
|
await exec("systemctl", ["--user", "disable", unit]).catch(() => { });
|
|
168
281
|
await unlink(path.join(homedir(), ".config/systemd/user", unit)).catch(() => { });
|
|
169
282
|
await exec("systemctl", ["--user", "daemon-reload"]).catch(() => { });
|
|
170
283
|
}
|
|
171
284
|
await applyAgentHooks(await planAgentHooks(path.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
|
|
285
|
+
await applyOpencodePlugin(true);
|
|
172
286
|
// Preserve journal, settings, uploaded images, rollback version and SSH backups.
|
|
173
|
-
console.log("Phren Hook stopped and its background service removed. Remove phren-iphone keys from authorized_keys to revoke
|
|
287
|
+
console.log("Phren Hook stopped and its background service removed. Remove phren-iphone and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
|
|
174
288
|
}
|
|
175
289
|
async function missingFile(operation) {
|
|
176
290
|
try {
|
|
@@ -182,11 +296,11 @@ async function missingFile(operation) {
|
|
|
182
296
|
throw error;
|
|
183
297
|
}
|
|
184
298
|
}
|
|
185
|
-
export async function planAgentHooks(program, remove = false) {
|
|
299
|
+
export async function planAgentHooks(program, remove = false, modules) {
|
|
186
300
|
const edits = [];
|
|
187
301
|
for (const [source, file] of [
|
|
188
|
-
["codex", path.join(
|
|
189
|
-
["claude", path.join(
|
|
302
|
+
["codex", path.join(codexHome(), "hooks.json")],
|
|
303
|
+
["claude", path.join(claudeConfigDir(), "settings.json")],
|
|
190
304
|
["copilot", path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "hooks/phren.json")],
|
|
191
305
|
]) {
|
|
192
306
|
const metadata = await missingFile(lstat(file));
|
|
@@ -194,7 +308,7 @@ export async function planAgentHooks(program, remove = false) {
|
|
|
194
308
|
throw new Error(`Agent settings require a manual update: ${file}`);
|
|
195
309
|
}
|
|
196
310
|
const before = await missingFile(readFile(file, "utf8"));
|
|
197
|
-
if (remove && before === undefined)
|
|
311
|
+
if ((remove || modules?.has("hook") === false) && before === undefined)
|
|
198
312
|
continue;
|
|
199
313
|
const parsed = before === undefined ? {} : JSON.parse(before);
|
|
200
314
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
@@ -205,7 +319,13 @@ export async function planAgentHooks(program, remove = false) {
|
|
|
205
319
|
const hooks = object(config.hooks);
|
|
206
320
|
const command = `${quote(process.execPath)} ${quote(program)} hook ${source}`;
|
|
207
321
|
const ownHook = (entry) => typeof entry === "string" && entry.endsWith(` ${quote(program)} hook ${source}`);
|
|
208
|
-
|
|
322
|
+
if (remove || modules?.has("hook") === false) {
|
|
323
|
+
const owned = Object.values(hooks).flatMap(objects).some(group => ownHook(group.command) || ownHook(group.bash) || objects(group.hooks).some(hook => ownHook(hook.command)));
|
|
324
|
+
const statusChanged = source === "claude" && JSON.stringify(usageStatusLine(config.statusLine, program, true)) !== JSON.stringify(config.statusLine);
|
|
325
|
+
if (!owned && !statusChanged)
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
for (const event of ["SessionStart", "UserPromptSubmit", "Stop", "PermissionRequest", "PreToolUse", "PostToolUse", ...(source === "claude" ? ["PreCompact"] : [])]) {
|
|
209
329
|
if (hooks[event] !== undefined && (!Array.isArray(hooks[event]) || hooks[event].some(v => !v || typeof v !== "object" || Array.isArray(v))))
|
|
210
330
|
throw new Error(`Invalid ${event} hooks: ${file}`);
|
|
211
331
|
if (source !== "copilot" && objects(hooks[event]).some(g => !Array.isArray(g.hooks)))
|
|
@@ -215,16 +335,30 @@ export async function planAgentHooks(program, remove = false) {
|
|
|
215
335
|
config.version = 1;
|
|
216
336
|
for (const event of ["SessionStart", "UserPromptSubmit"]) {
|
|
217
337
|
const entries = objects(hooks[event]).filter(h => !ownHook(h.bash) && !ownHook(h.command));
|
|
218
|
-
hooks[event] = remove ? entries : [...entries, { type: "command", bash: command, timeoutSec: 3 }];
|
|
338
|
+
hooks[event] = remove || modules?.has("hook") === false ? entries : [...entries, { type: "command", bash: command, timeoutSec: 3 }];
|
|
219
339
|
}
|
|
220
340
|
}
|
|
221
341
|
else {
|
|
222
|
-
for (const event of ["SessionStart", "UserPromptSubmit", "Stop", "PermissionRequest"]) {
|
|
342
|
+
for (const event of ["SessionStart", "UserPromptSubmit", "Stop", "PermissionRequest", "PreToolUse", "PostToolUse", ...(source === "claude" ? ["PreCompact"] : [])]) {
|
|
223
343
|
const groups = objects(hooks[event]).map(group => ({ ...group, hooks: objects(group.hooks).filter(h => !ownHook(h.command)) })).filter(group => group.hooks.length);
|
|
224
|
-
|
|
344
|
+
// Snapshot shell and file-edit calls so every card can show actual
|
|
345
|
+
// changed-file rows, including files outside the original cwd.
|
|
346
|
+
// Codex names tools differently across versions; filter its callbacks
|
|
347
|
+
// inside the Hook. Claude can narrow its registration here.
|
|
348
|
+
const group = event.endsWith("ToolUse") ? { ...(source === "claude" ? { matcher: "Bash|Write|Edit|MultiEdit|NotebookEdit|apply_patch|str_replace_editor" } : {}), hooks: [{ type: "command", command, timeout: 10 }] }
|
|
349
|
+
: { hooks: [{ type: "command", command, timeout: event === "PermissionRequest" ? 60 : 3 }] };
|
|
350
|
+
const owner = event.endsWith("ToolUse") ? "git" : "hook";
|
|
351
|
+
hooks[event] = remove || modules?.has("hook") === false || modules?.has(owner) === false ? groups : [...groups, group];
|
|
225
352
|
}
|
|
226
353
|
}
|
|
227
354
|
config.hooks = hooks;
|
|
355
|
+
if (source === "claude") {
|
|
356
|
+
const statusLine = usageStatusLine(config.statusLine, program, remove || modules?.has("hook") === false);
|
|
357
|
+
if (statusLine === undefined)
|
|
358
|
+
delete config.statusLine;
|
|
359
|
+
else
|
|
360
|
+
config.statusLine = statusLine;
|
|
361
|
+
}
|
|
228
362
|
const after = JSON.stringify(config, null, 2) + "\n";
|
|
229
363
|
if (after === before)
|
|
230
364
|
continue;
|
|
@@ -232,6 +366,48 @@ export async function planAgentHooks(program, remove = false) {
|
|
|
232
366
|
}
|
|
233
367
|
return edits;
|
|
234
368
|
}
|
|
369
|
+
const opencodePluginsDir = () => path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "opencode", "plugins");
|
|
370
|
+
/** The first line of every plugin copy phren wrote; a copy without it belongs to the user. */
|
|
371
|
+
export const OPENCODE_PLUGIN_MARKER = "// Installed by Phren Hook";
|
|
372
|
+
/** Whether to (re)write the installed plugin: a missing copy, or one phren wrote that is now out of date. */
|
|
373
|
+
export function opencodePluginNeedsWrite(existing, source) {
|
|
374
|
+
if (existing === undefined)
|
|
375
|
+
return true;
|
|
376
|
+
if (existing === source)
|
|
377
|
+
return false;
|
|
378
|
+
return existing.startsWith(OPENCODE_PLUGIN_MARKER);
|
|
379
|
+
}
|
|
380
|
+
async function opencodePluginSource() {
|
|
381
|
+
if (typeof OPENCODE_PLUGIN_SOURCE === "string")
|
|
382
|
+
return OPENCODE_PLUGIN_SOURCE;
|
|
383
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
384
|
+
for (const candidate of [
|
|
385
|
+
path.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
|
|
386
|
+
path.join(here, "..", "plugins", "opencode", "phren-transcript.js"),
|
|
387
|
+
]) {
|
|
388
|
+
const source = await missingFile(readFile(candidate, "utf8"));
|
|
389
|
+
if (source !== undefined)
|
|
390
|
+
return source;
|
|
391
|
+
}
|
|
392
|
+
return undefined;
|
|
393
|
+
}
|
|
394
|
+
async function applyOpencodePlugin(remove = false) {
|
|
395
|
+
const dir = opencodePluginsDir(), file = path.join(dir, "phren-transcript.js");
|
|
396
|
+
const source = await opencodePluginSource();
|
|
397
|
+
const existing = await missingFile(readFile(file, "utf8"));
|
|
398
|
+
if (remove) {
|
|
399
|
+
if (existing !== undefined && (existing === source || existing.startsWith(OPENCODE_PLUGIN_MARKER)))
|
|
400
|
+
await unlink(file);
|
|
401
|
+
return false;
|
|
402
|
+
}
|
|
403
|
+
if (source === undefined || !opencodePluginNeedsWrite(existing, source))
|
|
404
|
+
return false;
|
|
405
|
+
if (!(await lstat(path.dirname(dir)).catch(() => null))?.isDirectory())
|
|
406
|
+
return false;
|
|
407
|
+
await mkdir(dir, { recursive: true });
|
|
408
|
+
await atomic(file, source, 0o644);
|
|
409
|
+
return true;
|
|
410
|
+
}
|
|
235
411
|
async function applyAgentHooks(edits) {
|
|
236
412
|
for (const { file, before, after } of edits) {
|
|
237
413
|
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
@@ -262,3 +438,14 @@ export async function rollback() {
|
|
|
262
438
|
await startService();
|
|
263
439
|
await atomic(path.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config.previous, previous: config.version }) + "\n");
|
|
264
440
|
}
|
|
441
|
+
export async function reconcileModuleHooks(store, profile) {
|
|
442
|
+
const modules = moduleSnapshot(store, profile);
|
|
443
|
+
const root = bridgeRoot();
|
|
444
|
+
// Synced enablement alone never installs a host service or enrolls a key.
|
|
445
|
+
if (!await missingFile(readFile(path.join(root, "installed.json"))))
|
|
446
|
+
return;
|
|
447
|
+
await applyAgentHooks(await planAgentHooks(path.join(root, "current/bridge-hook.mjs"), false, modules));
|
|
448
|
+
await applyOpencodePlugin(!modules.has("hook"));
|
|
449
|
+
if (!modules.has("hook"))
|
|
450
|
+
await stopService();
|
|
451
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** A branch name the phone may ask for: plain characters, no leading dash or
|
|
3
|
+
* dot, and `git check-ref-format --branch` has the final say. */
|
|
4
|
+
export declare const worktreeBranch: z.ZodString;
|
|
5
|
+
export declare const launchWorktreeSchema: z.ZodObject<{
|
|
6
|
+
branch: z.ZodString;
|
|
7
|
+
}, z.core.$strict>;
|
|
8
|
+
export type LaunchWorktreeRequest = z.infer<typeof launchWorktreeSchema>;
|
|
9
|
+
/** The worktree folder's name for a branch: `phren/fix-login` is `phren-fix-login`. */
|
|
10
|
+
export declare function worktreeFolderName(branch: string): string;
|
|
11
|
+
export interface LaunchWorktree {
|
|
12
|
+
/** Where the agent starts: the same folder inside the new worktree as the project folder in its repository. */
|
|
13
|
+
cwd: string;
|
|
14
|
+
/** The new worktree's root. */
|
|
15
|
+
path: string;
|
|
16
|
+
branch: string;
|
|
17
|
+
/** Removes the worktree and its branch when the launch fails before anything ran there. */
|
|
18
|
+
discard(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/** Creates the worktree, or refuses with a message the phone shows as is. */
|
|
21
|
+
export declare function createLaunchWorktree(cwd: string, request: LaunchWorktreeRequest): Promise<LaunchWorktree>;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { mkdir, realpath, rm, stat } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { nonInteractiveGitEnv } from "../utils-helpers.js";
|
|
7
|
+
import { countGit } from "./metrics.js";
|
|
8
|
+
import { gitRoot } from "./projects.js";
|
|
9
|
+
import { BridgeError } from "./protocol.js";
|
|
10
|
+
/** A launch in a worktree of its own: `git worktree add` from the project's
|
|
11
|
+
* current HEAD into `<repo>/.claude/worktrees/<name>` on a new branch, so the
|
|
12
|
+
* agent's edits stay off the checkout the owner works in. The Changes
|
|
13
|
+
* screen's Workers tab then lists it through `/v1/git/worktrees`. */
|
|
14
|
+
const exec = promisify(execFile);
|
|
15
|
+
async function git(cwd, ...args) {
|
|
16
|
+
countGit("launch-worktree");
|
|
17
|
+
// A checkout of a large repository can take longer than a status read.
|
|
18
|
+
return (await exec("git", ["-C", cwd, "--no-pager", ...args], {
|
|
19
|
+
timeout: 120_000, maxBuffer: 1_048_576, env: nonInteractiveGitEnv({ ...process.env, GIT_CONFIG_NOSYSTEM: "1" }),
|
|
20
|
+
})).stdout;
|
|
21
|
+
}
|
|
22
|
+
/** A branch name the phone may ask for: plain characters, no leading dash or
|
|
23
|
+
* dot, and `git check-ref-format --branch` has the final say. */
|
|
24
|
+
export const worktreeBranch = z.string().trim().min(1).max(100)
|
|
25
|
+
.regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/, "A branch name uses letters, digits, dots, dashes, underscores and slashes.");
|
|
26
|
+
export const launchWorktreeSchema = z.object({ branch: worktreeBranch }).strict();
|
|
27
|
+
/** The worktree folder's name for a branch: `phren/fix-login` is `phren-fix-login`. */
|
|
28
|
+
export function worktreeFolderName(branch) {
|
|
29
|
+
return branch.replace(/[/.]+/g, "-").replace(/^-+|-+$/g, "") || "worktree";
|
|
30
|
+
}
|
|
31
|
+
/** Creates the worktree, or refuses with a message the phone shows as is. */
|
|
32
|
+
export async function createLaunchWorktree(cwd, request) {
|
|
33
|
+
const branch = request.branch;
|
|
34
|
+
const root = await gitRoot(cwd);
|
|
35
|
+
if (!root)
|
|
36
|
+
throw new BridgeError(409, "This folder is not a Git repository, so it cannot have a worktree. Turn off Work in a new worktree or choose a repository.");
|
|
37
|
+
const head = (await git(root, "rev-parse", "--verify", "--quiet", "HEAD^{commit}").catch(() => "")).trim();
|
|
38
|
+
if (!head)
|
|
39
|
+
throw new BridgeError(409, "This repository has no commits yet, so there is no HEAD to start a worktree from.");
|
|
40
|
+
if (!await git(root, "check-ref-format", "--branch", branch).then(() => true, () => false)) {
|
|
41
|
+
throw new BridgeError(400, `"${branch}" is not a valid Git branch name.`);
|
|
42
|
+
}
|
|
43
|
+
if (await git(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
|
|
44
|
+
throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
|
|
45
|
+
}
|
|
46
|
+
const worktree = path.join(root, ".claude", "worktrees", worktreeFolderName(branch));
|
|
47
|
+
if (await stat(worktree).then(() => true, () => false)) {
|
|
48
|
+
throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
|
|
49
|
+
}
|
|
50
|
+
await mkdir(path.dirname(worktree), { recursive: true });
|
|
51
|
+
try {
|
|
52
|
+
await git(root, "worktree", "add", "-b", branch, worktree, head);
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
const detail = error instanceof Error && "stderr" in error ? String(error.stderr ?? "").trim().split("\n").at(-1) : "";
|
|
56
|
+
throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
|
|
57
|
+
}
|
|
58
|
+
const abs = await realpath(worktree);
|
|
59
|
+
const inside = path.relative(root, await realpath(cwd));
|
|
60
|
+
const start = inside && !inside.startsWith("..") ? path.join(abs, inside) : abs;
|
|
61
|
+
const startDir = await stat(start).then(value => value.isDirectory(), () => false) ? start : abs;
|
|
62
|
+
return {
|
|
63
|
+
cwd: startDir, path: abs, branch,
|
|
64
|
+
async discard() {
|
|
65
|
+
await git(root, "worktree", "remove", "--force", abs).catch(() => rm(abs, { recursive: true, force: true }));
|
|
66
|
+
await git(root, "worktree", "prune").catch(() => undefined);
|
|
67
|
+
await git(root, "branch", "-D", branch).catch(() => undefined);
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** A bounded process pool. Cancelled waiters never start work. */
|
|
2
|
+
export declare class ProcessPool {
|
|
3
|
+
private readonly limit;
|
|
4
|
+
private active;
|
|
5
|
+
private waiting;
|
|
6
|
+
constructor(limit: number);
|
|
7
|
+
run<T>(signal: AbortSignal | undefined, work: () => Promise<T>): Promise<T>;
|
|
8
|
+
}
|
|
9
|
+
/** Shared by workspace and tab creation, including agent startup. */
|
|
10
|
+
export declare class LaunchLimiter {
|
|
11
|
+
private readonly now;
|
|
12
|
+
private active;
|
|
13
|
+
private starts;
|
|
14
|
+
constructor(now?: () => number);
|
|
15
|
+
run<T>(work: () => Promise<T>): Promise<T>;
|
|
16
|
+
}
|
|
17
|
+
/** A millisecond interval read once at startup from the environment variable
|
|
18
|
+
* `name`, when it is a number within `[min, max]`; otherwise `fallback`.
|
|
19
|
+
* Tests shorten these. */
|
|
20
|
+
export declare function intervalFromEnv(name: string, fallback: number, min?: number, max?: number): number;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { BridgeError } from "./protocol.js";
|
|
2
|
+
/** A bounded process pool. Cancelled waiters never start work. */
|
|
3
|
+
export class ProcessPool {
|
|
4
|
+
limit;
|
|
5
|
+
active = 0;
|
|
6
|
+
waiting = [];
|
|
7
|
+
constructor(limit) {
|
|
8
|
+
this.limit = limit;
|
|
9
|
+
}
|
|
10
|
+
async run(signal, work) {
|
|
11
|
+
signal?.throwIfAborted();
|
|
12
|
+
if (this.active >= this.limit) {
|
|
13
|
+
await new Promise((resolve, reject) => {
|
|
14
|
+
const ready = () => { signal?.removeEventListener("abort", abort); resolve(); };
|
|
15
|
+
const abort = () => { this.waiting = this.waiting.filter(w => w !== ready); reject(signal.reason); };
|
|
16
|
+
this.waiting.push(ready);
|
|
17
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
else
|
|
21
|
+
this.active++;
|
|
22
|
+
try {
|
|
23
|
+
signal?.throwIfAborted();
|
|
24
|
+
return await work();
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
const next = this.waiting.shift();
|
|
28
|
+
if (next)
|
|
29
|
+
next();
|
|
30
|
+
else
|
|
31
|
+
this.active--;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Shared by workspace and tab creation, including agent startup. */
|
|
36
|
+
export class LaunchLimiter {
|
|
37
|
+
now;
|
|
38
|
+
active = false;
|
|
39
|
+
starts = [];
|
|
40
|
+
constructor(now = Date.now) {
|
|
41
|
+
this.now = now;
|
|
42
|
+
}
|
|
43
|
+
async run(work) {
|
|
44
|
+
const now = this.now();
|
|
45
|
+
this.starts = this.starts.filter(at => now - at < 60_000);
|
|
46
|
+
if (this.active || this.starts.length >= 6)
|
|
47
|
+
throw new BridgeError(429, "Workspace launches are busy. Try again shortly.");
|
|
48
|
+
this.active = true;
|
|
49
|
+
this.starts.push(now);
|
|
50
|
+
try {
|
|
51
|
+
return await work();
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
this.active = false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** A millisecond interval read once at startup from the environment variable
|
|
59
|
+
* `name`, when it is a number within `[min, max]`; otherwise `fallback`.
|
|
60
|
+
* Tests shorten these. */
|
|
61
|
+
export function intervalFromEnv(name, fallback, min = 0, max = 60_000) {
|
|
62
|
+
const raw = process.env[name];
|
|
63
|
+
const value = Number(raw);
|
|
64
|
+
return raw && Number.isFinite(value) && value >= min && value <= max ? Math.floor(value) : fallback;
|
|
65
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type Json } from "./protocol.js";
|
|
2
|
+
/**
|
|
3
|
+
* Where a project lives on this computer, for the phone's "Open on a
|
|
4
|
+
* computer". The store's phren.project.yaml only knows the folder the project
|
|
5
|
+
* was added from — on whichever machine that was — so the answer comes from
|
|
6
|
+
* what this machine has actually seen: the Hook's activity journal (every
|
|
7
|
+
* folder an agent session ran in, newest first), Herdr's saved workspaces,
|
|
8
|
+
* phren's registered path, then the usual project roots. Only folders that
|
|
9
|
+
* exist here are offered.
|
|
10
|
+
*/
|
|
11
|
+
export interface LocatedFolder {
|
|
12
|
+
directory: string;
|
|
13
|
+
source: "activity" | "herdr" | "phren" | "search";
|
|
14
|
+
lastSeen?: string;
|
|
15
|
+
}
|
|
16
|
+
export declare function locateProject(project: string, activity: Json[], env?: NodeJS.ProcessEnv): Promise<LocatedFolder[]>;
|