pal-code 0.0.21 → 0.0.23

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.
@@ -0,0 +1,495 @@
1
+ /**
2
+ * Headless front-ends for pal: one-shot `-p` and NDJSON RPC over stdio.
3
+ *
4
+ * This is a *third* adapter over the same core, alongside the TUI. It exists
5
+ * because everything needed was already none-of-the-TUI's-business: `runTurn`
6
+ * takes an injected `AgentUi` port and an injected `Approval`, and the agent
7
+ * loop never renders. The TUI is one implementation of those ports; this is
8
+ * another. No change to `runAgent`, `runTurn`, or the tool executor.
9
+ *
10
+ * Two modes, deliberately sharing one runner:
11
+ *
12
+ * pal -p "fix the failing test" → final answer on stdout, progress on stderr
13
+ * pal --mode rpc → NDJSON commands in, NDJSON frames out
14
+ *
15
+ * Exit codes: 0 success, 1 failure, 130 aborted.
16
+ */
17
+
18
+ import {checkPermission, detectDangerousBash, loadPermissionConfig} from '@pal-code/core';
19
+ import type {
20
+ AgentUi,
21
+ Approval,
22
+ ConversationMessage,
23
+ Provider,
24
+ ProviderKeys,
25
+ TurnResult,
26
+ TurnSettings,
27
+ } from '@pal-code/core';
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Argument parsing (pure — tested without a provider or a terminal)
31
+ // ---------------------------------------------------------------------------
32
+
33
+ export type HeadlessMode = 'print' | 'rpc';
34
+
35
+ export interface HeadlessArgs {
36
+ mode: HeadlessMode;
37
+ /** The one-shot prompt. Empty for RPC (prompts arrive on stdin). */
38
+ prompt: string;
39
+ /** FR-1: permit `ask`-gated tool calls instead of failing closed. */
40
+ assumeYes: boolean;
41
+ /** Emit one JSON object instead of plain text (print mode only). */
42
+ json: boolean;
43
+ /** Override the configured model. */
44
+ model: string | null;
45
+ /** Agent role/primary to run the turn as. */
46
+ primary: string | null;
47
+ }
48
+
49
+ const MODE_ALIASES: Record<string, HeadlessMode> = {
50
+ print: 'print',
51
+ 'one-shot': 'print',
52
+ oneshot: 'print',
53
+ rpc: 'rpc',
54
+ };
55
+
56
+ /**
57
+ * Parse argv into a headless request, or `null` when this is an interactive
58
+ * invocation that belongs to the TUI.
59
+ *
60
+ * Returning `null` (rather than throwing) is what keeps this additive: every
61
+ * existing invocation path is untouched, and an unknown flag here is not an
62
+ * error — it just means "not mine".
63
+ */
64
+ export function parseHeadlessArgs(argv: readonly string[]): HeadlessArgs | null {
65
+ const args: HeadlessArgs = {
66
+ mode: 'print',
67
+ prompt: '',
68
+ assumeYes: false,
69
+ json: false,
70
+ model: null,
71
+ primary: null,
72
+ };
73
+
74
+ let sawHeadlessFlag = false;
75
+ const promptParts: string[] = [];
76
+
77
+ for (let i = 0; i < argv.length; i++) {
78
+ const arg = argv[i];
79
+
80
+ if (arg === '-p' || arg === '--print' || arg === '--prompt') {
81
+ sawHeadlessFlag = true;
82
+ // `-p "..."` — value may be omitted only for RPC/--json styles, where it
83
+ // is an error the caller should see rather than a silent empty prompt.
84
+ const value = argv[i + 1];
85
+ if (value === undefined || value.startsWith('-')) continue;
86
+ promptParts.push(value);
87
+ i++;
88
+ } else if (arg === '--mode') {
89
+ const value = argv[++i];
90
+ const mode = value ? MODE_ALIASES[value] : undefined;
91
+ if (mode) {
92
+ args.mode = mode;
93
+ sawHeadlessFlag = true;
94
+ }
95
+ } else if (arg === '-y' || arg === '--yes' || arg === '--assume-yes') {
96
+ args.assumeYes = true;
97
+ } else if (arg === '--json') {
98
+ args.json = true;
99
+ sawHeadlessFlag = true;
100
+ } else if (arg === '--model' || arg === '-m') {
101
+ const value = argv[++i];
102
+ if (value !== undefined && !value.startsWith('-')) args.model = value;
103
+ } else if (arg === '--agent' || arg === '--primary') {
104
+ const value = argv[++i];
105
+ if (value !== undefined && !value.startsWith('-')) args.primary = value;
106
+ } else if (arg.startsWith('--mode=')) {
107
+ const mode = MODE_ALIASES[arg.slice('--mode='.length)];
108
+ if (mode) {
109
+ args.mode = mode;
110
+ sawHeadlessFlag = true;
111
+ }
112
+ } else if (arg.startsWith('--model=')) {
113
+ args.model = arg.slice('--model='.length) || null;
114
+ } else if (!arg.startsWith('-')) {
115
+ // A bare trailing argument (or `pal -p -- that thing`) is the prompt.
116
+ // Only meaningful once a headless flag has been seen, so `pal add x`
117
+ // and friends keep their existing argv contract.
118
+ if (sawHeadlessFlag) promptParts.push(arg);
119
+ }
120
+ }
121
+
122
+ if (!sawHeadlessFlag) return null;
123
+ args.prompt = promptParts.join(' ').trim();
124
+ return args;
125
+ }
126
+
127
+ // ---------------------------------------------------------------------------
128
+ // Approval policy
129
+ // ---------------------------------------------------------------------------
130
+
131
+ /**
132
+ * Non-interactive approval: there is nobody to ask, so `ask` must resolve to a
133
+ * decision rather than hang.
134
+ *
135
+ * Fails closed by default. An agent that silently approves whatever its own
136
+ * permission config flagged as `ask` is exactly the surprise a CI job cannot
137
+ * recover from, so `--yes` is the only way to widen it — and it never
138
+ * overrides `deny`, including the dangerous-bash patterns.
139
+ */
140
+ export function headlessApproval(
141
+ assumeYes: boolean,
142
+ onAsk?: (tool: string, reason: string) => void,
143
+ ): Approval {
144
+ const config = loadPermissionConfig();
145
+ return async (toolName, toolArgs) => {
146
+ const target =
147
+ toolName === 'bash'
148
+ ? String(toolArgs.command ?? toolArgs.cmd ?? '')
149
+ : String(toolArgs.path ?? toolArgs.filePath ?? toolArgs.file ?? '*') || '*';
150
+
151
+ if (toolName === 'bash') {
152
+ const danger = detectDangerousBash(target);
153
+ // Not negotiable, in any mode.
154
+ if (danger) return 'deny';
155
+ }
156
+
157
+ const decision = checkPermission(toolName, target || '*', config, []);
158
+ if (decision === 'allow') return 'allow';
159
+ if (decision === 'deny') return 'deny';
160
+
161
+ if (assumeYes) return 'allow';
162
+ onAsk?.(toolName, target);
163
+ return 'deny';
164
+ };
165
+ }
166
+
167
+ // ---------------------------------------------------------------------------
168
+ // UI adapter
169
+ // ---------------------------------------------------------------------------
170
+
171
+ export interface HeadlessSink {
172
+ /** Assistant text. In `-p` mode this is the answer; it goes to stdout. */
173
+ text(delta: string): void;
174
+ /** Progress and diagnostics — never mixed into the answer. */
175
+ progress(line: string): void;
176
+ /** A structured event, for the JSON/RPC renderings. */
177
+ event(frame: Record<string, unknown>): void;
178
+ }
179
+
180
+ /**
181
+ * `AgentUi` over a sink.
182
+ *
183
+ * `startRun` is the turn boundary: it is where RPC emits `prompt_started` and
184
+ * where the one-shot collector resets — the loop calls it exactly once per turn.
185
+ */
186
+ export function createHeadlessUi(sink: HeadlessSink): AgentUi & {result(): string} {
187
+ let collected = '';
188
+
189
+ return {
190
+ startRun(model) {
191
+ collected = '';
192
+ sink.event({type: 'prompt_started', model});
193
+ },
194
+ setModel(model) {
195
+ sink.event({type: 'model', model});
196
+ },
197
+ beginRound(round, max) {
198
+ sink.event({type: 'round', round, max});
199
+ },
200
+ text(delta) {
201
+ collected += delta;
202
+ sink.text(delta);
203
+ },
204
+ thinking(delta) {
205
+ sink.event({type: 'thinking', content: delta});
206
+ },
207
+ toolStart(id, name, argsSummary) {
208
+ sink.progress(`→ ${name}(${argsSummary})`);
209
+ sink.event({type: 'tool_start', id, name, args: argsSummary});
210
+ },
211
+ toolEnd(id, ok, content) {
212
+ sink.progress(`${ok ? '✓' : '✗'} ${id} (${content.length} chars)`);
213
+ sink.event({type: 'tool_end', id, ok, content});
214
+ },
215
+ notice(text) {
216
+ sink.progress(text);
217
+ sink.event({type: 'notice', text});
218
+ },
219
+ aborted() {
220
+ sink.event({type: 'aborted'});
221
+ },
222
+ advisories(lines) {
223
+ for (const line of lines) sink.progress(line);
224
+ },
225
+ ready() {},
226
+ result() {
227
+ return collected;
228
+ },
229
+ };
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // Runners
234
+ // ---------------------------------------------------------------------------
235
+
236
+ /** What a front-end must hand the headless runner. Mirrors the TUI's wiring. */
237
+ export interface HeadlessContext {
238
+ settings: TurnSettings;
239
+ keys: ProviderKeys;
240
+ createProvider: (modelSpec: string) => Provider;
241
+ }
242
+
243
+ export interface HeadlessRunResult {
244
+ exitCode: number;
245
+ text: string;
246
+ turn: TurnResult | null;
247
+ error: string | null;
248
+ }
249
+
250
+ function errorMessage(err: unknown): string {
251
+ return err instanceof Error ? err.message : String(err);
252
+ }
253
+
254
+ /** One prompt through the real turn orchestrator (extensions, fallback, compaction). */
255
+ async function runOnePrompt(
256
+ prompt: string,
257
+ messages: ConversationMessage[],
258
+ ctx: HeadlessContext,
259
+ args: HeadlessArgs,
260
+ ui: AgentUi & {result(): string},
261
+ onAsk: (tool: string, reason: string) => void,
262
+ signal?: AbortSignal,
263
+ ): Promise<HeadlessRunResult> {
264
+ // Imported lazily so `pal --version` and the TUI never pay for loading the
265
+ // orchestrator's dependency graph.
266
+ const {runTurn} = await import('@pal-code/core');
267
+
268
+ try {
269
+ const turn = await runTurn(
270
+ prompt,
271
+ messages,
272
+ args.model ? {...ctx.settings, model: args.model} : ctx.settings,
273
+ ctx.keys,
274
+ ctx.createProvider,
275
+ ui,
276
+ headlessApproval(args.assumeYes, onAsk),
277
+ args.primary ?? undefined,
278
+ 0,
279
+ '',
280
+ signal,
281
+ );
282
+ return {exitCode: 0, text: ui.result(), turn, error: null};
283
+ } catch (err) {
284
+ return {exitCode: 1, text: ui.result(), turn: null, error: errorMessage(err)};
285
+ }
286
+ }
287
+
288
+ /** `pal -p "…"` — run one prompt, print the answer, exit. */
289
+ export async function runPrint(
290
+ prompt: string,
291
+ ctx: HeadlessContext,
292
+ args: HeadlessArgs,
293
+ io: {stdout: (s: string) => void; stderr: (s: string) => void},
294
+ ): Promise<number> {
295
+ const jsonFrames: Record<string, unknown>[] = [];
296
+ const denials: string[] = [];
297
+
298
+ const sink: HeadlessSink = {
299
+ text: (delta) => {
300
+ if (!args.json) io.stdout(delta);
301
+ },
302
+ progress: (line) => io.stderr(`${line}\n`),
303
+ event: (frame) => {
304
+ if (args.json) jsonFrames.push(frame);
305
+ },
306
+ };
307
+
308
+ const ui = createHeadlessUi(sink);
309
+ const result = await runOnePrompt(
310
+ prompt,
311
+ [{role: 'user', content: prompt}],
312
+ ctx,
313
+ args,
314
+ ui,
315
+ (tool, reason) =>
316
+ denials.push(`${tool} on "${reason}" needed approval (pass --yes to allow)`),
317
+ );
318
+
319
+ for (const d of denials) io.stderr(`pal: ${d}\n`);
320
+
321
+ if (args.json) {
322
+ io.stdout(
323
+ `${JSON.stringify(
324
+ {
325
+ ok: result.exitCode === 0,
326
+ text: result.text,
327
+ error: result.error,
328
+ model: result.turn?.model ?? null,
329
+ usage: result.turn
330
+ ? {
331
+ inputTokens: result.turn.inputTokens,
332
+ outputTokens: result.turn.outputTokens,
333
+ cachedTokens: result.turn.cachedTokens,
334
+ reportedCost: result.turn.reportedCost,
335
+ }
336
+ : null,
337
+ denials,
338
+ events: jsonFrames,
339
+ },
340
+ null,
341
+ 2,
342
+ )}\n`,
343
+ );
344
+ } else {
345
+ // The answer already streamed to stdout; only make sure it ends cleanly.
346
+ if (!result.text.endsWith('\n')) io.stdout('\n');
347
+ if (result.error) io.stderr(`pal: ${result.error}\n`);
348
+ }
349
+
350
+ return result.exitCode;
351
+ }
352
+
353
+ /**
354
+ * `pal --mode rpc` — NDJSON both ways.
355
+ *
356
+ * Commands (stdin, one JSON object per line):
357
+ * {"type":"prompt","text":"…"} — run a turn; ends with one prompt_result
358
+ * {"type":"abort"} — cancel the in-flight turn
359
+ * {"type":"reset"} — forget conversation history
360
+ *
361
+ * Frames (stdout, one JSON object per line): ready, prompt_started, round,
362
+ * text, thinking, tool_start, tool_end, notice, aborted, prompt_result, error.
363
+ *
364
+ * Every prompt terminates with exactly one `prompt_result`, so a caller can
365
+ * always wait for a single frame to know the turn is over — no sentinel needed.
366
+ */
367
+ export async function runRpc(
368
+ ctx: HeadlessContext,
369
+ args: HeadlessArgs,
370
+ io: {
371
+ stdout: (s: string) => void;
372
+ stderr: (s: string) => void;
373
+ stdin: AsyncIterable<string>;
374
+ },
375
+ signal?: AbortSignal,
376
+ ): Promise<number> {
377
+ const emit = (frame: Record<string, unknown>): void => {
378
+ io.stdout(`${JSON.stringify(frame)}\n`);
379
+ };
380
+
381
+ const messages: ConversationMessage[] = [];
382
+ const abortRef: {current: AbortController | null} = {current: null};
383
+ let exitCode = 0;
384
+
385
+ emit({type: 'ready', mode: 'rpc', model: args.model ?? ctx.settings.model});
386
+
387
+ const runPrompt = async (text: string): Promise<void> => {
388
+ abortRef.current = new AbortController();
389
+ const sink: HeadlessSink = {
390
+ text: (delta) => emit({type: 'text', content: delta}),
391
+ progress: (line) => io.stderr(`${line}\n`),
392
+ event: emit,
393
+ };
394
+ const ui = createHeadlessUi(sink);
395
+ const denials: string[] = [];
396
+
397
+ const result = await runOnePrompt(
398
+ text,
399
+ messages,
400
+ ctx,
401
+ args,
402
+ ui,
403
+ (tool, reason) => {
404
+ const msg = `${tool} on "${reason}" needed approval (restart with --yes to allow)`;
405
+ denials.push(msg);
406
+ emit({type: 'notice', text: msg});
407
+ },
408
+ abortRef.current.signal,
409
+ );
410
+
411
+ if (result.error) exitCode = 1;
412
+
413
+ emit({
414
+ type: 'prompt_result',
415
+ ok: result.error === null,
416
+ text: result.text,
417
+ error: result.error,
418
+ model: result.turn?.model ?? null,
419
+ rounds: result.turn ? undefined : null,
420
+ usage: result.turn
421
+ ? {
422
+ inputTokens: result.turn.inputTokens,
423
+ outputTokens: result.turn.outputTokens,
424
+ cachedTokens: result.turn.cachedTokens,
425
+ reportedCost: result.turn.reportedCost,
426
+ }
427
+ : null,
428
+ denials,
429
+ });
430
+ };
431
+
432
+ try {
433
+ for await (const line of io.stdin) {
434
+ const trimmed = line.trim();
435
+ if (!trimmed) continue;
436
+
437
+ let cmd: Record<string, unknown>;
438
+ try {
439
+ cmd = JSON.parse(trimmed) as Record<string, unknown>;
440
+ } catch {
441
+ emit({type: 'error', error: `invalid JSON: ${trimmed.slice(0, 80)}`});
442
+ continue;
443
+ }
444
+
445
+ const type = String(cmd.type ?? (cmd.prompt !== undefined ? 'prompt' : ''));
446
+ if (type === 'prompt') {
447
+ const text = String(cmd.text ?? cmd.prompt ?? '').trim();
448
+ if (!text) {
449
+ emit({type: 'prompt_result', ok: false, text: '', error: 'empty prompt'});
450
+ continue;
451
+ }
452
+ await runPrompt(text);
453
+ } else if (type === 'abort') {
454
+ abortRef.current?.abort();
455
+ emit({type: 'aborted'});
456
+ } else if (type === 'reset') {
457
+ messages.length = 0;
458
+ emit({type: 'reset'});
459
+ } else {
460
+ emit({type: 'error', error: `unknown command: ${type || trimmed.slice(0, 40)}`});
461
+ }
462
+
463
+ if (signal?.aborted) break;
464
+ }
465
+ } catch (err) {
466
+ emit({type: 'error', error: errorMessage(err)});
467
+ exitCode = 1;
468
+ }
469
+
470
+ return exitCode;
471
+ }
472
+
473
+ /**
474
+ * Split an arbitrary byte stream into lines, for `--mode rpc`.
475
+ *
476
+ * Handles the two things a naive `split('\n')` gets wrong: a final line without
477
+ * a trailing newline, and a JSON object arriving across two chunks.
478
+ */
479
+ export async function* linesOf(
480
+ stream: AsyncIterable<string | Uint8Array>,
481
+ ): AsyncGenerator<string> {
482
+ let buffer = '';
483
+ const decoder = new TextDecoder();
484
+ for await (const chunk of stream) {
485
+ buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, {stream: true});
486
+ let idx = buffer.indexOf('\n');
487
+ while (idx !== -1) {
488
+ yield buffer.slice(0, idx);
489
+ buffer = buffer.slice(idx + 1);
490
+ idx = buffer.indexOf('\n');
491
+ }
492
+ }
493
+ buffer += decoder.decode();
494
+ if (buffer.trim()) yield buffer;
495
+ }