@phren/cli 0.2.15 → 0.3.0
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 +195 -2
- package/dist/bridge/agent-hooks.js +1049 -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 +23 -0
- package/dist/bridge/code-note.js +51 -0
- package/dist/bridge/code-routes.d.ts +151 -0
- package/dist/bridge/code-routes.js +442 -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 +125 -0
- package/dist/bridge/dispatch-returns.js +283 -0
- package/dist/bridge/dispatch-tree.d.ts +54 -0
- package/dist/bridge/dispatch-tree.js +198 -0
- package/dist/bridge/dispatch.d.ts +210 -0
- package/dist/bridge/dispatch.js +286 -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 +28 -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 +61 -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 +54 -0
- package/dist/bridge/schedule-watch.js +255 -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 +36 -0
- package/dist/bridge/server-pane-routes.js +479 -0
- package/dist/bridge/server-routes.d.ts +108 -0
- package/dist/bridge/server-routes.js +556 -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 +96 -0
- package/dist/bridge/transcript-preview.js +491 -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 +46545 -21051
- package/dist/cli/actions.js +14 -1
- package/dist/cli/config-policy.js +25 -0
- 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.d.ts +0 -8
- package/dist/cli/extract.js +4 -7
- 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 +17 -4
- package/dist/content/validate.js +200 -122
- 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 +16 -1
- package/dist/data/access.js +31 -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 +525 -419
- 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 +11 -8
- 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 -15
- package/dist/hooks.js +14 -1
- 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 +15 -5
- 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 +68 -593
- package/dist/init/shared.js +2 -0
- package/dist/init/store-gitignore.d.ts +1 -6
- package/dist/init/store-gitignore.js +2 -8
- package/dist/init/teardown.d.ts +1 -1
- package/dist/init/teardown.js +2 -2
- package/dist/link/context-imports.d.ts +15 -0
- package/dist/link/context-imports.js +101 -0
- package/dist/link/context.js +1 -1
- package/dist/link/doctor.d.ts +22 -1
- package/dist/link/doctor.js +128 -58
- 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 -19
- package/dist/mcp/profile.js +64 -22
- package/dist/memory-ui-graph.runtime.js +525 -419
- package/dist/modules/code-package.d.ts +16 -0
- package/dist/modules/code-package.js +160 -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 +43 -8
- package/dist/project-config.d.ts +19 -1
- package/dist/project-config.js +29 -3
- package/dist/project-topics.d.ts +1 -0
- package/dist/project-topics.js +13 -10
- 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 -3
- package/dist/shared/retrieval.js +101 -12
- 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 +186 -0
- package/dist/tools/config.js +8 -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.d.ts +11 -0
- package/dist/tools/finding.js +180 -123
- 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 +52 -7
- package/dist/update.js +22 -11
- 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 +49 -7
- 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/server.js
CHANGED
|
@@ -1,48 +1,51 @@
|
|
|
1
|
+
import { FanoutMessages } from "./fanout-messages.js";
|
|
2
|
+
import { activateModules as moduleSnapshot } from "../modules/runtime.js";
|
|
3
|
+
import { disabledHint } from "../modules/registry.js";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { chmod, lstat, mkdir, readFile, rm, unlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
1
7
|
import { createServer } from "node:http";
|
|
2
|
-
import {
|
|
3
|
-
import { hostname } from "node:os";
|
|
8
|
+
import { cpus, hostname, loadavg } from "node:os";
|
|
4
9
|
import path from "node:path";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { z } from "zod";
|
|
10
|
+
import { WebSocketServer } from "ws";
|
|
11
|
+
import { relayTranscription } from "./speech-transcribe.js";
|
|
8
12
|
import { ActivityJournal } from "./activity.js";
|
|
9
|
-
import {
|
|
10
|
-
import { BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, serverName, socketPath, targetFromURL, targetSchema } from "./protocol.js";
|
|
11
|
-
import { repositoryDiff, webServers } from "./projects.js";
|
|
12
|
-
import { historicalImage, TranscriptReader, transcriptPath } from "./transcripts.js";
|
|
13
|
+
import { countTick } from "./metrics.js";
|
|
13
14
|
import { AgentHooks } from "./agent-hooks.js";
|
|
14
|
-
import {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
43
|
-
socket.send(data);
|
|
44
|
-
}
|
|
15
|
+
import { approvalPushCapability } from "./push.js";
|
|
16
|
+
import { startChangeRetention } from "./changes.js";
|
|
17
|
+
import { CodeReindexer, CodeRoutes } from "./code-routes.js";
|
|
18
|
+
import { WorkspaceContextUsage } from "./context.js";
|
|
19
|
+
import { DispatchService } from "./dispatch.js";
|
|
20
|
+
import { DispatchReturns } from "./dispatch-returns.js";
|
|
21
|
+
import { findPane, paneChatState, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
|
|
22
|
+
import { LaunchLimiter } from "./limits.js";
|
|
23
|
+
import { locateProject } from "./locate.js";
|
|
24
|
+
import { BridgeError, bridgeRoot, objects, PROTOCOL, provider, socketPath, targetSchema } from "./protocol.js";
|
|
25
|
+
import { CodexQuestions } from "./questions.js";
|
|
26
|
+
import { TabActivityStore } from "./tab-activity.js";
|
|
27
|
+
import { childAgentTree } from "./transcripts.js";
|
|
28
|
+
import { ModelCatalog } from "./models.js";
|
|
29
|
+
import { ModelSwitcher } from "./model-switch.js";
|
|
30
|
+
import { SideQuestions } from "./side-questions.js";
|
|
31
|
+
import { AccountUsageReader } from "./usage.js";
|
|
32
|
+
import { createScheduleLauncher, Scheduler, scheduleRunsFile } from "./schedules.js";
|
|
33
|
+
import { dailyCanaryDue, runCanary } from "./canary.js";
|
|
34
|
+
import { defaultPhrenPath } from "../shared.js";
|
|
35
|
+
import { capabilitiesForModules, createRouteHandler, requireRoute, selectedServer, workspacesReader } from "./server-routes.js";
|
|
36
|
+
import { overviewStream } from "./server-overview.js";
|
|
37
|
+
import { transcriptStreams } from "./server-stream.js";
|
|
38
|
+
import { launchSession } from "./server-launch.js";
|
|
39
|
+
import { localNames } from "./computer-names.js";
|
|
40
|
+
export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
|
|
41
|
+
export { streamCloseReason } from "./server-stream.js";
|
|
42
|
+
export { herdrAgentName, launchSession } from "./server-launch.js";
|
|
45
43
|
export async function serve(version) {
|
|
44
|
+
process.umask(0o077);
|
|
45
|
+
const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
|
|
46
|
+
if (!modules.has("hook"))
|
|
47
|
+
throw new BridgeError(404, disabledHint("hook"));
|
|
48
|
+
const activeCapabilities = capabilitiesForModules(modules);
|
|
46
49
|
const root = bridgeRoot();
|
|
47
50
|
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
48
51
|
await chmod(root, 0o700);
|
|
@@ -55,9 +58,66 @@ export async function serve(version) {
|
|
|
55
58
|
computerID = randomUUID();
|
|
56
59
|
await writeFile(identityFile, computerID, { flag: "wx", mode: 0o600 });
|
|
57
60
|
}
|
|
61
|
+
const launches = new LaunchLimiter();
|
|
62
|
+
const dispatches = modules.has("conductor")
|
|
63
|
+
? new DispatchService({ computerID, validateParentTarget: target => validateTarget(target, false, true),
|
|
64
|
+
originAgent: async (origin) => {
|
|
65
|
+
const pane = findPane(await snapshot(origin.server), origin);
|
|
66
|
+
const agent = provider.safeParse(pane?.agent);
|
|
67
|
+
return agent.success && typeof pane?.terminal_id === "string" ? { agent: agent.data, terminal: pane.terminal_id } : undefined;
|
|
68
|
+
} })
|
|
69
|
+
: undefined;
|
|
70
|
+
// Follows what dispatched workers do and tells the dispatching agent.
|
|
71
|
+
const returns = dispatches ? new DispatchReturns() : undefined;
|
|
72
|
+
const locatedDirectories = new Set();
|
|
58
73
|
const journal = new ActivityJournal();
|
|
59
|
-
const agentHooks = new AgentHooks();
|
|
60
|
-
|
|
74
|
+
const agentHooks = new AgentHooks(undefined, modules);
|
|
75
|
+
// Push is offered only once an APNs sender loaded; phones may still register.
|
|
76
|
+
if ("approvalPush" in activeCapabilities) {
|
|
77
|
+
Object.defineProperty(activeCapabilities, "approvalPush", { enumerable: true, get: () => approvalPushCapability(agentHooks.push.status) });
|
|
78
|
+
}
|
|
79
|
+
const modelCatalog = new ModelCatalog();
|
|
80
|
+
const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
|
|
81
|
+
const sideQuestions = new SideQuestions();
|
|
82
|
+
const contextUsage = new WorkspaceContextUsage();
|
|
83
|
+
const accountUsage = new AccountUsageReader();
|
|
84
|
+
const tabActivity = new TabActivityStore();
|
|
85
|
+
const codexQuestions = new CodexQuestions();
|
|
86
|
+
const scheduleStore = defaultPhrenPath();
|
|
87
|
+
const scheduler = modules.has("schedules") ? new Scheduler({ now: () => new Date(), store: scheduleStore, runsFile: scheduleRunsFile(),
|
|
88
|
+
launch: createScheduleLauncher((server, data) => launchSession(server, data), scheduleStore),
|
|
89
|
+
push: { notify: value => agentHooks.push.notifySchedule(value) },
|
|
90
|
+
locateProject: async (project) => (await locateProject(project, await journal.recent()))[0]?.directory }) : undefined;
|
|
91
|
+
const fanoutMessages = new FanoutMessages({ ...process.env, PHREN_PATH: scheduleStore }, {
|
|
92
|
+
validate: target => validateTarget(target, false, true),
|
|
93
|
+
tree: target => childAgentTree(target.source, target.session, 0, new Set(), computerID),
|
|
94
|
+
});
|
|
95
|
+
fanoutMessages.start();
|
|
96
|
+
const codeRoutes = modules.has("code") ? new CodeRoutes(scheduleStore) : undefined;
|
|
97
|
+
// The code module follows the git module's recorded file changes: an
|
|
98
|
+
// incremental re-index after a save, a full one after a branch switch.
|
|
99
|
+
const codeReindexer = codeRoutes ? new CodeReindexer({ store: scheduleStore }) : undefined;
|
|
100
|
+
if (codeReindexer)
|
|
101
|
+
agentHooks.changes.onRecord = files => codeReindexer.record(files);
|
|
102
|
+
// The node gateway writes its own cost after the first response byte, so a
|
|
103
|
+
// health read reflects the most recent node-path connection, if any.
|
|
104
|
+
function gatewayTiming() {
|
|
105
|
+
try {
|
|
106
|
+
const parsed = JSON.parse(readFileSync(path.join(root, "gateway.json"), "utf8"));
|
|
107
|
+
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0)
|
|
108
|
+
return Math.round(parsed.ms);
|
|
109
|
+
}
|
|
110
|
+
catch { /* the node gateway has not answered yet */ }
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
const info = { product: "phren-hook", protocol: PROTOCOL, version, computer: { id: computerID, name: hostname(), aliases: localNames() }, capabilities: activeCapabilities,
|
|
114
|
+
modules: Object.fromEntries(modules.modules.map(module => [module.name, module.version])),
|
|
115
|
+
store: modules.store, profile: modules.profile, generation: modules.generation,
|
|
116
|
+
get load() { return { average: Number(loadavg()[0].toFixed(2)), cpus: cpus().length }; },
|
|
117
|
+
get gatewayMs() { return gatewayTiming(); } };
|
|
118
|
+
// The canary launches through the same serialized launch path as the phone.
|
|
119
|
+
const canary = (trigger) => runCanary({ trigger, store: scheduleStore,
|
|
120
|
+
launch: (server, data) => launches.run(() => launchSession(server, data, { canary: true })), scheduler });
|
|
61
121
|
const old = await lstat(socketPath()).catch(() => null);
|
|
62
122
|
if (old) {
|
|
63
123
|
if (!old.isSocket() || (process.getuid && old.uid !== process.getuid()))
|
|
@@ -69,113 +129,20 @@ export async function serve(version) {
|
|
|
69
129
|
throw new Error("Phren Hook is already running.");
|
|
70
130
|
await unlink(socketPath());
|
|
71
131
|
}
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
case "/v1/health":
|
|
83
|
-
result = info;
|
|
84
|
-
break;
|
|
85
|
-
case "/v1/muxes":
|
|
86
|
-
result = { muxes: await servers() };
|
|
87
|
-
break;
|
|
88
|
-
case "/v1/activity":
|
|
89
|
-
result = { events: await journal.recent() };
|
|
90
|
-
break;
|
|
91
|
-
case "/v1/web-servers":
|
|
92
|
-
result = { servers: await webServers() };
|
|
93
|
-
break;
|
|
94
|
-
case "/v1/workspaces": {
|
|
95
|
-
const server = selectedServer(url), s = await snapshot(server);
|
|
96
|
-
await journal.record(server, objects(s.panes));
|
|
97
|
-
result = { ...workspaceSnapshot(s), phren: info };
|
|
98
|
-
break;
|
|
99
|
-
}
|
|
100
|
-
case "/v1/workspaces/panes":
|
|
101
|
-
result = await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || "");
|
|
102
|
-
break;
|
|
103
|
-
case "/v1/transcripts/blob": {
|
|
104
|
-
const target = targetFromURL(url);
|
|
105
|
-
await validateTarget(target);
|
|
106
|
-
const bytes = await historicalImage(await transcriptPath(target.source, target.session), Number(url.searchParams.get("line")), Number(url.searchParams.get("block")), target.source);
|
|
107
|
-
response.setHeader("Content-Type", "application/octet-stream");
|
|
108
|
-
response.end(bytes);
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
case "/v1/transcripts/history": {
|
|
112
|
-
const target = targetFromURL(url);
|
|
113
|
-
const before = z.coerce.number().int().positive().parse(url.searchParams.get("beforeLine"));
|
|
114
|
-
const abort = new AbortController();
|
|
115
|
-
response.once("close", () => { if (!response.writableEnded)
|
|
116
|
-
abort.abort(); });
|
|
117
|
-
await validateTarget(target);
|
|
118
|
-
const reader = new TranscriptReader(await transcriptPath(target.source, target.session), target.source);
|
|
119
|
-
const page = await reader.read(before, abort.signal);
|
|
120
|
-
result = { ...page, type: "older", source: target.source, session: target.session };
|
|
121
|
-
break;
|
|
122
|
-
}
|
|
123
|
-
default: throw new BridgeError(404, "Unknown Phren Hook route.");
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
else if (request.method === "POST") {
|
|
127
|
-
const data = await body(request);
|
|
128
|
-
if (url.pathname.startsWith("/v1/workspaces/")) {
|
|
129
|
-
result = await workspaceAction(selectedServer(url), url.pathname.split("/").at(-1), data);
|
|
130
|
-
}
|
|
131
|
-
else {
|
|
132
|
-
const target = targetSchema.parse(data.target);
|
|
133
|
-
const pane = await validateTarget(target, ["/v1/prompt", "/v1/upload", "/v1/keys"].includes(url.pathname));
|
|
134
|
-
if (url.pathname === "/v1/prompt") {
|
|
135
|
-
const text = z.string().min(1).max(32768).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t)).parse(data.text);
|
|
136
|
-
await rpc(target.server, "agent.prompt", { target: target.pane, text });
|
|
137
|
-
result = { ok: true };
|
|
138
|
-
}
|
|
139
|
-
else if (url.pathname === "/v1/keys") {
|
|
140
|
-
if (JSON.stringify(data.keys) !== '["Escape"]' || pane.agent_status !== "working")
|
|
141
|
-
throw new BridgeError(409, "This agent is no longer working.");
|
|
142
|
-
await rpc(target.server, "agent.send_keys", { target: target.pane, keys: ["esc"] });
|
|
143
|
-
result = { ok: true };
|
|
144
|
-
}
|
|
145
|
-
else if (url.pathname === "/v1/upload") {
|
|
146
|
-
const name = z.string().regex(/^[A-Za-z0-9_.-]{1,200}\.(png|jpg|jpeg|gif|webp)$/i).parse(data.name);
|
|
147
|
-
const encoded = z.string().max(11_184_812).regex(/^[A-Za-z0-9+/]*={0,2}$/).parse(data.data);
|
|
148
|
-
const bytes = Buffer.from(encoded, "base64");
|
|
149
|
-
if (!bytes.length || bytes.length > MAX_FRAME)
|
|
150
|
-
throw new BridgeError(413, "The image is too large.");
|
|
151
|
-
result = { ok: true, path: await saveUpload(target.session, name, bytes) };
|
|
152
|
-
}
|
|
153
|
-
else if (url.pathname === "/v1/diff")
|
|
154
|
-
result = await repositoryDiff(await trustedDirectory(pane));
|
|
155
|
-
else if (url.pathname === "/v1/approvals/answer") {
|
|
156
|
-
await agentHooks.answer(target, z.string().uuid().parse(data.actionId), data.decision);
|
|
157
|
-
result = { ok: true };
|
|
158
|
-
}
|
|
159
|
-
else if (url.pathname === "/v1/questions/answer")
|
|
160
|
-
throw new BridgeError(409, "Answer this agent's request in the Phren terminal.");
|
|
161
|
-
else
|
|
162
|
-
throw new BridgeError(404, "Unknown Phren Hook route.");
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
else
|
|
166
|
-
throw new BridgeError(405, "Unsupported request method.");
|
|
167
|
-
const payload = JSON.stringify(result);
|
|
168
|
-
if (Buffer.byteLength(payload) > MAX_FRAME)
|
|
169
|
-
throw new BridgeError(413, "The response is too large.");
|
|
170
|
-
response.setHeader("Content-Type", "application/json");
|
|
171
|
-
response.end(payload);
|
|
172
|
-
}
|
|
173
|
-
catch (error) {
|
|
174
|
-
response.statusCode = error instanceof BridgeError ? error.status : error instanceof z.ZodError || error instanceof SyntaxError ? 400 : 503;
|
|
175
|
-
response.setHeader("Content-Type", "application/json");
|
|
176
|
-
response.end(JSON.stringify({ error: error instanceof BridgeError ? error.message : "Phren Hook could not complete this request. Run phren bridge doctor on the computer." }));
|
|
177
|
-
}
|
|
132
|
+
const stopRetention = modules.has("git") ? await startChangeRetention() : () => { };
|
|
133
|
+
if (modules.has("git"))
|
|
134
|
+
await rm(path.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
135
|
+
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
|
|
136
|
+
const { stream } = streams;
|
|
137
|
+
// The phone's overview, pushed over a WebSocket when it changes.
|
|
138
|
+
const overview = overviewStream({
|
|
139
|
+
read: workspacesReader({ modules, info, agentHooks, journal, tabActivity, contextUsage }),
|
|
140
|
+
info: () => ({ ...info, capabilities: info.capabilities }),
|
|
141
|
+
renew: server => agentHooks.overview.renew(server),
|
|
178
142
|
});
|
|
143
|
+
const http = createServer(createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
|
|
144
|
+
journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, sideQuestions, accountUsage, codexQuestions, launches, locatedDirectories,
|
|
145
|
+
fanoutMessages, canary, streams, returns }));
|
|
179
146
|
http.requestTimeout = 20_000;
|
|
180
147
|
http.headersTimeout = 10_000;
|
|
181
148
|
http.maxHeadersCount = 32;
|
|
@@ -183,148 +150,79 @@ export async function serve(version) {
|
|
|
183
150
|
http.on("upgrade", (request, socket, head) => {
|
|
184
151
|
try {
|
|
185
152
|
const url = new URL(request.url || "/", "http://phren.local");
|
|
186
|
-
if (!["/v1/transcripts", "/v1/status"].includes(url.pathname) || url.origin !== "http://phren.local") {
|
|
153
|
+
if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe"].includes(url.pathname) || url.origin !== "http://phren.local") {
|
|
187
154
|
socket.destroy();
|
|
188
155
|
return;
|
|
189
156
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
let reader, timer;
|
|
200
|
-
let unwatch;
|
|
201
|
-
let busy = false, ready = false, first = true;
|
|
202
|
-
let initialPane;
|
|
203
|
-
const pending = [];
|
|
204
|
-
const stop = () => { abort.abort(); clearInterval(timer); unwatch?.(); pending.length = 0; };
|
|
205
|
-
client.once("close", stop);
|
|
206
|
-
client.once("error", stop);
|
|
207
|
-
const tick = async () => {
|
|
208
|
-
if (busy || !ready || abort.signal.aborted)
|
|
209
|
-
return;
|
|
210
|
-
busy = true;
|
|
211
|
-
try {
|
|
212
|
-
if (first || pending.length === 0) {
|
|
213
|
-
const pane = first ? initialPane : await validateTarget(target);
|
|
214
|
-
if (reader) {
|
|
215
|
-
const page = await reader.read(undefined, abort.signal);
|
|
216
|
-
if (first || page.entries.length || page.reset)
|
|
217
|
-
send(client, { ...page, type: first || page.reset ? "backlog" : "append", source: target.source,
|
|
218
|
-
session: target.session });
|
|
219
|
-
}
|
|
220
|
-
else {
|
|
221
|
-
const pendingApproval = agentHooks.approval(target);
|
|
222
|
-
send(client, { agentStatus: { source: target.source, session: target.session,
|
|
223
|
-
status: pendingApproval ? "waiting" : pane.agent_status, pendingApproval, capabilities } });
|
|
224
|
-
}
|
|
225
|
-
first = false;
|
|
157
|
+
requireRoute(modules, "WS", url.pathname);
|
|
158
|
+
// Parsed before the upgrade: an invalid server name is refused as the other routes refuse it.
|
|
159
|
+
const overviewServer = url.pathname === "/v1/overview" ? selectedServer(url) : undefined;
|
|
160
|
+
ws.handleUpgrade(request, socket, head, client => {
|
|
161
|
+
while (ws.clients.size > 16) {
|
|
162
|
+
const oldest = ws.clients.values().next().value;
|
|
163
|
+
oldest.close(1008, "Too many connections; reconnect");
|
|
164
|
+
oldest.terminate();
|
|
165
|
+
ws.clients.delete(oldest);
|
|
226
166
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
const page = await reader.read(before, abort.signal);
|
|
231
|
-
send(client, { ...page, type: "older", source: target.source, session: target.session });
|
|
167
|
+
if (overviewServer !== undefined) {
|
|
168
|
+
overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1");
|
|
169
|
+
return;
|
|
232
170
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
stop();
|
|
236
|
-
client.close(1011, "The conversation changed; refresh");
|
|
237
|
-
}
|
|
238
|
-
finally {
|
|
239
|
-
busy = false;
|
|
240
|
-
if (pending.length)
|
|
241
|
-
void tick();
|
|
242
|
-
}
|
|
243
|
-
};
|
|
244
|
-
client.on("message", bytes => {
|
|
245
|
-
try {
|
|
246
|
-
const message = object(JSON.parse(bytes.toString()));
|
|
247
|
-
if (message.type !== "older" || url.pathname !== "/v1/transcripts" || abort.signal.aborted)
|
|
171
|
+
if (url.pathname === "/v1/speech/transcribe") {
|
|
172
|
+
void relayTranscription(client, url.searchParams).catch(() => client.close(1011, "Transcription unavailable"));
|
|
248
173
|
return;
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
if (!pending.includes(before))
|
|
253
|
-
pending.push(before);
|
|
254
|
-
void tick();
|
|
255
|
-
}
|
|
256
|
-
catch {
|
|
257
|
-
stop();
|
|
258
|
-
client.close(1008, "Invalid history request");
|
|
259
|
-
}
|
|
260
|
-
});
|
|
261
|
-
try {
|
|
262
|
-
initialPane = await validateTarget(target);
|
|
263
|
-
if (abort.signal.aborted)
|
|
264
|
-
return;
|
|
265
|
-
unwatch = agentHooks.watch(target);
|
|
266
|
-
reader = url.pathname === "/v1/transcripts" ? new TranscriptReader(await transcriptPath(target.source, target.session), target.source) : undefined;
|
|
267
|
-
if (abort.signal.aborted) {
|
|
268
|
-
stop();
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
ready = true;
|
|
272
|
-
timer = setInterval(() => { void tick(); }, reader ? 500 : 1500);
|
|
273
|
-
await tick();
|
|
174
|
+
}
|
|
175
|
+
void stream(client, url).catch(() => client.close(1011, "Conversation unavailable; refresh"));
|
|
176
|
+
});
|
|
274
177
|
}
|
|
275
|
-
catch
|
|
276
|
-
|
|
277
|
-
throw error;
|
|
178
|
+
catch {
|
|
179
|
+
socket.destroy();
|
|
278
180
|
}
|
|
279
|
-
}
|
|
181
|
+
});
|
|
280
182
|
await new Promise((resolve, reject) => { http.once("error", reject); http.listen(socketPath(), () => resolve()); });
|
|
281
183
|
await chmod(socketPath(), 0o600);
|
|
282
184
|
await agentHooks.start();
|
|
185
|
+
void scheduler?.tick().catch(() => { });
|
|
186
|
+
const scheduleTimer = scheduler ? setInterval(() => { countTick("schedules"); void scheduler.tick().catch(() => { }); }, 30_000) : undefined;
|
|
187
|
+
// Off unless PHREN_CANARY_DAILY=1 or `phren canary --daily on`.
|
|
188
|
+
const canaryTimer = setInterval(() => { countTick("canary"); void dailyCanaryDue().then(due => due ? canary("daily") : undefined).catch(() => { }); }, 10 * 60_000);
|
|
283
189
|
let recording = false;
|
|
284
190
|
const activityTimer = setInterval(() => {
|
|
191
|
+
countTick("activity");
|
|
285
192
|
if (recording)
|
|
286
193
|
return;
|
|
287
194
|
recording = true;
|
|
288
195
|
void (async () => {
|
|
289
|
-
|
|
196
|
+
// The server list is reused for SERVER_LIST_REUSE_MS instead of pinging
|
|
197
|
+
// every Herdr directory each tick, and a snapshot an open chat or the
|
|
198
|
+
// overview fetched in the last four seconds is reused; otherwise each
|
|
199
|
+
// tick still takes its own, so activity keeps its 5 s resolution.
|
|
200
|
+
const live = await recentServers();
|
|
201
|
+
await tabActivity.pruneServers(live.map(server => String(server.session)));
|
|
202
|
+
for (const server of live) {
|
|
290
203
|
try {
|
|
291
|
-
|
|
204
|
+
const name = String(server.session), current = await sharedSnapshot(name, 4000);
|
|
205
|
+
await tabActivity.observe(name, current);
|
|
206
|
+
await journal.record(name, objects(current.panes));
|
|
207
|
+
// Approvals drawn in a terminal reach a phone with phren closed.
|
|
208
|
+
await agentHooks.observeWaitingPanes(name, objects(current.panes), async (pane) => {
|
|
209
|
+
const state = await paneChatState(name, pane, { tokenWhenIdentified: false });
|
|
210
|
+
const parsed = targetSchema.safeParse({ server: name, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id,
|
|
211
|
+
source: pane.agent, session: state.sessionId });
|
|
212
|
+
return parsed.success ? parsed.data : undefined;
|
|
213
|
+
});
|
|
292
214
|
}
|
|
293
215
|
catch { /* A disconnected computer keeps its previous local activity. */ }
|
|
294
216
|
}
|
|
217
|
+
// Dispatch returns ride this tick and its shared snapshots. The returns
|
|
218
|
+
// loop throttles its own peer polls and never holds up activity.
|
|
219
|
+
void returns?.tick();
|
|
295
220
|
})().finally(() => { recording = false; }).catch(() => { });
|
|
296
221
|
}, 5000);
|
|
297
222
|
await new Promise(resolve => {
|
|
298
|
-
const stop = () => { clearInterval(activityTimer); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
|
|
223
|
+
const stop = () => { fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
|
|
299
224
|
process.once("SIGTERM", stop);
|
|
300
225
|
process.once("SIGINT", stop);
|
|
301
226
|
});
|
|
302
227
|
await unlink(socketPath()).catch(() => { });
|
|
303
228
|
}
|
|
304
|
-
async function workspaceAction(server, operation, data) {
|
|
305
|
-
if (!["focus", "rename", "create", "close"].includes(operation))
|
|
306
|
-
throw new BridgeError(400, "Unsupported Herdr action.");
|
|
307
|
-
const s = await snapshot(server);
|
|
308
|
-
const workspace = typeof data.workspaceId === "string" ? data.workspaceId : undefined;
|
|
309
|
-
const tab = typeof data.tabId === "string" ? data.tabId : undefined;
|
|
310
|
-
const pane = typeof data.paneId === "string" ? data.paneId : undefined;
|
|
311
|
-
if (workspace && !objects(s.workspaces).some(w => w.workspace_id === workspace))
|
|
312
|
-
throw new BridgeError(409, "The workspace changed.");
|
|
313
|
-
if (tab && !objects(s.tabs).some(t => t.tab_id === tab && (!workspace || t.workspace_id === workspace)))
|
|
314
|
-
throw new BridgeError(409, "The tab changed.");
|
|
315
|
-
if (pane && !objects(s.panes).some(p => p.pane_id === pane && (!tab || p.tab_id === tab) && (!workspace || p.workspace_id === workspace)))
|
|
316
|
-
throw new BridgeError(409, "The pane changed.");
|
|
317
|
-
const label = data.label === undefined ? undefined : z.string().min(1).max(200).refine(t => !/[\x00-\x1f\x7f]/.test(t)).parse(data.label);
|
|
318
|
-
const cwd = data.cwd === undefined ? undefined : z.string().max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
319
|
-
if (operation === "create")
|
|
320
|
-
await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: {} });
|
|
321
|
-
else if (!workspace && !tab && !pane)
|
|
322
|
-
throw new BridgeError(400, "Choose a Herdr destination.");
|
|
323
|
-
else if (pane && operation === "focus")
|
|
324
|
-
await rpc(server, "pane.focus", { pane_id: pane });
|
|
325
|
-
else if (pane)
|
|
326
|
-
throw new BridgeError(400, "This pane action is not available.");
|
|
327
|
-
else
|
|
328
|
-
await rpc(server, `${tab ? "tab" : "workspace"}.${operation}`, { ...(tab ? { tab_id: tab } : { workspace_id: workspace }), ...(label ? { label } : {}) });
|
|
329
|
-
return { ok: true };
|
|
330
|
-
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type Json, type Provider } from "./protocol.js";
|
|
2
|
+
import { type LocalServer } from "./projects.js";
|
|
3
|
+
export interface SessionServer extends LocalServer {
|
|
4
|
+
source: "started" | "mentioned";
|
|
5
|
+
}
|
|
6
|
+
export declare function mentionedPorts(text: string): Set<number>;
|
|
7
|
+
/** Whether `pid` is one of `roots` or descends from one. */
|
|
8
|
+
export declare function descendsFrom(pid: number | undefined, roots: ReadonlySet<number>, parents: ReadonlyMap<number, number>): boolean;
|
|
9
|
+
/** The ownership rule itself, free of I/O so it is tested directly. */
|
|
10
|
+
export declare function attributeServers(input: {
|
|
11
|
+
servers: readonly LocalServer[];
|
|
12
|
+
parents: ReadonlyMap<number, number>;
|
|
13
|
+
ownRoots: ReadonlySet<number>;
|
|
14
|
+
otherRoots: ReadonlySet<number>;
|
|
15
|
+
mentioned: ReadonlySet<number>;
|
|
16
|
+
}): SessionServer[];
|
|
17
|
+
export declare function sessionWebServers(target: {
|
|
18
|
+
server: string;
|
|
19
|
+
pane: string;
|
|
20
|
+
source: Provider;
|
|
21
|
+
session: string;
|
|
22
|
+
}, pane: Json): Promise<{
|
|
23
|
+
servers: SessionServer[];
|
|
24
|
+
}>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { open, stat } from "node:fs/promises";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { object, objects } from "./protocol.js";
|
|
5
|
+
import { rpc, snapshot } from "./herdr.js";
|
|
6
|
+
import { webServers } from "./projects.js";
|
|
7
|
+
import { transcriptPath } from "./transcripts.js";
|
|
8
|
+
/**
|
|
9
|
+
* The web servers one agent session owns, for the chat's ••• menu. Never a
|
|
10
|
+
* machine-wide list: a server belongs to a session only when
|
|
11
|
+
*
|
|
12
|
+
* - "started": its listening process descends from the session's pane (the
|
|
13
|
+
* pane's shell or foreground processes), from a process running this
|
|
14
|
+
* conversation by id, or from one holding its transcript open (a Claude
|
|
15
|
+
* Code background job runs its tools under its own process, not under the
|
|
16
|
+
* pane's shell); or
|
|
17
|
+
* - "mentioned": its port appears as a loopback address in the session's
|
|
18
|
+
* transcript and no other pane's process tree owns it. This is how a server
|
|
19
|
+
* an agent detached (`nohup … &`, reparented to PID 1) is still found.
|
|
20
|
+
*
|
|
21
|
+
* Everything else is left out, including a port another pane owns.
|
|
22
|
+
*/
|
|
23
|
+
const exec = promisify(execFile);
|
|
24
|
+
/** How far a process tree is followed upward before giving up. */
|
|
25
|
+
const MAX_DEPTH = 64;
|
|
26
|
+
/** The transcript tail scanned for loopback addresses. */
|
|
27
|
+
const TRANSCRIPT_TAIL_BYTES = 1_048_576;
|
|
28
|
+
/** Other panes checked for ownership of a mentioned port. */
|
|
29
|
+
const MAX_OTHER_PANES = 48;
|
|
30
|
+
/** `localhost:3000`, `127.0.0.1:5173`, `0.0.0.0:8080`, `[::1]:4000`, with or without a scheme. */
|
|
31
|
+
const LOOPBACK_PORT = /(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]):(\d{2,5})\b/gi;
|
|
32
|
+
export function mentionedPorts(text) {
|
|
33
|
+
const ports = new Set();
|
|
34
|
+
for (const match of text.matchAll(LOOPBACK_PORT)) {
|
|
35
|
+
const port = Number(match[1]);
|
|
36
|
+
if (port > 0 && port <= 65_535)
|
|
37
|
+
ports.add(port);
|
|
38
|
+
}
|
|
39
|
+
return ports;
|
|
40
|
+
}
|
|
41
|
+
/** Whether `pid` is one of `roots` or descends from one. */
|
|
42
|
+
export function descendsFrom(pid, roots, parents) {
|
|
43
|
+
let current = pid;
|
|
44
|
+
for (let depth = 0; current !== undefined && current > 1 && depth < MAX_DEPTH; depth++) {
|
|
45
|
+
if (roots.has(current))
|
|
46
|
+
return true;
|
|
47
|
+
current = parents.get(current);
|
|
48
|
+
}
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
/** The ownership rule itself, free of I/O so it is tested directly. */
|
|
52
|
+
export function attributeServers(input) {
|
|
53
|
+
const result = [];
|
|
54
|
+
for (const server of input.servers) {
|
|
55
|
+
if (descendsFrom(server.pid, input.ownRoots, input.parents))
|
|
56
|
+
result.push({ ...server, source: "started" });
|
|
57
|
+
else if (input.mentioned.has(server.port) && !descendsFrom(server.pid, input.otherRoots, input.parents)) {
|
|
58
|
+
result.push({ ...server, source: "mentioned" });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return result.sort((a, b) => Number(a.source === "mentioned") - Number(b.source === "mentioned") || a.port - b.port);
|
|
62
|
+
}
|
|
63
|
+
/** The process tree, plus the processes running this conversation by id: a
|
|
64
|
+
* Claude Code background job runs as `<claude> --session-id <id>` under its
|
|
65
|
+
* own host, while the pane only shows `claude attach <prefix>`. */
|
|
66
|
+
async function processTable(session) {
|
|
67
|
+
const { stdout } = await exec("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4000, maxBuffer: 16_777_216 });
|
|
68
|
+
const parents = new Map();
|
|
69
|
+
const runners = [];
|
|
70
|
+
const flag = `--session-id ${session}`;
|
|
71
|
+
for (const line of stdout.split("\n")) {
|
|
72
|
+
const match = /^\s*(\d+)\s+(\d+)\s?(.*)$/.exec(line);
|
|
73
|
+
if (!match)
|
|
74
|
+
continue;
|
|
75
|
+
const pid = Number(match[1]), ppid = Number(match[2]);
|
|
76
|
+
parents.set(pid, ppid);
|
|
77
|
+
const args = match[3];
|
|
78
|
+
const at = args.indexOf(flag);
|
|
79
|
+
// The id must end there: a longer id sharing this prefix is another session.
|
|
80
|
+
if (at >= 0 && !/[\w-]/.test(args[at + flag.length] ?? "") && pid !== process.pid)
|
|
81
|
+
runners.push(pid);
|
|
82
|
+
}
|
|
83
|
+
return { parents, runners };
|
|
84
|
+
}
|
|
85
|
+
async function paneRoots(server, paneId) {
|
|
86
|
+
const answer = await rpc(server, "pane.process_info", { pane_id: paneId }).catch(() => ({}));
|
|
87
|
+
const info = object(answer.process_info);
|
|
88
|
+
const pids = [info.shell_pid, ...objects(info.foreground_processes).map(process => process.pid)];
|
|
89
|
+
return pids.filter((pid) => Number.isSafeInteger(pid) && Number(pid) > 1);
|
|
90
|
+
}
|
|
91
|
+
/** Processes holding the transcript open: a background-job agent's own process. */
|
|
92
|
+
async function transcriptHolders(file) {
|
|
93
|
+
const lsof = process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof";
|
|
94
|
+
const { stdout } = await exec(lsof, ["-t", "--", file], { timeout: 3000 }).catch(() => ({ stdout: "" }));
|
|
95
|
+
// The Hook itself reads the transcript to stream the chat; it is never the owner.
|
|
96
|
+
return stdout.split("\n").map(Number).filter(pid => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid);
|
|
97
|
+
}
|
|
98
|
+
async function transcriptTail(file) {
|
|
99
|
+
const size = (await stat(file)).size;
|
|
100
|
+
const handle = await open(file, "r");
|
|
101
|
+
try {
|
|
102
|
+
const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
|
|
103
|
+
const buffer = Buffer.alloc(length);
|
|
104
|
+
await handle.read(buffer, 0, length, size - length);
|
|
105
|
+
return buffer.toString("utf8");
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
await handle.close();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
export async function sessionWebServers(target, pane) {
|
|
112
|
+
const [servers, table, own, file] = await Promise.all([
|
|
113
|
+
webServers(), processTable(target.session), paneRoots(target.server, pane.pane_id),
|
|
114
|
+
transcriptPath(target.source, target.session).catch(() => undefined),
|
|
115
|
+
]);
|
|
116
|
+
const parents = table.parents;
|
|
117
|
+
const ownRoots = new Set([...own, ...table.runners]);
|
|
118
|
+
let mentioned = new Set();
|
|
119
|
+
if (file) {
|
|
120
|
+
for (const pid of await transcriptHolders(file))
|
|
121
|
+
ownRoots.add(pid);
|
|
122
|
+
mentioned = mentionedPorts(await transcriptTail(file).catch(() => ""));
|
|
123
|
+
}
|
|
124
|
+
// Other panes are only consulted for a mentioned port nobody here started.
|
|
125
|
+
const otherRoots = new Set();
|
|
126
|
+
const unclaimed = servers.some(server => mentioned.has(server.port) && !descendsFrom(server.pid, ownRoots, parents));
|
|
127
|
+
if (unclaimed) {
|
|
128
|
+
const others = objects((await snapshot(target.server)).panes).filter(other => other.pane_id !== pane.pane_id).slice(0, MAX_OTHER_PANES);
|
|
129
|
+
for (const roots of await Promise.all(others.map(other => paneRoots(target.server, other.pane_id)))) {
|
|
130
|
+
for (const pid of roots)
|
|
131
|
+
if (!ownRoots.has(pid))
|
|
132
|
+
otherRoots.add(pid);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { servers: attributeServers({ servers, parents, ownRoots, otherRoots, mentioned }) };
|
|
136
|
+
}
|