Skip to content

Commit 8e9ecbc

Browse files
committed
feat: introduce artifact management over ACP
- Added support for artifact creation, reading, and listing through new session methods: `session/artifacts/list`, `session/artifacts/read`, and `session/artifacts/write`. - Implemented artifact storage with versioning and conflict detection in `ArtifactStore`. - Created a new `artifacts.ts` module to handle artifact-related methods and notifications. - Updated `acp-agent.ts` to integrate artifact methods and metadata into the ACP agent. - Enhanced documentation to cover the new artifact features and usage. - Added tests for artifact storage functionality, including validation and error handling.
1 parent a6b66b3 commit 8e9ecbc

9 files changed

Lines changed: 718 additions & 4 deletions

File tree

‎crewcoder-agent/AGENTS.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,15 @@ replay. Treat persisted prompts/events as sensitive and preserve package/protoco
920920

921921
## ACP adapter
922922

923+
ACP artifact storage and model tools live in `src/core/artifact-store.ts` and
924+
`src/acp/artifacts.ts`; see [Artifacts over ACP](docs/ARTIFACTS.md). Keep source inert,
925+
session-scoped, bounded, private, and independent of workspace/host filesystem I/O.
926+
Updates require the current revision; notify `_crewcoder/artifact_updated` only after
927+
committing, and keep list/read authoritative for reconnect recovery. Never execute,
928+
render, sanitize, or resolve artifact dependencies inside CrewCoder. The embedding app
929+
owns its preview sandbox. Preserve mutation approvals, cancellation, and exclusion from
930+
hosted-text-only tools/writes. Reserve artifact tool names against host shadowing.
931+
923932
Host-managed Supervisor sessions use the versioned `session/set_tool_policy` contract in [Hosted text tool policy](docs/HOSTED_TOOL_POLICY.md). Preserve fail-closed native-tool restrictions, hosted I/O without disk/image fallback, and exclusion of executable extension hooks. Loaded sessions must receive the policy again before prompting; unrestricted Crew Member and CLI sessions remain unchanged.
924933

925934
The `codex-cli` provider runs the user's own Codex CLI and login; with provider-native file tools off it must stay locked to dynamic tools (see [Bring-your-own Codex CLI](docs/CODEX_CLI_PROVIDER.md)). `crewcoder auth --json` must stay read-only and identity-free.

‎crewcoder-agent/README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ Layout:
2525
config.json
2626
fleet-token
2727
sessions/
28+
artifacts/
2829
goals/
2930
extensions/
3031
cache/
@@ -281,6 +282,11 @@ ACP editor -> ACP over SSH stdio -> CrewCoder ACP adapter -> remote agent
281282

282283
Use ACP when editor interoperability matters. ACP is a standardized editor-facing protocol; it is not CrewCoder's persistent multi-run service. See `docs/ACP_ADAPTER.md`.
283284

285+
ACP sessions expose durable HTML, SVG, Mermaid, and Markdown artifacts through model tools,
286+
list/read/write endpoints, and change notifications. Your app owns the artifact browser,
287+
sandboxed preview, source editor, and download controls. See [Artifacts over ACP](docs/ARTIFACTS.md)
288+
for the versioned wire contract and integration examples.
289+
284290
### Fleet mode: applications and orchestration
285291

286292
Fleet mode keeps a CrewCoder server running and lets authenticated clients create runs, inspect status, replay events, stream live output, and send controls:

‎crewcoder-agent/docs/ACP_ADAPTER.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,18 @@ full `UsageSummary` including `contextWindow` and `lastInputTokens`) and a top-l
205205
Agent-to-client calls used: `session/update`, `session/request_permission`,
206206
`fs/read_text_file`, `fs/write_text_file`.
207207

208+
## Artifacts
209+
210+
`initialize._meta["crewcoder/artifacts"]` advertises the versioned
211+
`session/artifacts/list`, `session/artifacts/read`, and `session/artifacts/write`
212+
methods. Normal ACP sessions offer `artifact_write`, `artifact_read`, and
213+
`artifact_list` to tool-routed models. Changes emit a separate
214+
`_crewcoder/artifact_updated` JSON-RPC notification with session-scoped metadata.
215+
Hosts re-list after loading or reconnecting and fetch source to render or download.
216+
The embedding app owns preview isolation and editing UI; CrewCoder never executes source.
217+
Hosted-text-only sessions exclude these tools and refuse artifact write RPCs.
218+
See [Artifacts over ACP](ARTIFACTS.md) for schemas, revisions, permissions, and limitations.
219+
208220
## Event translation
209221

210222
`src/acp/event-translator.ts` maps `AgentEvent`s onto `session/update` payloads:

‎crewcoder-agent/docs/ARTIFACTS.md‎

Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
# Artifacts over ACP
2+
3+
CrewCoder stores model-generated source documents and exposes them to embedding apps over
4+
ACP. Your app owns its artifact browser, preview sandbox, source editor, and download UI.
5+
CrewCoder never renders or executes artifact content and does not start a preview server.
6+
7+
This is a CrewCoder ACP extension, not a standard ACP capability or a provider-native
8+
artifact format. It is implemented by CrewCoder as the ACP **agent** (`crewcoder acp`).
9+
HTTP model providers, Claude's CrewCoder MCP tools, and Codex's dynamic tools use the same
10+
artifact tools when running through this adapter. Nested external ACP providers such as
11+
Grok CLI own their tools and do not receive CrewCoder's artifact tools.
12+
13+
## Discover support
14+
15+
Read `initialize.result._meta["crewcoder/artifacts"]`:
16+
17+
```json
18+
{
19+
"version": 1,
20+
"listMethod": "session/artifacts/list",
21+
"readMethod": "session/artifacts/read",
22+
"writeMethod": "session/artifacts/write",
23+
"notification": "_crewcoder/artifact_updated",
24+
"formats": ["html", "svg", "mermaid", "markdown"],
25+
"maxContentBytes": 524288,
26+
"maxArtifacts": 100,
27+
"maxSessionBytes": 16777216
28+
}
29+
```
30+
31+
Use the advertised method names. Every request requires `sessionId` and `version: 1`.
32+
The session must have been opened through `session/new` or `session/load` on the current
33+
connection. Knowing another session's artifact ID does not grant access to its content.
34+
35+
## App integration
36+
37+
1. Initialize ACP and check the advertised artifact version.
38+
2. Open or load a session, then call `session/artifacts/list` to populate your browser.
39+
3. Listen for `_crewcoder/artifact_updated` JSON-RPC notifications; upsert the metadata by
40+
session and artifact ID. Fetch the latest source when opening or refreshing a preview.
41+
4. Use `session/artifacts/read` to retrieve the complete document. Route its `format`
42+
to your renderer; HTML includes self-contained interactive charts and apps.
43+
5. Save source edits with `session/artifacts/write`, supplying the revision you read.
44+
On a conflict, fetch the latest source and let the user reconcile it.
45+
6. For downloads, encode the returned `content` as UTF-8 with the returned `mimeType`
46+
and an app-chosen safe filename. There is no public file URL or HTTP download endpoint.
47+
48+
Example requests (JSON-RPC envelope omitted):
49+
50+
```json
51+
{ "method": "session/artifacts/list", "params": { "sessionId": "SESSION", "version": 1 } }
52+
```
53+
54+
Returns `{ artifacts: ArtifactMetadata[] }`, without source content.
55+
56+
```json
57+
{
58+
"method": "session/artifacts/write",
59+
"params": {
60+
"sessionId": "SESSION",
61+
"version": 1,
62+
"title": "Counter",
63+
"format": "html",
64+
"content": "<!doctype html><button onclick=\"this.textContent=Number(this.textContent)+1\">0</button>"
65+
}
66+
}
67+
```
68+
69+
Omit `id` and `expectedRevision` to create. The result is `{ artifact: Artifact }`.
70+
71+
```json
72+
{
73+
"method": "session/artifacts/read",
74+
"params": { "sessionId": "SESSION", "version": 1, "id": "ARTIFACT_ID" }
75+
}
76+
```
77+
78+
Returns `{ artifact: Artifact }`, including the complete `content`.
79+
80+
```json
81+
{
82+
"method": "session/artifacts/write",
83+
"params": {
84+
"sessionId": "SESSION",
85+
"version": 1,
86+
"id": "ARTIFACT_ID",
87+
"expectedRevision": 1,
88+
"title": "Counter",
89+
"format": "html",
90+
"content": "<!doctype html><button onclick=\"this.textContent=Number(this.textContent)+2\">0</button>"
91+
}
92+
}
93+
```
94+
95+
Updates replace the entire source, title, and format. They retain the ID and creation time
96+
and increment `revision`. Only the latest source is retained; revision numbers provide
97+
conflict detection, not historical source retrieval.
98+
99+
### Artifact shape
100+
101+
```ts
102+
type ArtifactFormat = "html" | "svg" | "mermaid" | "markdown";
103+
104+
type ArtifactMetadata = {
105+
id: string; // CrewCoder-generated opaque ID
106+
title: string; // 1–200 characters, no control characters
107+
format: ArtifactFormat;
108+
mimeType: string;
109+
revision: number; // starts at 1
110+
byteSize: number; // UTF-8 content bytes
111+
createdAt: string; // ISO timestamp
112+
updatedAt: string; // ISO timestamp
113+
};
114+
115+
type Artifact = ArtifactMetadata & { content: string };
116+
```
117+
118+
| Format | MIME type | Suggested download extension |
119+
| --- | --- | --- |
120+
| html | text/html | .html |
121+
| svg | image/svg+xml | .svg |
122+
| mermaid | text/vnd.mermaid | .mmd |
123+
| markdown | text/markdown | .md |
124+
125+
### Notifications and recovery
126+
127+
A successful write stores the source before sending this notification:
128+
129+
```json
130+
{
131+
"jsonrpc": "2.0",
132+
"method": "_crewcoder/artifact_updated",
133+
"params": {
134+
"sessionId": "SESSION",
135+
"version": 1,
136+
"action": "created",
137+
"artifact": {
138+
"id": "ARTIFACT_ID",
139+
"title": "Counter",
140+
"format": "html",
141+
"mimeType": "text/html",
142+
"revision": 1,
143+
"byteSize": 95,
144+
"createdAt": "2026-10-27T12:00:00.000Z",
145+
"updatedAt": "2026-10-27T12:00:00.000Z"
146+
}
147+
}
148+
}
149+
```
150+
151+
`action` is `created` or `updated`. Notifications contain metadata only. They are live
152+
hints, not a replay log: re-list after reconnect or load. A disconnected client can miss
153+
a notification even though the write committed. After an uncertain update outcome, read
154+
the artifact before retrying; after an uncertain create outcome, list before creating again.
155+
156+
Artifact validation errors use JSON-RPC code `-32602` with `error.data.artifactCode`:
157+
`invalid`, `not_found`, `conflict`, `limit`, or `busy`. Storage/transport failures retain
158+
the normal ACP internal error path. A conflicting write leaves the stored source unchanged.
159+
A concurrent writer receives `busy` and may retry after re-reading.
160+
161+
## Model behavior and permissions
162+
163+
Normal ACP sessions expose `artifact_write`, `artifact_read`, and `artifact_list` in
164+
the model's tool catalog. Ask the model to create an artifact rather than merely write
165+
HTML into a chat code fence. The write tool accepts the same document fields as the app
166+
endpoint and requires the latest `expectedRevision` on updates.
167+
168+
Model writes use the existing approval, cancellation, workflow, and tool-event paths.
169+
They are mutations, so review mode requests permission and deliberate CrewCoder mode
170+
requires its normal plan approval. App-initiated writes are explicit host operations
171+
and do not prompt the model's approval channel.
172+
173+
The `hosted-text-only` policy excludes these model tools and refuses artifact write RPCs.
174+
Hosts using that policy can supply their own artifact tools with distinct names through
175+
[client-hosted tools](CLIENT_TOOLS.md); the existing host authority stays intact.
176+
The three CrewCoder artifact tool names are reserved and cannot be shadowed by host tools.
177+
178+
Virtual workspace sessions may use artifact storage: these are explicitly owned CrewCoder
179+
state documents, never reads/writes of the host's workspace. Source documents contain no
180+
workspace paths and cannot cause CrewCoder to fetch files or run commands.
181+
182+
## Storage and limitations
183+
184+
Artifacts live at `<CREWCODER_HOME>/artifacts/<sessionId>/<artifactId>.json`, outside
185+
workspace directories and session-prune's disposable files. New artifact directories use
186+
mode `0700`; source records use `0600`. Writes use an atomic rename under a per-session
187+
writer lock. Source is limited to 512 KiB per artifact, 100 artifacts and 16 MiB of current
188+
source per session. UTF-8 bytes determine these limits.
189+
190+
A crash can leave a `.write-lock` directory. Writes fail closed with `busy`; an operator
191+
must confirm no writer is active and clear the stale lock before retrying. Limits and
192+
symlink checks also apply when reading persisted records.
193+
194+
The ordinary ACP session lifecycle still applies: `session/new` allocates an ID, and
195+
the first prompt saves the durable transcript. To reconnect with `session/load`, that
196+
transcript must already exist. Artifacts survive normal process restarts and compaction
197+
under the same session ID. They are not copied by session branching, export, or bundles,
198+
and session deletion/pruning does not automatically remove this separate artifact store.
199+
There is currently no artifact delete RPC or revision-history API.
200+
201+
Only single text documents are supported. Multi-file bundles, binary images, React/TSX
202+
compilation, package installation, external asset resolution, and rendering are not provided.
203+
For charts or apps, models should produce self-contained HTML with inline CSS/JavaScript.
204+
205+
## Preview trust boundary
206+
207+
Treat all source and metadata as untrusted. Your app must render HTML/SVG in an isolated
208+
preview that has no Node/Electron integration, app privileges, filesystem access, credentials,
209+
or privileged IPC bridge. Keep script execution out of the app's origin, deny navigation and
210+
network access by default, and expose only narrowly defined preview capabilities. Sanitize
211+
Markdown and configure diagram rendering safely. Display titles as text.
212+
213+
CrewCoder stores source exactly as supplied; it does not sanitize it or certify that it is
214+
safe to execute. The preview renderer and its security tests belong to the embedding app.

‎crewcoder-agent/src/acp/acp-agent.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import { createClientTextFileHost, virtualFilesystemFromMeta } from "./client-fi
4848
import { translateEvent, type SessionUpdate } from "./event-translator.js";
4949
import { toolKind, toolLocations, toolTitle } from "./tool-kind.js";
5050
import { hostedTextTools } from "./hosted-text-tools.js";
51+
import { ARTIFACT_TOOL_NAMES, CREWCODER_ARTIFACTS_META, artifactMethod, createArtifactTools } from "./artifacts.js";
5152
import { clientHostedTools, CREWCODER_CLIENT_TOOLS_META, parseClientToolDefinitions, type ClientToolDefinition } from "./client-hosted-tools.js";
5253
import { createToolRegistry } from "../tools/index.js";
5354
import { findProvider } from "../providers/provider-registry.js";
@@ -120,6 +121,9 @@ export const CREWCODER_SESSION_SYSTEM_PROMPT_META = {
120121
} as const;
121122

122123
const EXT_METHODS = new Set([
124+
CREWCODER_ARTIFACTS_META.listMethod,
125+
CREWCODER_ARTIFACTS_META.readMethod,
126+
CREWCODER_ARTIFACTS_META.writeMethod,
123127
"session/set_tool_policy",
124128
"session/set_client_tools",
125129
"session/set_system_prompt",
@@ -140,7 +144,7 @@ function reservedToolNames(): ReadonlySet<string> {
140144
if (!reservedNames) {
141145
const modes = ["general", "crewcoder", "plugin", "extension"] as const;
142146
const profiles = ["standalone", "crewcode"] as const;
143-
reservedNames = new Set(profiles.flatMap((profile) => modes.flatMap((mode) => createToolRegistry(profile, mode).map((tool) => tool.name))));
147+
reservedNames = new Set([...ARTIFACT_TOOL_NAMES, ...profiles.flatMap((profile) => modes.flatMap((mode) => createToolRegistry(profile, mode).map((tool) => tool.name)))]);
144148
}
145149
return reservedNames;
146150
}
@@ -191,7 +195,8 @@ export class CrewCoderAcpAgent implements Agent {
191195
"crewcoder/projectInstructions": CREWCODER_PROJECT_INSTRUCTIONS_META,
192196
"crewcoder/instructionPolicy": CREWCODER_INSTRUCTION_POLICY_META,
193197
"crewcoder/sessionToolPolicy": { method: "session/set_tool_policy", version: 1, policies: ["hosted-text-only"] },
194-
"crewcoder/clientTools": CREWCODER_CLIENT_TOOLS_META
198+
"crewcoder/clientTools": CREWCODER_CLIENT_TOOLS_META,
199+
"crewcoder/artifacts": CREWCODER_ARTIFACTS_META
195200
}
196201
};
197202
}
@@ -255,6 +260,10 @@ export class CrewCoderAcpAgent implements Agent {
255260
const sessionId = typeof params.sessionId === "string" ? params.sessionId : "";
256261
const session = this.session(sessionId);
257262

263+
if (method.startsWith("session/artifacts/")) {
264+
return artifactMethod(this.conn, session.sessionId, method, params, session.hostedTextOnly === true);
265+
}
266+
258267
if (method === "session/set_tool_policy") {
259268
if (session.abort) throw RequestError.invalidParams({ reason: "Cannot change tool policy during a prompt" });
260269
if (params.policy !== "hosted-text-only" || params.version !== 1) throw RequestError.invalidParams({ reason: "Unsupported tool policy" });
@@ -473,7 +482,10 @@ export class CrewCoderAcpAgent implements Agent {
473482
signal: abort.signal,
474483
textFiles: createClientTextFileHost(this.conn, session.sessionId, this.clientCapabilities),
475484
virtualFilesystem: session.hostedTextOnly || session.virtualFilesystem,
476-
additionalTools: session.clientTools?.length ? clientHostedTools(this.conn, session.sessionId, session.clientTools) : undefined,
485+
additionalTools: [
486+
...(session.hostedTextOnly ? [] : createArtifactTools(this.conn, session.sessionId)),
487+
...clientHostedTools(this.conn, session.sessionId, session.clientTools ?? [])
488+
],
477489
...(session.hostedTextOnly ? {
478490
tools: hostedTextTools(createClientTextFileHost(this.conn, session.sessionId, this.clientCapabilities)),
479491
hostedToolsOnly: true,

0 commit comments

Comments
 (0)