@ngockhoale/ckit 0.3.1 → 0.4.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.
Files changed (38) hide show
  1. package/README.md +14 -2
  2. package/dist/src/cli/ckit.js +0 -0
  3. package/dist/src/gui/server.d.ts +3 -1
  4. package/dist/src/gui/server.js +41 -15
  5. package/dist/src/team/bus.d.ts +60 -0
  6. package/dist/src/team/bus.js +172 -0
  7. package/dist/src/team/config.js +5 -4
  8. package/dist/src/team/engine.d.ts +33 -1
  9. package/dist/src/team/engine.js +1095 -170
  10. package/dist/src/team/mcp/hub.d.ts +16 -0
  11. package/dist/src/team/mcp/hub.js +99 -0
  12. package/dist/src/team/mcp/stdio-server.d.ts +2 -0
  13. package/dist/src/team/mcp/stdio-server.js +103 -0
  14. package/dist/src/team/runners.d.ts +4 -0
  15. package/dist/src/team/runners.js +8 -2
  16. package/dist/src/team/scheduler.d.ts +20 -0
  17. package/dist/src/team/scheduler.js +73 -0
  18. package/dist/src/team/sessions/claude.d.ts +16 -5
  19. package/dist/src/team/sessions/claude.js +127 -13
  20. package/dist/src/team/sessions/codex.d.ts +3 -2
  21. package/dist/src/team/sessions/codex.js +21 -3
  22. package/dist/src/team/sessions/fallback.js +6 -2
  23. package/dist/src/team/sessions/index.d.ts +1 -1
  24. package/dist/src/team/sessions/index.js +3 -3
  25. package/dist/src/team/sessions/omp.d.ts +12 -3
  26. package/dist/src/team/sessions/omp.js +95 -8
  27. package/dist/src/team/sessions/proc.d.ts +20 -2
  28. package/dist/src/team/sessions/proc.js +64 -18
  29. package/dist/src/team/sessions/types.d.ts +23 -2
  30. package/dist/src/team/telemetry.d.ts +32 -0
  31. package/dist/src/team/telemetry.js +135 -0
  32. package/dist/src/team/types.d.ts +173 -1
  33. package/dist/src/tui/team/model.js +10 -0
  34. package/gui/app.css +23 -0
  35. package/gui/app.js +208 -6
  36. package/gui/comic/engine.js +44 -0
  37. package/gui/index.html +1 -1
  38. package/package.json +1 -1
@@ -1,10 +1,11 @@
1
1
  import { cliArgTokens } from '../cli-args.js';
2
- import { NativeSession, oneLine } from './proc.js';
2
+ import { NativeSession, oneLine, rawTool } from './proc.js';
3
3
  export const codexSessionArgs = (agent) => ['app-server', '--listen', 'stdio://', ...cliArgTokens(agent.cliArgs)];
4
4
  const textInput = (text, images = []) => [{ type: 'text', text, text_elements: [] }, ...images.slice(0, 8).map(path => ({ type: 'localImage', path }))];
5
5
  export class CodexSession extends NativeSession {
6
6
  agent;
7
7
  cmd;
8
+ tools;
8
9
  label = 'codex';
9
10
  nextId = 1;
10
11
  calls = new Map();
@@ -12,10 +13,11 @@ export class CodexSession extends NativeSession {
12
13
  turnId = null;
13
14
  lastMessage = '';
14
15
  tokens = null;
15
- constructor(agent, cwd, env, cmd, grace) {
16
+ constructor(agent, cwd, env, cmd, grace, tools) {
16
17
  super(cwd, env, grace);
17
18
  this.agent = agent;
18
19
  this.cmd = cmd;
20
+ this.tools = tools;
19
21
  }
20
22
  call(method, params, timeoutMs = 30000) {
21
23
  return new Promise((resolve, reject) => {
@@ -33,7 +35,8 @@ export class CodexSession extends NativeSession {
33
35
  this.spawnLink(this.cmd);
34
36
  await this.call('initialize', { clientInfo: { name: 'ckit', version: '1.0.0' } });
35
37
  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 } : {}) });
38
+ 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 } : {}),
39
+ ...(this.tools ? { config: { mcp_servers: { ckit: { command: this.tools.mcp.command, args: this.tools.mcp.args, env: this.tools.mcp.env, default_tools_approval_mode: 'approve' } } } } : {}) });
37
40
  const id = r?.thread?.id;
