@ngockhoale/ckit 0.2.10 → 0.3.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.
@@ -0,0 +1,23 @@
1
+ import type { AgentConfig } from '../types.js';
2
+ import { NativeSession } from './proc.js';
3
+ import type { SendOptions, SessionCommand } from './types.js';
4
+ export declare const codexSessionArgs: (agent: AgentConfig) => string[];
5
+ export declare class CodexSession extends NativeSession {
6
+ private readonly agent;
7
+ private readonly cmd;
8
+ protected readonly label = "codex";
9
+ private nextId;
10
+ private calls;
11
+ private threadId;
12
+ private turnId;
13
+ private lastMessage;
14
+ private tokens;
15
+ constructor(agent: AgentConfig, cwd: string, env: Readonly<Record<string, string>>, cmd: SessionCommand, grace: number);
16
+ private call;
17
+ protected start(): Promise<void>;
18
+ protected onProcessGone(why: string, stderr: string): void;
19
+ protected begin(prompt: string, opts: SendOptions): void;
20
+ steer(text: string): boolean;
21
+ protected interruptTurn(): void;
22
+ protected onLine(line: string): void;
23
+ }
@@ -0,0 +1,130 @@
1
+ import { cliArgTokens } from '../cli-args.js';
2
+ import { NativeSession, oneLine } from './proc.js';
3
+ export const codexSessionArgs = (agent) => ['app-server', '--listen', 'stdio://', ...cliArgTokens(agent.cliArgs)];
4
+ const textInput = (text, images = []) => [{ type: 'text', text, text_elements: [] }, ...images.slice(0, 8).map(path => ({ type: 'localImage', path }))];
5
+ export class CodexSession extends NativeSession {
6
+ agent;
7
+ cmd;
8
+ label = 'codex';
9
+ nextId = 1;
10
+ calls = new Map();
11
+ threadId = null;
12
+ turnId = null;
13
+ lastMessage = '';
14
+ tokens = null;
15
+ constructor(agent, cwd, env, cmd, grace) {
16
+ super(cwd, env, grace);
17
+ this.agent = agent;
18
+ this.cmd = cmd;
19
+ }
20
+ call(method, params, timeoutMs = 30000) {
21
+ return new Promise((resolve, reject) => {
22
+ const id = this.nextId++;
23
+ const timer = setTimeout(() => { this.calls.delete(id); reject(new Error(`${method} timed out`)); }, timeoutMs);
24
+ this.calls.set(id, { resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
25
+ if (!this.link?.write({ id, method, params })) {
26
+ this.calls.delete(id);
27
+ clearTimeout(timer);
28
+ reject(new Error('codex stdin closed'));
29
+ }
30
+ });
31
+ }
32
+ async start() {
33
+ this.spawnLink(this.cmd);
34
+ await this.call('initialize', { clientInfo: { name: 'ckit', version: '1.0.0' } });
35
+ this.link?.write({ method: 'initialized' });
36
+ const r = await this.call('thread/start', { cwd: this.cwd, sandbox: this.agent.access === 'write' ? 'workspace-write' : 'read-only', approvalPolicy: 'never', ...(this.agent.model ? { model: this.agent.model } : {}) });
37
+ const id = r?.thread?.id;
38
+ if (typeof id !== 'string')
39
+ throw new Error('thread/start returned no thread id');
40
+ this.threadId = id;
41
+ this.sessionId = id;
42
+ }
43
+ onProcessGone(why, stderr) {
44
+ for (const [, c] of this.calls)
45
+ c.reject(new Error(`codex ${why}`));
46
+ this.calls.clear();
47
+ this.threadId = null;
48
+ this.turnId = null;
49
+ super.onProcessGone(why, stderr);
50
+ }
51
+ begin(prompt, opts) {
52
+ this.lastMessage = '';
53
+ this.tokens = null;
54
+ this.turnId = null;
55
+ void this.call('turn/start', { threadId: this.threadId, input: textInput(prompt, opts.images), cwd: this.cwd }).then(r => {
56
+ if (typeof r?.turn?.id === 'string' && !this.turnId)
57
+ this.turnId = r.turn.id;
58
+ }).catch(e => { this.finishTurn({ ok: false, reason: `codex turn/start failed: ${oneLine(String(e instanceof Error ? e.message : e), 200)}`, transport: true }); });
59
+ }
60
+ steer(text) {
61
+ if (!this.turn || !this.turnId || !this.threadId || !text.trim())
62
+ return false;
63
+ return !!this.link?.write({ id: this.nextId++, method: 'turn/steer', params: { threadId: this.threadId, expectedTurnId: this.turnId, input: textInput(text) } });
64
+ }
65
+ interruptTurn() {
66
+ if (this.threadId && this.turnId)
67
+ this.link?.write({ id: this.nextId++, method: 'turn/interrupt', params: { threadId: this.threadId, turnId: this.turnId } });
68
+ }
69
+ onLine(line) {
70
+ if (!line.startsWith('{'))
71
+ return;
72
+ let f;
73
+ try {
74
+ f = JSON.parse(line);
75
+ }
76
+ catch {
77
+ return;
78
+ }
79
+ if (typeof f['id'] === 'number' && !f['method']) { // response to one of our calls
80
+ const c = this.calls.get(f['id']);
81
+ if (!c)
82
+ return;
83
+ this.calls.delete(f['id']);
84
+ if (f['error'])
85
+ c.reject(new Error(String(f['error']?.message ?? 'rpc error')));
86
+ else
87
+ c.resolve(f['result']);
88
+ return;
89
+ }
90
+ if (typeof f['id'] !== 'undefined' && typeof f['method'] === 'string') { // server request we do not serve (approvals are 'never'): refuse so it cannot hang
91
+ this.link?.write({ id: f['id'], error: { code: -32601, message: 'not supported by CKit' } });
92
+ return;
93
+ }
94
+ const m = f['method'], p = f['params'] ?? {}, t = this.turn;
95
+ if (!t || p.threadId !== this.threadId)
96
+ return;
97
+ if (m === 'turn/started' && typeof p.turn?.id === 'string') {
98
+ this.turnId = p.turn.id;
99
+ return;
100
+ }
101
+ if (m === 'item/agentMessage/delta' && typeof p.delta === 'string') {
102
+ t.opts.onDelta?.(p.delta);
103
+ return;
104
+ }
105
+ if (m === 'thread/tokenUsage/updated' && typeof p.tokenUsage?.last?.totalTokens === 'number') {
106
+ this.tokens = p.tokenUsage.last.totalTokens;
107
+ return;
108
+ }
109
+ if (m === 'item/started' || m === 'item/completed') {
110
+ const it = p.item ?? {};
111
+ if (m === 'item/completed' && it.type === 'agentMessage' && typeof it.text === 'string')
112
+ this.lastMessage = it.text;
113
+ if (m === 'item/started' && it.type === 'commandExecution')
114
+ t.opts.onActivity?.(oneLine(`$ ${String(it.command ?? '')}`));
115
+ if (m === 'item/completed' && it.type === 'fileChange')
116
+ t.opts.onActivity?.(oneLine(`edited ${Array.isArray(it.changes) ? it.changes.map((c) => c.path).filter(Boolean).join(', ') : 'files'}`));
117
+ return;
118
+ }
119
+ if (m === 'turn/completed') {
120
+ const turn = p.turn ?? {};
121
+ if (turn.status === 'failed')
122
+ this.finishTurn({ ok: false, reason: oneLine(String(turn.error?.message ?? 'turn failed'), 200) });
123
+ else if (turn.status === 'interrupted')
124
+ this.finishTurn({ ok: false, reason: 'cancelled' });
125
+ else
126
+ this.finishTurn(this.lastMessage.trim() ? { ok: true, text: this.lastMessage, tokens: this.tokens } : { ok: false, reason: 'agent returned no text' });
127
+ }
128
+ }
129
+ }
130
+ //# sourceMappingURL=codex.js.map
@@ -0,0 +1,4 @@
1
+ import type { AgentRunner } from '../runners.js';
2
+ import type { AgentConfig } from '../types.js';
3
+ import type { AgentSession, OpenSessionOptions } from './types.js';
4
+ export declare function createPerTurnSession(agent: AgentConfig, runner: AgentRunner, o: Pick<OpenSessionOptions, 'cwd' | 'env'>): AgentSession;
@@ -0,0 +1,33 @@
1
+ export function createPerTurnSession(agent, runner, o) {
2
+ let ctl = null, closed = false;
3
+ return {
4
+ kind: 'per-turn', sessionId: null,
5
+ async send(prompt, opts) {
6
+ if (closed)
7
+ return { ok: false, reason: 'cancelled' };
8
+ const c = ctl = new AbortController();
9
+ const relay = () => c.abort();
10
+ if (opts.signal?.aborted)
11
+ c.abort();
12
+ else
13
+ opts.signal?.addEventListener('abort', relay, { once: true });
14
+ try {
15
+ return await runner(agent, prompt, { cwd: o.cwd, timeoutMs: opts.timeoutMs, signal: c.signal, ...(o.env ? { env: o.env } : {}),
16
+ ...(opts.onActivity ? { onActivity: opts.onActivity } : {}), ...(opts.onRaw ? { onRaw: opts.onRaw } : {}), ...(opts.onStep ? { onStep: opts.onStep } : {}),
17
+ ...(opts.onSubagent ? { onSubagent: opts.onSubagent } : {}), ...(opts.images ? { images: opts.images } : {}) });
18
+ }
19
+ catch (e) {
20
+ return { ok: false, reason: e instanceof Error ? e.message : 'runner threw' };
21
+ }
22
+ finally {
23
+ opts.signal?.removeEventListener('abort', relay);
24
+ if (ctl === c)
25
+ ctl = null;
26
+ }
27
+ },
28
+ steer: () => false,
29
+ interrupt: () => { ctl?.abort(); },
30
+ close: () => { closed = true; ctl?.abort(); },
31
+ };
32
+ }
33
+ //# sourceMappingURL=fallback.js.map
@@ -0,0 +1,6 @@
1
+ import type { OpenSession } from './types.js';
2
+ export type { AgentSession, OpenSession, OpenSessionOptions, SendOptions, SessionCommand } from './types.js';
3
+ export { createPerTurnSession } from './fallback.js';
4
+ /** CKIT_SESSIONS=0 turns native sessions off (every agent runs per-turn, as before). */
5
+ export declare const sessionsEnabled: (env?: Readonly<Record<string, string | undefined>>) => boolean;
6
+ export declare const openSession: OpenSession;
@@ -0,0 +1,38 @@
1
+ // openSession(agent, opts): native long-lived driver for codex / claude-code / omp, per-turn fallback wrapper for everything else.
2
+ import { executorEnvironment, resolveExecutable, ExecutorResolveError, selectExecutor } from '../../adapters/launch/executor.js';
3
+ import { advisorKeyOf, codexConfigText, codexWorkerEnv, dispatchRunner, findOnPath } from '../runners.js';
4
+ import { ClaudeSession, claudeSessionArgs } from './claude.js';
5
+ import { CodexSession, codexSessionArgs } from './codex.js';
6
+ import { createPerTurnSession } from './fallback.js';
7
+ import { OmpSession, ompSessionArgs } from './omp.js';
8
+ export { createPerTurnSession } from './fallback.js';
9
+ /** CKIT_SESSIONS=0 turns native sessions off (every agent runs per-turn, as before). */
10
+ export const sessionsEnabled = (env = process.env) => env['CKIT_SESSIONS'] !== '0';
11
+ export const openSession = (agent, opts) => {
12
+ const perTurn = () => createPerTurnSession(agent, opts.runner ?? dispatchRunner, opts);
13
+ if (agent.cli !== 'codex' && agent.cli !== 'claude-code' && agent.cli !== 'omp')
14
+ return perTurn();
15
+ const grace = opts.killGraceMs ?? 3000;
16
+ try {
17
+ if (agent.cli === 'codex') {
18
+ const env = opts.env ?? codexWorkerEnv(process.env, advisorKeyOf(opts.cwd), codexConfigText(process.env)).env;
19
+ const path = opts.command?.path ?? findOnPath('codex', env);
20
+ if (!path)
21
+ return perTurn();
22
+ return new CodexSession(agent, opts.cwd, env, opts.command ?? { path, args: codexSessionArgs(agent) }, grace);
23
+ }
24
+ const kind = agent.cli === 'omp' ? 'omp' : 'claude-code';
25
+ const env = opts.env ?? executorEnvironment(process.env, advisorKeyOf(opts.cwd), kind);
26
+ const path = opts.command?.path ?? resolveExecutable(selectExecutor({ executor: kind, executorModel: null }), { executorPath: null }, env);
27
+ if (kind === 'omp')
28
+ return new OmpSession(opts.command ?? { path, args: ompSessionArgs(agent) }, opts.cwd, env, grace);
29
+ const cmd = (id) => opts.command ?? { path, args: claudeSessionArgs(agent, id) };
30
+ return new ClaudeSession(agent, opts.cwd, env, cmd, grace);
31
+ }
32
+ catch (e) {
33
+ if (e instanceof ExecutorResolveError)
34
+ return perTurn();
35
+ return perTurn();
36
+ }
37
+ };
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,20 @@
1
+ import type { AgentConfig } from '../types.js';
2
+ import { NativeSession } from './proc.js';
3
+ import type { SessionCommand } from './types.js';
4
+ export declare const ompSessionArgs: (agent: AgentConfig) => string[];
5
+ export declare class OmpSession extends NativeSession {
6
+ private readonly cmd;
7
+ protected readonly label = "omp";
8
+ private nextId;
9
+ private promptId;
10
+ private text;
11
+ private ready;
12
+ private isReady;
13
+ constructor(cmd: SessionCommand, cwd: string, env: Readonly<Record<string, string>>, grace: number);
14
+ protected start(): Promise<void>;
15
+ protected begin(prompt: string): void;
16
+ steer(text: string): boolean;
17
+ protected interruptTurn(): void;
18
+ protected onLine(line: string): void;
19
+ get started(): boolean;
20
+ }
@@ -0,0 +1,75 @@
1
+ import { cliArgTokens } from '../cli-args.js';
2
+ import { NativeSession, oneLine } from './proc.js';
3
+ export const ompSessionArgs = (agent) => ['--mode', 'rpc', '--no-ui', ...(agent.model ? ['--model', agent.model] : []), ...(agent.access === 'write' ? ['--approval-mode', 'write'] : ['--approval-mode', 'always-ask']), ...cliArgTokens(agent.cliArgs)];
4
+ export class OmpSession extends NativeSession {
5
+ cmd;
6
+ label = 'omp';
7
+ nextId = 1;
8
+ promptId = null;
9
+ text = '';
10
+ ready = null;
11
+ isReady = false;
12
+ constructor(cmd, cwd, env, grace) {
13
+ super(cwd, env, grace);
14
+ this.cmd = cmd;
15
+ }
16
+ async start() {
17
+ this.isReady = false;
18
+ const ready = new Promise((res, rej) => { this.ready = res; setTimeout(() => rej(new Error('omp rpc did not send ready')), 30000).unref(); });
19
+ this.spawnLink(this.cmd);
20
+ await ready;
21
+ }
22
+ begin(prompt) {
23
+ this.text = '';
24
+ this.promptId = `p${this.nextId++}`;
25
+ if (!this.link?.write({ id: this.promptId, type: 'prompt', message: `${prompt}` }))
26
+ throw new Error('could not write to omp stdin');
27
+ }
28
+ steer(text) { return !!this.turn && !!text.trim() && !!this.link?.write({ id: `s${this.nextId++}`, type: 'steer', message: text.trim() }); }
29
+ interruptTurn() { this.link?.write({ id: `a${this.nextId++}`, type: 'abort' }); }
30
+ onLine(line) {
31
+ if (!line.startsWith('{'))
32
+ return;
33
+ let f;
34
+ try {
35
+ f = JSON.parse(line);
36
+ }
37
+ catch {
38
+ return;
39
+ }
40
+ if (f['type'] === 'ready') {
41
+ this.isReady = true;
42
+ this.ready?.();
43
+ return;
44
+ }
45
+ const t = this.turn;
46
+ if (!t)
47
+ return;
48
+ if (f['type'] === 'response' && f['command'] === 'prompt' && f['success'] === false && f['id'] === this.promptId) {
49
+ this.finishTurn({ ok: false, reason: oneLine(String(f['error'] ?? 'prompt rejected'), 200) });
50
+ return;
51
+ }
52
+ if (f['type'] === 'message_update') {
53
+ const ev = f['assistantMessageEvent'];
54
+ if (ev?.type === 'text_delta' && typeof ev.delta === 'string') {
55
+ this.text += ev.delta;
56
+ t.opts.onDelta?.(ev.delta);
57
+ }
58
+ return;
59
+ }
60
+ if (f['type'] === 'message_end' && f['message']?.role === 'assistant' && Array.isArray(f['message'].content)) {
61
+ const txt = f['message'].content.filter(c => c.type === 'text' && typeof c.text === 'string').map(c => c.text).join('');
62
+ if (txt.trim())
63
+ this.text = txt;
64
+ return;
65
+ }
66
+ if (f['type'] === 'tool_execution_start') {
67
+ t.opts.onActivity?.(oneLine(`tool: ${String(f['toolName'] ?? '')}`));
68
+ return;
69
+ }
70
+ if (f['type'] === 'agent_end')
71
+ this.finishTurn(this.text.trim() ? { ok: true, text: this.text, tokens: null } : { ok: false, reason: 'agent returned no text' });
72
+ }
73
+ get started() { return this.isReady; }
74
+ }
75
+ //# sourceMappingURL=omp.js.map
@@ -0,0 +1,62 @@
1
+ import { type ChildProcess } from 'node:child_process';
2
+ import type { AgentRunResult } from '../runners.js';
3
+ import type { AgentSession, SendOptions, SessionCommand } from './types.js';
4
+ export declare const oneLine: (s: string, max?: number) => string;
5
+ /** A spawned child in its own process group; only that group is ever signalled. */
6
+ export declare class ProcLink {
7
+ readonly child: ChildProcess;
8
+ alive: boolean;
9
+ stderr: string;
10
+ private pending;
11
+ private killTimer;
12
+ constructor(cmd: SessionCommand, o: {
13
+ cwd: string;
14
+ env: Readonly<Record<string, string>>;
15
+ onLine: (line: string) => void;
16
+ onExit: (why: string) => void;
17
+ onRaw?: SendOptions['onRaw'];
18
+ killGraceMs: number;
19
+ });
20
+ private readonly grace;
21
+ write(obj: unknown): boolean;
22
+ private signal;
23
+ kill(): void;
24
+ }
25
+ interface Turn {
26
+ readonly opts: SendOptions;
27
+ resolve: (r: AgentRunResult) => void;
28
+ timer: NodeJS.Timeout;
29
+ grace?: NodeJS.Timeout;
30
+ stop: 'timeout' | 'cancelled' | null;
31
+ onAbort: () => void;
32
+ }
33
+ /** Base class: lazy start, one turn at a time, timeout/abort -> interrupt then kill, process death -> transport failure. */
34
+ export declare abstract class NativeSession implements AgentSession {
35
+ protected readonly cwd: string;
36
+ protected readonly env: Readonly<Record<string, string>>;
37
+ protected readonly killGraceMs: number;
38
+ readonly kind: 'native';
39
+ sessionId: string | null;
40
+ protected link: ProcLink | null;
41
+ protected turn: Turn | null;
42
+ protected closed: boolean;
43
+ private starting;
44
+ constructor(cwd: string, env: Readonly<Record<string, string>>, killGraceMs: number);
45
+ protected abstract readonly label: string;
46
+ /** Spawn + handshake. Implementations call spawnLink() and throw on failure. */
47
+ protected abstract start(): Promise<void>;
48
+ /** Write the turn's prompt. Returns once the request was handed over (completion arrives via frames -> finishTurn). */
49
+ protected abstract begin(prompt: string, opts: SendOptions): void | Promise<void>;
50
+ protected abstract onLine(line: string): void;
51
+ abstract steer(text: string): boolean;
52
+ protected abstract interruptTurn(): void;
53
+ protected spawnLink(cmd: SessionCommand): ProcLink;
54
+ protected onProcessGone(why: string, stderr: string): void;
55
+ send(prompt: string, opts: SendOptions): Promise<AgentRunResult>;
56
+ private stopTurn;
57
+ /** Settles the running turn exactly once. A stop requested earlier wins over whatever the CLI reported. */
58
+ protected finishTurn(res: AgentRunResult): void;
59
+ interrupt(): void;
60
+ close(): void;
61
+ }
62
+ export {};
@@ -0,0 +1,188 @@
1
+ // Shared plumbing for native session drivers: owned detached process group, NDJSON line framing, turn bookkeeping.
2
+ import { spawn } from 'node:child_process';
3
+ const STDERR_TAIL = 4000;
4
+ export const oneLine = (s, max = 160) => { const t = s.replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
5
+ /** A spawned child in its own process group; only that group is ever signalled. */
6
+ export class ProcLink {
7
+ child;
8
+ alive = true;
9
+ stderr = '';
10
+ pending = '';
11
+ killTimer;
12
+ constructor(cmd, o) {
13
+ this.grace = o.killGraceMs;
14
+ const grouped = process.platform !== 'win32';
15
+ this.child = spawn(cmd.path, [...cmd.args], { cwd: o.cwd, shell: false, env: o.env, stdio: ['pipe', 'pipe', 'pipe'], ...(grouped ? { detached: true } : {}) });
16
+ this.child.stdin?.on('error', () => { });
17
+ this.child.stdout?.on('data', (chunk) => {
18
+ this.pending += chunk.toString('utf8');
19
+ const lines = this.pending.split('\n');
20
+ this.pending = lines.pop() ?? '';
21
+ for (const l of lines) {
22
+ if (!l.trim())
23
+ continue;
24
+ try {
25
+ o.onRaw?.('stdout', l.slice(0, 4000));
26
+ }
27
+ catch { /* observer */ }
28
+ o.onLine(l);
29
+ }
30
+ });
31
+ this.child.stderr?.on('data', (chunk) => { const t = chunk.toString('utf8'); try {
32
+ o.onRaw?.('stderr', t.slice(0, 4000));
33
+ }
34
+ catch { /* observer */ } this.stderr = (this.stderr + t).slice(-STDERR_TAIL); });
35
+ const gone = (why) => { if (!this.alive)
36
+ return; this.alive = false; clearTimeout(this.killTimer); o.onExit(why); };
37
+ this.child.on('error', e => gone(`could not start: ${e.message}`));
38
+ this.child.on('close', (code, sig) => gone(`exited ${code !== null ? `with code ${code}` : `by ${sig ?? 'signal'}`}`));
39
+ }
40
+ grace;
41
+ write(obj) {
42
+ if (!this.alive || !this.child.stdin?.writable)
43
+ return false;
44
+ try {
45
+ this.child.stdin.write(`${JSON.stringify(obj)}\n`);
46
+ return true;
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ }
52
+ signal(sig) {
53
+ const pid = this.child.pid;
54
+ if (process.platform !== 'win32' && typeof pid === 'number' && pid > 1) {
55
+ try {
56
+ process.kill(-pid, sig);
57
+ return;
58
+ }
59
+ catch { /* group gone */ }
60
+ }
61
+ try {
62
+ this.child.kill(sig);
63
+ }
64
+ catch { /* already gone */ }
65
+ }
66
+ kill() {
67
+ if (!this.alive)
68
+ return;
69
+ try {
70
+ this.child.stdin?.end();
71
+ }
72
+ catch { /* ignore */ }
73
+ this.signal('SIGTERM');
74
+ this.killTimer = setTimeout(() => { if (this.alive)
75
+ this.signal('SIGKILL'); }, this.grace);
76
+ this.killTimer.unref();
77
+ }
78
+ }
79
+ /** Base class: lazy start, one turn at a time, timeout/abort -> interrupt then kill, process death -> transport failure. */
80
+ export class NativeSession {
81
+ cwd;
82
+ env;
83
+ killGraceMs;
84
+ kind = 'native';
85
+ sessionId = null;
86
+ link = null;
87
+ turn = null;
88
+ closed = false;
89
+ starting = null;
90
+ constructor(cwd, env, killGraceMs) {
91
+ this.cwd = cwd;
92
+ this.env = env;
93
+ this.killGraceMs = killGraceMs;
94
+ }
95
+ spawnLink(cmd) {
96
+ const link = new ProcLink(cmd, { cwd: this.cwd, env: this.env, killGraceMs: this.killGraceMs,
97
+ onLine: l => { if (this.link === link)
98
+ this.onLine(l); },
99
+ onExit: why => {
100
+ if (this.link === link)
101
+ this.link = null;
102
+ this.onProcessGone(why, link.stderr);
103
+ },
104
+ onRaw: (s, l) => this.turn?.opts.onRaw?.(s, l) });
105
+ this.link = link;
106
+ return link;
107
+ }
108
+ onProcessGone(why, stderr) {
109
+ this.starting = null;
110
+ this.finishTurn({ ok: false, reason: `${this.label} ${why}${stderr.trim() ? ` (${oneLine(stderr, 200)})` : ''}`, transport: true });
111
+ }
112
+ async send(prompt, opts) {
113
+ if (this.closed)
114
+ return { ok: false, reason: `${this.label} session is closed`, transport: true };
115
+ if (this.turn)
116
+ return { ok: false, reason: `${this.label} session is busy with another turn` };
117
+ if (opts.signal?.aborted)
118
+ return { ok: false, reason: 'cancelled' };
119
+ return new Promise(resolve => {
120
+ const turn = { opts, resolve, stop: null,
121
+ timer: setTimeout(() => this.stopTurn('timeout'), opts.timeoutMs),
122
+ onAbort: () => this.stopTurn('cancelled') };
123
+ this.turn = turn;
124
+ opts.signal?.addEventListener('abort', turn.onAbort, { once: true });
125
+ void (async () => {
126
+ try {
127
+ if (!this.link) {
128
+ this.starting ??= this.start();
129
+ await this.starting;
130
+ }
131
+ if (this.turn !== turn)
132
+ return;
133
+ await this.begin(prompt, opts);
134
+ }
135
+ catch (e) {
136
+ this.starting = null;
137
+ if (this.turn === turn) {
138
+ this.link?.kill();
139
+ this.link = null;
140
+ this.finishTurn({ ok: false, reason: `${this.label} failed to start: ${e instanceof Error ? e.message : String(e)}`, transport: true });
141
+ }
142
+ }
143
+ })();
144
+ });
145
+ }
146
+ stopTurn(why) {
147
+ const t = this.turn;
148
+ if (!t || t.stop)
149
+ return;
150
+ t.stop = why;
151
+ try {
152
+ this.interruptTurn();
153
+ }
154
+ catch { /* fall through to kill */ }
155
+ t.grace = setTimeout(() => { if (this.turn === t) {
156
+ this.link?.kill();
157
+ this.link = null;
158
+ this.starting = null;
159
+ this.finishTurn({ ok: false, reason: 'x' });
160
+ } }, this.killGraceMs);
161
+ }
162
+ /** Settles the running turn exactly once. A stop requested earlier wins over whatever the CLI reported. */
163
+ finishTurn(res) {
164
+ const t = this.turn;
165
+ if (!t)
166
+ return;
167
+ this.turn = null;
168
+ clearTimeout(t.timer);
169
+ clearTimeout(t.grace);
170
+ t.opts.signal?.removeEventListener('abort', t.onAbort);
171
+ t.resolve(t.stop ? { ok: false, reason: t.stop === 'timeout' ? 'timed out' : 'cancelled' } : res);
172
+ }
173
+ interrupt() { if (this.turn) {
174
+ try {
175
+ this.interruptTurn();
176
+ }
177
+ catch { /* best effort */ }
178
+ } }
179
+ close() {
180
+ if (this.closed)
181
+ return;
182
+ this.closed = true;
183
+ this.link?.kill();
184
+ this.link = null;
185
+ this.finishTurn({ ok: false, reason: 'cancelled' });
186
+ }
187
+ }
188
+ //# sourceMappingURL=proc.js.map
@@ -0,0 +1,43 @@
1
+ import type { AgentRunOptions, AgentRunResult, AgentRunner, SubagentSignal } from '../runners.js';
2
+ import type { AgentConfig } from '../types.js';
3
+ export interface SendOptions {
4
+ readonly timeoutMs: number;
5
+ readonly signal?: AbortSignal;
6
+ readonly onActivity?: (text: string) => void;
7
+ /** Partial assistant text as it is produced (raw chunks; the engine coalesces). */
8
+ readonly onDelta?: (text: string) => void;
9
+ readonly onRaw?: AgentRunOptions['onRaw'];
10
+ readonly onStep?: AgentRunOptions['onStep'];
11
+ readonly onSubagent?: (e: SubagentSignal) => void;
12
+ /** Absolute paths of owner-attached images (codex gets image inputs; the others open them by path from the prompt). */
13
+ readonly images?: readonly string[];
14
+ }
15
+ export interface AgentSession {
16
+ /** Runs one turn. Never throws. A failed result with `transport: true` means the process/protocol broke and the turn may be retried per-turn. */
17
+ send(prompt: string, opts: SendOptions): Promise<AgentRunResult>;
18
+ /** Add guidance to the running turn. true = delivered natively mid-turn; false = not delivered natively (claude: held and prepended to the next send). */
19
+ steer(text: string): boolean;
20
+ /** Ask the running turn to stop (the session stays usable). */
21
+ interrupt(): void;
22
+ /** Kill the owned process group. Idempotent. */
23
+ close(): void;
24
+ readonly sessionId: string | null;
25
+ /** 'native' = long-lived CLI process; 'per-turn' = fallback wrapper around the one-process-per-turn runner. */
26
+ readonly kind: 'native' | 'per-turn';
27
+ }
28
+ export interface SessionCommand {
29
+ readonly path: string;
30
+ readonly args: readonly string[];
31
+ }
32
+ export interface OpenSessionOptions {
33
+ readonly cwd: string;
34
+ /** Child env; omitted = derived through the same worker-env policy as the per-turn runners. */
35
+ readonly env?: Readonly<Record<string, string>>;
36
+ /** Replace the resolved executable + args entirely (tests: a fake protocol server). */
37
+ readonly command?: SessionCommand;
38
+ /** Runner used by the per-turn fallback driver (default dispatchRunner). */
39
+ readonly runner?: AgentRunner;
40
+ /** Grace between a polite stop and SIGKILL (default 3000). */
41
+ readonly killGraceMs?: number;
42
+ }
43
+ export type OpenSession = (agent: AgentConfig, opts: OpenSessionOptions) => AgentSession;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -121,6 +121,12 @@ export type TeamEvent = {
121
121
  readonly agentId: string;
122
122
  readonly text: string;
123
123
  }
124
+ /** Partial assistant text from a native session (coalesced ~250 ms; not a finished message). Not journaled to events.jsonl: live listeners only. */
125
+ | {
126
+ readonly type: 'agent.delta';
127
+ readonly agentId: string;
128
+ readonly text: string;
129
+ }
124
130
  /** A finished turn. `to` = addressee agent id, team id, or 'all'. */
125
131
  | {
126
132
  readonly type: 'agent.message';