@maheidem/pi-delegate 0.1.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/types.ts ADDED
@@ -0,0 +1,365 @@
1
+ /**
2
+ * delegate — shared domain contracts.
3
+ *
4
+ * Pi-free types shared across config, mode, store, runner, application,
5
+ * commands and the UI adapter. Anything that needs a Pi context must not
6
+ * live here.
7
+ */
8
+
9
+ // ── Roles ──────────────────────────────────────────────────────────────────
10
+
11
+ export const ROLE_NAMES = ["general", "research"] as const;
12
+ export type RoleName = (typeof ROLE_NAMES)[number];
13
+
14
+ export interface DelegateRole {
15
+ name: RoleName;
16
+ description: string;
17
+ /** Absolute path of the package-owned role prompt file. */
18
+ promptPath: string;
19
+ /** Closed child tool ceiling for this role. */
20
+ tools: readonly string[];
21
+ writeCapable: boolean;
22
+ }
23
+
24
+ // ── Errors ────────────────────────────────────────────────────────────────
25
+
26
+ export const DELEGATE_ERROR_CODES = [
27
+ "E_INVALID_TASK",
28
+ "E_INVALID_ROLE",
29
+ "E_DELEGATE_BUSY",
30
+ "E_PARENT_BUSY",
31
+ "E_PROJECT_UNTRUSTED",
32
+ "E_MODEL_UNAVAILABLE",
33
+ "E_RESEARCH_TOOLS",
34
+ "E_STORE",
35
+ "E_SPAWN",
36
+ "E_RPC_PROTOCOL",
37
+ "E_RPC_PROMPT_REJECTED",
38
+ "E_CHILD_EXIT",
39
+ "E_CHILD_MODEL",
40
+ "E_NO_HANDOFF",
41
+ "E_CANCELLED",
42
+ "E_TIMEOUT_IDLE",
43
+ "E_TIMEOUT_HARD",
44
+ "E_MODE_PERSIST",
45
+ "E_TOOL_RESTORE",
46
+ "E_ORPHANED_RUN",
47
+ ] as const;
48
+ export type DelegateErrorCode = (typeof DELEGATE_ERROR_CODES)[number];
49
+
50
+ export interface DelegateError {
51
+ code: DelegateErrorCode;
52
+ /** Concise, safe for model/tool output. Never dumps stderr/env/transcripts. */
53
+ message: string;
54
+ runId?: string;
55
+ }
56
+
57
+ // ── Run lifecycle ─────────────────────────────────────────────────────────
58
+
59
+ export const RUN_TERMINAL_STATES = [
60
+ "succeeded",
61
+ "failed",
62
+ "cancelled",
63
+ "timed_out_idle",
64
+ "timed_out_hard",
65
+ "crashed",
66
+ ] as const;
67
+ export type RunTerminalState = (typeof RUN_TERMINAL_STATES)[number];
68
+
69
+ export type RunState = "created" | "starting" | "running" | RunTerminalState;
70
+
71
+ export function isTerminalRunState(state: RunState): state is RunTerminalState {
72
+ return (RUN_TERMINAL_STATES as readonly string[]).includes(state);
73
+ }
74
+
75
+ export interface DelegateUsage {
76
+ input: number;
77
+ output: number;
78
+ cacheRead: number;
79
+ cacheWrite: number;
80
+ cost: number;
81
+ contextTokens: number;
82
+ turns: number;
83
+ }
84
+
85
+ export const EMPTY_USAGE: DelegateUsage = {
86
+ input: 0,
87
+ output: 0,
88
+ cacheRead: 0,
89
+ cacheWrite: 0,
90
+ cost: 0,
91
+ contextTokens: 0,
92
+ turns: 0,
93
+ };
94
+
95
+ export type RunSource = "tool" | "command";
96
+
97
+ export interface DelegateRequest {
98
+ task: string;
99
+ role: RoleName;
100
+ source: RunSource;
101
+ /** Filled by the application, never by the caller. */
102
+ cwd: string;
103
+ /** "provider/model-id" of the parent model. */
104
+ parentModel: string;
105
+ /** Parent thinking level, when available. */
106
+ thinkingLevel?: string;
107
+ projectTrusted: boolean;
108
+ }
109
+
110
+ /** Bounded, parent-visible tool result details (schema v1). */
111
+ export interface DelegateDetails {
112
+ schemaVersion: 1;
113
+ runId: string;
114
+ role: RoleName;
115
+ state: RunTerminalState;
116
+ startedAt: string;
117
+ finishedAt: string;
118
+ durationMs: number;
119
+ model: string;
120
+ thinkingLevel?: string;
121
+ exitCode?: number;
122
+ stopReason?: string;
123
+ usage: DelegateUsage;
124
+ outputBytes: number;
125
+ outputTruncated: boolean;
126
+ transcriptPath: string;
127
+ stderrPath: string;
128
+ displayItems: DelegateDisplayItem[];
129
+ }
130
+
131
+ export type DelegateDisplayItem =
132
+ | { type: "text"; text: string }
133
+ | { type: "toolCall"; name: string; args: Record<string, unknown> };
134
+
135
+ export interface DelegateRunResult {
136
+ ok: boolean;
137
+ /** Bounded final handoff for the parent context ("" on failure). */
138
+ handoff: string;
139
+ details: DelegateDetails;
140
+ error?: DelegateError;
141
+ }
142
+
143
+ /** Terminal outcome the runner reports back to the application. */
144
+ export interface RunnerOutcome {
145
+ runId: string;
146
+ state: RunTerminalState;
147
+ handoff: string;
148
+ outputBytes: number;
149
+ outputTruncated: boolean;
150
+ startedAt: string;
151
+ finishedAt: string;
152
+ durationMs: number;
153
+ exitCode?: number;
154
+ stopReason?: string;
155
+ usage: DelegateUsage;
156
+ displayItems: DelegateDisplayItem[];
157
+ error?: DelegateError;
158
+ transcriptPath: string;
159
+ stderrPath: string;
160
+ /** Display-safe recent child actions (bounded). */
161
+ lastActions: string[];
162
+ }
163
+
164
+ // ── Run store ─────────────────────────────────────────────────────────────
165
+
166
+ export interface RunMetadataV1 {
167
+ schemaVersion: 1;
168
+ runId: string;
169
+ state: RunState;
170
+ role: RoleName;
171
+ source: RunSource;
172
+ cwd: string;
173
+ task: string;
174
+ taskSha256: string;
175
+ model: string;
176
+ thinkingLevel?: string;
177
+ createdAt: string;
178
+ startedAt?: string;
179
+ finishedAt?: string;
180
+ pid?: number;
181
+ exitCode?: number;
182
+ stopReason?: string;
183
+ errorCode?: DelegateErrorCode;
184
+ errorMessage?: string;
185
+ usage: DelegateUsage;
186
+ outputBytes?: number;
187
+ outputTruncated?: boolean;
188
+ finalHandoff?: string;
189
+ transcriptPath: string;
190
+ stderrPath: string;
191
+ }
192
+
193
+ export interface TranscriptRecordV1 {
194
+ schemaVersion: 1;
195
+ sequence: number;
196
+ receivedAt: string;
197
+ stream: "stdout";
198
+ rawBase64: string;
199
+ }
200
+
201
+ export interface DelegatePaths {
202
+ agentDir: string;
203
+ configPath: string;
204
+ runsDir: string;
205
+ }
206
+
207
+ export interface RunInspection {
208
+ metadata: RunMetadataV1;
209
+ /** Included only when the user explicitly asks for the transcript. */
210
+ transcriptPreview?: string;
211
+ stderrPreview?: string;
212
+ }
213
+
214
+ // ── Strict mode ───────────────────────────────────────────────────────────
215
+
216
+ export const DELEGATE_MODE_CUSTOM_TYPE = "delegate-mode";
217
+
218
+ export interface DelegateModeEntryV1 {
219
+ schemaVersion: 1;
220
+ enabled: boolean;
221
+ changedAt: string;
222
+ source: "command";
223
+ }
224
+
225
+ /** Minimal structural view of a session entry, for branch replay. */
226
+ export interface SessionEntryLike {
227
+ type?: unknown;
228
+ customType?: unknown;
229
+ data?: unknown;
230
+ }
231
+
232
+ export interface ModeReplayResult {
233
+ hydrated: true;
234
+ modeEnabled: boolean;
235
+ /** Diagnostics for malformed/ignored entries. */
236
+ diagnostics: string[];
237
+ }
238
+
239
+ export interface ModeRuntime {
240
+ hydrated: boolean;
241
+ modeEnabled: boolean;
242
+ persistenceDegraded: boolean;
243
+ /** Ordered active-tool snapshot captured on entry to strict mode. */
244
+ restoreTools: string[];
245
+ /** toolName -> blocked attempts this turn. */
246
+ blockedThisTurn: Map<string, number>;
247
+ }
248
+
249
+ export interface ModeGateDecision {
250
+ block: boolean;
251
+ reason?: string;
252
+ }
253
+
254
+ export type ModeResult =
255
+ | { ok: true; message: string }
256
+ | { ok: false; code: DelegateErrorCode; message: string };
257
+
258
+ /**
259
+ * Port surface the adapter (index.ts) implements so mode.ts stays Pi-free.
260
+ * Every failure path must degrade toward restriction, never permissiveness.
261
+ */
262
+ export interface ModeTransitionContext {
263
+ isBusy(): boolean;
264
+ /** Ask the user to abort the in-flight turn before activating. */
265
+ requestAbortConfirmation(): Promise<boolean>;
266
+ abort(): void;
267
+ waitForIdle(): Promise<void>;
268
+ getActiveTools(): string[];
269
+ setActiveTools(names: string[]): void;
270
+ persistModeEntry(entry: DelegateModeEntryV1): void;
271
+ setFooterStatus(text: string | undefined): void;
272
+ notify(message: string, level: "info" | "warning" | "error"): void;
273
+ }
274
+
275
+ // ── Status / doctor ───────────────────────────────────────────────────────
276
+
277
+ export interface DelegateStatus {
278
+ modeEnabled: boolean;
279
+ activeTools: string[] | "degraded";
280
+ activeRun: { runId: string; role: RoleName; startedAt: string } | null;
281
+ lastRun: {
282
+ runId: string;
283
+ role: RoleName;
284
+ state: RunState;
285
+ finishedAt?: string;
286
+ durationMs?: number;
287
+ } | null;
288
+ defaultRole: RoleName;
289
+ store: DelegatePaths;
290
+ }
291
+
292
+ export interface DoctorCheck {
293
+ name: string;
294
+ status: "ok" | "warning" | "error";
295
+ detail: string;
296
+ }
297
+
298
+ export interface DoctorReport {
299
+ checks: DoctorCheck[];
300
+ ok: boolean;
301
+ }
302
+
303
+ // ── Streaming / renderer state ───────────────────────────────────────────
304
+
305
+ export interface RunStreamUpdate {
306
+ runId: string;
307
+ role: RoleName;
308
+ phase: "starting" | "running" | `tool:${string}` | "finalizing";
309
+ elapsedMs: number;
310
+ lastActions: string[];
311
+ usage: DelegateUsage;
312
+ }
313
+
314
+ export type RunHooks = {
315
+ onUpdate?: (update: RunStreamUpdate) => void;
316
+ abortSignal?: AbortSignal;
317
+ };
318
+
319
+ /** A second invocation while a child is active: busy, with identity. */
320
+ export interface BusyRunError {
321
+ ok: false;
322
+ busy: true;
323
+ runId: string;
324
+ role: RoleName;
325
+ message: string;
326
+ error: DelegateError;
327
+ }
328
+
329
+ export type RunAttemptResult = DelegateRunResult | BusyRunError;
330
+
331
+ export interface CancelResult {
332
+ ok: boolean;
333
+ runId?: string;
334
+ message: string;
335
+ error?: DelegateError;
336
+ }
337
+
338
+ // ── Application ports (§11 Pi-free port surface) ────────────────────────
339
+
340
+ import type { DelegateConfigV1 } from "./config.ts";
341
+
342
+ export type DelegateAppConfig = DelegateConfigV1;
343
+
344
+ export interface DelegateApplicationPorts {
345
+ agentDir: string;
346
+ config: DelegateAppConfig;
347
+ /** Injectable Pi invocation resolver for tests. */
348
+ resolveInvocation?: (piPath?: string) => { command: string; args: string[] };
349
+ }
350
+
351
+ export interface DelegateApplication {
352
+ isStrict(): boolean;
353
+ getModeRuntime(): ModeRuntime;
354
+ hydrateFromBranch(branch: SessionEntryLike[]): void;
355
+ gate(toolName: unknown): ModeGateDecision;
356
+ enableStrict(ctx: ModeTransitionContext): Promise<ModeResult>;
357
+ disableStrict(ctx: ModeTransitionContext): Promise<ModeResult>;
358
+ run(request: DelegateRequest, hooks?: RunHooks): Promise<RunAttemptResult>;
359
+ cancel(runId?: string): Promise<CancelResult>;
360
+ inspect(runId?: string, includeTranscript?: boolean): RunInspection;
361
+ doctor(): DoctorReport;
362
+ getStatus(activeTools: string[] | "degraded"): DelegateStatus;
363
+ patchConfig(key: string, rawValue: string): string | null;
364
+ paths(): DelegatePaths;
365
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * delegate — compact live running view for command-driven foreground runs.
3
+ *
4
+ * Renders ≤ ~4 bounded lines (status, elapsed, last actions) inside a
5
+ * width-safe bordered box and cancels via Escape (done({ cancel: true })).
6
+ * Keyboard uses the injected KeybindingsManager where available; Escape is
7
+ * the canonical cancel. Refresh cadence is owned by the host (1 s).
8
+ */
9
+
10
+ import { truncateToWidth, visibleWidth, matchesKey, type Component } from "@earendil-works/pi-tui";
11
+ import type { Theme, KeybindingsManager } from "@earendil-works/pi-coding-agent";
12
+
13
+ export interface RunningViewState {
14
+ runId: string;
15
+ role: string;
16
+ phase: string;
17
+ elapsedMs: number;
18
+ lastActions: string[];
19
+ }
20
+
21
+ export interface RunningViewHost {
22
+ theme: Theme;
23
+ keybindings: KeybindingsManager;
24
+ state(): RunningViewState;
25
+ done(result: { cancelled?: boolean }): void;
26
+ }
27
+
28
+ export class RunningView implements Component {
29
+ private readonly host: RunningViewHost;
30
+ private cachedLines: string[] | undefined;
31
+ private cancelArmed = false;
32
+
33
+ constructor(host: RunningViewHost) {
34
+ this.host = host;
35
+ }
36
+
37
+ handleInput(data: string): void {
38
+ const kb = this.host.keybindings;
39
+ const isCancelKey =
40
+ (kb?.matches?.(data, "tui.select.cancel") ?? false) ||
41
+ matchesKey(data, "escape") ||
42
+ matchesKey(data, "q");
43
+ if (isCancelKey) {
44
+ // §12 — confirm cancellation of a running child before signalling.
45
+ if (this.cancelArmed) {
46
+ this.host.done({ cancelled: true });
47
+ } else {
48
+ this.cancelArmed = true;
49
+ this.invalidate();
50
+ }
51
+ }
52
+ }
53
+
54
+ invalidate(): void {
55
+ this.cachedLines = undefined;
56
+ }
57
+
58
+ render(width: number): string[] {
59
+ const s = this.host.state();
60
+ const theme = this.host.theme;
61
+ const w = Math.max(1, Math.floor(width));
62
+ const secs = Math.round(s.elapsedMs / 1000);
63
+ const title = truncateToWidth(" Delegating ", Math.max(4, w - 4));
64
+ const border = "─".repeat(Math.max(0, w - title.length - 2));
65
+ const top = `╭─${title}${border}─╮`;
66
+ const bottom = `╰${"─".repeat(Math.max(0, w - 2))}╯`;
67
+ const inner = Math.max(1, w - 4);
68
+ const pad = (text: string) => `│ ${truncateToWidth(text, inner)} │`;
69
+ const lines: string[] = [top, pad(`${s.role} · ${s.phase} · ${secs}s`), pad(s.runId)];
70
+ for (const action of s.lastActions.slice(-2)) {
71
+ lines.push(pad(`· ${action}`));
72
+ }
73
+ lines.push(pad(this.cancelArmed ? "ESC again: CONFIRM cancel" : "esc cancel"));
74
+ lines.push(bottom);
75
+ // Width safety: every rendered line must fit the available width.
76
+ for (const line of lines) {
77
+ if (visibleWidth(line) > w) {
78
+ // Fallback: clip hard rather than corrupt layout.
79
+ return [truncateToWidth(top, w), ...lines.map((l) => truncateToWidth(l, w))].slice(0, Math.max(1, Math.min(lines.length, 20)));
80
+ }
81
+ }
82
+ this.cachedLines = lines;
83
+ return lines;
84
+ }
85
+ }