@phren/cli 0.3.10 → 0.3.12

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.
Files changed (184) hide show
  1. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  2. package/dist/bridge/agent-hook-stores.js +5 -0
  3. package/dist/bridge/agent-hooks.d.ts +159 -5
  4. package/dist/bridge/agent-hooks.js +663 -49
  5. package/dist/bridge/approval-summary.d.ts +16 -0
  6. package/dist/bridge/approval-summary.js +133 -0
  7. package/dist/bridge/authority-command.d.ts +20 -0
  8. package/dist/bridge/authority-command.js +120 -0
  9. package/dist/bridge/authority.d.ts +223 -0
  10. package/dist/bridge/authority.js +231 -0
  11. package/dist/bridge/claude-account-setup.d.ts +14 -0
  12. package/dist/bridge/claude-account-setup.js +69 -0
  13. package/dist/bridge/claude-accounts.d.ts +49 -0
  14. package/dist/bridge/claude-accounts.js +195 -0
  15. package/dist/bridge/code-routes.js +2 -2
  16. package/dist/bridge/codex-app-server.d.ts +144 -0
  17. package/dist/bridge/codex-app-server.js +319 -0
  18. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  19. package/dist/bridge/codex-auth-refresh.js +71 -0
  20. package/dist/bridge/codex-question-reply.d.ts +16 -0
  21. package/dist/bridge/codex-question-reply.js +57 -0
  22. package/dist/bridge/codex-review-mode.d.ts +10 -0
  23. package/dist/bridge/codex-review-mode.js +74 -0
  24. package/dist/bridge/codex-servers.d.ts +217 -0
  25. package/dist/bridge/codex-servers.js +636 -0
  26. package/dist/bridge/command.js +94 -4
  27. package/dist/bridge/computer-identity.d.ts +75 -0
  28. package/dist/bridge/computer-identity.js +166 -0
  29. package/dist/bridge/conductor-group.d.ts +91 -8
  30. package/dist/bridge/conductor-group.js +105 -9
  31. package/dist/bridge/conductor-role.d.ts +94 -0
  32. package/dist/bridge/conductor-role.js +176 -0
  33. package/dist/bridge/conductor-sets.d.ts +20 -0
  34. package/dist/bridge/conductor-sets.js +59 -0
  35. package/dist/bridge/dispatch-command.d.ts +3 -0
  36. package/dist/bridge/dispatch-command.js +75 -11
  37. package/dist/bridge/dispatch-returns.d.ts +123 -19
  38. package/dist/bridge/dispatch-returns.js +357 -50
  39. package/dist/bridge/dispatch.d.ts +103 -2
  40. package/dist/bridge/dispatch.js +272 -40
  41. package/dist/bridge/fanout-messages.js +2 -2
  42. package/dist/bridge/fanouts.d.ts +7 -1
  43. package/dist/bridge/fanouts.js +40 -5
  44. package/dist/bridge/folder-trust.d.ts +56 -0
  45. package/dist/bridge/folder-trust.js +195 -0
  46. package/dist/bridge/grants.d.ts +22 -1
  47. package/dist/bridge/grants.js +57 -9
  48. package/dist/bridge/hand-off.d.ts +21 -9
  49. package/dist/bridge/hand-off.js +58 -45
  50. package/dist/bridge/harness-status.d.ts +11 -0
  51. package/dist/bridge/harness-status.js +32 -0
  52. package/dist/bridge/harnesses.d.ts +39 -0
  53. package/dist/bridge/harnesses.js +65 -0
  54. package/dist/bridge/health.d.ts +2 -0
  55. package/dist/bridge/health.js +1 -1
  56. package/dist/bridge/herdr.d.ts +11 -2
  57. package/dist/bridge/herdr.js +98 -23
  58. package/dist/bridge/hook-fast.d.ts +4 -0
  59. package/dist/bridge/hook-fast.js +68 -0
  60. package/dist/bridge/install.d.ts +16 -1
  61. package/dist/bridge/install.js +88 -21
  62. package/dist/bridge/launch-brief.d.ts +96 -0
  63. package/dist/bridge/launch-brief.js +164 -0
  64. package/dist/bridge/model-switch.d.ts +3 -0
  65. package/dist/bridge/model-switch.js +17 -1
  66. package/dist/bridge/models.d.ts +8 -4
  67. package/dist/bridge/models.js +24 -8
  68. package/dist/bridge/mux-wire.d.ts +9 -0
  69. package/dist/bridge/mux-wire.js +19 -0
  70. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  71. package/dist/bridge/opencode-pane-server.js +332 -0
  72. package/dist/bridge/opencode-panes.d.ts +111 -0
  73. package/dist/bridge/opencode-panes.js +295 -0
  74. package/dist/bridge/pane-accounts.d.ts +8 -0
  75. package/dist/bridge/pane-accounts.js +46 -0
  76. package/dist/bridge/prompt-startup.d.ts +5 -0
  77. package/dist/bridge/prompt-startup.js +24 -0
  78. package/dist/bridge/protocol.d.ts +5 -0
  79. package/dist/bridge/protocol.js +4 -0
  80. package/dist/bridge/push.d.ts +5 -4
  81. package/dist/bridge/push.js +6 -4
  82. package/dist/bridge/questions.d.ts +37 -2
  83. package/dist/bridge/questions.js +158 -15
  84. package/dist/bridge/resources.d.ts +125 -0
  85. package/dist/bridge/resources.js +314 -0
  86. package/dist/bridge/schedule-format.d.ts +2 -0
  87. package/dist/bridge/schedule-format.js +3 -0
  88. package/dist/bridge/schedule-launch.d.ts +2 -1
  89. package/dist/bridge/schedule-launch.js +23 -53
  90. package/dist/bridge/schedule-watch.d.ts +10 -1
  91. package/dist/bridge/schedule-watch.js +54 -2
  92. package/dist/bridge/server-launch.d.ts +22 -5
  93. package/dist/bridge/server-launch.js +225 -29
  94. package/dist/bridge/server-overview.d.ts +8 -2
  95. package/dist/bridge/server-overview.js +26 -5
  96. package/dist/bridge/server-pane-routes.d.ts +2 -0
  97. package/dist/bridge/server-pane-routes.js +145 -15
  98. package/dist/bridge/server-routes.d.ts +11 -1
  99. package/dist/bridge/server-routes.js +195 -36
  100. package/dist/bridge/server-stream.d.ts +2 -0
  101. package/dist/bridge/server-stream.js +22 -8
  102. package/dist/bridge/server.d.ts +6 -1
  103. package/dist/bridge/server.js +47 -12
  104. package/dist/bridge/session-activity.d.ts +81 -0
  105. package/dist/bridge/session-activity.js +117 -0
  106. package/dist/bridge/session-rename.d.ts +48 -0
  107. package/dist/bridge/session-rename.js +190 -0
  108. package/dist/bridge/session-servers.js +2 -2
  109. package/dist/bridge/settings-switch.d.ts +60 -0
  110. package/dist/bridge/settings-switch.js +287 -0
  111. package/dist/bridge/speech-voice.d.ts +55 -0
  112. package/dist/bridge/speech-voice.js +132 -0
  113. package/dist/bridge/speech.d.ts +70 -11
  114. package/dist/bridge/speech.js +169 -41
  115. package/dist/bridge/terminal-herdr.js +9 -3
  116. package/dist/bridge/terminal-tmux.d.ts +3 -3
  117. package/dist/bridge/terminal-tmux.js +24 -9
  118. package/dist/bridge/terminal.d.ts +27 -4
  119. package/dist/bridge/terminal.js +8 -1
  120. package/dist/bridge/transcript-claude.js +62 -12
  121. package/dist/bridge/transcript-codex.d.ts +0 -2
  122. package/dist/bridge/transcript-codex.js +29 -4
  123. package/dist/bridge/transcript-preview.d.ts +1 -0
  124. package/dist/bridge/transcript-preview.js +24 -4
  125. package/dist/bridge/transcripts.d.ts +15 -2
  126. package/dist/bridge/transcripts.js +47 -16
  127. package/dist/bridge/turn-records.d.ts +85 -0
  128. package/dist/bridge/turn-records.js +143 -0
  129. package/dist/bridge/uploads.d.ts +3 -0
  130. package/dist/bridge/uploads.js +14 -0
  131. package/dist/bridge/usage.d.ts +73 -28
  132. package/dist/bridge/usage.js +313 -340
  133. package/dist/bridge-hook.mjs +24624 -18450
  134. package/dist/cli/claude-unmanaged.d.ts +12 -0
  135. package/dist/cli/claude-unmanaged.js +105 -0
  136. package/dist/cli/schedules.js +2 -1
  137. package/dist/cli/session-start.js +10 -1
  138. package/dist/cli/session-stop.js +9 -1
  139. package/dist/cli-registry.d.ts +2 -0
  140. package/dist/cli-registry.js +37 -5
  141. package/dist/computers/command.d.ts +6 -0
  142. package/dist/computers/command.js +152 -0
  143. package/dist/computers/mcp.d.ts +1 -0
  144. package/dist/computers/mcp.js +97 -0
  145. package/dist/computers/read.d.ts +85 -0
  146. package/dist/computers/read.js +177 -0
  147. package/dist/data/task-receipts.d.ts +19 -0
  148. package/dist/data/task-receipts.js +68 -0
  149. package/dist/data/tasks.js +4 -1
  150. package/dist/entrypoint.js +10 -0
  151. package/dist/fanout/adapters/claude.js +15 -2
  152. package/dist/fanout/adapters/types.d.ts +6 -0
  153. package/dist/fanout/launcher.d.ts +5 -1
  154. package/dist/fanout/launcher.js +34 -3
  155. package/dist/fanout/picker.js +3 -2
  156. package/dist/fanout/usage.js +1 -1
  157. package/dist/generated/memory-ui-graph.browser.js +63 -63
  158. package/dist/graph-core/model.js +24 -3
  159. package/dist/graph-core/types.d.ts +4 -1
  160. package/dist/graph-core/types.js +1 -0
  161. package/dist/init/init-preset.js +7 -3
  162. package/dist/init/init-uninstall.js +2 -11
  163. package/dist/init/teardown.d.ts +3 -0
  164. package/dist/init/teardown.js +47 -0
  165. package/dist/link/context.js +21 -9
  166. package/dist/mcp/plugin-mode.js +1 -1
  167. package/dist/memory-ui-graph.runtime.js +63 -63
  168. package/dist/modules/code-package.d.ts +1 -0
  169. package/dist/modules/code-package.js +36 -7
  170. package/dist/modules/registry.js +14 -13
  171. package/dist/profile-store.d.ts +6 -0
  172. package/dist/profile-store.js +25 -1
  173. package/dist/shell/graph/glyphs.js +4 -0
  174. package/dist/shell/graph/graph-view.js +2 -0
  175. package/dist/status.js +7 -1
  176. package/dist/sync/task-claim.js +3 -2
  177. package/dist/task/lifecycle.js +25 -4
  178. package/dist/test-global-setup.js +5 -0
  179. package/dist/tools/dispatch.js +35 -2
  180. package/dist/tools/tasks.js +10 -1
  181. package/package.json +1 -1
  182. package/plugins/opencode/phren-transcript.js +87 -4
  183. package/starter/global/skills/conductor/SKILL.md +17 -2
  184. package/starter/global/skills/fanout/SKILL.md +3 -0