38
41
  if (typeof id !== 'string')
39
42
  throw new Error('thread/start returned no thread id');
@@ -112,6 +115,21 @@ export class CodexSession extends NativeSession {
112
115
  this.lastMessage = it.text;
113
116
  if (m === 'item/started' && it.type === 'commandExecution')
114
117
  t.opts.onActivity?.(oneLine(`$ ${String(it.command ?? '')}`));
118
+ if (it.type === 'mcpToolCall' || it.type === 'commandExecution') {
119
+ const name = it.type === 'mcpToolCall' ? `${String(it.server ?? 'mcp')}.${String(it.tool ?? 'tool')}` : 'shell';
120
+ if (m === 'item/started') {
121
+ this.markFirst();
122
+ t.opts.onTool?.('call', name, rawTool(it.type === 'mcpToolCall' ? JSON.stringify(it.arguments ?? {}) : String(it.command ?? '')));
123
+ }
124
+ else {
125
+ const out = it.type === 'mcpToolCall'
126
+ ? (Array.isArray(it.result?.content) ? it.result.content.map((c) => typeof c?.text === 'string' ? c.text : '').join(' ') : '') || String(it.error?.message ?? it.error ?? '')
127
+ : String(it.aggregatedOutput ?? it.output ?? '');
128
+ t.opts.onTool?.('result', name, rawTool(out));
129
+ }
130
+ }
131
+ if (m === 'item/started' && it.type === 'agentMessage')
132
+ this.markFirst();
115
133
  if (m === 'item/completed' && it.type === 'fileChange')
116
134
  t.opts.onActivity?.(oneLine(`edited ${Array.isArray(it.changes) ? it.changes.map((c) => c.path).filter(Boolean).join(', ') : 'files'}`));
117
135
  return;
@@ -6,6 +6,7 @@ export function createPerTurnSession(agent, runner, o) {
6
6
  if (closed)
7
7
  return { ok: false, reason: 'cancelled' };
8
8
  const c = ctl = new AbortController();
9
+ let first = false;
9
10
  const relay = () => c.abort();
10
11
  if (opts.signal?.aborted)
11
12
  c.abort();
@@ -13,7 +14,10 @@ export function createPerTurnSession(agent, runner, o) {
13
14
  opts.signal?.addEventListener('abort', relay, { once: true });
14
15
  try {
15
16
  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.onActivity || opts.onFirstOutput ? { onActivity: (t) => { if (!first) {
18
+ first = true;
19
+ opts.onFirstOutput?.();
20
+ } opts.onActivity?.(t); } } : {}), ...(opts.onRaw ? { onRaw: opts.onRaw } : {}), ...(opts.onStep ? { onStep: opts.onStep } : {}),
17
21
  ...(opts.onSubagent ? { onSubagent: opts.onSubagent } : {}), ...(opts.images ? { images: opts.images } : {}) });
18
22
  }
19
23
  catch (e) {
@@ -27,7 +31,7 @@ export function createPerTurnSession(agent, runner, o) {
27
31
  },
28
32
  steer: () => false,
29
33
  interrupt: () => { ctl?.abort(); },
30
- close: () => { closed = true; ctl?.abort(); },
34
+ close: () => { closed = true; ctl?.abort(); return Promise.resolve(); },
31
35
  };
32
36
  }
33
37
  //# sourceMappingURL=fallback.js.map
@@ -1,5 +1,5 @@
1
1
  import type { OpenSession } from './types.js';
2
- export type { AgentSession, OpenSession, OpenSessionOptions, SendOptions, SessionCommand } from './types.js';
2
+ export type { AgentSession, OpenSession, OpenSessionOptions, SendOptions, SessionCommand, SessionTools } from './types.js';
3
3
  export { createPerTurnSession } from './fallback.js';
4
4
  /** CKIT_SESSIONS=0 turns native sessions off (every agent runs per-turn, as before). */
5
5
  export declare const sessionsEnabled: (env?: Readonly<Record<string, string | undefined>>) => boolean;
