Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions examples/rsc-agent-runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,19 @@ This private, opt-in example shows one React Server Components (RSC) runtime sha
| RSC render | Hook and MCP result component trees, lowered from Flight | One request |
| MCP App UI | Mounted timeline, Refresh, and recoverable row selection | One UI instance |

Native hooks are fresh requests: a process normalizes one host event, invokes the RSC worker through the runtime dispatcher seam, projects the final Agent Document, and exits. The durable kernel—not a Node module cache or React state—connects later hook processes and MCP calls.
Native hooks are fresh requests: the compiler-generated client validates one host event, invokes `src/events/tool/after.tsx` in its explicit standalone mode, projects the final Agent Document, and exits. The durable kernel—not a Node module cache or React state—connects later hook processes and MCP calls.

```tsx
// An Agent Document route reads request-scoped context.
import { Agent, agent } from '@agent-bundle/runtime';
import type { CanonicalPostToolUse, RuntimeSnapshot } from '../runtime/contracts.js';

export async function AfterFileEdit() {
const context = await agent();
const edit = context.services.edit as CanonicalPostToolUse;
const snapshot = context.services.snapshot as RuntimeSnapshot;
// The semantic event route receives canonical identity plus the complete native payload.
import { Agent } from '@agent-bundle/runtime';
import type { AgentEventRouteProps } from 'agent-bundle';

export const config = { runtime: 'standalone', targets: ['claude', 'codex'] };

export default async function AfterFileEdit({ canonical, native }: AgentEventRouteProps) {
return (
<Agent.Result>
<Agent.Text>
{`Recorded ${edit.path}; ${snapshot.edits.length} edits exist.`}
</Agent.Text>
<Agent.Context>{`Recorded ${String(native.tool_name)} from ${canonical.provenance.host}.`}</Agent.Context>
</Agent.Result>
);
}
Expand Down Expand Up @@ -97,8 +94,8 @@ To exercise one hook manually, give it an explicit state file and native Claude-

```bash
AGENT_RUNTIME_STATE_FILE=/tmp/rsc-agent-state.sqlite \
node examples/rsc-agent-runtime/dist/runtime/hook/index.js --host claude <<JSON
{"hook_event_name":"PostToolUse","session_id":"manual","cwd":"$PWD","tool_name":"Write","tool_input":{"file_path":"README.md"}}
node examples/rsc-agent-runtime/dist/plugins/claude/hooks/event-route-tool-after.mjs <<JSON
{"hook_event_name":"PostToolUse","session_id":"manual","cwd":"$PWD","transcript_path":"$PWD/transcript.jsonl","tool_name":"Write","tool_input":{"file_path":"README.md"},"tool_response":{"success":true},"tool_use_id":"manual-write-1"}
JSON
```

Expand Down Expand Up @@ -150,7 +147,7 @@ pnpm eval:spot
```

