Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Provide the project skill to new ACP sessions (#4442)

mike-inkeep70a62bca218f
diff --git a/.changeset/acp-project-skill-pointer.md b/.changeset/acp-project-skill-pointer.md
new file mode 100644
index 000000000..44539c3c8
--- /dev/null
+++ b/.changeset/acp-project-skill-pointer.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-server": patch
+---
+
+In-app agents now receive the Open Knowledge project skill automatically on their first non-command message, without editor setup. Gemini receives the guidance inline. For older projects showing staged skill files in git status, open the project in the desktop app to update its ignore rules.
diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdx
index 3696000fd..b759bcffd 100644
--- a/docs/content/features/editor.mdx
+++ b/docs/content/features/editor.mdx
@@ -126,6 +126,8 @@ An **Ask AI** composer is docked at the bottom of the editor — in the desktop
It's the primary in-editor way to hand work to an agent, and the freetext companion to the menu-driven [Open with AI](#open-with-ai) (whole file / folder / project). Submitting dispatches the typed prompt to your **default agent**, scoped to the current doc (or, in a folder view, the folder), which the agent receives as an `@`-mention. Until you pick something else, that default is an **In app** agent, so the conversation stays inside OpenKnowledge; it falls back to a **Terminal** CLI — preferring one detected on this machine — and then to an **External app**, when no higher option is available here. The agent picker beside the field overrides the default per send, listing In app agents first, then the [Terminal](#open-with-ai) CLIs available on this machine, then the external agent apps detected here. Whatever you pick is remembered on that machine and stays your default until you change it or turn it off in **Agent connections**. Success and failure use the same handoff toast as Open with AI.
+New in-app agent sessions automatically receive the [OpenKnowledge project skill](./skills/built-in-skills.mdx#project-scope) on their first non-command message, even if you have not installed it into an editor. The added guidance stays out of your visible message text.
+
The field also takes attachments when an **In app** agent is selected: drop a file on it, paste a screenshot into it, or use the attach button beside the field. Each one appears as a removable chip above the input and travels with the prompt into the new conversation. Once the prompt is sent, the chip for a doc that's still in the project opens that doc. Images can come from anywhere; other files are sent as a path reference, so they have to live inside the project. Images must be PNG, JPEG, GIF, or WebP, and all attachments on one message are capped at 700 KB combined. That budget is tight for screenshots — a full-screen Retina capture is usually several megabytes and will be refused, so crop the capture or resize it first. Pick a **Terminal** CLI or an **External app** instead and the composer refuses the drop with the reason — those targets have no attachment channel — and if you attach first and switch afterwards, the send is blocked with the same explanation rather than silently dropping the file. Attachments aren't available in note windows yet, and whether an in-app agent can actually read an image is up to that agent: if it can't, OpenKnowledge shows a notification saying so once the agent's capabilities are known. The empty-state create composer on a fresh project takes attachments the same way — drop, paste, or the attach button while an **In app** agent is picked — and refuses them with the reason for **Terminal** and **External apps** targets.
The composer stays out of the way where it doesn't belong: it's hidden inside an AI editor's embedded view, while the [docked terminal](#terminal) is open (the terminal is its own AI entry point), and when no doc or folder is open (the empty state's create composer offers the same handoff, attachments included). It's also dismissible — an **Ask AI** badge in the status bar brings it back.
diff --git a/docs/content/features/skills/built-in-skills.mdx b/docs/content/features/skills/built-in-skills.mdx
index 6facf7d1a..372ff21d8 100644
--- a/docs/content/features/skills/built-in-skills.mdx
+++ b/docs/content/features/skills/built-in-skills.mdx
@@ -3,7 +3,7 @@ title: Skills OpenKnowledge ships
description: What each built-in skill does, and how to install or remove it.
---
-OpenKnowledge ships skills that teach an AI how to work with OpenKnowledge itself. None is required, and none installs without you choosing it.
+OpenKnowledge ships skills that teach an AI how to work with OpenKnowledge itself. Installing them into your editors is optional and requires your choice. In-app agent threads receive the project guidance automatically, as described below.
| Skill | Use it to | Where |
| --- | --- | --- |
@@ -27,4 +27,6 @@ Only the discovery skill is offered at first launch; the authoring one is offere
The `open-knowledge` skill installs into the project's own skill folders, which are not committed by default. A teammate who clones the repository installs it themselves.
+Agents started inside OpenKnowledge receive the project skill on the first non-command message of each new in-app agent session. This uses a [runtime copy under `.ok/local/`](../../reference/what-open-knowledge-writes.mdx) and leaves editor skill folders unchanged. Gemini receives the top-level skill text inline; its file tool cannot read the gitignored `references/` files. Other agents receive a path to read the skill and its references.
+
From the CLI: `ok init --skills discovery,write-skill` selects built-ins during setup, `ok init --no-skills` skips them.
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index f2f56014f..62e8f9d8d 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -123,6 +123,7 @@ The app runs a collaboration server for the open project. It writes runtime stat
| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored |
| `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored |
| `.ok/local/installed-skills.json` | Per-project skill-install markers (which editors each skill is projected into) | In-project, gitignored |
+| `.ok/local/agent-skill/open-knowledge/` | Runtime copy of the OpenKnowledge project skill (`SKILL.md` and `references/`), refreshed before in-app agent processes start. New in-app agent sessions receive this guidance automatically, even when the skill is not installed into an editor | In-project, gitignored with the `local/` ignore rule |
| `.ok/local/skill-move-retained.json` | Bookkeeping for a skill move between Project and Global scope that could not finish: which destination copy was kept, why, and what the source looked like at the time. Keyed by scope and skill name, one record each. A record clears when a later move of that skill completes, when the copy at the destination stops matching the one recorded, or when you delete that skill at that scope. No document content | In-project, gitignored |
| `.ok/local/terminal/claude-settings-{mcp,tools,mcp-tools}.json` | Windows-only Claude launch settings written when **Open in Claude** requests MCP or tool preapproval; one of three possible files, overwritten rather than appended on each launch that uses that combination. macOS and Linux pass the same settings inline | In-project, gitignored |
| `.ok/local/comments/` | [Comments](/docs/features/comments) left on documents, one JSON file each — the note, the passage it quotes, and whether it has been sent | In-project, gitignored |
@@ -133,7 +134,7 @@ Diagnostic logs and telemetry are **on by default but local-only** — credentia
On each launch and project open, the app also runs **repair sweeps**: it rewrites *existing* `open-knowledge` MCP entries (in the editor configs above) to the current canonical form, and removes any stale `open-knowledge-ui` entry left in `.claude/launch.json` by an older OK version. It **never adds** an MCP entry to an editor that doesn't already have one. Same `OK_RECLAIM_DISABLE=1` opt-out.
-**Skills are never installed by a sweep.** OpenKnowledge writes a skill only when you ask for one — the first-launch setup dialog, the Settings toggles, Skills Studio, or `ok init`. A launch does two housekeeping passes over skills and writes nothing new: it removes superseded pre-split `open-knowledge` copies OpenKnowledge itself left in your agent folders, and it removes a bundle you switched off that is still on disk.
+**Skills are never installed by a sweep.** OpenKnowledge writes a skill into editor folders only when you ask for one — the first-launch setup dialog, the Settings toggles, Skills Studio, or `ok init`. A launch does two housekeeping passes over installed editor skills and writes nothing new into those folders: it removes superseded pre-split `open-knowledge` copies OpenKnowledge itself left in your agent folders, and it removes a bundle you switched off that is still on disk.
### Home directory and credentials (`~/.ok/`)
@@ -247,6 +248,7 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a
| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored |
| `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored |
| `.ok/local/installed-skills.json` | Per-project skill-install markers (which editors each skill is projected into) | In-project, gitignored |
+| `.ok/local/agent-skill/open-knowledge/` | Runtime copy of the OpenKnowledge project skill (`SKILL.md` and `references/`), refreshed before in-app agent processes start. New in-app agent sessions receive this guidance automatically, even when the skill is not installed into an editor | In-project, gitignored with the `local/` ignore rule |
| `.ok/local/skill-move-retained.json` | Bookkeeping for a skill move between Project and Global scope that could not finish: which destination copy was kept, why, and what the source looked like at the time. Keyed by scope and skill name, one record each. A record clears when a later move of that skill completes, when the copy at the destination stops matching the one recorded, or when you delete that skill at that scope. No document content | In-project, gitignored |
| `.ok/local/comments/` | [Comments](/docs/features/comments) left on documents, one JSON file each — the note, the passage it quotes, and whether it has been sent | In-project, gitignored |
| `.git/ok/` — or `.git/worktrees/<name>/ok/` in a linked worktree, or the enclosing repo's `.git/ok-<slug>/` when your project is a subfolder of a larger repo | Shadow git repo holding per-writer work-in-progress refs (powers the timeline); always inside a git admin dir, never in your content tree. Its own `info/exclude` file, written when OpenKnowledge opens the repo, keeps machine-local runtime state — `.ok/local/` and `.ok/worktrees/`, plus the pre-`.ok/local/` equivalents that older projects still keep at the `.ok/` root (`.ok/principal.json`, `.ok/server.lock`, `.ok/cache/`, …) — and the `.tmp.<uuid>` files an in-flight atomic write leaves behind out of every saved version, the way `.ok/.gitignore` keeps them out of git | In-project, gitignored (inside `.git/`) |
@@ -260,7 +262,9 @@ On each boot, `ok start` also runs **repair sweeps**: it re-checks a few things
| Existing `open-knowledge` MCP entries | The same editor configs `ok init` writes — **both** user-level (`~/.claude.json`, `~/.cursor/mcp.json`, …) and project-level | Outside-project (editor config) **and** in-project |
| Stale `open-knowledge-ui` entry in `.claude/launch.json` | Project | Removed if present — OK no longer writes launch.json |
-Disable both with `OK_RECLAIM_DISABLE=1`. `ok start` does not touch skill files; `ok repair-skills` is the explicit command for that.
+Disable both repair sweeps with `OK_RECLAIM_DISABLE=1`. They leave installed editor skills alone; `ok repair-skills` is the explicit command for those. Starting an in-app agent thread creates or refreshes the runtime skill copy listed above.
+
+Projects initialized by an older CLI may lack the `local/` rule in `.ok/.gitignore`, which leaves these runtime files visible in `git status`. Add `local/` to that file or open the project in the desktop app, which updates it automatically. The runtime skill copy is always excluded from the knowledge base.
### `ok mcp`
diff --git a/knip.config.ts b/knip.config.ts
index 5b8951125..659eef71e 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -143,11 +143,15 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
- ignoreDependencies: ['yjs'],
+ ignoreDependencies: [
+ 'yjs',
+ ],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index 8a60e5826..a28cc2b18 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
index 6fcdc23f2..4fc2c11f9 100644
--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { updateYFragment } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 40b5cdfd6..9f2f6feb6 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index 93666af70..2a085742b 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 867598d34..878d5196b 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
index 0970ac12f..4ada3cf26 100644
--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
index b632185e1..cbe2b705f 100644
--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
@@ -1,3 +1,4 @@
+
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
index c530ce4ba..89bc9b4d9 100644
--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.ts
index d3767adc9..a78aeb0e4 100644
--- a/packages/app/tests/integration/undo-after-rollback.test.ts
+++ b/packages/app/tests/integration/undo-after-rollback.test.ts
@@ -1,3 +1,4 @@
+
import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.ts
index b076f955c..e7cc69c3f 100644
--- a/packages/app/tests/integration/undo-recycle-reset.test.ts
+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.ts
index 7935e35f8..9ddcd0730 100644
--- a/packages/app/tests/integration/undo-rederive-survival.test.ts
+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter } from '@inkeep/open-knowledge-core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8fb428b90..01ef76a9f 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index fc267cbea..fb0ba5a7c 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/server/src/acp/project-skill-staging.test.ts b/packages/server/src/acp/project-skill-staging.test.ts
new file mode 100644
index 000000000..dc404dd20
--- /dev/null
+++ b/packages/server/src/acp/project-skill-staging.test.ts
@@ -0,0 +1,193 @@
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import * as coreServer from '@inkeep/open-knowledge-core/server';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { resolveBundledSkillDir } from '../build-skill-zip.ts';
+import { getLogger } from '../logger.ts';
+import {
+ PROJECT_SKILL_ENTRY,
+ ProjectSkillSymlinkError,
+ projectSkillStageDir,
+ stagedBundleMatches,
+ stageProjectSkill,
+} from './project-skill-staging.ts';
+
+const log = getLogger('project-skill-staging-test');
+
+let dirs: string[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'project-skill-staging-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+function writeBundle(dir: string, files: Record<string, string>): string {
+ for (const [rel, body] of Object.entries(files)) {
+ const abs = join(dir, rel);
+ mkdirSync(join(abs, '..'), { recursive: true });
+ writeFileSync(abs, body);
+ }
+ return dir;
+}
+
+function listFiles(dir: string, base: string = dir): string[] {
+ const out: string[] = [];
+ for (const entry of readdirSync(dir).sort()) {
+ const abs = join(dir, entry);
+ if (statSync(abs).isDirectory()) out.push(...listFiles(abs, base));
+ else out.push(abs.slice(base.length + 1));
+ }
+ return out;
+}
+
+const SMALL_BUNDLE = {
+ [PROJECT_SKILL_ENTRY]: '# skill\n',
+ 'references/a.md': 'alpha\n',
+ 'references/deep/b.md': 'beta\n',
+};
+
+describe('stageProjectSkill', () => {
+ test('stages the bundle byte-for-byte under <localDir>/agent-skill/open-knowledge', async () => {
+ const localDir = tmp();
+ const source = writeBundle(tmp(), SMALL_BUNDLE);
+ const staged = await stageProjectSkill({ localDir, sourceDir: source, log });
+ expect(staged).toBe(projectSkillStageDir(localDir));
+ expect(listFiles(staged)).toEqual(listFiles(source));
+ for (const rel of listFiles(source)) {
+ expect(readFileSync(join(staged, rel))).toEqual(readFileSync(join(source, rel)));
+ }
+ expect(
+ readdirSync(join(localDir, 'agent-skill')).filter((n) => n.startsWith('.install-')),
+ ).toEqual([]);
+ });
+
+ test('restores a modified or truncated staged copy on the next spawn', async () => {
+ const localDir = tmp();
+ const source = writeBundle(tmp(), SMALL_BUNDLE);
+ const staged = await stageProjectSkill({ localDir, sourceDir: source, log });
+ writeFileSync(join(staged, PROJECT_SKILL_ENTRY), 'tampered\n');
+ rmSync(join(staged, 'references', 'deep'), { recursive: true, force: true });
+ expect(stagedBundleMatches(source, staged)).toBe(false);
+
+ await stageProjectSkill({ localDir, sourceDir: source, log });
+ expect(readFileSync(join(staged, PROJECT_SKILL_ENTRY), 'utf8')).toBe('# skill\n');
+ expect(readFileSync(join(staged, 'references', 'deep', 'b.md'), 'utf8')).toBe('beta\n');
+ expect(stagedBundleMatches(source, staged)).toBe(true);
+ });
+
+ test.each(['references/a.md', 'references/deep'])(
+ 'removes retired bundle entries on the next spawn: %s',
+ async (retiredPath) => {
+ const localDir = tmp();
+ const source = writeBundle(tmp(), SMALL_BUNDLE);
+ const staged = await stageProjectSkill({ localDir, sourceDir: source, log });
+ rmSync(join(source, retiredPath), { recursive: true });
+
+ expect(stagedBundleMatches(source, staged)).toBe(false);
+ await stageProjectSkill({ localDir, sourceDir: source, log });
+
+ expect(existsSync(join(staged, retiredPath))).toBe(false);
+ expect(listFiles(staged)).toEqual(listFiles(source));
+ expect(stagedBundleMatches(source, staged)).toBe(true);
+ },
+ );
+
+ test('leaves an identical staged copy untouched instead of replacing it', async () => {
+ const localDir = tmp();
+ const source = writeBundle(tmp(), SMALL_BUNDLE);
+ const staged = await stageProjectSkill({ localDir, sourceDir: source, log });
+ const before = statSync(join(staged, PROJECT_SKILL_ENTRY));
+ await new Promise((r) => setTimeout(r, 20));
+ await stageProjectSkill({ localDir, sourceDir: source, log });
+ const after = statSync(join(staged, PROJECT_SKILL_ENTRY));
+ expect(after.ino).toBe(before.ino);
+ expect(after.mtimeMs).toBe(before.mtimeMs);
+ });
+
+ test('concurrent spawns converge on one complete copy', async () => {
+ const localDir = tmp();
+ const source = writeBundle(tmp(), SMALL_BUNDLE);
+ const results = await Promise.all(
+ Array.from({ length: 6 }, () => stageProjectSkill({ localDir, sourceDir: source, log })),
+ );
+ expect(new Set(results).size).toBe(1);
+ expect(stagedBundleMatches(source, results[0] as string)).toBe(true);
+ expect(
+ readdirSync(join(localDir, 'agent-skill')).filter((n) => n.startsWith('.install-')),
+ ).toEqual([]);
+ });
+
+ test('refuses a symlinked destination or parent and writes nothing through it', async () => {
+ const localDir = tmp();
+ const source = writeBundle(tmp(), SMALL_BUNDLE);
+ const elsewhere = tmp();
+ mkdirSync(localDir, { recursive: true });
+ symlinkSync(elsewhere, join(localDir, 'agent-skill'), 'dir');
+ await expect(stageProjectSkill({ localDir, sourceDir: source, log })).rejects.toBeInstanceOf(
+ ProjectSkillSymlinkError,
+ );
+ expect(readdirSync(elsewhere)).toEqual([]);
+
+ const localDir2 = tmp();
+ mkdirSync(join(localDir2, 'agent-skill'), { recursive: true });
+ symlinkSync(elsewhere, projectSkillStageDir(localDir2), 'dir');
+ await expect(
+ stageProjectSkill({ localDir: localDir2, sourceDir: source, log }),
+ ).rejects.toBeInstanceOf(ProjectSkillSymlinkError);
+ expect(readdirSync(elsewhere)).toEqual([]);
+ });
+
+ test('refuses a symlink installed while waiting for the commit lock', async () => {
+ const localDir = tmp();
+ const source = writeBundle(tmp(), SMALL_BUNDLE);
+ const elsewhere = writeBundle(tmp(), SMALL_BUNDLE);
+ const stagedDir = projectSkillStageDir(localDir);
+ const lockPath = `${stagedDir}.install.lock`;
+ mkdirSync(join(localDir, 'agent-skill'));
+ writeFileSync(lockPath, 'held');
+ const lock = vi.spyOn(coreServer, 'withFileLock');
+ const staging = stageProjectSkill({ localDir, sourceDir: source, log });
+ const rejected = expect(staging).rejects.toBeInstanceOf(ProjectSkillSymlinkError);
+ try {
+ await vi.waitFor(() => expect(lock).toHaveBeenCalled());
+ symlinkSync(elsewhere, stagedDir, 'dir');
+ } finally {
+ rmSync(lockPath, { force: true });
+ }
+ await rejected;
+ expect(listFiles(elsewhere)).toEqual(Object.keys(SMALL_BUNDLE).sort());
+ expect(readFileSync(join(elsewhere, PROJECT_SKILL_ENTRY), 'utf8')).toBe('# skill\n');
+ });
+
+ test('rejects a missing source without creating the staged folder', async () => {
+ const localDir = tmp();
+ await expect(
+ stageProjectSkill({ localDir, sourceDir: join(tmp(), 'nope'), log }),
+ ).rejects.toThrow();
+ expect(existsSync(projectSkillStageDir(localDir))).toBe(false);
+ });
+
+ test('stages the shipped project bundle with SKILL.md at the root', async () => {
+ const localDir = tmp();
+ const source = resolveBundledSkillDir('project', { checkDesktop: false });
+ const staged = await stageProjectSkill({ localDir, sourceDir: source, log });
+ expect(existsSync(join(staged, PROJECT_SKILL_ENTRY))).toBe(true);
+ expect(listFiles(staged)).toEqual(listFiles(source));
+ });
+});
diff --git a/packages/server/src/acp/project-skill-staging.ts b/packages/server/src/acp/project-skill-staging.ts
new file mode 100644
index 000000000..d43e128ef
--- /dev/null
+++ b/packages/server/src/acp/project-skill-staging.ts
@@ -0,0 +1,113 @@
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { lstat } from 'node:fs/promises';
+import { dirname, join } from 'node:path';
+import { copyDirSync } from '../copy-dir.ts';
+import type { PinoLogger } from '../logger.ts';
+import { stagedInstall } from './staged-install.ts';
+
+const PROJECT_SKILL_STAGE_PARENT = 'agent-skill';
+const PROJECT_SKILL_STAGE_NAME = 'open-knowledge';
+export const PROJECT_SKILL_ENTRY = 'SKILL.md';
+
+const MISSING_OR_WRONG_KIND = new Set(['ENOENT', 'ENOTDIR', 'EISDIR']);
+
+export function projectSkillStageDir(localDir: string): string {
+ return join(localDir, PROJECT_SKILL_STAGE_PARENT, PROJECT_SKILL_STAGE_NAME);
+}
+
+function fileBytesEqual(src: string, dest: string): boolean {
+ let destBytes: Buffer;
+ try {
+ destBytes = readFileSync(dest);
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== undefined && MISSING_OR_WRONG_KIND.has(code)) return false;
+ throw err;
+ }
+ return readFileSync(src).equals(destBytes);
+}
+
+export function stagedBundleMatches(sourceDir: string, stagedDir: string): boolean {
+ const sourceEntries = readdirSync(sourceDir);
+ let stagedEntries: Set<string>;
+ try {
+ stagedEntries = new Set(readdirSync(stagedDir));
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== undefined && MISSING_OR_WRONG_KIND.has(code)) return false;
+ throw err;
+ }
+ if (sourceEntries.length !== stagedEntries.size) return false;
+ for (const entry of sourceEntries) {
+ if (!stagedEntries.has(entry)) return false;
+ const src = join(sourceDir, entry);
+ const dest = join(stagedDir, entry);
+ if (statSync(src).isDirectory()) {
+ let destIsDir: boolean;
+ try {
+ destIsDir = statSync(dest).isDirectory();
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== undefined && MISSING_OR_WRONG_KIND.has(code)) return false;
+ throw err;
+ }
+ if (!destIsDir || !stagedBundleMatches(src, dest)) return false;
+ } else if (!fileBytesEqual(src, dest)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+export class ProjectSkillSymlinkError extends Error {
+ readonly path: string;
+ constructor(path: string) {
+ super(`refusing to stage the project skill through a symlink at ${path}`);
+ this.name = 'ProjectSkillSymlinkError';
+ this.path = path;
+ }
+}
+
+async function assertNotSymlink(path: string): Promise<void> {
+ let st: Awaited<ReturnType<typeof lstat>>;
+ try {
+ st = await lstat(path);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw err;
+ }
+ if (st.isSymbolicLink()) throw new ProjectSkillSymlinkError(path);
+}
+
+export interface StageProjectSkillOptions {
+ localDir: string;
+ sourceDir: string;
+ log: PinoLogger;
+ logContext?: Record<string, unknown>;
+}
+
+export async function stageProjectSkill(opts: StageProjectSkillOptions): Promise<string> {
+ const stageDir = projectSkillStageDir(opts.localDir);
+ const parentDir = dirname(stageDir);
+ const guardDestination = async (): Promise<void> => {
+ await assertNotSymlink(parentDir);
+ await assertNotSymlink(stageDir);
+ };
+ return stagedInstall<string>({
+ versionDir: stageDir,
+ stagingLabel: PROJECT_SKILL_STAGE_NAME,
+ findInstalled: async () => {
+ await guardDestination();
+ return stagedBundleMatches(opts.sourceDir, stageDir) ? stageDir : null;
+ },
+ prepare: async (stagingDir) => {
+ copyDirSync(opts.sourceDir, stagingDir);
+ return stagingDir;
+ },
+ log: opts.log,
+ logPrefix: '[acp-threads]',
+ logContext: opts.logContext ?? {},
+ installedMessage: 'project skill staged',
+ missingAfterCommitMessage: 'project skill missing after the staging commit',
+ });
+}
diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.ts
index 7e54f12bc..d3e31d95c 100644
--- a/packages/server/src/acp/thread-manager.integration.test.ts
+++ b/packages/server/src/acp/thread-manager.integration.test.ts
@@ -16,10 +16,12 @@ import codexFixture from '../../../../test-support/fixtures/codex-legacy-warning
};
import type { AgentPresenceBroadcaster } from '../agent-presence.ts';
import type { AgentSessionManager } from '../agent-sessions.ts';
+import { resolveBundledSkillDir } from '../build-skill-zip.ts';
import { getLogger, type PinoLogger } from '../logger.ts';
import { isValidLockPid } from '../process-alive.ts';
import { RUNTIME_VERSION } from '../version-constants.ts';
import { withLocalAcquisitionRegistry } from './acquisition-contract.test-helper.ts';
+import { isWithin } from './archive.ts';
import {
installNodeFixture,
npmCli,
@@ -30,11 +32,14 @@ import {
writeRecordingNpm,
} from './package-acquisition.test-helper.ts';
import { AcpPermissionStore } from './permissions.ts';
+import * as projectSkillStaging from './project-skill-staging.ts';
+import { PROJECT_SKILL_ENTRY, projectSkillStageDir } from './project-skill-staging.ts';
import { AcpRegistry } from './registry.ts';
import {
ACP_ENVIRONMENT_NOTE,
AcpThreadManager,
type AcpThreadManagerOptions,
+ buildEnvironmentNote,
MAX_QUEUED_PROMPTS,
} from './thread-manager.ts';
@@ -63,6 +68,7 @@ function tmp(): string {
afterEach(async () => {
await Promise.allSettled(managers.map((m) => m.destroy()));
managers = [];
+ vi.restoreAllMocks();
for (const d of dirs) rmSync(d, { recursive: true, force: true });
dirs = [];
});
@@ -84,6 +90,7 @@ function makeManager(
agentPresenceBroadcaster?: AgentPresenceBroadcaster;
sessionManager?: AgentSessionManager;
log?: PinoLogger;
+ projectSkillSourceDir?: string | null;
},
): AcpThreadManager {
const manager = new AcpThreadManager({
@@ -137,6 +144,14 @@ function internals(manager: AcpThreadManager): {
};
}
+function stagedSkillPath(localDir: string): string {
+ return join(projectSkillStageDir(localDir), PROJECT_SKILL_ENTRY);
+}
+
+function stagedSkillNote(localDir: string): string {
+ return buildEnvironmentNote({ skillPath: stagedSkillPath(localDir) });
+}
+
describe('package acquisition failure projection', () => {
test.each(['npx', 'uvx'] as const)(
'%s start and retry retain actionable native refusal and clean up',
@@ -979,7 +994,7 @@ process.stdin.on('data', (chunk) => {
await waitFor(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000);
manager.sendPrompt(info.threadId, 'first hello');
await waitFor(() => receivedTexts().length === 3, 15_000);
- expect(receivedTexts()[2]).toBe(`received:${ACP_ENVIRONMENT_NOTE}\n\nfirst hello`);
+ expect(receivedTexts()[2]).toBe(`received:${stagedSkillNote(localDir)}\n\nfirst hello`);
const userMessages = events
.map((e) => e.event)
.filter((e) => e.kind === 'user_message')
@@ -1173,7 +1188,8 @@ describe('AcpThreadManager persistence + resume', () => {
}
};
const kinds = (events: Collected): string[] => events.map((e) => e.event.kind);
- const notedEcho = (text: string): string => `echo:${ACP_ENVIRONMENT_NOTE}\n\n${text}`;
+ const notedEcho = (localDir: string, text: string): string =>
+ `echo:${stagedSkillNote(localDir)}\n\n${text}`;
const agentChunks = (events: Collected): string[] =>
events
.map((e) => e.event)
@@ -1271,7 +1287,7 @@ describe('AcpThreadManager persistence + resume', () => {
expect(replayed.length).toBeGreaterThanOrEqual(liveEvents.length);
expect(replayed.map((e) => e.seq)).toEqual(replayed.map((_, i) => i));
expect(kinds(replayed)).toContain('user_message');
- expect(agentChunks(replayed)).toContain(notedEcho('hello there'));
+ expect(agentChunks(replayed)).toContain(notedEcho(localDir, 'hello there'));
}, 45_000);
test('closing a never-prompted thread discards it instead of archiving', async () => {
@@ -1581,7 +1597,10 @@ describe('AcpThreadManager persistence + resume', () => {
.filter((e): e is Extract<ThreadEvent, { kind: 'user_message' }> => e.kind === 'user_message')
.map((e) => e.content);
expect(userMessages).toEqual(['first message', 'second message']);
- expect(agentChunks(replayed)).toEqual([notedEcho('first message'), 'echo:second message']);
+ expect(agentChunks(replayed)).toEqual([
+ notedEcho(localDir, 'first message'),
+ 'echo:second message',
+ ]);
expect(manager.getInfo(threadId)?.availableCommands).toBeNull();
await manager.closeThread(threadId);
@@ -1610,7 +1629,10 @@ describe('AcpThreadManager persistence + resume', () => {
const replayed: Collected = [];
await manager.subscribe(threadId, 0, collector(replayed));
- expect(agentChunks(replayed)).toEqual([notedEcho('first message'), 'echo:second message']);
+ expect(agentChunks(replayed)).toEqual([
+ notedEcho(localDir, 'first message'),
+ 'echo:second message',
+ ]);
expect(agentChunks(replayed)).not.toContain('old-user');
expect(agentChunks(replayed)).not.toContain('old-agent');
@@ -1638,7 +1660,7 @@ describe('AcpThreadManager persistence + resume', () => {
expect(manager.getInfo(threadId)?.archived).toBe(true);
const replayed: Collected = [];
await manager.subscribe(threadId, 0, collector(replayed));
- expect(agentChunks(replayed)).toContain(notedEcho('first message'));
+ expect(agentChunks(replayed)).toContain(notedEcho(localDir, 'first message'));
}, 45_000);
test('an agent that drops its resume capability retires the offer instead of repeating it', async () => {
@@ -1708,7 +1730,7 @@ describe('AcpThreadManager persistence + resume', () => {
);
const replayed: Collected = [];
await manager2.subscribe(threadId, 0, collector(replayed));
- expect(agentChunks(replayed)).toContain(notedEcho('survives shutdown'));
+ expect(agentChunks(replayed)).toContain(notedEcho(localDir, 'survives shutdown'));
await manager2.closeThread(threadId);
}, 45_000);
});
@@ -5495,6 +5517,7 @@ function registryManagerFor(
contentDir: string,
localDir: string,
binDir: string,
+ extra?: Parameters<typeof makeManager>[2],
): AcpThreadManager {
const manifest = {
id: agentId,
@@ -5511,6 +5534,7 @@ function registryManagerFor(
status: 200,
})) as unknown as typeof fetch,
}),
+ ...extra,
});
}
@@ -5730,6 +5754,263 @@ describe.skipIf(process.platform === 'win32')('a typed session notice mid-turn',
}, 60_000);
});
+describe('AcpThreadManager project skill delivery', () => {
+ const BLOCKS_AGENT = `
+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');
+const notify = (update) =>
+ write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 's1', update } });
+let buffer = '';
+process.stdin.setEncoding('utf8');
+process.stdin.on('data', (chunk) => {
+ buffer += chunk;
+ let idx = buffer.indexOf('\\n');
+ while (idx !== -1) {
+ const line = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 1);
+ idx = buffer.indexOf('\\n');
+ if (line.trim() === '') continue;
+ const msg = JSON.parse(line);
+ const reply = (result) =>
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id, result }) + '\\n');
+ if (msg.method === 'initialize') {
+ reply({
+ protocolVersion: 1,
+ agentCapabilities: {
+ promptCapabilities: { embeddedContext: process.env.FAKE_EMBEDDED === '1' },
+ },
+ });
+ } else if (msg.method === 'session/new') {
+ reply({ sessionId: 's1' });
+ } else if (msg.method === 'session/prompt') {
+ notify({
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'text', text: 'blocks:' + JSON.stringify(msg.params.prompt) },
+ });
+ reply({ stopReason: 'end_turn' });
+ } else if (msg.id !== undefined) {
+ reply({});
+ }
+ }
+});
+`;
+
+ type EchoedBlock = { type: string; text?: string; resource?: Record<string, string> };
+
+ function writeBlocksAgent(localDir: string, id: string, embeddedContext: boolean): void {
+ const agentPath = join(localDir, `${id}-blocks-agent.mjs`);
+ writeFileSync(agentPath, BLOCKS_AGENT);
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([
+ {
+ id,
+ name: `Fake ${id}`,
+ command: 'node',
+ args: [agentPath],
+ env: { FAKE_EMBEDDED: embeddedContext ? '1' : '0' },
+ },
+ ]),
+ );
+ }
+
+ async function firstPromptBlocks(
+ manager: AcpThreadManager,
+ agentId: string,
+ prompt: string,
+ source: 'custom' | 'registry' = 'custom',
+ ): Promise<EchoedBlock[]> {
+ const info = await manager.createThread({ agent: { source, id: agentId } });
+ const events: ThreadEvent[] = [];
+ await manager.subscribe(info.threadId, 0, (frame: ThreadServerFrame) => {
+ if (frame.op === 'event') events.push(frame.event);
+ if (frame.op === 'events') events.push(...frame.events);
+ });
+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');
+ manager.sendPrompt(info.threadId, prompt);
+ const echoed = (): string | undefined =>
+ events
+ .filter((e) => e.kind === 'session_update')
+ .map((e) => (e.update as { content?: { text?: string } }).content?.text ?? '')
+ .find((text) => text.startsWith('blocks:'));
+ await waitUntil(() => echoed() !== undefined, 15_000, 'echoed prompt blocks');
+ return JSON.parse((echoed() as string).slice('blocks:'.length)) as EchoedBlock[];
+ }
+
+ function geminiRegistryManager(
+ localDir: string,
+ embeddedContext: boolean,
+ extra?: Parameters<typeof makeManager>[2],
+ ): AcpThreadManager {
+ const binDir = tmp();
+ writeRegistryAgentShims(binDir, []);
+ writeFileSync(
+ join(binDir, 'agent.mjs'),
+ `process.env.FAKE_EMBEDDED = ${JSON.stringify(embeddedContext ? '1' : '0')};\n${BLOCKS_AGENT}`,
+ );
+ return registryManagerFor('gemini', tmp(), localDir, binDir, extra);
+ }
+
+ const bundledSkillText = (): string =>
+ readFileSync(
+ join(resolveBundledSkillDir('project', { checkDesktop: false }), PROJECT_SKILL_ENTRY),
+ 'utf8',
+ );
+
+ test('stages the shipped bundle under localDir and points the first prompt at it', async () => {
+ const localDir = tmp();
+ writeBlocksAgent(localDir, 'pointer-agent', false);
+ const manager = makeManager(tmp(), localDir);
+
+ const blocks = await firstPromptBlocks(manager, 'pointer-agent', 'hello');
+ expect(blocks).toEqual([{ type: 'text', text: `${stagedSkillNote(localDir)}\n\nhello` }]);
+ expect(readFileSync(stagedSkillPath(localDir), 'utf8')).toBe(bundledSkillText());
+ expect(existsSync(join(projectSkillStageDir(localDir), 'references'))).toBe(true);
+ }, 30_000);
+
+ test('a custom agent named gemini receives the ordinary path pointer', async () => {
+ const localDir = tmp();
+ writeBlocksAgent(localDir, 'gemini', true);
+ const manager = makeManager(tmp(), localDir);
+
+ const blocks = await firstPromptBlocks(manager, 'gemini', 'hello');
+ expect(blocks).toEqual([{ type: 'text', text: `${stagedSkillNote(localDir)}\n\nhello` }]);
+ }, 30_000);
+
+ test('a content subfolder still receives the pointer above its cwd', async () => {
+ const projectDir = tmp();
+ const contentDir = join(projectDir, 'docs');
+ const localDir = join(projectDir, '.ok', 'local');
+ mkdirSync(contentDir, { recursive: true });
+ mkdirSync(localDir, { recursive: true });
+ writeBlocksAgent(localDir, 'subfolder-agent', false);
+ const lines: { obj: Record<string, unknown>; msg: string }[] = [];
+ const manager = makeManager(contentDir, localDir, { log: capturingLog(lines) });
+
+ const blocks = await firstPromptBlocks(manager, 'subfolder-agent', 'hello');
+ expect(isWithin(contentDir, stagedSkillPath(localDir))).toBe(false);
+ expect(blocks).toEqual([{ type: 'text', text: `${stagedSkillNote(localDir)}\n\nhello` }]);
+ expect(lines.some((line) => line.msg.includes('skill staged above agent cwd'))).toBe(true);
+ }, 30_000);
+
+ test('concurrent connects share staging and a later connect still repairs changes', async () => {
+ const localDir = tmp();
+ writeBlocksAgent(localDir, 'concurrent-agent', false);
+ const lines: { obj: Record<string, unknown>; msg: string }[] = [];
+ const barrier = Promise.withResolvers<void>();
+ let coordinate = false;
+ let arrivals = 0;
+ const manager = makeManager(tmp(), localDir, {
+ log: capturingLog(lines),
+ resolveLoginShellPath: async () => {
+ if (coordinate) {
+ arrivals += 1;
+ if (arrivals === 2) barrier.resolve();
+ await barrier.promise;
+ }
+ return null;
+ },
+ });
+ await manager.init();
+ coordinate = true;
+ const stage = vi.spyOn(projectSkillStaging, 'stageProjectSkill');
+ await Promise.all([
+ firstPromptBlocks(manager, 'concurrent-agent', 'first'),
+ firstPromptBlocks(manager, 'concurrent-agent', 'second'),
+ ]);
+ expect(stage).toHaveBeenCalledTimes(1);
+ const staged = lines.find((line) => line.msg.includes('project skill staged'));
+ expect(staged?.obj).toMatchObject({ localDir });
+ expect(staged?.obj).not.toHaveProperty('threadId');
+ expect(staged?.obj).not.toHaveProperty('agentId');
+
+ coordinate = false;
+ writeFileSync(stagedSkillPath(localDir), 'modified');
+ await firstPromptBlocks(manager, 'concurrent-agent', 'third');
+ expect(stage).toHaveBeenCalledTimes(2);
+ expect(readFileSync(stagedSkillPath(localDir), 'utf8')).toBe(bundledSkillText());
+ }, 30_000);
+
+ test.skipIf(process.platform === 'win32')(
+ 'registry gemini receives no pointer when the inline skill cannot be read',
+ async () => {
+ const localDir = tmp();
+ const sourceDir = tmp();
+ mkdirSync(join(sourceDir, PROJECT_SKILL_ENTRY));
+ const lines: { obj: Record<string, unknown>; msg: string }[] = [];
+ const manager = geminiRegistryManager(localDir, true, {
+ projectSkillSourceDir: sourceDir,
+ log: capturingLog(lines),
+ });
+
+ const blocks = await firstPromptBlocks(manager, 'gemini', 'hello', 'registry');
+ expect(blocks).toEqual([{ type: 'text', text: `${ACP_ENVIRONMENT_NOTE}\n\nhello` }]);
+ const failure = lines.find((line) => line.msg.includes('skill inline read failed'));
+ expect(failure?.obj.err).toMatchObject({ code: 'EISDIR' });
+ },
+ 30_000,
+ );
+
+ test('sends the plain note when staging fails, and never blocks the spawn', async () => {
+ const localDir = tmp();
+ writeBlocksAgent(localDir, 'degrade-agent', false);
+ const manager = makeManager(tmp(), localDir, {
+ projectSkillSourceDir: join(localDir, 'no-such-bundle'),
+ });
+
+ const blocks = await firstPromptBlocks(manager, 'degrade-agent', 'hello');
+ expect(blocks).toEqual([{ type: 'text', text: `${ACP_ENVIRONMENT_NOTE}\n\nhello` }]);
+ expect(existsSync(projectSkillStageDir(localDir))).toBe(false);
+ }, 30_000);
+
+ test('sends the plain note when staging is switched off', async () => {
+ const localDir = tmp();
+ writeBlocksAgent(localDir, 'off-agent', false);
+ const manager = makeManager(tmp(), localDir, { projectSkillSourceDir: null });
+
+ const blocks = await firstPromptBlocks(manager, 'off-agent', 'hello');
+ expect(blocks).toEqual([{ type: 'text', text: `${ACP_ENVIRONMENT_NOTE}\n\nhello` }]);
+ expect(existsSync(projectSkillStageDir(localDir))).toBe(false);
+ }, 30_000);
+
+ test.skipIf(process.platform === 'win32')(
+ 'registry gemini gets the skill body inline as an embedded resource',
+ async () => {
+ const localDir = tmp();
+ const manager = geminiRegistryManager(localDir, true);
+
+ const blocks = await firstPromptBlocks(manager, 'gemini', 'hello', 'registry');
+ const skillPath = stagedSkillPath(localDir);
+ expect(blocks).toEqual([
+ { type: 'text', text: `${buildEnvironmentNote({ skillPath, inline: true })}\n\nhello` },
+ {
+ type: 'resource',
+ resource: {
+ uri: pathToFileURL(skillPath).href,
+ mimeType: 'text/markdown',
+ text: bundledSkillText(),
+ },
+ },
+ ]);
+ },
+ 30_000,
+ );
+
+ test.skipIf(process.platform === 'win32')(
+ 'registry gemini without embeddedContext still gets the body, as a text block',
+ async () => {
+ const localDir = tmp();
+ const manager = geminiRegistryManager(localDir, false);
+
+ const blocks = await firstPromptBlocks(manager, 'gemini', 'hello', 'registry');
+ expect(blocks).toHaveLength(2);
+ expect(blocks[0]?.type).toBe('text');
+ expect(blocks[1]?.type).toBe('text');
+ expect(blocks[1]?.text).toContain(bundledSkillText());
+ },
+ 30_000,
+ );
+});
+
describe('status frames for an open that installs nothing', () => {
test('a custom agent start never reports installing', async () => {
const localDir = tmp();
diff --git a/packages/server/src/acp/thread-manager.test.ts b/packages/server/src/acp/thread-manager.test.ts
new file mode 100644
index 000000000..4a8e28ad2
--- /dev/null
+++ b/packages/server/src/acp/thread-manager.test.ts
@@ -0,0 +1,47 @@
+import { resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { PromptCapabilities } from '@agentclientprotocol/sdk';
+import { describe, expect, test } from 'vitest';
+import { deliversSkillInline, inlineSkillBlock } from './thread-manager.ts';
+
+describe('project skill delivery policy', () => {
+ test.each([
+ ['registry', 'gemini', true],
+ ['custom', 'gemini', false],
+ ['registry', 'codex-acp', false],
+ ['custom', 'codex-acp', false],
+ ['registry', 'other-agent', false],
+ ] as const)('%s agent %s uses inline delivery: %s', (source, id, expected) => {
+ expect(deliversSkillInline({ source, id })).toBe(expected);
+ });
+});
+
+describe('inline project skill blocks', () => {
+ const skillPath = resolve('project with spaces', '.ok', 'local', 'skill #1', 'SKILL.md');
+ const text = '# OpenKnowledge\n\nUse the project tools before editing markdown.\n';
+
+ test('an embedded resource preserves the skill text and native file path', () => {
+ const block = inlineSkillBlock(skillPath, text, { embeddedContext: true });
+ expect(block.type).toBe('resource');
+ if (block.type !== 'resource') throw new Error('expected an embedded resource');
+ expect(block.resource.mimeType).toBe('text/markdown');
+ expect(block.resource).toHaveProperty('text', text);
+ expect(fileURLToPath(block.resource.uri)).toBe(skillPath);
+ expect(block.resource.uri).toContain('%20');
+ expect(block.resource.uri).toContain('%23');
+ });
+
+ test.each<PromptCapabilities | null | undefined>([
+ undefined,
+ null,
+ {},
+ { embeddedContext: false },
+ ])('without embedded resource support (%j), delivers readable text', (capabilities) => {
+ const block = inlineSkillBlock(skillPath, text, capabilities);
+ expect(block.type).toBe('text');
+ if (block.type !== 'text') throw new Error('expected a text block');
+ expect(block.text).toContain(text);
+ expect(block.text).toContain('SKILL.md');
+ expect(block.text).not.toContain(skillPath);
+ });
+});
diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.ts
index 4f35c6f60..383cd673d 100644
--- a/packages/server/src/acp/thread-manager.ts
+++ b/packages/server/src/acp/thread-manager.ts
@@ -8,15 +8,18 @@ import type { ChildProcess } from 'node:child_process';
import { readFile, realpath } from 'node:fs/promises';
import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
import { Readable, Writable } from 'node:stream';
+import { pathToFileURL } from 'node:url';
import {
client as acpClient,
methods as acpMethods,
type ClientConnection,
+ type ContentBlock,
type InitializeResponse,
type McpServer,
ndJsonStream,
type PermissionOption,
PROTOCOL_VERSION,
+ type PromptCapabilities,
RequestError,
type RequestPermissionResponse,
type SessionConfigOption,
@@ -61,6 +64,7 @@ import {
applyAgentMarkdownWrite,
snapshotBlocks,
} from '../agent-sessions.ts';
+import { resolveBundledSkillDir } from '../build-skill-zip.ts';
import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';
import {
CONCURRENT_OVERWRITE_REFUSED_DETAIL,
@@ -73,6 +77,7 @@ import { resolveOnPath } from '../git-preflight.ts';
import type { PinoLogger } from '../logger.ts';
import { MCP_HOSTED_AGENT_HEADER } from '../mcp/agent-identity.ts';
import { RUNTIME_VERSION } from '../version-constants.ts';
+import { isWithin } from './archive.ts';
import { buildPromptBlocks } from './attachment-blocks.ts';
import {
ACQUISITION_DETAIL_MAX_CHARS,
@@ -128,6 +133,7 @@ import {
launchContextMechanism,
} from './model-discovery/launch-context.ts';
import type { AcpPermissionStore } from './permissions.ts';
+import { PROJECT_SKILL_ENTRY, stageProjectSkill } from './project-skill-staging.ts';
import {
ACP_AGENT_EDITOR_IDS,
type AcpRegistry,
@@ -174,6 +180,56 @@ export const ACP_ENVIRONMENT_NOTE =
'exist here; never recommend them. The only slash commands available to the ' +
'user are the ones you advertise over ACP.';
+export interface ProjectSkillNoteInput {
+ skillPath: string;
+ inline?: boolean;
+}
+
+export function buildEnvironmentNote(skill: ProjectSkillNoteInput | null): string {
+ if (skill === null) return ACP_ENVIRONMENT_NOTE;
+ const pointer =
+ skill.inline === true
+ ? 'This project uses OpenKnowledge. Its agent skill (SKILL.md) is attached to this message. ' +
+ 'Follow it before editing any markdown here; it overrides generic markdown habits. ' +
+ 'If you already have the `open-knowledge` skill loaded, skip it.'
+ : `This project uses OpenKnowledge. Its agent skill is at \`${skill.skillPath}\`. ` +
+ 'Read it before editing any markdown here; it overrides generic markdown habits, ' +
+ 'and you may read its `references/` files by path when it points to them. ' +
+ 'If you already have the `open-knowledge` skill loaded, skip the read.';
+ return `${ACP_ENVIRONMENT_NOTE}\n\n${pointer}`;
+}
+
+const INLINE_SKILL_AGENT_IDS: ReadonlySet<string> = new Set(['gemini']);
+
+export function deliversSkillInline(agentRef: {
+ source: 'registry' | 'custom';
+ id: string;
+}): boolean {
+ return agentRef.source === 'registry' && INLINE_SKILL_AGENT_IDS.has(agentRef.id);
+}
+
+interface StagedProjectSkill {
+ skillPath: string;
+ inlineText: string | null;
+}
+
+export function inlineSkillBlock(
+ skillPath: string,
+ text: string,
+ capabilities: PromptCapabilities | null | undefined,
+): ContentBlock {
+ if (capabilities?.embeddedContext !== true) {
+ return {
+ type: 'text',
+ text: `\n\n--- OpenKnowledge skill: ${PROJECT_SKILL_ENTRY} ---\n${text}\n--- End skill ---`,
+ };
+ }
+ return {
+ type: 'resource',
+ resource: { uri: pathToFileURL(skillPath).href, text, mimeType: 'text/markdown' },
+ };
+}
+
export class ThreadOpError extends Error {
readonly code:
| 'unknown-thread'
@@ -274,6 +330,7 @@ interface ThreadRecord {
hadUserMessage: boolean;
titleHint?: string;
envNotePending: boolean;
+ projectSkill: StagedProjectSkill | null;
}
export interface HarnessManagedMcpEntryHit {
@@ -341,6 +398,7 @@ export interface AcpThreadManagerOptions {
fetchImpl?: typeof fetch;
};
resolveLoginShellPath?: () => Promise<string | null>;
+ projectSkillSourceDir?: string | null;
log: PinoLogger;
maxThreads?: number;
idleReapMs?: number;
@@ -395,6 +453,7 @@ export class AcpThreadManager {
private readonly persistence: ThreadPersistenceStore;
private readonly resolveLoginShellPath: () => Promise<string | null>;
private readonly healthyInterpreters = new Set<string>();
+ private projectSkillStaging: Promise<string> | null = null;
private destroyed = false;
private initialized = false;
@@ -603,6 +662,7 @@ export class AcpThreadManager {
hadUserMessage: false,
titleHint: params.titleHint,
envNotePending: false,
+ projectSkill: null,
};
this.threads.set(threadId, record);
this.emitStatus(record, 'spawning');
@@ -652,6 +712,44 @@ export class AcpThreadManager {
};
}
+ private async stageProjectSkillFor(record: ThreadRecord): Promise<StagedProjectSkill | null> {
+ const source = this.opts.projectSkillSourceDir;
+ if (source === null) return null;
+ const logContext = { threadId: record.info.threadId, agentId: record.info.agent.id };
+ let dir: string;
+ try {
+ this.projectSkillStaging ??= stageProjectSkill({
+ localDir: this.opts.localDir,
+ sourceDir: source ?? resolveBundledSkillDir('project', { checkDesktop: false }),
+ log: this.opts.log,
+ logContext: { localDir: this.opts.localDir },
+ }).finally(() => {
+ this.projectSkillStaging = null;
+ });
+ dir = await this.projectSkillStaging;
+ } catch (err) {
+ this.opts.log.warn({ err, ...logContext }, '[acp-threads] skill staging failed');
+ return null;
+ }
+ if (!isWithin(record.cwd, dir)) {
+ this.opts.log.info(
+ { ...logContext, cwd: record.cwd, skillDir: dir },
+ '[acp-threads] skill staged above agent cwd',
+ );
+ }
+ const skillPath = join(dir, PROJECT_SKILL_ENTRY);
+ if (!deliversSkillInline(record.agentRef)) return { skillPath, inlineText: null };
+ try {
+ return { skillPath, inlineText: await readFile(skillPath, 'utf8') };
+ } catch (err) {
+ this.opts.log.warn(
+ { err, ...logContext, skillPath },
+ '[acp-threads] skill inline read failed; skipping skill delivery',
+ );
+ return null;
+ }
+ }
+
private async connectAgent(
record: ThreadRecord,
custom: CustomAgentEntry | null,
@@ -693,6 +791,9 @@ export class AcpThreadManager {
const loginShellPath = await this.resolveLoginShellPath().catch(() => null);
if (record.closed) return null;
+ record.projectSkill = await this.stageProjectSkillFor(record);
+ if (record.closed) return null;
+
const terminals = new AcpTerminalSet({
defaultCwd: record.cwd,
emit: (event) => this.appendEvent(record, event),
@@ -817,12 +918,42 @@ export class AcpThreadManager {
.onRequest(acpMethods.client.session.requestPermission, (ctx) =>
this.handlePermissionRequest(record, ctx.params.toolCall, ctx.params.options),
)
- .onRequest(acpMethods.client.fs.readTextFile, (ctx) =>
- this.handleFsRead(ctx.params.path, ctx.params.line ?? null, ctx.params.limit ?? null),
- )
+ .onRequest(acpMethods.client.fs.readTextFile, async (ctx) => {
+ try {
+ return await this.handleFsRead(
+ ctx.params.path,
+ ctx.params.line ?? null,
+ ctx.params.limit ?? null,
+ );
+ } catch (err) {
+ this.opts.log.warn(
+ {
+ err,
+ threadId: record.info.threadId,
+ agentId: record.info.agent.id,
+ path: ctx.params.path,
+ },
+ '[acp-threads] agent file read failed',
+ );
+ throw err;
+ }
+ })
.onRequest(acpMethods.client.fs.writeTextFile, async (ctx) => {
- await this.handleFsWrite(record, ctx.params.path, ctx.params.content);
- return {};
+ try {
+ await this.handleFsWrite(record, ctx.params.path, ctx.params.content);
+ return {};
+ } catch (err) {
+ this.opts.log.warn(
+ {
+ err,
+ threadId: record.info.threadId,
+ agentId: record.info.agent.id,
+ path: ctx.params.path,
+ },
+ '[acp-threads] agent file write failed',
+ );
+ throw err;
+ }
})
.onRequest(acpMethods.client.terminal.create, (ctx) => {
record.info.lastActivityAt = Date.now();
@@ -2314,9 +2445,33 @@ export class AcpThreadManager {
this.echoUserMessage(t, content, attachments);
}
let wireText = content;
+ let skillBlock: ContentBlock | null = null;
if (t.envNotePending && !content.startsWith('/')) {
t.envNotePending = false;
- wireText = `${ACP_ENVIRONMENT_NOTE}\n\n${content}`;
+ const skill = t.projectSkill;
+ const inline = skill !== null && skill.inlineText !== null;
+ const note = buildEnvironmentNote(
+ skill === null ? null : { skillPath: skill.skillPath, inline },
+ );
+ wireText = `${note}\n\n${content}`;
+ if (skill !== null) {
+ if (skill.inlineText !== null) {
+ skillBlock = inlineSkillBlock(
+ skill.skillPath,
+ skill.inlineText,
+ t.info.promptCapabilities,
+ );
+ }
+ this.opts.log.info(
+ {
+ threadId: t.info.threadId,
+ agentId: t.info.agent.id,
+ skillPath: skill.skillPath,
+ delivery: inline ? 'inline' : 'path',
+ },
+ '[acp-threads] skill pointer sent',
+ );
+ }
}
t.turnActive = true;
t.cancelRequested = false;
@@ -2360,7 +2515,7 @@ export class AcpThreadManager {
}
return t.conn.agent.request(acpMethods.agent.session.prompt, {
sessionId,
- prompt: [...built.blocks],
+ prompt: skillBlock === null ? [...built.blocks] : [...built.blocks, skillBlock],
});
});
requestPromise
@@ -3283,6 +3438,7 @@ function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {
closed: false,
hadUserMessage: true,
envNotePending: false,
+ projectSkill: null,
};
}