@@ -6,6 +6,7 @@ export declare function loadedFrom(): string | undefined;
6
6
  /** Resolution order for the optional package. First success wins and is remembered. */
7
7
  export declare function loadCodePackage(store?: string): Promise<CodePackage | undefined>;
8
8
  export declare function requireCodePackage(store?: string): Promise<CodePackage>;
9
+ export declare function codePackageHint(store?: string): string;
9
10
  /**
10
11
  * Make @phren/code available to this store. A workspace checkout links its own
11
12
  * package; otherwise npm installs into the store's runtime packages, which the
@@ -13,8 +13,8 @@ export function loadedFrom() { return resolvedFrom; }
13
13
  * The Hook bundle runs from `<bridge>/versions/<v>` with no node_modules, so a
14
14
  * bare import fails there and the npm global root is invisible when the
15
15
  * daemon's PATH has no npm (mise shims under systemd). Resolve a local copy
16
- * before the bare import: an explicit directory, the bridge install, then the
17
- * store's runtime packages.
16
+ * before the bare import: an explicit directory, the bridge install, the
17
+ * store's runtime packages, then a built workspace sibling.
18
18
  */
19
19
  function bridgeRoot() { return process.env.PHREN_BRIDGE_HOME || path.join(homedir(), ".local/share/phren/bridge"); }
20
20
  /** The npm shims and Homebrew bin a service manager's PATH usually omits. */
