@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
@@ -0,0 +1,16 @@
1
+ import type { RunBus } from '../bus.js';
2
+ export interface ToolHub {
3
+ readonly socketPath: string;
4
+ /** `dir`: the hub's private 0700 directory (removed on close), for driver files that carry the token (never argv). */
5
+ mcpServer(agentId: string): {
6
+ command: string;
7
+ args: string[];
8
+ env: Record<string, string>;
9
+ dir?: string;
10
+ };
11
+ close(): void;
12
+ }
13
+ export declare function startToolHub(bus: RunBus, o: {
14
+ runId: string;
15
+ dir?: string;
16
+ }): Promise<ToolHub>;
@@ -0,0 +1,99 @@
1
+ // Tool hub: a private local socket (UNIX domain socket / Windows named pipe, never TCP) that the per-agent MCP stdio servers call back into.
2
+ // Every request carries a per-agent capability token = HMAC-SHA256(runSecret, runId:agentId); a mismatch is rejected.
3
+ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
4
+ import { chmodSync, mkdtempSync, rmSync } from 'node:fs';
5
+ import { createServer } from 'node:net';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ const MAX_LINE = 1_000_000;
10
+ export function startToolHub(bus, o) {
11
+ const secret = randomBytes(32);
12
+ const token = (agentId) => createHmac('sha256', secret).update(`${o.runId}:${agentId}`).digest('hex');
13
+ const okToken = (agentId, given) => {
14
+ if (typeof given !== 'string')
15
+ return false;
16
+ const a = Buffer.from(token(agentId)), b = Buffer.from(given);
17
+ return a.length === b.length && timingSafeEqual(a, b);
18
+ };
19
+ const win = process.platform === 'win32';
20
+ let dir = null;
21
+ let socketPath;
22
+ if (win)
23
+ socketPath = `\\\\.\\pipe\\ckit-${randomBytes(8).toString('hex')}`;
24
+ else {
25
+ dir = mkdtempSync(join(o.dir ?? tmpdir(), 'ckh-'));
26
+ try {
27
+ chmodSync(dir, 0o700);
28
+ }
29
+ catch { /* best effort */ }
30
+ socketPath = join(dir, 's');
31
+ }
32
+ const sockets = new Set();
33
+ const handle = async (line) => {
34
+ let req;
35
+ try {
36
+ req = JSON.parse(line);
37
+ }
38
+ catch {
39
+ return { id: null, ok: false, text: 'bad json', isError: true };
40
+ }
41
+ const id = req['id'] ?? null;
42
+ const agentId = req['agentId'];
43
+ if (typeof agentId !== 'string' || !agentId || !okToken(agentId, req['token']))
44
+ return { id, ok: false, text: 'unauthorized', isError: true };
45
+ const tool = req['tool'];
46
+ if (tool === '__list')
47
+ return { id, ok: true, text: JSON.stringify(bus.toolSpecs()), isError: false };
48
+ if (typeof tool !== 'string')
49
+ return { id, ok: false, text: 'tool required', isError: true };
50
+ const r = await bus.callTool(agentId, tool, req['args']);
51
+ return { id, ok: !r.isError, text: r.text, isError: r.isError === true };
52
+ };
53
+ const server = createServer(sock => {
54
+ sockets.add(sock);
55
+ sock.on('close', () => sockets.delete(sock));
56
+ sock.on('error', () => { });
57
+ let buf = '';
58
+ sock.on('data', chunk => {
59
+ buf += chunk.toString('utf8');
60
+ if (buf.length > MAX_LINE && !buf.includes('\n')) {
61
+ sock.destroy();
62
+ return;
63
+ }
64
+ const lines = buf.split('\n');
65
+ buf = lines.pop() ?? '';
66
+ for (const l of lines)
67
+ if (l.trim())
68
+ void handle(l).then(res => { if (!sock.destroyed)
69
+ sock.write(`${JSON.stringify(res)}\n`); });
70
+ });
71
+ });
72
+ const cleanup = () => { if (dir) {
73
+ try {
74
+ rmSync(dir, { recursive: true, force: true });
75
+ }
76
+ catch { /* ignore */ }
77
+ } };
78
+ return new Promise((resolve, reject) => {
79
+ server.once('error', e => { cleanup(); reject(e); });
80
+ server.listen(socketPath, () => {
81
+ if (!win) {
82
+ try {
83
+ chmodSync(socketPath, 0o600);
84
+ }
85
+ catch { /* best effort */ }
86
+ }
87
+ let closed = false;
88
+ resolve({
89
+ socketPath,
90
+ mcpServer: agentId => ({ command: process.execPath, args: [fileURLToPath(new URL('./stdio-server.js', import.meta.url))],
91
+ env: { CKIT_BUS_SOCKET: socketPath, CKIT_BUS_TOKEN: token(agentId), CKIT_AGENT_ID: agentId, CKIT_RUN_ID: o.runId }, ...(dir ? { dir } : {}) }),
92
+ close() { if (closed)
93
+ return; closed = true; for (const s of sockets)
94
+ s.destroy(); server.close(); cleanup(); },
95
+ });
96
+ });
97
+ });
98
+ }
99
+ //# sourceMappingURL=hub.js.map
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env node
2
+ // CKit MCP server (stdio transport, newline-delimited JSON-RPC 2.0). Forwards tools to the run's tool hub over a local socket.
3
+ // stdout carries protocol frames only; diagnostics go to stderr. Exits when stdin ends. No network.
4
+ import { createInterface } from 'node:readline';
5
+ import { createConnection } from 'node:net';
6
+ const sock = process.env['CKIT_BUS_SOCKET'] ?? '', tok = process.env['CKIT_BUS_TOKEN'] ?? '', agent = process.env['CKIT_AGENT_ID'] ?? '';
7
+ const VERSIONS = ['2024-11-05', '2025-03-26', '2025-06-18'];
8
+ const write = (o) => { process.stdout.write(`${JSON.stringify(o)}\n`); };
9
+ /** One request/response round trip to the hub (new connection per call; calls may block for a long time, e.g. ckit_ask_director). */
10
+ function hubCall(tool, args) {
11
+ return new Promise(resolve => {
12
+ if (!sock) {
13
+ resolve({ ok: false, text: 'CKIT_BUS_SOCKET is not set', isError: true });
14
+ return;
15
+ }
16
+ const c = createConnection(sock);
17
+ let buf = '', done = false;
18
+ const end = (r) => { if (done)
19
+ return; done = true; c.destroy(); resolve(r); };
20
+ c.on('connect', () => c.write(`${JSON.stringify({ id: 1, agentId: agent, token: tok, tool, args })}\n`));
21
+ c.on('data', d => {
22
+ buf += d.toString('utf8');
23
+ const i = buf.indexOf('\n');
24
+ if (i < 0)
25
+ return;
26
+ try {
27
+ const r = JSON.parse(buf.slice(0, i));
28
+ end({ ok: r.ok === true, text: String(r.text ?? ''), isError: r.isError === true });
29
+ }
30
+ catch {
31
+ end({ ok: false, text: 'bad hub response', isError: true });
32
+ }
33
+ });
34
+ c.on('error', e => end({ ok: false, text: `hub unreachable: ${e.message}`, isError: true }));
35
+ c.on('close', () => end({ ok: false, text: 'hub closed the connection', isError: true }));
36
+ });
37
+ }
38
+ async function handle(msg) {
39
+ const id = msg['id'], method = msg['method'];
40
+ const hasId = id !== undefined && id !== null;
41
+ const reply = (result) => { if (hasId)
42
+ write({ jsonrpc: '2.0', id, result }); };
43
+ const error = (code, message) => { if (hasId)
44
+ write({ jsonrpc: '2.0', id, error: { code, message } }); };
45
+ const params = (msg['params'] && typeof msg['params'] === 'object' ? msg['params'] : {});
46
+ switch (method) {
47
+ case 'initialize': {
48
+ const v = typeof params['protocolVersion'] === 'string' && VERSIONS.includes(params['protocolVersion']) ? params['protocolVersion'] : '2025-06-18';
49
+ reply({ protocolVersion: v, capabilities: { tools: {} }, serverInfo: { name: 'ckit', version: '1.0.0' } });
50
+ return;
51
+ }
52
+ case 'ping':
53
+ reply({});
54
+ return;
55
+ case 'tools/list': {
56
+ const r = await hubCall('__list', {});
57
+ if (!r.ok) {
58
+ error(-32603, r.text);
59
+ return;
60
+ }
61
+ try {
62
+ const specs = JSON.parse(r.text);
63
+ reply({ tools: specs.map(s => ({ name: s.name, description: s.description, inputSchema: s.parameters })) });
64
+ }
65
+ catch {
66
+ error(-32603, 'bad tool list');
67
+ }
68
+ return;
69
+ }
70
+ case 'tools/call': {
71
+ const name = params['name'];
72
+ if (typeof name !== 'string') {
73
+ error(-32602, 'name required');
74
+ return;
75
+ }
76
+ const r = await hubCall(name, params['arguments'] ?? {});
77
+ reply({ content: [{ type: 'text', text: r.text }], isError: r.isError || !r.ok });
78
+ return;
79
+ }
80
+ default:
81
+ if (typeof method === 'string' && method.startsWith('notifications/'))
82
+ return;
83
+ error(-32601, `method not found: ${String(method)}`);
84
+ }
85
+ }
86
+ const rl = createInterface({ input: process.stdin });
87
+ rl.on('line', line => {
88
+ if (!line.trim())
89
+ return;
90
+ let msg;
91
+ try {
92
+ msg = JSON.parse(line);
93
+ }
94
+ catch {
95
+ write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
96
+ return;
97
+ }
98
+ if (!msg || typeof msg !== 'object')
99
+ return;
100
+ void handle(msg).catch(e => { process.stderr.write(`ckit mcp: ${e instanceof Error ? e.message : String(e)}\n`); });
101
+ });
102
+ rl.on('close', () => process.exit(0));
103
+ //# sourceMappingURL=stdio-server.js.map
@@ -70,6 +70,10 @@ export declare const withCliArgs: <T extends {
70
70
  }>(spec: T, agent: AgentConfig) => T;
