piher 0.0.0-stage → 0.2.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 +60 -2
- package/package.json +58 -4
- package/schemas/role-manifest.schema.json +62 -0
- package/skills/piher-tools/SKILL.md +212 -0
- package/src/ansi-text.ts +143 -0
- package/src/bg-job-core.ts +412 -0
- package/src/bootstrap.ts +102 -0
- package/src/config-catalog-core.ts +200 -0
- package/src/config-command.ts +324 -0
- package/src/cordis-services.ts +38 -0
- package/src/core-client.ts +715 -0
- package/src/delegation-core.ts +94 -0
- package/src/gc-core.ts +150 -0
- package/src/guards.ts +6 -0
- package/src/hc-templates.ts +134 -0
- package/src/index-locks.ts +118 -0
- package/src/index-master.ts +92 -0
- package/src/index-notices.ts +79 -0
- package/src/index-pipe.ts +71 -0
- package/src/index-roles.ts +265 -0
- package/src/index-runtime.ts +23 -0
- package/src/index.ts +460 -0
- package/src/ledger.ts +61 -0
- package/src/lock-core.ts +200 -0
- package/src/manifest-compose.ts +103 -0
- package/src/options.ts +78 -0
- package/src/pi-surface.ts +140 -0
- package/src/pipe-channel.ts +291 -0
- package/src/platform-paths.ts +37 -0
- package/src/plugins/bg-job.ts +560 -0
- package/src/plugins/subagent.ts +1244 -0
- package/src/prompt-store.ts +50 -0
- package/src/renderers.ts +195 -0
- package/src/role-catalog.ts +99 -0
- package/src/role-loader.ts +196 -0
- package/src/role-manifest.ts +163 -0
- package/src/role-state.ts +119 -0
- package/src/roles/master.json +23 -0
- package/src/roles/worker-default.json +23 -0
- package/src/runtime-policy.ts +45 -0
- package/src/session-state.ts +19 -0
- package/src/session-tail.ts +276 -0
- package/src/settle-wake-core.ts +73 -0
- package/src/settlement-card.ts +96 -0
- package/src/storage-layout.ts +92 -0
- package/src/subagent-core.ts +543 -0
- package/src/subagent-gc.ts +312 -0
- package/src/subagent-poller.ts +484 -0
- package/src/subagent-session.ts +548 -0
- package/src/subagent-spawn.ts +695 -0
- package/src/swallow.ts +59 -0
- package/src/task-row.ts +257 -0
- package/src/task-store.ts +173 -0
- package/src/tool-error.ts +19 -0
- package/src/tool-gate.ts +99 -0
- package/src/tree-view.ts +58 -0
- package/src/vocab.ts +41 -0
- package/src/worker-marker.ts +65 -0
- package/src/worktree-io.ts +177 -0
- package/src/worktree.ts +280 -0
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent domain: launch lines, liveness notices, tab/worktree planning, task-id
|
|
3
|
+
* resolution, and the outbound port types. Pure: planners decide, adapters do I/O.
|
|
4
|
+
*
|
|
5
|
+
* The row itself lives in task-row.ts; the documents in task-store.ts.
|
|
6
|
+
*/
|
|
7
|
+
import { normalizeEntryKind, taskRef } from './task-row.ts';
|
|
8
|
+
import { CORE_REQUIRED } from './core-client.ts';
|
|
9
|
+
import type { SettlementCard, SettlementOutcome } from './settlement-card.ts';
|
|
10
|
+
import type { WorkerWidgetRow } from './tree-view.ts';
|
|
11
|
+
import { Type } from 'typebox';
|
|
12
|
+
|
|
13
|
+
export function sleep(ms: number): Promise<void> {
|
|
14
|
+
const { promise, resolve } = Promise.withResolvers<void>();
|
|
15
|
+
setTimeout(resolve, ms);
|
|
16
|
+
return promise;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface SubagentSpec {
|
|
20
|
+
description: string;
|
|
21
|
+
prompt: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** POSIX single-quote escape; win32 PowerShell doubles the quote instead. */
|
|
25
|
+
export function buildLaunchLine(parts: readonly string[], platform: NodeJS.Platform = process.platform): string {
|
|
26
|
+
const win = platform === 'win32';
|
|
27
|
+
const quoted = parts.map((s) => (win
|
|
28
|
+
? `'${String(s).replace(/'/g, "''")}'`
|
|
29
|
+
: `'${String(s).replace(/'/g, `'\\''`)}'`));
|
|
30
|
+
return (win ? '& ' : '') + quoted.join(' ');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Tab name of the master's own tab: a worker placed there joins the master terminal's tab. */
|
|
34
|
+
export const MAIN_TAB_NAME = 'main';
|
|
35
|
+
|
|
36
|
+
/** App tab addresses must be stable across spawns (a named tab is joined, not recreated) and ASCII. */
|
|
37
|
+
function tabIdFor(name: string): string {
|
|
38
|
+
const slug = String(name ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24);
|
|
39
|
+
if (slug) return `tbpiher-${slug}`;
|
|
40
|
+
// Non-ASCII task names (CJK descriptions) sanitize to nothing: the hash keeps the id stable.
|
|
41
|
+
let hash = 0x811c9dc5;
|
|
42
|
+
for (const ch of String(name)) {
|
|
43
|
+
hash ^= ch.codePointAt(0)!;
|
|
44
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
45
|
+
}
|
|
46
|
+
return `tbpiher-${hash.toString(16).padStart(8, '0')}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* pi ≥ 0.99 outputSchema for the subagent tool: the `details` each action already produces, stamped
|
|
51
|
+
* with the normalized action. Codemode scripts (and any structured consumer) read this instead of
|
|
52
|
+
* parsing the prose reply; the text content stays authoritative for the transcript. Hard failures
|
|
53
|
+
* throw (toolError), so every returned value is a success and always carries structuredContent.
|
|
54
|
+
*/
|
|
55
|
+
export const SUBAGENT_OUTPUT_SCHEMA = Type.Object({
|
|
56
|
+
action: Type.Union([
|
|
57
|
+
Type.Literal('spawn'), Type.Literal('resume'), Type.Literal('list'),
|
|
58
|
+
Type.Literal('send'), Type.Literal('interrupt'), Type.Literal('output'), Type.Literal('close'), Type.Literal('help'),
|
|
59
|
+
]),
|
|
60
|
+
paneId: Type.Optional(Type.String()),
|
|
61
|
+
taskId: Type.Optional(Type.String()),
|
|
62
|
+
role: Type.Optional(Type.String()),
|
|
63
|
+
alreadyRunning: Type.Optional(Type.Boolean()),
|
|
64
|
+
alreadyClosed: Type.Optional(Type.Boolean()),
|
|
65
|
+
}, { additionalProperties: true });
|
|
66
|
+
|
|
67
|
+
export function attachSubagentStructuredContent(action: string, result: unknown): unknown {
|
|
68
|
+
if (result === null || typeof result !== 'object' || Array.isArray(result)) return result;
|
|
69
|
+
const record = result as Record<string, unknown>;
|
|
70
|
+
const details = record.details !== null && typeof record.details === 'object' && !Array.isArray(record.details)
|
|
71
|
+
? record.details as Record<string, unknown>
|
|
72
|
+
: {};
|
|
73
|
+
return { ...record, structuredContent: { action, ...details } };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Caps how many children are being CREATED at once (SUBAGENT_CONCURRENCY); see withAdmission. */
|
|
77
|
+
export class Semaphore {
|
|
78
|
+
private active = 0;
|
|
79
|
+
private queue: Array<() => void> = [];
|
|
80
|
+
private readonly cap: number;
|
|
81
|
+
|
|
82
|
+
constructor(cap: number) {
|
|
83
|
+
if (cap < 1) throw new Error('semaphore cap must be >= 1');
|
|
84
|
+
this.cap = cap;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
get activeCount(): number {
|
|
88
|
+
return this.active;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
acquire(): Promise<() => void> {
|
|
92
|
+
if (this.active < this.cap) {
|
|
93
|
+
this.active++;
|
|
94
|
+
return Promise.resolve(this.release.bind(this));
|
|
95
|
+
}
|
|
96
|
+
const { promise, resolve } = Promise.withResolvers<() => void>();
|
|
97
|
+
this.queue.push(() => {
|
|
98
|
+
this.active++;
|
|
99
|
+
resolve(this.release.bind(this));
|
|
100
|
+
});
|
|
101
|
+
return promise;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private release(): void {
|
|
105
|
+
this.active--;
|
|
106
|
+
const next = this.queue.shift();
|
|
107
|
+
if (next) next();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Hold one admission slot for a `create` call and nothing else (S50). The cap bounds how many
|
|
112
|
+
* children are being created at once, never how long a tool call waits: a call that then waits for
|
|
113
|
+
* its pane's pipe (readiness, up to PIHER_READY_TIMEOUT_MS) must not occupy a slot, or four slow
|
|
114
|
+
* boots in `resume` would starve a `spawn` for as long as they take. */
|
|
115
|
+
export async function withAdmission<T>(sem: Semaphore, create: () => Promise<T>): Promise<T> {
|
|
116
|
+
const release = await sem.acquire();
|
|
117
|
+
try {
|
|
118
|
+
return await create();
|
|
119
|
+
} finally {
|
|
120
|
+
release();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** A spawn that never started: no pane, no ledger row, nothing running. */
|
|
125
|
+
export function formatSpawnFailure(description: string, message: string): string {
|
|
126
|
+
return `Error: failed to spawn subagent "${description}": ${message}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface AliveProbe {
|
|
130
|
+
paneExists: boolean;
|
|
131
|
+
agentStatus: string | null;
|
|
132
|
+
lastActivityMs: number | null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* A subagent outlives its "no output" result: a working/blocked agent is alive regardless of session
|
|
137
|
+
* age, otherwise recent session writes decide. `paneExists: false` is death — an unavailable probe is
|
|
138
|
+
* the caller's to report, not guessed here.
|
|
139
|
+
*/
|
|
140
|
+
export function isAlive(probe: AliveProbe, nowMs: number, staleAfterMs = 120_000): boolean {
|
|
141
|
+
if (!probe.paneExists) return false;
|
|
142
|
+
if (probe.agentStatus === 'working' || probe.agentStatus === 'blocked') return true;
|
|
143
|
+
return probe.lastActivityMs != null && nowMs - probe.lastActivityMs < staleAfterMs;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function agoText(ms: number, nowMs: number): string {
|
|
147
|
+
const s = Math.max(0, Math.round((nowMs - ms) / 1000));
|
|
148
|
+
if (s < 60) return `${s}s ago`;
|
|
149
|
+
if (s < 3600) return `${Math.floor(s / 60)}m ago`;
|
|
150
|
+
return `${Math.floor(s / 3600)}h ago`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A failing subagent call must not read as a dead worker: the pane is alive and will settle. */
|
|
154
|
+
export function buildAliveNotice(
|
|
155
|
+
opts: { paneId: string; description: string; probe: AliveProbe },
|
|
156
|
+
nowMs: number,
|
|
157
|
+
): string {
|
|
158
|
+
const { paneId, description, probe } = opts;
|
|
159
|
+
const status = probe.agentStatus ?? 'unknown';
|
|
160
|
+
const activity = probe.lastActivityMs != null ? `, last session activity ${agoText(probe.lastActivityMs, nowMs)}` : '';
|
|
161
|
+
return [
|
|
162
|
+
`The subagent "${description}" is ALIVE in pane ${paneId} (agent_status=${status}${activity}) — the failing call did not kill it, and this result is NOT the task's outcome.`,
|
|
163
|
+
'Do NOT redo its work: when it settles, its result arrives as a settlement notice at your next turn boundary.',
|
|
164
|
+
'Use subagent(action: "list") to check its live state.',
|
|
165
|
+
].join(' ');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** A pane blocked on a human decision keeps running: the master must not take the work over. */
|
|
169
|
+
export function buildBlockedGateNotice(opts: { paneId: string; description: string; question: string | null }): string {
|
|
170
|
+
const { paneId, description, question } = opts;
|
|
171
|
+
const q = question ? ` (question: "${question}")` : '';
|
|
172
|
+
return [
|
|
173
|
+
`Subagent "${description}" is BLOCKED waiting for a HUMAN decision in pane ${paneId}${q}.`,
|
|
174
|
+
'It keeps running in background; once the human answers it resumes, and you will be notified when it settles.',
|
|
175
|
+
'Do NOT take over its work and do NOT answer on the human\'s behalf.',
|
|
176
|
+
'Tell the user to open that terminal in the Herdr app and answer directly.',
|
|
177
|
+
'Only if the user explicitly authorizes you: relay their decision to the subagent via subagent(action: "send") — do not redo the work yourself.',
|
|
178
|
+
].join(' ');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Identity of a final report across the output action and the settlement notice: its tail. */
|
|
182
|
+
export function reportFingerprint(report: string): string {
|
|
183
|
+
return report.slice(-64);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Shorter sleeps are ordinary polling of builds/logs; from a minute up, they were waits on workers. */
|
|
187
|
+
const SLEEP_NOTE_MIN_SECONDS = 60;
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Note for a master bash call that sleeps ≥ SLEEP_NOTE_MIN_SECONDS while background workers run:
|
|
191
|
+
* masters slept 660-840 s per worker although the settlement notice arrives on its own. Worded so a
|
|
192
|
+
* sleep that waits on something else (a load test, a build) is left alone.
|
|
193
|
+
*/
|
|
194
|
+
export function sleepWhileSubsRunningNote(
|
|
195
|
+
command: string,
|
|
196
|
+
running: ReadonlyArray<{ paneId: string; slug?: string }>,
|
|
197
|
+
): string | null {
|
|
198
|
+
if (running.length === 0) return null;
|
|
199
|
+
const longest = Math.max(0, ...[...command.matchAll(/\bsleep\s+(\d+)s?\b/g)].map((m) => Number(m[1])));
|
|
200
|
+
if (longest < SLEEP_NOTE_MIN_SECONDS) return null;
|
|
201
|
+
return `[piher] ${running.length} background subagent(s) running (${running.map(taskRef).join(', ')}): their settlement `
|
|
202
|
+
+ 'notice arrives automatically at your next tool boundary, so do not sleep to wait for them — keep working or end '
|
|
203
|
+
+ 'your turn. Sleeping is only needed for other work (builds, logs).';
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
/** Latest row per taskId; newest createdAt wins. */
|
|
209
|
+
export function newestPerTaskId<T extends { taskId: string; createdAt: number }>(
|
|
210
|
+
entries: Iterable<T>,
|
|
211
|
+
): Map<string, T> {
|
|
212
|
+
const byTask = new Map<string, T>();
|
|
213
|
+
for (const sub of entries) {
|
|
214
|
+
const prev = byTask.get(sub.taskId);
|
|
215
|
+
if (!prev || sub.createdAt >= prev.createdAt) byTask.set(sub.taskId, sub);
|
|
216
|
+
}
|
|
217
|
+
return byTask;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Split `provider/model` on the first '/' only: model ids such as `moonshotai/kimi-k2` carry their own. */
|
|
221
|
+
export function splitRoleModel(roleModel: string): { provider: string | null; model: string } {
|
|
222
|
+
const slash = roleModel.indexOf('/');
|
|
223
|
+
if (slash <= 0 || slash === roleModel.length - 1) return { provider: null, model: roleModel };
|
|
224
|
+
return { provider: roleModel.slice(0, slash), model: roleModel.slice(slash + 1) };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Models sometimes wrap fields in a `parameters` object (JSON-schema habit). Top-level wins;
|
|
229
|
+
* only missing keys are filled from the nested bag so a real field is never overwritten.
|
|
230
|
+
*/
|
|
231
|
+
export function flattenToolParams(params: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
|
|
232
|
+
if (!params) return params;
|
|
233
|
+
const nested = params.parameters;
|
|
234
|
+
if (nested === null || typeof nested !== 'object' || Array.isArray(nested)) return params;
|
|
235
|
+
const out: Record<string, unknown> = { ...params };
|
|
236
|
+
for (const [key, value] of Object.entries(nested as Record<string, unknown>)) {
|
|
237
|
+
if (key === 'parameters') continue;
|
|
238
|
+
const current = out[key];
|
|
239
|
+
if (current == null || current === '') out[key] = value;
|
|
240
|
+
}
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export function idParam(params: Record<string, unknown> | undefined, ...keys: string[]): string {
|
|
245
|
+
const flat = flattenToolParams(params);
|
|
246
|
+
for (const key of keys) {
|
|
247
|
+
const v = flat?.[key];
|
|
248
|
+
if (v != null && String(v).trim() !== '') return String(v).trim();
|
|
249
|
+
}
|
|
250
|
+
return '';
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function ambiguousIdError(label: 'task id' | 'subagent id', query: string, candidates: readonly string[]): string {
|
|
254
|
+
const head = candidates.slice(0, 5).join(', ');
|
|
255
|
+
const more = candidates.length > 5 ? `, ... (+${candidates.length - 5} more)` : '';
|
|
256
|
+
return `Error: ambiguous ${label} "${query}" matches ${candidates.length} tasks: ${head}${more}`;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export const TAB_NAME_MAX = 20;
|
|
260
|
+
|
|
261
|
+
export function tabNameForTask(description: string): string {
|
|
262
|
+
const cleaned = String(description ?? '').replace(/\s+/g, ' ').trim();
|
|
263
|
+
const truncated = cleaned.slice(0, TAB_NAME_MAX).trim();
|
|
264
|
+
return truncated || 'task';
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** A worker placed in its own app space carries no tab label of the master's (the app makes one). */
|
|
268
|
+
export function withoutPlacement(labels: Readonly<Record<string, string>>): Record<string, string> {
|
|
269
|
+
const out = { ...labels };
|
|
270
|
+
delete out['herdr.space'];
|
|
271
|
+
delete out['herdr.tab'];
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export interface TabPlacementPlan {
|
|
276
|
+
/** Display name of the task tab; `main` when the worker shares the master's tab. */
|
|
277
|
+
tabName: string;
|
|
278
|
+
/** Address for the `herdr.tab` label; null = join the master terminal's tab. */
|
|
279
|
+
tabId: string | null;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Case/slash-insensitive containment; `/repo-x` is NOT under `/repo`. */
|
|
283
|
+
export function isPathUnder(cwd: string, wt: string): boolean {
|
|
284
|
+
const n = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
|
|
285
|
+
const a = n(cwd);
|
|
286
|
+
const b = n(wt);
|
|
287
|
+
return a === b || a.startsWith(`${b}/`);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export interface WorktreeZone {
|
|
291
|
+
zone: 'main' | 'worktree';
|
|
292
|
+
tabName: string | null;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** D86: subagents working in the master's checkout share its tab; another worktree gets its own. */
|
|
296
|
+
export function classifyWorktreeZone(opts: {
|
|
297
|
+
cwd: string;
|
|
298
|
+
masterCwd: string;
|
|
299
|
+
worktrees: readonly string[];
|
|
300
|
+
}): WorktreeZone {
|
|
301
|
+
for (const wt of opts.worktrees) {
|
|
302
|
+
if (!isPathUnder(opts.cwd, wt)) continue;
|
|
303
|
+
if (isPathUnder(opts.masterCwd, wt)) return { zone: 'main', tabName: null };
|
|
304
|
+
const base = wt.replace(/\\/g, '/').split('/').filter(Boolean).pop() ?? 'worktree';
|
|
305
|
+
return { zone: 'worktree', tabName: base };
|
|
306
|
+
}
|
|
307
|
+
return { zone: 'main', tabName: null };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Explicit `tab` and a worktree zone get their own app tab (the id is stable per name, so repeat
|
|
311
|
+
* spawns join instead of piling up tabs); a worker in the master's checkout joins the master tab. */
|
|
312
|
+
export function planTabPlacement(opts: {
|
|
313
|
+
desiredTab?: string | null;
|
|
314
|
+
description: string;
|
|
315
|
+
zone?: WorktreeZone;
|
|
316
|
+
}): TabPlacementPlan {
|
|
317
|
+
const desired = opts.desiredTab != null ? String(opts.desiredTab).replace(/\s+/g, ' ').trim() : '';
|
|
318
|
+
if (desired) return placementFor(tabNameForTask(desired));
|
|
319
|
+
const zone = opts.zone;
|
|
320
|
+
if (zone?.zone === 'worktree' && zone.tabName) return placementFor(tabNameForTask(zone.tabName));
|
|
321
|
+
if (zone?.zone === 'main') return { tabName: MAIN_TAB_NAME, tabId: null };
|
|
322
|
+
return placementFor(tabNameForTask(opts.description));
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function placementFor(tabName: string): TabPlacementPlan {
|
|
326
|
+
if (tabName.toLowerCase() === MAIN_TAB_NAME) return { tabName: MAIN_TAB_NAME, tabId: null };
|
|
327
|
+
return { tabName, tabId: tabIdFor(tabName) };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** D97: fullscreen is what makes the pane a static frame the master can read. */
|
|
331
|
+
/**
|
|
332
|
+
* The script argument to relaunch pi with, or '' when there is none. A compiled bun binary reports
|
|
333
|
+
* `argv[1]` as an embedded `/$bunfs/root/pi` that no filesystem has, and passing it makes it the
|
|
334
|
+
* child's first prompt — the worker greeted "/$bunfs/root/pi" before its real task. A script that is
|
|
335
|
+
* not on disk is not a script; an interpreter's real file is. The caller supplies `exists` so this
|
|
336
|
+
* stays a decision, not I/O.
|
|
337
|
+
*/
|
|
338
|
+
/** bun's embedded filesystem root: a compiled binary reports it as `argv[1]` (Windows: `B:\~BUN\`). */
|
|
339
|
+
export function isEmbeddedEntrypoint(path: string): boolean {
|
|
340
|
+
return /^\/(?:\$bunfs|bunfs)\//.test(path) || /^[A-Za-z]:\\~BUN\\/i.test(path);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export function entryScript(argv1: string | undefined, exists: (path: string) => boolean): string {
|
|
344
|
+
const path = argv1 ?? '';
|
|
345
|
+
// The embedded root is rejected before the filesystem is consulted, because bun answers `exists` for
|
|
346
|
+
// its own virtual paths: `existsSync('/$bunfs/root/pi')` is true inside the binary and false in any
|
|
347
|
+
// shell. Only a real path makes existence the right question.
|
|
348
|
+
if (path === '' || isEmbeddedEntrypoint(path)) return '';
|
|
349
|
+
return exists(path) ? path : '';
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export function buildLaunchParts(
|
|
353
|
+
runtime: { nodePath: string; cliPath: string; extPath: string },
|
|
354
|
+
opts: { resumeFile?: string | null; roleModel?: string | null; roleThinking?: string | null; approve?: boolean } = {},
|
|
355
|
+
env: { PIHER_TUI?: string | undefined } = process.env,
|
|
356
|
+
): string[] {
|
|
357
|
+
// A compiled binary is its own entrypoint: `execPath` and `argv[1]` are the same file, and passing
|
|
358
|
+
// both makes the second one the child's first prompt. `entryScript` already dropped an `argv[1]`
|
|
359
|
+
// that is not on disk; this covers the case where it genuinely is the binary again.
|
|
360
|
+
const parts = runtime.cliPath === '' || runtime.cliPath === runtime.nodePath
|
|
361
|
+
? [runtime.nodePath]
|
|
362
|
+
: [runtime.nodePath, runtime.cliPath];
|
|
363
|
+
if (opts.approve) parts.push('-a');
|
|
364
|
+
parts.push('-e', runtime.extPath);
|
|
365
|
+
if (env.PIHER_TUI !== 'regular') parts.push('--tui-mode', 'fullscreen');
|
|
366
|
+
if (opts.roleModel) {
|
|
367
|
+
const { provider, model } = splitRoleModel(opts.roleModel);
|
|
368
|
+
if (provider) parts.push('--provider', provider);
|
|
369
|
+
parts.push('--model', model);
|
|
370
|
+
}
|
|
371
|
+
if (opts.roleThinking) parts.push('--thinking', opts.roleThinking);
|
|
372
|
+
if (opts.resumeFile) parts.push('--session', opts.resumeFile);
|
|
373
|
+
return parts;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* The role profiles a master can actually launch here, as `help` prints them. Discovery belongs to the
|
|
378
|
+
* tool: without this a master hunts the filesystem (workspace, user dir, find, then the whole manifest)
|
|
379
|
+
* to answer "which agents do I have", which is what it did before every review spawn.
|
|
380
|
+
*/
|
|
381
|
+
export function formatRoleCatalog(
|
|
382
|
+
profiles: readonly {
|
|
383
|
+
name: string;
|
|
384
|
+
description?: string | null;
|
|
385
|
+
tools?: readonly string[];
|
|
386
|
+
lifecycle?: 'one-shot' | 'persistent';
|
|
387
|
+
invalid?: string | null;
|
|
388
|
+
}[],
|
|
389
|
+
): string {
|
|
390
|
+
if (profiles.length === 0) {
|
|
391
|
+
return 'role profiles — none in this workspace or user directory; pass no `role` for the builtin worker-default.';
|
|
392
|
+
}
|
|
393
|
+
const lines = profiles.map((profile) => {
|
|
394
|
+
if (profile.invalid) return ` - ${profile.name} — INVALID: ${profile.invalid}`;
|
|
395
|
+
const facts = [
|
|
396
|
+
profile.lifecycle === 'one-shot' ? 'one-shot' : 'persistent',
|
|
397
|
+
profile.tools?.length ? `tools: ${profile.tools.join(', ')}` : 'tools: none declared',
|
|
398
|
+
].join(' · ');
|
|
399
|
+
const described = profile.description?.trim() ?? '';
|
|
400
|
+
// One line each: a long description must not push `help` over the inline budget (4096 B on a
|
|
401
|
+
// context-mode host, which replaces larger outputs with a pointer — silently losing the catalog).
|
|
402
|
+
const what = described === '' ? 'no description' : described.length > 120 ? `${described.slice(0, 117)}…` : described;
|
|
403
|
+
return ` - ${profile.name} — ${what} (${facts})`;
|
|
404
|
+
});
|
|
405
|
+
return [
|
|
406
|
+
'role profiles available here (`role` accepts these; omit it for the builtin worker-default):',
|
|
407
|
+
...lines,
|
|
408
|
+
].join('\n');
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/* ── execute planners ───────────────────────────────────────────── */
|
|
412
|
+
|
|
413
|
+
type LaunchValidation =
|
|
414
|
+
| { kind: 'error'; text: string }
|
|
415
|
+
| {
|
|
416
|
+
kind: 'ok';
|
|
417
|
+
spec: SubagentSpec;
|
|
418
|
+
cwdParam: string | null;
|
|
419
|
+
worktreeParam: string | null;
|
|
420
|
+
roleKind: string;
|
|
421
|
+
suggested: string[];
|
|
422
|
+
manifestRole: string | null;
|
|
423
|
+
tab: string | null;
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
/** Validate spawn parameters. `role` doubles as the pane label and (when it names a profile) the
|
|
427
|
+
* manifest to compose; unknown names stay labels. */
|
|
428
|
+
export function planLaunchValidation(
|
|
429
|
+
params: {
|
|
430
|
+
description?: unknown;
|
|
431
|
+
prompt?: unknown;
|
|
432
|
+
cwd?: unknown;
|
|
433
|
+
worktree?: unknown;
|
|
434
|
+
role?: unknown;
|
|
435
|
+
allowed_tools?: unknown;
|
|
436
|
+
tab?: unknown;
|
|
437
|
+
} | null | undefined,
|
|
438
|
+
available: boolean,
|
|
439
|
+
): LaunchValidation {
|
|
440
|
+
if (!available) {
|
|
441
|
+
return { kind: 'error', text: `Error: subagent: ${CORE_REQUIRED}.` };
|
|
442
|
+
}
|
|
443
|
+
const spec: SubagentSpec = {
|
|
444
|
+
description: String(params?.description ?? 'subagent'),
|
|
445
|
+
prompt: String(params?.prompt ?? ''),
|
|
446
|
+
};
|
|
447
|
+
if (!spec.prompt.trim()) {
|
|
448
|
+
// The schema cannot catch this (`prompt` is optional), so the refusal restates the real constraint
|
|
449
|
+
// where the mistake happens: only the prompt reaches the worker.
|
|
450
|
+
return {
|
|
451
|
+
kind: 'error',
|
|
452
|
+
text: 'Error: `prompt` is required and must be a non-empty string: the worker does not see this conversation, so `prompt` must be the complete, self-contained task (paths, acceptance criteria, the command to run, what to report back).',
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
const cwdParam = typeof params?.cwd === 'string' && params.cwd.trim() ? params.cwd.trim() : null;
|
|
456
|
+
const worktreeParam = typeof params?.worktree === 'string' && params.worktree.trim() ? params.worktree.trim() : null;
|
|
457
|
+
if (cwdParam && worktreeParam) {
|
|
458
|
+
// Both describe where the worker runs, so one of them has to be dropped: `cwd` for a checkout the
|
|
459
|
+
// caller made, `worktree` for one piher makes (S71).
|
|
460
|
+
return {
|
|
461
|
+
kind: 'error',
|
|
462
|
+
text: 'Error: `cwd` and `worktree` are mutually exclusive — `cwd` runs the worker in a checkout you already have, `worktree` asks piher to create one. Drop one of them: pass `worktree: "<name>"` and no `cwd`, or `cwd` and no `worktree`.',
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
const role = typeof params?.role === 'string' ? params.role.trim() : undefined;
|
|
466
|
+
return {
|
|
467
|
+
kind: 'ok',
|
|
468
|
+
spec,
|
|
469
|
+
cwdParam,
|
|
470
|
+
worktreeParam,
|
|
471
|
+
roleKind: normalizeEntryKind(role),
|
|
472
|
+
suggested: Array.isArray(params?.allowed_tools)
|
|
473
|
+
? params.allowed_tools.filter((t): t is string => typeof t === 'string' && t.trim() !== '')
|
|
474
|
+
: [],
|
|
475
|
+
manifestRole: role || 'worker-default',
|
|
476
|
+
tab: typeof params?.tab === 'string' ? params.tab : null,
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/* ── task-id resolution ─────────────────────────────────────────── */
|
|
481
|
+
|
|
482
|
+
export type TaskIdResolutionResult =
|
|
483
|
+
| { kind: 'resolved'; taskId: string }
|
|
484
|
+
| { kind: 'ambiguous'; query: string; candidates: string[] }
|
|
485
|
+
| { kind: 'too_short'; query: string }
|
|
486
|
+
| { kind: 'not_found'; query: string };
|
|
487
|
+
|
|
488
|
+
/** Resolve a full or short task ID: exact matches at any length, prefix matches need four characters. */
|
|
489
|
+
export function resolveTaskIdPrefix(
|
|
490
|
+
query: string,
|
|
491
|
+
candidates: Iterable<string>,
|
|
492
|
+
): TaskIdResolutionResult {
|
|
493
|
+
const trimmed = query.trim();
|
|
494
|
+
if (!trimmed) return { kind: 'not_found', query: trimmed };
|
|
495
|
+
|
|
496
|
+
const unique = Array.from(new Set(candidates));
|
|
497
|
+
const exact = unique.find((candidate) => candidate === trimmed);
|
|
498
|
+
if (exact) return { kind: 'resolved', taskId: exact };
|
|
499
|
+
|
|
500
|
+
if (trimmed.length < 4) return { kind: 'too_short', query: trimmed };
|
|
501
|
+
|
|
502
|
+
const lower = trimmed.toLowerCase();
|
|
503
|
+
const matches = unique.filter((candidate) => candidate.toLowerCase().startsWith(lower));
|
|
504
|
+
if (matches.length === 1) return { kind: 'resolved', taskId: matches[0]! };
|
|
505
|
+
if (matches.length > 1) {
|
|
506
|
+
matches.sort();
|
|
507
|
+
return { kind: 'ambiguous', query: trimmed, candidates: matches };
|
|
508
|
+
}
|
|
509
|
+
return { kind: 'not_found', query: trimmed };
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** Error text for a non-resolved `resolveTaskIdPrefix` outcome; null for `resolved` (each caller owns
|
|
513
|
+
* its success path) and `not_found` (each caller words its own unknown-id hint). `rawQuery` keeps
|
|
514
|
+
* the caller's original string in the message even though matching works on the trimmed form. */
|
|
515
|
+
export function taskIdResolutionError(
|
|
516
|
+
res: TaskIdResolutionResult,
|
|
517
|
+
label: 'task id' | 'subagent id',
|
|
518
|
+
rawQuery: string,
|
|
519
|
+
): string | null {
|
|
520
|
+
if (res.kind === 'too_short') return `Error: ${label} prefix "${rawQuery}" is too short (minimum 4 characters).`;
|
|
521
|
+
if (res.kind === 'ambiguous') return ambiguousIdError(label, rawQuery, res.candidates);
|
|
522
|
+
return null;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/* ── outbound port (composition root → plugin) ──────────────────── */
|
|
526
|
+
|
|
527
|
+
/** Bound atomically at session_start: consumers read `current` and must tolerate null. */
|
|
528
|
+
export interface SubagentPort {
|
|
529
|
+
applyReplySession(paneId: string, sessionFile: string | null): void;
|
|
530
|
+
listRunningSubs(): WorkerWidgetRow[];
|
|
531
|
+
/** The `piher.settlement` card for a pipe-delivered settlement (S57). */
|
|
532
|
+
settlementCard(paneId: string, outcome: SettlementOutcome): SettlementCard;
|
|
533
|
+
/** Pipe settlement: drop the row out of listRunningSubs before the finish notice wakes the master. */
|
|
534
|
+
consumeReply(paneId: string, outcome: string | null): void;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
export interface SubagentPortBox {
|
|
538
|
+
current: SubagentPort | null;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
export function emptySubagentPortBox(): SubagentPortBox {
|
|
542
|
+
return { current: null };
|
|
543
|
+
}
|