@@ -69,6 +69,9 @@ export async function loadCodePackage(store) {
69
69
  const root = store || process.env.PHREN_PATH;
70
70
  if (root)
71
71
  candidates.push(path.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
72
+ const workspace = workspaceCodeDirectory();
73
+ if (workspace && builtEntryExists(workspace))
74
+ candidates.push(workspace);
72
75
  for (const directory of candidates) {
73
76
  if (!fs.existsSync(path.join(directory, "package.json")))
74
77
  continue;
@@ -102,7 +105,7 @@ export async function loadCodePackage(store) {
102
105
  export async function requireCodePackage(store) {
103
106
  const code = await loadCodePackage(store);
104
107
  if (!code)
105
- throw new Error(CODE_PACKAGE_HINT);
108
+ throw new Error(codePackageHint(store));
106
109
  return code;
107
110
  }
108
111
  /** This repository checked out as a workspace, if its packages/code is present. */
@@ -119,6 +122,31 @@ function workspaceCodeDirectory() {
119
122
  }
120
123
  return undefined;
121
124
  }
125
+ function builtEntryExists(directory) {
126
+ try {
127
+ return fs.existsSync(packageEntry(directory));
128
+ }
129
+ catch {
130
+ return false;
131
+ }
132
+ }
133
+ export function codePackageHint(store) {
134
+ const root = store || process.env.PHREN_PATH;
135
+ const linked = root && path.join(root, ".runtime", "packages", "node_modules", "@phren", "code");
136
+ const workspace = workspaceCodeDirectory();
137
+ let workspaceLink;
138
+ try {
139
+ if (linked && fs.lstatSync(linked).isSymbolicLink())
140
+ workspaceLink = linked;
141
+ }
142
+ catch { /* no store link */ }
143
+ for (const directory of [workspace, workspaceLink]) {
144
+ if (!directory || !fs.existsSync(path.join(directory, "package.json")) || builtEntryExists(directory))
145
+ continue;
146
+ return `${CODE_PACKAGE_HINT}. @phren/code at ${directory} has no built entry. From the source checkout root run: pnpm --filter @phren/code build`;
147
+ }
148
+ return `${CODE_PACKAGE_HINT}. For a source checkout, from its root run pnpm --filter @phren/code build, then node packages/cli/dist/index.js modules enable code and restart the Hook.`;
149
+ }
122
150
  /**
123
151
  * Make @phren/code available to this store. A workspace checkout links its own
124
152
  * package; otherwise npm installs into the store's runtime packages, which the
@@ -126,18 +154,19 @@ function workspaceCodeDirectory() {
126
154
  */
127
155
  export async function installCodePackage(store) {
128
156
  const existing = await loadCodePackage(store);
129
- if (existing)
157
+ const workspace = workspaceCodeDirectory();
158
+ // The installed Hook bundle cannot find the workspace sibling after relocation.
159
+ if (existing && resolvedFrom !== workspace)
130
160
  return existing;
131
161
  const packages = path.join(store, ".runtime", "packages");
132
162
  const linked = path.join(packages, "node_modules", "@phren", "code");
133
- const workspace = workspaceCodeDirectory();
134
163
  if (workspace) {
135
164
  fs.mkdirSync(path.dirname(linked), { recursive: true });
136
165
  fs.rmSync(linked, { recursive: true, force: true });
137
166
  fs.symlinkSync(workspace, linked, "junction");
138
- const code = await loadCodePackage(store);
167
+ const code = existing ?? await loadCodePackage(store);
139
168
  if (!code)
140
- throw new Error(`${CODE_PACKAGE_HINT}\nLinked ${workspace}, but it could not be loaded. Run pnpm build.`);
169
+ throw new Error(`${codePackageHint(store)}\nLinked ${workspace}, but it could not be loaded.`);
141
170
  console.log(`@phren/code linked from ${workspace} into ${linked}.`);
142
171
  return code;
143
172
  }
@@ -69,25 +69,25 @@ export const BUILTIN_MODULES = [
69
69
  cliCommands: [
70
70
  "bridge", "bridge install", "bridge update", "bridge uninstall", "bridge rollback", "bridge status",
71
71
  "bridge doctor", "bridge usage", "bridge usage-statusline", "bridge hook", "bridge serve", "bridge ssh", "pair",
72
- "bridge fanouts archive", "canary",
72
+ "bridge fanouts archive", "bridge accounts", "canary", "computers", "computers mcp", "usage",
73
73
  ],
74
74
  agentHooks: [
75
- { agents: ["codex", "claude"], events: ["SessionStart", "UserPromptSubmit", "Stop", "PermissionRequest"], handler: "bridge-hook.mjs hook <agent>" },
76
- { agents: ["claude"], events: ["PreCompact"], handler: "bridge-hook.mjs hook claude" },
75
+ { agents: ["codex"], events: ["SessionStart", "UserPromptSubmit", "Stop", "PermissionRequest"], handler: "bridge-hook.mjs hook codex" },
76
+ { agents: ["claude"], events: ["SessionStart", "UserPromptSubmit", "Stop", "PermissionRequest", "PreCompact"], handler: "claude-hook.mjs claude" },
77
77
  { agents: ["copilot"], events: ["SessionStart", "UserPromptSubmit"], handler: "bridge-hook.mjs hook copilot" },
78
78
  ],
79
79
  hookRoutes: [
80
80
  ...routes("GET", [
81
81
  "/v1/health", "/v1/health/details", "/v1/health/peers", "/v1/muxes", "/v1/activity", "/v1/metrics", "/v1/web-servers", "/v1/simulators",
82
- "/v1/simulators/screenshot", "/v1/simulators/apps", "/v1/files", "/v1/models", "/v1/projects/files",
83
- "/v1/uploads/image", "/v1/files/range", "/v1/usage", "/v1/push/status", "/v1/projects/locate", "/v1/projects/repos",
82
+ "/v1/simulators/screenshot", "/v1/simulators/apps", "/v1/files", "/v1/models", "/v1/harnesses", "/v1/projects/files",
83
+ "/v1/uploads/image", "/v1/files/range", "/v1/usage", "/v1/resources", "/v1/speech/voices", "/v1/push/status", "/v1/projects/locate", "/v1/projects/repos",
84
84
  "/v1/workspaces", "/v1/workspaces/panes", "/v1/transcripts/blob", "/v1/transcripts/history",
85
85
  "/v1/subagents", "/v1/subagents/transcript", "/v1/subagents/messages",
86
86
  ]),
87
87
  ...routes("POST", [
88
88
  "/v1/push/register", "/v1/push/answer", "/v1/push/target", "/v1/files", "/v1/projects/add", "/v1/simulators/action",
89
89
  "/v1/workspaces/launch", "/v1/workspaces/create", "/v1/workspaces/focus", "/v1/workspaces/rename",
90
- "/v1/workspaces/close", "/v1/prompt", "/v1/model", "/v1/side-question/dismiss", "/v1/keys", "/v1/secret", "/v1/upload",
90
+ "/v1/workspaces/close", "/v1/sessions/rename", "/v1/prompt", "/v1/prompt/status", "/v1/model", "/v1/settings", "/v1/side-question/dismiss", "/v1/keys", "/v1/secret", "/v1/upload",
91
91
  "/v1/approvals/answer", "/v1/questions/answer", "/v1/subagents/resume", "/v1/subagents/archive-finished", "/v1/canary",
92
92
  "/v1/speech",
93
93
  ]),
@@ -96,7 +96,7 @@ export const BUILTIN_MODULES = [
96
96
  capabilities: [
97
97
  "hook", "transcript", "progress", "images", "prompt", "stop", "terminal", "shell", "herdr",
98
98
  "webServers", "webPreview", "activity", "approvals", "questions", "accountUsage", "providers",
99
- "files", "repositoryFiles", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "speechTimestamps", "transcribe", "promptOnce",
99
+ "files", "repositoryFiles", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "speechTimestamps", "speechVoices", "speechFormats", "transcribe", "promptOnce", "promptStatus", "resources", "sessionRename",
100
100
  ],
101
101
  storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
102
102
  localFiles: ["<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily"],
@@ -107,7 +107,8 @@ export const BUILTIN_MODULES = [
107
107
  schemaVersion: 1, name: "git", version: VERSION, defaultEnabled: false, requires: ["memory"],
108
108
  tools: full(["auto_extract_findings"]), cliCommands: ["maintain extract", "extract-memories"],
109
109
  agentHooks: [
110
- { agents: ["codex", "claude"], events: ["PreToolUse", "PostToolUse"], handler: "bridge-hook.mjs hook <agent>" },
110
+ { agents: ["codex"], events: ["PreToolUse", "PostToolUse"], handler: "bridge-hook.mjs hook codex" },
111
+ { agents: ["claude"], events: ["PreToolUse", "PostToolUse"], handler: "claude-hook.mjs claude" },
111
112
  ],
112
113
  hookRoutes: routes("POST", [
113
114
  "/v1/diff", "/v1/web-servers/session", "/v1/git/status", "/v1/git/log", "/v1/git/branches", "/v1/git/pulls",
@@ -127,11 +128,11 @@ export const BUILTIN_MODULES = [
127
128
  },
128
129
  {
129
130
  schemaVersion: 1, name: "conductor", version: VERSION, defaultEnabled: false, requires: ["memory", "hook"],
130
- tools: full(["dispatch", "dispatch_returns", "hand_off", "live_sessions"]), cliCommands: ["dispatch", "dispatch status", "dispatch returns", "dispatch sessions", "hand-off", "conductor", "conductor grants", "bridge enroll-computer"], agentHooks: [],
131
- hookRoutes: [...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/conductor", "/v1/conductor/grants"]),
132
- ...routes("POST", ["/v1/dispatch", "/v1/dispatch/workers", "/v1/dispatch/returns", "/v1/conductor/grants"]), ...routes("DELETE", ["/v1/conductor/grants"])],
133
- capabilities: ["dispatch"], storeFiles: ["global/skills/conductor/**"],
134
- localFiles: ["<bridge>/hooks.yaml", "<bridge>/conductor.yaml", "<bridge>/dispatches/*.json"], phoneScreens: [], skills: ["conductor"],
131
+ tools: full(["dispatch", "dispatch_returns", "dispatch_approve", "hand_off", "live_sessions", "authority"]), cliCommands: ["dispatch", "dispatch status", "dispatch returns", "dispatch sessions", "hand-off", "conductor", "conductor grants", "conductor status", "conductor make", "conductor stop", "conductor sets", "authority", "bridge enroll-computer"], agentHooks: [],
132
+ hookRoutes: [...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/dispatch/arrival", "/v1/conductor", "/v1/conductor/grants", "/v1/computers", "/v1/sets", "/v1/authority"]),
133
+ ...routes("POST", ["/v1/dispatch", "/v1/dispatch/workers", "/v1/dispatch/returns", "/v1/dispatch/approve", "/v1/conductor/grants", "/v1/conductor/make", "/v1/conductor/stop", "/v1/sets/name", "/v1/authority", "/v1/authority/confirm"]), ...routes("DELETE", ["/v1/conductor/grants", "/v1/authority"])],
134
+ capabilities: ["dispatch", "conductorSets"], storeFiles: ["global/skills/conductor/**"],
135
+ localFiles: ["<bridge>/hooks.yaml", "<bridge>/conductor.yaml", "<bridge>/conductor-role.json", "<bridge>/authority.yaml", "<bridge>/authority-confirmations.json", "<bridge>/dispatches/*.json"], phoneScreens: [], skills: ["conductor"],
135
136
  },
136
137
  {
137
138
  schemaVersion: 1, name: "fanout", version: VERSION, defaultEnabled: false, requires: ["memory", "hook"],
@@ -27,6 +27,12 @@ export interface ProjectCard {
27
27
  store?: string;
28
28
  }
29
29
  export declare function resolveActiveProfile(phrenPath: string, requestedProfile?: string): PhrenResult<string | undefined>;
30
+ /** Explain implicit selection without changing the selected profile. */
31
+ export declare function describeProfileMapping(phrenPath: string): {
32
+ machine: string;
33
+ mapped: boolean;
34
+ assumed?: string;
35
+ };
30
36
  export declare function getDefaultMachineAlias(): string;
31
37
  export declare function listMachines(phrenPath: string): PhrenResult<Record<string, string>>;
32
38
  export declare function setMachineProfile(phrenPath: string, machine: string, profile: string): PhrenResult<string>;
@@ -43,7 +43,31 @@ export function resolveActiveProfile(phrenPath, requestedProfile) {
43
43
  const profiles = listProfiles(phrenPath);
44
44
  if (!profiles.ok)
45
45
  return phrenOk(undefined);
46
- return phrenOk(profiles.data[0]?.name);
46
+ const assumed = profiles.data[0]?.name;
47
+ if (assumed && profiles.data.length > 1 && process.env.PHREN_QUIET !== "1") {
48
+ const machine = getMachineName();
49
+ const key = JSON.stringify([phrenPath, machine, assumed]);
50
+ if (!warnedProfileAssumptions.has(key)) {
51
+ warnedProfileAssumptions.add(key);
52
+ process.stderr.write(`[phren] Machine "${machine}" is not mapped in machines.yaml; assuming profile "${assumed}". Run 'phren profile switch ${assumed}' to pin it.\n`);
53
+ }
54
+ }
55
+ return phrenOk(assumed);
56
+ }
57
+ const warnedProfileAssumptions = new Set();
58
+ /** Explain implicit selection without changing the selected profile. */
59
+ export function describeProfileMapping(phrenPath) {
60
+ const machine = getMachineName();
61
+ const machines = listMachines(phrenPath);
62
+ const profiles = listProfiles(phrenPath);
63
+ if (machines.ok && profiles.ok) {
64
+ for (const name of [machine, defaultMachineName()]) {
65
+ const mapped = machines.data[name];
66
+ if (mapped && profiles.data.some((entry) => entry.name === mapped))
67
+ return { machine, mapped: true };
68
+ }
69
+ }
70
+ return { machine, mapped: false, assumed: profiles.ok ? profiles.data[0]?.name : undefined };
47
71
  }
48
72
  export function getDefaultMachineAlias() {
49
73
  return getMachineName();
@@ -12,6 +12,8 @@ const UNICODE = {
12
12
  task: "▤",
13
13
  entity: "❖",
14
14
  reference: "▣",
15
+ topic: "◆",
16
+ note: "▪",
15
17
  other: "·",
16
18
  };
17
19
  const NERD = {
@@ -20,6 +22,8 @@ const NERD = {
20
22
  task: "", // nf-fa-check_square_o
21
23
  entity: "", // nf-fa-share_alt (node graph)
22
24
  reference: "", // nf-fa-book
25
+ topic: "", // nf-fa-tag
26
+ note: "", // nf-fa-sticky_note
23
27
  other: "", // nf-fa-circle
24
28
  };
25
29
  export function iconMode(env = process.env) {
@@ -34,6 +34,8 @@ const KIND_LABEL = {
34
34
  task: "task",
35
35
  entity: "fragment",
36
36
  reference: "reference",
37
+ topic: "topic",
38
+ note: "note",
37
39
  other: "node",
38
40
  };
39
41
  const HEALTH_COLOR = {
package/dist/status.js CHANGED
@@ -13,6 +13,7 @@ import { logger } from "./logger.js";
13
13
  import { readRuntimeHealth, resolveTaskFilePath, FINDINGS_FILENAME } from "./data/access.js";
14
14
  import { assessSyncOutage } from "./shared/governance.js";
15
15
  import { resolveRuntimeProfile } from "./runtime-profile.js";
16
+ import { describeProfileMapping } from "./profile-store.js";
16
17
  import { renderPhrenArt } from "./phren-art.js";
17
18
  import { RESET, BOLD, DIM, GREEN, YELLOW, RED, CYAN } from "./shell/render.js";
18
19
  import { storeWeight } from "./store-weight.js";
@@ -117,7 +118,12 @@ export async function runStatus() {
117
118
  console.log(` ${DIM}sync${RESET} ${manifest.syncMode}`);
118
119
  }
119
120
  if (profile) {
120
- console.log(` ${DIM}profile${RESET} ${profile}`);
121
+ const mapping = describeProfileMapping(phrenPath);
122
+ const assumed = !process.env.PHREN_PROFILE?.trim() && !mapping.mapped && mapping.assumed === profile;
123
+ const suffix = assumed
124
+ ? ` ${YELLOW}(assumed; machine "${mapping.machine}" is not mapped in machines.yaml)${RESET}`
125
+ : "";
126
+ console.log(` ${DIM}profile${RESET} ${profile}${suffix}`);
121
127
  }
122
128
  // Management preset + MCP + hooks status
123
129
  const preset = getManagementPreset(phrenPath);
@@ -2,11 +2,12 @@ import { runBestEffortGit } from "../cli/session-git.js";
2
2
  import { claimTask, resolveTaskItem } from "../data/tasks.js";
3
3
  import { withFileLock } from "../governance/locks.js";
4
4
  import { runtimeFile } from "../phren-paths.js";
5
+ import { trackTaskWriteCommits } from "../data/task-receipts.js";
5
6
  import { mergeStoreUpstream } from "./store-merge.js";
6
- const git = async (cwd, args) => {
7
+ const git = trackTaskWriteCommits(async (cwd, args) => {
7
8
  const result = await runBestEffortGit(args, cwd);
8
9
  return { ok: result.ok, output: result.output ?? "", error: result.error };
9
- };
10
+ });
10
11
  /**
11
12
  * Claims a task across unlinked conductors: pull the store so a claim already
12
13
  * pushed elsewhere refuses this one, write the claim, then commit and push.
@@ -45,9 +45,21 @@ const CONVERSATIONAL_FILLER_RE = /\b(?:lmao|lmfao|rofl|lol+|haha+|idk|idc|tbh|ng
45
45
  // words (a relayed conductor message rewrote a task's Context three times), so it never
46
46
  // files or touches a task; only what was typed outside the wrapper counts.
47
47
  const PASTED_CONTENT_WRAPPER_RE = /<pasted_content\b[^>]*>[\s\S]*?<\/pasted_content\b[^>]*>/g;
48
- // A message relayed from another agent: "From the conductor, a correction: …",
49
- // "From tidy-phren: …". One name (optionally after "the"), then a comma or colon.
50
- const RELAYED_MESSAGE_RE = /^\s*from\s+(?:the\s+)?(?!(?:now|here|there|then|scratch|today|tomorrow)\b)[\w.-]+\s*[,:]/i;
48
+ // Relays may name one sender ("From tidy-phren:") or a computer and agent
49
+ // ("From macbook android-codex:"). Keep "From now on" as a request.
50
+ // A two-word sender needs the colon; longer names need a parenthesized handle.
51
+ // "From the settings page, add …" stays a request.
52
+ const RELAYED_MESSAGE_RE = /^\s*from\s+(?:the\s+)?(?!(?:now|here|there|then|scratch|today|tomorrow)\b)(?:[\w.-]+\s*[,:]|[\w.-]+\s+[\w.-]+\s*:|[\w.-]+(?:[ \t]+[\w.-]+)*[ \t]+\([\w.-]+\)[ \t]*:)/i;
53
+ // Dispatch returns are typed into an idle agent as ordinary prompts.
54
+ const DISPATCH_RETURN_NOTICE_RE = /^\s*returns?:\s+[^\n]+\bCall dispatch_returns\.\s*$/i;
55
+ // A dispatched or scheduled worker's first prompt names its brief file
56
+ // (launch-brief.ts). The dispatch already tracks that work, so the worker's
57
+ // own hook must not file it again: every dispatched Claude filed one task.
58
+ const LAUNCH_BRIEF_PROMPT_RE = /^\s*Read and follow the brief in \/[^\n]+$/;
59
+ // Completed-work reports can arrive without a relay prefix. Only a status
60
+ // reporting a commit or push, or ending in an opened PR, is excluded;
61
+ // imperative requests stay eligible even when they mention a pushed commit.
62
+ const AGENT_STATUS_REPORT_RE = /(?:\b(?:committed|pushed)\s+(?:as\s+)?[0-9a-f]{7,40}\b|\bPR\s+#\d+\s+opened\s*[.!]?\s*$)/i;
51
63
  // Frames another agent or the harness put in the prompt: a cross-session message, a
52
64
  // sub-agent hand-back, a delivery/idle notice, a task or system notification, a system
53
65
  // reminder. Not the person's request. Matched anywhere, since a harness may put the
@@ -61,10 +73,19 @@ const QUESTION_RE = /\?\s*$/;
61
73
  export function typedPromptText(prompt) {
62
74
  return prompt.includes("<pasted_content") ? prompt.replace(PASTED_CONTENT_WRAPPER_RE, " ").trim() : prompt;
63
75
  }
76
+ function isAgentStatusReportPrompt(prompt) {
77
+ const trimmed = prompt.trim();
78
+ if (ACTION_PREFIX_RE.test(trimmed) || /^(?:can|could|would|will|should)\b/i.test(trimmed)
79
+ || ACTIONABLE_RE.exec(trimmed)?.index === 0)
80
+ return false;
81
+ return AGENT_STATUS_REPORT_RE.test(trimmed);
82
+ }
64
83
  /** A frame from another agent or the harness, or a message relayed from one,
65
84
  * rather than something the person asked. */
66
85
  export function isAgentFramePrompt(prompt) {
67
- return AGENT_FRAME_RE.test(prompt) || RELAYED_MESSAGE_RE.test(prompt);
86
+ return AGENT_FRAME_RE.test(prompt) || RELAYED_MESSAGE_RE.test(prompt)
87
+ || DISPATCH_RETURN_NOTICE_RE.test(prompt) || LAUNCH_BRIEF_PROMPT_RE.test(prompt)
88
+ || isAgentStatusReportPrompt(prompt);
68
89
  }
69
90
  /** A reply or a question: conversation with the agent, not a request for work. */
70
91
  function isConversationalTurn(prompt) {
@@ -42,6 +42,11 @@ function sandboxHomeDir() {
42
42
  // resolves exactly as on a clean CI machine: the sandbox store if a test
43
43
  // makes one, otherwise no store. A test that needs the walk clears this.
44
44
  process.env.PHREN_PATH = path.join(sandboxHome, ".phren");
45
+ // The Hook writes folder trust into Claude's and Codex's own config
46
+ // (bridge/folder-trust.ts). A developer's CLAUDE_CONFIG_DIR or CODEX_HOME
47
+ // would point that at their real files, so both fall back to the sandbox.
48
+ delete process.env.CLAUDE_CONFIG_DIR;
49
+ delete process.env.CODEX_HOME;
45
50
  }
46
51
  export async function teardown() {
47
52
  if (sandboxHome)
@@ -1,3 +1,4 @@
1
+ import { z } from "zod";
1
2
  import { hookRequest } from "../bridge/client.js";
2
3
  import { dispatchSchema } from "../bridge/dispatch.js";
3
4
  import { handOff, handOffSchema, listLiveSessions } from "../bridge/hand-off.js";
@@ -21,7 +22,7 @@ export function register(server) {
21
22
  });
22
23
  server.registerTool("dispatch_returns", {
23
24
  title: "◆ phren · dispatch returns",
24
- description: "List unread returns from dispatched workers and mark them read: the worker finished (done, with its final reply), finished by asking the owner something (needs-you, with the question), failed (the harness ended the turn on an error such as a usage limit, with the error), is blocked on terminal input, or its pane is gone. Each row has the dispatch id, computer, project, label and the worker's target for hand_off.",
25
+ description: "List unread returns from dispatched workers and mark them read: the worker finished (done, with its final reply), finished by asking the owner something (needs-you, with the question), failed (the harness ended the turn on an error such as a usage limit, with the error), is blocked on terminal input, or its pane is gone. A blocked row with an `approval` field (actionId, tool, request) is a permission request the worker is waiting on, forwarded from its computer: answer it with dispatch_approve. A worker that ended its turn with background tasks pending is waited on for up to two hours; a row has `waited` (the most tasks it waited on) or, if some were still running after that, `background`. Each row has the dispatch id, computer, project, label and the worker's target for hand_off.",
25
26
  inputSchema: {},
26
27
  }, async () => {
27
28
  try {
@@ -33,9 +34,27 @@ export function register(server) {
33
34
  return mcpResponse({ ok: false, error: error instanceof Error ? error.message : "Could not read dispatch returns." });
34
35
  }
35
36
  });
37
+ server.registerTool("dispatch_approve", {
38
+ title: "◆ phren · dispatch approve",
39
+ description: "Answer the permission request a dispatched worker is waiting on, forwarded from its computer: a dispatch_returns row with an approval field names it. The owner's standing grants already answer the dispatch and hand_off requests they cover. Only the agent that dispatched the worker can answer, never the worker itself. Pass the approval's actionId, so a request that changed since you read it is never answered blind. Deny when unsure and ask the owner.",
40
+ inputSchema: {
41
+ id: z.string().uuid().describe("Dispatch id from dispatch_returns."),
42
+ decision: z.enum(["approve", "deny"]),
43
+ actionId: z.string().min(1).max(200).describe("The approval's actionId from dispatch_returns; a request that has since changed is refused."),
44
+ },
45
+ }, async (input) => {
46
+ try {
47
+ const origin = await terminalPaneFromEnv();
48
+ const result = await hookRequest("/v1/dispatch/approve", { ...input, ...(origin ? { origin } : {}) });
49
+ return mcpResponse({ ok: result.ok === true, data: result, message: input.decision === "approve" ? "Approved." : "Denied." });
50
+ }
51
+ catch (error) {
52
+ return mcpResponse({ ok: false, error: error instanceof Error ? error.message : "Could not answer the approval." });
53
+ }
54
+ });
36
55
  server.registerTool("live_sessions", {
37
56
  title: "◆ phren · live sessions",
38
- description: "List the live agent sessions on this computer and every enrolled computer: computer, project, harness, status, idleFor (seconds since the tab last changed), role and the target hand_off takes. Computers that could not be reached are listed separately, and computers registered in the store but not linked in hooks.yaml come back in notLinked: their sessions are unknown, not absent.",
57
+ description: "List the live agent sessions on this computer and every enrolled computer: computer, project, harness, status (working, with backgroundTasks, while background work runs after the main turn ended), idleFor (seconds since the tab last changed), role and the target hand_off takes. Computers that could not be reached are listed separately, and computers registered in the store but not linked in hooks.yaml come back in notLinked: their sessions are unknown, not absent.",
39
58
  inputSchema: {},
40
59
  }, async () => {
41
60
  try {
@@ -50,6 +69,20 @@ export function register(server) {
50
69
  return mcpResponse({ ok: false, error: error instanceof Error ? error.message : "Could not list live sessions." });
51
70
  }
52
71
  });
72
+ server.registerTool("authority", {
73
+ title: "◆ phren · release authority",
74
+ description: "Read the owner's release authority policy: per project, which release-type actions (merge, publish, deploy, app-store, github-admin) are go and which are ask-first, and the highest permission mode an agent may start a worker in there. Quote the project's `line` in a brief that asks for release work, and declare those actions in dispatch's releaseActions. An ask-first action needs the owner's confirmation first; ask the owner, never try to confirm it yourself. Read-only: only the owner changes the policy. Without project, lists every project the policy names.",
75
+ inputSchema: { project: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/).optional().describe("Project slug; omit to list the whole policy.") },
76
+ }, async (input) => {
77
+ try {
78
+ const result = await hookRequest(`/v1/authority${input.project ? `?project=${encodeURIComponent(input.project)}` : ""}`);
79
+ const one = result.authority;
80
+ return mcpResponse({ ok: true, data: result, message: one?.line ?? `${Array.isArray(result.projects) ? result.projects.length : 0} projects in the release authority policy.` });
81
+ }
82
+ catch (error) {
83
+ return mcpResponse({ ok: false, error: error instanceof Error ? error.message : "Could not read the release authority policy." });
84
+ }
85
+ });
53
86
  server.registerTool("hand_off", {
54
87
  title: "◆ phren · hand off",
55
88
  description: "Deliver a prompt to an existing local or enrolled-computer agent session through Phren Hook. Prefer a session that already owns the project and is idle or doing related work.",
@@ -5,6 +5,7 @@ import * as path from "path";
5
5
  import { isValidProjectName } from "../utils.js";
6
6
  import { addTask as addTaskStore, addTasks as addTasksBatch, taskMarkdown, completeTask as completeTaskStore, completeTasks as completeTasksBatch, removeTask as removeTaskStore, removeTasks as removeTasksBatch, linkTaskIssue, pinTask, unpinTask, workNextTask, tidyDoneTasks, readTasks, readTasksAcrossProjects, resolveTaskItem, TASKS_FILENAME, updateTask as updateTaskStore, promoteTask, } from "../data/access.js";
7
7
  import { applyGravity } from "../data/tasks.js";
8
+ import { captureTaskWrites } from "../data/task-receipts.js";
8
9
  import { buildTaskIssueBody, createGithubIssueForTask, parseGithubIssueUrl, resolveProjectGithubRepo, } from "../task/github.js";
9
10
  import { clearTaskCheckpoint } from "../session/checkpoints.js";
10
11
  import { incrementSessionTasksCompleted } from "./session.js";
@@ -91,7 +92,15 @@ function buildTaskSummary(doc, includedSections) {
91
92
  return lines.join("\n");
92
93
  }
93
94
  export function register(server, ctx) {
94
- const { phrenPath, profile, withWriteQueue, updateFileInIndex } = ctx;
95
+ const { phrenPath, profile, updateFileInIndex } = ctx;
96
+ const withWriteQueue = (fn) => ctx.withWriteQueue(async () => {
97
+ const { result, write } = await captureTaskWrites(fn);
98
+ // Preserve each handler's existing data, including per-item batch errors.
99
+ const payload = JSON.parse(result.content[0].text);
100
+ if (write || payload.ok)
101
+ payload.data = { ...payload.data, write };
102
+ return mcpResponse(payload);
103
+ });
95
104
  server.registerTool("get_tasks", {
96
105
  title: "◆ phren · tasks",
97
106
  description: "Get tasks. Defaults to Active and Queue sections only. Pass status='all' to include Done items.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.10",
3
+ "version": "0.3.12",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,4 +1,5 @@
1
1
  // Installed by Phren Hook and replaced on every update. Copy it under another name to customize.
2
+ import { execFileSync } from "node:child_process";
2
3
  import { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
4
  import { homedir } from "node:os";
4
5
  import path from "node:path";
@@ -16,6 +17,9 @@ const STOP_REASONS = { stop: "end_turn", "tool-calls": "tool_use", length: "max_
16
17
  const OPENCODE_SESSION = /^ses_[0-9A-Za-z]{1,64}$/;
17
18
  const APPROVAL_POLL_MS = 200;
18
19
  const APPROVAL_DEADLINE_MS = 50_000;
20
+ // An ask relayed from its event blocks nothing: the TUI keeps its own prompt,
21
+ // so the phone's card can wait as long as the ask does.
22
+ const RELAYED_DEADLINE_MS = 30 * 60_000;
19
23
 
20
24
  function storeRoot() {
21
25
  if (PHREN_STORE && !PHREN_STORE.startsWith("__")) return PHREN_STORE;
@@ -116,6 +120,26 @@ function sleep(ms) {
116
120
  return new Promise(resolve => setTimeout(resolve, ms));
117
121
  }
118
122
 
123
+ /** Started by Phren Hook with a port of its own (`opencode --port N`, with
124
+ * PHREN_OPENCODE_PORT=N and a server password in its environment): the Hook
125
+ * lists and answers this process's permission asks over its HTTP API, so no
126
+ * request file is written for them. The port must be on this process's own
127
+ * command line, so an OpenCode started by hand in the same shell keeps the
128
+ * file path. Plugins run in a worker whose `process.argv` is the worker's,
129
+ * so the command line comes from `ps`, once. */
130
+ let served;
131
+ function servedByHook() {
132
+ if (served !== undefined) return served;
133
+ const port = text(process.env.PHREN_OPENCODE_PORT);
134
+ served = false;
135
+ if (!/^\d{1,5}$/.test(port) || !text(process.env.OPENCODE_SERVER_PASSWORD)) return served;
136
+ try {
137
+ const command = execFileSync("ps", ["-ww", "-o", "command=", "-p", String(process.pid)], { encoding: "utf8", timeout: 2_000 });
138
+ served = new RegExp(`(?:^|\\s)--port(?:\\s+|=)${port}(?:\\s|$)`).test(command.trim());
139
+ } catch {}
140
+ return served;
141
+ }
142
+
119
143
  function setStatus(output, status) {
120
144
  if (output && typeof output === "object") output.status = status;
121
145
  }
@@ -229,7 +253,9 @@ function writePidBinding(sessionID) {
229
253
  * whose terminal does not watch its agents (tmux); Herdr has its own. */
230
254
  const statusFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-status-${process.pid}.json`);
231
255
 
232
- export const PhrenTranscriptPlugin = async () => {
256
+ export const PhrenTranscriptPlugin = async input => {
257
+ // The process's own API, bound to its in-process server (no port needed).
258
+ const client = input?.client;
233
259
  const sessions = new Map();
234
260
  // Subagent sessions run inside the same process; the pane shows their parent.
235
261
  const children = new Set();
@@ -239,14 +265,22 @@ export const PhrenTranscriptPlugin = async () => {
239
265
  let recordedStatus;
240
266
  // Permission asks still open, by id: while any is, the process is blocked.
241
267
  const asking = new Set();
268
+ // The session's last turn: when it went busy, and when it went idle after
269
+ // that. Dispatch returns read these as the turn's start and Stop.
270
+ let turn = {};
242
271
  const recordStatus = (status, sessionID) => {
243
272
  // A fan-out worker runs headless, in no pane.
244
273
  if (process.env.PHREN_FANOUT_JOB) return;
245
274
  const next = asking.size && status === "working" ? "blocked" : status;
246
275
  if (next === recordedStatus) return;
247
276
  try {
277
+ const at = new Date().toISOString();
278
+ if (sessionID && turn.session !== sessionID) turn = { session: sessionID };
279
+ if (next !== "idle" && (recordedStatus === undefined || recordedStatus === "idle")) { turn.busyAt = at; delete turn.idleAt; }
280
+ else if (next === "idle" && turn.busyAt) turn.idleAt = at;
248
281
  mkdirSync(path.dirname(statusFile()), { recursive: true });
249
- writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at: new Date().toISOString() });
282
+ writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at,
283
+ ...(turn.session === sessionID && turn.busyAt ? { busyAt: turn.busyAt } : {}), ...(turn.session === sessionID && turn.idleAt ? { idleAt: turn.idleAt } : {}) });
250
284
  recordedStatus = next;
251
285
  } catch {}
252
286
  };
@@ -254,6 +288,51 @@ export const PhrenTranscriptPlugin = async () => {
254
288
  const timers = new Map();
255
289
  const written = new Map();
256
290
  const pendingApprovals = new Set();
291
+ // Asks the permission.ask hook took (OpenCode before 1.18), and asks relayed
292
+ // from their event, by id; `done` once the terminal answered one.
293
+ const hookAsks = new Set();
294
+ const relayed = new Map();
295
+
296
+ /** OpenCode 1.18 never calls the permission.ask hook: its TUI draws the ask
297
+ * from the `permission.asked` event. For an OpenCode started by hand the ask
298
+ * goes to the phone through the same request file, and the phone's answer
299
+ * is replied through this process's own API. Whichever answers first wins;
300
+ * an answer in the terminal (`permission.replied`) withdraws the card. */
301
+ const relayAsk = async ask => {
302
+ const id = text(ask?.id), sessionID = text(ask?.sessionID);
303
+ if (process.env.PHREN_FANOUT_JOB || !id || hookAsks.has(id) || relayed.has(id) || !OPENCODE_SESSION.test(sessionID)
304
+ || typeof client?.postSessionIdPermissionsPermissionId !== "function" || servedByHook() || pendingApprovals.has(sessionID)) return;
305
+ const shown = { type: text(ask.permission) || text(ask.type), pattern: Array.isArray(ask.patterns) ? ask.patterns : ask.pattern,
306
+ metadata: ask.metadata, title: ask.title };
307
+ const state = { done: false };
308
+ relayed.set(id, state); pendingApprovals.add(sessionID);
309
+ const { request, answer } = approvalPaths(sessionID);
310
+ try {
311
+ mkdirSync(approvalDirectory(), { recursive: true });
312
+ removeFile(answer);
313
+ const created = Date.now();
314
+ writeJsonAtomic(request, { id, sessionID, type: shown.type || "action",
315
+ title: text(shown.title) || `Allow ${shown.type || "action"}?`, message: permissionMessage(shown),
316
+ createdAt: new Date(created).toISOString(), expiresAt: new Date(created + RELAYED_DEADLINE_MS).toISOString() });
317
+ let decision;
318
+ while (!state.done && Date.now() < created + RELAYED_DEADLINE_MS) {
319
+ await sleep(APPROVAL_POLL_MS);
320
+ try {
321
+ const info = lstatSync(answer);
322
+ if (!info.isFile() || info.size > 65_536) continue;
323
+ const value = JSON.parse(readFileSync(answer, "utf8"));
324
+ if (value && value.id === id && (value.decision === "approve" || value.decision === "deny")) { decision = value.decision; break; }
325
+ } catch {}
326
+ }
327
+ if (decision && !state.done) {
328
+ await client.postSessionIdPermissionsPermissionId({ path: { id: sessionID, permissionID: id },
329
+ body: { response: decision === "approve" ? "once" : "reject" } });
330
+ }
331
+ } catch {} finally {
332
+ removeFile(answer); removeFile(request);
333
+ pendingApprovals.delete(sessionID); relayed.delete(id);
334
+ }
335
+ };
257
336
 
258
337
  const sessionState = sessionID => {
259
338
  let state = sessions.get(sessionID);
@@ -346,10 +425,10 @@ export const PhrenTranscriptPlugin = async () => {
346
425
  // The ask blocks the process until it is answered: here from the
347
426
  // phone, or in the terminal (permission.replied below).
348
427
  const askId = text(input?.id);
349
- if (askId) { asking.add(askId); recordStatus("blocked", text(input?.sessionID)); }
428
+ if (askId) { hookAsks.add(askId); asking.add(askId); recordStatus("blocked", text(input?.sessionID)); }
350
429
  try {
351
430
  const sessionID = text(input?.sessionID), id = text(input?.id);
352
- if (!OPENCODE_SESSION.test(sessionID) || !id) { setStatus(output, "ask"); return; }
431
+ if (!OPENCODE_SESSION.test(sessionID) || !id || servedByHook()) { setStatus(output, "ask"); return; }
353
432
  // A second request for this session belongs in the terminal until
354
433
  // the existing phone request has finished.
355
434
  if (pendingApprovals.has(sessionID)) { setStatus(output, "ask"); return; }
@@ -382,6 +461,7 @@ export const PhrenTranscriptPlugin = async () => {
382
461
  if (pendingSession) pendingApprovals.delete(pendingSession);
383
462
  // Answered from the phone: back to work. Otherwise the terminal asks.
384
463
  if (askId && (decision === "approve" || decision === "deny")) { asking.delete(askId); recordStatus("working", pendingSession); }
464
+ if (askId) hookAsks.delete(askId);
385
465
  }
386
466
  },
387
467
  event: async ({ event }) => {
@@ -394,9 +474,12 @@ export const PhrenTranscriptPlugin = async () => {
394
474
  if (event?.type === "permission.updated" || event?.type === "permission.asked") {
395
475
  const id = permissionId(properties);
396
476
  if (id) { asking.add(id); recordStatus("blocked", text(sessionID)); }
477
+ if (event.type === "permission.asked") void relayAsk(properties).catch(() => {});
397
478
  } else if (event?.type === "permission.replied") {
398
479
  const id = permissionId(properties);
399
480
  if (id) asking.delete(id); else asking.clear();
481
+ const relay = id && relayed.get(id);
482
+ if (relay) relay.done = true;
400
483
  recordStatus("working", text(sessionID));
401
484
  }
402
485
  if (!OPENCODE_SESSION.test(text(sessionID))) return;