@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/commands.ts ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * delegate — /delegate grammar and intents.
3
+ *
4
+ * Reserved subcommands are matched before the general-task fallback.
5
+ * This module owns grammar only: no mutation, no rendering.
6
+ */
7
+
8
+ import type { RoleName } from "./types.ts";
9
+ import { ROLE_NAMES } from "./types.ts";
10
+
11
+ export type DelegateIntent =
12
+ | { kind: "dashboard" }
13
+ | { kind: "enable" }
14
+ | { kind: "disable" }
15
+ | { kind: "status" }
16
+ | { kind: "paths" }
17
+ | { kind: "doctor" }
18
+ | { kind: "help" }
19
+ | { kind: "cancel"; runId?: string }
20
+ | { kind: "inspect"; runId?: string }
21
+ | { kind: "run"; role: RoleName; task: string; explicit: boolean }
22
+ | { kind: "invalid"; token: string; usage: string };
23
+
24
+ export const DELEGATE_USAGE = [
25
+ "/delegate dashboard (TUI) or status (headless)",
26
+ "/delegate on enable strict delegation mode",
27
+ "/delegate off disable strict delegation mode",
28
+ "/delegate status mode, active run, last run",
29
+ "/delegate paths config and run-store paths",
30
+ "/delegate doctor diagnostics (no LLM call)",
31
+ "/delegate cancel [run-id] cancel the active (or matching) run",
32
+ "/delegate inspect [run-id] show run metadata (defaults to latest)",
33
+ "/delegate run <general|research> <task...> run with an explicit role",
34
+ "/delegate research <task...> research-role shorthand",
35
+ "/delegate <task...> general-role shorthand",
36
+ "/delegate help this help",
37
+ ].join("\n");
38
+
39
+ const RESERVED_FIRST_TOKENS = new Set([
40
+ "on",
41
+ "off",
42
+ "status",
43
+ "paths",
44
+ "doctor",
45
+ "help",
46
+ "cancel",
47
+ "inspect",
48
+ "run",
49
+ "research",
50
+ ]);
51
+
52
+ export interface ParseOptions {
53
+ /** Recent run IDs offered for completion (newest first). */
54
+ recentRunIds?: string[];
55
+ }
56
+
57
+ export function parseDelegateCommand(input: string, options: ParseOptions = {}): DelegateIntent {
58
+ const trimmed = (input ?? "").trim();
59
+ if (!trimmed) return { kind: "dashboard" };
60
+
61
+ const first = trimmed.split(/\s+/)[0]!;
62
+ if (!RESERVED_FIRST_TOKENS.has(first)) {
63
+ // General-role shorthand. `research` is reserved, so a general task
64
+ // that starts with that word must use `run general ...`.
65
+ return { kind: "run", role: "general", task: trimmed, explicit: false };
66
+ }
67
+
68
+ switch (first) {
69
+ case "on":
70
+ return trimmed === "on" ? { kind: "enable" } : invalid("on");
71
+ case "off":
72
+ return trimmed === "off" ? { kind: "disable" } : invalid("off");
73
+ case "status":
74
+ return trimmed === "status" ? { kind: "status" } : invalid("status");
75
+ case "paths":
76
+ return trimmed === "paths" ? { kind: "paths" } : invalid("paths");
77
+ case "doctor":
78
+ return trimmed === "doctor" ? { kind: "doctor" } : invalid("doctor");
79
+ case "help":
80
+ return trimmed === "help" ? { kind: "help" } : invalid("help");
81
+ case "cancel": {
82
+ const rest = trimmed.slice("cancel".length).trim();
83
+ return { kind: "cancel", runId: rest || undefined };
84
+ }
85
+ case "inspect": {
86
+ const rest = trimmed.slice("inspect".length).trim();
87
+ return { kind: "inspect", runId: rest || undefined };
88
+ }
89
+ case "run": {
90
+ const rest = trimmed.slice("run".length).trim();
91
+ const parts = rest.split(/\s+/);
92
+ if (!rest) return invalid("run");
93
+ const roleToken = parts[0]!;
94
+ if (roleToken === "general" || roleToken === "research") {
95
+ const task = parts.slice(1).join(" ").trim();
96
+ if (!task) return invalid("run");
97
+ return { kind: "run", role: roleToken, task, explicit: true };
98
+ }
99
+ // `run <task...>` — role defaults to general.
100
+ return { kind: "run", role: "general", task: rest, explicit: true };
101
+ }
102
+ case "research": {
103
+ const task = trimmed.slice("research".length).trim();
104
+ if (!task) return invalid("research");
105
+ return { kind: "run", role: "research", task, explicit: true };
106
+ }
107
+ }
108
+ return invalid(first);
109
+ }
110
+
111
+ function invalid(token: string): DelegateIntent {
112
+ return { kind: "invalid", token, usage: DELEGATE_USAGE };
113
+ }
114
+
115
+ /** Argument completion: reserved subcommands, roles, then recent run IDs. */
116
+ export function delegateCompletions(prefix: string, recentRunIds: string[] = []): string[] {
117
+ const words = (prefix ?? "").trimStart();
118
+ const tokens = words.split(/\s+/);
119
+ const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "inspect ", "run ", "research "];
120
+
121
+ const matches: string[] = [];
122
+ if (tokens.length <= 1) {
123
+ const p = words;
124
+ for (const value of base) {
125
+ const head = value.trimEnd();
126
+ if (head.startsWith(p) || value.startsWith(p)) matches.push(value);
127
+ }
128
+ } else if (tokens[0] === "run") {
129
+ const p = tokens[1] ?? "";
130
+ for (const role of ROLE_NAMES) {
131
+ if (role.startsWith(p)) matches.push(`${role} `);
132
+ }
133
+ } else if (tokens[0] === "cancel" || tokens[0] === "inspect") {
134
+ const p = tokens[1] ?? "";
135
+ for (const id of recentRunIds) {
136
+ if (id.startsWith(p)) matches.push(`${id} `);
137
+ }
138
+ }
139
+ // De-duplicate, keep order, cap for the TUI.
140
+ return [...new Set(matches)].slice(0, 10);
141
+ }
142
+
143
+ /**
144
+ * Validate a raw task: normalize line endings, reject blank input,
145
+ * enforce the UTF-8 byte limit. Returns the normalized task or a stable
146
+ * E_INVALID_TASK error message.
147
+ */
148
+ export function validateTask(task: unknown, maxTaskBytes: number): string | { error: string } {
149
+ if (typeof task !== "string") return { error: "task must be a non-empty string" };
150
+ const normalized = task.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();
151
+ if (!normalized) return { error: "task is blank" };
152
+ const bytes = Buffer.byteLength(normalized, "utf8");
153
+ if (bytes > maxTaskBytes) {
154
+ return {
155
+ error: `task exceeds the ${maxTaskBytes} byte limit (${bytes} bytes); split it into a smaller, self-contained task`,
156
+ };
157
+ }
158
+ return normalized;
159
+ }
package/config.ts ADDED
@@ -0,0 +1,216 @@
1
+ /**
2
+ * delegate — global configuration: defaults, validation, migration, atomic
3
+ * persistence. Strict mode is NOT stored here; it is session-scoped state.
4
+ */
5
+
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import type { RoleName } from "./types.ts";
9
+ import { ROLE_NAMES } from "./types.ts";
10
+
11
+ export interface DelegateConfigV1 {
12
+ schemaVersion: 1;
13
+ defaultRole: RoleName;
14
+ maxTaskBytes: number;
15
+ maxResultBytes: number;
16
+ inactivityTimeoutMs: number;
17
+ hardTimeoutMs: number;
18
+ killGraceMs: number;
19
+ maxRuns: number;
20
+ maxRunAgeDays: number;
21
+ updateThrottleMs: number;
22
+ }
23
+
24
+ export const DEFAULT_DELEGATE_CONFIG: DelegateConfigV1 = {
25
+ schemaVersion: 1,
26
+ defaultRole: "general",
27
+ maxTaskBytes: 32768,
28
+ maxResultBytes: 51200,
29
+ inactivityTimeoutMs: 300_000,
30
+ hardTimeoutMs: 1_800_000,
31
+ killGraceMs: 5_000,
32
+ maxRuns: 50,
33
+ maxRunAgeDays: 30,
34
+ updateThrottleMs: 100,
35
+ };
36
+
37
+ const MIN_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
38
+ maxTaskBytes: 1024,
39
+ maxResultBytes: 1024,
40
+ inactivityTimeoutMs: 1_000,
41
+ hardTimeoutMs: 1_000,
42
+ killGraceMs: 100,
43
+ maxRuns: 1,
44
+ maxRunAgeDays: 1,
45
+ updateThrottleMs: 0,
46
+ };
47
+
48
+ const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
49
+ maxTaskBytes: 1_048_576,
50
+ maxResultBytes: 10_485_760,
51
+ inactivityTimeoutMs: 86_400_000,
52
+ hardTimeoutMs: 604_800_000,
53
+ killGraceMs: 60_000,
54
+ maxRuns: 10_000,
55
+ maxRunAgeDays: 3650,
56
+ updateThrottleMs: 5_000,
57
+ };
58
+
59
+ /**
60
+ * Clamp/normalize a raw value into a valid config. Unknown future keys are
61
+ * deliberately preserved in the returned `extras` so a save round-trips
62
+ * them; they are diagnosed but never silently dropped.
63
+ */
64
+ export function normalizeConfig(
65
+ raw: unknown,
66
+ ): { config: DelegateConfigV1; unknownKeys: string[] } {
67
+ const base: DelegateConfigV1 = { ...DEFAULT_DELEGATE_CONFIG };
68
+ const unknownKeys: string[] = [];
69
+ const extras: Record<string, unknown> = {};
70
+ const known = new Set<string>(Object.keys(base));
71
+
72
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
73
+ const record = raw as Record<string, unknown>;
74
+ // §5.1: missing or old schemaVersion migrates to v1; future versions
75
+ // are corrupt (fail closed).
76
+ if ("schemaVersion" in record) {
77
+ const v = record.schemaVersion;
78
+ const numeric = typeof v === "number" ? v : Number(v);
79
+ if (!Number.isFinite(numeric) || numeric > 1) {
80
+ throw new Error(
81
+ `unsupported config schemaVersion: ${String(v)} (expected <= 1)`,
82
+ );
83
+ }
84
+ }
85
+ for (const key of Object.keys(record)) {
86
+ if (!known.has(key)) {
87
+ unknownKeys.push(key);
88
+ extras[key] = record[key];
89
+ continue;
90
+ }
91
+ applyKnownField(base, key, record[key]);
92
+ }
93
+ } else if (raw !== undefined && raw !== null) {
94
+ throw new Error("config must be a JSON object");
95
+ }
96
+
97
+ return { config: base, unknownKeys };
98
+ }
99
+
100
+ function applyKnownField(config: DelegateConfigV1, key: string, value: unknown): void {
101
+ if (key === "schemaVersion") return;
102
+ if (key === "defaultRole") {
103
+ if ((ROLE_NAMES as readonly string[]).includes(String(value))) {
104
+ config.defaultRole = value as RoleName;
105
+ }
106
+ return;
107
+ }
108
+ const numeric = typeof value === "number" ? value : Number(value);
109
+ if (!Number.isFinite(numeric)) return;
110
+ const min = MIN_VALUES[key as keyof DelegateConfigV1];
111
+ const max = MAX_VALUES[key as keyof DelegateConfigV1];
112
+ config[key as keyof DelegateConfigV1] = Math.min(
113
+ max ?? Number.MAX_SAFE_INTEGER,
114
+ Math.max(min ?? 0, Math.trunc(numeric)),
115
+ ) as never;
116
+ }
117
+
118
+ export interface ConfigLoadResult {
119
+ config: DelegateConfigV1;
120
+ unknownKeys: string[];
121
+ /** True when a corrupt file was preserved and defaults recovered. */
122
+ recoveredFromCorrupt: boolean;
123
+ corruptEvidencePath?: string;
124
+ }
125
+
126
+ /**
127
+ * Load config from `<agentDir>/delegate/config.json`.
128
+ * Corrupt files are renamed with timestamp evidence and defaults recover.
129
+ * Missing files simply load defaults (nothing is written).
130
+ */
131
+ export function loadConfig(agentDir: string, configPath?: string): ConfigLoadResult {
132
+ const cfgPath = configPath ?? path.join(agentDir, "delegate", "config.json");
133
+ let raw: unknown;
134
+ try {
135
+ const text = fs.readFileSync(cfgPath, "utf8");
136
+ raw = JSON.parse(text);
137
+ } catch (error) {
138
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
139
+ return { config: { ...DEFAULT_DELEGATE_CONFIG }, unknownKeys: [], recoveredFromCorrupt: false };
140
+ }
141
+ // Preserve the corrupt file as evidence, then recover with defaults.
142
+ let evidencePath: string | undefined;
143
+ try {
144
+ evidencePath = `${cfgPath}.corrupt-${Date.now()}`;
145
+ fs.renameSync(cfgPath, evidencePath);
146
+ fs.chmodSync(evidencePath, 0o600);
147
+ } catch {
148
+ // If we cannot preserve evidence, still recover with defaults.
149
+ }
150
+ return {
151
+ config: { ...DEFAULT_DELEGATE_CONFIG },
152
+ unknownKeys: [],
153
+ recoveredFromCorrupt: true,
154
+ corruptEvidencePath: evidencePath,
155
+ };
156
+ }
157
+ try {
158
+ const { config, unknownKeys } = normalizeConfig(raw);
159
+ return { config, unknownKeys, recoveredFromCorrupt: false };
160
+ } catch {
161
+ // Normalize failed (e.g. unsupported schemaVersion): same recovery.
162
+ let evidencePath: string | undefined;
163
+ try {
164
+ evidencePath = `${cfgPath}.corrupt-${Date.now()}`;
165
+ fs.renameSync(cfgPath, evidencePath);
166
+ fs.chmodSync(evidencePath, 0o600);
167
+ } catch {
168
+ // ignore
169
+ }
170
+ return {
171
+ config: { ...DEFAULT_DELEGATE_CONFIG },
172
+ unknownKeys: [],
173
+ recoveredFromCorrupt: true,
174
+ corruptEvidencePath: evidencePath,
175
+ };
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Persist config: temp file + fsync + close + rename inside the same
181
+ * directory, mode 0600. Unknown future keys carried in `extraKeys` are
182
+ * preserved on disk.
183
+ */
184
+ export function saveConfig(
185
+ agentDir: string,
186
+ config: DelegateConfigV1,
187
+ extraKeys: Record<string, unknown> = {},
188
+ configPath?: string,
189
+ ): string {
190
+ const cfgPath = configPath ?? path.join(agentDir, "delegate", "config.json");
191
+ const dir = path.dirname(cfgPath);
192
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
193
+ const payload: Record<string, unknown> = { ...config };
194
+ for (const [key, value] of Object.entries(extraKeys)) payload[key] = value;
195
+ return atomicWriteJson(cfgPath, payload);
196
+ }
197
+
198
+ /**
199
+ * Atomic JSON replace: write a sibling temp file, fsync, close, rename.
200
+ * Owner-only (0600). Exported for run-store.ts so both persistence modules
201
+ * share one proven primitive.
202
+ */
203
+ export function atomicWriteJson(filePath: string, value: unknown): string {
204
+ const dir = path.dirname(filePath);
205
+ const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`);
206
+ const data = `${JSON.stringify(value, null, 2)}\n`;
207
+ const handle = fs.openSync(tmp, "w", 0o600);
208
+ try {
209
+ fs.writeSync(handle, data, 0, "utf8");
210
+ fs.fsyncSync(handle);
211
+ } finally {
212
+ fs.closeSync(handle);
213
+ }
214
+ fs.renameSync(tmp, filePath);
215
+ return filePath;
216
+ }