@luminascale/shepherd 0.0.0-stage → 0.6.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/.agents/agents/README.md +12 -0
- package/.agents/agents/planner.md +38 -0
- package/.agents/agents/reviewer.md +38 -0
- package/.agents/agents/scout.md +43 -0
- package/.agents/agents/worker.md +33 -0
- package/.agents/skills/smoke-test/SKILL.md +155 -0
- package/.agents/skills/smoke-test/references/forensics.md +46 -0
- package/.agents/skills/smoke-test/scripts/live-smoke-poll.mjs +130 -0
- package/.github/workflows/publish.yml +77 -0
- package/.pi/prompts/release.md +21 -0
- package/.prettierrc +10 -0
- package/AGENTS.md +88 -0
- package/CONTRIBUTING.md +177 -0
- package/LICENSE +201 -0
- package/README.md +424 -2
- package/docs/README.md +25 -0
- package/docs/guides/agent-definitions.md +42 -0
- package/docs/guides/diagnostics.md +199 -0
- package/docs/guides/tool-reference.md +55 -0
- package/docs/manual-tests/ping-pong-peer-messaging.md +147 -0
- package/docs/plans/agent-labels.md +257 -0
- package/docs/plans/architecture.md +110 -0
- package/docs/plans/settings-scope.md +163 -0
- package/docs/plans/tool-surface-split.md +278 -0
- package/docs/reference/dictionary +26 -0
- package/docs/releasing.md +47 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/baseline.md +115 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/handoff.md +564 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase10-notes.md +109 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase6-notes.md +69 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase7-notes.md +100 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase8-notes.md +127 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase9-notes.md +104 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/plan.md +1093 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/spec.md +583 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/tasks.md +838 -0
- package/docs/specs/006-shepherd-tool-rendering/plan.md +175 -0
- package/docs/specs/006-shepherd-tool-rendering/spec.md +469 -0
- package/index.ts +599 -0
- package/package.json +112 -4
- package/scripts/capture-system-prompt.mjs +45 -0
- package/scripts/extract-pi-system-prompt.mjs +277 -0
- package/scripts/host-impact.mjs +74 -0
- package/scripts/resolve-agent.mjs +43 -0
- package/scripts/show-shepherd-orchestrator.mjs +58 -0
- package/scripts/show-shepherd-prompt.mjs +96 -0
- package/scripts/verify-suites.mjs +67 -0
- package/specs/001-artifacts/spec.md +436 -0
- package/specs/002-simplify-agent-orchestration/plan.md +287 -0
- package/specs/002-simplify-agent-orchestration/spec.md +323 -0
- package/specs/002-simplify-agent-orchestration/tasks.md +212 -0
- package/specs/003-orchestrator-session-artifacts/plan.md +396 -0
- package/specs/003-orchestrator-session-artifacts/spec.md +453 -0
- package/specs/003-orchestrator-session-artifacts/tasks.md +141 -0
- package/specs/004-asynchronous-prompt-watchers/plan.md +139 -0
- package/specs/004-asynchronous-prompt-watchers/spec.md +202 -0
- package/specs/004-asynchronous-prompt-watchers/tasks.md +126 -0
- package/specs/005-per-workspace-settings/plan.md +230 -0
- package/specs/005-per-workspace-settings/spec.md +368 -0
- package/specs/005-per-workspace-settings/tasks.md +178 -0
- package/specs/006-dual-runtime-herdr-durable/intent.md +86 -0
- package/specs/006-dual-runtime-herdr-durable/journal.md +80 -0
- package/specs/006-dual-runtime-herdr-durable/plan.md +242 -0
- package/specs/006-dual-runtime-herdr-durable/spec.md +389 -0
- package/specs/006-dual-runtime-herdr-durable/tasks.md +199 -0
- package/specs/007-unwatched-completion-notice/journal.md +145 -0
- package/specs/007-unwatched-completion-notice/plan.md +186 -0
- package/specs/007-unwatched-completion-notice/spec.md +284 -0
- package/specs/007-unwatched-completion-notice/tasks.md +147 -0
- package/specs/008-remote-machine-sheep/intent.md +174 -0
- package/specs/008-remote-machine-sheep/journal.md +57 -0
- package/specs/008-remote-machine-sheep/prerequisites.md +219 -0
- package/specs/009-hc-runtime/intent.md +44 -0
- package/specs/009-hc-runtime/plan.md +49 -0
- package/specs/009-hc-runtime/spec.md +118 -0
- package/specs/009-hc-runtime/tasks.md +62 -0
- package/specs/010-unseen-watch-parity/intent.md +57 -0
- package/specs/010-unseen-watch-parity/journal.md +172 -0
- package/specs/010-unseen-watch-parity/plan.md +74 -0
- package/specs/010-unseen-watch-parity/spec.md +191 -0
- package/specs/010-unseen-watch-parity/tasks.md +119 -0
- package/specs/011-hc-background-poll/intent.md +57 -0
- package/specs/011-hc-background-poll/journal.md +95 -0
- package/specs/011-hc-background-poll/plan.md +87 -0
- package/specs/011-hc-background-poll/spec.md +141 -0
- package/specs/011-hc-background-poll/tasks.md +83 -0
- package/specs/012-steer-default/intent.md +12 -0
- package/specs/012-steer-default/journal.md +40 -0
- package/specs/012-steer-default/plan.md +7 -0
- package/specs/012-steer-default/spec.md +42 -0
- package/specs/012-steer-default/tasks.md +6 -0
- package/specs/013-opencode-shepherd/handoff-t011.md +94 -0
- package/specs/013-opencode-shepherd/intent.md +59 -0
- package/specs/013-opencode-shepherd/plan.md +204 -0
- package/specs/013-opencode-shepherd/spec.md +258 -0
- package/specs/013-opencode-shepherd/tasks.md +259 -0
- package/src/core/artifact-sessions.ts +835 -0
- package/src/core/config.ts +329 -0
- package/src/core/discovery.ts +342 -0
- package/src/core/herdr.ts +1 -0
- package/src/core/host.ts +77 -0
- package/src/core/ids.ts +78 -0
- package/src/core/lifecycle.ts +1 -0
- package/src/core/messaging.ts +1 -0
- package/src/core/migration.ts +55 -0
- package/src/core/orchestration.ts +1 -0
- package/src/core/types.ts +143 -0
- package/src/core/unseen-completions.ts +114 -0
- package/src/extension/cli.ts +417 -0
- package/src/extension/config.ts +1 -0
- package/src/extension/settings-ui.ts +296 -0
- package/src/extension/shepherd-done.ts +768 -0
- package/src/extension/shepherd.ts +2548 -0
- package/src/extension/system-prompt.ts +38 -0
- package/src/extension/unseen-completions.ts +237 -0
- package/src/opencode/actions.ts +794 -0
- package/src/opencode/bridge.ts +777 -0
- package/src/opencode/display.ts +36 -0
- package/src/opencode/fieldnotes.ts +60 -0
- package/src/opencode/host.ts +62 -0
- package/src/opencode/orphans.ts +162 -0
- package/src/opencode/server.ts +458 -0
- package/src/runtimes/backend.ts +119 -0
- package/src/runtimes/detect.ts +102 -0
- package/src/runtimes/hc/hc.ts +527 -0
- package/src/runtimes/hc/runtime.ts +1898 -0
- package/src/runtimes/herdr/herdr.ts +912 -0
- package/src/runtimes/herdr/lifecycle.ts +1712 -0
- package/src/runtimes/herdr/messaging.ts +703 -0
- package/src/runtimes/herdr/orchestration.ts +1583 -0
- package/src/runtimes/herdr/runtime.ts +224 -0
- package/src/runtimes/runtime.ts +133 -0
- package/src/runtimes/settle-observations.ts +114 -0
- package/test/fixtures/context-project/AGENTS.md +2 -0
- package/test/fixtures/home/.agents/agents/same.md +6 -0
- package/test/fixtures/home/.agents/agents/shared-only.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/invalid-thinking.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/model-empty.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/model-explicit.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-absent.md +5 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-false.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-invalid.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-true.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-false.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-invalid.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-pi-docs.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/omit-true.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/only-user.md +9 -0
- package/test/fixtures/home/.pi/agent/agents/same.md +6 -0
- package/test/fixtures/proj/.agents/agents/proj-shared.md +6 -0
- package/test/fixtures/proj/.pi/agents/project-pi.md +6 -0
- package/test/fixtures/proj/.pi/agents/same.md +6 -0
- package/test/helpers/fake-clock.mjs +39 -0
- package/test/helpers/feature-contracts.mjs +44 -0
- package/test/helpers/test-utils.mjs +44 -0
- package/test/verify-artifact-sessions.mjs +258 -0
- package/test/verify-backend.mjs +297 -0
- package/test/verify-child-mislabel.mjs +135 -0
- package/test/verify-child-surface.mjs +321 -0
- package/test/verify-cli.mjs +197 -0
- package/test/verify-command-ux.mjs +100 -0
- package/test/verify-compat.mjs +32 -0
- package/test/verify-cross-host-notes.mjs +128 -0
- package/test/verify-delegate.mjs +161 -0
- package/test/verify-detect.mjs +151 -0
- package/test/verify-discovery.mjs +239 -0
- package/test/verify-done-nudge.mjs +238 -0
- package/test/verify-effective-prompt.mjs +98 -0
- package/test/verify-hc-matrix.mjs +246 -0
- package/test/verify-hc-poll.mjs +260 -0
- package/test/verify-host-docs.mjs +35 -0
- package/test/verify-host-impact.mjs +49 -0
- package/test/verify-ids.mjs +141 -0
- package/test/verify-launch.mjs +183 -0
- package/test/verify-message-routing.mjs +560 -0
- package/test/verify-messaging.mjs +303 -0
- package/test/verify-migration-notice.mjs +69 -0
- package/test/verify-multi-wait.mjs +42 -0
- package/test/verify-opencode-display.mjs +47 -0
- package/test/verify-opencode-fieldnotes.mjs +121 -0
- package/test/verify-opencode-notice.mjs +77 -0
- package/test/verify-opencode-nudge.mjs +116 -0
- package/test/verify-opencode-orphans.mjs +160 -0
- package/test/verify-opencode-surface.mjs +107 -0
- package/test/verify-packaging.mjs +82 -0
- package/test/verify-parent-surface.mjs +118 -0
- package/test/verify-phase0.mjs +95 -0
- package/test/verify-registry.mjs +124 -0
- package/test/verify-rename-migration.mjs +111 -0
- package/test/verify-rendering.mjs +379 -0
- package/test/verify-session-boundary.mjs +146 -0
- package/test/verify-settings.mjs +260 -0
- package/test/verify-stale-wait.mjs +339 -0
- package/test/verify-status-widget.mjs +377 -0
- package/test/verify-status.mjs +172 -0
- package/test/verify-task-completion.mjs +156 -0
- package/test/verify-task-failures.mjs +201 -0
- package/test/verify-task-mislabel.mjs +143 -0
- package/test/verify-task-registry.mjs +194 -0
- package/test/verify-task-watchers.mjs +217 -0
- package/test/verify-tool-schemas.mjs +120 -0
- package/test/verify-unseen-completions.mjs +1211 -0
- package/test/verify-watchers.mjs +181 -0
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hc runtime — herdr-core terminal integration for pi-shepherd.
|
|
3
|
+
*
|
|
4
|
+
* Shells out to the `hc` CLI (no JS library) and provides the building blocks
|
|
5
|
+
* the hc backend depends on: the availability guard (`isHcAvailable`), the
|
|
6
|
+
* JSON exec bridges (`hcExec` / `hcExecSync`), the created-terminals registry
|
|
7
|
+
* (`recordCreatedTerminal` / `pruneStaleCreatedTerminals`), the launch-script
|
|
8
|
+
* runner (`launchPiInHcTerminal`), and the terminal tail reader
|
|
9
|
+
* (`readHcTerminalTail`).
|
|
10
|
+
*
|
|
11
|
+
* This module mirrors `src/runtimes/herdr/herdr.ts` ownership/launch/read
|
|
12
|
+
* patterns: background terminals, cwd preservation, only-close-what-we-created
|
|
13
|
+
* (registry file beside `created-panes.json`), temp launch-dir lifetime tied
|
|
14
|
+
* to the owned terminal, and never `hc server stop` from a live session.
|
|
15
|
+
*
|
|
16
|
+
* Transport-independent helpers owned by the pane-based backend are reused
|
|
17
|
+
* here (launch-file writer, completion-signal readers, filesystem mailbox)
|
|
18
|
+
* so the two runtimes stay boring and identical where the substrate does not
|
|
19
|
+
* matter. `runtime.ts` imports them through this module and never touches the
|
|
20
|
+
* pane-based backend directly.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { execFile, execFileSync } from 'node:child_process';
|
|
24
|
+
import * as fs from 'node:fs';
|
|
25
|
+
import * as os from 'node:os';
|
|
26
|
+
import * as path from 'node:path';
|
|
27
|
+
import { promisify } from 'node:util';
|
|
28
|
+
import { hostCapabilities } from '../../core/host.ts';
|
|
29
|
+
import { sessionOwner } from '../herdr/orchestration.ts';
|
|
30
|
+
import {
|
|
31
|
+
readCompletionSignal,
|
|
32
|
+
readLastAssistantText,
|
|
33
|
+
writePiLaunchFiles,
|
|
34
|
+
} from '../herdr/herdr.ts';
|
|
35
|
+
|
|
36
|
+
// ── Reused transport-independent helpers ───────────────────────────────
|
|
37
|
+
// The launch-file writer, the completion-signal readers, and the parent-owned
|
|
38
|
+
// filesystem mailbox do not depend on panes or terminals; both backends share
|
|
39
|
+
// them so agent launch, completion detection, and `shepherd_done` behave the
|
|
40
|
+
// same everywhere. Re-exported here so `runtime.ts` stays free of any
|
|
41
|
+
// pane-backend import.
|
|
42
|
+
export { readCompletionSignal, readLastAssistantText, writePiLaunchFiles };
|
|
43
|
+
export {
|
|
44
|
+
createChildBroker,
|
|
45
|
+
createEnvelope,
|
|
46
|
+
createParentBroker,
|
|
47
|
+
pollParentInbox,
|
|
48
|
+
publishFromParent,
|
|
49
|
+
registerChild,
|
|
50
|
+
unregisterChild,
|
|
51
|
+
type ChildCapability,
|
|
52
|
+
type ParentBroker,
|
|
53
|
+
type ShepherdMessageEnvelope,
|
|
54
|
+
} from '../herdr/messaging.ts';
|
|
55
|
+
|
|
56
|
+
const execFileAsync = promisify(execFile);
|
|
57
|
+
|
|
58
|
+
export const HC_SETUP_HINT =
|
|
59
|
+
'Run from an `hc` terminal (HC_TERMINAL_ID and HC_TERMINAL_SOCKET set) with `hc` on PATH, or ensure the herdr-core server is reachable.';
|
|
60
|
+
|
|
61
|
+
/** Structured `hc` failure: the CLI exits 0 with `{ error: { kind, message } }`. */
|
|
62
|
+
export class HcError extends Error {
|
|
63
|
+
readonly kind: string;
|
|
64
|
+
readonly hint?: string;
|
|
65
|
+
constructor(kind: string, message: string, hint?: string) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.name = 'HcError';
|
|
68
|
+
this.kind = kind;
|
|
69
|
+
if (hint !== undefined) this.hint = hint;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Extract a structured `HcError` from raw CLI stdout, if it carries `{ error }`. */
|
|
74
|
+
function hcErrorFromStdout(stdout: unknown, context: string): HcError | undefined {
|
|
75
|
+
if (typeof stdout !== 'string' || !stdout.trim()) return undefined;
|
|
76
|
+
let parsed: unknown;
|
|
77
|
+
try {
|
|
78
|
+
parsed = JSON.parse(stdout);
|
|
79
|
+
} catch {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
const err = (parsed as { error?: { kind?: unknown; message?: unknown; hint?: unknown } })?.error;
|
|
83
|
+
if (!err || typeof err !== 'object') return undefined;
|
|
84
|
+
const kind = typeof err.kind === 'string' ? err.kind : 'hc_error';
|
|
85
|
+
const message = typeof err.message === 'string' ? err.message : `hc ${context} failed.`;
|
|
86
|
+
const hint = typeof err.hint === 'string' ? err.hint : undefined;
|
|
87
|
+
return new HcError(kind, `hc ${context} failed: ${message}`, hint);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function throwOnHcError(output: unknown, context: string): unknown {
|
|
91
|
+
const err = (output as { error?: { kind?: unknown; message?: unknown; hint?: unknown } })
|
|
92
|
+
?.error;
|
|
93
|
+
if (err && typeof err === 'object') {
|
|
94
|
+
const kind = typeof err.kind === 'string' ? err.kind : 'hc_error';
|
|
95
|
+
const message = typeof err.message === 'string' ? err.message : `hc ${context} failed.`;
|
|
96
|
+
const hint = typeof err.hint === 'string' ? err.hint : undefined;
|
|
97
|
+
throw new HcError(kind, `hc ${context} failed: ${message}`, hint);
|
|
98
|
+
}
|
|
99
|
+
return output;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** True when the `hc` binary is on PATH. */
|
|
103
|
+
export function isHcCliPresent(): boolean {
|
|
104
|
+
try {
|
|
105
|
+
execFileSync('hc', ['--version'], { stdio: 'ignore', timeout: 3000 });
|
|
106
|
+
return true;
|
|
107
|
+
} catch {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* True when the herdr-core server is reachable: the CLI is present and
|
|
114
|
+
* `hc ls` succeeds. Like the pane-based guard, a plain terminal can drive
|
|
115
|
+
* `hc` when the server is up — no HC_* env required here (detection of the
|
|
116
|
+
* caller lives in `src/runtimes/detect.ts`).
|
|
117
|
+
*/
|
|
118
|
+
export function isHcAvailable(): boolean {
|
|
119
|
+
if (!isHcCliPresent()) return false;
|
|
120
|
+
try {
|
|
121
|
+
throwOnHcError(hcExecSync(['ls', '--json']), 'ls');
|
|
122
|
+
return true;
|
|
123
|
+
} catch {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Run an `hc` subcommand synchronously and parse its JSON output. Callers
|
|
130
|
+
* pass `--json` explicitly (run/read print text even when piped). A response
|
|
131
|
+
* body carrying `{ error }` throws `HcError`.
|
|
132
|
+
*/
|
|
133
|
+
export function hcExecSync(args: string[]): unknown {
|
|
134
|
+
let stdout: string;
|
|
135
|
+
try {
|
|
136
|
+
stdout = execFileSync('hc', args, {
|
|
137
|
+
encoding: 'utf8',
|
|
138
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
139
|
+
});
|
|
140
|
+
} catch (error: any) {
|
|
141
|
+
const out = typeof error?.stdout === 'string' ? error.stdout : (error?.stdout?.toString?.() ?? '');
|
|
142
|
+
const errOut =
|
|
143
|
+
typeof error?.stderr === 'string' ? error.stderr : (error?.stderr?.toString?.() ?? '');
|
|
144
|
+
const structured =
|
|
145
|
+
hcErrorFromStdout(out, args[0] ?? '') ?? hcErrorFromStdout(errOut, args[0] ?? '');
|
|
146
|
+
if (structured) throw structured;
|
|
147
|
+
const stderr = typeof error?.stderr === 'string' ? error.stderr.trim() : '';
|
|
148
|
+
throw new Error(
|
|
149
|
+
`hc ${args[0] ?? ''} failed.${stderr ? ` ${stderr}` : ''}${error?.message ? ` (${error.message})` : ''}`
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
let parsed: unknown;
|
|
153
|
+
try {
|
|
154
|
+
parsed = JSON.parse(stdout);
|
|
155
|
+
} catch {
|
|
156
|
+
throw new Error(`Unexpected non-JSON hc output: ${stdout.slice(0, 200)}`);
|
|
157
|
+
}
|
|
158
|
+
return throwOnHcError(parsed, args[0] ?? '');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Async `hc` bridge: same JSON contract as `hcExecSync`. */
|
|
162
|
+
export async function hcExec(args: string[]): Promise<unknown> {
|
|
163
|
+
let stdout: string;
|
|
164
|
+
try {
|
|
165
|
+
({ stdout } = await execFileAsync('hc', args, { encoding: 'utf8' }));
|
|
166
|
+
} catch (error: any) {
|
|
167
|
+
const out = typeof error?.stdout === 'string' ? error.stdout : (error?.stdout?.toString?.() ?? '');
|
|
168
|
+
const errOut =
|
|
169
|
+
typeof error?.stderr === 'string' ? error.stderr : (error?.stderr?.toString?.() ?? '');
|
|
170
|
+
const structured =
|
|
171
|
+
hcErrorFromStdout(out, args[0] ?? '') ?? hcErrorFromStdout(errOut, args[0] ?? '');
|
|
172
|
+
if (structured) throw structured;
|
|
173
|
+
const stderr = typeof error?.stderr === 'string' ? error.stderr.trim() : '';
|
|
174
|
+
throw new Error(
|
|
175
|
+
`hc ${args[0] ?? ''} failed.${stderr ? ` ${stderr}` : ''}${error?.message ? ` (${error.message})` : ''}`
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
let parsed: unknown;
|
|
179
|
+
try {
|
|
180
|
+
parsed = JSON.parse(stdout);
|
|
181
|
+
} catch {
|
|
182
|
+
throw new Error(`Unexpected non-JSON hc output: ${String(stdout).slice(0, 200)}`);
|
|
183
|
+
}
|
|
184
|
+
return throwOnHcError(parsed, args[0] ?? '');
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function shellQuote(value: string): string {
|
|
188
|
+
return "'" + value.replace(/'/g, "'\\''") + "'";
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let cachedPiBinary: string | undefined;
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Absolute path to the `pi` binary for launch scripts. `hc run` starts
|
|
195
|
+
* through a non-login shell without the user's profile PATH, so the bare
|
|
196
|
+
* `pi` the shared launch script uses would fail with "command not found".
|
|
197
|
+
* Resolved once per process: `which pi`, then the default agent bin dir.
|
|
198
|
+
*/export function resolvePiBinary(): string {
|
|
199
|
+
if (cachedPiBinary) return cachedPiBinary;
|
|
200
|
+
try {
|
|
201
|
+
const found = execFileSync('which', ['pi'], { encoding: 'utf8' }).trim().split('\n')[0];
|
|
202
|
+
if (found) {
|
|
203
|
+
cachedPiBinary = found;
|
|
204
|
+
return cachedPiBinary;
|
|
205
|
+
}
|
|
206
|
+
} catch {
|
|
207
|
+
/* fall through to the well-known location */
|
|
208
|
+
}
|
|
209
|
+
const home = process.env.HOME || os.homedir();
|
|
210
|
+
const fallback = path.join(home, '.pi', 'agent', 'bin', 'pi');
|
|
211
|
+
try {
|
|
212
|
+
fs.accessSync(fallback, fs.constants.X_OK);
|
|
213
|
+
cachedPiBinary = fallback;
|
|
214
|
+
return cachedPiBinary;
|
|
215
|
+
} catch {
|
|
216
|
+
/* last resort: keep the bare name and let the failure surface */
|
|
217
|
+
}
|
|
218
|
+
cachedPiBinary = 'pi';
|
|
219
|
+
return cachedPiBinary;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Extract the terminal address (`t7`) from an `hc run`/`hc get` response. */
|
|
223
|
+
export function terminalAddressOf(output: unknown, context: string): string {
|
|
224
|
+
const address = (output as { address?: unknown })?.address;
|
|
225
|
+
if (typeof address !== 'string' || !address) {
|
|
226
|
+
throw new Error(`Unexpected hc ${context} output: ${JSON.stringify(output)}`);
|
|
227
|
+
}
|
|
228
|
+
return address;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ── Owned-terminals registry ────────────────────────────────────────────
|
|
232
|
+
// Mirrors the created-panes registry: tracks terminals pi-shepherd created so
|
|
233
|
+
// close/prune only ever touch our own terminals (safety invariant: never
|
|
234
|
+
// kill terminals we didn't create; never `hc server stop`).
|
|
235
|
+
|
|
236
|
+
export interface CreatedTerminal {
|
|
237
|
+
terminalId: string;
|
|
238
|
+
name: string;
|
|
239
|
+
cwd: string;
|
|
240
|
+
createdAt: number;
|
|
241
|
+
/** Temp launch dir (if any) to remove when this terminal is closed. */
|
|
242
|
+
dir?: string;
|
|
243
|
+
/** Parent pi session that created this terminal (legacy entries omit it). */
|
|
244
|
+
ownerSession?: string;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Owner session id of a terminal entry; legacy entries belong to the current session. */
|
|
248
|
+
function terminalOwner(entry: CreatedTerminal): string {
|
|
249
|
+
return entry.ownerSession ?? sessionOwner() ?? '';
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function registryFile(): string {
|
|
253
|
+
// Beside created-panes.json in the active agent dir (~/.pi/agent by
|
|
254
|
+
// default on Pi, overridable via PI_CODING_AGENT_DIR).
|
|
255
|
+
const host = hostCapabilities();
|
|
256
|
+
return path.join(host.getAgentDir(), host.dataDirName, 'created-terminals.json');
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export function loadCreatedTerminals(): CreatedTerminal[] {
|
|
260
|
+
try {
|
|
261
|
+
const parsed = JSON.parse(fs.readFileSync(registryFile(), 'utf8'));
|
|
262
|
+
return Array.isArray(parsed) ? (parsed as CreatedTerminal[]) : [];
|
|
263
|
+
} catch {
|
|
264
|
+
return [];
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function saveCreatedTerminals(terminals: CreatedTerminal[]): void {
|
|
269
|
+
const file = registryFile();
|
|
270
|
+
try {
|
|
271
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
272
|
+
fs.writeFileSync(file, JSON.stringify(terminals, null, 2));
|
|
273
|
+
} catch {
|
|
274
|
+
/* best effort */
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function recordCreatedTerminal(entry: CreatedTerminal): void {
|
|
279
|
+
const terminals = loadCreatedTerminals();
|
|
280
|
+
if (!terminals.some(t => t.terminalId === entry.terminalId)) {
|
|
281
|
+
terminals.push(entry);
|
|
282
|
+
saveCreatedTerminals(terminals);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export function forgetCreatedTerminal(terminalId: string): void {
|
|
287
|
+
saveCreatedTerminals(loadCreatedTerminals().filter(t => t.terminalId !== terminalId));
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Drop one registry entry only when its recorded owner matches (orphan reap). */
|
|
291
|
+
export function forgetOwnedTerminal(terminalId: string, ownerSession?: string): boolean {
|
|
292
|
+
const entry = loadCreatedTerminals().find(t => t.terminalId === terminalId);
|
|
293
|
+
if (!entry || (ownerSession && terminalOwner(entry) !== ownerSession)) return false;
|
|
294
|
+
removeCreatedTerminalDir(terminalId);
|
|
295
|
+
forgetCreatedTerminal(terminalId);
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Attach (or overwrite) the temp launch dir for an existing terminal so that
|
|
301
|
+
* close can clean it up. The terminal is recorded early (for orphan safety)
|
|
302
|
+
* but its launch dir is only known once pi is booted, so it is set
|
|
303
|
+
* afterwards.
|
|
304
|
+
*/
|
|
305
|
+
export function setCreatedTerminalDir(terminalId: string, dir: string): void {
|
|
306
|
+
const terminals = loadCreatedTerminals();
|
|
307
|
+
const entry = terminals.find(t => t.terminalId === terminalId);
|
|
308
|
+
if (!entry) return;
|
|
309
|
+
entry.dir = dir;
|
|
310
|
+
saveCreatedTerminals(terminals);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Best-effort removal of a terminal's retained temp launch dir. */
|
|
314
|
+
export function removeCreatedTerminalDir(terminalId: string): void {
|
|
315
|
+
const entry = loadCreatedTerminals().find(t => t.terminalId === terminalId);
|
|
316
|
+
if (!entry?.dir) return;
|
|
317
|
+
try {
|
|
318
|
+
fs.rmSync(entry.dir, { recursive: true, force: true });
|
|
319
|
+
} catch {
|
|
320
|
+
/* best effort */
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* True when herdr-core still lists a terminal with this id. Returns true when
|
|
326
|
+
* the check itself fails — safer to never prune a terminal we can't confirm
|
|
327
|
+
* is gone.
|
|
328
|
+
*/
|
|
329
|
+
export function terminalExists(terminalId: string): boolean {
|
|
330
|
+
try {
|
|
331
|
+
const out = hcExecSync(['get', terminalId, '--json']) as any;
|
|
332
|
+
return typeof out?.address === 'string';
|
|
333
|
+
} catch (error) {
|
|
334
|
+
// A removed/unknown terminal reports kind not_found; anything else (a
|
|
335
|
+
// failed probe) must not prune.
|
|
336
|
+
if (error instanceof HcError) return error.kind !== 'not_found';
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Drop created-terminal registrations whose terminal is gone (and remove
|
|
343
|
+
* finished strays we own, then clean their retained temp launch dirs).
|
|
344
|
+
* Returns how many stale entries were pruned.
|
|
345
|
+
*/
|
|
346
|
+
export function pruneStaleCreatedTerminals(): number {
|
|
347
|
+
const terminals = loadCreatedTerminals();
|
|
348
|
+
if (terminals.length === 0) return 0;
|
|
349
|
+
const stale: CreatedTerminal[] = [];
|
|
350
|
+
for (const entry of terminals) {
|
|
351
|
+
let state: string | undefined;
|
|
352
|
+
try {
|
|
353
|
+
const out = hcExecSync(['get', entry.terminalId, '--json']) as any;
|
|
354
|
+
state = typeof out?.state === 'string' ? out.state : undefined;
|
|
355
|
+
} catch (error) {
|
|
356
|
+
if (error instanceof HcError && error.kind === 'not_found') {
|
|
357
|
+
stale.push(entry);
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
continue; // ambiguous probe failure: keep the entry
|
|
361
|
+
}
|
|
362
|
+
if (state !== undefined && state !== 'live') {
|
|
363
|
+
try {
|
|
364
|
+
hcExecSync(['rm', entry.terminalId, '--json']);
|
|
365
|
+
} catch {
|
|
366
|
+
/* best effort; the registry entry is still dropped */
|
|
367
|
+
}
|
|
368
|
+
stale.push(entry);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
if (stale.length === 0) return 0;
|
|
372
|
+
for (const entry of stale) removeCreatedTerminalDir(entry.terminalId);
|
|
373
|
+
saveCreatedTerminals(terminals.filter(t => !stale.includes(t)));
|
|
374
|
+
return stale.length;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* True when a created-terminal entry was spawned by THIS parent session (or is
|
|
379
|
+
* a legacy entry without an owner marker, attributed to the current session).
|
|
380
|
+
*/
|
|
381
|
+
export function terminalOwnedByCurrentSession(entry: CreatedTerminal): boolean {
|
|
382
|
+
return terminalOwner(entry) === sessionOwner();
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// ── hc-backed agent terminal lifecycle ───────────────────────────────────
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Boot pi in a fresh background `hc` terminal from the shared launch files.
|
|
389
|
+
* The temp dir is intentionally RETAINED while the terminal's pi is alive —
|
|
390
|
+
* removing it would make the still-running pi hit ENOENT on its own session
|
|
391
|
+
* file (same invariant as the pane-based backend).
|
|
392
|
+
*
|
|
393
|
+
* Flags: `--bg` (return at once), `--no-notify` (don't type spawn notes into
|
|
394
|
+
* the parent terminal), `--outlive-parent` (sheep outlive the parent like
|
|
395
|
+
* panes do). `--keep` is deliberately NOT passed: a crashed pi must surface
|
|
396
|
+
* as a finished terminal (fast failure) instead of being replaced by a
|
|
397
|
+
* shell that masks the exit.
|
|
398
|
+
*/
|
|
399
|
+
export function launchPiInHcTerminal(
|
|
400
|
+
name: string,
|
|
401
|
+
opts: Parameters<typeof writePiLaunchFiles>[0] & { cwd: string; label?: string }
|
|
402
|
+
): { terminalId: string; dir: string; sessionFile: string; scriptFile: string } {
|
|
403
|
+
const { cwd, label: _label, ...launchOpts } = opts;
|
|
404
|
+
void _label;
|
|
405
|
+
const files = writePiLaunchFiles(launchOpts);
|
|
406
|
+
// Point the shared launch script at the absolute pi binary (see
|
|
407
|
+
// resolvePiBinary): the file itself is owned by the pane-based backend
|
|
408
|
+
// and stays untouched.
|
|
409
|
+
try {
|
|
410
|
+
const script = fs.readFileSync(files.scriptFile, 'utf8');
|
|
411
|
+
const patched = script.replace(/\npi /, `\n${shellQuote(resolvePiBinary())} `);
|
|
412
|
+
if (patched !== script) fs.writeFileSync(files.scriptFile, patched);
|
|
413
|
+
} catch {
|
|
414
|
+
/* best effort; a bare `pi` may still resolve */
|
|
415
|
+
}
|
|
416
|
+
const sanitizedAgent = name.replace(/[^a-z0-9-_]/gi, '-').slice(0, 20) || 'agent';
|
|
417
|
+
let terminalId: string;
|
|
418
|
+
try {
|
|
419
|
+
const out = hcExecSync([
|
|
420
|
+
'run',
|
|
421
|
+
'--bg',
|
|
422
|
+
'--json',
|
|
423
|
+
'--cwd',
|
|
424
|
+
cwd,
|
|
425
|
+
'--label',
|
|
426
|
+
'shepherd.owned=true',
|
|
427
|
+
'--label',
|
|
428
|
+
`shepherd.agent=${sanitizedAgent}`,
|
|
429
|
+
'--no-notify',
|
|
430
|
+
'--outlive-parent',
|
|
431
|
+
'bash',
|
|
432
|
+
files.scriptFile,
|
|
433
|
+
]);
|
|
434
|
+
terminalId = terminalAddressOf(out, 'run');
|
|
435
|
+
} catch (error) {
|
|
436
|
+
try {
|
|
437
|
+
fs.rmSync(files.dir, { recursive: true, force: true });
|
|
438
|
+
} catch {
|
|
439
|
+
/* best effort */
|
|
440
|
+
}
|
|
441
|
+
throw error;
|
|
442
|
+
}
|
|
443
|
+
try {
|
|
444
|
+
hcExecSync(['label', terminalId, `shepherd.name=${sanitizedAgent}`, '--json']);
|
|
445
|
+
} catch {
|
|
446
|
+
/* cosmetic */
|
|
447
|
+
}
|
|
448
|
+
recordCreatedTerminal({
|
|
449
|
+
terminalId,
|
|
450
|
+
name,
|
|
451
|
+
cwd,
|
|
452
|
+
createdAt: Date.now(),
|
|
453
|
+
ownerSession: sessionOwner(),
|
|
454
|
+
});
|
|
455
|
+
setCreatedTerminalDir(terminalId, files.dir);
|
|
456
|
+
return { terminalId, ...files };
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Poll until herdr-core reports the terminal's agent (or timeout). Used as
|
|
461
|
+
* the post-spawn readiness check: `hc get` shows `status.app === "pi"` once
|
|
462
|
+
* the booted pi registers. A terminal that finishes before registering
|
|
463
|
+
* resolves immediately with its exit code so the caller can surface the tail
|
|
464
|
+
* instead of waiting out the full timeout.
|
|
465
|
+
*/
|
|
466
|
+
export async function waitForHcAgentDetected(
|
|
467
|
+
terminalId: string,
|
|
468
|
+
options: { timeoutMs?: number; intervalMs?: number } = {}
|
|
469
|
+
): Promise<{ detected: boolean; state?: string; exitCode?: number }> {
|
|
470
|
+
const timeoutMs = options.timeoutMs ?? 20_000;
|
|
471
|
+
const intervalMs = options.intervalMs ?? 500;
|
|
472
|
+
const deadline = Date.now() + timeoutMs;
|
|
473
|
+
let state: string | undefined;
|
|
474
|
+
while (Date.now() <= deadline) {
|
|
475
|
+
let rec: any;
|
|
476
|
+
try {
|
|
477
|
+
rec = await hcExec(['get', terminalId, '--json']);
|
|
478
|
+
} catch (error) {
|
|
479
|
+
if (error instanceof HcError && error.kind === 'not_found') {
|
|
480
|
+
return { detected: false, state: 'removed' };
|
|
481
|
+
}
|
|
482
|
+
if (Date.now() >= deadline) break;
|
|
483
|
+
await new Promise(r => setTimeout(r, intervalMs));
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
const app = (rec as any)?.status?.app;
|
|
487
|
+
state =
|
|
488
|
+
typeof (rec as any)?.status?.state === 'string'
|
|
489
|
+
? (rec as any).status.state
|
|
490
|
+
: typeof (rec as any)?.state === 'string'
|
|
491
|
+
? (rec as any).state
|
|
492
|
+
: undefined;
|
|
493
|
+
if (typeof app === 'string' && app.length > 0) return { detected: true, state };
|
|
494
|
+
if ((rec as any)?.state === 'finished') {
|
|
495
|
+
const exitCode =
|
|
496
|
+
typeof (rec as any)?.exit_code === 'number' ? (rec as any).exit_code : undefined;
|
|
497
|
+
return { detected: false, state: 'exited', ...(exitCode !== undefined ? { exitCode } : {}) };
|
|
498
|
+
}
|
|
499
|
+
if (Date.now() >= deadline) break;
|
|
500
|
+
await new Promise(r => setTimeout(r, intervalMs));
|
|
501
|
+
}
|
|
502
|
+
return { detected: false, state };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** Tail human-readable output for an owned terminal (fixed fetch, sliced by the caller). */
|
|
506
|
+
export async function readHcTerminalTail(terminalId: string, lines = 120): Promise<string> {
|
|
507
|
+
try {
|
|
508
|
+
const out = (await hcExec(['read', terminalId, '--lines', String(lines), '--json'])) as any;
|
|
509
|
+
return typeof out?.text === 'string' ? out.text : '';
|
|
510
|
+
} catch {
|
|
511
|
+
return '';
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Best-effort kill-then-remove for an owned terminal. */
|
|
516
|
+
export function killHcTerminal(terminalId: string): void {
|
|
517
|
+
try {
|
|
518
|
+
hcExecSync(['kill', terminalId, '--json']);
|
|
519
|
+
} catch {
|
|
520
|
+
/* already finished or kill raced; rm below still applies */
|
|
521
|
+
}
|
|
522
|
+
try {
|
|
523
|
+
hcExecSync(['rm', terminalId, '--json']);
|
|
524
|
+
} catch {
|
|
525
|
+
/* best effort */
|
|
526
|
+
}
|
|
527
|
+
}
|