@phren/cli 0.3.58 → 0.3.59

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 (75) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-add.d.ts +30 -0
  3. package/dist/bridge/account-add.js +125 -19
  4. package/dist/bridge/account-failover.d.ts +9 -2
  5. package/dist/bridge/account-failover.js +1 -1
  6. package/dist/bridge/account-policy.d.ts +44 -0
  7. package/dist/bridge/account-policy.js +103 -0
  8. package/dist/bridge/account-pools.d.ts +35 -0
  9. package/dist/bridge/account-pools.js +171 -0
  10. package/dist/bridge/account-usage.d.ts +18 -0
  11. package/dist/bridge/account-usage.js +57 -1
  12. package/dist/bridge/agent-hook-callback.d.ts +6 -0
  13. package/dist/bridge/agent-hook-callback.js +10 -2
  14. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  15. package/dist/bridge/agent-hook-stores.js +13 -0
  16. package/dist/bridge/agent-hooks.d.ts +12 -2
  17. package/dist/bridge/agent-hooks.js +41 -4
  18. package/dist/bridge/claude-account-setup.d.ts +16 -0
  19. package/dist/bridge/claude-account-setup.js +46 -2
  20. package/dist/bridge/claude-accounts.d.ts +9 -0
  21. package/dist/bridge/claude-accounts.js +53 -15
  22. package/dist/bridge/claude-credits.d.ts +5 -1
  23. package/dist/bridge/claude-credits.js +37 -29
  24. package/dist/bridge/command.js +12 -3
  25. package/dist/bridge/dispatch-command.js +22 -0
  26. package/dist/bridge/dispatch-returns.d.ts +23 -0
  27. package/dist/bridge/dispatch-returns.js +57 -0
  28. package/dist/bridge/dispatch.d.ts +26 -4
  29. package/dist/bridge/dispatch.js +100 -11
  30. package/dist/bridge/git-host-gitlab.js +2 -1
  31. package/dist/bridge/hand-off-queue.d.ts +71 -0
  32. package/dist/bridge/hand-off-queue.js +38 -0
  33. package/dist/bridge/harnesses.d.ts +12 -0
  34. package/dist/bridge/harnesses.js +20 -4
  35. package/dist/bridge/helper.d.ts +54 -0
  36. package/dist/bridge/helper.js +186 -0
  37. package/dist/bridge/herdr.js +6 -2
  38. package/dist/bridge/hook-fast.d.ts +3 -0
  39. package/dist/bridge/hook-fast.js +10 -2
  40. package/dist/bridge/move-computers.d.ts +15 -1
  41. package/dist/bridge/move-computers.js +123 -26
  42. package/dist/bridge/prompt-deliveries.d.ts +29 -1
  43. package/dist/bridge/prompt-deliveries.js +146 -10
  44. package/dist/bridge/schedule-watch.js +17 -3
  45. package/dist/bridge/server-routes.d.ts +3 -0
  46. package/dist/bridge/server-routes.js +66 -6
  47. package/dist/bridge/server.js +2 -1
  48. package/dist/bridge/session-move.d.ts +59 -1
  49. package/dist/bridge/session-move.js +266 -18
  50. package/dist/bridge/simulators.d.ts +19 -0
  51. package/dist/bridge/simulators.js +93 -13
  52. package/dist/bridge/speech-live.js +132 -22
  53. package/dist/bridge/task-routes.d.ts +16 -16
  54. package/dist/bridge/terminal-herdr.js +6 -1
  55. package/dist/bridge/terminal-tmux.js +9 -5
  56. package/dist/bridge/terminal.d.ts +9 -2
  57. package/dist/bridge/transcript-claude.d.ts +3 -0
  58. package/dist/bridge/transcript-claude.js +175 -29
  59. package/dist/bridge/transcript-preview.d.ts +11 -2
  60. package/dist/bridge/transcript-preview.js +90 -8
  61. package/dist/bridge/turn-records.d.ts +19 -0
  62. package/dist/bridge/turn-records.js +78 -3
  63. package/dist/bridge-hook.mjs +11394 -9961
  64. package/dist/cli-registry.js +2 -2
  65. package/dist/content/citation.d.ts +4 -0
  66. package/dist/content/citation.js +21 -21
  67. package/dist/data/task-contract.d.ts +4 -4
  68. package/dist/governance/policy.js +5 -2
  69. package/dist/index.js +1 -1
  70. package/dist/modules/registry.js +3 -3
  71. package/dist/project-config.d.ts +14 -0
  72. package/dist/project-config.js +40 -1
  73. package/dist/tools/helper.d.ts +3 -0
  74. package/dist/tools/helper.js +44 -0
  75. package/package.json +1 -1