71
71
  /** Claude team workers run with host hooks disabled (workspace Stop gates / prompt routers must not hijack the answer); the owner's cliArgs come after.
72
72
  * Write agents also get Claude's sandbox with sandboxed Bash auto-allowed: `acceptEdits` alone denies every Bash call, so a developer could edit files but never run the tests it was asked to run (seen in a real run). */
73
+ export declare const CLAUDE_WRITE_TOOLS: readonly ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'];
74
+ /** Read agents must be read-only regardless of the owner's/project's Claude `defaultMode` (auto/acceptEdits/bypass would otherwise be inherited and let a
75
+ * "read" agent write files — seen in a real run): explicit `default` permission mode (unapproved Bash such as redirects is denied headless, read-only
76
+ * Bash still runs), file-writing tools removed, and denied again in settings. `--disallowedTools=` keeps the variadic flag from eating a trailing prompt. */
73
77
  export declare const claudeTeamArgs: (args: readonly string[], agent: AgentConfig) => string[];
74
78
  export declare function runExecutorAgent(agent: AgentConfig, prompt: string, opts: AgentRunOptions): Promise<AgentRunResult>;
75
79
  export { parseExecutorOutput };
@@ -231,9 +231,15 @@ export function claudeFrameActivity(frame) {
231
231
  export const withCliArgs = (spec, agent) => { const extra = cliArgTokens(agent.cliArgs); return extra.length ? { ...spec, args: [...spec.args, ...extra] } : spec; };
232
232
  /** Claude team workers run with host hooks disabled (workspace Stop gates / prompt routers must not hijack the answer); the owner's cliArgs come after.
233
233
  * Write agents also get Claude's sandbox with sandboxed Bash auto-allowed: `acceptEdits` alone denies every Bash call, so a developer could edit files but never run the tests it was asked to run (seen in a real run). */
234
+ export const CLAUDE_WRITE_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'];
235
+ /** Read agents must be read-only regardless of the owner's/project's Claude `defaultMode` (auto/acceptEdits/bypass would otherwise be inherited and let a
236
+ * "read" agent write files — seen in a real run): explicit `default` permission mode (unapproved Bash such as redirects is denied headless, read-only
237
+ * Bash still runs), file-writing tools removed, and denied again in settings. `--disallowedTools=` keeps the variadic flag from eating a trailing prompt. */
234
238
  export const claudeTeamArgs = (args, agent) => {
235
- const settings = agent.access === 'write' ? { disableAllHooks: true, sandbox: { enabled: true, autoAllowBashIfSandboxed: true } } : { disableAllHooks: true };
236
- return [...args, '--settings', JSON.stringify(settings), ...cliArgTokens(agent.cliArgs)];
239
+ const write = agent.access === 'write';
240
+ const settings = write ? { disableAllHooks: true, sandbox: { enabled: true, autoAllowBashIfSandboxed: true } } : { disableAllHooks: true, permissions: { deny: [...CLAUDE_WRITE_TOOLS] } };
241
+ const readOnly = write ? [] : ['--permission-mode', 'default', `--disallowedTools=${CLAUDE_WRITE_TOOLS.join(',')}`];
242
+ return [...args, ...readOnly, '--settings', JSON.stringify(settings), ...cliArgTokens(agent.cliArgs)];
237
243
  };
238
244
  export async function runExecutorAgent(agent, prompt, opts) {
239
245
  const kind = agent.cli === 'omp' ? 'omp' : 'claude-code';
@@ -0,0 +1,20 @@
1
+ export interface SchedulerStats {
2
+ readonly cap: number;
3
+ readonly running: number;
4
+ readonly queued: number;
5
+ readonly byRun: Readonly<Record<string, {
6
+ running: number;
7
+ queued: number;
8
+ }>>;
9
+ }
10
+ export interface AgentScheduler {
11
+ readonly cap: number;
12
+ /** Resolves with a release function once a slot is free. Rejects with an AbortError when `signal` aborts while queued. onWait fires once when the call has to queue. */
13
+ acquire(runId: string, agentId: string, signal?: AbortSignal, onWait?: (s: SchedulerStats) => void): Promise<() => void>;
14
+ stats(): SchedulerStats;
15
+ }
16
+ /** Default cap from the machine: one slot per CPU, bounded by half the RAM at ~512 MB per agent process; clamped to 2..32. Env CKIT_MAX_AGENTS (1..256) overrides. */
17
+ export declare function defaultAgentCap(env?: NodeJS.ProcessEnv, cpuCount?: number, memBytes?: number): number;
18
+ export declare function createAgentScheduler(cap?: number): AgentScheduler;
19
+ /** The process-wide scheduler used by every real run (created on first use with the default cap). */
20
+ export declare function globalAgentScheduler(): AgentScheduler;
@@ -0,0 +1,73 @@
1
+ // PF-RES-SCHED: one process-wide cap on concurrently running agent processes, shared by every run.
2
+ // Fairness: one FIFO queue across all runs - the oldest waiter gets the next free slot, whatever run it belongs to.
3
+ import { cpus, totalmem } from 'node:os';
4
+ const PER_AGENT_MB = 512;
5
+ /** Default cap from the machine: one slot per CPU, bounded by half the RAM at ~512 MB per agent process; clamped to 2..32. Env CKIT_MAX_AGENTS (1..256) overrides. */
6
+ export function defaultAgentCap(env = process.env, cpuCount = cpus().length, memBytes = totalmem()) {
7
+ const v = Number(env['CKIT_MAX_AGENTS']);
8
+ if (Number.isInteger(v) && v >= 1 && v <= 256)
9
+ return v;
10
+ const byMem = Math.floor((memBytes / 2) / (PER_AGENT_MB * 1024 * 1024));
11
+ return Math.max(2, Math.min(32, Math.min(Math.max(1, cpuCount), byMem)));
12
+ }
13
+ export function createAgentScheduler(cap = defaultAgentCap()) {
14
+ if (!Number.isInteger(cap) || cap < 1)
15
+ throw new Error(`scheduler cap must be a positive integer (got ${cap})`);
16
+ const held = new Map(); // runId -> running slots
17
+ const queue = [];
18
+ let running = 0;
19
+ const stats = () => {
20
+ const byRun = {};
21
+ for (const [r, n] of held)
22
+ byRun[r] = { running: n, queued: 0 };
23
+ for (const q of queue)
24
+ (byRun[q.runId] ??= { running: 0, queued: 0 }).queued++;
25
+ return { cap, running, queued: queue.length, byRun };
26
+ };
27
+ const grantNext = () => { while (running < cap && queue.length)
28
+ queue.shift()?.grant(); };
29
+ return {
30
+ cap,
31
+ stats,
32
+ acquire(runId, agentId, signal, onWait) {
33
+ return new Promise((resolveP, reject) => {
34
+ if (signal?.aborted) {
35
+ reject(abortError());
36
+ return;
37
+ }
38
+ const take = () => {
39
+ running++;
40
+ held.set(runId, (held.get(runId) ?? 0) + 1);
41
+ let released = false;
42
+ resolveP(() => {
43
+ if (released)
44
+ return;
45
+ released = true;
46
+ running--;
47
+ const n = (held.get(runId) ?? 1) - 1;
48
+ if (n > 0)
49
+ held.set(runId, n);
50
+ else
51
+ held.delete(runId);
52
+ grantNext();
53
+ });
54
+ };
55
+ if (running < cap && !queue.length) {
56
+ take();
57
+ return;
58
+ }
59
+ const entry = { runId, agentId, grant: () => { signal?.removeEventListener('abort', onAbort); take(); } };
60
+ const onAbort = () => { const i = queue.indexOf(entry); if (i >= 0)
61
+ queue.splice(i, 1); reject(abortError()); };
62
+ signal?.addEventListener('abort', onAbort, { once: true });
63
+ queue.push(entry);
64
+ onWait?.(stats());
65
+ });
66
+ },
67
+ };
68
+ }
69
+ function abortError() { const e = new Error('cancelled'); e.name = 'AbortError'; return e; }
70
+ let shared = null;
71
+ /** The process-wide scheduler used by every real run (created on first use with the default cap). */
72
+ export function globalAgentScheduler() { return shared ??= createAgentScheduler(); }
73
+ //# sourceMappingURL=scheduler.js.map
@@ -1,7 +1,9 @@
1
1
  import type { AgentConfig } from '../types.js';
2
2
  import { NativeSession } from './proc.js';
3
- import type { SessionCommand } from './types.js';
4
- export declare function claudeSessionArgs(agent: AgentConfig, sessionId: string): string[];
3
+ import type { SendOptions, SessionCommand, SessionTools } from './types.js';
4
+ /** Writes the MCP config (it carries the per-agent bus token) to a 0600 file in a private 0700 directory and returns its path: the token never appears in argv (ps). */
5
+ export declare function claudeMcpConfigFile(agent: AgentConfig, tools: SessionTools): string;
6
+ export declare function claudeSessionArgs(agent: AgentConfig, sessionId: string, tools?: SessionTools, resume?: boolean): string[];
5
7
  export declare class ClaudeSession extends NativeSession {
6
8
  private readonly agent;
7
9
  private readonly cmd;
@@ -9,11 +11,20 @@ export declare class ClaudeSession extends NativeSession {
9
11
  private held;
10
12
  private open;
11
13
  private seen;
12
- constructor(agent: AgentConfig, cwd: string, env: Readonly<Record<string, string>>, cmd: (sessionId: string) => SessionCommand, grace: number);
14
+ private toolNames;
15
+ private spoke;
16
+ private pendingSteer;
17
+ private interruptSent;
18
+ /** cmd(sessionId, resume): resume=false only for the very first spawn. */
19
+ constructor(agent: AgentConfig, cwd: string, env: Readonly<Record<string, string>>, cmd: (sessionId: string, resume: boolean) => SessionCommand, grace: number);
13
20
  protected start(): Promise<void>;
14
- protected begin(prompt: string): void;
15
- /** claude has no native mid-turn injection: hold the text and prepend it to the next send. */
21
+ private frame;
22
+ protected begin(prompt: string, opts: SendOptions): void;
23
+ /** Running turn: interrupt it and continue with the guidance in a resumed process (true). No turn: hold for the next send (false). */
16
24
  steer(text: string): boolean;
17
25
  protected interruptTurn(): void;
26
+ /** The interrupted process is gone/going: respawn with --resume and deliver the coalesced guidance as the continuation of the same turn. */
27
+ private continueWithSteer;
28
+ protected onProcessGone(why: string, stderr: string): void;
18
29
  protected onLine(line: string): void;
19
30
  }
@@ -1,14 +1,39 @@
1
1
  // claude driver: ONE long-lived `claude -p --input-format stream-json --output-format stream-json` process per agent.
2
2
  // Turns are `user` frames on stdin; a `result` frame closes each turn; text deltas come from `stream_event` frames.
3
3
  import { randomUUID } from 'node:crypto';
4
+ import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
4
7
  import { claudeSubagentObservations } from '../../adapters/launch/executor.js';
5
8
  import { claudeFrameActivity, claudeTeamArgs } from '../runners.js';
6
- import { NativeSession, oneLine } from './proc.js';
7
- export function claudeSessionArgs(agent, sessionId) {
8
- const base = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--session-id', sessionId,
9
- ...(agent.model ? ['--model', agent.model] : []), ...(agent.access === 'write' ? ['--permission-mode', 'acceptEdits'] : [])];
9
+ import { NativeSession, loadImages, oneLine, rawTool } from './proc.js';
10
+ /** Writes the MCP config (it carries the per-agent bus token) to a 0600 file in a private 0700 directory and returns its path: the token never appears in argv (ps). */
11
+ export function claudeMcpConfigFile(agent, tools) {
12
+ let dir = tools.mcp.dir;
13
+ if (!dir) {
14
+ dir = mkdtempSync(join(tmpdir(), 'ckm-'));
15
+ try {
16
+ chmodSync(dir, 0o700);
17
+ }
18
+ catch { /* best effort */ }
19
+ }
20
+ const file = join(dir, `mcp-${agent.id.replace(/[^\w.-]/g, '_')}.json`);
21
+ writeFileSync(file, JSON.stringify({ mcpServers: { ckit: { command: tools.mcp.command, args: tools.mcp.args, env: tools.mcp.env } } }), { mode: 0o600 });
22
+ try {
23
+ chmodSync(file, 0o600);
24
+ }
25
+ catch { /* best effort */ }
26
+ return file;
27
+ }
28
+ export function claudeSessionArgs(agent, sessionId, tools, resume = false) {
29
+ const base = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', resume ? '--resume' : '--session-id', sessionId,
30
+ ...(agent.model ? ['--model', agent.model] : []), ...(agent.access === 'write' ? ['--permission-mode', 'acceptEdits'] : []),
31
+ ...(tools ? ['--mcp-config', claudeMcpConfigFile(agent, tools), '--strict-mcp-config', '--allowedTools', 'mcp__ckit__*'] : [])];
10
32
  return claudeTeamArgs(base, agent);
11
33
  }
34
+ const STEER_PREFIX = 'Owner guidance sent while you were working: ';
35
+ const STEER_SUFFIX = '\nContinue the task you were working on, taking this guidance into account, and give your complete final answer.';
36
+ const textOf = (c) => typeof c === 'string' ? c : Array.isArray(c) ? c.map(x => (x && typeof x === 'object' && typeof x.text === 'string' ? x.text : '')).join(' ') : '';
12
37
  export class ClaudeSession extends NativeSession {
13
38
  agent;
14
39
  cmd;
@@ -16,25 +41,79 @@ export class ClaudeSession extends NativeSession {
16
41
  held = [];
17
42
  open = new Map();
18
43
  seen = new Set();
44
+ toolNames = new Map();
45
+ spoke = false; // the first process produced output: the session exists on disk, later spawns must --resume
46
+ pendingSteer = [];
47
+ interruptSent = false;
48
+ /** cmd(sessionId, resume): resume=false only for the very first spawn. */
19
49
  constructor(agent, cwd, env, cmd, grace) {
20
50
  super(cwd, env, grace);
21
51
  this.agent = agent;
22
52
  this.cmd = cmd;
23
53
  this.sessionId = randomUUID();
24
54
  }
25
- async start() { this.spawnLink(this.cmd(this.sessionId)); }
26
- begin(prompt) {
55
+ async start() { this.spawnLink(this.cmd(this.sessionId, this.spoke)); }
56
+ frame(content) { return !!this.link?.write({ type: 'user', message: { role: 'user', content } }); }
57
+ begin(prompt, opts) {
58
+ this.pendingSteer = [];
59
+ this.interruptSent = false;
27
60
  const text = this.held.length ? `${this.held.splice(0).map(h => `[Owner guidance sent while you were working] ${h}`).join('\n')}\n\n${prompt}` : prompt;
28
- if (!this.link?.write({ type: 'user', message: { role: 'user', content: text } }))
61
+ const imgs = loadImages(opts.images);
62
+ const content = imgs.length ? [...imgs.map(i => ({ type: 'image', source: { type: 'base64', media_type: i.mediaType, data: i.data } })), { type: 'text', text }] : text;
63
+ if (!this.frame(content))
29
64
  throw new Error('could not write to claude stdin');
30
65
  }
31
- /** claude has no native mid-turn injection: hold the text and prepend it to the next send. */
32
- steer(text) { if (text.trim())
33
- this.held.push(text.trim()); return false; }
66
+ /** Running turn: interrupt it and continue with the guidance in a resumed process (true). No turn: hold for the next send (false). */
67
+ steer(text) {
68
+ const t = text.trim();
69
+ if (!t)
70
+ return false;
71
+ if (!this.turn || !this.link) {
72
+ this.held.push(t);
73
+ return false;
74
+ }
75
+ this.pendingSteer.push(t);
76
+ if (!this.interruptSent) {
77
+ this.interruptSent = true;
78
+ this.interruptTurn();
79
+ }
80
+ return true;
81
+ }
34
82
  interruptTurn() { this.link?.write({ type: 'control_request', request_id: randomUUID(), request: { subtype: 'interrupt' } }); }
35
- onLine(line) {
83
+ /** The interrupted process is gone/going: respawn with --resume and deliver the coalesced guidance as the continuation of the same turn. */
84
+ continueWithSteer() {
36
85
  const t = this.turn;
37
- if (!t || !line.startsWith('{'))
86
+ if (!t)
87
+ return;
88
+ const guidance = this.pendingSteer.splice(0);
89
+ this.interruptSent = false;
90
+ const old = this.link;
91
+ this.dropLink();
92
+ // the old process must be gone before `--resume` reopens the same session on disk (two writers on one session corrupt it)
93
+ void (old ? old.exited : Promise.resolve()).then(() => {
94
+ if (this.turn !== t || this.closed || t.stop)
95
+ return; // the turn ended (timeout / cancel / close) while the old process shut down
96
+ try {
97
+ this.spawnLink(this.cmd(this.sessionId, true));
98
+ if (!this.frame(`${STEER_PREFIX}${guidance.join('\n')}${STEER_SUFFIX}`))
99
+ throw new Error('could not write to claude stdin');
100
+ }
101
+ catch (e) {
102
+ this.dropLink();
103
+ this.finishTurn({ ok: false, reason: `claude failed to resume: ${e instanceof Error ? e.message : String(e)}`, transport: true });
104
+ }
105
+ });
106
+ }
107
+ onProcessGone(why, stderr) {
108
+ if (this.turn && this.pendingSteer.length && !this.turn.stop && !this.closed) {
109
+ this.starting = null;
110
+ this.continueWithSteer();
111
+ return;
112
+ }
113
+ super.onProcessGone(why, stderr);
114
+ }
115
+ onLine(line) {
116
+ if (!line.startsWith('{'))
38
117
  return;
39
118
  let f;
40
119
  try {
@@ -43,11 +122,20 @@ export class ClaudeSession extends NativeSession {
43
122
  catch {
44
123
  return;
45
124
  }
125
+ this.spoke = true;
126
+ const t = this.turn;
127
+ if (!t) {
128
+ if (f['type'] === 'result' && f['terminal_reason'] === 'aborted_streaming')
129
+ this.dropLink();
130
+ return;
131
+ }
46
132
  const opts = t.opts;
47
133
  if (f['type'] === 'stream_event') {
48
134
  const d = f['event']?.delta;
49
- if (d?.type === 'text_delta' && typeof d.text === 'string' && !f['parent_tool_use_id'])
135
+ if (d?.type === 'text_delta' && typeof d.text === 'string' && !f['parent_tool_use_id']) {
136
+ this.markFirst();
50
137
  opts.onDelta?.(d.text);
138
+ }
51
139
  return;
52
140
  }
53
141
  if (f['type'] === 'assistant' || f['type'] === 'user') {
@@ -63,11 +151,37 @@ export class ClaudeSession extends NativeSession {
63
151
  opts.onSubagent?.({ type: 'activity', childId: parent, text: a });
64
152
  return;
65
153
  }
154
+ this.markFirst();
155
+ const blocks = Array.isArray(f['message']?.content) ? f['message'].content : [];
156
+ for (const b of blocks) {
157
+ if (b['type'] === 'tool_use' && typeof b['name'] === 'string') {
158
+ if (typeof b['id'] === 'string')
159
+ this.toolNames.set(b['id'], b['name']);
160
+ opts.onTool?.('call', b['name'], rawTool(JSON.stringify(b['input'] ?? {})));
161
+ }
162
+ else if (b['type'] === 'tool_result')
163
+ opts.onTool?.('result', this.toolNames.get(String(b['tool_use_id'])) ?? 'tool', rawTool(textOf(b['content'])));
164
+ }
66
165
  for (const a of claudeFrameActivity(f))
67
166
  opts.onActivity?.(a);
68
167
  return;
69
168
  }
70
169
  if (f['type'] === 'result') {
170
+ const aborted = f['is_error'] === true && (f['terminal_reason'] === 'aborted_streaming' || f['subtype'] === 'error_during_execution');
171
+ if (aborted) { // the CLI exits after an interrupt: never reuse this process
172
+ if (this.pendingSteer.length && !t.stop && !this.closed) {
173
+ this.continueWithSteer();
174
+ return;
175
+ }
176
+ this.dropLink();
177
+ }
178
+ else if (this.pendingSteer.length) {
179
+ this.held.push(...this.pendingSteer.splice(0));
180
+ this.interruptSent = false;
181
+ }
182
+ const denied = Array.isArray(f['permission_denials']) ? f['permission_denials'] : [];
183
+ if (denied.length)
184
+ opts.onActivity?.(oneLine(`permission denied for: ${[...new Set(denied.map(d => String(d?.tool_name ?? 'tool')))].join(', ')}`, 200));
71
185
  for (const [childId] of this.open)
72
186
  opts.onSubagent?.({ type: 'finished', childId, ok: f['is_error'] !== true, summary: 'finished with the turn' });
73
187
  this.open.clear();
@@ -1,10 +1,11 @@
1
1
  import type { AgentConfig } from '../types.js';
2
2
  import { NativeSession } from './proc.js';
3
- import type { SendOptions, SessionCommand } from './types.js';
3
+ import type { SendOptions, SessionCommand, SessionTools } from './types.js';
4
4
  export declare const codexSessionArgs: (agent: AgentConfig) => string[];
5
5
  export declare class CodexSession extends NativeSession {
6
6
  private readonly agent;
7
7
  private readonly cmd;
8
+ private readonly tools?;
8
9
  protected readonly label = "codex";
9
10
  private nextId;
10
11
  private calls;
@@ -12,7 +13,7 @@ export declare class CodexSession extends NativeSession {
12
13
  private turnId;
13
14
  private lastMessage;
14
15
  private tokens;
15
- constructor(agent: AgentConfig, cwd: string, env: Readonly<Record<string, string>>, cmd: SessionCommand, grace: number);
16
+ constructor(agent: AgentConfig, cwd: string, env: Readonly<Record<string, string>>, cmd: SessionCommand, grace: number, tools?: SessionTools | undefined);
16
17
  private call;
17
18
  protected start(): Promise<void>;
18
19
  protected onProcessGone(why: string, stderr: string): void;