@@ -19,14 +19,14 @@ export const openSession = (agent, opts) => {
19
19
  const path = opts.command?.path ?? findOnPath('codex', env);
20
20
  if (!path)
21
21
  return perTurn();
22
- return new CodexSession(agent, opts.cwd, env, opts.command ?? { path, args: codexSessionArgs(agent) }, grace);
22
+ return new CodexSession(agent, opts.cwd, env, opts.command ?? { path, args: codexSessionArgs(agent) }, grace, opts.tools);
23
23
  }
24
24
  const kind = agent.cli === 'omp' ? 'omp' : 'claude-code';
25
25
  const env = opts.env ?? executorEnvironment(process.env, advisorKeyOf(opts.cwd), kind);
26
26
  const path = opts.command?.path ?? resolveExecutable(selectExecutor({ executor: kind, executorModel: null }), { executorPath: null }, env);
27
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) };
28
+ return new OmpSession(opts.command ?? { path, args: ompSessionArgs(agent) }, opts.cwd, env, grace, opts.tools);
29
+ const cmd = (id, resume) => opts.command ?? { path, args: claudeSessionArgs(agent, id, opts.tools, resume) };
30
30
  return new ClaudeSession(agent, opts.cwd, env, cmd, grace);
31
31
  }
32
32
  catch (e) {
@@ -1,20 +1,29 @@
1
1
  import type { AgentConfig } from '../types.js';
2
2
  import { NativeSession } from './proc.js';
3
- import type { SessionCommand } from './types.js';
3
+ import type { SendOptions, SessionCommand, SessionTools } from './types.js';
4
4
  export declare const ompSessionArgs: (agent: AgentConfig) => string[];
5
5
  export declare class OmpSession extends NativeSession {
6
6
  private readonly cmd;
7
+ private readonly tools?;
7
8
  protected readonly label = "omp";
8
9
  private nextId;
9
10
  private promptId;
10
11
  private text;
11
12
  private ready;
12
13
  private isReady;
13
- constructor(cmd: SessionCommand, cwd: string, env: Readonly<Record<string, string>>, grace: number);
14
+ private waiters;
15
+ private lastTotal;
16
+ private toolCalls;
17
+ constructor(cmd: SessionCommand, cwd: string, env: Readonly<Record<string, string>>, grace: number, tools?: SessionTools | undefined);
18
+ private request;
14
19
  protected start(): Promise<void>;
15
- protected begin(prompt: string): void;
20
+ protected onProcessGone(why: string, stderr: string): void;
21
+ protected begin(prompt: string, opts: SendOptions): void;
16
22
  steer(text: string): boolean;
17
23
  protected interruptTurn(): void;
24
+ private hostTool;
25
+ /** Token delta of this turn from get_session_stats; null when stats do not arrive in ~3 s. */
26
+ private turnTokens;
18
27
  protected onLine(line: string): void;
19
28
  get started(): boolean;
20
29
  }
@@ -1,32 +1,85 @@
1
1
  import { cliArgTokens } from '../cli-args.js';
2
- import { NativeSession, oneLine } from './proc.js';
2
+ import { NativeSession, loadImages, oneLine, rawTool } from './proc.js';
3
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
4
  export class OmpSession extends NativeSession {
5
5
  cmd;
6
+ tools;
6
7
  label = 'omp';
7
8
  nextId = 1;
8
9
  promptId = null;
9
10
  text = '';
10
11
  ready = null;
11
12
  isReady = false;
12
- constructor(cmd, cwd, env, grace) {
13
+ waiters = new Map(); // rpc responses we await, by command id
14
+ lastTotal = 0;
15
+ toolCalls = new Map();
16
+ constructor(cmd, cwd, env, grace, tools) {
13
17
  super(cwd, env, grace);
14
18
  this.cmd = cmd;
19
+ this.tools = tools;
20
+ }
21
+ request(obj, ms) {
22
+ return new Promise(resolve => {
23
+ const id = `r${this.nextId++}`;
24
+ const timer = setTimeout(() => { this.waiters.delete(id); resolve(null); }, ms);
25
+ timer.unref();
26
+ this.waiters.set(id, { resolve: f => { clearTimeout(timer); resolve(f); }, timer });
27
+ if (!this.link?.write({ ...obj, id })) {
28
+ this.waiters.delete(id);
29
+ clearTimeout(timer);
30
+ resolve(null);
31
+ }
32
+ });
15
33
  }
16
34
  async start() {
17
35
  this.isReady = false;
36
+ this.lastTotal = 0;
18
37
  const ready = new Promise((res, rej) => { this.ready = res; setTimeout(() => rej(new Error('omp rpc did not send ready')), 30000).unref(); });
19
38
  this.spawnLink(this.cmd);
20
39
  await ready;
40
+ if (this.tools) {
41
+ const r = await this.request({ type: 'set_host_tools', tools: this.tools.specs.map(s => ({ name: s.name, description: s.description, parameters: s.parameters, loadMode: 'essential' })) }, 10000);
42
+ if (!r || r['success'] === false)
43
+ throw new Error(`omp set_host_tools failed${r ? `: ${String(r['error'] ?? '')}` : ' (no reply)'}`);
44
+ }
45
+ }
46
+ onProcessGone(why, stderr) {
47
+ for (const [, w] of this.waiters) {
48
+ clearTimeout(w.timer);
49
+ w.resolve({ success: false, error: `omp ${why}` });
50
+ }
51
+ this.waiters.clear();
52
+ super.onProcessGone(why, stderr);
21
53
  }
22
- begin(prompt) {
54
+ begin(prompt, opts) {
23
55
  this.text = '';
24
56
  this.promptId = `p${this.nextId++}`;
25
- if (!this.link?.write({ id: this.promptId, type: 'prompt', message: `${prompt}` }))
57
+ const imgs = loadImages(opts.images);
58
+ if (!this.link?.write({ id: this.promptId, type: 'prompt', message: `${prompt}`, ...(imgs.length ? { images: imgs.map(i => ({ type: 'image', data: i.data, mimeType: i.mediaType })) } : {}) }))
26
59
  throw new Error('could not write to omp stdin');
27
60
  }
28
61
  steer(text) { return !!this.turn && !!text.trim() && !!this.link?.write({ id: `s${this.nextId++}`, type: 'steer', message: text.trim() }); }
29
62
  interruptTurn() { this.link?.write({ id: `a${this.nextId++}`, type: 'abort' }); }
63
+ hostTool(f) {
64
+ const id = f['id'], name = String(f['toolName'] ?? '');
65
+ const link = this.link;
66
+ const answer = (text, isError) => { link?.write({ type: 'host_tool_result', id, result: { content: [{ type: 'text', text }] }, isError }); };
67
+ if (!this.tools) {
68
+ answer('no host tools registered', true);
69
+ return;
70
+ }
71
+ this.tools.call(name, f['arguments']).then(r => answer(r.text, r.isError === true), e => answer(`tool failed: ${e instanceof Error ? e.message : String(e)}`, true));
72
+ }
73
+ /** Token delta of this turn from get_session_stats; null when stats do not arrive in ~3 s. */
74
+ async turnTokens() {
75
+ const r = await this.request({ type: 'get_session_stats' }, 3000);
76
+ const total = r?.['success'] === false ? undefined : r?.['data']?.tokens?.total;
77
+ if (typeof total !== 'number')
78
+ return null;
79
+ const delta = total - this.lastTotal;
80
+ this.lastTotal = total;
81
+ return delta >= 0 ? delta : total;
82
+ }
30
83
  onLine(line) {
31
84
  if (!line.startsWith('{'))
32
85
  return;
@@ -42,6 +95,18 @@ export class OmpSession extends NativeSession {
42
95
  this.ready?.();
43
96
  return;
44
97
  }
98
+ if (f['type'] === 'response' && typeof f['id'] === 'string' && this.waiters.has(f['id'])) {
99
+ const w = this.waiters.get(f['id']);
100
+ this.waiters.delete(f['id']);
101
+ w.resolve(f);
102
+ return;
103
+ }
104
+ if (f['type'] === 'host_tool_call') {
105
+ this.hostTool(f);
106
+ return;
107
+ }
108
+ if (f['type'] === 'host_tool_cancel')
109
+ return; // tool results are idempotent text; a late answer is ignored by omp
45
110
  const t = this.turn;
46
111
  if (!t)
47
112
  return;
@@ -53,22 +118,44 @@ export class OmpSession extends NativeSession {
53
118
  const ev = f['assistantMessageEvent'];
54
119
  if (ev?.type === 'text_delta' && typeof ev.delta === 'string') {
55
120
  this.text += ev.delta;
121
+ this.markFirst();
56
122
  t.opts.onDelta?.(ev.delta);
57
123
  }
58
124
  return;
59
125
  }
60
126
  if (f['type'] === 'message_end' && f['message']?.role === 'assistant' && Array.isArray(f['message'].content)) {
61
127
  const txt = f['message'].content.filter(c => c.type === 'text' && typeof c.text === 'string').map(c => c.text).join('');
62
- if (txt.trim())
128
+ if (txt.trim()) {
63
129
  this.text = txt;
130
+ this.markFirst();
131
+ }
64
132
  return;
65
133
  }
66
134
  if (f['type'] === 'tool_execution_start') {
67
- t.opts.onActivity?.(oneLine(`tool: ${String(f['toolName'] ?? '')}`));
135
+ const name = String(f['toolName'] ?? '');
136
+ if (typeof f['toolCallId'] === 'string')
137
+ this.toolCalls.set(f['toolCallId'], name);
138
+ this.markFirst();
139
+ t.opts.onActivity?.(oneLine(`tool: ${name}`));
140
+ t.opts.onTool?.('call', name, rawTool(JSON.stringify(f['args'] ?? f['arguments'] ?? f['input'] ?? {})));
141
+ return;
142
+ }
143
+ if (f['type'] === 'tool_execution_end') {
144
+ const name = String(f['toolName'] ?? this.toolCalls.get(String(f['toolCallId'])) ?? 'tool'), r = f['result'] ?? f['output'];
145
+ const text = typeof r === 'string' ? r : Array.isArray(r?.content) ? r.content.map((c) => typeof c?.text === 'string' ? c.text : '').join(' ') : r === undefined ? '' : JSON.stringify(r);
146
+ t.opts.onTool?.('result', name, rawTool(text));
68
147
  return;
69
148
  }
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' });
149
+ if (f['type'] === 'agent_end') {
150
+ const ok = this.text.trim().length > 0, text = this.text;
151
+ const turn = t;
152
+ void (async () => {
153
+ const tokens = ok && !turn.stop ? await this.turnTokens() : null;
154
+ if (this.turn !== turn)
155
+ return;
156
+ this.finishTurn(ok ? { ok: true, text, tokens } : { ok: false, reason: 'agent returned no text' });
157
+ })();
158
+ }
72
159
  }
73
160
  get started() { return this.isReady; }
74
161
  }
@@ -1,7 +1,14 @@
1
1
  import { type ChildProcess } from 'node:child_process';
2
2
  import type { AgentRunResult } from '../runners.js';
3
3
  import type { AgentSession, SendOptions, SessionCommand } from './types.js';
4
+ /** Owner-attached images as base64 (png/jpeg/gif/webp only; unreadable files and files over 5 MB are skipped; at most 8). */
5
+ export declare function loadImages(paths: readonly string[] | undefined): {
6
+ mediaType: string;
7
+ data: string;
8
+ }[];
4
9
  export declare const oneLine: (s: string, max?: number) => string;
10
+ /** Tool call/result text handed to onTool: whole (memory-capped at 16k), never cut short, so the engine redacts BEFORE it shortens for display. */
11
+ export declare const rawTool: (s: string) => string;
5
12
  /** A spawned child in its own process group; only that group is ever signalled. */
6
13
  export declare class ProcLink {
7
14
  readonly child: ChildProcess;
@@ -9,6 +16,8 @@ export declare class ProcLink {
9
16
  stderr: string;
10
17
  private pending;
11
18
  private killTimer;
19
+ /** Resolves once the child is gone (closed, or failed to start). */
20
+ readonly exited: Promise<void>;
12
21
  constructor(cmd: SessionCommand, o: {
13
22
  cwd: string;
14
23
  env: Readonly<Record<string, string>>;
@@ -29,6 +38,7 @@ interface Turn {
29
38
  grace?: NodeJS.Timeout;
30
39
  stop: 'timeout' | 'cancelled' | null;
31
40
  onAbort: () => void;
41
+ first?: boolean;
32
42
  }
33
43
  /** Base class: lazy start, one turn at a time, timeout/abort -> interrupt then kill, process death -> transport failure. */
34
44
  export declare abstract class NativeSession implements AgentSession {
@@ -40,7 +50,9 @@ export declare abstract class NativeSession implements AgentSession {
40
50
  protected link: ProcLink | null;
41
51
  protected turn: Turn | null;
42
52
  protected closed: boolean;
43
- private starting;
53
+ protected starting: Promise<void> | null;
54
+ /** Every spawned link that has not exited yet (a dropped link may still be shutting down). */
55
+ private readonly live;
44
56
  constructor(cwd: string, env: Readonly<Record<string, string>>, killGraceMs: number);
45
57
  protected abstract readonly label: string;
46
58
  /** Spawn + handshake. Implementations call spawnLink() and throw on failure. */
@@ -53,10 +65,16 @@ export declare abstract class NativeSession implements AgentSession {
53
65
  protected spawnLink(cmd: SessionCommand): ProcLink;
54
66
  protected onProcessGone(why: string, stderr: string): void;
55
67
  send(prompt: string, opts: SendOptions): Promise<AgentRunResult>;
68
+ /** Kill and forget the current process so the next turn starts a fresh one. */
69
+ protected dropLink(): void;
70
+ /** Call at the first frame of the turn's model output (delta, tool call, message): fires onFirstOutput once per turn. */
71
+ protected markFirst(): void;
56
72
  private stopTurn;
57
73
  /** Settles the running turn exactly once. A stop requested earlier wins over whatever the CLI reported. */
58
74
  protected finishTurn(res: AgentRunResult): void;
75
+ /** Owner interrupt: the turn resolves 'cancelled' (interrupt first, kill after the grace if the CLI ignores it). */
59
76
  interrupt(): void;
60
- close(): void;
77
+ /** Kills every owned process group; resolves once all of them have exited (SIGKILL after the grace). */
78
+ close(): Promise<void>;
61
79
  }
62
80
  export {};
@@ -1,7 +1,31 @@
1
1
  // Shared plumbing for native session drivers: owned detached process group, NDJSON line framing, turn bookkeeping.
2
2
  import { spawn } from 'node:child_process';
3
+ import { readFileSync, statSync } from 'node:fs';
4
+ import { extname } from 'node:path';
3
5
  const STDERR_TAIL = 4000;
6
+ const IMAGE_TYPES = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
7
+ const IMAGE_MAX_BYTES = 5 * 1024 * 1024;
8
+ /** Owner-attached images as base64 (png/jpeg/gif/webp only; unreadable files and files over 5 MB are skipped; at most 8). */
9
+ export function loadImages(paths) {
10
+ const out = [];
11
+ for (const p of paths ?? []) {
12
+ if (out.length >= 8)
13
+ break;
14
+ const mediaType = IMAGE_TYPES[extname(p).toLowerCase()];
15
+ if (!mediaType)
16
+ continue;
17
+ try {
18
+ if (statSync(p).size > IMAGE_MAX_BYTES)
19
+ continue;
20
+ out.push({ mediaType, data: readFileSync(p).toString('base64') });
21
+ }
22
+ catch { /* unreadable: skip */ }
23
+ }
24
+ return out;
25
+ }
4
26
  export const oneLine = (s, max = 160) => { const t = s.replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
27
+ /** Tool call/result text handed to onTool: whole (memory-capped at 16k), never cut short, so the engine redacts BEFORE it shortens for display. */
28
+ export const rawTool = (s) => s.length > 16000 ? s.slice(0, 16000) : s;
5
29
  /** A spawned child in its own process group; only that group is ever signalled. */
6
30
  export class ProcLink {
7
31
  child;
@@ -9,8 +33,12 @@ export class ProcLink {
9
33
  stderr = '';
10
34
  pending = '';
11
35
  killTimer;
36
+ /** Resolves once the child is gone (closed, or failed to start). */
37
+ exited;
12
38
  constructor(cmd, o) {
13
39
  this.grace = o.killGraceMs;
40
+ let exitedNow;
41
+ this.exited = new Promise(r => { exitedNow = r; });
14
42
  const grouped = process.platform !== 'win32';
15
43
  this.child = spawn(cmd.path, [...cmd.args], { cwd: o.cwd, shell: false, env: o.env, stdio: ['pipe', 'pipe', 'pipe'], ...(grouped ? { detached: true } : {}) });
16
44
  this.child.stdin?.on('error', () => { });
@@ -33,7 +61,7 @@ export class ProcLink {
33
61
  }
34
62
  catch { /* observer */ } this.stderr = (this.stderr + t).slice(-STDERR_TAIL); });
35
63
  const gone = (why) => { if (!this.alive)
36
- return; this.alive = false; clearTimeout(this.killTimer); o.onExit(why); };
64
+ return; this.alive = false; clearTimeout(this.killTimer); exitedNow(); o.onExit(why); };
37
65
  this.child.on('error', e => gone(`could not start: ${e.message}`));
38
66
  this.child.on('close', (code, sig) => gone(`exited ${code !== null ? `with code ${code}` : `by ${sig ?? 'signal'}`}`));
39
67
  }
@@ -71,9 +99,10 @@ export class ProcLink {
71
99
  }
72
100
  catch { /* ignore */ }
73
101
  this.signal('SIGTERM');
74
- this.killTimer = setTimeout(() => { if (this.alive)
75
- this.signal('SIGKILL'); }, this.grace);
76
- this.killTimer.unref();
102
+ // not unref'd: a process exiting right after close() must still SIGKILL a group that ignored SIGTERM (no orphaned process groups)
103
+ if (!this.killTimer)
104
+ this.killTimer = setTimeout(() => { if (this.alive)
105
+ this.signal('SIGKILL'); }, this.grace);
77
106
  }
78
107
  }
79
108
  /** Base class: lazy start, one turn at a time, timeout/abort -> interrupt then kill, process death -> transport failure. */
@@ -87,6 +116,8 @@ export class NativeSession {
87
116
  turn = null;
88
117
  closed = false;
89
118
  starting = null;
119
+ /** Every spawned link that has not exited yet (a dropped link may still be shutting down). */
120
+ live = new Set();
90
121
  constructor(cwd, env, killGraceMs) {
91
122
  this.cwd = cwd;
92
123
  this.env = env;
@@ -97,11 +128,14 @@ export class NativeSession {
97
128
  onLine: l => { if (this.link === link)
98
129
  this.onLine(l); },
99
130
  onExit: why => {
100
- if (this.link === link)
101
- this.link = null;
131
+ if (this.link !== link)
132
+ return; // a link we already dropped (killed on purpose): its exit must not touch the current turn
133
+ this.link = null;
102
134
  this.onProcessGone(why, link.stderr);
103
135
  },
104
136
  onRaw: (s, l) => this.turn?.opts.onRaw?.(s, l) });
137
+ this.live.add(link);
138
+ void link.exited.then(() => this.live.delete(link));
105
139
  this.link = link;
106
140
  return link;
107
141
  }
@@ -143,6 +177,19 @@ export class NativeSession {
143
177
  })();
144
178
  });
145
179
  }
180
+ /** Kill and forget the current process so the next turn starts a fresh one. */
181
+ dropLink() { this.link?.kill(); this.link = null; this.starting = null; }
182
+ /** Call at the first frame of the turn's model output (delta, tool call, message): fires onFirstOutput once per turn. */
183
+ markFirst() {
184
+ const t = this.turn;
185
+ if (!t || t.first)
186
+ return;
187
+ t.first = true;
188
+ try {
189
+ t.opts.onFirstOutput?.();
190
+ }
191
+ catch { /* observer */ }
192
+ }
146
193
  stopTurn(why) {
147
194
  const t = this.turn;
148
195
  if (!t || t.stop)
@@ -170,19 +217,18 @@ export class NativeSession {
170
217
  t.opts.signal?.removeEventListener('abort', t.onAbort);
171
218
  t.resolve(t.stop ? { ok: false, reason: t.stop === 'timeout' ? 'timed out' : 'cancelled' } : res);
172
219
  }
173
- interrupt() { if (this.turn) {
174
- try {
175
- this.interruptTurn();
176
- }
177
- catch { /* best effort */ }
178
- } }
220
+ /** Owner interrupt: the turn resolves 'cancelled' (interrupt first, kill after the grace if the CLI ignores it). */
221
+ interrupt() { this.stopTurn('cancelled'); }
222
+ /** Kills every owned process group; resolves once all of them have exited (SIGKILL after the grace). */
179
223
  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' });
224
+ if (!this.closed) {
225
+ this.closed = true;
226
+ this.link = null;
227
+ for (const l of this.live)
228
+ l.kill();
229
+ this.finishTurn({ ok: false, reason: 'cancelled' });
230
+ }
231
+ return Promise.all([...this.live].map(l => l.exited)).then(() => undefined);
186
232
  }
187
233
  }
188
234
  //# sourceMappingURL=proc.js.map
@@ -1,4 +1,5 @@
1
1
  import type { AgentRunOptions, AgentRunResult, AgentRunner, SubagentSignal } from '../runners.js';
2
+ import type { ToolSpec } from '../bus.js';
2
3
  import type { AgentConfig } from '../types.js';
3
4
  export interface SendOptions {
4
5
  readonly timeoutMs: number;
@@ -11,6 +12,24 @@ export interface SendOptions {
11
12
  readonly onSubagent?: (e: SubagentSignal) => void;
12
13
  /** Absolute paths of owner-attached images (codex gets image inputs; the others open them by path from the prompt). */
13
14
  readonly images?: readonly string[];
15
+ /** Native tool call / result of the turn (claude tool_use, codex mcpToolCall/commandExecution, omp tool_execution). */
16
+ readonly onTool?: (phase: 'call' | 'result', name: string, text: string) => void;
17
+ /** Called once per turn at the first frame of the model's output (delta, tool call or message). */
18
+ readonly onFirstOutput?: () => void;
19
+ }
20
+ /** CKit bus tools exposed to the agent: an MCP server description (claude/codex), plus specs + a direct caller (omp host tools). */
21
+ export interface SessionTools {
22
+ readonly mcp: {
23
+ command: string;
24
+ args: string[];
25
+ env: Record<string, string>;
26
+ dir?: string;
27
+ };
28
+ readonly specs: ToolSpec[];
29
+ readonly call: (name: string, args: unknown) => Promise<{
30
+ text: string;
31
+ isError?: boolean;
32
+ }>;
14
33
  }
15
34
  export interface AgentSession {
16
35
  /** Runs one turn. Never throws. A failed result with `transport: true` means the process/protocol broke and the turn may be retried per-turn. */
@@ -19,8 +38,8 @@ export interface AgentSession {
19
38
  steer(text: string): boolean;
20
39
  /** Ask the running turn to stop (the session stays usable). */
21
40
  interrupt(): void;
22
- /** Kill the owned process group. Idempotent. */
23
- close(): void;
41
+ /** Kill the owned process group. Idempotent. A returned promise resolves once every owned process has exited. */
42
+ close(): void | Promise<void>;
24
43
  readonly sessionId: string | null;
25
44
  /** 'native' = long-lived CLI process; 'per-turn' = fallback wrapper around the one-process-per-turn runner. */
26
45
  readonly kind: 'native' | 'per-turn';
@@ -39,5 +58,7 @@ export interface OpenSessionOptions {
39
58
  readonly runner?: AgentRunner;
40
59
  /** Grace between a polite stop and SIGKILL (default 3000). */
41
60
  readonly killGraceMs?: number;
61
+ /** CKit bus tools for this agent (A2A mail, progress, ask director, contributions). */
62
+ readonly tools?: SessionTools;
42
63
  }
43
64
  export type OpenSession = (agent: AgentConfig, opts: OpenSessionOptions) => AgentSession;
@@ -0,0 +1,32 @@
1
+ import { type CollabMode, type TeamEvent, type WaitReason } from './types.js';
2
+ export interface AgentTelemetry {
3
+ turns: number;
4
+ tokens: number;
5
+ busyMs: number;
6
+ queueMs: number;
7
+ lastEventAt: string | null;
8
+ lastWait: WaitReason | null;
9
+ }
10
+ export interface RunTelemetry {
11
+ startedAt: string | null;
12
+ endedAt: string | null;
13
+ wallMs: number;
14
+ firstEventMs: number | null;
15
+ firstAgentOutputMs: number | null;
16
+ turns: number;
17
+ turnsByClass: Record<string, number>;
18
+ directorTurns: number;
19
+ modelCalls: number;
20
+ discussionRounds: number;
21
+ contributions: number;
22
+ decisions: number;
23
+ loopsDetected: number;
24
+ tokens: number;
25
+ perAgent: Record<string, AgentTelemetry>;
26
+ maxParallelAgents: number;
27
+ waitingOwnerMs: number; /** PF-RES-SCHED: total time agent turns waited for a resource (process slot or workspace lease). */
28
+ queueMs: number;
29
+ mode: CollabMode | null;
30
+ paused: boolean;
31
+ }
32
+ export declare function runTelemetry(events: readonly TeamEvent[], nowMs?: number): RunTelemetry;