@celljs/ai-coding-agent 0.0.0-stage → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +225 -2
- package/cell.yml +16 -0
- package/esm/node/application-lifecycle.d.ts +7 -0
- package/esm/node/application-lifecycle.js +25 -0
- package/esm/node/application-lifecycle.js.map +1 -0
- package/esm/node/coding-agent-protocol.d.ts +92 -0
- package/esm/node/coding-agent-protocol.js +8 -0
- package/esm/node/coding-agent-protocol.js.map +1 -0
- package/esm/node/error/errors.d.ts +22 -0
- package/esm/node/error/errors.js +25 -0
- package/esm/node/error/errors.js.map +1 -0
- package/esm/node/error/index.d.ts +1 -0
- package/esm/node/error/index.js +2 -0
- package/esm/node/error/index.js.map +1 -0
- package/esm/node/event/agent-event-util.d.ts +1 -0
- package/esm/node/event/agent-event-util.js +3 -0
- package/esm/node/event/agent-event-util.js.map +1 -0
- package/esm/node/event/index.d.ts +1 -0
- package/esm/node/event/index.js +2 -0
- package/esm/node/event/index.js.map +1 -0
- package/esm/node/index.d.ts +8 -0
- package/esm/node/index.js +10 -0
- package/esm/node/index.js.map +1 -0
- package/esm/node/module.d.ts +3 -0
- package/esm/node/module.js +4 -0
- package/esm/node/module.js.map +1 -0
- package/esm/node/pi/index.d.ts +2 -0
- package/esm/node/pi/index.js +3 -0
- package/esm/node/pi/index.js.map +1 -0
- package/esm/node/pi/pi-sdk-util.d.ts +9 -0
- package/esm/node/pi/pi-sdk-util.js +20 -0
- package/esm/node/pi/pi-sdk-util.js.map +1 -0
- package/esm/node/pi/pi-types.d.ts +10 -0
- package/esm/node/pi/pi-types.js +2 -0
- package/esm/node/pi/pi-types.js.map +1 -0
- package/esm/node/runtime/index.d.ts +1 -0
- package/esm/node/runtime/index.js +2 -0
- package/esm/node/runtime/index.js.map +1 -0
- package/esm/node/runtime/model-runtime-provider.d.ts +11 -0
- package/esm/node/runtime/model-runtime-provider.js +67 -0
- package/esm/node/runtime/model-runtime-provider.js.map +1 -0
- package/esm/node/session/agent-session-factory.d.ts +23 -0
- package/esm/node/session/agent-session-factory.js +178 -0
- package/esm/node/session/agent-session-factory.js.map +1 -0
- package/esm/node/session/agent-session-manager.d.ts +16 -0
- package/esm/node/session/agent-session-manager.js +72 -0
- package/esm/node/session/agent-session-manager.js.map +1 -0
- package/esm/node/session/index.d.ts +2 -0
- package/esm/node/session/index.js +3 -0
- package/esm/node/session/index.js.map +1 -0
- package/esm/node/test/faux-models.d.ts +28 -0
- package/esm/node/test/faux-models.js +39 -0
- package/esm/node/test/faux-models.js.map +1 -0
- package/esm/node/test/index.d.ts +2 -0
- package/esm/node/test/index.js +3 -0
- package/esm/node/test/index.js.map +1 -0
- package/esm/node/test/test-container.d.ts +18 -0
- package/esm/node/test/test-container.js +25 -0
- package/esm/node/test/test-container.js.map +1 -0
- package/esm/package.json +3 -0
- package/lib/node/application-lifecycle.d.ts +8 -0
- package/lib/node/application-lifecycle.d.ts.map +1 -0
- package/lib/node/application-lifecycle.js +28 -0
- package/lib/node/application-lifecycle.js.map +1 -0
- package/lib/node/coding-agent-protocol.d.ts +93 -0
- package/lib/node/coding-agent-protocol.d.ts.map +1 -0
- package/lib/node/coding-agent-protocol.js +11 -0
- package/lib/node/coding-agent-protocol.js.map +1 -0
- package/lib/node/error/errors.d.ts +23 -0
- package/lib/node/error/errors.d.ts.map +1 -0
- package/lib/node/error/errors.js +32 -0
- package/lib/node/error/errors.js.map +1 -0
- package/lib/node/error/index.d.ts +2 -0
- package/lib/node/error/index.d.ts.map +1 -0
- package/lib/node/error/index.js +18 -0
- package/lib/node/error/index.js.map +1 -0
- package/lib/node/event/agent-event-util.d.ts +2 -0
- package/lib/node/event/agent-event-util.d.ts.map +1 -0
- package/lib/node/event/agent-event-util.js +7 -0
- package/lib/node/event/agent-event-util.js.map +1 -0
- package/lib/node/event/agent-event-util.spec.d.ts +2 -0
- package/lib/node/event/agent-event-util.spec.d.ts.map +1 -0
- package/lib/node/event/agent-event-util.spec.js +85 -0
- package/lib/node/event/agent-event-util.spec.js.map +1 -0
- package/lib/node/event/index.d.ts +2 -0
- package/lib/node/event/index.d.ts.map +1 -0
- package/lib/node/event/index.js +18 -0
- package/lib/node/event/index.js.map +1 -0
- package/lib/node/index.d.ts +9 -0
- package/lib/node/index.d.ts.map +1 -0
- package/lib/node/index.js +28 -0
- package/lib/node/index.js.map +1 -0
- package/lib/node/module.d.ts +4 -0
- package/lib/node/module.d.ts.map +1 -0
- package/lib/node/module.js +6 -0
- package/lib/node/module.js.map +1 -0
- package/lib/node/pi/index.d.ts +3 -0
- package/lib/node/pi/index.d.ts.map +1 -0
- package/lib/node/pi/index.js +19 -0
- package/lib/node/pi/index.js.map +1 -0
- package/lib/node/pi/pi-sdk-util.d.ts +10 -0
- package/lib/node/pi/pi-sdk-util.d.ts.map +1 -0
- package/lib/node/pi/pi-sdk-util.js +23 -0
- package/lib/node/pi/pi-sdk-util.js.map +1 -0
- package/lib/node/pi/pi-types.d.ts +11 -0
- package/lib/node/pi/pi-types.d.ts.map +1 -0
- package/lib/node/pi/pi-types.js +3 -0
- package/lib/node/pi/pi-types.js.map +1 -0
- package/lib/node/runtime/index.d.ts +2 -0
- package/lib/node/runtime/index.d.ts.map +1 -0
- package/lib/node/runtime/index.js +18 -0
- package/lib/node/runtime/index.js.map +1 -0
- package/lib/node/runtime/model-runtime-provider.d.ts +12 -0
- package/lib/node/runtime/model-runtime-provider.d.ts.map +1 -0
- package/lib/node/runtime/model-runtime-provider.js +70 -0
- package/lib/node/runtime/model-runtime-provider.js.map +1 -0
- package/lib/node/session/agent-session-builtins.spec.d.ts +2 -0
- package/lib/node/session/agent-session-builtins.spec.d.ts.map +1 -0
- package/lib/node/session/agent-session-builtins.spec.js +55 -0
- package/lib/node/session/agent-session-builtins.spec.js.map +1 -0
- package/lib/node/session/agent-session-factory.d.ts +24 -0
- package/lib/node/session/agent-session-factory.d.ts.map +1 -0
- package/lib/node/session/agent-session-factory.js +181 -0
- package/lib/node/session/agent-session-factory.js.map +1 -0
- package/lib/node/session/agent-session-manager.d.ts +17 -0
- package/lib/node/session/agent-session-manager.d.ts.map +1 -0
- package/lib/node/session/agent-session-manager.js +75 -0
- package/lib/node/session/agent-session-manager.js.map +1 -0
- package/lib/node/session/agent-session-manager.spec.d.ts +33 -0
- package/lib/node/session/agent-session-manager.spec.d.ts.map +1 -0
- package/lib/node/session/agent-session-manager.spec.js +203 -0
- package/lib/node/session/agent-session-manager.spec.js.map +1 -0
- package/lib/node/session/index.d.ts +3 -0
- package/lib/node/session/index.d.ts.map +1 -0
- package/lib/node/session/index.js +19 -0
- package/lib/node/session/index.js.map +1 -0
- package/lib/node/test/faux-models.d.ts +29 -0
- package/lib/node/test/faux-models.d.ts.map +1 -0
- package/lib/node/test/faux-models.js +43 -0
- package/lib/node/test/faux-models.js.map +1 -0
- package/lib/node/test/index.d.ts +3 -0
- package/lib/node/test/index.d.ts.map +1 -0
- package/lib/node/test/index.js +19 -0
- package/lib/node/test/index.js.map +1 -0
- package/lib/node/test/test-container.d.ts +19 -0
- package/lib/node/test/test-container.d.ts.map +1 -0
- package/lib/node/test/test-container.js +28 -0
- package/lib/node/test/test-container.js.map +1 -0
- package/package.json +96 -4
- package/src/node/application-lifecycle.ts +13 -0
- package/src/node/coding-agent-protocol.ts +106 -0
- package/src/node/error/errors.ts +32 -0
- package/src/node/error/index.ts +1 -0
- package/src/node/event/agent-event-util.spec.ts +95 -0
- package/src/node/event/agent-event-util.ts +2 -0
- package/src/node/event/index.ts +1 -0
- package/src/node/index.ts +9 -0
- package/src/node/module.ts +4 -0
- package/src/node/pi/index.ts +2 -0
- package/src/node/pi/pi-sdk-util.ts +25 -0
- package/src/node/pi/pi-types.ts +12 -0
- package/src/node/runtime/index.ts +1 -0
- package/src/node/runtime/model-runtime-provider.ts +50 -0
- package/src/node/session/agent-session-builtins.spec.ts +59 -0
- package/src/node/session/agent-session-factory.ts +175 -0
- package/src/node/session/agent-session-manager.spec.ts +198 -0
- package/src/node/session/agent-session-manager.ts +64 -0
- package/src/node/session/index.ts +2 -0
- package/src/node/test/faux-models.ts +54 -0
- package/src/node/test/index.ts +2 -0
- package/src/node/test/test-container.ts +36 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { AgentSession, ExtensionAPI, McpServerConfig, ModelRuntime, ThinkingLevel } from './pi';
|
|
2
|
+
|
|
3
|
+
export const ModelRuntimeProvider = Symbol('ModelRuntimeProvider');
|
|
4
|
+
export const ModelRuntimeContribution = Symbol('ModelRuntimeContribution');
|
|
5
|
+
export const AgentExtension = Symbol('AgentExtension');
|
|
6
|
+
export const AgentSessionFactory = Symbol('AgentSessionFactory');
|
|
7
|
+
export const AgentSessionManager = Symbol('AgentSessionManager');
|
|
8
|
+
|
|
9
|
+
/** Configuration key of {@link CodingAgentOptions}. */
|
|
10
|
+
export const CODING_AGENT_OPTIONS = 'cell.ai.codingAgent';
|
|
11
|
+
|
|
12
|
+
/** `cell.ai.codingAgent`. Names follow the options of pi's `createAgentSession()`. */
|
|
13
|
+
export interface CodingAgentOptions {
|
|
14
|
+
/** Working directory of sessions: tools act here and project resources are found here. Default: the process directory. */
|
|
15
|
+
cwd?: string;
|
|
16
|
+
/** pi's global directory (auth.json, models.json, settings.json, extensions, skills). Default: `~/.pi/agent`. */
|
|
17
|
+
agentDir?: string;
|
|
18
|
+
/** `<provider>/<model id>`. Default: pi's settings, then the first model with credentials. */
|
|
19
|
+
model?: string;
|
|
20
|
+
thinkingLevel?: ThinkingLevel;
|
|
21
|
+
/** Allowlist of tool names; `*` matches any characters. Default: read, bash, edit, write and extension tools. */
|
|
22
|
+
tools?: string[];
|
|
23
|
+
excludeTools?: string[];
|
|
24
|
+
/** Replaces pi's system prompt. */
|
|
25
|
+
systemPrompt?: string;
|
|
26
|
+
/** Appended to the system prompt. */
|
|
27
|
+
appendSystemPrompt?: string;
|
|
28
|
+
/** Load extensions, skills, prompt templates and AGENTS.md from cwd and agentDir as the pi CLI does. Default: true. */
|
|
29
|
+
discoverResources?: boolean;
|
|
30
|
+
/** Write sessions as JSONL files where the pi CLI keeps them (`pi --resume` lists them). Default: false. */
|
|
31
|
+
persistSessions?: boolean;
|
|
32
|
+
/** Let the model runtime refresh model catalogs over the network when it is created. Default: false. */
|
|
33
|
+
allowModelNetwork?: boolean;
|
|
34
|
+
/** pi's MCP client: the servers of mcp.json (agentDir, and the project once trusted) plus `servers`. */
|
|
35
|
+
mcp?: CodingAgentMcpOptions;
|
|
36
|
+
/** pi's codemode tool: the model writes JavaScript that calls tools in a sandbox. `only` hides the tools codemode can call. Default: off. */
|
|
37
|
+
codemode?: 'off' | 'on' | 'only';
|
|
38
|
+
/** pi's tool_search tool, which finds tools that are not declared to the model. Default: false. */
|
|
39
|
+
toolSearch?: boolean;
|
|
40
|
+
/** API keys by provider id, e.g. `anthropic: "${ env.MY_KEY }"`. Empty values are ignored. */
|
|
41
|
+
apiKeys?: Record<string, string | undefined>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface CodingAgentMcpOptions {
|
|
45
|
+
/** Default: false. */
|
|
46
|
+
enabled?: boolean;
|
|
47
|
+
/** MCP servers by name, in the `mcpServers` format of mcp.json (`command`/`args`/`env`, or `url`/`headers`). */
|
|
48
|
+
servers?: Record<string, McpServerConfig>;
|
|
49
|
+
/** How long the first prompt waits for servers with `direct` exposure that are still connecting. Default: 10000. */
|
|
50
|
+
startupWaitMs?: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Options of one session; they override `cell.ai.codingAgent`. */
|
|
54
|
+
export type AgentSessionOptions = Pick<
|
|
55
|
+
CodingAgentOptions,
|
|
56
|
+
'cwd' | 'model' | 'thinkingLevel' | 'tools' | 'excludeTools' | 'systemPrompt' | 'appendSystemPrompt'
|
|
57
|
+
>;
|
|
58
|
+
|
|
59
|
+
export interface AgentSessionInfo {
|
|
60
|
+
id: string;
|
|
61
|
+
cwd: string;
|
|
62
|
+
/** `<provider>/<model id>`, undefined when no model is available. */
|
|
63
|
+
model?: string;
|
|
64
|
+
thinkingLevel: ThinkingLevel;
|
|
65
|
+
streaming: boolean;
|
|
66
|
+
messageCount: number;
|
|
67
|
+
createdAt: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The pi model runtime (catalogs and credentials) shared by all sessions. */
|
|
71
|
+
export interface ModelRuntimeProvider {
|
|
72
|
+
provide(): Promise<ModelRuntime>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Configures the model runtime once it is created: register providers, set credentials. */
|
|
76
|
+
export interface ModelRuntimeContribution {
|
|
77
|
+
configure(runtime: ModelRuntime): void | Promise<void>;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* A pi extension as a Cell component: `register` runs for each new session with pi's `ExtensionAPI`
|
|
82
|
+
* (`registerTool`, `registerCommand`, `on(event)`, ...), and the component can use injected services.
|
|
83
|
+
*/
|
|
84
|
+
export interface AgentExtension {
|
|
85
|
+
/** Name in pi's diagnostics. Default: the class name. */
|
|
86
|
+
readonly name?: string;
|
|
87
|
+
register(pi: ExtensionAPI): void | Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Creates pi sessions from `cell.ai.codingAgent`, the model runtime and the {@link AgentExtension}s. */
|
|
91
|
+
export interface AgentSessionFactory {
|
|
92
|
+
create(options?: AgentSessionOptions): Promise<AgentSession>;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Live sessions of the application, by pi's session id. They are disposed when the application stops. */
|
|
96
|
+
export interface AgentSessionManager {
|
|
97
|
+
create(options?: AgentSessionOptions): Promise<AgentSession>;
|
|
98
|
+
/** Throws {@link AgentSessionNotFoundError} for an unknown id. */
|
|
99
|
+
get(id: string): AgentSession;
|
|
100
|
+
find(id: string): AgentSession | undefined;
|
|
101
|
+
info(id: string): AgentSessionInfo;
|
|
102
|
+
list(): AgentSessionInfo[];
|
|
103
|
+
/** Aborts the running work of the session and forgets it. */
|
|
104
|
+
dispose(id: string): void;
|
|
105
|
+
disposeAll(): void;
|
|
106
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { CustomError } from '@celljs/core';
|
|
2
|
+
|
|
3
|
+
export class CodingAgentError extends CustomError {}
|
|
4
|
+
|
|
5
|
+
export class AgentSessionNotFoundError extends CodingAgentError {
|
|
6
|
+
constructor(readonly sessionId: string) {
|
|
7
|
+
super(
|
|
8
|
+
`No agent session was found with the id ${sessionId}. Create one with AgentSessionManager.create(); sessions live in memory and end when the application stops.`,
|
|
9
|
+
);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class AgentModelNotFoundError extends CodingAgentError {
|
|
14
|
+
constructor(
|
|
15
|
+
readonly model: string,
|
|
16
|
+
readonly available: string[],
|
|
17
|
+
) {
|
|
18
|
+
super(
|
|
19
|
+
`The model ${model} is not known to pi. Use "<provider>/<model id>"${
|
|
20
|
+
available.length
|
|
21
|
+
? `, one of: ${available.join(', ')}`
|
|
22
|
+
: '; no model has credentials yet: set the API key of a provider (e.g. ANTHROPIC_API_KEY) or cell.ai.codingAgent.apiKeys'
|
|
23
|
+
}.`,
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export class AgentExtensionError extends CodingAgentError {
|
|
29
|
+
constructor(readonly errors: { path: string; error: string }[]) {
|
|
30
|
+
super(`Agent extensions failed to load: ${errors.map(e => `${e.path}: ${e.error}`).join('; ')}`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './errors';
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { afterEach, describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { AgentSessionManager } from '../coding-agent-protocol';
|
|
4
|
+
import type { AgentSessionEvent } from '../pi';
|
|
5
|
+
import { createTestContainer, type TestContainer } from '../test';
|
|
6
|
+
import { AgentEventUtil, type EventStreamResponse } from './agent-event-util';
|
|
7
|
+
|
|
8
|
+
class RecordingResponse implements EventStreamResponse {
|
|
9
|
+
readonly headers: Record<string, string> = {};
|
|
10
|
+
chunks = '';
|
|
11
|
+
writableEnded = false;
|
|
12
|
+
|
|
13
|
+
setHeader(name: string, value: string): void {
|
|
14
|
+
this.headers[name.toLowerCase()] = value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
write(chunk: string): void {
|
|
18
|
+
expect(this.writableEnded).to.equal(false);
|
|
19
|
+
this.chunks += chunk;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
end(): void {
|
|
23
|
+
this.writableEnded = true;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
get frames(): { event: string; data: any }[] {
|
|
27
|
+
return this.chunks
|
|
28
|
+
.split('\n\n')
|
|
29
|
+
.filter(Boolean)
|
|
30
|
+
.map(frame => {
|
|
31
|
+
const [event, data] = frame.split('\n');
|
|
32
|
+
return { event: event.slice('event: '.length), data: JSON.parse(data.slice('data: '.length)) };
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
describe('AgentEventUtil', () => {
|
|
38
|
+
let test: TestContainer;
|
|
39
|
+
|
|
40
|
+
afterEach(() => test?.container.get<AgentSessionManager>(AgentSessionManager).disposeAll());
|
|
41
|
+
|
|
42
|
+
describe('toWire', () => {
|
|
43
|
+
const usage = { input: 1, output: 2 };
|
|
44
|
+
const update = (assistantMessageEvent: any) =>
|
|
45
|
+
({ type: 'message_update', message: { role: 'assistant', usage, content: [] }, assistantMessageEvent }) as unknown as AgentSessionEvent;
|
|
46
|
+
|
|
47
|
+
it('keeps the delta and the usage of message_update', () => {
|
|
48
|
+
const wire = AgentEventUtil.toWire(update({ type: 'text_delta', contentIndex: 0, delta: 'Hi', partial: { content: [] } }));
|
|
49
|
+
expect(wire).to.deep.equal({ type: 'message_update', usage, assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: 'Hi' } });
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('names the tool of toolcall_start', () => {
|
|
53
|
+
const partial = {
|
|
54
|
+
content: [
|
|
55
|
+
{ type: 'text', text: '' },
|
|
56
|
+
{ type: 'toolCall', id: 'call-1', name: 'greet', arguments: {} },
|
|
57
|
+
],
|
|
58
|
+
};
|
|
59
|
+
const wire = AgentEventUtil.toWire(update({ type: 'toolcall_start', contentIndex: 1, partial })) as any;
|
|
60
|
+
expect(wire.assistantMessageEvent).to.deep.equal({ type: 'toolcall_start', contentIndex: 1, id: 'call-1', toolName: 'greet' });
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('leaves other events unchanged', () => {
|
|
64
|
+
const event = { type: 'agent_settled', aborted: false } as AgentSessionEvent;
|
|
65
|
+
expect(AgentEventUtil.toWire(event)).to.equal(event);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe('stream', () => {
|
|
70
|
+
it('writes the events of a run as Server-Sent Events and ends the response', async () => {
|
|
71
|
+
test = await createTestContainer();
|
|
72
|
+
test.faux.reply('Hello from pi');
|
|
73
|
+
const session = await test.container.get<AgentSessionManager>(AgentSessionManager).create();
|
|
74
|
+
const response = new RecordingResponse();
|
|
75
|
+
await AgentEventUtil.stream(session, response, () => session.prompt('hi'));
|
|
76
|
+
expect(response.headers['content-type']).to.equal('text/event-stream; charset=utf-8');
|
|
77
|
+
expect(response.writableEnded).to.equal(true);
|
|
78
|
+
const frames = response.frames;
|
|
79
|
+
expect(frames[0].event).to.equal('agent_start');
|
|
80
|
+
expect(frames[frames.length - 1]).to.deep.equal({ event: 'agent_settled', data: { type: 'agent_settled', aborted: false } });
|
|
81
|
+
const deltas = frames.filter(f => f.data.assistantMessageEvent?.type === 'text_delta');
|
|
82
|
+
expect(deltas.map(f => f.data.assistantMessageEvent.delta).join('')).to.equal('Hello from pi');
|
|
83
|
+
expect(frames.every(f => f.event === f.data.type && !f.data.assistantMessageEvent?.partial)).to.equal(true);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('sends an error event when the run fails', async () => {
|
|
87
|
+
test = await createTestContainer();
|
|
88
|
+
const session = await test.container.get<AgentSessionManager>(AgentSessionManager).create();
|
|
89
|
+
const response = new RecordingResponse();
|
|
90
|
+
await AgentEventUtil.stream(session, response, () => Promise.reject(new Error('no credits')));
|
|
91
|
+
expect(response.frames).to.deep.equal([{ event: 'error', data: { type: 'error', message: 'no credits' } }]);
|
|
92
|
+
expect(response.writableEnded).to.equal(true);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './agent-event-util';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Tools are written once, as @celljs/ai-agent's AgentTool components, for agents and coding agent sessions.
|
|
2
|
+
export { AgentTool } from '@celljs/ai-agent';
|
|
3
|
+
export * from './application-lifecycle';
|
|
4
|
+
export * from './coding-agent-protocol';
|
|
5
|
+
export * from './error';
|
|
6
|
+
export * from './event';
|
|
7
|
+
export * from './pi';
|
|
8
|
+
export * from './runtime';
|
|
9
|
+
export * from './session';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { CodingAgentError } from '../error';
|
|
2
|
+
|
|
3
|
+
/** The module namespace of `@earendil-works/pi-coding-agent`. */
|
|
4
|
+
export type PiSdk = typeof import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }});
|
|
5
|
+
|
|
6
|
+
export namespace PiSdkUtil {
|
|
7
|
+
let sdk: Promise<PiSdk> | undefined;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Loads pi once. pi is an ES module package, so both builds of this package load it with a dynamic
|
|
11
|
+
* `import()`, which also keeps it out of the startup of applications that never create a session.
|
|
12
|
+
*/
|
|
13
|
+
export function load(): Promise<PiSdk> {
|
|
14
|
+
if (!sdk) {
|
|
15
|
+
sdk = import('@earendil-works/pi-coding-agent').catch(cause => {
|
|
16
|
+
sdk = undefined;
|
|
17
|
+
throw new CodingAgentError(
|
|
18
|
+
'Cannot load @earendil-works/pi-coding-agent. Install it next to @celljs/ai-coding-agent; it needs Node.js >= 22.19.0 or Bun.',
|
|
19
|
+
{ cause },
|
|
20
|
+
);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
return sdk;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// pi is an ES module package: the CommonJS build of this package can only name its types through
|
|
2
|
+
// import types with `resolution-mode`.
|
|
3
|
+
export type AgentSession = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).AgentSession;
|
|
4
|
+
export type ModelRuntime = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ModelRuntime;
|
|
5
|
+
export type AgentSessionEvent = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).AgentSessionEvent;
|
|
6
|
+
export type JsonAgentSessionEvent = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).JsonAgentSessionEvent;
|
|
7
|
+
export type ExtensionAPI = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ExtensionAPI;
|
|
8
|
+
export type ExtensionFactory = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ExtensionFactory;
|
|
9
|
+
export type ToolDefinition = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ToolDefinition;
|
|
10
|
+
export type McpServerConfig = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).McpServerConfig;
|
|
11
|
+
export type ThinkingLevel = AgentSession['thinkingLevel'];
|
|
12
|
+
export type Model = NonNullable<AgentSession['model']>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './model-runtime-provider';
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { PI_OPTIONS, type PiOptions } from '@celljs/ai-pi';
|
|
3
|
+
import { Autowired, Component, Optional, Value } from '@celljs/core';
|
|
4
|
+
import { CODING_AGENT_OPTIONS, type CodingAgentOptions, ModelRuntimeContribution, ModelRuntimeProvider } from '../coding-agent-protocol';
|
|
5
|
+
import { type ModelRuntime, PiSdkUtil } from '../pi';
|
|
6
|
+
|
|
7
|
+
@Component(ModelRuntimeProvider)
|
|
8
|
+
export class DefaultModelRuntimeProvider implements ModelRuntimeProvider {
|
|
9
|
+
@Value(CODING_AGENT_OPTIONS)
|
|
10
|
+
protected readonly options?: CodingAgentOptions;
|
|
11
|
+
|
|
12
|
+
@Value(PI_OPTIONS)
|
|
13
|
+
protected readonly piOptions?: PiOptions;
|
|
14
|
+
|
|
15
|
+
@Autowired(ModelRuntimeContribution)
|
|
16
|
+
@Optional()
|
|
17
|
+
protected readonly contributions: ModelRuntimeContribution[] = [];
|
|
18
|
+
|
|
19
|
+
protected runtime?: Promise<ModelRuntime>;
|
|
20
|
+
|
|
21
|
+
provide(): Promise<ModelRuntime> {
|
|
22
|
+
if (!this.runtime) {
|
|
23
|
+
const runtime = this.doProvide();
|
|
24
|
+
this.runtime = runtime;
|
|
25
|
+
runtime.catch(() => {
|
|
26
|
+
if (this.runtime === runtime) {
|
|
27
|
+
this.runtime = undefined;
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return this.runtime;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
protected async doProvide(): Promise<ModelRuntime> {
|
|
35
|
+
const options = this.options ?? {};
|
|
36
|
+
const sdk = await PiSdkUtil.load();
|
|
37
|
+
const files = options.agentDir ? { authPath: join(options.agentDir, 'auth.json'), modelsPath: join(options.agentDir, 'models.json') } : {};
|
|
38
|
+
const runtime = await sdk.ModelRuntime.create({ ...files, allowModelNetwork: options.allowModelNetwork === true });
|
|
39
|
+
// Keys of cell.ai.pi serve coding agent sessions too; cell.ai.codingAgent.apiKeys win.
|
|
40
|
+
for (const [provider, apiKey] of Object.entries({ ...this.piOptions?.apiKeys, ...options.apiKeys })) {
|
|
41
|
+
if (apiKey) {
|
|
42
|
+
await runtime.setRuntimeApiKey(provider, apiKey);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
for (const contribution of this.contributions ?? []) {
|
|
46
|
+
await contribution.configure(runtime);
|
|
47
|
+
}
|
|
48
|
+
return runtime;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { afterEach, describe, it } from 'bun:test';
|
|
2
|
+
import { mkdtempSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { expect } from 'chai';
|
|
6
|
+
import { AgentSessionManager } from '../coding-agent-protocol';
|
|
7
|
+
import { createTestContainer, type TestContainer } from '../test';
|
|
8
|
+
|
|
9
|
+
/** A stdio MCP server with one tool, `say`, that echoes its text. */
|
|
10
|
+
const ECHO_SERVER = `
|
|
11
|
+
import { createInterface } from 'node:readline';
|
|
12
|
+
const send = message => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\\n');
|
|
13
|
+
createInterface({ input: process.stdin }).on('line', line => {
|
|
14
|
+
const { id, method, params } = JSON.parse(line);
|
|
15
|
+
if (id === undefined) return;
|
|
16
|
+
if (method === 'initialize') {
|
|
17
|
+
send({ id, result: { protocolVersion: params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'echo', version: '1.0.0' } } });
|
|
18
|
+
} else if (method === 'tools/list') {
|
|
19
|
+
send({ id, result: { tools: [ { name: 'say', description: 'Echoes the text', inputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: [ 'text' ] } } ] } });
|
|
20
|
+
} else if (method === 'tools/call') {
|
|
21
|
+
send({ id, result: { content: [ { type: 'text', text: 'echo: ' + params.arguments.text } ] } });
|
|
22
|
+
} else {
|
|
23
|
+
send({ id, error: { code: -32601, message: 'Method not found' } });
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
`;
|
|
27
|
+
|
|
28
|
+
describe('built-in pi extensions', () => {
|
|
29
|
+
let test: TestContainer;
|
|
30
|
+
|
|
31
|
+
const sessions = () => test.container.get<AgentSessionManager>(AgentSessionManager);
|
|
32
|
+
|
|
33
|
+
afterEach(() => sessions().disposeAll());
|
|
34
|
+
|
|
35
|
+
it('are off by default', async () => {
|
|
36
|
+
test = await createTestContainer();
|
|
37
|
+
const tools = (await sessions().create()).getActiveToolNames();
|
|
38
|
+
expect(tools).to.not.include('codemode').and.not.include('tool_search');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('turns on codemode and tool_search', async () => {
|
|
42
|
+
test = await createTestContainer({ codemode: 'on', toolSearch: true });
|
|
43
|
+
const session = await sessions().create();
|
|
44
|
+
expect(session.getActiveToolNames()).to.include('codemode').and.include('tool_search');
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('connects the configured MCP servers and lets the model call their tools', async () => {
|
|
48
|
+
const server = join(mkdtempSync(join(tmpdir(), 'mcp-echo-')), 'echo-server.mjs');
|
|
49
|
+
writeFileSync(server, ECHO_SERVER);
|
|
50
|
+
test = await createTestContainer({ mcp: { enabled: true, servers: { echo: { command: process.execPath, args: [server], exposure: 'direct' } } } });
|
|
51
|
+
const session = await sessions().create();
|
|
52
|
+
test.faux.reply({ tool: 'mcp__echo__say', args: { text: 'hi' } }, 'Done');
|
|
53
|
+
await session.prompt('say hi');
|
|
54
|
+
expect(session.getActiveToolNames()).to.include('mcp__echo__say');
|
|
55
|
+
const result = session.messages.find(m => m.role === 'toolResult') as any;
|
|
56
|
+
expect(result.content[0].text).to.equal('echo: hi');
|
|
57
|
+
expect(session.getLastAssistantText()).to.equal('Done');
|
|
58
|
+
}, 30000);
|
|
59
|
+
});
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { AgentTool } from '@celljs/ai-agent';
|
|
3
|
+
import { Autowired, Component, Logger, Optional, Value } from '@celljs/core';
|
|
4
|
+
import {
|
|
5
|
+
AgentExtension,
|
|
6
|
+
AgentSessionFactory,
|
|
7
|
+
type AgentSessionOptions,
|
|
8
|
+
CODING_AGENT_OPTIONS,
|
|
9
|
+
type CodingAgentOptions,
|
|
10
|
+
ModelRuntimeProvider,
|
|
11
|
+
} from '../coding-agent-protocol';
|
|
12
|
+
import { AgentExtensionError, AgentModelNotFoundError } from '../error';
|
|
13
|
+
import { type AgentSession, type ExtensionAPI, type ExtensionFactory, type Model, type ModelRuntime, type PiSdk, PiSdkUtil, type ToolDefinition } from '../pi';
|
|
14
|
+
|
|
15
|
+
@Component(AgentSessionFactory)
|
|
16
|
+
export class DefaultAgentSessionFactory implements AgentSessionFactory {
|
|
17
|
+
@Value(CODING_AGENT_OPTIONS)
|
|
18
|
+
protected readonly options?: CodingAgentOptions;
|
|
19
|
+
|
|
20
|
+
@Autowired(ModelRuntimeProvider)
|
|
21
|
+
protected readonly modelRuntimeProvider: ModelRuntimeProvider;
|
|
22
|
+
|
|
23
|
+
@Autowired(AgentExtension)
|
|
24
|
+
@Optional()
|
|
25
|
+
protected readonly extensions: AgentExtension[] = [];
|
|
26
|
+
|
|
27
|
+
@Autowired(AgentTool)
|
|
28
|
+
@Optional()
|
|
29
|
+
protected readonly tools: AgentTool[] = [];
|
|
30
|
+
|
|
31
|
+
@Autowired(Logger)
|
|
32
|
+
protected readonly logger: Logger;
|
|
33
|
+
|
|
34
|
+
async create(sessionOptions: AgentSessionOptions = {}): Promise<AgentSession> {
|
|
35
|
+
const options = this.mergeOptions(sessionOptions);
|
|
36
|
+
const sdk = await PiSdkUtil.load();
|
|
37
|
+
const modelRuntime = await this.modelRuntimeProvider.provide();
|
|
38
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
39
|
+
const agentDir = options.agentDir ? resolve(options.agentDir) : sdk.getAgentDir();
|
|
40
|
+
const settingsManager = sdk.SettingsManager.create(cwd, agentDir);
|
|
41
|
+
const resourceLoader = await this.createResourceLoader(sdk, options, cwd, agentDir, settingsManager);
|
|
42
|
+
const builtinTools = [options.codemode && options.codemode !== 'off' ? '+codemode' : '', options.toolSearch ? '+tool_search' : ''].filter(Boolean);
|
|
43
|
+
if (builtinTools.length) {
|
|
44
|
+
// pi registers codemode and tool_search inactive; `+name` adds them to the default tools. Set after
|
|
45
|
+
// the resource loader, whose reload reads the settings again.
|
|
46
|
+
settingsManager.applyOverrides({ defaultTools: builtinTools });
|
|
47
|
+
}
|
|
48
|
+
const { session } = await sdk.createAgentSession({
|
|
49
|
+
cwd,
|
|
50
|
+
agentDir,
|
|
51
|
+
modelRuntime,
|
|
52
|
+
settingsManager,
|
|
53
|
+
resourceLoader,
|
|
54
|
+
sessionManager: options.persistSessions ? sdk.SessionManager.create(cwd) : sdk.SessionManager.inMemory(cwd),
|
|
55
|
+
model: options.model ? this.resolveModel(modelRuntime, options.model) : undefined,
|
|
56
|
+
thinkingLevel: options.thinkingLevel,
|
|
57
|
+
tools: options.tools,
|
|
58
|
+
excludeTools: options.excludeTools,
|
|
59
|
+
customTools: (this.tools ?? []).map(tool => this.toToolDefinition(tool)),
|
|
60
|
+
});
|
|
61
|
+
// Headless: extensions run without a UI, as in pi's RPC mode.
|
|
62
|
+
await session.bindExtensions({ mode: 'rpc' });
|
|
63
|
+
return session;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
protected mergeOptions(sessionOptions: AgentSessionOptions): CodingAgentOptions {
|
|
67
|
+
const options: CodingAgentOptions = { ...this.options };
|
|
68
|
+
for (const [key, value] of Object.entries(sessionOptions)) {
|
|
69
|
+
if (value !== undefined) {
|
|
70
|
+
(options as any)[key] = value;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return options;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
protected async createResourceLoader(
|
|
77
|
+
sdk: PiSdk,
|
|
78
|
+
options: CodingAgentOptions,
|
|
79
|
+
cwd: string,
|
|
80
|
+
agentDir: string,
|
|
81
|
+
settingsManager: ReturnType<PiSdk['SettingsManager']['create']>,
|
|
82
|
+
): Promise<InstanceType<PiSdk['DefaultResourceLoader']>> {
|
|
83
|
+
const discover = options.discoverResources !== false;
|
|
84
|
+
const names = new Set<string>();
|
|
85
|
+
const resourceLoader = new sdk.DefaultResourceLoader({
|
|
86
|
+
cwd,
|
|
87
|
+
agentDir,
|
|
88
|
+
settingsManager,
|
|
89
|
+
noExtensions: !discover,
|
|
90
|
+
noSkills: !discover,
|
|
91
|
+
noPromptTemplates: !discover,
|
|
92
|
+
noThemes: true,
|
|
93
|
+
noContextFiles: !discover,
|
|
94
|
+
systemPrompt: options.systemPrompt,
|
|
95
|
+
appendSystemPrompt: options.appendSystemPrompt ? [options.appendSystemPrompt] : undefined,
|
|
96
|
+
extensionFactories: [
|
|
97
|
+
...this.builtinExtensions(sdk, options),
|
|
98
|
+
...(this.extensions ?? []).map(extension => ({
|
|
99
|
+
name: extension.name ?? extension.constructor.name,
|
|
100
|
+
factory: (pi: ExtensionAPI) => extension.register(pi),
|
|
101
|
+
})),
|
|
102
|
+
].map(extension => {
|
|
103
|
+
names.add(extension.name);
|
|
104
|
+
return extension;
|
|
105
|
+
}),
|
|
106
|
+
});
|
|
107
|
+
await resourceLoader.reload();
|
|
108
|
+
const errors = resourceLoader.getExtensions().errors;
|
|
109
|
+
const own = errors.filter(e => names.has(this.inlineName(e.path)));
|
|
110
|
+
if (own.length) {
|
|
111
|
+
throw new AgentExtensionError(own);
|
|
112
|
+
}
|
|
113
|
+
for (const error of errors) {
|
|
114
|
+
this.logger.warn(`Skipped the pi extension ${error.path}: ${error.error}`);
|
|
115
|
+
}
|
|
116
|
+
return resourceLoader;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** An AgentTool component as a tool of pi coding agent: the same shape, plus the session context it does not need. */
|
|
120
|
+
protected toToolDefinition(tool: AgentTool): ToolDefinition {
|
|
121
|
+
return {
|
|
122
|
+
name: tool.name,
|
|
123
|
+
label: tool.label,
|
|
124
|
+
description: tool.description,
|
|
125
|
+
parameters: tool.parameters,
|
|
126
|
+
executionMode: tool.executionMode,
|
|
127
|
+
prepareArguments: tool.prepareArguments?.bind(tool),
|
|
128
|
+
execute: (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params as any, signal, onUpdate as any),
|
|
129
|
+
} as ToolDefinition;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The extensions the pi CLI loads by default, as `cell.ai.codingAgent` turns them on. */
|
|
133
|
+
protected builtinExtensions(sdk: PiSdk, options: CodingAgentOptions): { name: string; factory: ExtensionFactory }[] {
|
|
134
|
+
const extensions: { name: string; factory: ExtensionFactory }[] = [];
|
|
135
|
+
if (options.codemode && options.codemode !== 'off') {
|
|
136
|
+
extensions.push({ name: 'codemode', factory: sdk.createCodemodeExtension({ mode: options.codemode }) });
|
|
137
|
+
}
|
|
138
|
+
if (options.toolSearch) {
|
|
139
|
+
extensions.push({ name: 'tool_search', factory: sdk.createToolSearchExtension() });
|
|
140
|
+
}
|
|
141
|
+
const mcp = options.mcp;
|
|
142
|
+
if (mcp?.enabled) {
|
|
143
|
+
extensions.push({ name: 'mcp', factory: sdk.createMcpExtension({ startupWaitMs: mcp.startupWaitMs }) });
|
|
144
|
+
const servers = Object.entries(mcp.servers ?? {});
|
|
145
|
+
if (servers.length) {
|
|
146
|
+
extensions.push({
|
|
147
|
+
name: 'cell-mcp-servers',
|
|
148
|
+
factory: pi => {
|
|
149
|
+
for (const [name, config] of servers) {
|
|
150
|
+
pi.registerMcpServer(name, config);
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return extensions;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
protected inlineName(path: string): string {
|
|
160
|
+
const match = /^<inline:(.*)>$/.exec(path);
|
|
161
|
+
return match ? match[1] : path;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
protected resolveModel(modelRuntime: ModelRuntime, ref: string): Model {
|
|
165
|
+
const index = ref.indexOf('/');
|
|
166
|
+
const model = index > 0 ? modelRuntime.getModel(ref.slice(0, index), ref.slice(index + 1)) : undefined;
|
|
167
|
+
if (!model) {
|
|
168
|
+
throw new AgentModelNotFoundError(
|
|
169
|
+
ref,
|
|
170
|
+
modelRuntime.getAvailableSnapshot().map(m => `${m.provider}/${m.id}`),
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
return model;
|
|
174
|
+
}
|
|
175
|
+
}
|