It builds this example, replays one native-shaped Claude `PostToolUse` event
through the built hook binary (RSC worker render, Flight lowering, a durable
through the compiled `src/events/tool/after.tsx` route (Agent Document projection, a durable
state-kernel commit), replays the same native tool id from a second hook
process to prove cross-process idempotency, then connects a real stdio MCP
client to the built server over the same state file and asserts the
Expand Down
18 changes: 0 additions & 18 deletions examples/rsc-agent-runtime/agent-bundle.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,6 @@ export default defineConfig({
claude: {},
codex: {},
dev: { runtime: { provider: './src/dev/provider.ts' } },
hooks: {
afterTool: [
{
args: ['--host', 'claude'],
handler: { prebuilt: './dist/runtime/hook/index.js' },
targets: ['claude'],
timeout: 30,
tools: ['file.write'],
},
{
args: ['--host', 'codex'],
handler: { prebuilt: './dist/runtime/hook/index.js' },
targets: ['codex'],
timeout: 30,
tools: ['file.write'],
},
],
},
marketplace: true,
mcp: {
servers: {
Expand Down
52 changes: 52 additions & 0 deletions examples/rsc-agent-runtime/src/events/tool/after.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { basename, resolve } from 'node:path';

import { Agent } from '@agent-bundle/runtime';
import type { AgentEventRouteProps } from 'agent-bundle';
import * as React from 'react';

import { normalizeClaudeHook, normalizeCodexHook } from '../../hook/normalize.js';
import { createFileRuntimeKernel, resolveImplicitRuntimeStateFile } from '../../runtime/state-file.js';

export const config = {
runtime: 'standalone',
targets: ['claude', 'codex'],
timeoutMs: 30_000,
tools: ['file.write'],
};

export default async function AfterFileEdit({
canonical,
native,
signal,
}: AgentEventRouteProps) {
const host = canonical.provenance.host;
const normalized = host === 'claude'
? normalizeClaudeHook(native)
: host === 'codex'
? normalizeCodexHook(native)
: undefined;
if (normalized === undefined) {
throw new Error(`Unsupported event-route host ${JSON.stringify(host)}`);
}

const configuredStateFile = process.env.AGENT_RUNTIME_STATE_FILE;
const stateFile = configuredStateFile === undefined || configuredStateFile.trim() === ''
? await resolveImplicitRuntimeStateFile(normalized.cwd)
: resolve(configuredStateFile);
const snapshot = await createFileRuntimeKernel({ stateFile }).recordEdit({
host: normalized.host,
idempotencyKey: canonical.idempotencyKey,
path: normalized.path,
sessionId: normalized.sessionId,
toolName: normalized.toolName,
}, { signal });
Comment on lines +36 to +42

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restore the launch probe on the packaged hook path

When eval:hosts -- --host claude runs a successful packaged hook, this route records state but never appends to AGENT_RUNTIME_HOOK_PROBE_FILE; the only writer remains src/hook/cli.ts, whose prebuilt hook declarations were removed from the package configuration. Consequently scripts/eval-hosts.mjs observes zero launches, classifies hook-dispatch and shared hook/MCP state as unavailable, and exits nonzero even when the route, edit, and MCP calls all succeed. Preserve the value-free probe on the new event-route execution path.

AGENTS.md reference: AGENTS.md:L10-L12

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in #196 (merged as 8c77ce6). The packaged event route now appends the same value-free probe line to AGENT_RUNTIME_HOOK_PROBE_FILE as the original hook CLI (shared writeEvalProbe in src/hook/eval-probe.ts; exitStatus: 0 on success, 1 on failure), so eval:hosts can observe packaged hook execution again. Covered by a route-unit test pinning the exact probe format.

const editNoun = snapshot.stateVersion === 1 ? 'edit' : 'edits';

return (
<Agent.Result>
<Agent.Context>
{`Recorded ${basename(normalized.path)} from ${normalized.host}. Shared state now contains ${snapshot.stateVersion} ${editNoun}.`}
</Agent.Context>
</Agent.Result>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"cwd": "/tmp/agent-bundle-schema-conformance",
"hook_event_name": "PostToolUse",
"session_id": "schema-conformance-claude",
"tool_input": {
"file_path": "claude-note.txt"
},
"tool_name": "Write",
"tool_response": {
"success": true
},
"tool_use_id": "schema-conformance-claude-write",
"transcript_path": "/tmp/agent-bundle-schema-conformance/claude-transcript.jsonl"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"cwd": "/tmp/agent-bundle-schema-conformance",
"event_id": "schema-conformance-codex-event",
"hook_event_name": "PostToolUse",
"session_id": "schema-conformance-codex",
"tool_input": {
"command": "*** Begin Patch\n*** Add File: codex-note.txt\n+recorded\n*** End Patch"
},
"tool_name": "apply_patch",
"tool_response": {
"success": true
},
"tool_use_id": "schema-conformance-codex-patch",
"transcript_path": "/tmp/agent-bundle-schema-conformance/codex-transcript.jsonl"
}
34 changes: 10 additions & 24 deletions examples/rsc-agent-runtime/tests/host-artifacts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,10 @@ test('materializes self-contained Claude and Codex native plugin artifacts', asy
expect(JSON.stringify(codexMcp)).not.toMatch(/\$\{|workspace/i);
expect(claudeHooks.hooks.PostToolUse[0]).toMatchObject({ matcher: '^(?:Write|Edit)$' });
expect(claudeHooks.hooks.PostToolUse[0].hooks[0].command).toContain('${CLAUDE_PLUGIN_ROOT}');
expect(claudeHooks.hooks.PostToolUse[0].hooks[0].command).toContain('--host claude');
expect(claudeHooks.hooks.PostToolUse[0].hooks[0].command).toContain('hooks/event-route-tool-after.mjs');
expect(codexHooks.hooks.PostToolUse[0]).toMatchObject({ matcher: '^(?:apply_patch|Edit|Write)$' });
expect(codexHooks.hooks.PostToolUse[0].hooks[0].command).toContain('${PLUGIN_ROOT}');
expect(codexHooks.hooks.PostToolUse[0].hooks[0].command).toContain('--host codex');
expect(codexHooks.hooks.PostToolUse[0].hooks[0].command).toContain('hooks/event-route-tool-after.mjs');
expect(JSON.stringify({ claudeMcp, claudeHooks, codexMcp, codexHooks })).not.toMatch(/api[ _-]?key/i);

const runtimeRoot = join(exampleRoot, 'dist/runtime');
Expand Down Expand Up @@ -243,7 +243,7 @@ test('runs the packaged MCP server after its artifact is isolated from the examp
}
});

test('runs each packaged native hook from one shell argv path when its plugin root contains spaces and metacharacters', async () => {
test('replays schema-conformance fixtures through each packaged native event route', async () => {
await runPackageHosts();
const temporaryRoot = await mkdtemp(join(tmpdir(), 'rsc-agent-runtime-hook-root-'));
try {
Expand All @@ -255,33 +255,19 @@ test('runs each packaged native hook from one shell argv path when its plugin ro

for (const host of ['claude', 'codex'] as const) {
const pluginRoot = join(temporaryRoot, `${host} plugin root ; ordinary`);
const workspace = join(temporaryRoot, `${host}-workspace`);
const stateFile = join(temporaryRoot, `${host}-state.sqlite`);
const manifestPath = join(pluginRoot, 'hooks/hooks.json');
const rootVariable = host === 'claude' ? 'CLAUDE_PLUGIN_ROOT' : 'PLUGIN_ROOT';
const filename = `${host}-note.txt`;
await cp(join(pluginsRoot, host), pluginRoot, { recursive: true });
await mkdir(workspace);
const manifest = await readJson<{ hooks: { PostToolUse: Array<{ hooks: Array<{ command: string }> }> } }>(manifestPath);
const command = manifest.hooks.PostToolUse[0]?.hooks[0]?.command;
expect(command).toBeTypeOf('string');
const input = host === 'claude'
? {
cwd: workspace,
hook_event_name: 'PostToolUse',
session_id: `${host}-session`,
tool_input: { file_path: join(workspace, filename) },
tool_name: 'Write',
tool_use_id: `${host}-tool`,
}
: {
cwd: workspace,
event_id: `${host}-event`,
hook_event_name: 'PostToolUse',
session_id: `${host}-session`,
tool_input: { command: `*** Begin Patch\n*** Add File: ${filename}\n+recorded\n*** End Patch` },
tool_name: 'apply_patch',
};
// These checked-in payloads establish schema conformance only; replay
// through a local command is not evidence of commercial-host dispatch.
const input = await readJson<Record<string, unknown>>(
join(exampleRoot, `tests/fixtures/events/${host}-post-tool-use.json`),
);
const result = await runDeclaredHook(command!, {
[rootVariable]: pluginRoot,
AGENT_RUNTIME_HOOK_ARGV_FILE: argvFile,
Expand All @@ -299,11 +285,11 @@ test('runs each packaged native hook from one shell argv path when its plugin ro
},
});
expect((await readFile(argvFile)).toString('utf8').split('\0').filter(Boolean)).toEqual([
join(pluginRoot, 'runtime/hook/index.js'), '--host', host,
join(pluginRoot, 'hooks/event-route-tool-after.mjs'),
]);
const recorded = await createFileRuntimeKernel({ stateFile }).readSnapshot();
expect(recorded.edits.map((edit) => edit.host)).toEqual([host]);
expect(command).toBe(`node "\${${rootVariable}}/runtime/hook/index.js" --host ${host}`);
expect(command).toBe(`node "\${${rootVariable}}/hooks/event-route-tool-after.mjs"`);
expect(command).not.toMatch(/(?:api[ _-]?key|echo|printenv|AGENT_RUNTIME_)/iu);
}
} finally {
Expand Down
7 changes: 4 additions & 3 deletions examples/rsc-agent-runtime/tests/micro-eval.spot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import { ensureExampleBuilt } from './support/ensure-built.js';
// This is the ordinary-CI micro-eval spot-check (`npm run eval:spot`): one
// deterministic pass over the built production artifacts, with no real Claude
// or Codex host. It proves the end-to-end runtime path in a small way: a
// native-shaped hook event renders through the RSC worker into the framework
// state kernel's workspace-durable sqlite store (#98), a second hook process
// native-shaped hook event renders through the compiled semantic event route
// into the framework state kernel's workspace-durable sqlite store (#98), a second hook process
// replaying the same native tool id commits nothing new, and the MCP server
// then RSC-lowers that same shared state for a tool call while linking the
// MCP App resource.
Expand All @@ -32,7 +32,7 @@ test('micro-eval spot-check: built hook and MCP server share one RSC-rendered ru
});

const runHookOnce = async (): Promise<void> => {
const hook = spawn(process.execPath, [join(process.cwd(), 'dist/runtime/hook/index.js'), '--host', 'claude'], {
const hook = spawn(process.execPath, [join(process.cwd(), 'dist/plugins/claude/hooks/event-route-tool-after.mjs')], {
env: { ...process.env, AGENT_RUNTIME_STATE_FILE: stateFile },
stdio: ['pipe', 'pipe', 'pipe'],
});
Expand All @@ -44,6 +44,7 @@ test('micro-eval spot-check: built hook and MCP server share one RSC-rendered ru
tool_name: 'Write',
tool_response: { success: true },
tool_use_id: 'micro-eval-tool-1',
transcript_path: join(workspace, 'transcript.jsonl'),
}));
const hookStdout: Buffer[] = [];
const hookStderr: Buffer[] = [];
Expand Down
Loading