@phren/cli 0.3.71 → 0.3.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/agent-hooks.js +11 -1
- package/dist/bridge/browser-env.d.ts +5 -0
- package/dist/bridge/browser-env.js +110 -0
- package/dist/bridge/browser-protocol.d.ts +120 -0
- package/dist/bridge/browser-protocol.js +70 -0
- package/dist/bridge/browser-recordings.d.ts +63 -0
- package/dist/bridge/browser-recordings.js +148 -0
- package/dist/bridge/browser-registry.d.ts +64 -0
- package/dist/bridge/browser-registry.js +262 -0
- package/dist/bridge/browser-routes.d.ts +4 -0
- package/dist/bridge/browser-routes.js +39 -0
- package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
- package/dist/bridge/browser-socket.d.ts +2 -0
- package/dist/bridge/browser-socket.js +10 -0
- package/dist/bridge/browser-stream.d.ts +3 -0
- package/dist/bridge/browser-stream.js +129 -0
- package/dist/bridge/browser-watch.d.ts +12 -0
- package/dist/bridge/browser-watch.js +83 -0
- package/dist/bridge/claude-account-setup.js +3 -1
- package/dist/bridge/claude-accounts.d.ts +5 -1
- package/dist/bridge/claude-accounts.js +36 -6
- package/dist/bridge/codex-servers.d.ts +2 -0
- package/dist/bridge/codex-servers.js +1 -1
- package/dist/bridge/command.js +24 -5
- package/dist/bridge/dispatch-clone.d.ts +33 -0
- package/dist/bridge/dispatch-clone.js +176 -0
- package/dist/bridge/dispatch-command.d.ts +14 -0
- package/dist/bridge/dispatch-command.js +98 -13
- package/dist/bridge/dispatch-idempotency.d.ts +85 -0
- package/dist/bridge/dispatch-idempotency.js +235 -0
- package/dist/bridge/dispatch-returns.d.ts +6 -0
- package/dist/bridge/dispatch-returns.js +131 -1
- package/dist/bridge/dispatch-wait.d.ts +32 -0
- package/dist/bridge/dispatch-wait.js +177 -0
- package/dist/bridge/dispatch.d.ts +78 -2
- package/dist/bridge/dispatch.js +841 -25
- package/dist/bridge/dream-schedule.d.ts +133 -0
- package/dist/bridge/dream-schedule.js +322 -0
- package/dist/bridge/fanouts.js +20 -3
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/git-credential.d.ts +44 -0
- package/dist/bridge/git-credential.js +113 -0
- package/dist/bridge/git-host-auth.d.ts +9 -1
- package/dist/bridge/git-host-auth.js +18 -5
- package/dist/bridge/git-host-gitboy.js +8 -1
- package/dist/bridge/git-hosts.d.ts +12 -1
- package/dist/bridge/git-publish.js +3 -2
- package/dist/bridge/herdr.d.ts +4 -0
- package/dist/bridge/herdr.js +44 -9
- package/dist/bridge/install.d.ts +1 -1
- package/dist/bridge/install.js +12 -4
- package/dist/bridge/launch-brief.d.ts +11 -0
- package/dist/bridge/launch-brief.js +22 -0
- package/dist/bridge/launch-worktree.d.ts +2 -0
- package/dist/bridge/launch-worktree.js +5 -1
- package/dist/bridge/pane-status.js +1 -1
- package/dist/bridge/protocol.d.ts +7 -0
- package/dist/bridge/schedule-watch.js +13 -2
- package/dist/bridge/server-launch.d.ts +2 -0
- package/dist/bridge/server-launch.js +251 -145
- package/dist/bridge/server-routes.d.ts +3 -0
- package/dist/bridge/server-routes.js +33 -17
- package/dist/bridge/server-stream.d.ts +4 -0
- package/dist/bridge/server-stream.js +24 -5
- package/dist/bridge/server.js +35 -4
- package/dist/bridge/session-move.d.ts +10 -4
- package/dist/bridge/session-move.js +65 -34
- package/dist/bridge/simulator-stream.d.ts +2 -0
- package/dist/bridge/simulator-stream.js +2 -0
- package/dist/bridge/status-line-fast.d.ts +9 -0
- package/dist/bridge/status-line-fast.js +56 -0
- package/dist/bridge/tab-activity.d.ts +2 -0
- package/dist/bridge/tab-activity.js +15 -2
- package/dist/bridge/task-routes.d.ts +20 -16
- package/dist/bridge/task-routes.js +1 -1
- package/dist/bridge/terminal-herdr.d.ts +5 -1
- package/dist/bridge/terminal-herdr.js +67 -2
- package/dist/bridge/terminal-tmux.d.ts +2 -0
- package/dist/bridge/terminal-tmux.js +29 -7
- package/dist/bridge/terminal.d.ts +5 -1
- package/dist/bridge/transcript-claude.js +192 -112
- package/dist/bridge/transcript-preview.d.ts +2 -1
- package/dist/bridge/transcript-preview.js +85 -3
- package/dist/bridge/transcripts.js +17 -11
- package/dist/bridge/turn-records.js +16 -4
- package/dist/bridge/usage.d.ts +7 -1
- package/dist/bridge/usage.js +47 -31
- package/dist/bridge/worker-close.d.ts +15 -0
- package/dist/bridge/worker-close.js +304 -3
- package/dist/bridge/worker-identity.d.ts +51 -0
- package/dist/bridge/worker-identity.js +289 -0
- package/dist/bridge/worker-reports.js +15 -3
- package/dist/bridge-hook.mjs +39990 -36152
- package/dist/capabilities/mcp.js +1 -1
- package/dist/cli/browser-hint.d.ts +2 -0
- package/dist/cli/browser-hint.js +21 -0
- package/dist/cli/config-dreaming.d.ts +7 -0
- package/dist/cli/config-dreaming.js +72 -0
- package/dist/cli/config.js +6 -0
- package/dist/cli/dream.d.ts +59 -0
- package/dist/cli/dream.js +315 -0
- package/dist/cli/hooks-context.d.ts +2 -2
- package/dist/cli/hooks-context.js +3 -3
- package/dist/cli/hooks.js +20 -11
- package/dist/cli/namespaces-tasks.js +14 -0
- package/dist/cli-registry.js +28 -3
- package/dist/config/dreaming.d.ts +82 -0
- package/dist/config/dreaming.js +195 -0
- package/dist/config/resolve.js +11 -0
- package/dist/config/schema.d.ts +4 -4
- package/dist/config/schema.js +157 -1
- package/dist/content/citation-freshness.js +6 -0
- package/dist/content/learning.d.ts +1 -0
- package/dist/content/learning.js +2 -0
- package/dist/data/access.d.ts +1 -1
- package/dist/data/access.js +3 -1
- package/dist/data/task-contract.d.ts +5 -4
- package/dist/data/tasks.d.ts +5 -0
- package/dist/data/tasks.js +28 -2
- package/dist/dream/apply.d.ts +69 -0
- package/dist/dream/apply.js +372 -0
- package/dist/dream/budget.d.ts +78 -0
- package/dist/dream/budget.js +180 -0
- package/dist/dream/collect.d.ts +86 -0
- package/dist/dream/collect.js +449 -0
- package/dist/dream/eval/dream-adapter.d.ts +16 -0
- package/dist/dream/eval/dream-adapter.js +21 -0
- package/dist/dream/eval/fixture.d.ts +53 -0
- package/dist/dream/eval/fixture.js +172 -0
- package/dist/dream/eval/index.d.ts +40 -0
- package/dist/dream/eval/index.js +78 -0
- package/dist/dream/eval/score.d.ts +34 -0
- package/dist/dream/eval/score.js +99 -0
- package/dist/dream/eval/scripted-model.d.ts +19 -0
- package/dist/dream/eval/scripted-model.js +70 -0
- package/dist/dream/pages.d.ts +68 -0
- package/dist/dream/pages.js +220 -0
- package/dist/dream/privacy.d.ts +3 -0
- package/dist/dream/privacy.js +18 -0
- package/dist/dream/prompt.d.ts +13 -0
- package/dist/dream/prompt.js +84 -0
- package/dist/dream/run.d.ts +98 -0
- package/dist/dream/run.js +317 -0
- package/dist/dream/types.d.ts +74 -0
- package/dist/dream/types.js +4 -0
- package/dist/finding/lifecycle.d.ts +2 -2
- package/dist/finding/lifecycle.js +5 -2
- package/dist/finding/versions.d.ts +4 -0
- package/dist/finding/versions.js +28 -0
- package/dist/index.js +1 -0
- package/dist/modules/registry.js +10 -8
- package/dist/project-config.d.ts +3 -0
- package/dist/task/merge-links.d.ts +38 -0
- package/dist/task/merge-links.js +45 -0
- package/dist/task/reconcile.d.ts +39 -0
- package/dist/task/reconcile.js +201 -0
- package/dist/task/report-links.d.ts +10 -0
- package/dist/task/report-links.js +47 -0
- package/dist/tools/config.js +46 -4
- package/dist/tools/dispatch.js +2 -1
- package/dist/tools/dream.d.ts +3 -0
- package/dist/tools/dream.js +123 -0
- package/dist/tools/tasks.js +4 -1
- package/package.json +1 -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
|
+
}
|
package/dist/bridge/fanouts.js
CHANGED
|
@@ -120,6 +120,9 @@ export async function containedFanoutRoot(env) {
|
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
122
|
async function regularContainedFile(root, candidate, maxBytes) {
|
|
123
|
+
return (await containedFileStat(root, candidate, maxBytes))?.resolved;
|
|
124
|
+
}
|
|
125
|
+
async function containedFileStat(root, candidate, maxBytes) {
|
|
123
126
|
try {
|
|
124
127
|
const link = await lstat(candidate);
|
|
125
128
|
if (!link.isFile() || link.isSymbolicLink() || link.size > maxBytes)
|
|
@@ -128,12 +131,26 @@ async function regularContainedFile(root, candidate, maxBytes) {
|
|
|
128
131
|
if (!resolved.startsWith(root + path.sep))
|
|
129
132
|
return;
|
|
130
133
|
const metadata = await stat(resolved);
|
|
131
|
-
return metadata.isFile() && metadata.size <= maxBytes ? resolved : undefined;
|
|
134
|
+
return metadata.isFile() && metadata.size <= maxBytes ? { resolved, stamp: `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}` } : undefined;
|
|
132
135
|
}
|
|
133
136
|
catch {
|
|
134
137
|
return;
|
|
135
138
|
}
|
|
136
139
|
}
|
|
140
|
+
/** Parsed manifests by file, while unchanged: every conversation's child tree reads every job's manifest
|
|
141
|
+
* to find its own, so parsing them each time cost the Hook per session per overview. */
|
|
142
|
+
const manifestCache = new Map();
|
|
143
|
+
async function readManifest(file) {
|
|
144
|
+
const cached = manifestCache.get(file.resolved);
|
|
145
|
+
if (cached?.stamp === file.stamp)
|
|
146
|
+
return cached.manifest;
|
|
147
|
+
const manifest = manifestSchema.parse(JSON.parse(await readFile(file.resolved, "utf8")));
|
|
148
|
+
manifestCache.delete(file.resolved);
|
|
149
|
+
manifestCache.set(file.resolved, { stamp: file.stamp, manifest });
|
|
150
|
+
while (manifestCache.size > MAX_JOBS * 2)
|
|
151
|
+
manifestCache.delete(manifestCache.keys().next().value);
|
|
152
|
+
return manifest;
|
|
153
|
+
}
|
|
137
154
|
export async function nativeClaudeTranscript(candidate, session) {
|
|
138
155
|
if (path.basename(candidate) !== `${session}.jsonl`)
|
|
139
156
|
return;
|
|
@@ -219,11 +236,11 @@ export async function fanoutChildren(parentProvider, parentSession, env = proces
|
|
|
219
236
|
const children = [];
|
|
220
237
|
for (const name of names) {
|
|
221
238
|
const directory = path.join(root, name);
|
|
222
|
-
const manifestFile = await
|
|
239
|
+
const manifestFile = await containedFileStat(root, path.join(directory, "manifest.json"), MAX_MANIFEST_BYTES);
|
|
223
240
|
if (!manifestFile)
|
|
224
241
|
continue;
|
|
225
242
|
try {
|
|
226
|
-
const manifest =
|
|
243
|
+
const manifest = await readManifest(manifestFile);
|
|
227
244
|
if (manifest.id !== name || manifest.parent?.provider !== parentProvider || manifest.parent.session !== parentSession
|
|
228
245
|
|| (manifest.parent.computer !== undefined && parentComputer !== undefined && manifest.parent.computer !== parentComputer))
|
|
229
246
|
continue;
|
package/dist/bridge/files.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** Read-only browsing beneath a root selected and verified by the server. */
|
|
2
2
|
export declare function browseFiles(root: string, relative: string): Promise<{
|
|
3
|
+
size?: undefined;
|
|
3
4
|
path: string;
|
|
4
5
|
kind: string;
|
|
5
6
|
truncated: boolean;
|
|
@@ -8,7 +9,6 @@ export declare function browseFiles(root: string, relative: string): Promise<{
|
|
|
8
9
|
path: string;
|
|
9
10
|
kind: string;
|
|
10
11
|
}[];
|
|
11
|
-
size?: undefined;
|
|
12
12
|
data?: undefined;
|
|
13
13
|
} | {
|
|
14
14
|
truncated?: undefined;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type GitHost } from "./git-hosts.js";
|
|
2
|
+
/**
|
|
3
|
+
* The gitboy path's credentials. The Hook's stored `gba_` agent token is the
|
|
4
|
+
* only one a keyed dispatch may use: a credential helper in the worktree's own
|
|
5
|
+
* config answers git, and the agent environment carries the same token for the
|
|
6
|
+
* API. The token never enters argv, a remote URL or a log.
|
|
7
|
+
*/
|
|
8
|
+
/** Variables a keyed worker may inherit from the Hook's own environment. */
|
|
9
|
+
export declare const KEYED_ENV_ALLOW: readonly ["HOME", "USER", "LOGNAME", "PATH", "SHELL", "TERM", "LANG", "LC_ALL", "TMPDIR"];
|
|
10
|
+
/**
|
|
11
|
+
* The exact environment for a keyed worker: a small allowlist plus the values
|
|
12
|
+
* this Hook owns. Nothing else from process.env is copied, so no caller or
|
|
13
|
+
* Hook token reaches the harness.
|
|
14
|
+
*/
|
|
15
|
+
export declare function keyedExplicitEnv(base?: NodeJS.ProcessEnv, extra?: Record<string, string>): Record<string, string>;
|
|
16
|
+
/** The credential-free HTTPS remote for a gitboy host, or a refusal when owner/repo cannot be derived. */
|
|
17
|
+
export declare function credentialFreeRemote(host: Pick<GitHost, "domain" | "webUrl">): string;
|
|
18
|
+
/** Write the agent token to an exact private file path. */
|
|
19
|
+
export declare function writeAgentTokenFileAt(file: string, token: string): Promise<string>;
|
|
20
|
+
/** Remove a token file this Hook wrote; only the expected file name is ever touched. */
|
|
21
|
+
export declare function removeAgentTokenFile(file: string | undefined): Promise<void>;
|
|
22
|
+
export interface KeyedGitboy {
|
|
23
|
+
env: Record<string, string>;
|
|
24
|
+
tokenFile: string;
|
|
25
|
+
}
|
|
26
|
+
export interface KeyedGitboyOptions {
|
|
27
|
+
/** The exact token file path (the clone's git dir). */
|
|
28
|
+
tokenFile: string;
|
|
29
|
+
/** The managed global config the clone and the agent use. */
|
|
30
|
+
gitConfigFile?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A keyed dispatch in a gitboy checkout uses this computer's stored agent token
|
|
34
|
+
* and fails closed when there is none. The token goes to a 0600 file; the agent
|
|
35
|
+
* gets only GITBOY_TOKEN_FILE (and, for a clone, its managed GIT_CONFIG_GLOBAL).
|
|
36
|
+
*/
|
|
37
|
+
export declare function prepareKeyedGitboy(cwd: string, options: KeyedGitboyOptions): Promise<KeyedGitboy | undefined>;
|
|
38
|
+
/** A git credential request for a host with a stored gitboy token, answered for `get` only. */
|
|
39
|
+
export declare function gitCredentialAnswer(request: string): Promise<{
|
|
40
|
+
username: string;
|
|
41
|
+
password: string;
|
|
42
|
+
} | undefined>;
|
|
43
|
+
/** The `phren bridge git-credential` helper: get answers, store and erase do nothing. */
|
|
44
|
+
export declare function gitCredentialCommand(operation: string | undefined, request: string): Promise<string | undefined>;
|