@phren/cli 0.2.15 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/agent-instructions.d.ts +12 -0
- package/dist/agent-instructions.js +52 -0
- package/dist/bridge/agent-hook-stores.d.ts +32 -0
- package/dist/bridge/agent-hook-stores.js +67 -0
- package/dist/bridge/agent-hooks.d.ts +195 -2
- package/dist/bridge/agent-hooks.js +1049 -38
- package/dist/bridge/canary.d.ts +27 -0
- package/dist/bridge/canary.js +189 -0
- package/dist/bridge/changes.d.ts +57 -0
- package/dist/bridge/changes.js +403 -0
- package/dist/bridge/client.d.ts +3 -0
- package/dist/bridge/client.js +36 -0
- package/dist/bridge/code-note.d.ts +23 -0
- package/dist/bridge/code-note.js +51 -0
- package/dist/bridge/code-routes.d.ts +151 -0
- package/dist/bridge/code-routes.js +442 -0
- package/dist/bridge/codex-threads.d.ts +27 -0
- package/dist/bridge/codex-threads.js +442 -0
- package/dist/bridge/command.d.ts +7 -0
- package/dist/bridge/command.js +50 -5
- package/dist/bridge/computer-names.d.ts +4 -0
- package/dist/bridge/computer-names.js +16 -0
- package/dist/bridge/computers.d.ts +9 -0
- package/dist/bridge/computers.js +111 -0
- package/dist/bridge/context.d.ts +14 -0
- package/dist/bridge/context.js +149 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +93 -0
- package/dist/bridge/dispatch-hosts.d.ts +23 -0
- package/dist/bridge/dispatch-hosts.js +25 -0
- package/dist/bridge/dispatch-returns.d.ts +125 -0
- package/dist/bridge/dispatch-returns.js +283 -0
- package/dist/bridge/dispatch-tree.d.ts +54 -0
- package/dist/bridge/dispatch-tree.js +198 -0
- package/dist/bridge/dispatch.d.ts +210 -0
- package/dist/bridge/dispatch.js +286 -0
- package/dist/bridge/enroll.d.ts +31 -0
- package/dist/bridge/enroll.js +236 -0
- package/dist/bridge/fanout-messages.d.ts +74 -0
- package/dist/bridge/fanout-messages.js +230 -0
- package/dist/bridge/fanouts.d.ts +160 -0
- package/dist/bridge/fanouts.js +702 -0
- package/dist/bridge/file-range.d.ts +16 -0
- package/dist/bridge/file-range.js +90 -0
- package/dist/bridge/files.d.ts +20 -0
- package/dist/bridge/files.js +54 -0
- package/dist/bridge/git-publish.d.ts +23 -0
- package/dist/bridge/git-publish.js +145 -0
- package/dist/bridge/git-worktrees.d.ts +21 -0
- package/dist/bridge/git-worktrees.js +150 -0
- package/dist/bridge/git.d.ts +54 -0
- package/dist/bridge/git.js +552 -0
- package/dist/bridge/grants.d.ts +31 -0
- package/dist/bridge/grants.js +181 -0
- package/dist/bridge/hand-off.d.ts +79 -0
- package/dist/bridge/hand-off.js +151 -0
- package/dist/bridge/health.d.ts +128 -0
- package/dist/bridge/health.js +260 -0
- package/dist/bridge/herdr.d.ts +79 -6
- package/dist/bridge/herdr.js +292 -27
- package/dist/bridge/hook-main.js +2 -0
- package/dist/bridge/install.d.ts +28 -1
- package/dist/bridge/install.js +225 -38
- package/dist/bridge/launch-worktree.d.ts +21 -0
- package/dist/bridge/launch-worktree.js +70 -0
- package/dist/bridge/limits.d.ts +20 -0
- package/dist/bridge/limits.js +65 -0
- package/dist/bridge/locate.d.ts +16 -0
- package/dist/bridge/locate.js +75 -0
- package/dist/bridge/metrics.d.ts +29 -0
- package/dist/bridge/metrics.js +71 -0
- package/dist/bridge/model-switch.d.ts +35 -0
- package/dist/bridge/model-switch.js +250 -0
- package/dist/bridge/models.d.ts +46 -0
- package/dist/bridge/models.js +257 -0
- package/dist/bridge/opencode-approvals.d.ts +6 -0
- package/dist/bridge/opencode-approvals.js +60 -0
- package/dist/bridge/pane-text.d.ts +15 -0
- package/dist/bridge/pane-text.js +23 -0
- package/dist/bridge/peers.d.ts +27 -0
- package/dist/bridge/peers.js +130 -0
- package/dist/bridge/projects.d.ts +12 -1
- package/dist/bridge/projects.js +268 -20
- package/dist/bridge/protocol.d.ts +35 -2
- package/dist/bridge/protocol.js +61 -7
- package/dist/bridge/push.d.ts +83 -0
- package/dist/bridge/push.js +199 -0
- package/dist/bridge/questions.d.ts +38 -0
- package/dist/bridge/questions.js +205 -0
- package/dist/bridge/schedule-format.d.ts +103 -0
- package/dist/bridge/schedule-format.js +266 -0
- package/dist/bridge/schedule-launch.d.ts +11 -0
- package/dist/bridge/schedule-launch.js +169 -0
- package/dist/bridge/schedule-watch.d.ts +54 -0
- package/dist/bridge/schedule-watch.js +255 -0
- package/dist/bridge/schedules.d.ts +48 -0
- package/dist/bridge/schedules.js +205 -0
- package/dist/bridge/server-launch.d.ts +14 -0
- package/dist/bridge/server-launch.js +218 -0
- package/dist/bridge/server-overview.d.ts +45 -0
- package/dist/bridge/server-overview.js +102 -0
- package/dist/bridge/server-pane-routes.d.ts +36 -0
- package/dist/bridge/server-pane-routes.js +479 -0
- package/dist/bridge/server-routes.d.ts +108 -0
- package/dist/bridge/server-routes.js +556 -0
- package/dist/bridge/server-stream.d.ts +46 -0
- package/dist/bridge/server-stream.js +253 -0
- package/dist/bridge/server.d.ts +3 -15
- package/dist/bridge/server.js +162 -264
- package/dist/bridge/session-servers.d.ts +24 -0
- package/dist/bridge/session-servers.js +136 -0
- package/dist/bridge/side-questions.d.ts +74 -0
- package/dist/bridge/side-questions.js +252 -0
- package/dist/bridge/simulators.d.ts +28 -0
- package/dist/bridge/simulators.js +198 -0
- package/dist/bridge/speech-transcribe.d.ts +24 -0
- package/dist/bridge/speech-transcribe.js +124 -0
- package/dist/bridge/speech.d.ts +35 -0
- package/dist/bridge/speech.js +98 -0
- package/dist/bridge/steps.d.ts +13 -0
- package/dist/bridge/steps.js +222 -0
- package/dist/bridge/tab-activity.d.ts +18 -0
- package/dist/bridge/tab-activity.js +99 -0
- package/dist/bridge/terminal-choice.d.ts +64 -0
- package/dist/bridge/terminal-choice.js +281 -0
- package/dist/bridge/transcript-claude.d.ts +22 -0
- package/dist/bridge/transcript-claude.js +353 -0
- package/dist/bridge/transcript-codex.d.ts +30 -0
- package/dist/bridge/transcript-codex.js +282 -0
- package/dist/bridge/transcript-copilot.d.ts +4 -0
- package/dist/bridge/transcript-copilot.js +14 -0
- package/dist/bridge/transcript-opencode.d.ts +5 -0
- package/dist/bridge/transcript-opencode.js +26 -0
- package/dist/bridge/transcript-preview.d.ts +96 -0
- package/dist/bridge/transcript-preview.js +491 -0
- package/dist/bridge/transcripts.d.ts +81 -4
- package/dist/bridge/transcripts.js +332 -67
- package/dist/bridge/transport.d.ts +3 -0
- package/dist/bridge/transport.js +96 -15
- package/dist/bridge/uploads.d.ts +15 -0
- package/dist/bridge/uploads.js +44 -2
- package/dist/bridge/usage.d.ts +124 -0
- package/dist/bridge/usage.js +859 -0
- package/dist/bridge-hook.mjs +46545 -21051
- package/dist/cli/actions.js +14 -1
- package/dist/cli/config-policy.js +25 -0
- package/dist/cli/config-proactivity.d.ts +3 -1
- package/dist/cli/config-proactivity.js +35 -3
- package/dist/cli/config.js +4 -1
- package/dist/cli/extract.d.ts +0 -8
- package/dist/cli/extract.js +4 -7
- package/dist/cli/govern.js +5 -2
- package/dist/cli/hooks-globs.js +1 -1
- package/dist/cli/hooks.d.ts +1 -1
- package/dist/cli/hooks.js +9 -7
- package/dist/cli/namespaces-projects.js +12 -6
- package/dist/cli/namespaces-store.js +37 -6
- package/dist/cli/namespaces-tasks.js +1 -1
- package/dist/cli/schedules.d.ts +1 -0
- package/dist/cli/schedules.js +164 -0
- package/dist/cli/session-background.js +1 -1
- package/dist/cli/session-git.d.ts +8 -5
- package/dist/cli/session-git.js +45 -120
- package/dist/cli/session-start.js +3 -1
- package/dist/cli/session-stop.js +19 -8
- package/dist/cli/team.js +13 -10
- package/dist/cli-handlers.d.ts +1 -1
- package/dist/cli-handlers.js +8 -4
- package/dist/cli-help.d.ts +5 -4
- package/dist/cli-help.js +15 -15
- package/dist/cli-registry.d.ts +4 -1
- package/dist/cli-registry.js +119 -6
- package/dist/content/archive.js +2 -2
- package/dist/content/citation.d.ts +11 -0
- package/dist/content/citation.js +18 -0
- package/dist/content/learning.js +2 -0
- package/dist/content/summarize.d.ts +14 -15
- package/dist/content/summarize.js +60 -5
- package/dist/content/validate.d.ts +17 -4
- package/dist/content/validate.js +200 -122
- package/dist/core/project-registry.d.ts +26 -0
- package/dist/core/project-registry.js +573 -0
- package/dist/core/project.js +2 -3
- package/dist/data/access.d.ts +16 -1
- package/dist/data/access.js +31 -3
- package/dist/data/tasks.d.ts +18 -3
- package/dist/data/tasks.js +8 -7
- package/dist/entrypoint.js +44 -10
- package/dist/fanout/adapters/claude.d.ts +2 -0
- package/dist/fanout/adapters/claude.js +7 -0
- package/dist/fanout/adapters/codex.d.ts +2 -0
- package/dist/fanout/adapters/codex.js +9 -0
- package/dist/fanout/adapters/opencode.d.ts +4 -0
- package/dist/fanout/adapters/opencode.js +9 -0
- package/dist/fanout/adapters/types.d.ts +21 -0
- package/dist/fanout/adapters/types.js +3 -0
- package/dist/fanout/command.d.ts +2 -0
- package/dist/fanout/command.js +78 -0
- package/dist/fanout/launcher.d.ts +27 -0
- package/dist/fanout/launcher.js +156 -0
- package/dist/fanout/opencode-serve.d.ts +24 -0
- package/dist/fanout/opencode-serve.js +191 -0
- package/dist/fanout/picker.d.ts +91 -0
- package/dist/fanout/picker.js +51 -0
- package/dist/fanout/usage.d.ts +5 -0
- package/dist/fanout/usage.js +51 -0
- package/dist/fanout/watchdog.d.ts +10 -0
- package/dist/fanout/watchdog.js +27 -0
- package/dist/filenames.d.ts +9 -0
- package/dist/filenames.js +11 -0
- package/dist/finding/context.js +4 -22
- package/dist/generated/memory-ui-graph.browser.js +525 -419
- package/dist/governance/policy-constants.d.ts +11 -0
- package/dist/governance/policy-constants.js +9 -0
- package/dist/governance/policy.d.ts +5 -8
- package/dist/governance/policy.js +11 -8
- package/dist/graph-core/camera.d.ts +24 -0
- package/dist/graph-core/camera.js +18 -0
- package/dist/graph-core/index.d.ts +2 -0
- package/dist/graph-core/index.js +2 -0
- package/dist/graph-core/labels.d.ts +77 -0
- package/dist/graph-core/labels.js +124 -0
- package/dist/graph-core/model.d.ts +13 -0
- package/dist/graph-core/model.js +33 -0
- package/dist/graph-core/types.d.ts +2 -0
- package/dist/home-paths.d.ts +7 -0
- package/dist/home-paths.js +21 -0
- package/dist/hooks.d.ts +3 -15
- package/dist/hooks.js +14 -1
- package/dist/index.js +24 -2
- package/dist/init/guard-globals.d.ts +1 -1
- package/dist/init/guard-globals.js +4 -4
- package/dist/init/init-configure.js +3 -3
- package/dist/init/init-uninstall.js +15 -5
- package/dist/init/init-walkthrough.js +1 -1
- package/dist/init/init.js +26 -6
- package/dist/init/management-preset.d.ts +1 -1
- package/dist/init/management-preset.js +2 -2
- package/dist/init/preferences.js +1 -1
- package/dist/init/self-wiring.js +1 -1
- package/dist/init/setup.d.ts +3 -26
- package/dist/init/setup.js +68 -593
- package/dist/init/shared.js +2 -0
- package/dist/init/store-gitignore.d.ts +1 -6
- package/dist/init/store-gitignore.js +2 -8
- package/dist/init/teardown.d.ts +1 -1
- package/dist/init/teardown.js +2 -2
- package/dist/link/context-imports.d.ts +15 -0
- package/dist/link/context-imports.js +101 -0
- package/dist/link/context.js +1 -1
- package/dist/link/doctor.d.ts +22 -1
- package/dist/link/doctor.js +128 -58
- package/dist/link/link.js +29 -61
- package/dist/link/refresh.js +2 -2
- package/dist/link/skills.js +26 -5
- package/dist/machine-identity.d.ts +3 -0
- package/dist/machine-identity.js +6 -0
- package/dist/mcp/profile.d.ts +2 -19
- package/dist/mcp/profile.js +64 -22
- package/dist/memory-ui-graph.runtime.js +525 -419
- package/dist/modules/code-package.d.ts +16 -0
- package/dist/modules/code-package.js +160 -0
- package/dist/modules/command.d.ts +2 -0
- package/dist/modules/command.js +67 -0
- package/dist/modules/config.d.ts +4 -0
- package/dist/modules/config.js +70 -0
- package/dist/modules/manifest.d.ts +41 -0
- package/dist/modules/manifest.js +1 -0
- package/dist/modules/provision.d.ts +3 -0
- package/dist/modules/provision.js +84 -0
- package/dist/modules/registry.d.ts +16 -0
- package/dist/modules/registry.js +250 -0
- package/dist/modules/runtime.d.ts +15 -0
- package/dist/modules/runtime.js +59 -0
- package/dist/package-metadata.js +10 -2
- package/dist/phren-dotenv.js +4 -2
- package/dist/phren-paths.d.ts +3 -2
- package/dist/phren-paths.js +4 -5
- package/dist/profile-store.js +43 -8
- package/dist/project-config.d.ts +19 -1
- package/dist/project-config.js +29 -3
- package/dist/project-topics.d.ts +1 -0
- package/dist/project-topics.js +13 -10
- package/dist/provider-adapters.js +1 -4
- package/dist/query-correlation.js +6 -6
- package/dist/session/artifacts.js +5 -5
- package/dist/session/checkpoints.js +5 -0
- package/dist/session/utils.d.ts +2 -2
- package/dist/session/utils.js +6 -6
- package/dist/shared/content.d.ts +1 -1
- package/dist/shared/content.js +1 -1
- package/dist/shared/data-utils.js +1 -1
- package/dist/shared/fragment-graph.d.ts +1 -1
- package/dist/shared/fragment-graph.js +5 -5
- package/dist/shared/index.js +48 -7
- package/dist/shared/retrieval.d.ts +18 -3
- package/dist/shared/retrieval.js +101 -12
- package/dist/shared/search-fallback.js +4 -6
- package/dist/shared/sqljs.d.ts +2 -0
- package/dist/shared/sqljs.js +4 -2
- package/dist/shared.d.ts +0 -1
- package/dist/shared.js +0 -1
- package/dist/shell/input.d.ts +1 -5
- package/dist/shell/input.js +16 -10
- package/dist/shell/palette.d.ts +2 -2
- package/dist/shell/palette.js +3 -7
- package/dist/shell/render.d.ts +3 -1
- package/dist/shell/render.js +4 -4
- package/dist/shell/shell.js +4 -1
- package/dist/shell/types.d.ts +1 -0
- package/dist/shell/types.js +4 -0
- package/dist/shell/view.d.ts +0 -4
- package/dist/shell/view.js +19 -27
- package/dist/skill/registry.js +25 -17
- package/dist/skill/state.d.ts +3 -0
- package/dist/skill/state.js +13 -7
- package/dist/status.js +38 -17
- package/dist/store-registry.d.ts +44 -18
- package/dist/store-registry.js +169 -60
- package/dist/store-weight.d.ts +1 -6
- package/dist/store-weight.js +4 -2
- package/dist/sync/auth-doctor.d.ts +8 -0
- package/dist/sync/auth-doctor.js +27 -0
- package/dist/sync/auth.d.ts +27 -0
- package/dist/sync/auth.js +114 -0
- package/dist/sync/conflict-resolve.d.ts +9 -0
- package/dist/sync/conflict-resolve.js +146 -0
- package/dist/sync/git-state.d.ts +4 -0
- package/dist/sync/git-state.js +49 -0
- package/dist/sync/outcome.d.ts +34 -0
- package/dist/sync/outcome.js +57 -0
- package/dist/sync/pull.d.ts +15 -7
- package/dist/sync/pull.js +84 -35
- package/dist/sync/store-merge.d.ts +29 -0
- package/dist/sync/store-merge.js +137 -0
- package/dist/sync/task-merge.d.ts +22 -0
- package/dist/sync/task-merge.js +158 -0
- package/dist/task/github.js +1 -1
- package/dist/task/lifecycle.d.ts +5 -0
- package/dist/task/lifecycle.js +67 -23
- package/dist/terminal-text.d.ts +5 -0
- package/dist/terminal-text.js +11 -0
- package/dist/test-global-setup.js +7 -0
- package/dist/tool-registry.d.ts +1 -1
- package/dist/tool-registry.js +3 -1
- package/dist/tools/code.d.ts +3 -0
- package/dist/tools/code.js +186 -0
- package/dist/tools/config.js +8 -0
- package/dist/tools/data.js +14 -7
- package/dist/tools/dispatch.d.ts +2 -0
- package/dist/tools/dispatch.js +66 -0
- package/dist/tools/finding.d.ts +11 -0
- package/dist/tools/finding.js +180 -123
- package/dist/tools/ops.js +5 -2
- package/dist/tools/search.js +21 -8
- package/dist/tools/session.js +21 -22
- package/dist/tools/tasks.js +8 -2
- package/dist/tools/types.d.ts +2 -2
- package/dist/tools/types.js +2 -2
- package/dist/ui/assets.js +1 -1
- package/dist/ui/data.js +14 -15
- package/dist/ui/deep-void.d.ts +1 -1
- package/dist/ui/deep-void.js +0 -1
- package/dist/ui/graph-chrome.d.ts +1 -1
- package/dist/ui/graph-chrome.js +51 -0
- package/dist/ui/page.js +5 -5
- package/dist/ui/scripts.js +67 -30
- package/dist/ui/server.js +52 -7
- package/dist/update.js +22 -11
- package/dist/utils-fts.js +1 -0
- package/dist/utils-helpers.d.ts +7 -0
- package/dist/utils-helpers.js +17 -0
- package/dist/utils.d.ts +1 -1
- package/dist/utils.js +1 -1
- package/package.json +49 -7
- package/plugins/opencode/phren-transcript.js +340 -0
- package/starter/README.md +4 -4
- package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
- package/starter/global/skills/conductor/SKILL.md +106 -0
- package/starter/global/skills/fanout/SKILL.md +20 -0
- package/starter/global/skills/phren-discover/SKILL.md +6 -6
- package/starter/global/skills/phren-init/SKILL.md +4 -4
- package/starter/global/skills/phren-sync/SKILL.md +3 -3
- package/starter/templates/frontend/reference/README.md +1 -1
- package/starter/templates/library/reference/README.md +1 -1
- package/starter/templates/monorepo/reference/README.md +1 -1
- package/starter/templates/python-project/reference/README.md +1 -1
- /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import * as yaml from "js-yaml";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
|
|
7
|
+
/** The schedules.yaml store: the schedule and run record shapes, validation,
|
|
8
|
+
* the five timing forms evaluated in local time, and the run history file. */
|
|
9
|
+
export const SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
10
|
+
export const SCHEDULE_HARNESSES = ["claude", "codex", "opencode"];
|
|
11
|
+
export const SCHEDULE_NOTIFY = ["start", "finish", "failure"];
|
|
12
|
+
export const WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
13
|
+
export const SCHEDULE_RUN_STATUSES = ["launched", "running", "blocked", "finished", "needs-you", "failed", "skipped"];
|
|
14
|
+
const scheduleId = z.string().regex(/^[a-f0-9]{8}$/);
|
|
15
|
+
const plain = (max) => z.string().min(1).max(max).refine(value => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value));
|
|
16
|
+
const singleLine = (max) => z.string().min(1).max(max).refine(value => value.trim().length > 0 && !/[\x00-\x1f\x7f]/.test(value));
|
|
17
|
+
const scheduleName = singleLine(80);
|
|
18
|
+
const timestamp = z.string().datetime({ offset: true });
|
|
19
|
+
const localTimestamp = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/);
|
|
20
|
+
const clockTime = z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
|
|
21
|
+
const schedulePath = (projectDir) => path.join(projectDir, "schedules.yaml");
|
|
22
|
+
export const runningStatuses = new Set(["launched", "running", "blocked"]);
|
|
23
|
+
const MAX_SCHEDULES = 64;
|
|
24
|
+
const MAX_RUNS = 2000;
|
|
25
|
+
function validateLocalTimestamp(value) {
|
|
26
|
+
localTimestamp.parse(value);
|
|
27
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/.exec(value);
|
|
28
|
+
const parts = match.slice(1).map(Number), date = new Date(Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]));
|
|
29
|
+
if (date.getUTCFullYear() !== parts[0] || date.getUTCMonth() !== parts[1] - 1 || date.getUTCDate() !== parts[2]
|
|
30
|
+
|| date.getUTCHours() !== parts[3] || date.getUTCMinutes() !== parts[4] || date.getUTCSeconds() !== parts[5]) {
|
|
31
|
+
throw new Error(`Invalid local schedule time: ${value}`);
|
|
32
|
+
}
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
export function intervalMilliseconds(value) {
|
|
36
|
+
const match = /^(\d+)(m|h|d)$/.exec(value);
|
|
37
|
+
if (!match || Number(match[1]) < 1)
|
|
38
|
+
throw new Error("Interval must look like 30m, 6h, or 2d.");
|
|
39
|
+
const unit = match[2] === "m" ? 60_000 : match[2] === "h" ? 3_600_000 : 86_400_000;
|
|
40
|
+
const milliseconds = Number(match[1]) * unit;
|
|
41
|
+
if (!Number.isSafeInteger(milliseconds))
|
|
42
|
+
throw new Error("Schedule interval is too large.");
|
|
43
|
+
return milliseconds;
|
|
44
|
+
}
|
|
45
|
+
export function parseSchedule(value) {
|
|
46
|
+
const raw = object(value);
|
|
47
|
+
const every = z.enum(SCHEDULE_EVERY).parse(raw.every);
|
|
48
|
+
const computer = singleLine(200).parse(raw.computer);
|
|
49
|
+
if (canonicalComputer(computer) === "any")
|
|
50
|
+
throw new Error('Schedule computer "any" is not supported.');
|
|
51
|
+
const schedule = {
|
|
52
|
+
...raw,
|
|
53
|
+
id: scheduleId.parse(raw.id),
|
|
54
|
+
name: scheduleName.parse(raw.name),
|
|
55
|
+
enabled: z.boolean().parse(raw.enabled),
|
|
56
|
+
computer,
|
|
57
|
+
harness: z.enum(SCHEDULE_HARNESSES).parse(raw.harness),
|
|
58
|
+
every,
|
|
59
|
+
prompt: plain(8000).parse(raw.prompt),
|
|
60
|
+
createdAt: timestamp.parse(raw.createdAt),
|
|
61
|
+
updatedAt: timestamp.parse(raw.updatedAt),
|
|
62
|
+
};
|
|
63
|
+
if (raw.model !== undefined)
|
|
64
|
+
schedule.model = singleLine(200).parse(raw.model);
|
|
65
|
+
if (raw.notify !== undefined)
|
|
66
|
+
schedule.notify = z.array(z.enum(SCHEDULE_NOTIFY)).max(3).parse(raw.notify)
|
|
67
|
+
.filter((kind, index, kinds) => kinds.indexOf(kind) === index);
|
|
68
|
+
if (every === "daily" || every === "weekly")
|
|
69
|
+
schedule.at = clockTime.parse(raw.at);
|
|
70
|
+
if (every === "weekly")
|
|
71
|
+
schedule.days = z.array(z.enum(WEEKDAYS)).min(1).max(7).parse(raw.days).filter((day, index, days) => days.indexOf(day) === index);
|
|
72
|
+
if (every === "interval") {
|
|
73
|
+
schedule.interval = singleLine(32).parse(raw.interval);
|
|
74
|
+
intervalMilliseconds(schedule.interval);
|
|
75
|
+
}
|
|
76
|
+
if (every === "once")
|
|
77
|
+
schedule.once = validateLocalTimestamp(singleLine(32).parse(raw.once));
|
|
78
|
+
if (every === "cron") {
|
|
79
|
+
schedule.cron = singleLine(200).parse(raw.cron);
|
|
80
|
+
parseCron(schedule.cron);
|
|
81
|
+
}
|
|
82
|
+
return schedule;
|
|
83
|
+
}
|
|
84
|
+
export async function readScheduleDocument(projectDir) {
|
|
85
|
+
let text;
|
|
86
|
+
try {
|
|
87
|
+
text = await readFile(schedulePath(projectDir), "utf8");
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
if (error.code === "ENOENT")
|
|
91
|
+
return { document: { version: 1 }, schedules: [] };
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
const document = object(yaml.load(text, { schema: yaml.CORE_SCHEMA }));
|
|
95
|
+
if (document.version !== 1)
|
|
96
|
+
throw new Error("schedules.yaml must have version: 1.");
|
|
97
|
+
if (!Array.isArray(document.schedules))
|
|
98
|
+
throw new Error("schedules.yaml must contain a schedules list.");
|
|
99
|
+
if (document.schedules.length > MAX_SCHEDULES)
|
|
100
|
+
throw new Error(`A project can have at most ${MAX_SCHEDULES} schedules.`);
|
|
101
|
+
const schedules = document.schedules.map(parseSchedule);
|
|
102
|
+
if (new Set(schedules.map(item => item.id)).size !== schedules.length)
|
|
103
|
+
throw new Error("Schedule IDs must be unique within a project.");
|
|
104
|
+
return { document, schedules };
|
|
105
|
+
}
|
|
106
|
+
export async function writeScheduleDocument(projectDir, schedules, original = { version: 1 }) {
|
|
107
|
+
if (schedules.length > MAX_SCHEDULES)
|
|
108
|
+
throw new Error(`A project can have at most ${MAX_SCHEDULES} schedules.`);
|
|
109
|
+
schedules.forEach(parseSchedule);
|
|
110
|
+
const text = yaml.dump({ ...original, version: 1, schedules }, { lineWidth: 1000, noRefs: true, sortKeys: false });
|
|
111
|
+
await atomicInPrivateDir(schedulePath(projectDir), text);
|
|
112
|
+
}
|
|
113
|
+
export function canonicalComputer(value) {
|
|
114
|
+
const normalized = value.trim().toLowerCase();
|
|
115
|
+
return normalized.endsWith(".local") ? normalized.slice(0, -".local".length) : normalized;
|
|
116
|
+
}
|
|
117
|
+
export function computerMatches(wanted, current) {
|
|
118
|
+
return canonicalComputer(wanted) === canonicalComputer(current);
|
|
119
|
+
}
|
|
120
|
+
export function scheduleNotifications(schedule) {
|
|
121
|
+
return new Set(schedule.notify ?? ["finish", "failure"]);
|
|
122
|
+
}
|
|
123
|
+
export function scheduleSessionRoute(schedule, launch) {
|
|
124
|
+
if (launch.mode !== "herdr" || !launch.server || !launch.workspaceId || !launch.tabId || !launch.paneId)
|
|
125
|
+
return undefined;
|
|
126
|
+
const route = Buffer.from(JSON.stringify({ server: launch.server, workspace: launch.workspaceId, tab: launch.tabId,
|
|
127
|
+
pane: launch.paneId, source: schedule.harness })).toString("base64url");
|
|
128
|
+
return `phren://session?route=${encodeURIComponent(route)}`;
|
|
129
|
+
}
|
|
130
|
+
function parseCronField(text, minimum, maximum, sunday = false) {
|
|
131
|
+
const values = new Set(), wildcard = text === "*" || text.startsWith("*/");
|
|
132
|
+
for (const part of text.split(",")) {
|
|
133
|
+
const [rangeText, stepText] = part.split("/");
|
|
134
|
+
if (part.split("/").length > 2 || stepText !== undefined && !/^\d+$/.test(stepText))
|
|
135
|
+
throw new Error(`Invalid cron field: ${text}`);
|
|
136
|
+
const step = stepText === undefined ? 1 : Number(stepText);
|
|
137
|
+
if (step < 1)
|
|
138
|
+
throw new Error(`Invalid cron step: ${text}`);
|
|
139
|
+
let start, end;
|
|
140
|
+
if (rangeText === "*") {
|
|
141
|
+
start = minimum;
|
|
142
|
+
end = maximum;
|
|
143
|
+
}
|
|
144
|
+
else if (/^\d+$/.test(rangeText))
|
|
145
|
+
start = end = Number(rangeText);
|
|
146
|
+
else {
|
|
147
|
+
const range = /^(\d+)-(\d+)$/.exec(rangeText);
|
|
148
|
+
if (!range)
|
|
149
|
+
throw new Error(`Invalid cron field: ${text}`);
|
|
150
|
+
start = Number(range[1]);
|
|
151
|
+
end = Number(range[2]);
|
|
152
|
+
}
|
|
153
|
+
if (start < minimum || end > maximum || start > end)
|
|
154
|
+
throw new Error(`Cron field is out of range: ${text}`);
|
|
155
|
+
for (let value = start; value <= end; value += step)
|
|
156
|
+
values.add(sunday && value === 7 ? 0 : value);
|
|
157
|
+
}
|
|
158
|
+
return { values: [...values].sort((left, right) => left - right), wildcard };
|
|
159
|
+
}
|
|
160
|
+
function parseCron(value) {
|
|
161
|
+
const fields = value.trim().split(/\s+/);
|
|
162
|
+
if (fields.length !== 5)
|
|
163
|
+
throw new Error("Cron schedules need five fields.");
|
|
164
|
+
return {
|
|
165
|
+
minute: parseCronField(fields[0], 0, 59), hour: parseCronField(fields[1], 0, 23),
|
|
166
|
+
day: parseCronField(fields[2], 1, 31), month: parseCronField(fields[3], 1, 12),
|
|
167
|
+
weekday: parseCronField(fields[4], 0, 7, true),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
function cronDayMatches(cron, date) {
|
|
171
|
+
const day = cron.day.values.includes(date.getDate()), weekday = cron.weekday.values.includes(date.getDay());
|
|
172
|
+
if (cron.day.wildcard && cron.weekday.wildcard)
|
|
173
|
+
return true;
|
|
174
|
+
if (cron.day.wildcard)
|
|
175
|
+
return weekday;
|
|
176
|
+
if (cron.weekday.wildcard)
|
|
177
|
+
return day;
|
|
178
|
+
return day || weekday;
|
|
179
|
+
}
|
|
180
|
+
function nextCron(schedule, after) {
|
|
181
|
+
const cron = parseCron(schedule.cron);
|
|
182
|
+
const day = new Date(after.getFullYear(), after.getMonth(), after.getDate());
|
|
183
|
+
for (let offset = 0; offset < 366 * 8; offset++) {
|
|
184
|
+
const date = new Date(day.getFullYear(), day.getMonth(), day.getDate() + offset);
|
|
185
|
+
if (!cron.month.values.includes(date.getMonth() + 1) || !cronDayMatches(cron, date))
|
|
186
|
+
continue;
|
|
187
|
+
for (const hour of cron.hour.values)
|
|
188
|
+
for (const minute of cron.minute.values) {
|
|
189
|
+
const candidate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), hour, minute);
|
|
190
|
+
if (candidate.getHours() === hour && candidate.getMinutes() === minute && candidate > after)
|
|
191
|
+
return candidate;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
function nextDailyOrWeekly(schedule, after) {
|
|
197
|
+
const [hour, minute] = schedule.at.split(":").map(Number);
|
|
198
|
+
const allowed = schedule.every === "weekly" ? new Set(schedule.days.map(day => WEEKDAYS.indexOf(day))) : undefined;
|
|
199
|
+
for (let offset = 0; offset < 370; offset++) {
|
|
200
|
+
const candidate = new Date(after.getFullYear(), after.getMonth(), after.getDate() + offset, hour, minute);
|
|
201
|
+
if (candidate.getHours() !== hour || candidate.getMinutes() !== minute || candidate <= after)
|
|
202
|
+
continue;
|
|
203
|
+
if (!allowed || allowed.has(candidate.getDay()))
|
|
204
|
+
return candidate;
|
|
205
|
+
}
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
function localDate(value) {
|
|
209
|
+
validateLocalTimestamp(value);
|
|
210
|
+
const parts = value.match(/\d+/g).map(Number);
|
|
211
|
+
const date = new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
|
|
212
|
+
return date.getFullYear() === parts[0] && date.getMonth() === parts[1] - 1 && date.getDate() === parts[2]
|
|
213
|
+
&& date.getHours() === parts[3] && date.getMinutes() === parts[4] && date.getSeconds() === parts[5] ? date : null;
|
|
214
|
+
}
|
|
215
|
+
export function nextRun(schedule, lastRun) {
|
|
216
|
+
if (schedule.every === "once")
|
|
217
|
+
return lastRun ? null : localDate(schedule.once);
|
|
218
|
+
const after = new Date(lastRun?.startedAt ?? schedule.createdAt);
|
|
219
|
+
if (!Number.isFinite(after.getTime()))
|
|
220
|
+
return null;
|
|
221
|
+
if (schedule.every === "interval")
|
|
222
|
+
return new Date(after.getTime() + intervalMilliseconds(schedule.interval));
|
|
223
|
+
if (schedule.every === "cron")
|
|
224
|
+
return nextCron(schedule, after);
|
|
225
|
+
return nextDailyOrWeekly(schedule, after);
|
|
226
|
+
}
|
|
227
|
+
export async function readScheduleRuns(file) {
|
|
228
|
+
let text;
|
|
229
|
+
try {
|
|
230
|
+
text = await readFile(file, "utf8");
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
if (error.code === "ENOENT")
|
|
234
|
+
return [];
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
const runs = [];
|
|
238
|
+
for (const line of text.split("\n")) {
|
|
239
|
+
if (!line.trim())
|
|
240
|
+
continue;
|
|
241
|
+
try {
|
|
242
|
+
const raw = object(JSON.parse(line));
|
|
243
|
+
const launch = object(raw.launch);
|
|
244
|
+
if (typeof raw.id !== "string" || typeof raw.scheduleId !== "string" || typeof raw.project !== "string"
|
|
245
|
+
|| typeof raw.startedAt !== "string" || !SCHEDULE_RUN_STATUSES.includes(String(raw.status))
|
|
246
|
+
|| !["herdr", "headless"].includes(String(launch.mode)))
|
|
247
|
+
continue;
|
|
248
|
+
runs.push(raw);
|
|
249
|
+
}
|
|
250
|
+
catch { /* A torn final line does not hide older history. */ }
|
|
251
|
+
}
|
|
252
|
+
return runs;
|
|
253
|
+
}
|
|
254
|
+
export async function writeScheduleRuns(file, runs) {
|
|
255
|
+
const kept = runs.slice(-MAX_RUNS);
|
|
256
|
+
await atomicInPrivateDir(file, kept.map(run => JSON.stringify(run)).join("\n") + (kept.length ? "\n" : ""));
|
|
257
|
+
}
|
|
258
|
+
export function newScheduleId(existing) {
|
|
259
|
+
const ids = new Set(existing);
|
|
260
|
+
for (;;) {
|
|
261
|
+
const id = randomBytes(4).toString("hex");
|
|
262
|
+
if (!ids.has(id))
|
|
263
|
+
return id;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
export function scheduleRunsFile() { return path.join(bridgeRoot(), "schedule-runs.jsonl"); }
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Json } from "./protocol.js";
|
|
2
|
+
import type { Schedule, ScheduleLauncher } from "./schedule-format.js";
|
|
3
|
+
type HerdrLauncher = (server: string, data: Json) => Promise<Json>;
|
|
4
|
+
export declare function createScheduleLauncher(launchHerdr: HerdrLauncher, store?: string): ScheduleLauncher;
|
|
5
|
+
export declare function headlessCommand(schedule: Schedule, cwd: string): {
|
|
6
|
+
file: string;
|
|
7
|
+
args: string[];
|
|
8
|
+
cwd: string;
|
|
9
|
+
};
|
|
10
|
+
export declare function ensureCodexDirTrusted(cwd: string): Promise<void>;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createWriteStream } from "node:fs";
|
|
3
|
+
import { mkdir, readFile, stat } from "node:fs/promises";
|
|
4
|
+
import { codexHome } from "../home-paths.js";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { finished as streamFinished } from "node:stream/promises";
|
|
7
|
+
import { fanoutRoot } from "./fanouts.js";
|
|
8
|
+
import { findPane, paneIdentity, rpc, servers, snapshot } from "./herdr.js";
|
|
9
|
+
import { atomic, atomicInPrivateDir, BridgeError } from "./protocol.js";
|
|
10
|
+
import { logger } from "../logger.js";
|
|
11
|
+
import { defaultPhrenPath } from "../shared.js";
|
|
12
|
+
import { watchHerdrRun } from "./schedule-watch.js";
|
|
13
|
+
/** Starting a scheduled run: in a Herdr pane when a server is live, otherwise
|
|
14
|
+
* as a headless job under the fan-out root. */
|
|
15
|
+
const CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
|
|
16
|
+
export function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
|
|
17
|
+
const abort = new AbortController(), children = new Set();
|
|
18
|
+
const launcher = async (context) => {
|
|
19
|
+
const live = await servers();
|
|
20
|
+
if (live.length)
|
|
21
|
+
return launchInHerdr(String(live[0].session), context, launchHerdr, abort.signal);
|
|
22
|
+
return launchHeadless(context, store, child => { children.add(child); child.once("exit", () => children.delete(child)); });
|
|
23
|
+
};
|
|
24
|
+
launcher.close = () => { abort.abort(); for (const child of children)
|
|
25
|
+
child.kill("SIGTERM"); children.clear(); };
|
|
26
|
+
return launcher;
|
|
27
|
+
}
|
|
28
|
+
async function launchInHerdr(server, context, launchHerdr, signal) {
|
|
29
|
+
const launched = await launchHerdr(server, { cwd: context.cwd, label: context.schedule.name, kind: context.schedule.harness, model: context.schedule.model });
|
|
30
|
+
const workspaceId = String(launched.workspaceId), tabId = String(launched.tabId), paneId = String(launched.paneId);
|
|
31
|
+
await promptWhenReady(server, paneId, context.schedule.prompt, signal);
|
|
32
|
+
let sessionId = typeof launched.sessionId === "string" ? launched.sessionId : undefined;
|
|
33
|
+
for (let attempt = 0; attempt < 10 && !sessionId; attempt++) {
|
|
34
|
+
const pane = findPane(await snapshot(server), { workspace: workspaceId, tab: tabId, pane: paneId });
|
|
35
|
+
if (pane)
|
|
36
|
+
sessionId = await paneIdentity(server, pane).catch(() => undefined);
|
|
37
|
+
if (!sessionId)
|
|
38
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
39
|
+
}
|
|
40
|
+
const launch = { mode: "herdr", server, workspaceId, tabId, paneId,
|
|
41
|
+
...(sessionId ? { sessionId } : {}) };
|
|
42
|
+
return { launch, completion: watchHerdrRun(server, { workspaceId, tabId, paneId }, signal, { source: context.schedule.harness, startedAt: Date.now(), sessionId, onBlocked: context.blockedStartup }) };
|
|
43
|
+
}
|
|
44
|
+
/** Herdr refuses a prompt until the agent has finished starting; a run
|
|
45
|
+
* launched a moment ago waits for it rather than failing on the first try. */
|
|
46
|
+
async function promptWhenReady(server, paneId, text, signal, waitMs = 60_000) {
|
|
47
|
+
const deadline = Date.now() + waitMs;
|
|
48
|
+
for (;;) {
|
|
49
|
+
try {
|
|
50
|
+
await rpc(server, "agent.prompt", { target: paneId, text }, signal);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
const starting = error instanceof BridgeError && error.details?.herdrCode === "agent_not_ready";
|
|
55
|
+
if (!starting || signal.aborted)
|
|
56
|
+
throw error;
|
|
57
|
+
if (Date.now() >= deadline)
|
|
58
|
+
throw new BridgeError(409, `The agent in ${paneId} never became ready for the prompt; it may be waiting at a startup screen on the computer.`);
|
|
59
|
+
await new Promise(resolve => setTimeout(resolve, 1_000));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async function launchHeadless(context, store, started) {
|
|
64
|
+
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path.join(root, context.runId);
|
|
65
|
+
await mkdir(jobDir, { recursive: true, mode: 0o700 });
|
|
66
|
+
const eventLog = "events.jsonl", now = new Date().toISOString();
|
|
67
|
+
const manifest = { schemaVersion: 1, id: context.runId, provider: context.schedule.harness,
|
|
68
|
+
taskLabel: context.schedule.name, cwd: context.cwd, worktree: context.cwd, ...(context.schedule.model ? { model: context.schedule.model } : {}),
|
|
69
|
+
eventLog, createdAt: now, startedAt: now, updatedAt: now, status: "queued", schedule: { id: context.schedule.id, project: context.project } };
|
|
70
|
+
await writeManifest(jobDir, manifest);
|
|
71
|
+
const command = headlessCommand(context.schedule, context.cwd);
|
|
72
|
+
// An untrusted directory only costs Codex a prompt; the run still starts, and the log says why.
|
|
73
|
+
if (context.schedule.harness === "codex")
|
|
74
|
+
await ensureCodexDirTrusted(context.cwd).catch(error => logger.warn("schedule", `Could not mark ${path.basename(context.cwd)} trusted for Codex (run ${context.runId}): ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`));
|
|
75
|
+
let child;
|
|
76
|
+
try {
|
|
77
|
+
child = spawn(command.file, command.args, { cwd: command.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
await writeManifest(jobDir, { ...manifest, status: "failed", updatedAt: new Date().toISOString(), finishedAt: new Date().toISOString() });
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
started(child);
|
|
84
|
+
const closed = new Promise(resolve => {
|
|
85
|
+
child.once("close", (code, signal) => resolve({ code, signal }));
|
|
86
|
+
});
|
|
87
|
+
const output = createWriteStream(path.join(jobDir, eventLog), { flags: "a", mode: 0o600 });
|
|
88
|
+
const errors = createWriteStream(path.join(jobDir, "stderr.log"), { flags: "a", mode: 0o600 });
|
|
89
|
+
const streamsFinished = Promise.all([streamFinished(output), streamFinished(errors)]).then(() => undefined).catch(() => undefined);
|
|
90
|
+
child.stdin?.on("error", () => { });
|
|
91
|
+
child.stdout?.pipe(output);
|
|
92
|
+
child.stderr?.pipe(errors);
|
|
93
|
+
child.stdin?.end(context.schedule.prompt);
|
|
94
|
+
await new Promise((resolve, reject) => {
|
|
95
|
+
child.once("spawn", resolve);
|
|
96
|
+
child.once("error", reject);
|
|
97
|
+
}).catch(async (error) => {
|
|
98
|
+
output.end();
|
|
99
|
+
errors.end();
|
|
100
|
+
await writeManifest(jobDir, { ...manifest, status: "failed", updatedAt: new Date().toISOString(), finishedAt: new Date().toISOString() });
|
|
101
|
+
throw error;
|
|
102
|
+
});
|
|
103
|
+
await writeManifest(jobDir, { ...manifest, status: "running", updatedAt: new Date().toISOString() });
|
|
104
|
+
const completion = closed.then(async ({ code, signal }) => {
|
|
105
|
+
await streamsFinished;
|
|
106
|
+
const finishedAt = new Date().toISOString(), ok = code === 0;
|
|
107
|
+
await writeManifest(jobDir, { ...manifest, status: ok ? "completed" : "failed", updatedAt: finishedAt, finishedAt,
|
|
108
|
+
...(typeof code === "number" ? { exitCode: code } : {}) }).catch(() => { });
|
|
109
|
+
return ok ? { status: "finished" } : { status: "failed", reason: signal ? `The scheduled agent exited after ${signal}.` : `The scheduled agent exited with code ${code ?? "unknown"}.` };
|
|
110
|
+
});
|
|
111
|
+
return { launch: { mode: "headless", jobDir }, completion };
|
|
112
|
+
}
|
|
113
|
+
export function headlessCommand(schedule, cwd) {
|
|
114
|
+
const model = schedule.model ? ["--model", schedule.model] : [];
|
|
115
|
+
if (schedule.harness === "codex")
|
|
116
|
+
return { file: "codex", cwd, args: ["exec", ...model, "--sandbox", "workspace-write", "-C", cwd,
|
|
117
|
+
"--skip-git-repo-check", "--json", "-"] };
|
|
118
|
+
if (schedule.harness === "opencode")
|
|
119
|
+
return { file: "opencode", cwd, args: ["run", "--format", "json", "--dir", cwd, ...model] };
|
|
120
|
+
return { file: "claude", cwd, args: ["-p", "--output-format", "stream-json", "--settings", CLAUDE_SCHEDULE_SETTINGS, ...model] };
|
|
121
|
+
}
|
|
122
|
+
function tomlQuote(value) {
|
|
123
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
124
|
+
}
|
|
125
|
+
export async function ensureCodexDirTrusted(cwd) {
|
|
126
|
+
const directory = codexHome();
|
|
127
|
+
const file = path.join(directory, "config.toml");
|
|
128
|
+
let text = "";
|
|
129
|
+
try {
|
|
130
|
+
text = await readFile(file, "utf8");
|
|
131
|
+
}
|
|
132
|
+
// An unreadable config is left untouched; the caller logs why.
|
|
133
|
+
catch (error) {
|
|
134
|
+
if (error.code !== "ENOENT")
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
const header = `[projects.${tomlQuote(cwd)}]`;
|
|
138
|
+
const trustLine = 'trust_level = "trusted"';
|
|
139
|
+
let next;
|
|
140
|
+
const at = text.indexOf(header);
|
|
141
|
+
if (at >= 0) {
|
|
142
|
+
const bodyStart = at + header.length;
|
|
143
|
+
const rest = text.slice(bodyStart);
|
|
144
|
+
const nextTable = rest.search(/^\s*\[/m);
|
|
145
|
+
const section = nextTable >= 0 ? rest.slice(0, nextTable) : rest;
|
|
146
|
+
if (new RegExp(`trust_level\\s*=\\s*"trusted"`).test(section))
|
|
147
|
+
return;
|
|
148
|
+
const existing = /^[ \t]*trust_level\s*=.*$/m.exec(section);
|
|
149
|
+
if (existing) {
|
|
150
|
+
const replaced = section.replace(existing[0], existing[0].match(/^[ \t]*/)[0] + trustLine);
|
|
151
|
+
next = text.slice(0, bodyStart) + replaced + rest.slice(section.length);
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
const newline = section.startsWith("\n") || section.startsWith("\r\n") ? "" : "\n";
|
|
155
|
+
next = text.slice(0, bodyStart) + newline + trustLine + (section.startsWith("\n") || section.startsWith("\r\n") ? section : "\n" + section) + rest.slice(section.length);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
const separator = text && !text.endsWith("\n") ? "\n\n" : text ? "\n" : "";
|
|
160
|
+
next = text + `${separator}${header}\n${trustLine}\n`;
|
|
161
|
+
}
|
|
162
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
163
|
+
const metadata = await stat(file).catch(() => undefined);
|
|
164
|
+
const mode = metadata ? metadata.mode & 0o777 : 0o600;
|
|
165
|
+
await atomic(file, next, mode);
|
|
166
|
+
}
|
|
167
|
+
async function writeManifest(jobDir, manifest) {
|
|
168
|
+
await atomicInPrivateDir(path.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
|
169
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type Json, type Provider } from "./protocol.js";
|
|
2
|
+
import type { ScheduleHarness, ScheduleRunOutcome } from "./schedule-format.js";
|
|
3
|
+
/** Watching a scheduled run in its Herdr pane: how it ended, whether the final
|
|
4
|
+
* reply asks the owner something, and a startup screen that blocked it. */
|
|
5
|
+
export declare const STARTUP_BLOCK_WINDOW_MS = 90000;
|
|
6
|
+
export declare const STARTUP_BLOCK_WINDOW_OPEN_MS = 5000;
|
|
7
|
+
export declare function classifyStartupBlock(input: {
|
|
8
|
+
elapsedMs: number;
|
|
9
|
+
transcriptActive: boolean;
|
|
10
|
+
status: unknown;
|
|
11
|
+
lines: readonly string[];
|
|
12
|
+
}): string | undefined;
|
|
13
|
+
/** The watch loop's own words for a failure, instead of assuming Herdr went away. */
|
|
14
|
+
export declare function watchFailureReason(error: unknown): string;
|
|
15
|
+
interface StartupWatch {
|
|
16
|
+
source: ScheduleHarness;
|
|
17
|
+
startedAt: number;
|
|
18
|
+
sessionId?: string;
|
|
19
|
+
onBlocked?: (promptText: string) => void | Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
export interface StartupWatchEnv {
|
|
22
|
+
now?: () => number;
|
|
23
|
+
pause?: (ms: number) => Promise<void>;
|
|
24
|
+
readPane?: (server: string, paneId: string) => Promise<string[]>;
|
|
25
|
+
resolveSession?: (server: string, pane: Json) => Promise<string | undefined>;
|
|
26
|
+
transcriptStamp?: (source: ScheduleHarness, sessionId: string | undefined) => Promise<{
|
|
27
|
+
size: number;
|
|
28
|
+
mtimeMs: number;
|
|
29
|
+
} | undefined>;
|
|
30
|
+
panes?: (server: string) => Promise<Json[]>;
|
|
31
|
+
finalTurn?: (source: ScheduleHarness, sessionId: string | undefined) => Promise<FinalTurn | undefined>;
|
|
32
|
+
}
|
|
33
|
+
/** `error`: the harness ended the turn on an error (Codex's usage limit) instead of a reply. */
|
|
34
|
+
export interface FinalTurn {
|
|
35
|
+
completed: boolean;
|
|
36
|
+
lastAssistant?: string;
|
|
37
|
+
error?: string;
|
|
38
|
+
}
|
|
39
|
+
/** The public text of one assistant row, without reasoning or tool output. */
|
|
40
|
+
export declare function publicAssistant(raw: Json, source: Provider): string | undefined;
|
|
41
|
+
/** The last assistant reply in a transcript and whether its turn finished.
|
|
42
|
+
* A person's message after the reply opens a new turn, so it clears both. */
|
|
43
|
+
export declare function finalTurnFromLines(lines: readonly string[], source: ScheduleHarness): FinalTurn;
|
|
44
|
+
/** The final turn of a conversation, read from the tail of its transcript. */
|
|
45
|
+
export declare function readFinalTurn(source: ScheduleHarness, sessionId: string | undefined): Promise<FinalTurn | undefined>;
|
|
46
|
+
/** When a finished reply ends by asking the owner something (a question, or
|
|
47
|
+
* numbered options introduced as a choice), the question's first line. */
|
|
48
|
+
export declare function ownerQuestion(text: string): string | undefined;
|
|
49
|
+
export declare function watchHerdrRun(server: string, target: {
|
|
50
|
+
workspaceId: string;
|
|
51
|
+
tabId: string;
|
|
52
|
+
paneId: string;
|
|
53
|
+
}, signal: AbortSignal, startup: StartupWatch, env?: StartupWatchEnv): Promise<ScheduleRunOutcome>;
|
|
54
|
+
export {};
|