@@ -147,7 +147,7 @@ export const REGISTRY = [
147
147
  summary: "Install Phren Hook and enroll phone or computer connections",
148
148
  subcommands: [
149
149
  { name: "enroll-computer", usage: "phren bridge enroll-computer <name> [--accept <public-key-file>]", summary: "Print or accept a restricted computer dispatch key" },
150
- { name: "accounts", usage: "phren bridge accounts [add <slug> [--label <name>] | label <id> <label> | credit <id> [--amount <usd> [--expires <date>] [--label <name>] | --remove <credit>]]", summary: "List this computer's harnesses and Claude accounts, add a Claude account home, label one, or enter an API credit for a Console login" },
150
+ { name: "accounts", usage: "phren bridge accounts [add <slug> [--label <name>] | label <id> <label> | credit <id> [--amount <usd> [--expires <date>] [--label <name>] | --remove <credit>] | pool <id> <pool>|--clear | role <id> helpers|last-resort|off|--clear | allowed-pools [--project <name>] [<pool>... | --clear]]", summary: "List this computer's harnesses and Claude accounts, add a Claude account home, label one, enter an API credit for a Console login, or set account pools and roles" },
151
151
  { name: "discover", usage: "phren bridge discover", summary: "List computers you already reach over ssh that run Phren Hook and are not linked" },
152
152
  { name: "link", usage: "phren bridge link <ssh-host> [--name <name>] [--as <name>] [--back-address <address>] [--yes]", summary: "Link this computer and an ssh host both ways in one step, after confirming" },
153
153
  { name: "fanouts archive", usage: "phren bridge fanouts archive [--dry-run] [--parent <session-id>] [--older-than <minutes>]", summary: "Archive finished fan-out jobs older than 24 hours, or one parent chat's, or older than N minutes" },
@@ -167,7 +167,7 @@ export const REGISTRY = [
167
167
  name: "dispatch", topic: "core", usage: "phren dispatch <computer|anywhere> <project> --label <label> --prompt <brief> [--harness codex|claude|opencode|copilot] [--model <model>] [--effort <effort>] [--account <id>] [--permission-mode <mode>] [--keep-open]",
168
168
  summary: "Dispatch a worker brief through Phren Hook",
169
169
  subcommands: [{ name: "status", usage: "phren dispatch status", summary: "List local dispatch receipts" },
170
- { name: "returns", usage: "phren dispatch returns", summary: "List unread worker returns (done, needs you, blocked, gone) and mark them read" },
170
+ { name: "returns", usage: "phren dispatch returns [--watch [--json] [--consume]]", summary: "List unread worker returns (done, needs you, blocked, gone) and mark them read; --watch prints them as they land until Ctrl-C, leaving them unread unless --consume" },
171
171
  { name: "sessions", usage: "phren dispatch sessions", summary: "List live agent sessions on this and every enrolled computer" },
172
172
  { name: "usage", usage: "phren dispatch usage [--json]", summary: "Show agent usage on this and every enrolled computer, merged by account" },
173
173
  { name: "report", usage: "phren dispatch report --prs <JSON>", summary: "Record this worker turn's PR evidence for the integrator" },
@@ -60,6 +60,10 @@ export declare function parseCitationComment(line: string): FindingCitation | nu
60
60
  /** Every distinct `symbol:` value in a document's `phren:cite` comments, in order. */
61
61
  export declare function collectSymbolCitations(content: string): string[];
62
62
  export declare function validateFindingCitation(citation: FindingCitation): boolean;
63
+ /** How many days a finding bullet lives before it expires: its type's limit in place of the TTL when it
64
+ * has a type (a decision never expires, a pattern lives a year), else `ttlDays`. The trust filter and
65
+ * maintenance's TTL review both expire findings by this. */
66
+ export declare function findingAgeLimitDays(line: string, ttlDays: number): number;
63
67
  export declare function filterTrustedFindings(content: string, ttlDays: number): string;
64
68
  export declare function filterTrustedFindingsDetailed(content: string, opts: number | TrustFilterOptions): {
65
69
  content: string;
@@ -285,6 +285,19 @@ function parseLearningDateHeading(line) {
285
285
  const match = line.match(/^## (\d{4}-\d{2}-\d{2})$/);
286
286
  return match ? match[1] : null;
287
287
  }
288
+ /** The decay rule of a finding's leading type tag. Only the tag phren writes at the front counts, so a
289
+ * "[decision]" quoted in a finding's text does not keep it forever. */
290
+ function leadingTypeConfig(line) {
291
+ const leadingTag = line.match(/^- (\[\w[\w-]*\])/);
292
+ const findingType = leadingTag ? extractFindingType(leadingTag[1]) : null;
293
+ return findingType ? FINDING_TYPE_DECAY[findingType] : undefined;
294
+ }
295
+ /** How many days a finding bullet lives before it expires: its type's limit in place of the TTL when it
296
+ * has a type (a decision never expires, a pattern lives a year), else `ttlDays`. The trust filter and
297
+ * maintenance's TTL review both expire findings by this. */
298
+ export function findingAgeLimitDays(line, ttlDays) {
299
+ return leadingTypeConfig(line)?.maxAgeDays ?? ttlDays;
300
+ }
288
301
  function isDateStale(headingDate, ttlDays) {
289
302
  const ts = Date.parse(`${headingDate}T00:00:00Z`);
290
303
  if (Number.isNaN(ts))
@@ -402,7 +415,9 @@ export function filterTrustedFindingsDetailed(content, opts) {
402
415
  }
403
416
  }
404
417
  }
405
- const stale = effectiveDate ? isDateStale(effectiveDate, ttlDays) : false;
418
+ // Checked first: a long-lived type would otherwise be cut off at the TTL.
419
+ const typeConfig = leadingTypeConfig(line);
420
+ const stale = effectiveDate ? isDateStale(effectiveDate, findingAgeLimitDays(line, ttlDays)) : false;
406
421
  if (stale) {
407
422
  issues.push({ date: effectiveDate || "unknown", bullet: line, reason: "stale" });
408
423
  if (citation)
@@ -418,26 +433,11 @@ export function filterTrustedFindingsDetailed(content, opts) {
418
433
  confidence = DEFAULT_UNDATED_CONFIDENCE;
419
434
  }
420
435
  // Type-specific decay adjustment
421
- const findingType = extractFindingType(line);
422
- if (findingType) {
423
- const typeConfig = FINDING_TYPE_DECAY[findingType];
424
- if (typeConfig) {
425
- // Override max age for this type
426
- if (effectiveDate && typeConfig.maxAgeDays !== Infinity) {
427
- const age = ageDaysForDate(effectiveDate);
428
- if (age !== null && age > typeConfig.maxAgeDays) {
429
- issues.push({ date: effectiveDate || "unknown", bullet: line, reason: "stale" });
430
- if (citation)
431
- i++;
432
- continue;
433
- }
434
- }
435
- // Apply type-specific decay multiplier
436
- confidence *= typeConfig.decayMultiplier;
437
- // Decisions and anti-patterns get a floor boost (never drop below 0.6)
438
- if (typeConfig.maxAgeDays === Infinity) {
439
- confidence = Math.max(confidence, 0.6);
440
- }
436
+ if (typeConfig) {
437
+ confidence *= typeConfig.decayMultiplier;
438
+ // Decisions get a floor boost (never drop below 0.6)
439
+ if (typeConfig.maxAgeDays === Infinity) {
440
+ confidence = Math.max(confidence, 0.6);
441
441
  }
442
442
  }
443
443
  if (citation && !validateFindingCitation(citation)) {
@@ -29,10 +29,6 @@ export declare function taskIdentity(phrenPath: string, doc: TaskDoc, item: Task
29
29
  /** Derived, never persisted. Missing or unknown metadata blocks autonomous selection. */
30
30
  export declare function taskReadiness(phrenPath: string, doc: TaskDoc, item: TaskItem): TaskReadiness;
31
31
  export declare function taskView(phrenPath: string, doc: TaskDoc, item: TaskItem): {
32
- responsibility: TaskResponsibility;
33
- readiness: "ready" | "waiting-on-human" | "waiting-on-task";
34
- prerequisites: TaskPrerequisite[];
35
- identity: TaskDependency | null;
36
32
  id: string;
37
33
  stableId?: string;
38
34
  identityAmbiguous?: boolean;
@@ -59,6 +55,10 @@ export declare function taskView(phrenPath: string, doc: TaskDoc, item: TaskItem
59
55
  taskContractRecords?: string[];
60
56
  taskContractLines?: string[];
61
57
  opaqueContinuationLines?: string[];
58
+ responsibility: TaskResponsibility;
59
+ readiness: "ready" | "waiting-on-human" | "waiting-on-task";
60
+ prerequisites: TaskPrerequisite[];
61
+ identity: TaskDependency | null;
62
62
  };
63
63
  export declare function validateTaskDependencies(phrenPath: string, doc: TaskDoc, item: TaskItem, refs: TaskDependency[]): string | undefined;
64
64
  export interface TaskFilter {
@@ -9,6 +9,7 @@ import { readProjectConfig } from "../project-config.js";
9
9
  import { getActiveProfileDefaults } from "../profile-store.js";
10
10
  import { runCustomHooks } from "../hooks.js";
11
11
  import { METADATA_REGEX, isCitationLine, isArchiveStart as isArchiveStartMeta, isArchiveEnd as isArchiveEndMeta, stripLifecycleMetadata as stripLifecycleMetadataMeta, } from "../content/metadata.js";
12
+ import { findingAgeLimitDays } from "../content/citation.js";
12
13
  import { VALID_FINDING_SENSITIVITY, VALID_PROACTIVITY_LEVELS, VALID_TASK_MODES, VALID_RISKY_SECTIONS, } from "./policy-constants.js";
13
14
  /** @internal Exported for tests. */
14
15
  export const MAX_QUEUE_ENTRY_LENGTH = 500;
@@ -793,7 +794,6 @@ function lastRetrievalByDocument(phrenPath) {
793
794
  * Entries without a `<!-- created: -->` stamp are skipped defensively.
794
795
  */
795
796
  function collectTtlExpiredEntries(file, project, ttlDays, lastRetrieval) {
796
- const retrievalGraceDays = Math.floor(ttlDays / 2);
797
797
  const now = Date.now();
798
798
  const expired = [];
799
799
  let content;
@@ -814,8 +814,11 @@ function collectTtlExpiredEntries(file, project, ttlDays, lastRetrieval) {
814
814
  const createdMs = Date.parse(`${createdDate}T00:00:00Z`);
815
815
  if (Number.isNaN(createdMs))
816
816
  continue;
817
- if (Math.floor((now - createdMs) / 86_400_000) <= ttlDays)
817
+ // The trust filter's expiry: a typed finding lives as long as its type allows, in place of the TTL.
818
+ const limitDays = findingAgeLimitDays(line, ttlDays);
819
+ if (Math.floor((now - createdMs) / 86_400_000) <= limitDays)
818
820
  continue;
821
+ const retrievalGraceDays = Math.floor(limitDays / 2);
819
822
  // Retrieval is logged at document level, so look up the document key rather than
820
823
  // the bullet.
821
824
  const retrievedAt = lastRetrieval.get(`${project}/${path.basename(file)}:findings`) || 0;
package/dist/index.js CHANGED
@@ -336,7 +336,7 @@ async function main() {
336
336
  import("./tools/notes.js"),
337
337
  import("./tools/summaries.js"),
338
338
  ...(codeAvailable ? [import("./tools/code.js")] : []),
339
- ...(hasModule("conductor") ? [import("./tools/dispatch.js")] : []),
339
+ ...(hasModule("conductor") ? [import("./tools/dispatch.js"), import("./tools/helper.js")] : []),
340
340
  ]);
341
341
  for (const mod of toolModules) {
342
342
  registeringIndexModule = "readsIndex" in mod && mod.readsIndex === true;
@@ -89,7 +89,7 @@ export const BUILTIN_MODULES = [
89
89
  ...routes("POST", [
90
90
  "/v1/push/register", "/v1/push/answer", "/v1/push/target", "/v1/push/presence", "/v1/files", "/v1/files/delete", "/v1/projects/add", "/v1/simulators/action",
91
91
  "/v1/workspaces/launch", "/v1/workspaces/create", "/v1/workspaces/focus", "/v1/workspaces/rename",
92
- "/v1/workspaces/close", "/v1/sessions/rename", "/v1/sessions/move", "/v1/accounts/claude/add", "/v1/sessions/move/abort", "/v1/sessions/move/launch", "/v1/prompt", "/v1/prompt/status", "/v1/model", "/v1/settings", "/v1/agents/permission-mode", "/v1/side-question/dismiss", "/v1/keys", "/v1/secret", "/v1/upload",
92
+ "/v1/workspaces/close", "/v1/sessions/rename", "/v1/sessions/move", "/v1/accounts/claude/add", "/v1/accounts/claude/settings", "/v1/accounts/allowed-pools", "/v1/sessions/move/abort", "/v1/sessions/move/launch", "/v1/prompt", "/v1/prompt/status", "/v1/model", "/v1/settings", "/v1/agents/permission-mode", "/v1/side-question/dismiss", "/v1/keys", "/v1/secret", "/v1/upload",
93
93
  "/v1/approvals/answer", "/v1/questions/answer", "/v1/subagents/resume", "/v1/subagents/archive-finished", "/v1/canary",
94
94
  "/v1/speech", "/v1/sudo/answer", "/v1/jobs/cleanup",
95
95
  ]),
@@ -98,7 +98,7 @@ export const BUILTIN_MODULES = [
98
98
  capabilities: [
99
99
  "hook", "transcript", "progress", "images", "prompt", "stop", "terminal", "shell", "paneTerminal", "paneLayout", "deskPresence", "herdr",
100
100
  "webServers", "webPreview", "activity", "approvals", "questions", "accountUsage", "providers",
101
- "files", "repositoryFiles", "fileResolution", "subagents", "sideQuestions", "approvalPush", "simulators", "simulatorStream", "overviewStream", "speech", "speechTimestamps", "speechTimestampStream", "speechLive", "speechVoices", "speechFormats", "transcribe", "promptOnce", "promptStatus", "deliveryFrames", "resources", "sessionRename", "sudo", "sudoOutcome", "previewDeltas", "quickChat", "agentFolder", "launchPermissionMode", "sessionMove", "moveNewChat", "moveConductor", "moveToComputer", "moveResume", "claudeAccountAdd", "workerRelocation",
101
+ "files", "repositoryFiles", "fileResolution", "subagents", "sideQuestions", "approvalPush", "simulators", "simulatorStream", "simulatorDevices", "simulatorDrag", "overviewStream", "speech", "speechTimestamps", "speechTimestampStream", "speechLive", "speechVoices", "speechFormats", "transcribe", "promptOnce", "promptStatus", "deliveryFrames", "resources", "sessionRename", "sudo", "sudoOutcome", "previewDeltas", "quickChat", "agentFolder", "launchPermissionMode", "sessionMove", "moveNewChat", "moveConductor", "moveToComputer", "moveResume", "claudeAccountAdd", "accountPools", "workerRelocation",
102
102
  ],
103
103
  storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
104
104
  localFiles: ["<bridge>/gitboy-webhooks.json", "<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/askpass", "<bridge>/computer-id", "<bridge>/move-intents/*.json", "<bridge>/canary.json", "<bridge>/canary-daily", "<bridge>/moves/*.json", "<bridge>/move-launches/*.json"],
@@ -130,7 +130,7 @@ export const BUILTIN_MODULES = [
130
130
  },
131
131
  {
132
132
  schemaVersion: 1, name: "conductor", version: VERSION, defaultEnabled: false, requires: ["memory", "hook"],
133
- tools: full(["dispatch", "dispatch_returns", "dispatch_approve", "hand_off", "live_sessions", "account_usage", "authority", "dispatch_report", "owner_inbox", "move_session"]), cliCommands: ["dispatch", "dispatch status", "dispatch returns", "dispatch sessions", "dispatch usage", "dispatch report", "hand-off", "move", "conductor", "conductor grants", "conductor status", "conductor make", "conductor stop", "conductor sets", "conductor integrator", "owner-inbox", "authority", "bridge enroll-computer"], agentHooks: [],
133
+ tools: full(["dispatch", "dispatch_returns", "dispatch_approve", "hand_off", "live_sessions", "account_usage", "authority", "dispatch_report", "owner_inbox", "move_session", "helper"]), cliCommands: ["dispatch", "dispatch status", "dispatch returns", "dispatch sessions", "dispatch usage", "dispatch report", "hand-off", "move", "conductor", "conductor grants", "conductor status", "conductor make", "conductor stop", "conductor sets", "conductor integrator", "owner-inbox", "authority", "bridge enroll-computer"], agentHooks: [],
134
134
  hookRoutes: [...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/conductor/move/status", "/v1/conductor/move/launch", "/v1/conductor/move/operation", "/v1/conductor/move/notification", "/v1/dispatch/brief", "/v1/conductor", "/v1/conductor/grants", "/v1/computers", "/v1/sets", "/v1/authority", "/v1/owner-inbox", "/v1/conductor/integrator"]),
135
135
  ...routes("POST", ["/v1/conductor/call", "/v1/conductor/move/prepare", "/v1/conductor/move/commit", "/v1/conductor/move/operate", "/v1/conductor/move/ack", "/v1/conductor/move/notice", "/v1/dispatch", "/v1/dispatch/workers", "/v1/dispatch/returns", "/v1/dispatch/approve", "/v1/dispatch/report", "/v1/dispatch/close", "/v1/dispatch/close-self", "/v1/owner-inbox", "/v1/conductor/integrator", "/v1/hand-off", "/v1/hand-off/status", "/v1/conductor/grants", "/v1/conductor/make", "/v1/conductor/stop", "/v1/sets/name", "/v1/sets/link", "/v1/authority", "/v1/authority/confirm"]), ...routes("DELETE", ["/v1/conductor/grants", "/v1/authority"])],
136
136
  capabilities: ["dispatch", "moveConductorToComputer", "conductorSets", "setLink", "ownerInbox", "workerReports", "queuedHandOff"], storeFiles: ["global/skills/conductor/**"],
@@ -50,15 +50,29 @@ export interface ProjectConfig {
50
50
  mcpServers?: Record<string, ProjectMcpServerEntry>;
51
51
  config?: ProjectConfigOverrides;
52
52
  access?: ProjectAccessControl;
53
+ /** The account pools whose Claude accounts may do this project's work (bridge/account-pools.ts); none: any. */
54
+ allowedPools?: string[];
55
+ /** The Claude account and model the `helper` MCP tool runs this project's helper tasks with (bridge/helper.ts). */
56
+ helper?: {
57
+ account?: string;
58
+ model?: string;
59
+ };
53
60
  }
54
61
  export declare const PROJECT_HOOK_EVENTS: readonly ["UserPromptSubmit", "Stop", "SessionStart", "PostToolUse"];
55
62
  export type ProjectHookEvent = typeof PROJECT_HOOK_EVENTS[number];
56
63
  type ProjectHookConfig = NonNullable<ProjectConfig["hooks"]>;
57
64
  export declare function parseProjectOwnershipMode(raw: string | undefined | null): ProjectOwnershipMode | undefined;
58
65
  export declare function projectConfigPath(phrenPath: string, project: string): string;
66
+ /** A project's `phren.project.yaml`, in the primary store or the team store that holds it; null when it escapes. */
67
+ export declare function resolveProjectConfigPath(phrenPath: string, project: string): string | null;
59
68
  export declare function clearProjectConfigCache(): void;
60
69
  export declare function readProjectConfig(phrenPath: string, project: string): ProjectConfig;
61
70
  export declare function writeProjectConfig(phrenPath: string, project: string, patch: Partial<ProjectConfig>): ProjectConfig;
71
+ /**
72
+ * Sets one top-level field of a project's config, or removes it when `value` is undefined. Refuses a config file
73
+ * it can't parse rather than replacing it.
74
+ */
75
+ export declare function setProjectConfigField<K extends keyof ProjectConfig>(phrenPath: string, project: string, key: K, value: ProjectConfig[K] | undefined): ProjectConfig;
62
76
  export declare function updateProjectConfigOverrides(phrenPath: string, project: string, updater: (current: ProjectConfigOverrides) => ProjectConfigOverrides): ProjectConfig;
63
77
  /**
64
78
  * Where this project's source lives on this machine. The store syncs between
@@ -27,7 +27,8 @@ export function parseProjectOwnershipMode(raw) {
27
27
  export function projectConfigPath(phrenPath, project) {
28
28
  return path.join(phrenPath, project, "phren.project.yaml");
29
29
  }
30
- function resolveProjectConfigPath(phrenPath, project) {
30
+ /** A project's `phren.project.yaml`, in the primary store or the team store that holds it; null when it escapes. */
31
+ export function resolveProjectConfigPath(phrenPath, project) {
31
32
  return storeAwareProjectPath(phrenPath, project, "phren.project.yaml");
32
33
  }
33
34
  function writeProjectConfigFile(configPath, next) {
@@ -91,6 +92,44 @@ export function writeProjectConfig(phrenPath, project, patch) {
91
92
  return next;
92
93
  });
93
94
  }
95
+ /**
96
+ * Sets one top-level field of a project's config, or removes it when `value` is undefined. Refuses a config file
97
+ * it can't parse rather than replacing it.
98
+ */
99
+ export function setProjectConfigField(phrenPath, project, key, value) {
100
+ const configPath = resolveProjectConfigPath(phrenPath, project);
101
+ if (!configPath) {
102
+ throw new Error(`Project config path escapes phren store`);
103
+ }
104
+ return withFileLock(configPath, () => {
105
+ let text;
106
+ try {
107
+ text = fs.readFileSync(configPath, "utf8");
108
+ }
109
+ catch (err) {
110
+ if (err.code !== "ENOENT")
111
+ throw err;
112
+ }
113
+ let parsed = undefined;
114
+ if (text !== undefined && text.trim()) {
115
+ try {
116
+ parsed = loadYamlDocument(text, (raw) => yaml.load(raw, { schema: yaml.CORE_SCHEMA }));
117
+ }
118
+ catch (err) {
119
+ throw new Error(`${configPath} can't be read (${errorMessage(err)}); fix it first.`);
120
+ }
121
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
122
+ throw new Error(`${configPath} is not a mapping; fix it first.`);
123
+ }
124
+ const next = { ...parsed };
125
+ if (value === undefined)
126
+ delete next[key];
127
+ else
128
+ next[key] = value;
129
+ writeProjectConfigFile(configPath, next);
130
+ return next;
131
+ });
132
+ }
94
133
  export function updateProjectConfigOverrides(phrenPath, project, updater) {
95
134
  const configPath = resolveProjectConfigPath(phrenPath, project);
96
135
  if (!configPath) {
@@ -0,0 +1,3 @@
1
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { type McpContext } from "./types.js";
3
+ export declare function register(server: McpServer, ctx: McpContext): void;
@@ -0,0 +1,44 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import { z } from "zod";
4
+ import { detectProject } from "../shared/index.js";
5
+ import { HELPER_TIMEOUT_DEFAULT_S, HELPER_TIMEOUT_MAX_S, helperFor, runHelper } from "../bridge/helper.js";
6
+ import { mcpResponse, resolveStoreForProject } from "./types.js";
7
+ export function register(server, ctx) {
8
+ server.registerTool("helper", {
9
+ title: "◆ phren · helper",
10
+ description: `Run one small, self-contained task as a headless Claude Code run (claude -p) under the project's helper account and model (phren.project.yaml helper: { account, model }, model haiku by default), in your folder (a project checkout or worktree), and return its reply. Use it for narrow work you can describe fully in one prompt (summarize a file, draft a test, look something up); the helper sees no conversation, only the prompt and the folder. It bills the helper account, not yours: Claude Code's own subagents always run under your login. Read-only unless allowEdits (Bash and the edit tools are refused); no MCP servers. Stops after timeoutSeconds (default ${HELPER_TIMEOUT_DEFAULT_S}, at most ${HELPER_TIMEOUT_MAX_S}). Refused when the project has no helper account, the account's role is off, or its pool is not allowed for the project or this computer.`,
11
+ inputSchema: {
12
+ prompt: z.string().min(1).max(100_000).describe("The whole task: what to do, which files, what to return."),
13
+ project: z.string().optional().describe("Expected project; it must be the project cwd belongs to, whose helper setting applies."),
14
+ cwd: z.string().optional().describe("Absolute folder the helper runs in (your worktree); default: this server's folder."),
15
+ timeoutSeconds: z.number().int().min(1).max(HELPER_TIMEOUT_MAX_S).optional(),
16
+ allowEdits: z.boolean().optional().describe("Let the helper edit files in cwd (acceptEdits). Default false."),
17
+ },
18
+ }, async (input, extra) => {
19
+ try {
20
+ if (input.cwd !== undefined && !path.isAbsolute(input.cwd))
21
+ throw new Error("cwd is an absolute path.");
22
+ const cwd = path.resolve(input.cwd ?? process.cwd());
23
+ if (!fs.statSync(cwd, { throwIfNoEntry: false })?.isDirectory())
24
+ throw new Error(`${cwd} is not a folder.`);
25
+ // The folder decides whose rules apply: a helper only runs in a project's checkout or worktree, under that
26
+ // project's own helper and pools, so naming another project can't carry its account into this folder.
27
+ const owner = detectProject(ctx.phrenPath, cwd, ctx.profile);
28
+ if (!owner)
29
+ throw new Error(`${cwd} is not in a project's folder; a helper runs only in a project checkout or worktree.`);
30
+ if (input.project !== undefined && input.project !== owner)
31
+ throw new Error(`${cwd} belongs to project ${owner}, not ${input.project}.`);
32
+ const { phrenPath, project } = resolveStoreForProject(ctx, owner, "read");
33
+ const choice = helperFor(phrenPath, project);
34
+ const result = await runHelper(choice, { prompt: input.prompt, cwd, timeoutSeconds: input.timeoutSeconds, allowEdits: input.allowEdits, signal: extra?.signal });
35
+ const spent = result.costUSD !== undefined ? `, $${result.costUSD.toFixed(4)}` : "";
36
+ // The reply is in data.output; a failure's reason is also the error.
37
+ return mcpResponse({ ok: result.ok, data: result, ...(result.ok ? {} : { error: result.output.slice(0, 2000) }),
38
+ message: `${result.ok ? "Helper replied" : "Helper failed"} (${result.account}, ${result.model}, ${Math.round(result.durationMs / 1000)}s${spent}).` });
39
+ }
40
+ catch (error) {
41
+ return mcpResponse({ ok: false, error: error instanceof Error ? error.message : "The helper could not run." });
42
+ }
43
+ });
44
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.58",
3
+ "version": "0.3.59",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {