@celljs/ai-coding-agent 4.6.0 → 4.7.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 (2) hide show
  1. package/README.en.md +224 -0
  2. package/package.json +4 -4
package/README.en.md ADDED
@@ -0,0 +1,224 @@
1
+ # Cell - AI Coding Agent Component
2
+
3
+ Run a [pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) coding agent session in a Cell application. Pi handles model calls, tools (read, bash, edit, write, etc.), sessions, and context compression. This component integrates pi into Cell:
4
+
5
+ - Sessions and model runtime are managed by the DI container and are automatically released when the application stops;
6
+ - Configuration is written under `ai.codingAgent` in `cell.yml`, and option names match those of pi's `createAgentSession()`;
7
+ - Tools are written as `AgentTool` components (shared with @celljs/ai-agent), pi extensions as `AgentExtension` components, and both can use injected services directly;
8
+ - Pi's MCP client, codemode, and tool_search can be enabled by configuration;
9
+ - Events are output in pi's JSON-RPC format and can be returned directly to the frontend as Server-Sent Events.
10
+
11
+ ## Requirements
12
+
13
+ Node.js >= 22.19 or Bun (pi requirement). Pi is an ES module package; this component loads it using dynamic `import()`. Both CommonJS and ESM builds are usable; it is loaded only when the first session is created.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ bun add @celljs/ai-coding-agent
19
+ ```
20
+
21
+ ## Configuration
22
+
23
+ ```yaml
24
+ ai:
25
+ codingAgent:
26
+ cwd: /srv/repo # session working directory where tools read and write; default process cwd
27
+ model: anthropic/claude-sonnet-4-5 # <provider>/<model id>; defaults to pi's settings, then first model with credentials
28
+ thinkingLevel: medium
29
+ tools: [read, grep, find, ls] # tool whitelist, supports *; default read, bash, edit, write plus extension-registered tools
30
+ appendSystemPrompt: Answer in Chinese.
31
+ apiKeys: # in memory only, not written to pi's auth.json
32
+ anthropic: "${ env.MY_ANTHROPIC_KEY }"
33
+ ```
34
+
35
+ | Config | Default | Explanation |
36
+ | --- | --- | --- |
37
+ | `cwd` | Process cwd | Session working directory where tools read and write; this is also where project resources (AGENTS.md, `.pi/`) are discovered |
38
+ | `agentDir` | `~/.pi/agent` | pi global directory: auth.json, models.json, settings.json, extensions, skills |
39
+ | `model` / `thinkingLevel` | pi settings | Model as `<provider>/<model id>`, error `AgentModelNotFoundError` with available models if not found |
40
+ | `tools` / `excludeTools` | pi default tools | Tool whitelist or blacklist |
41
+ | `systemPrompt` / `appendSystemPrompt` | — | Replace or append the system prompt |
42
+ | `discoverResources` | `true` | Load extensions, skills, prompt templates, and AGENTS.md from the cwd and agentDir like the pi CLI does |
43
+ | `persistSessions` | `false` | Also write sessions as pi CLI JSONL files, visible to `pi --resume` |
44
+ | `allowModelNetwork` | `false` | Refresh the model directory online when creating the model runtime |
45
+ | `mcp.enabled` / `mcp.servers` | `false` / — | Enable pi's MCP client: connect servers in the agentDir (and trusted projects) `mcp.json`, plus `servers` (format like `mcpServers`) |
46
+ | `codemode` | `off` | `on` / `only`: model writes JavaScript, called in sandbox via tools |
47
+ | `toolSearch` | `false` | Enable `tool_search` to allow the model to find undeclared tools |
48
+ | `apiKeys` | — | Set API keys per provider; empty values are ignored. `ai.pi.apiKeys` (@celljs/ai-pi) is also used for sessions, and entries here take precedence. Pi also reads `ANTHROPIC_API_KEY` etc. from environment variables. |
49
+
50
+ ## Usage
51
+
52
+ ### Create a session and ask
53
+
54
+ `AgentSessionManager.create()` returns pi's `AgentSession`; you then use pi's API directly (`prompt`, `steer`, `followUp`, `abort`, `subscribe`, `messages`, etc.):
55
+
56
+ ```typescript
57
+ import { Autowired, Component } from '@celljs/core';
58
+ import { AgentSessionManager } from '@celljs/ai-coding-agent';
59
+
60
+ @Component()
61
+ export class ReviewService {
62
+
63
+ @Autowired(AgentSessionManager)
64
+ protected readonly sessionManager: AgentSessionManager;
65
+
66
+ async review(): Promise<string | undefined> {
67
+ const session = await this.sessionManager.create({ tools: [ 'read', 'grep', 'find', 'ls' ] });
68
+ try {
69
+ await session.prompt('Review the changes in src/ and list the risks.');
70
+ return session.getLastAssistantText();
71
+ } finally {
72
+ this.sessionManager.dispose(session.sessionId);
73
+ }
74
+ }
75
+ }
76
+ ```
77
+
78
+ `create()` parameters (`cwd`, `model`, `thinkingLevel`, `tools`, `excludeTools`, `systemPrompt`, `appendSystemPrompt`) override the same-named settings in `ai.codingAgent`. Sessions are stored in memory by pi's `sessionId`: `get(id)` (throws `AgentSessionNotFoundError` if not found), `find(id)`, `info(id)`, `list()`, `dispose(id)`.
79
+
80
+ ### Write tools as Cell components
81
+
82
+ Tools are [@celljs/ai-agent](../ai-agent) `AgentTool` components (also exported from this package). Tools can use injected services directly. One component serves both as a coding session tool and as a tool for general agents created by `AgentFactory`:
83
+
84
+ ```typescript
85
+ import { AgentTool } from '@celljs/ai-coding-agent';
86
+ import { Autowired, Component } from '@celljs/core';
87
+ import { TicketService } from './ticket-service';
88
+
89
+ @Component(AgentTool)
90
+ export class CreateTicketTool implements AgentTool {
91
+ readonly name = 'create_ticket';
92
+ readonly label = 'Create ticket';
93
+ readonly description = 'Creates a ticket in the issue tracker.';
94
+ readonly parameters = { type: 'object', properties: { title: { type: 'string' } }, required: [ 'title' ] };
95
+
96
+ @Autowired(TicketService)
97
+ protected readonly ticketService: TicketService;
98
+
99
+ async execute(_toolCallId: string, params: any) {
100
+ const ticket = await this.ticketService.create(params.title);
101
+ return { content: [ { type: 'text' as const, text: `Created ${ticket.id}` } ], details: {} };
102
+ }
103
+ }
104
+ ```
105
+
106
+ `parameters` is JSON Schema; tool failures are thrown as exceptions. If a `tools` whitelist is configured, the tool name must be listed in it.
107
+
108
+ ### Write pi extensions as Cell components
109
+
110
+ Extension capabilities beyond tools (commands, event handlers, intercepting tool calls, registering MCP servers, etc.; see pi docs `docs/extensions.md`) are written as `AgentExtension` components. The `register` method receives pi's `ExtensionAPI` for each new session:
111
+
112
+ ```typescript
113
+ import { AgentExtension, type ExtensionAPI } from '@celljs/ai-coding-agent';
114
+ import { Autowired, Component, Logger } from '@celljs/core';
115
+
116
+ @Component(AgentExtension)
117
+ export class AuditExtension implements AgentExtension {
118
+
119
+ @Autowired(Logger)
120
+ protected readonly logger: Logger;
121
+
122
+ register(pi: ExtensionAPI): void {
123
+ pi.on('tool_call', async event => {
124
+ this.logger.info(`agent calls ${event.toolName}`);
125
+ return event.toolName === 'bash' ? { block: true, reason: 'bash is disabled' } : undefined;
126
+ });
127
+ }
128
+ }
129
+ ```
130
+
131
+ If `register` throws an error, session creation fails with `AgentExtensionError`. Errors in extensions discovered from disk are only logged as warnings.
132
+
133
+ ### MCP, codemode, and tool_search
134
+
135
+ The pi CLI loads these three extensions by default; the SDK does not. Enable them in configuration. MCP server tool names are `mcp__<server>__<tool>`. Tools with `exposure: direct` are declared directly to the model; tools with the default setting (for example, in `codemode`) are only callable within codemode scripts:
136
+
137
+ ```yaml
138
+ ai:
139
+ codingAgent:
140
+ codemode: "on"
141
+ mcp:
142
+ enabled: true
143
+ servers:
144
+ docs:
145
+ url: https://example.com/mcp
146
+ headers:
147
+ Authorization: "Bearer ${ env.DOCS_TOKEN }"
148
+ filesystem:
149
+ command: npx
150
+ args: [-y, "@modelcontextprotocol/server-filesystem", "."]
151
+ exposure: direct
152
+ ```
153
+
154
+ If a `tools` whitelist is configured, `codemode`, `tool_search`, and `mcp__*` must also be listed. `AgentExtension` can also use `pi.registerMcpServer(name, config)` to register servers on demand.
155
+
156
+ ### Return events as Server-Sent Events
157
+
158
+ `AgentEventUtil.stream(session, response, run)` writes session events as SSE during the execution of `run` and closes the response when done. If `run` fails, it writes an `error` event:
159
+
160
+ ```typescript
161
+ import { AgentEventUtil, AgentSessionManager, type EventStreamResponse } from '@celljs/ai-coding-agent';
162
+ import { Autowired } from '@celljs/core';
163
+ import { Body, Controller, Param, Post, Res } from '@celljs/mvc/lib/node';
164
+
165
+ @Controller('sessions')
166
+ export class AgentController {
167
+
168
+ @Autowired(AgentSessionManager)
169
+ protected readonly sessionManager: AgentSessionManager;
170
+
171
+ @Post(':id/prompt')
172
+ async prompt(@Param('id') id: string, @Body('text') text: string, @Res() response: EventStreamResponse): Promise<void> {
173
+ const session = this.sessionManager.get(id);
174
+ await AgentEventUtil.stream(session, response, () => session.prompt(text));
175
+ }
176
+ }
177
+ ```
178
+
179
+ Each frame is `event: <type>\ndata: <JSON>`. The JSON matches events from pi `--mode json` (pi docs `docs/json.md`): `message_update` carries only deltas and usage information, the full message is in `message_end`, and `agent_settled` marks the round as complete. The component also adds `{ "type": "error", "message": "..." }` when needed. Client disconnection does not abort the session; call `session.abort()` if needed. The full add/get/remove and prompt/abort API is documented in [examples/coding-agent-app](../../examples/coding-agent-app).
180
+
181
+ ### Configure model runtime
182
+
183
+ All sessions share one pi `ModelRuntime` (`ModelRuntimeProvider`). To register custom providers or load credentials from a secret service, implement `ModelRuntimeContribution`:
184
+
185
+ ```typescript
186
+ import { type ModelRuntime, ModelRuntimeContribution } from '@celljs/ai-coding-agent';
187
+ import { Autowired, Component } from '@celljs/core';
188
+ import { SecretStore } from './secret-store';
189
+
190
+ @Component(ModelRuntimeContribution)
191
+ export class GatewayModels implements ModelRuntimeContribution {
192
+
193
+ @Autowired(SecretStore)
194
+ protected readonly secrets: SecretStore;
195
+
196
+ async configure(runtime: ModelRuntime): Promise<void> {
197
+ await runtime.setRuntimeApiKey('openai', await this.secrets.get('openai'));
198
+ }
199
+ }
200
+ ```
201
+
202
+ ## Testing
203
+
204
+ `createTestContainer()` and `FauxModels` from `@celljs/ai-coding-agent/lib/node/test` provide scripted models based on pi's faux provider, with no network access and no reading or writing of `~/.pi`:
205
+
206
+ ```typescript
207
+ import { AgentSessionManager } from '@celljs/ai-coding-agent';
208
+ import { createTestContainer } from '@celljs/ai-coding-agent/lib/node/test';
209
+
210
+ const { container, faux } = await createTestContainer({ tools: [ 'create_ticket' ] }, myModule);
211
+ faux.reply({ tool: 'create_ticket', args: { title: 'Fix login' } }, 'Created.');
212
+ const session = await container.get<AgentSessionManager>(AgentSessionManager).create();
213
+ await session.prompt('File a ticket for the login bug');
214
+ ```
215
+
216
+ `createTestContainer` places the session `cwd` and `agentDir` in a new temporary directory, with the default model being `FauxModels.MODEL`, and resource discovery disabled.
217
+
218
+ ## Security
219
+
220
+ Pi executes tools (read/write files, run commands) with the service process permissions and no sandbox. When exposing sessions over HTTP, add authentication (e.g., `@celljs/security`), open only the needed tools using `tools`, and limit `cwd` to directories the agent is allowed to access. Do not let clients pass `cwd`. See pi docs `docs/security.md` for details.
221
+
222
+ ## Build Output
223
+
224
+ Pi remains an external dependency during `cell build` (in `cell.optionalDependencies`). It is copied along with its dependencies to `.cell/output/server/node_modules` (~160 MB); the output directory can be deployed independently.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ai-coding-agent",
3
- "version": "4.6.0",
3
+ "version": "4.7.0",
4
4
  "description": "Hosts pi coding agent sessions in Cell applications",
5
5
  "keywords": [
6
6
  "cell-component"
@@ -33,9 +33,9 @@
33
33
  "watch": "tsc -b -w --preserveWatchOutput"
34
34
  },
35
35
  "dependencies": {
36
- "@celljs/ai-agent": "4.6.0",
37
- "@celljs/ai-pi": "4.6.0",
38
- "@celljs/core": "4.6.0",
36
+ "@celljs/ai-agent": "4.7.0",
37
+ "@celljs/ai-pi": "4.7.0",
38
+ "@celljs/core": "4.7.0",
39
39
  "@earendil-works/pi-ai": "^1.5.0",
40
40
  "@earendil-works/pi-coding-agent": "^1.5.0"
41
41
  },