@phren/cli 0.2.15 → 0.2.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/agent-instructions.d.ts +12 -0
- package/dist/agent-instructions.js +52 -0
- package/dist/bridge/agent-hook-stores.d.ts +32 -0
- package/dist/bridge/agent-hook-stores.js +67 -0
- package/dist/bridge/agent-hooks.d.ts +193 -2
- package/dist/bridge/agent-hooks.js +1045 -38
- package/dist/bridge/canary.d.ts +27 -0
- package/dist/bridge/canary.js +189 -0
- package/dist/bridge/changes.d.ts +57 -0
- package/dist/bridge/changes.js +403 -0
- package/dist/bridge/client.d.ts +3 -0
- package/dist/bridge/client.js +36 -0
- package/dist/bridge/code-note.d.ts +22 -0
- package/dist/bridge/code-note.js +42 -0
- package/dist/bridge/code-routes.d.ts +133 -0
- package/dist/bridge/code-routes.js +319 -0
- package/dist/bridge/codex-threads.d.ts +27 -0
- package/dist/bridge/codex-threads.js +442 -0
- package/dist/bridge/command.d.ts +7 -0
- package/dist/bridge/command.js +50 -5
- package/dist/bridge/computer-names.d.ts +4 -0
- package/dist/bridge/computer-names.js +16 -0
- package/dist/bridge/computers.d.ts +9 -0
- package/dist/bridge/computers.js +111 -0
- package/dist/bridge/context.d.ts +14 -0
- package/dist/bridge/context.js +149 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +93 -0
- package/dist/bridge/dispatch-hosts.d.ts +23 -0
- package/dist/bridge/dispatch-hosts.js +25 -0
- package/dist/bridge/dispatch-returns.d.ts +123 -0
- package/dist/bridge/dispatch-returns.js +279 -0
- package/dist/bridge/dispatch-tree.d.ts +54 -0
- package/dist/bridge/dispatch-tree.js +198 -0
- package/dist/bridge/dispatch.d.ts +207 -0
- package/dist/bridge/dispatch.js +261 -0
- package/dist/bridge/enroll.d.ts +31 -0
- package/dist/bridge/enroll.js +236 -0
- package/dist/bridge/fanout-messages.d.ts +74 -0
- package/dist/bridge/fanout-messages.js +230 -0
- package/dist/bridge/fanouts.d.ts +160 -0
- package/dist/bridge/fanouts.js +702 -0
- package/dist/bridge/file-range.d.ts +16 -0
- package/dist/bridge/file-range.js +90 -0
- package/dist/bridge/files.d.ts +20 -0
- package/dist/bridge/files.js +54 -0
- package/dist/bridge/git-publish.d.ts +23 -0
- package/dist/bridge/git-publish.js +145 -0
- package/dist/bridge/git-worktrees.d.ts +21 -0
- package/dist/bridge/git-worktrees.js +150 -0
- package/dist/bridge/git.d.ts +54 -0
- package/dist/bridge/git.js +552 -0
- package/dist/bridge/grants.d.ts +31 -0
- package/dist/bridge/grants.js +181 -0
- package/dist/bridge/hand-off.d.ts +79 -0
- package/dist/bridge/hand-off.js +151 -0
- package/dist/bridge/health.d.ts +128 -0
- package/dist/bridge/health.js +260 -0
- package/dist/bridge/herdr.d.ts +79 -6
- package/dist/bridge/herdr.js +292 -27
- package/dist/bridge/hook-main.js +2 -0
- package/dist/bridge/install.d.ts +32 -1
- package/dist/bridge/install.js +225 -38
- package/dist/bridge/launch-worktree.d.ts +21 -0
- package/dist/bridge/launch-worktree.js +70 -0
- package/dist/bridge/limits.d.ts +20 -0
- package/dist/bridge/limits.js +65 -0
- package/dist/bridge/locate.d.ts +16 -0
- package/dist/bridge/locate.js +75 -0
- package/dist/bridge/metrics.d.ts +29 -0
- package/dist/bridge/metrics.js +71 -0
- package/dist/bridge/model-switch.d.ts +35 -0
- package/dist/bridge/model-switch.js +250 -0
- package/dist/bridge/models.d.ts +46 -0
- package/dist/bridge/models.js +257 -0
- package/dist/bridge/opencode-approvals.d.ts +6 -0
- package/dist/bridge/opencode-approvals.js +60 -0
- package/dist/bridge/pane-text.d.ts +15 -0
- package/dist/bridge/pane-text.js +23 -0
- package/dist/bridge/peers.d.ts +27 -0
- package/dist/bridge/peers.js +130 -0
- package/dist/bridge/projects.d.ts +12 -1
- package/dist/bridge/projects.js +268 -20
- package/dist/bridge/protocol.d.ts +35 -2
- package/dist/bridge/protocol.js +42 -7
- package/dist/bridge/push.d.ts +83 -0
- package/dist/bridge/push.js +199 -0
- package/dist/bridge/questions.d.ts +38 -0
- package/dist/bridge/questions.js +205 -0
- package/dist/bridge/schedule-format.d.ts +103 -0
- package/dist/bridge/schedule-format.js +266 -0
- package/dist/bridge/schedule-launch.d.ts +11 -0
- package/dist/bridge/schedule-launch.js +169 -0
- package/dist/bridge/schedule-watch.d.ts +52 -0
- package/dist/bridge/schedule-watch.js +242 -0
- package/dist/bridge/schedules.d.ts +48 -0
- package/dist/bridge/schedules.js +205 -0
- package/dist/bridge/server-launch.d.ts +14 -0
- package/dist/bridge/server-launch.js +218 -0
- package/dist/bridge/server-overview.d.ts +45 -0
- package/dist/bridge/server-overview.js +102 -0
- package/dist/bridge/server-pane-routes.d.ts +29 -0
- package/dist/bridge/server-pane-routes.js +400 -0
- package/dist/bridge/server-routes.d.ts +106 -0
- package/dist/bridge/server-routes.js +538 -0
- package/dist/bridge/server-stream.d.ts +46 -0
- package/dist/bridge/server-stream.js +253 -0
- package/dist/bridge/server.d.ts +3 -15
- package/dist/bridge/server.js +162 -264
- package/dist/bridge/session-servers.d.ts +24 -0
- package/dist/bridge/session-servers.js +136 -0
- package/dist/bridge/side-questions.d.ts +74 -0
- package/dist/bridge/side-questions.js +252 -0
- package/dist/bridge/simulators.d.ts +28 -0
- package/dist/bridge/simulators.js +198 -0
- package/dist/bridge/speech-transcribe.d.ts +24 -0
- package/dist/bridge/speech-transcribe.js +124 -0
- package/dist/bridge/speech.d.ts +35 -0
- package/dist/bridge/speech.js +98 -0
- package/dist/bridge/steps.d.ts +13 -0
- package/dist/bridge/steps.js +222 -0
- package/dist/bridge/tab-activity.d.ts +18 -0
- package/dist/bridge/tab-activity.js +99 -0
- package/dist/bridge/terminal-choice.d.ts +64 -0
- package/dist/bridge/terminal-choice.js +281 -0
- package/dist/bridge/transcript-claude.d.ts +22 -0
- package/dist/bridge/transcript-claude.js +353 -0
- package/dist/bridge/transcript-codex.d.ts +30 -0
- package/dist/bridge/transcript-codex.js +282 -0
- package/dist/bridge/transcript-copilot.d.ts +4 -0
- package/dist/bridge/transcript-copilot.js +14 -0
- package/dist/bridge/transcript-opencode.d.ts +5 -0
- package/dist/bridge/transcript-opencode.js +26 -0
- package/dist/bridge/transcript-preview.d.ts +94 -0
- package/dist/bridge/transcript-preview.js +476 -0
- package/dist/bridge/transcripts.d.ts +81 -4
- package/dist/bridge/transcripts.js +332 -67
- package/dist/bridge/transport.d.ts +3 -0
- package/dist/bridge/transport.js +96 -15
- package/dist/bridge/uploads.d.ts +15 -0
- package/dist/bridge/uploads.js +44 -2
- package/dist/bridge/usage.d.ts +124 -0
- package/dist/bridge/usage.js +859 -0
- package/dist/bridge-hook.mjs +41246 -21385
- package/dist/cli/actions.js +14 -1
- package/dist/cli/config-proactivity.d.ts +3 -1
- package/dist/cli/config-proactivity.js +35 -3
- package/dist/cli/config.js +4 -1
- package/dist/cli/extract.js +3 -6
- package/dist/cli/govern.js +5 -2
- package/dist/cli/hooks-globs.js +1 -1
- package/dist/cli/hooks.d.ts +1 -1
- package/dist/cli/hooks.js +9 -7
- package/dist/cli/namespaces-projects.js +12 -6
- package/dist/cli/namespaces-store.js +37 -6
- package/dist/cli/namespaces-tasks.js +1 -1
- package/dist/cli/schedules.d.ts +1 -0
- package/dist/cli/schedules.js +164 -0
- package/dist/cli/session-background.js +1 -1
- package/dist/cli/session-git.d.ts +8 -5
- package/dist/cli/session-git.js +45 -120
- package/dist/cli/session-start.js +3 -1
- package/dist/cli/session-stop.js +19 -8
- package/dist/cli/team.js +13 -10
- package/dist/cli-handlers.d.ts +1 -1
- package/dist/cli-handlers.js +8 -4
- package/dist/cli-help.d.ts +5 -4
- package/dist/cli-help.js +15 -15
- package/dist/cli-registry.d.ts +4 -1
- package/dist/cli-registry.js +119 -6
- package/dist/content/archive.js +2 -2
- package/dist/content/citation.d.ts +11 -0
- package/dist/content/citation.js +18 -0
- package/dist/content/learning.js +2 -0
- package/dist/content/summarize.d.ts +14 -15
- package/dist/content/summarize.js +60 -5
- package/dist/content/validate.d.ts +3 -1
- package/dist/content/validate.js +26 -8
- package/dist/core/project-registry.d.ts +26 -0
- package/dist/core/project-registry.js +573 -0
- package/dist/core/project.js +2 -3
- package/dist/data/access.d.ts +7 -1
- package/dist/data/access.js +13 -3
- package/dist/data/tasks.d.ts +18 -3
- package/dist/data/tasks.js +8 -7
- package/dist/entrypoint.js +44 -10
- package/dist/fanout/adapters/claude.d.ts +2 -0
- package/dist/fanout/adapters/claude.js +7 -0
- package/dist/fanout/adapters/codex.d.ts +2 -0
- package/dist/fanout/adapters/codex.js +9 -0
- package/dist/fanout/adapters/opencode.d.ts +4 -0
- package/dist/fanout/adapters/opencode.js +9 -0
- package/dist/fanout/adapters/types.d.ts +21 -0
- package/dist/fanout/adapters/types.js +3 -0
- package/dist/fanout/command.d.ts +2 -0
- package/dist/fanout/command.js +78 -0
- package/dist/fanout/launcher.d.ts +27 -0
- package/dist/fanout/launcher.js +156 -0
- package/dist/fanout/opencode-serve.d.ts +24 -0
- package/dist/fanout/opencode-serve.js +191 -0
- package/dist/fanout/picker.d.ts +91 -0
- package/dist/fanout/picker.js +51 -0
- package/dist/fanout/usage.d.ts +5 -0
- package/dist/fanout/usage.js +51 -0
- package/dist/fanout/watchdog.d.ts +10 -0
- package/dist/fanout/watchdog.js +27 -0
- package/dist/filenames.d.ts +9 -0
- package/dist/filenames.js +11 -0
- package/dist/finding/context.js +4 -22
- package/dist/generated/memory-ui-graph.browser.js +279 -283
- package/dist/governance/policy-constants.d.ts +11 -0
- package/dist/governance/policy-constants.js +9 -0
- package/dist/governance/policy.d.ts +5 -8
- package/dist/governance/policy.js +7 -5
- package/dist/graph-core/camera.d.ts +24 -0
- package/dist/graph-core/camera.js +18 -0
- package/dist/graph-core/index.d.ts +2 -0
- package/dist/graph-core/index.js +2 -0
- package/dist/graph-core/labels.d.ts +77 -0
- package/dist/graph-core/labels.js +124 -0
- package/dist/graph-core/model.d.ts +13 -0
- package/dist/graph-core/model.js +33 -0
- package/dist/graph-core/types.d.ts +2 -0
- package/dist/home-paths.d.ts +7 -0
- package/dist/home-paths.js +21 -0
- package/dist/hooks.d.ts +3 -0
- package/dist/hooks.js +13 -0
- package/dist/index.js +24 -2
- package/dist/init/guard-globals.d.ts +1 -1
- package/dist/init/guard-globals.js +4 -4
- package/dist/init/init-configure.js +3 -3
- package/dist/init/init-uninstall.js +2 -2
- package/dist/init/init-walkthrough.js +1 -1
- package/dist/init/init.js +26 -6
- package/dist/init/management-preset.d.ts +1 -1
- package/dist/init/management-preset.js +2 -2
- package/dist/init/preferences.js +1 -1
- package/dist/init/self-wiring.js +1 -1
- package/dist/init/setup.d.ts +3 -26
- package/dist/init/setup.js +49 -588
- package/dist/init/shared.js +2 -0
- package/dist/init/store-gitignore.d.ts +1 -1
- package/dist/init/store-gitignore.js +2 -0
- package/dist/init/teardown.d.ts +1 -1
- package/dist/init/teardown.js +2 -2
- package/dist/link/context.js +1 -1
- package/dist/link/doctor.d.ts +22 -1
- package/dist/link/doctor.js +100 -54
- package/dist/link/link.js +29 -61
- package/dist/link/refresh.js +2 -2
- package/dist/link/skills.js +26 -5
- package/dist/machine-identity.d.ts +3 -0
- package/dist/machine-identity.js +6 -0
- package/dist/mcp/profile.d.ts +2 -15
- package/dist/mcp/profile.js +64 -9
- package/dist/memory-ui-graph.runtime.js +279 -283
- package/dist/modules/code-package.d.ts +16 -0
- package/dist/modules/code-package.js +152 -0
- package/dist/modules/command.d.ts +2 -0
- package/dist/modules/command.js +67 -0
- package/dist/modules/config.d.ts +4 -0
- package/dist/modules/config.js +70 -0
- package/dist/modules/manifest.d.ts +41 -0
- package/dist/modules/manifest.js +1 -0
- package/dist/modules/provision.d.ts +3 -0
- package/dist/modules/provision.js +84 -0
- package/dist/modules/registry.d.ts +16 -0
- package/dist/modules/registry.js +250 -0
- package/dist/modules/runtime.d.ts +15 -0
- package/dist/modules/runtime.js +59 -0
- package/dist/package-metadata.js +10 -2
- package/dist/phren-dotenv.js +4 -2
- package/dist/phren-paths.d.ts +3 -2
- package/dist/phren-paths.js +4 -5
- package/dist/profile-store.js +4 -5
- package/dist/project-config.d.ts +19 -1
- package/dist/project-config.js +29 -3
- package/dist/project-topics.js +4 -4
- package/dist/provider-adapters.js +1 -4
- package/dist/query-correlation.js +6 -6
- package/dist/session/artifacts.js +5 -5
- package/dist/session/checkpoints.js +5 -0
- package/dist/session/utils.d.ts +2 -2
- package/dist/session/utils.js +6 -6
- package/dist/shared/content.d.ts +1 -1
- package/dist/shared/content.js +1 -1
- package/dist/shared/data-utils.js +1 -1
- package/dist/shared/fragment-graph.d.ts +1 -1
- package/dist/shared/fragment-graph.js +5 -5
- package/dist/shared/index.js +48 -7
- package/dist/shared/retrieval.d.ts +18 -1
- package/dist/shared/retrieval.js +100 -11
- package/dist/shared/search-fallback.js +4 -6
- package/dist/shared/sqljs.d.ts +2 -0
- package/dist/shared/sqljs.js +4 -2
- package/dist/shared.d.ts +0 -1
- package/dist/shared.js +0 -1
- package/dist/shell/input.d.ts +1 -5
- package/dist/shell/input.js +16 -10
- package/dist/shell/palette.d.ts +2 -2
- package/dist/shell/palette.js +3 -7
- package/dist/shell/render.d.ts +3 -1
- package/dist/shell/render.js +4 -4
- package/dist/shell/shell.js +4 -1
- package/dist/shell/types.d.ts +1 -0
- package/dist/shell/types.js +4 -0
- package/dist/shell/view.d.ts +0 -4
- package/dist/shell/view.js +19 -27
- package/dist/skill/registry.js +25 -17
- package/dist/skill/state.d.ts +3 -0
- package/dist/skill/state.js +13 -7
- package/dist/status.js +38 -17
- package/dist/store-registry.d.ts +44 -18
- package/dist/store-registry.js +169 -60
- package/dist/store-weight.d.ts +1 -6
- package/dist/store-weight.js +4 -2
- package/dist/sync/auth-doctor.d.ts +8 -0
- package/dist/sync/auth-doctor.js +27 -0
- package/dist/sync/auth.d.ts +27 -0
- package/dist/sync/auth.js +114 -0
- package/dist/sync/conflict-resolve.d.ts +9 -0
- package/dist/sync/conflict-resolve.js +146 -0
- package/dist/sync/git-state.d.ts +4 -0
- package/dist/sync/git-state.js +49 -0
- package/dist/sync/outcome.d.ts +34 -0
- package/dist/sync/outcome.js +57 -0
- package/dist/sync/pull.d.ts +15 -7
- package/dist/sync/pull.js +84 -35
- package/dist/sync/store-merge.d.ts +29 -0
- package/dist/sync/store-merge.js +137 -0
- package/dist/sync/task-merge.d.ts +22 -0
- package/dist/sync/task-merge.js +158 -0
- package/dist/task/github.js +1 -1
- package/dist/task/lifecycle.d.ts +5 -0
- package/dist/task/lifecycle.js +67 -23
- package/dist/terminal-text.d.ts +5 -0
- package/dist/terminal-text.js +11 -0
- package/dist/test-global-setup.js +7 -0
- package/dist/tool-registry.d.ts +1 -1
- package/dist/tool-registry.js +3 -1
- package/dist/tools/code.d.ts +3 -0
- package/dist/tools/code.js +178 -0
- package/dist/tools/config.js +5 -0
- package/dist/tools/data.js +14 -7
- package/dist/tools/dispatch.d.ts +2 -0
- package/dist/tools/dispatch.js +66 -0
- package/dist/tools/finding.js +43 -41
- package/dist/tools/ops.js +5 -2
- package/dist/tools/search.js +21 -8
- package/dist/tools/session.js +21 -22
- package/dist/tools/tasks.js +8 -2
- package/dist/tools/types.d.ts +2 -2
- package/dist/tools/types.js +2 -2
- package/dist/ui/assets.js +1 -1
- package/dist/ui/data.js +14 -15
- package/dist/ui/deep-void.d.ts +1 -1
- package/dist/ui/deep-void.js +0 -1
- package/dist/ui/graph-chrome.d.ts +1 -1
- package/dist/ui/graph-chrome.js +51 -0
- package/dist/ui/page.js +5 -5
- package/dist/ui/scripts.js +67 -30
- package/dist/ui/server.js +34 -6
- package/dist/update.js +1 -1
- package/dist/utils-fts.js +1 -0
- package/dist/utils-helpers.d.ts +7 -0
- package/dist/utils-helpers.js +17 -0
- package/dist/utils.d.ts +1 -1
- package/dist/utils.js +1 -1
- package/package.json +45 -3
- package/plugins/opencode/phren-transcript.js +340 -0
- package/starter/README.md +4 -4
- package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
- package/starter/global/skills/conductor/SKILL.md +106 -0
- package/starter/global/skills/fanout/SKILL.md +20 -0
- package/starter/global/skills/phren-discover/SKILL.md +6 -6
- package/starter/global/skills/phren-init/SKILL.md +4 -4
- package/starter/global/skills/phren-sync/SKILL.md +3 -3
- package/starter/templates/frontend/reference/README.md +1 -1
- package/starter/templates/library/reference/README.md +1 -1
- package/starter/templates/monorepo/reference/README.md +1 -1
- package/starter/templates/python-project/reference/README.md +1 -1
- /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { createPrivateKey, sign } from "node:crypto";
|
|
2
|
+
import { readFile, stat } from "node:fs/promises";
|
|
3
|
+
import { connect } from "node:http2";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { atomic, bridgeRoot } from "./protocol.js";
|
|
7
|
+
const deviceSchema = z.object({
|
|
8
|
+
deviceID: z.string().uuid(),
|
|
9
|
+
hostID: z.string().uuid(),
|
|
10
|
+
token: z.string().regex(/^[0-9a-f]{64}$/),
|
|
11
|
+
environment: z.enum(["development", "production"]),
|
|
12
|
+
kinds: z.array(z.enum(["approval", "scheduleStarted", "scheduleFinished", "scheduleFailed", "scheduleBlocked"])).max(5).default(["approval"]),
|
|
13
|
+
});
|
|
14
|
+
const configSchema = z.object({
|
|
15
|
+
keyId: z.string().regex(/^[A-Z0-9]{10}$/),
|
|
16
|
+
teamId: z.string().regex(/^[A-Z0-9]{10}$/),
|
|
17
|
+
topic: z.string().regex(/^[A-Za-z0-9.-]{1,255}$/).default("com.phren.ios"),
|
|
18
|
+
privateKeyPath: z.string().min(1),
|
|
19
|
+
});
|
|
20
|
+
export function scheduleCollapseId(kind, runId) {
|
|
21
|
+
return `${runId.slice(0, 63 - kind.length)}-${kind}`;
|
|
22
|
+
}
|
|
23
|
+
export function approvalPushPayload(value, host) {
|
|
24
|
+
const label = value.provider === "claude" ? "Claude" : value.provider === "codex" ? "Codex" : value.provider === "opencode" ? "opencode" : "Your agent";
|
|
25
|
+
return {
|
|
26
|
+
aps: {
|
|
27
|
+
alert: { title: value.title ?? (value.question ? `${label} has a question` : `${label} needs approval`),
|
|
28
|
+
body: value.message ?? "Open Phren to review the request." },
|
|
29
|
+
sound: "default", category: value.question ? "PHREN_AGENT_QUESTION" : "PHREN_AGENT_APPROVAL",
|
|
30
|
+
"interruption-level": "time-sensitive",
|
|
31
|
+
},
|
|
32
|
+
phren: { version: 1, binding: value.binding, expiresAt: value.expiresAt, ...(host ? { host } : {}) },
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export function fanoutBlockedPushPayload(value) {
|
|
36
|
+
return {
|
|
37
|
+
aps: { alert: { title: `${value.label} blocked`, body: value.reason }, sound: "default", category: "PHREN_FANOUT" },
|
|
38
|
+
phren: { kind: "fanoutBlocked", job: value.job, provider: value.provider, label: value.label, reason: value.reason },
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export function schedulePushPayload(value) {
|
|
42
|
+
const state = value.kind === "scheduleStarted" ? "started" : value.kind === "scheduleFinished" ? (value.status === "needs-you" ? "needs you" : "finished")
|
|
43
|
+
: value.kind === "scheduleBlocked" ? "blocked" : "failed";
|
|
44
|
+
return {
|
|
45
|
+
aps: {
|
|
46
|
+
alert: { title: `${value.name} ${state}`, body: `${value.project} on ${value.computer}${value.reason ? `. ${value.reason}` : ""}` },
|
|
47
|
+
sound: "default", category: "PHREN_SCHEDULE",
|
|
48
|
+
},
|
|
49
|
+
phren: { kind: value.kind, scheduleId: value.scheduleId, project: value.project, name: value.name,
|
|
50
|
+
computer: value.computer, runId: value.runId, status: value.status, ...(value.reason ? { reason: value.reason } : {}),
|
|
51
|
+
...(value.route ? { route: value.route } : {}) },
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
async function secureJSON(file, schema) {
|
|
55
|
+
try {
|
|
56
|
+
const metadata = await stat(file);
|
|
57
|
+
if ((metadata.mode & 0o077) !== 0 || (process.getuid && metadata.uid !== process.getuid()))
|
|
58
|
+
return undefined;
|
|
59
|
+
return schema.parse(JSON.parse(await readFile(file, "utf8")));
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
async function secureFile(file) {
|
|
66
|
+
try {
|
|
67
|
+
const metadata = await stat(file);
|
|
68
|
+
if (!metadata.isFile() || (metadata.mode & 0o077) !== 0 || (process.getuid && metadata.uid !== process.getuid()))
|
|
69
|
+
return undefined;
|
|
70
|
+
return await readFile(file, "utf8");
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** What `phren bridge doctor` prints when the Hook has no APNs sender. */
|
|
77
|
+
export function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path.join(bridgeRoot(), "apns.json")) {
|
|
78
|
+
return [
|
|
79
|
+
"Approval push is not configured: the phone only alerts while Phren runs, and a registered phone gets nothing while suspended.",
|
|
80
|
+
"1. In your Apple developer account, create an APNs key (Keys, Apple Push Notifications service) and download AuthKey_<KEYID>.p8.",
|
|
81
|
+
`2. Save it next to ${configFile} with mode 600.`,
|
|
82
|
+
`3. Write ${configFile} with mode 600: {"keyId":"<KEYID>","teamId":"<TEAMID>","topic":"com.phren.ios","privateKeyPath":"AuthKey_<KEYID>.p8"}`,
|
|
83
|
+
"4. Restart the Hook (phren bridge install), then run phren bridge doctor again.",
|
|
84
|
+
].join("\n");
|
|
85
|
+
}
|
|
86
|
+
/** The capability a phone reads: only a Hook with a loaded APNs sender offers push. */
|
|
87
|
+
export function approvalPushCapability(status) {
|
|
88
|
+
return status.configured ? "direct-apns" : undefined;
|
|
89
|
+
}
|
|
90
|
+
export function upsertPushDevice(devices, value) {
|
|
91
|
+
const device = deviceSchema.parse(value);
|
|
92
|
+
return [...devices.filter(item => item.deviceID !== device.deviceID), device].slice(-16);
|
|
93
|
+
}
|
|
94
|
+
const base64url = (value) => Buffer.from(value).toString("base64url");
|
|
95
|
+
class APNsSender {
|
|
96
|
+
config;
|
|
97
|
+
key;
|
|
98
|
+
now;
|
|
99
|
+
jwt;
|
|
100
|
+
constructor(config, key, now = Date.now) {
|
|
101
|
+
this.config = config;
|
|
102
|
+
this.key = key;
|
|
103
|
+
this.now = now;
|
|
104
|
+
}
|
|
105
|
+
token() {
|
|
106
|
+
const created = Math.floor(this.now() / 1000);
|
|
107
|
+
if (this.jwt && created - this.jwt.created < 50 * 60)
|
|
108
|
+
return this.jwt.value;
|
|
109
|
+
const header = base64url(JSON.stringify({ alg: "ES256", kid: this.config.keyId }));
|
|
110
|
+
const claims = base64url(JSON.stringify({ iss: this.config.teamId, iat: created }));
|
|
111
|
+
const input = `${header}.${claims}`;
|
|
112
|
+
const signature = sign("sha256", Buffer.from(input), { key: createPrivateKey(this.key), dsaEncoding: "ieee-p1363" });
|
|
113
|
+
const value = `${input}.${base64url(signature)}`;
|
|
114
|
+
this.jwt = { value, created };
|
|
115
|
+
return value;
|
|
116
|
+
}
|
|
117
|
+
send(device, payload, headers) {
|
|
118
|
+
const authority = device.environment === "production" ? "https://api.push.apple.com" : "https://api.sandbox.push.apple.com";
|
|
119
|
+
return new Promise(resolve => {
|
|
120
|
+
const client = connect(authority);
|
|
121
|
+
let settled = false;
|
|
122
|
+
const finish = (ok) => { if (settled)
|
|
123
|
+
return; settled = true; client.close(); resolve(ok); };
|
|
124
|
+
client.once("error", () => finish(false));
|
|
125
|
+
const request = client.request({ ":method": "POST", ":path": `/3/device/${device.token}`,
|
|
126
|
+
authorization: `bearer ${this.token()}`, "apns-topic": this.config.topic, "apns-push-type": "alert",
|
|
127
|
+
"apns-priority": "10", "apns-expiration": headers.expiration, "apns-collapse-id": headers.collapseId });
|
|
128
|
+
request.on("response", headers => finish(Number(headers[":status"]) === 200));
|
|
129
|
+
request.once("error", () => finish(false));
|
|
130
|
+
request.setTimeout(10_000, () => { request.close(); finish(false); });
|
|
131
|
+
request.end(JSON.stringify(payload));
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/** Direct Hook -> APNs delivery. Apple receives only a short-lived opaque
|
|
136
|
+
* binding; conversation identity, action id, command and SSH key stay local. */
|
|
137
|
+
export class ApprovalPushService {
|
|
138
|
+
devices = [];
|
|
139
|
+
sender;
|
|
140
|
+
devicesFile = path.join(bridgeRoot(), "push-devices.json");
|
|
141
|
+
async start() {
|
|
142
|
+
this.devices = await secureJSON(this.devicesFile, z.array(deviceSchema).max(16)) ?? [];
|
|
143
|
+
const configFile = process.env.PHREN_APNS_CONFIG || path.join(bridgeRoot(), "apns.json");
|
|
144
|
+
const config = await secureJSON(configFile, configSchema);
|
|
145
|
+
if (!config)
|
|
146
|
+
return;
|
|
147
|
+
const keyPath = path.isAbsolute(config.privateKeyPath) ? config.privateKeyPath : path.resolve(path.dirname(configFile), config.privateKeyPath);
|
|
148
|
+
const key = await secureFile(keyPath);
|
|
149
|
+
if (key)
|
|
150
|
+
this.sender = new APNsSender(config, key);
|
|
151
|
+
}
|
|
152
|
+
get available() { return this.sender !== undefined && this.devices.length > 0; }
|
|
153
|
+
get status() { return { supported: true, configured: this.sender !== undefined, devices: this.devices.length }; }
|
|
154
|
+
async register(value) {
|
|
155
|
+
this.devices = upsertPushDevice(this.devices, value);
|
|
156
|
+
await atomic(this.devicesFile, JSON.stringify(this.devices));
|
|
157
|
+
}
|
|
158
|
+
async notify(value) {
|
|
159
|
+
if (!this.sender || !this.devices.length)
|
|
160
|
+
return false;
|
|
161
|
+
const devices = this.devices.filter(device => device.kinds.includes("approval"));
|
|
162
|
+
if (!devices.length)
|
|
163
|
+
return false;
|
|
164
|
+
return (await Promise.all(devices.map(device => this.sender.send(device, approvalPushPayload(value, device.hostID), {
|
|
165
|
+
expiration: String(Math.floor(Date.parse(value.expiresAt) / 1000)), collapseId: value.binding,
|
|
166
|
+
})))).some(Boolean);
|
|
167
|
+
}
|
|
168
|
+
/** A headless worker whose permission the plugin refused. Approval-registered
|
|
169
|
+
* phones already accept agent alerts; the payload carries the reason so the
|
|
170
|
+
* notification is actionable on its own. */
|
|
171
|
+
async notifyFanoutBlocked(value) {
|
|
172
|
+
if (!this.sender || !this.devices.length)
|
|
173
|
+
return false;
|
|
174
|
+
const devices = this.devices.filter(device => device.kinds.includes("approval"));
|
|
175
|
+
if (!devices.length)
|
|
176
|
+
return false;
|
|
177
|
+
return (await Promise.all(devices.map(device => this.sender.send(device, fanoutBlockedPushPayload(value), {
|
|
178
|
+
expiration: "0", collapseId: `fanout-${value.job}`,
|
|
179
|
+
})))).some(Boolean);
|
|
180
|
+
}
|
|
181
|
+
async notifySchedule(value) {
|
|
182
|
+
if (!this.sender)
|
|
183
|
+
return { notified: false, reason: "no push config" };
|
|
184
|
+
let devices = this.devices.filter(device => device.kinds.includes(value.kind));
|
|
185
|
+
if (!devices.length && value.kind === "scheduleBlocked")
|
|
186
|
+
devices = this.devices.filter(device => device.kinds.includes("scheduleFailed"));
|
|
187
|
+
if (!devices.length)
|
|
188
|
+
return { notified: false, reason: "no registered devices" };
|
|
189
|
+
try {
|
|
190
|
+
const notified = (await Promise.all(devices.map(device => this.sender.send(device, schedulePushPayload(value), {
|
|
191
|
+
expiration: "0", collapseId: scheduleCollapseId(value.kind, value.runId),
|
|
192
|
+
})))).some(Boolean);
|
|
193
|
+
return notified ? { notified: true } : { notified: false, reason: "push delivery failed" };
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
return { notified: false, reason: "push delivery failed" };
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { type Json, type Target } from "./protocol.js";
|
|
3
|
+
declare const question: z.ZodObject<{
|
|
4
|
+
title: z.ZodString;
|
|
5
|
+
options: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
|
|
6
|
+
}, z.core.$strip>;
|
|
7
|
+
type Question = z.infer<typeof question>;
|
|
8
|
+
/** Codex's asynchronous questions return {accepted:true} immediately. Their
|
|
9
|
+
* answers are ordinary user messages quoting the original title, not replies
|
|
10
|
+
* to item/tool/requestUserInput (that RPC is the synchronous tool). */
|
|
11
|
+
export declare function asyncQuestion(raw: Json, id: string): Question[] | undefined;
|
|
12
|
+
/** An `item_completed` event for an AgentMessage delivered async with
|
|
13
|
+
* questions attached: the newer shape, already acknowledged by nature. */
|
|
14
|
+
export declare function deliveredQuestion(raw: Json): {
|
|
15
|
+
id: string;
|
|
16
|
+
questions: Question[];
|
|
17
|
+
} | undefined;
|
|
18
|
+
export declare function questionReply(questions: Question[], answers: unknown): string;
|
|
19
|
+
interface PendingQuestion {
|
|
20
|
+
id: string;
|
|
21
|
+
questions: Question[];
|
|
22
|
+
}
|
|
23
|
+
export declare function pendingAsyncQuestions(file: string, targetID?: string): Promise<PendingQuestion[]>;
|
|
24
|
+
export declare function pendingAsyncQuestion(file: string, id: string): Promise<Question[]>;
|
|
25
|
+
export declare class CodexQuestions {
|
|
26
|
+
private executable;
|
|
27
|
+
private snapshots;
|
|
28
|
+
private failedSnapshots;
|
|
29
|
+
private inboxAvailable;
|
|
30
|
+
/** Feature discovery must never delay permission/status frames. */
|
|
31
|
+
get available(): boolean;
|
|
32
|
+
private probe?;
|
|
33
|
+
constructor(executable?: string);
|
|
34
|
+
supported(): Promise<boolean>;
|
|
35
|
+
pending(target: Target): Promise<Json[]>;
|
|
36
|
+
answer(target: Target, data: Json): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { mkdir, open, stat, readFile, writeFile } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { BridgeError, bridgeRoot, object, objects } from "./protocol.js";
|
|
8
|
+
import { paneIdentity, validateTarget } from "./herdr.js";
|
|
9
|
+
import { transcriptPath } from "./transcripts.js";
|
|
10
|
+
import { withTranscriptIndex } from "./transcript-index.js";
|
|
11
|
+
const exec = promisify(execFile);
|
|
12
|
+
const text = z.string().trim().min(1).max(4000).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
|
|
13
|
+
const question = z.object({ title: text, options: z.array(text).max(12).nullable().optional() });
|
|
14
|
+
const questionSet = z.array(question).min(1).max(8);
|
|
15
|
+
/** Codex's asynchronous questions return {accepted:true} immediately. Their
|
|
16
|
+
* answers are ordinary user messages quoting the original title, not replies
|
|
17
|
+
* to item/tool/requestUserInput (that RPC is the synchronous tool). */
|
|
18
|
+
export function asyncQuestion(raw, id) {
|
|
19
|
+
const p = object(raw.payload);
|
|
20
|
+
// Codex 0.155 asks through an agent message delivered async, with the
|
|
21
|
+
// questions on the item itself; older versions called a tool.
|
|
22
|
+
const asked = deliveredQuestion(raw);
|
|
23
|
+
if (asked)
|
|
24
|
+
return asked.id === id ? asked.questions : undefined;
|
|
25
|
+
if (raw.type !== "response_item" || p.type !== "function_call" || p.call_id !== id
|
|
26
|
+
|| !["request_user_input_async", "functions.request_user_input_async"].includes(String(p.name)))
|
|
27
|
+
return;
|
|
28
|
+
try {
|
|
29
|
+
return questionSet.parse(object(JSON.parse(String(p.arguments))).questions);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** An `item_completed` event for an AgentMessage delivered async with
|
|
36
|
+
* questions attached: the newer shape, already acknowledged by nature. */
|
|
37
|
+
export function deliveredQuestion(raw) {
|
|
38
|
+
const p = object(raw.payload), item = object(p.item);
|
|
39
|
+
if (raw.type !== "event_msg" || p.type !== "item_completed" || !["AgentMessage", "agentMessage"].includes(String(item.type))
|
|
40
|
+
|| item.delivery !== "async" || !Array.isArray(item.questions) || typeof item.id !== "string" || !item.id)
|
|
41
|
+
return;
|
|
42
|
+
try {
|
|
43
|
+
const questions = questionSet.parse(objects(item.questions).map(q => ({ ...q, options: Array.isArray(q.options) ? q.options : undefined })));
|
|
44
|
+
return { id: item.id.slice(0, 512), questions };
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export function questionReply(questions, answers) {
|
|
51
|
+
const parsed = z.array(z.object({ optionIndexes: z.array(z.number().int().nonnegative()).max(1), text: z.string().max(4000).optional() })).parse(answers);
|
|
52
|
+
if (parsed.length !== questions.length)
|
|
53
|
+
throw new BridgeError(400, "Answer every question.");
|
|
54
|
+
return questions.map((q, index) => {
|
|
55
|
+
const answer = parsed[index], typed = answer.text?.trim() ?? "", options = q.options ?? [];
|
|
56
|
+
if (answer.optionIndexes.length + (typed ? 1 : 0) !== 1)
|
|
57
|
+
throw new BridgeError(400, "Choose one answer for each question.");
|
|
58
|
+
const value = typed || options[answer.optionIndexes[0]];
|
|
59
|
+
if (!value || !text.safeParse(value).success)
|
|
60
|
+
throw new BridgeError(400, "Choose an available answer.");
|
|
61
|
+
return q.title.split("\n").map(line => `> ${line}`).join("\n") + "\n\n" + value;
|
|
62
|
+
}).join("\n\n");
|
|
63
|
+
}
|
|
64
|
+
const answersQuestions = (reply, questions) => questions.every(q => {
|
|
65
|
+
const quote = q.title.split("\n").map(line => `> ${line}`).join("\n") + "\n\n";
|
|
66
|
+
const index = reply.indexOf(quote);
|
|
67
|
+
return index >= 0 && reply.slice(index + quote.length).trim().length > 0;
|
|
68
|
+
});
|
|
69
|
+
export async function pendingAsyncQuestions(file, targetID) {
|
|
70
|
+
return withTranscriptIndex(file, async (handle, index) => {
|
|
71
|
+
const replies = [], acknowledged = new Set(), resolved = new Set(), pending = [];
|
|
72
|
+
let bytes = 0;
|
|
73
|
+
for await (const row of index.rows(handle, index.lines, Math.max(0, index.lines - 10_000))) {
|
|
74
|
+
// An incomplete scan is not evidence that no questions remain. Status
|
|
75
|
+
// omits this field on failure, preserving the phone's known prompts.
|
|
76
|
+
if (!row.bytes || (bytes += row.bytes.length) > 8_388_608)
|
|
77
|
+
throw new BridgeError(413, "The pending question history is too large to verify.");
|
|
78
|
+
let raw;
|
|
79
|
+
try {
|
|
80
|
+
raw = object(JSON.parse(row.bytes.toString()));
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const delivered = deliveredQuestion(raw);
|
|
86
|
+
if (delivered)
|
|
87
|
+
acknowledged.add(delivered.id);
|
|
88
|
+
if (raw.type !== "response_item" && !delivered)
|
|
89
|
+
continue;
|
|
90
|
+
const p = object(raw.payload), id = delivered ? delivered.id : typeof p.call_id === "string" ? p.call_id : "";
|
|
91
|
+
if (p.type === "message" && p.role === "user")
|
|
92
|
+
replies.push(objects(p.content).map(b => typeof b.text === "string" ? b.text : "").join("\n"));
|
|
93
|
+
if (id && ["function_call_output", "custom_tool_call_output"].includes(String(p.type)) && !resolved.has(id) && !acknowledged.has(id)) {
|
|
94
|
+
try {
|
|
95
|
+
if (object(JSON.parse(String(p.output))).accepted === true)
|
|
96
|
+
acknowledged.add(id);
|
|
97
|
+
else
|
|
98
|
+
resolved.add(id);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
resolved.add(id);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (targetID && resolved.has(targetID))
|
|
105
|
+
return [];
|
|
106
|
+
if (!id || !acknowledged.has(id))
|
|
107
|
+
continue;
|
|
108
|
+
const questions = asyncQuestion(raw, id);
|
|
109
|
+
if (questions && !replies.some(reply => answersQuestions(reply, questions))) {
|
|
110
|
+
pending.push({ id, questions });
|
|
111
|
+
if (pending.length >= 64)
|
|
112
|
+
throw new BridgeError(413, "Too many pending questions to verify.");
|
|
113
|
+
}
|
|
114
|
+
if (targetID && questions && id === targetID)
|
|
115
|
+
return pending.filter(p => p.id === targetID);
|
|
116
|
+
}
|
|
117
|
+
if (index.lines > 10_000)
|
|
118
|
+
throw new BridgeError(413, "The pending question history is too large to verify.");
|
|
119
|
+
return pending.reverse();
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
export async function pendingAsyncQuestion(file, id) {
|
|
123
|
+
const pending = (await pendingAsyncQuestions(file, id)).find(p => p.id === id);
|
|
124
|
+
if (!pending)
|
|
125
|
+
throw new BridgeError(409, "This question is no longer pending. Refresh the conversation.");
|
|
126
|
+
return pending.questions;
|
|
127
|
+
}
|
|
128
|
+
export class CodexQuestions {
|
|
129
|
+
executable;
|
|
130
|
+
snapshots = new Map();
|
|
131
|
+
failedSnapshots = new Map();
|
|
132
|
+
inboxAvailable = false;
|
|
133
|
+
/** Feature discovery must never delay permission/status frames. */
|
|
134
|
+
get available() { void this.supported(); return this.inboxAvailable; }
|
|
135
|
+
probe;
|
|
136
|
+
constructor(executable = "codex") {
|
|
137
|
+
this.executable = executable;
|
|
138
|
+
}
|
|
139
|
+
supported() {
|
|
140
|
+
if (!this.probe || Date.now() - this.probe.at > 300_000)
|
|
141
|
+
this.probe = { at: Date.now(), result: exec(this.executable, ["queue", "--help"], { timeout: 5000, maxBuffer: 65_536 })
|
|
142
|
+
.then(({ stdout }) => stdout.includes("--thread") && stdout.includes("--message")).catch(() => false)
|
|
143
|
+
.then(available => { this.inboxAvailable = available; return available; }) };
|
|
144
|
+
return this.probe.result;
|
|
145
|
+
}
|
|
146
|
+
async pending(target) {
|
|
147
|
+
if (target.source !== "codex")
|
|
148
|
+
return [];
|
|
149
|
+
if (Date.now() - (this.failedSnapshots.get(target.session) ?? 0) < 5000)
|
|
150
|
+
throw new BridgeError(503, "Pending question history is unavailable.");
|
|
151
|
+
const file = await transcriptPath("codex", target.session);
|
|
152
|
+
const cached = this.snapshots.get(target.session);
|
|
153
|
+
let pending = cached?.pending;
|
|
154
|
+
if (!cached || Date.now() - cached.at > 1000) {
|
|
155
|
+
const metadata = await stat(file), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
|
|
156
|
+
pending = cached?.stamp === stamp ? cached.pending : await pendingAsyncQuestions(file).catch(error => {
|
|
157
|
+
if (this.failedSnapshots.size >= 64)
|
|
158
|
+
this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
|
|
159
|
+
this.failedSnapshots.set(target.session, Date.now());
|
|
160
|
+
throw error;
|
|
161
|
+
});
|
|
162
|
+
this.failedSnapshots.delete(target.session);
|
|
163
|
+
if (this.snapshots.size >= 64)
|
|
164
|
+
this.snapshots.delete(this.snapshots.keys().next().value);
|
|
165
|
+
this.snapshots.set(target.session, { at: Date.now(), stamp, pending });
|
|
166
|
+
}
|
|
167
|
+
return Promise.all((pending ?? []).map(async (p) => {
|
|
168
|
+
const key = createHash("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
|
|
169
|
+
const submitted = await readFile(path.join(bridgeRoot(), "question-replies", key), "utf8").then(value => value === "submitted").catch(() => false);
|
|
170
|
+
return { toolUseId: p.id, isAsync: true, submitted, questions: p.questions.map(q => ({ question: q.title,
|
|
171
|
+
options: (q.options ?? []).map(label => ({ label })), ...(!q.options?.length ? { kind: "text" } : {}) })) };
|
|
172
|
+
})).then(prompts => prompts.filter(p => !p.submitted));
|
|
173
|
+
}
|
|
174
|
+
async answer(target, data) {
|
|
175
|
+
if (target.source !== "codex" || !await this.supported())
|
|
176
|
+
throw new BridgeError(409, "This connection needs the question answered in the terminal.");
|
|
177
|
+
z.string().uuid().parse(target.session);
|
|
178
|
+
const id = z.string().min(1).max(512).parse(data.toolUseId);
|
|
179
|
+
const questions = await pendingAsyncQuestion(await transcriptPath("codex", target.session), id);
|
|
180
|
+
const reply = questionReply(questions, data.answers);
|
|
181
|
+
const pane = await validateTarget(target);
|
|
182
|
+
if (await paneIdentity(target.server, pane, true) !== target.session)
|
|
183
|
+
throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
|
|
184
|
+
// Record before invoking the provider: a timeout can mean it accepted the
|
|
185
|
+
// message. Concurrent taps, reconnects, and helper restarts must not resend.
|
|
186
|
+
const directory = path.join(bridgeRoot(), "question-replies");
|
|
187
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
188
|
+
const key = createHash("sha256").update(JSON.stringify([target.source, target.session, id])).digest("hex");
|
|
189
|
+
const receiptPath = path.join(directory, key);
|
|
190
|
+
const receipt = await open(receiptPath, "wx", 0o600).catch(error => {
|
|
191
|
+
if (error.code === "EEXIST")
|
|
192
|
+
throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
|
|
193
|
+
throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
|
|
194
|
+
});
|
|
195
|
+
await receipt.close();
|
|
196
|
+
try {
|
|
197
|
+
// Explicit UUID, no session-name lookup, no shell, no terminal keystrokes.
|
|
198
|
+
await exec(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8000, maxBuffer: 65_536 });
|
|
199
|
+
await writeFile(receiptPath, "submitted", { mode: 0o600 });
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
throw new BridgeError(409, "Codex did not confirm the answer. Check the conversation; Phren has not retried it.");
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { SchedulePush, SchedulePushResult } from "./push.js";
|
|
2
|
+
/** The schedules.yaml store: the schedule and run record shapes, validation,
|
|
3
|
+
* the five timing forms evaluated in local time, and the run history file. */
|
|
4
|
+
export declare const SCHEDULE_EVERY: readonly ["interval", "daily", "weekly", "once", "cron"];
|
|
5
|
+
export declare const SCHEDULE_HARNESSES: readonly ["claude", "codex", "opencode"];
|
|
6
|
+
export declare const SCHEDULE_NOTIFY: readonly ["start", "finish", "failure"];
|
|
7
|
+
export declare const WEEKDAYS: readonly ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
8
|
+
export type ScheduleEvery = typeof SCHEDULE_EVERY[number];
|
|
9
|
+
export type ScheduleHarness = typeof SCHEDULE_HARNESSES[number];
|
|
10
|
+
export type ScheduleNotify = typeof SCHEDULE_NOTIFY[number];
|
|
11
|
+
export type Weekday = typeof WEEKDAYS[number];
|
|
12
|
+
export declare const SCHEDULE_RUN_STATUSES: readonly ["launched", "running", "blocked", "finished", "needs-you", "failed", "skipped"];
|
|
13
|
+
export type ScheduleRunStatus = typeof SCHEDULE_RUN_STATUSES[number];
|
|
14
|
+
/** How a run ended: done, done but waiting on the owner's answer, or not done. */
|
|
15
|
+
export interface ScheduleRunOutcome {
|
|
16
|
+
status: "finished" | "needs-you" | "failed";
|
|
17
|
+
reason?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface Schedule {
|
|
20
|
+
id: string;
|
|
21
|
+
name: string;
|
|
22
|
+
enabled: boolean;
|
|
23
|
+
computer: string;
|
|
24
|
+
harness: ScheduleHarness;
|
|
25
|
+
model?: string;
|
|
26
|
+
notify?: ScheduleNotify[];
|
|
27
|
+
every: ScheduleEvery;
|
|
28
|
+
at?: string;
|
|
29
|
+
days?: Weekday[];
|
|
30
|
+
interval?: string;
|
|
31
|
+
once?: string;
|
|
32
|
+
cron?: string;
|
|
33
|
+
prompt: string;
|
|
34
|
+
createdAt: string;
|
|
35
|
+
updatedAt: string;
|
|
36
|
+
[key: string]: unknown;
|
|
37
|
+
}
|
|
38
|
+
export interface ScheduleLaunchRecord {
|
|
39
|
+
mode: "herdr" | "headless";
|
|
40
|
+
workspaceId?: string;
|
|
41
|
+
tabId?: string;
|
|
42
|
+
paneId?: string;
|
|
43
|
+
sessionId?: string;
|
|
44
|
+
server?: string;
|
|
45
|
+
jobDir?: string;
|
|
46
|
+
}
|
|
47
|
+
export interface ScheduleRun {
|
|
48
|
+
id: string;
|
|
49
|
+
scheduleId: string;
|
|
50
|
+
project: string;
|
|
51
|
+
startedAt: string;
|
|
52
|
+
finishedAt?: string;
|
|
53
|
+
status: ScheduleRunStatus;
|
|
54
|
+
reason?: string;
|
|
55
|
+
blockedStartupPrompt?: string;
|
|
56
|
+
blockNotified?: boolean;
|
|
57
|
+
notified?: boolean;
|
|
58
|
+
notifyReason?: string;
|
|
59
|
+
launch: ScheduleLaunchRecord;
|
|
60
|
+
}
|
|
61
|
+
export interface ScheduleLaunchResult {
|
|
62
|
+
launch: ScheduleLaunchRecord;
|
|
63
|
+
completion?: Promise<ScheduleRunOutcome>;
|
|
64
|
+
}
|
|
65
|
+
export interface ScheduleLaunchContext {
|
|
66
|
+
schedule: Schedule;
|
|
67
|
+
project: string;
|
|
68
|
+
projectDir: string;
|
|
69
|
+
cwd: string;
|
|
70
|
+
runId: string;
|
|
71
|
+
blockedStartup?: (promptText: string) => void | Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
export type ScheduleLauncher = ((context: ScheduleLaunchContext) => Promise<ScheduleLaunchResult>) & {
|
|
74
|
+
close?: () => void;
|
|
75
|
+
};
|
|
76
|
+
export interface SchedulePushSender {
|
|
77
|
+
notify(value: SchedulePush): Promise<SchedulePushResult>;
|
|
78
|
+
}
|
|
79
|
+
export interface ScheduleStatus extends Schedule {
|
|
80
|
+
project: string;
|
|
81
|
+
nextRun: string | null;
|
|
82
|
+
lastRun: Omit<ScheduleRun, "id" | "scheduleId" | "project"> | null;
|
|
83
|
+
running: boolean;
|
|
84
|
+
}
|
|
85
|
+
interface ScheduleDocument {
|
|
86
|
+
document: Record<string, unknown>;
|
|
87
|
+
schedules: Schedule[];
|
|
88
|
+
}
|
|
89
|
+
export declare const runningStatuses: Set<"blocked" | "failed" | "finished" | "launched" | "needs-you" | "running" | "skipped">;
|
|
90
|
+
export declare function intervalMilliseconds(value: string): number;
|
|
91
|
+
export declare function parseSchedule(value: unknown): Schedule;
|
|
92
|
+
export declare function readScheduleDocument(projectDir: string): Promise<ScheduleDocument>;
|
|
93
|
+
export declare function writeScheduleDocument(projectDir: string, schedules: Schedule[], original?: Record<string, unknown>): Promise<void>;
|
|
94
|
+
export declare function canonicalComputer(value: string): string;
|
|
95
|
+
export declare function computerMatches(wanted: string, current: string): boolean;
|
|
96
|
+
export declare function scheduleNotifications(schedule: Schedule): Set<ScheduleNotify>;
|
|
97
|
+
export declare function scheduleSessionRoute(schedule: Schedule, launch: ScheduleLaunchRecord): string | undefined;
|
|
98
|
+
export declare function nextRun(schedule: Schedule, lastRun?: ScheduleRun): Date | null;
|
|
99
|
+
export declare function readScheduleRuns(file: string): Promise<ScheduleRun[]>;
|
|
100
|
+
export declare function writeScheduleRuns(file: string, runs: ScheduleRun[]): Promise<void>;
|
|
101
|
+
export declare function newScheduleId(existing: Iterable<string>): string;
|
|
102
|
+
export declare function scheduleRunsFile(): string;
|
|
103
|
+
export {};
|