@phren/cli 0.3.70 → 0.3.72

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 (108) hide show
  1. package/dist/bridge/browser-env.d.ts +5 -0
  2. package/dist/bridge/browser-env.js +86 -0
  3. package/dist/bridge/browser-protocol.d.ts +120 -0
  4. package/dist/bridge/browser-protocol.js +70 -0
  5. package/dist/bridge/browser-recordings.d.ts +63 -0
  6. package/dist/bridge/browser-recordings.js +148 -0
  7. package/dist/bridge/browser-registry.d.ts +64 -0
  8. package/dist/bridge/browser-registry.js +262 -0
  9. package/dist/bridge/browser-routes.d.ts +4 -0
  10. package/dist/bridge/browser-routes.js +39 -0
  11. package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
  12. package/dist/bridge/browser-socket.d.ts +2 -0
  13. package/dist/bridge/browser-socket.js +10 -0
  14. package/dist/bridge/browser-stream.d.ts +3 -0
  15. package/dist/bridge/browser-stream.js +129 -0
  16. package/dist/bridge/claude-question-dialog.js +32 -7
  17. package/dist/bridge/dispatch.d.ts +10 -0
  18. package/dist/bridge/dispatch.js +3 -1
  19. package/dist/bridge/dream-schedule.d.ts +133 -0
  20. package/dist/bridge/dream-schedule.js +322 -0
  21. package/dist/bridge/herdr.js +15 -6
  22. package/dist/bridge/install.js +4 -0
  23. package/dist/bridge/launch-brief.d.ts +11 -0
  24. package/dist/bridge/launch-brief.js +22 -0
  25. package/dist/bridge/pane-status.js +1 -1
  26. package/dist/bridge/server-routes.d.ts +3 -0
  27. package/dist/bridge/server-routes.js +15 -15
  28. package/dist/bridge/server-stream.d.ts +4 -0
  29. package/dist/bridge/server-stream.js +24 -5
  30. package/dist/bridge/server.js +23 -3
  31. package/dist/bridge/session-move.d.ts +10 -4
  32. package/dist/bridge/session-move.js +65 -34
  33. package/dist/bridge/simulator-stream.d.ts +2 -0
  34. package/dist/bridge/simulator-stream.js +2 -0
  35. package/dist/bridge/tab-activity.d.ts +2 -0
  36. package/dist/bridge/tab-activity.js +15 -2
  37. package/dist/bridge/task-routes.d.ts +20 -16
  38. package/dist/bridge/task-routes.js +1 -1
  39. package/dist/bridge/terminal-herdr.js +2 -1
  40. package/dist/bridge/terminal-tmux.js +2 -1
  41. package/dist/bridge/worker-reports.js +15 -3
  42. package/dist/bridge-hook.mjs +36819 -35219
  43. package/dist/capabilities/mcp.js +1 -1
  44. package/dist/cli/config-dreaming.d.ts +7 -0
  45. package/dist/cli/config-dreaming.js +72 -0
  46. package/dist/cli/config.js +6 -0
  47. package/dist/cli/dream.d.ts +59 -0
  48. package/dist/cli/dream.js +315 -0
  49. package/dist/cli/namespaces-tasks.js +14 -0
  50. package/dist/cli-registry.js +24 -1
  51. package/dist/config/dreaming.d.ts +82 -0
  52. package/dist/config/dreaming.js +195 -0
  53. package/dist/config/resolve.js +11 -0
  54. package/dist/config/schema.d.ts +4 -4
  55. package/dist/config/schema.js +157 -1
  56. package/dist/content/citation-freshness.js +6 -0
  57. package/dist/content/learning.d.ts +1 -0
  58. package/dist/content/learning.js +2 -0
  59. package/dist/data/access.d.ts +1 -1
  60. package/dist/data/access.js +3 -1
  61. package/dist/data/task-contract.d.ts +5 -4
  62. package/dist/data/tasks.d.ts +5 -0
  63. package/dist/data/tasks.js +28 -2
  64. package/dist/dream/apply.d.ts +69 -0
  65. package/dist/dream/apply.js +372 -0
  66. package/dist/dream/budget.d.ts +78 -0
  67. package/dist/dream/budget.js +180 -0
  68. package/dist/dream/collect.d.ts +86 -0
  69. package/dist/dream/collect.js +449 -0
  70. package/dist/dream/eval/dream-adapter.d.ts +16 -0
  71. package/dist/dream/eval/dream-adapter.js +21 -0
  72. package/dist/dream/eval/fixture.d.ts +53 -0
  73. package/dist/dream/eval/fixture.js +172 -0
  74. package/dist/dream/eval/index.d.ts +40 -0
  75. package/dist/dream/eval/index.js +78 -0
  76. package/dist/dream/eval/score.d.ts +34 -0
  77. package/dist/dream/eval/score.js +99 -0
  78. package/dist/dream/eval/scripted-model.d.ts +19 -0
  79. package/dist/dream/eval/scripted-model.js +70 -0
  80. package/dist/dream/pages.d.ts +68 -0
  81. package/dist/dream/pages.js +220 -0
  82. package/dist/dream/privacy.d.ts +3 -0
  83. package/dist/dream/privacy.js +18 -0
  84. package/dist/dream/prompt.d.ts +13 -0
  85. package/dist/dream/prompt.js +84 -0
  86. package/dist/dream/run.d.ts +98 -0
  87. package/dist/dream/run.js +317 -0
  88. package/dist/dream/types.d.ts +74 -0
  89. package/dist/dream/types.js +4 -0
  90. package/dist/finding/lifecycle.d.ts +2 -2
  91. package/dist/finding/lifecycle.js +5 -2
  92. package/dist/finding/versions.d.ts +4 -0
  93. package/dist/finding/versions.js +28 -0
  94. package/dist/index.js +1 -0
  95. package/dist/modules/registry.js +9 -7
  96. package/dist/project-config.d.ts +3 -0
  97. package/dist/task/merge-links.d.ts +38 -0
  98. package/dist/task/merge-links.js +45 -0
  99. package/dist/task/reconcile.d.ts +39 -0
  100. package/dist/task/reconcile.js +201 -0
  101. package/dist/task/report-links.d.ts +10 -0
  102. package/dist/task/report-links.js +47 -0
  103. package/dist/tools/config.js +46 -4
  104. package/dist/tools/dispatch.js +2 -1
  105. package/dist/tools/dream.d.ts +3 -0
  106. package/dist/tools/dream.js +123 -0
  107. package/dist/tools/tasks.js +4 -1
  108. package/package.json +1 -1
@@ -27,16 +27,41 @@ const GUTTER = /^(\s*)│(?: |$)/;
27
27
  * with its "Esc to cancel" footer or the review's Submit/Cancel rows. */
28
28
  export function claudeQuestionDialog(text) {
29
29
  const lines = joinDialogFooters(text.split(/\r?\n/));
30
- let bar = -1;
31
- for (let index = lines.length - 1; index >= 0; index--)
32
- if (TAB_BAR.test(lines[index]) && /[☐☒]/.test(lines[index])) {
33
- bar = index;
34
- break;
30
+ let bar = -1, barEnd = -1, tabBar = "";
31
+ // A narrow pane soft-wraps the tab bar. Reading only its last physical
32
+ // row either loses tabs (a false set mismatch) or misses the dialog when
33
+ // that row contains only Submit. Keep the complete last bar and start
34
+ // the body after all of its physical rows.
35
+ for (let end = lines.length - 1; end >= 0 && bar < 0; end--) {
36
+ let candidates = [];
37
+ for (let start = end; start >= 0; start--) {
38
+ const line = lines[start];
39
+ if (!line.trim() || /^─+$/.test(line.trim()))
40
+ break;
41
+ // Terminal cell counts cannot reliably recover a wrap boundary (emoji
42
+ // sequences vary by terminal), and a capture drops the space a row
43
+ // wrapped after. Keep both joins of each wrap, no space first, while
44
+ // they still end in the Submit suffix; a complete bar wins over one
45
+ // that only has the suffix.
46
+ const joins = candidates.length ? candidates.flatMap(value => [line + value, line + " " + value]) : [line];
47
+ const viable = joins.filter(value => TAB_BAR.test(value) || /✔\s+Submit\s*(?:→\s*)?$/.test(value));
48
+ candidates = (viable.length ? viable : joins.slice(0, 1)).slice(0, 16);
49
+ const complete = candidates.find(value => TAB_BAR.test(value) && /[☐☒]/.test(value));
50
+ if (complete) {
51
+ bar = start;
52
+ barEnd = end;
53
+ tabBar = complete;
54
+ }
55
+ // The leading arrow is the start of this bar. A checkbox in earlier
56
+ // output belongs to that output, even when there is no blank row.
57
+ if (/^\s*←/.test(line))
58
+ break;
35
59
  }
60
+ }
36
61
  if (bar < 0)
37
62
  return undefined;
38
- const tabs = [...lines[bar].matchAll(/[☐☒]\s+([^☐☒✔→]+?)(?=\s{2,}|\s*[☐☒✔→]|\s*$)/g)].map(match => match[1].trim());
39
- const body = lines.slice(bar + 1);
63
+ const tabs = [...tabBar.matchAll(/[☐☒]\s+([^☐☒✔→]+?)(?=\s{2,}|\s*[☐☒✔→]|\s*$)/g)].map(match => match[1].trim());
64
+ const body = lines.slice(barEnd + 1);
40
65
  const tail = body.map(line => line.trim()).filter(line => line && !/^─+$/.test(line));
41
66
  if (!/^(?:Enter to .*Esc to cancel|2\. Cancel)$/.test(tail.at(-1) ?? ""))
42
67
  return undefined;
@@ -12,6 +12,11 @@ export declare const PEER_COPILOT_REASON = "Copilot cannot continue on another c
12
12
  export declare const DISPATCH_HARNESSES: readonly ["codex", "claude", "opencode", "copilot"];
13
13
  export declare const dispatchSchema: z.ZodObject<{
14
14
  computer: z.ZodUnion<readonly [z.ZodLiteral<"anywhere">, z.ZodString]>;
15
+ task: z.ZodOptional<z.ZodObject<{
16
+ storeId: z.ZodString;
17
+ project: z.ZodString;
18
+ stableId: z.ZodString;
19
+ }, z.core.$strict>>;
15
20
  project: z.ZodString;
16
21
  harness: z.ZodEnum<{
17
22
  claude: "claude";
@@ -121,6 +126,11 @@ export declare const workerStates: readonly ["working", "done", "needs-you", "fa
121
126
  export type WorkerState = typeof workerStates[number];
122
127
  declare const receiptSchema: z.ZodObject<{
123
128
  computer: z.ZodUnion<readonly [z.ZodLiteral<"anywhere">, z.ZodString]>;
129
+ task: z.ZodOptional<z.ZodObject<{
130
+ storeId: z.ZodString;
131
+ project: z.ZodString;
132
+ stableId: z.ZodString;
133
+ }, z.core.$strict>>;
124
134
  project: z.ZodString;
125
135
  harness: z.ZodEnum<{
126
136
  claude: "claude";
@@ -1,3 +1,4 @@
1
+ import { mergeTaskIdentitySchema } from "../task/merge-links.js";
1
2
  import { redactPeerHandoff } from "./peer-handoff.js";
2
3
  import { integratorSchema, prsSchema } from "./return-contract.js";
3
4
  import { randomUUID } from "node:crypto";
@@ -32,6 +33,7 @@ export const PEER_COPILOT_REASON = "Copilot cannot continue on another computer:
32
33
  export const DISPATCH_HARNESSES = ["codex", "claude", "opencode", "copilot"];
33
34
  export const dispatchSchema = z.object({
34
35
  computer: z.union([z.literal("anywhere"), computerName]).describe("Enrolled computer name, or anywhere for the least busy connected computer."),
36
+ task: mergeTaskIdentitySchema.optional().describe("Private task identity for merge reconciliation. Never put it in commits or GitHub."),
35
37
  project: projectName.describe("Project slug registered on the receiving computer."),
36
38
  harness: z.enum(DISPATCH_HARNESSES).describe("Agent harness on the receiving computer."),
37
39
  model: text(200).optional().describe("Explicit model, otherwise the remote harness default."),
@@ -745,7 +747,7 @@ export class DispatchService {
745
747
  try {
746
748
  // The brief goes with the launch: a Hook that can start the harness
747
749
  // with it says so, and any other types it below.
748
- const launched = await peer.request(`/v1/workspaces/launch?server=${encodeURIComponent(peer.server)}`, { project: data.project, kind: data.harness, model: data.model, ...(data.effort ? { effort: data.effort } : {}), ...(data.account ?? policyChoice?.account ? { account: data.account ?? policyChoice.account } : {}), ...(data.permissionMode ? { permissionMode: data.permissionMode } : {}), label: peer.local ? data.label : redactPeerHandoff(data.label), brief: { id: receipt.id, text: prompt } });
750
+ const launched = await peer.request(`/v1/workspaces/launch?server=${encodeURIComponent(peer.server)}`, { project: data.project, kind: data.harness, model: data.model, ...(data.effort ? { effort: data.effort } : {}), ...(data.account ?? policyChoice?.account ? { account: data.account ?? policyChoice.account } : {}), ...(data.permissionMode ? { permissionMode: data.permissionMode } : {}), label: peer.local ? data.label : redactPeerHandoff(data.label), brief: { id: receipt.id, text: prompt, ...(data.task ? { task: data.task } : {}) } });
749
751
  // Placed: the brief is confirmed outside the lock.
750
752
  placed = peer.name;
751
753
  this.placing.set(placed, this.inFlight(placed) + 1);
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Dreaming on the Hook: a ticker that starts a dream (docs/dreaming.md) for
3
+ * each project whose `dreaming` config makes one due, one project at a time.
4
+ *
5
+ * Why not `schedules.ts`: a schedule there is a prompt typed into a new agent
6
+ * pane on a fixed timing, recorded in `schedules.yaml` and launched through
7
+ * Herdr. A dream is no pane and no prompt: it is a headless pass whose timing
8
+ * depends on per-project config, on whether anyone is working in the project
9
+ * and on its own last-run marker. So this is a small module of its own that
10
+ * borrows schedules.ts's shape (an injected clock, a non-reentrant `tick`, a
11
+ * timer in server.ts) rather than a schedule entry.
12
+ *
13
+ * Each dream runs as `phren dream run --project <p> --scheduled` in a child
14
+ * process at low CPU priority, so the dream engine and its helper (`claude -p`,
15
+ * which inherits the niceness) never block or crash the Hook, and the CLI
16
+ * records `dreams/last-run.json` the same way for manual and scheduled runs.
17
+ */
18
+ import { type DreamingConfig } from "../config/dreaming.js";
19
+ import type { AgentHooks } from "./agent-hooks.js";
20
+ import type { CodexQuestions } from "./questions.js";
21
+ export declare const DREAM_TICK_MS: number;
22
+ /** After starting a dream for a project, the ticker leaves it alone this long, whatever the outcome. */
23
+ export declare const DREAM_RETRY_MS: number;
24
+ /** A scheduled dream that runs longer than this is stopped. */
25
+ export declare const DREAM_CHILD_TIMEOUT_MS: number;
26
+ /** One live agent session as the Hook sees it. */
27
+ export interface DreamSession {
28
+ project?: string;
29
+ status?: string;
30
+ }
31
+ export { readLastRun, type DreamLastRun } from "../dream/apply.js";
32
+ import { type DreamLastRun } from "../dream/apply.js";
33
+ export declare function dreamsDir(phrenPath: string, project: string): string | null;
34
+ /**
35
+ * Per-status counts from a dream result, read loosely so the engine's result
36
+ * shape can grow: `counts` if it reports one, else its per-change `outcomes`
37
+ * (or `changes`) tallied by `status`/`outcome`.
38
+ */
39
+ export declare function dreamOutcomeCounts(result: unknown): Record<string, number> | undefined;
40
+ /** The latest local start of the window at or before `now`. */
41
+ export declare function windowStartAtOrBefore(config: DreamingConfig, now: Date): Date;
42
+ /** The first local start of the window after `now`. */
43
+ export declare function nextWindowStart(config: DreamingConfig, now: Date): Date;
44
+ export interface DreamEligibilityInput {
45
+ config: DreamingConfig;
46
+ now: Date;
47
+ lastRunAt?: Date;
48
+ /** Live sessions in this project only. Undefined when the caller cannot see sessions (CLI status). */
49
+ sessions?: DreamSession[];
50
+ /** For the idle cadence: when the Hook last saw a live session in this project. */
51
+ lastSeenAt?: Date;
52
+ }
53
+ export interface DreamEligibility {
54
+ eligible: boolean;
55
+ /** Plain-English why (not). */
56
+ reason: string;
57
+ /** When a dream could next start, when that can be known. */
58
+ nextEligibleAt?: Date;
59
+ }
60
+ /** Whether a scheduled dream may start for one project now. Pure; tested directly. */
61
+ export declare function dreamEligibility(input: DreamEligibilityInput): DreamEligibility;
62
+ /** What `phren dream status` and `dream_status` report for one project. */
63
+ export interface DreamStatus {
64
+ project: string;
65
+ enabled: boolean;
66
+ mode: DreamingConfig["mode"];
67
+ cadence: DreamingConfig["cadence"];
68
+ window: string;
69
+ lastRun?: DreamLastRun;
70
+ /** Null when no scheduled dream will start (off or manual). */
71
+ nextEligibleAt: string | null;
72
+ reason: string;
73
+ lastOutcome?: Record<string, number>;
74
+ /** The helper account and model a dream would use, or why there is none. */
75
+ runsOn?: string;
76
+ pendingProposals: number;
77
+ }
78
+ /**
79
+ * The status of one project from config and the last-run marker. Live sessions
80
+ * are not consulted (that needs the Hook), so "eligible now" means as far as
81
+ * timing goes; the Hook still waits for working agents.
82
+ */
83
+ export declare function dreamStatus(phrenPath: string, project: string, now?: Date): DreamStatus;
84
+ export interface DreamSchedulerDeps {
85
+ now: () => Date;
86
+ /** Project names in the store the Hook serves. */
87
+ projects: () => string[];
88
+ config: (project: string) => DreamingConfig;
89
+ lastRun: (project: string) => DreamLastRun | undefined;
90
+ /** This computer's live agent sessions with their project. Rejects when unknown; the tick is then skipped. */
91
+ liveSessions: () => Promise<DreamSession[]>;
92
+ /** Start one dream and resolve when it ends. */
93
+ run: (project: string) => Promise<void>;
94
+ }
95
+ export declare class DreamScheduler {
96
+ private readonly deps;
97
+ private ticking;
98
+ /** When a live session was last seen in each project (for the idle cadence). */
99
+ private readonly lastSeen;
100
+ /** When the ticker last started a dream for each project, so a failing run is not retried every tick. */
101
+ private readonly lastAttempt;
102
+ constructor(deps: DreamSchedulerDeps);
103
+ private observe;
104
+ private decide;
105
+ /** Projects whose dream would start now, given these sessions. Exposed for tests and diagnostics. */
106
+ due(sessions: DreamSession[], now?: Date): string[];
107
+ tick(): Promise<string[]>;
108
+ }
109
+ /**
110
+ * The agent panes of one terminal snapshot (the Hook's `{ tabs, panes }`
111
+ * shape) as dream sessions: the project from the pane's folder, the status
112
+ * from the pane or, when the terminal reports none per pane, its tab.
113
+ */
114
+ export declare function dreamSessionsFromSnapshot(snapshot: unknown, projectOf: (cwd: string | undefined) => string | undefined): DreamSession[];
115
+ /**
116
+ * A pane folder's project: the registered project whose checkout (or a
117
+ * worktree of it) holds the folder, else the folder's name, so a session is
118
+ * never missed when deciding that nobody is working.
119
+ */
120
+ export declare function dreamProjectOf(store: string, profile?: string): (cwd: string | undefined) => string | undefined;
121
+ /** Projects in the store the Hook serves, skipping `global`. */
122
+ export declare function dreamStoreProjects(store: string, profile?: string): string[];
123
+ /** Off with `PHREN_DREAMING=off`; otherwise the ticker runs and each project's config decides. */
124
+ export declare function dreamTickerEnabled(env?: NodeJS.ProcessEnv): boolean;
125
+ /** The command that runs a dream; `PHREN_DREAM_COMMAND` points it at a specific phren binary. */
126
+ export declare function dreamCommand(project: string, env?: NodeJS.ProcessEnv): {
127
+ command: string;
128
+ args: string[];
129
+ };
130
+ /** Run one scheduled dream as a low-priority child process of the Hook. */
131
+ export declare function runDreamChild(store: string, project: string, env?: NodeJS.ProcessEnv): Promise<void>;
132
+ /** Resolve the same evidence used by the live overview before deciding a project is idle. */
133
+ export declare function effectiveDreamSessions(server: string, snapshot: unknown, projectOf: (cwd: string | undefined) => string | undefined, hooks?: AgentHooks, questions?: CodexQuestions): Promise<DreamSession[]>;
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Dreaming on the Hook: a ticker that starts a dream (docs/dreaming.md) for
3
+ * each project whose `dreaming` config makes one due, one project at a time.
4
+ *
5
+ * Why not `schedules.ts`: a schedule there is a prompt typed into a new agent
6
+ * pane on a fixed timing, recorded in `schedules.yaml` and launched through
7
+ * Herdr. A dream is no pane and no prompt: it is a headless pass whose timing
8
+ * depends on per-project config, on whether anyone is working in the project
9
+ * and on its own last-run marker. So this is a small module of its own that
10
+ * borrows schedules.ts's shape (an injected clock, a non-reentrant `tick`, a
11
+ * timer in server.ts) rather than a schedule entry.
12
+ *
13
+ * Each dream runs as `phren dream run --project <p> --scheduled` in a child
14
+ * process at low CPU priority, so the dream engine and its helper (`claude -p`,
15
+ * which inherits the niceness) never block or crash the Hook, and the CLI
16
+ * records `dreams/last-run.json` the same way for manual and scheduled runs.
17
+ */
18
+ import { spawn } from "node:child_process";
19
+ import * as os from "node:os";
20
+ import * as path from "node:path";
21
+ import { DEFAULT_DREAMING_CONFIG, getDreamingConfig, insideDreamWindow, parseDreamWindow } from "../config/dreaming.js";
22
+ import { storeAwareProjectPath } from "../store-routing.js";
23
+ import { getProjectDirs } from "../phren-paths.js";
24
+ import { detectProject } from "../shared/index.js";
25
+ import { effectivePaneEvidence } from "./session-evidence.js";
26
+ import { resolveEffectiveStatus } from "./session-activity.js";
27
+ import { paneChatState } from "./herdr.js";
28
+ import { paneProject } from "./approval-summary.js";
29
+ export const DREAM_TICK_MS = 10 * 60_000;
30
+ /** After starting a dream for a project, the ticker leaves it alone this long, whatever the outcome. */
31
+ export const DREAM_RETRY_MS = 60 * 60_000;
32
+ /** A scheduled dream that runs longer than this is stopped. */
33
+ export const DREAM_CHILD_TIMEOUT_MS = 45 * 60_000;
34
+ const DAY_MS = 24 * 60 * 60_000;
35
+ /** Only confirmed resting states permit a dream beside an open session. */
36
+ const SAFE_STATUSES = new Set(["idle", "done"]);
37
+ export { readLastRun } from "../dream/apply.js";
38
+ import { pendingDreamProposals, readLastRun } from "../dream/apply.js";
39
+ export function dreamsDir(phrenPath, project) {
40
+ return storeAwareProjectPath(phrenPath, project, "dreams");
41
+ }
42
+ /**
43
+ * Per-status counts from a dream result, read loosely so the engine's result
44
+ * shape can grow: `counts` if it reports one, else its per-change `outcomes`
45
+ * (or `changes`) tallied by `status`/`outcome`.
46
+ */
47
+ export function dreamOutcomeCounts(result) {
48
+ if (!result || typeof result !== "object")
49
+ return undefined;
50
+ const record = result;
51
+ if (record.counts && typeof record.counts === "object" && !Array.isArray(record.counts)) {
52
+ const counts = Object.fromEntries(Object.entries(record.counts).filter(([, n]) => typeof n === "number"));
53
+ if (Object.keys(counts).length)
54
+ return counts;
55
+ }
56
+ const list = [record.outcomes, record.changes].find(Array.isArray);
57
+ if (!list)
58
+ return undefined;
59
+ const counts = {};
60
+ for (const item of list) {
61
+ const row = item && typeof item === "object" ? item : {};
62
+ const key = typeof row.status === "string" ? row.status : typeof row.outcome === "string" ? row.outcome : "total";
63
+ counts[key] = (counts[key] ?? 0) + 1;
64
+ }
65
+ return counts;
66
+ }
67
+ // ── Eligibility ──────────────────────────────────────────────────────────────
68
+ function windowOf(config) {
69
+ return parseDreamWindow(config.window) ?? parseDreamWindow(DEFAULT_DREAMING_CONFIG.window);
70
+ }
71
+ function atMinute(day, minute) {
72
+ const date = new Date(day);
73
+ date.setHours(Math.floor(minute / 60), minute % 60, 0, 0);
74
+ return date;
75
+ }
76
+ /** The latest local start of the window at or before `now`. */
77
+ export function windowStartAtOrBefore(config, now) {
78
+ const start = atMinute(now, windowOf(config).start);
79
+ if (start.getTime() > now.getTime())
80
+ start.setDate(start.getDate() - 1);
81
+ return start;
82
+ }
83
+ /** The first local start of the window after `now`. */
84
+ export function nextWindowStart(config, now) {
85
+ const start = atMinute(now, windowOf(config).start);
86
+ if (start.getTime() <= now.getTime())
87
+ start.setDate(start.getDate() + 1);
88
+ return start;
89
+ }
90
+ /** Whether a scheduled dream may start for one project now. Pure; tested directly. */
91
+ export function dreamEligibility(input) {
92
+ const { config, now, lastRunAt, sessions, lastSeenAt } = input;
93
+ if (!config.enabled)
94
+ return { eligible: false, reason: "Dreaming is off for this project." };
95
+ if (config.cadence === "manual")
96
+ return { eligible: false, reason: "Cadence is manual: dreams run only with `phren dream run`." };
97
+ let timing;
98
+ if (config.cadence === "idle") {
99
+ const idleMs = config.idleMinutes * 60_000;
100
+ if (sessions && sessions.length) {
101
+ timing = { eligible: false, reason: `A live agent session is open in the project; waits until ${config.idleMinutes} minutes after it closes.` };
102
+ }
103
+ else if (!lastSeenAt) {
104
+ timing = { eligible: false, reason: "No session seen in the project since the Hook started; an idle dream follows work." };
105
+ }
106
+ else if (lastRunAt && lastRunAt.getTime() >= lastSeenAt.getTime()) {
107
+ timing = { eligible: false, reason: "Nothing new since the last dream; waits for the next session to end." };
108
+ }
109
+ else if (now.getTime() - lastSeenAt.getTime() < idleMs) {
110
+ timing = { eligible: false, reason: `Waiting for ${config.idleMinutes} idle minutes.`, nextEligibleAt: new Date(lastSeenAt.getTime() + idleMs) };
111
+ }
112
+ else {
113
+ timing = { eligible: true, reason: `No live session for ${config.idleMinutes}+ minutes.` };
114
+ }
115
+ }
116
+ else {
117
+ const inside = insideDreamWindow(config.window, now);
118
+ const currentStart = windowStartAtOrBefore(config, now);
119
+ // A run counts for this window when it finished after the window opened (nightly), or less
120
+ // than six days before it (weekly: once in any seven consecutive windows).
121
+ const cutoff = config.cadence === "weekly" ? new Date(currentStart.getTime() - 6 * DAY_MS) : currentStart;
122
+ const ranThisPeriod = lastRunAt !== undefined && lastRunAt.getTime() >= cutoff.getTime();
123
+ if (ranThisPeriod) {
124
+ const next = config.cadence === "weekly"
125
+ ? new Date(windowStartAtOrBefore(config, lastRunAt).getTime() + 7 * DAY_MS)
126
+ : nextWindowStart(config, now);
127
+ timing = { eligible: false, reason: `Already dreamed ${config.cadence === "weekly" ? "this week" : "in this window"}.`,
128
+ nextEligibleAt: next.getTime() > now.getTime() ? next : nextWindowStart(config, now) };
129
+ }
130
+ else if (!inside) {
131
+ timing = { eligible: false, reason: `Outside the ${config.window} window.`, nextEligibleAt: nextWindowStart(config, now) };
132
+ }
133
+ else {
134
+ timing = { eligible: true, reason: `Inside the ${config.window} window.` };
135
+ }
136
+ }
137
+ if (!timing.eligible)
138
+ return timing;
139
+ if (sessions?.some((session) => !SAFE_STATUSES.has(String(session.status)))) {
140
+ return { eligible: false, reason: "An agent is working in the project; a dream never runs beside one." };
141
+ }
142
+ return timing.eligible && !timing.nextEligibleAt ? { ...timing, nextEligibleAt: now } : timing;
143
+ }
144
+ /**
145
+ * The status of one project from config and the last-run marker. Live sessions
146
+ * are not consulted (that needs the Hook), so "eligible now" means as far as
147
+ * timing goes; the Hook still waits for working agents.
148
+ */
149
+ export function dreamStatus(phrenPath, project, now = new Date()) {
150
+ const config = getDreamingConfig(phrenPath, project);
151
+ const lastRun = readLastRun(phrenPath, project);
152
+ const lastRunAt = lastRun ? new Date(lastRun.at) : undefined;
153
+ // Idle timing depends on the Hook's view of sessions, so only its rule is reported.
154
+ const idle = config.enabled && config.cadence === "idle";
155
+ const decision = idle
156
+ ? { eligible: false, reason: `After ${config.idleMinutes} minutes with no live agent session in the project (the Hook checks every 10 minutes).` }
157
+ : dreamEligibility({ config, now, lastRunAt });
158
+ return {
159
+ project,
160
+ enabled: config.enabled,
161
+ pendingProposals: pendingDreamProposals(phrenPath, project),
162
+ mode: config.mode,
163
+ cadence: config.cadence,
164
+ window: config.window,
165
+ ...(lastRun ? { lastRun } : {}),
166
+ nextEligibleAt: !config.enabled || config.cadence === "manual" || idle ? null : (decision.nextEligibleAt ?? now).toISOString(),
167
+ reason: decision.reason,
168
+ ...(lastRun?.counts ? { lastOutcome: { ...lastRun.counts } } : {}),
169
+ };
170
+ }
171
+ export class DreamScheduler {
172
+ deps;
173
+ ticking = false;
174
+ /** When a live session was last seen in each project (for the idle cadence). */
175
+ lastSeen = new Map();
176
+ /** When the ticker last started a dream for each project, so a failing run is not retried every tick. */
177
+ lastAttempt = new Map();
178
+ constructor(deps) {
179
+ this.deps = deps;
180
+ }
181
+ observe(sessions, now) {
182
+ for (const session of sessions)
183
+ if (session.project)
184
+ this.lastSeen.set(session.project, now);
185
+ }
186
+ decide(project, sessions, now) {
187
+ const config = this.deps.config(project);
188
+ const lastRun = this.deps.lastRun(project);
189
+ const attempted = this.lastAttempt.get(project);
190
+ if (attempted && now.getTime() - attempted.getTime() < DREAM_RETRY_MS) {
191
+ return { eligible: false, reason: "A dream started for this project within the last hour." };
192
+ }
193
+ return dreamEligibility({ config, now, lastRunAt: lastRun ? new Date(lastRun.at) : undefined,
194
+ sessions: sessions.filter((session) => !session.project || session.project === project), lastSeenAt: this.lastSeen.get(project) });
195
+ }
196
+ /** Projects whose dream would start now, given these sessions. Exposed for tests and diagnostics. */
197
+ due(sessions, now = this.deps.now()) {
198
+ return this.deps.projects().filter((project) => this.decide(project, sessions, now).eligible);
199
+ }
200
+ async tick() {
201
+ if (this.ticking)
202
+ return [];
203
+ this.ticking = true;
204
+ const started = [];
205
+ try {
206
+ let sessions = await this.deps.liveSessions();
207
+ this.observe(sessions, this.deps.now());
208
+ for (const project of this.deps.projects()) {
209
+ if (!this.decide(project, sessions, this.deps.now()).eligible)
210
+ continue;
211
+ // An earlier dream in this tick may have taken minutes: look again before starting.
212
+ if (started.length) {
213
+ sessions = await this.deps.liveSessions();
214
+ this.observe(sessions, this.deps.now());
215
+ if (!this.decide(project, sessions, this.deps.now()).eligible)
216
+ continue;
217
+ }
218
+ this.lastAttempt.set(project, this.deps.now());
219
+ started.push(project);
220
+ await this.deps.run(project).catch(() => { });
221
+ }
222
+ }
223
+ catch {
224
+ // Sessions unknown: never guess that nobody is working.
225
+ }
226
+ finally {
227
+ this.ticking = false;
228
+ }
229
+ return started;
230
+ }
231
+ }
232
+ /**
233
+ * The agent panes of one terminal snapshot (the Hook's `{ tabs, panes }`
234
+ * shape) as dream sessions: the project from the pane's folder, the status
235
+ * from the pane or, when the terminal reports none per pane, its tab.
236
+ */
237
+ export function dreamSessionsFromSnapshot(snapshot, projectOf) {
238
+ const record = snapshot && typeof snapshot === "object" ? snapshot : {};
239
+ const rows = (value) => (Array.isArray(value) ? value : []).filter((row) => !!row && typeof row === "object");
240
+ const tabStatus = new Map(rows(record.tabs).map((tab) => [`${String(tab.workspace_id)}/${String(tab.tab_id)}`, tab.agent_status]));
241
+ return rows(record.panes).filter((pane) => typeof pane.agent === "string" && pane.agent).map((pane) => {
242
+ const cwd = typeof pane.foreground_cwd === "string" && pane.foreground_cwd ? pane.foreground_cwd : typeof pane.cwd === "string" ? pane.cwd : undefined;
243
+ const status = pane.agent_status ?? tabStatus.get(`${String(pane.workspace_id)}/${String(pane.tab_id)}`);
244
+ const project = projectOf(cwd);
245
+ return { ...(project ? { project } : {}), ...(typeof status === "string" ? { status } : {}) };
246
+ });
247
+ }
248
+ /**
249
+ * A pane folder's project: the registered project whose checkout (or a
250
+ * worktree of it) holds the folder, else the folder's name, so a session is
251
+ * never missed when deciding that nobody is working.
252
+ */
253
+ export function dreamProjectOf(store, profile) {
254
+ return (cwd) => {
255
+ if (!cwd)
256
+ return undefined;
257
+ try {
258
+ const found = detectProject(store, cwd, profile);
259
+ if (found)
260
+ return found;
261
+ }
262
+ catch { /* fall back to the folder name */ }
263
+ return paneProject(cwd, store);
264
+ };
265
+ }
266
+ /** Projects in the store the Hook serves, skipping `global`. */
267
+ export function dreamStoreProjects(store, profile) {
268
+ try {
269
+ return getProjectDirs(store, profile).map((dir) => path.basename(dir)).filter((name) => name !== "global");
270
+ }
271
+ catch {
272
+ return [];
273
+ }
274
+ }
275
+ /** Off with `PHREN_DREAMING=off`; otherwise the ticker runs and each project's config decides. */
276
+ export function dreamTickerEnabled(env = process.env) {
277
+ return env.PHREN_DREAMING?.trim().toLowerCase() !== "off";
278
+ }
279
+ /** The command that runs a dream; `PHREN_DREAM_COMMAND` points it at a specific phren binary. */
280
+ export function dreamCommand(project, env = process.env) {
281
+ return { command: env.PHREN_DREAM_COMMAND?.trim() || "phren", args: ["dream", "run", "--project", project, "--scheduled"] };
282
+ }
283
+ /** Run one scheduled dream as a low-priority child process of the Hook. */
284
+ export function runDreamChild(store, project, env = process.env) {
285
+ const { command, args } = dreamCommand(project, env);
286
+ return new Promise((resolve) => {
287
+ let child;
288
+ try {
289
+ child = spawn(command, args, { env: { ...env, PHREN_PATH: store }, stdio: "ignore", shell: process.platform === "win32" });
290
+ }
291
+ catch {
292
+ resolve();
293
+ return;
294
+ }
295
+ // Children (the helper's `claude -p`) inherit this on POSIX.
296
+ try {
297
+ if (child.pid)
298
+ os.setPriority(child.pid, 10);
299
+ }
300
+ catch { /* Not permitted here; run at normal priority. */ }
301
+ const timer = setTimeout(() => { try {
302
+ child.kill("SIGTERM");
303
+ }
304
+ catch { /* gone */ } }, DREAM_CHILD_TIMEOUT_MS);
305
+ timer.unref();
306
+ const done = () => { clearTimeout(timer); resolve(); };
307
+ child.once("error", done);
308
+ child.once("exit", done);
309
+ });
310
+ }
311
+ /** Resolve the same evidence used by the live overview before deciding a project is idle. */
312
+ export async function effectiveDreamSessions(server, snapshot, projectOf, hooks, questions) {
313
+ const record = snapshot && typeof snapshot === "object" ? snapshot : {};
314
+ const panes = (Array.isArray(record.panes) ? record.panes : []).filter((p) => !!p && typeof p === "object" && !!p.agent);
315
+ const resolved = await Promise.all(panes.map(async (pane) => {
316
+ const chat = await paneChatState(server, pane, { tokenWhenIdentified: false });
317
+ const session = typeof chat.sessionId === "string" ? chat.sessionId : undefined;
318
+ const evidence = session ? await effectivePaneEvidence(server, pane, session, hooks, questions) : undefined;
319
+ return { ...pane, agent_status: evidence ? resolveEffectiveStatus(evidence) ?? "unknown" : "unknown" };
320
+ }));
321
+ return dreamSessionsFromSnapshot({ ...record, panes: resolved }, projectOf);
322
+ }
@@ -10,7 +10,7 @@ import { BridgeError, id, object, objects, requestID, serverName, provider, sess
10
10
  import { logger } from "../logger.js";
11
11
  import { recordedSession } from "./agent-hook-stores.js";
12
12
  import { paneRecord, recordTitle } from "./session-activity.js";
13
- import { tabActivityKey } from "./tab-activity.js";
13
+ import { panesByTab, tabActivityKey } from "./tab-activity.js";
14
14
  import { intervalFromEnv } from "./limits.js";
15
15
  import { countHerdr, countIdentity } from "./metrics.js";
16
16
  import { phrenStoreRoot } from "./transcripts.js";
@@ -280,6 +280,15 @@ export function isConductorName(name) {
280
280
  /** `conductorPane` is the pane the Hook records as the conductor (null for
281
281
  * none); left out, the agent's name decides, as before the record. */
282
282
  export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged, conductorPane) {
283
+ const grouped = panesByTab(s);
284
+ const tabsByWorkspace = new Map();
285
+ for (const tab of objects(s.tabs)) {
286
+ const tabs = tabsByWorkspace.get(tab.workspace_id);
287
+ if (tabs)
288
+ tabs.push(tab);
289
+ else
290
+ tabsByWorkspace.set(tab.workspace_id, [tab]);
291
+ }
283
292
  const focusedPane = objects(s.panes).find(p => p.pane_id === s.focused_pane_id
284
293
  && p.tab_id === s.focused_tab_id && p.workspace_id === s.focused_workspace_id);
285
294
  const focus = focusedPane && id.safeParse(s.focused_workspace_id).success
@@ -290,9 +299,9 @@ export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChan
290
299
  // Focus identifies a pane to inspect. Its conversation is still resolved and
291
300
  // validated independently through panes(), never inferred from a directory.
292
301
  return { kind: "herdr", focus, groups: objects(s.workspaces).map(w => ({ id: w.workspace_id, label: w.label,
293
- children: objects(s.tabs).filter(t => t.workspace_id === w.workspace_id).map(t => {
294
- const panes = objects(s.panes).filter(p => p.tab_id === t.tab_id && p.workspace_id === t.workspace_id);
295
- const agent = panes.find(p => p.agent);
302
+ children: (tabsByWorkspace.get(w.workspace_id) ?? []).map(t => {
303
+ const panes = grouped.get(tabActivityKey(t.workspace_id, t.tab_id)) ?? [];
304
+ const agents = panes.filter(p => p.agent), agent = agents[0];
296
305
  const activity = lastChanged?.get(tabActivityKey(t.workspace_id, t.tab_id));
297
306
  // Herdr's per-pane state_change_seq climbs with every agent status
298
307
  // change; the phone orders "just finished" ahead of "finished an hour ago" by it.
@@ -304,8 +313,8 @@ export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChan
304
313
  lastChangedAt: activity?.lastChangedAt,
305
314
  statusSince: activity?.statusSince,
306
315
  approvalPending: panes.some(p => approvalPanes?.has(String(p.pane_id))) || undefined,
307
- contextUsedPercent: agent && panes.filter(p => p.agent).length === 1 ? contextUsedPercent?.get(agent) : undefined,
308
- agentPaneCount: panes.filter(p => p.agent).length, paneCount: panes.length };
316
+ contextUsedPercent: agent && agents.length === 1 ? contextUsedPercent?.get(agent) : undefined,
317
+ agentPaneCount: agents.length, paneCount: panes.length };
309
318
  }) })) };
310
319
  }
311
320
  /** Only file descriptors held by this pane's foreground processes establish identity.
@@ -1,3 +1,4 @@
1
+ import { browserShimPath } from "./browser-env.js";
1
2
  import { activateModules as moduleSnapshot } from "../modules/runtime.js";
2
3
  import { defaultPhrenPath } from "../shared.js";
3
4
  import { disabledHint } from "../modules/registry.js";
@@ -299,6 +300,9 @@ export async function install(version, noService = false, force = false) {
299
300
  const stagedBundle = installedBundle + `.phren-${process.pid}`;
300
301
  await copyFile(bundle, stagedBundle);
301
302
  await rename(stagedBundle, installedBundle);
303
+ const shimDirectory = path.join(destination, "bridge/browser-shim");
304
+ await mkdir(shimDirectory, { recursive: true, mode: 0o700 });
305
+ await atomic(path.join(shimDirectory, "phren-playwright.cjs"), typeof BROWSER_SHIM_SOURCE !== "undefined" ? BROWSER_SHIM_SOURCE : await readFile(browserShimPath(), "utf8"), 0o600);
302
306
  await atomic(fastHookPath(destination), FAST_HOOK_SOURCE);
303
307
  const previous = await readFile(path.join(root, "installed.json"), "utf8").then(v => JSON.parse(v)).catch(() => null);
304
308
  const gateway = await detectGateway();
@@ -20,6 +20,11 @@ import { type Target } from "./protocol.js";
20
20
  export declare const briefId: z.ZodString;
21
21
  export declare const launchBriefSchema: z.ZodObject<{
22
22
  id: z.ZodString;
23
+ task: z.ZodOptional<z.ZodObject<{
24
+ storeId: z.ZodString;
25
+ project: z.ZodString;
26
+ stableId: z.ZodString;
27
+ }, z.core.$strict>>;
23
28
  text: z.ZodString;
24
29
  }, z.core.$strict>;
25
30
  export type LaunchBrief = z.infer<typeof launchBriefSchema>;
@@ -103,3 +108,9 @@ export declare function briefIdInPrompt(prompt: string): string | undefined;
103
108
  /** Records a worker hook's report about its brief. Only the first of each
104
109
  * event counts, and only for a brief this computer wrote. */
105
110
  export declare function recordBriefArrival(id: string, event: string, target: Target, now?: Date): Promise<void>;
111
+ /** Private association carried with the launch, never included in GitHub data. */
112
+ export declare function briefTask(id: string): Promise<{
113
+ storeId: string;
114
+ project: string;
115
+ stableId: string;
116
+ } | undefined>;