codeassembly-agent-logic 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/.meta/changelog.json +67 -0
  2. package/CHANGELOG.md +23 -0
  3. package/README.md +75 -5
  4. package/bin/agent-logic.js +1 -0
  5. package/dist/esm/agent/convert-with-agent.d.ts +53 -0
  6. package/dist/esm/agent/convert-with-agent.js +111 -0
  7. package/dist/esm/agent/create-conversion-session.d.ts +34 -0
  8. package/dist/esm/agent/create-conversion-session.js +62 -0
  9. package/dist/esm/agent/index.d.ts +3 -0
  10. package/dist/esm/agent/index.js +2 -0
  11. package/dist/esm/cli/check-coverage-command.js +7 -10
  12. package/dist/esm/cli/convert-command.d.ts +8 -0
  13. package/dist/esm/cli/convert-command.js +3 -1
  14. package/dist/esm/cli/convert-with-agent-command.d.ts +11 -0
  15. package/dist/esm/cli/convert-with-agent-command.js +183 -0
  16. package/dist/esm/cli/index.js +3 -3
  17. package/dist/esm/cli/run.d.ts +1 -1
  18. package/dist/esm/cli/run.js +9 -5
  19. package/dist/esm/client/create-conversion-client.d.ts +44 -0
  20. package/dist/esm/client/create-conversion-client.js +86 -0
  21. package/dist/esm/client/index.d.ts +3 -0
  22. package/dist/esm/client/index.js +1 -0
  23. package/dist/esm/conversion-protocol/conversion-schemas.d.ts +70 -0
  24. package/dist/esm/conversion-protocol/conversion-schemas.js +32 -0
  25. package/dist/esm/coverage-map/format-coverage-result.d.ts +6 -0
  26. package/dist/esm/coverage-map/format-coverage-result.js +7 -0
  27. package/dist/esm/react/hooks/describe-load-outcome.d.ts +0 -2
  28. package/dist/esm/react/hooks/describe-load-outcome.js +0 -3
  29. package/dist/esm/react/index.d.ts +0 -7
  30. package/dist/esm/react/index.js +0 -7
  31. package/dist/esm/server/conversion-store.d.ts +13 -0
  32. package/dist/esm/server/conversion-store.js +1 -0
  33. package/dist/esm/server/create-conversion-handler.d.ts +36 -0
  34. package/dist/esm/server/create-conversion-handler.js +199 -0
  35. package/dist/esm/server/create-memory-conversion-store.d.ts +12 -0
  36. package/dist/esm/server/create-memory-conversion-store.js +30 -0
  37. package/dist/esm/server/index.d.ts +5 -7
  38. package/dist/esm/server/index.js +2 -6
  39. package/docs/agent-instructions.md +19 -0
  40. package/package.json +22 -14
  41. package/dist/esm/contract/built-in-harnesses.d.ts +0 -22
  42. package/dist/esm/contract/built-in-harnesses.js +0 -30
  43. package/dist/esm/contract/conversion-job.d.ts +0 -36
  44. package/dist/esm/contract/conversion-job.js +0 -17
  45. package/dist/esm/contract/index.d.ts +0 -4
  46. package/dist/esm/contract/index.js +0 -3
  47. package/dist/esm/contract/viewer-contract.d.ts +0 -804
  48. package/dist/esm/contract/viewer-contract.js +0 -38
  49. package/dist/esm/react/hooks/conversion-client.d.ts +0 -77
  50. package/dist/esm/react/hooks/conversion-client.js +0 -132
  51. package/dist/esm/react/hooks/describe-agent-selection.d.ts +0 -6
  52. package/dist/esm/react/hooks/describe-agent-selection.js +0 -18
  53. package/dist/esm/react/hooks/useAgentBridge.d.ts +0 -28
  54. package/dist/esm/react/hooks/useAgentBridge.js +0 -52
  55. package/dist/esm/react/hooks/useAgentSync.d.ts +0 -29
  56. package/dist/esm/react/hooks/useAgentSync.js +0 -75
  57. package/dist/esm/react/hooks/useConversion.d.ts +0 -31
  58. package/dist/esm/react/hooks/useConversion.js +0 -177
  59. package/dist/esm/react/hooks/useHarnessList.d.ts +0 -26
  60. package/dist/esm/react/hooks/useHarnessList.js +0 -24
  61. package/dist/esm/react/hooks/usePromptDirectory.d.ts +0 -27
  62. package/dist/esm/react/hooks/usePromptDirectory.js +0 -34
  63. package/dist/esm/server/conversion-job-implementation.d.ts +0 -11
  64. package/dist/esm/server/conversion-job-implementation.js +0 -84
  65. package/dist/esm/server/create-prompts-app.d.ts +0 -26
  66. package/dist/esm/server/create-prompts-app.js +0 -41
  67. package/dist/esm/server/create-viewer-server-plugins.d.ts +0 -15
  68. package/dist/esm/server/create-viewer-server-plugins.js +0 -76
  69. package/dist/esm/server/prompt-directory-schemas.d.ts +0 -30
  70. package/dist/esm/server/prompt-directory-schemas.js +0 -11
  71. package/dist/esm/server/prompt-directory.d.ts +0 -40
  72. package/dist/esm/server/prompt-directory.js +0 -86
  73. package/dist/esm/server/viewer-contract-implementation.d.ts +0 -12
  74. package/dist/esm/server/viewer-contract-implementation.js +0 -85
  75. /package/dist/esm/{cli → package-files}/find-package-root.d.ts +0 -0
  76. /package/dist/esm/{cli → package-files}/find-package-root.js +0 -0
@@ -1,4 +1,71 @@
1
1
  [
2
+ {
3
+ "version": "0.3.0",
4
+ "date": "2026-11-16",
5
+ "sections": [
6
+ {
7
+ "title": "🎉 Features",
8
+ "audience": "all",
9
+ "items": [
10
+ {
11
+ "description": "Adds the `codeassembly-agent-logic/agent` entry, whose `convertWithAgent` converts a prompt by directing an Agent Client Protocol (ACP) agent that can call only the `check_coverage` and `submit_draft` tools, and yields an event for each coverage check and draft submission, then a `result` event that contains the outcome of the last submission. (#2283)",
12
+ "hash": "37b7b1d22998e613e187200135f6c3f51a83ef3f",
13
+ "entry": 1
14
+ },
15
+ {
16
+ "description": "Adds the `agent-logic convert-with-agent --agent <profile> <prompt-file> [output-file]` command, which reports each coverage check and draft submission on stderr, writes the config only when it is valid, and exits 130 without writing any output file when Ctrl+C stops the conversion. (#2283)",
17
+ "hash": "37b7b1d22998e613e187200135f6c3f51a83ef3f",
18
+ "entry": 2
19
+ },
20
+ {
21
+ "description": "Adds `createConversionHandler` to `codeassembly-agent-logic/server`, a Fetch handler that starts, reads, and cancels conversions on an ACP agent under a base path, together with the `ConversionStore` interface and `createMemoryConversionStore`, which keeps conversions in process memory and drops each ended one after a retention period, one hour by default. (#2285)",
22
+ "hash": "2529cac0cf94ffc7298d50ccf4dd90b0b48e8b42",
23
+ "entry": 1
24
+ },
25
+ {
26
+ "description": "Adds the `codeassembly-agent-logic/client` entry, whose browser-safe `createConversionClient` starts, reads, cancels, and watches conversions on the routes that `createConversionHandler` serves, so that a page can resume a conversion by its id after a reload. (#2285)",
27
+ "hash": "2529cac0cf94ffc7298d50ccf4dd90b0b48e8b42",
28
+ "entry": 2
29
+ }
30
+ ]
31
+ },
32
+ {
33
+ "title": "🪦 Removed",
34
+ "audience": "all",
35
+ "items": [
36
+ {
37
+ "description": "Removes the telefactor-backed conversion path from `codeassembly-agent-logic`: the `./contract` entry, the `createViewerServerPlugins`, `createPromptsApp`, prompt-directory, and viewer-contract exports of `./server`, and the `useAgentBridge`, `useAgentSync`, `useConversion`, `useHarnessList`, and `usePromptDirectory` hooks of `./react`, together with the `@williamthorsen/telefactor` peer dependency. (#2286)",
38
+ "breaking": true,
39
+ "migration": "Serve conversions with `createConversionHandler` from `codeassembly-agent-logic/server` and call them from the browser with `createConversionClient` from `codeassembly-agent-logic/client`, then remove `@williamthorsen/telefactor`; the handler runs conversions on an ACP agent and needs the `@williamthorsen/toolbelt.acp` and `@modelcontextprotocol/server` peers, and the package no longer provides a replacement that serves a prompts directory.",
40
+ "hash": "9acb9605722bab87149159de3afc0d8ea580b984",
41
+ "entry": 1
42
+ }
43
+ ]
44
+ },
45
+ {
46
+ "title": "🧪 Tests",
47
+ "audience": "dev",
48
+ "items": [
49
+ {
50
+ "description": "Replaces the `vi.waitFor` polls in `conversion-job-implementation.tool.test.ts` and `create-viewer-server-plugins.dev-server.tool.test.ts` with waits that end when the job ends, which only each test's own timeout limits, so that a slow fake-harness start no longer fails either test on a 1 s or 10 s limit. (#2277)",
51
+ "hash": "a5ab31fe194e633d9e665a7b51184a40ff6a71e7",
52
+ "entry": 1
53
+ }
54
+ ]
55
+ },
56
+ {
57
+ "title": "⚙️ Tooling",
58
+ "audience": "dev",
59
+ "items": [
60
+ {
61
+ "description": "Upgrade the lint and TypeScript config packages (#2280)",
62
+ "body": "Upgrades `@williamthorsen/eslint-config-typescript` to 22.0.0, `@williamthorsen/strict-lint` to 15.0.0, and `@williamthorsen/tsconfig` to 0.13.0, and removes the TypeScript import resolver and its `eslint-import-resolver-typescript` dev dependency from the root lint setup.",
63
+ "hash": "a68dff407958bbc82b969e0edfdd58cfde9d861e"
64
+ }
65
+ ]
66
+ }
67
+ ]
68
+ },
2
69
  {
3
70
  "version": "0.2.1",
4
71
  "date": "2026-11-12",
package/CHANGELOG.md CHANGED
@@ -2,6 +2,29 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## 0.3.0 — 2026-11-16
6
+
7
+ ### 🎉 Features
8
+
9
+ - Adds the `codeassembly-agent-logic/agent` entry, whose `convertWithAgent` converts a prompt by directing an Agent Client Protocol (ACP) agent that can call only the `check_coverage` and `submit_draft` tools, and yields an event for each coverage check and draft submission, then a `result` event that contains the outcome of the last submission. (#2283)
10
+ - Adds the `agent-logic convert-with-agent --agent <profile> <prompt-file> [output-file]` command, which reports each coverage check and draft submission on stderr, writes the config only when it is valid, and exits 130 without writing any output file when Ctrl+C stops the conversion. (#2283)
11
+ - Adds `createConversionHandler` to `codeassembly-agent-logic/server`, a Fetch handler that starts, reads, and cancels conversions on an ACP agent under a base path, together with the `ConversionStore` interface and `createMemoryConversionStore`, which keeps conversions in process memory and drops each ended one after a retention period, one hour by default. (#2285)
12
+ - Adds the `codeassembly-agent-logic/client` entry, whose browser-safe `createConversionClient` starts, reads, cancels, and watches conversions on the routes that `createConversionHandler` serves, so that a page can resume a conversion by its id after a reload. (#2285)
13
+
14
+ ### 🪦 Removed
15
+
16
+ - 🚨 **Breaking:** Removes the telefactor-backed conversion path from `codeassembly-agent-logic`: the `./contract` entry, the `createViewerServerPlugins`, `createPromptsApp`, prompt-directory, and viewer-contract exports of `./server`, and the `useAgentBridge`, `useAgentSync`, `useConversion`, `useHarnessList`, and `usePromptDirectory` hooks of `./react`, together with the `@williamthorsen/telefactor` peer dependency. (#2286)
17
+
18
+ ### 🧪 Tests
19
+
20
+ - Replaces the `vi.waitFor` polls in `conversion-job-implementation.tool.test.ts` and `create-viewer-server-plugins.dev-server.tool.test.ts` with waits that end when the job ends, which only each test's own timeout limits, so that a slow fake-harness start no longer fails either test on a 1 s or 10 s limit. (#2277)
21
+
22
+ ### ⚙️ Tooling
23
+
24
+ - Upgrade the lint and TypeScript config packages (#2280)
25
+
26
+ Upgrades `@williamthorsen/eslint-config-typescript` to 22.0.0, `@williamthorsen/strict-lint` to 15.0.0, and `@williamthorsen/tsconfig` to 0.13.0, and removes the TypeScript import resolver and its `eslint-import-resolver-typescript` dev dependency from the root lint setup.
27
+
5
28
  ## 0.2.1 — 2026-11-12
6
29
 
7
30
  ### Notes
package/README.md CHANGED
@@ -1,3 +1,18 @@
1
+ <!-- section:release-notes -->
2
+ ## Release notes — v0.3.0 (2026-11-16)
3
+
4
+ ### 🎉 Features
5
+
6
+ - Adds the `codeassembly-agent-logic/agent` entry, whose `convertWithAgent` converts a prompt by directing an Agent Client Protocol (ACP) agent that can call only the `check_coverage` and `submit_draft` tools, and yields an event for each coverage check and draft submission, then a `result` event that contains the outcome of the last submission. (#2283)
7
+ - Adds the `agent-logic convert-with-agent --agent <profile> <prompt-file> [output-file]` command, which reports each coverage check and draft submission on stderr, writes the config only when it is valid, and exits 130 without writing any output file when Ctrl+C stops the conversion. (#2283)
8
+ - Adds `createConversionHandler` to `codeassembly-agent-logic/server`, a Fetch handler that starts, reads, and cancels conversions on an ACP agent under a base path, together with the `ConversionStore` interface and `createMemoryConversionStore`, which keeps conversions in process memory and drops each ended one after a retention period, one hour by default. (#2285)
9
+ - Adds the `codeassembly-agent-logic/client` entry, whose browser-safe `createConversionClient` starts, reads, cancels, and watches conversions on the routes that `createConversionHandler` serves, so that a page can resume a conversion by its id after a reload. (#2285)
10
+
11
+ ### 🪦 Removed
12
+
13
+ - 🚨 **Breaking:** Removes the telefactor-backed conversion path from `codeassembly-agent-logic`: the `./contract` entry, the `createViewerServerPlugins`, `createPromptsApp`, prompt-directory, and viewer-contract exports of `./server`, and the `useAgentBridge`, `useAgentSync`, `useConversion`, `useHarnessList`, and `usePromptDirectory` hooks of `./react`, together with the `@williamthorsen/telefactor` peer dependency. (#2286)
14
+ <!-- /section:release-notes -->
15
+
1
16
  <!-- readme-type: library -->
2
17
 
3
18
  # codeassembly-agent-logic
@@ -25,17 +40,71 @@ if (result.ok) {
25
40
  | Entry | Exports |
26
41
  | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
42
  | `codeassembly-agent-logic` | The config schema and its validation, the converter and coverage check, the chart description, its ELK graph (`buildElkGraph`), its layout, source marking, and the bundled examples. |
43
+ | `codeassembly-agent-logic/agent` | `convertWithAgent`, which converts a prompt by directing an ACP agent through the conversion. |
28
44
  | `codeassembly-agent-logic/react` | `StatechartCanvas`, the key's entries as data (`CANVAS_KEY_ENTRIES` and the mark glyphs), and the hooks of a page that presents a chart. |
29
45
  | `codeassembly-agent-logic/react/styles.css` | The canvas stylesheet. |
30
- | `codeassembly-agent-logic/server` | `createViewerServerPlugins`, the Vite plugins that serve the prompts directory and run conversions through a harness that telefactor hosts. |
31
- | `codeassembly-agent-logic/contract` | The contracts between a page and its server: the viewer contract, the conversion job, and the built-in harnesses. |
46
+ | `codeassembly-agent-logic/server` | `createConversionHandler`, which serves conversions on an ACP agent, and its stores. |
47
+ | `codeassembly-agent-logic/client` | `createConversionClient`, the browser client of the routes that `createConversionHandler` serves. |
32
48
  | `codeassembly-agent-logic/agent-logic.schema.json` | The config's JSON Schema. |
33
49
 
34
- React 19 is a peer of `./react`, and `@williamthorsen/telefactor` a peer of `./server` and `./contract`.
50
+ React 19 is a peer of `./react`, and `@williamthorsen/toolbelt.acp` and `@modelcontextprotocol/server` peers of `./agent` and `./server`.
51
+
52
+ ## Converting on an ACP agent
53
+
54
+ ```ts
55
+ import { convertWithAgent } from 'codeassembly-agent-logic/agent';
56
+ import { claudeCodeProfile } from '@williamthorsen/toolbelt.acp/proposed';
57
+
58
+ for await (const event of convertWithAgent({ prompt, name: 'refund-request.md', agent: claudeCodeProfile() })) {
59
+ if (event.type === 'result') console.log(event.result);
60
+ }
61
+ ```
62
+
63
+ `convertWithAgent` runs the agent through [`@williamthorsen/toolbelt.acp`](https://github.com/williamthorsen/toolbelt/tree/main/packages/acp#readme) in an empty temporary directory and gives it two tools: `check_coverage`, which answers 3 checks of its coverage map, and `submit_draft`, which converts a draft and accepts 5. Every other request of the agent is refused. It yields the agent's message text and each check and submission, then a `result` event whose `ConvertResult` is the outcome of the last submission, with the usage and cost that the agent reports. The agent's instructions are [`docs/agent-instructions.md`](docs/agent-instructions.md) followed by the [extraction rules](docs/extraction-rules.md). The doc comment of `convertWithAgent` states when it rejects.
64
+
65
+ The agent's harness must be installed and signed in. Each profile signs in as follows:
66
+
67
+ | Profile | Signs in with |
68
+ | -------------------- | ------------------------------------------------------------------------------------------------------------- |
69
+ | `claudeCodeProfile` | The `claude` CLI's login, or `ANTHROPIC_API_KEY` in the environment |
70
+ | `antigravityProfile` | The CLI's personal Google login |
71
+ | `codexProfile` | Not supported: The profile cannot identify calls of the conversion's tools, so `convertWithAgent` rejects it. |
72
+
73
+ ## Serving conversions
74
+
75
+ ```ts
76
+ import { createConversionHandler, createMemoryConversionStore } from 'codeassembly-agent-logic/server';
77
+ import { claudeCodeProfile } from '@williamthorsen/toolbelt.acp/proposed';
78
+
79
+ const handleConversion = createConversionHandler({
80
+ agent: claudeCodeProfile(),
81
+ store: createMemoryConversionStore(),
82
+ authorize: (request) => isSignedIn(request),
83
+ timeoutMs: 10 * 60_000,
84
+ basePath: '/api/conversions',
85
+ });
86
+ ```
87
+
88
+ ```ts
89
+ import { createConversionClient } from 'codeassembly-agent-logic/client';
90
+
91
+ const client = createConversionClient({ url: '/api/conversions' });
92
+ const started = await client.start({ prompt, name: 'refund-request.md' });
93
+ if (started.ok) {
94
+ for await (const outcome of client.watch(started.conversion.id)) console.log(outcome);
95
+ }
96
+ ```
97
+
98
+ `createConversionHandler` is a Fetch handler (`Request → Response`) that starts a conversion with `POST {basePath}`, reads it with `GET {basePath}/{id}`, and cancels it with `DELETE {basePath}/{id}`, running each one through `convertWithAgent`. A page that reloads resumes by calling `watch` with the id that it kept. The doc comments of `createConversionHandler` and `ConversionClient` state the status codes and the edge cases. The host supplies:
99
+
100
+ - Mounting: The host's server passes each request under `basePath` to the handler.
101
+ - Authorization: `authorize` decides whether the handler serves a request.
102
+ - Store: `createMemoryConversionStore` keeps conversions in one process and drops each ended one after an hour; a durable store implements `ConversionStore`.
103
+ - Timeout: `timeoutMs` bounds each conversion, after which it fails.
35
104
 
36
105
  ## What the app supplies
37
106
 
38
- The package draws the chart; the page around it is the app's. The app renders the load controls, the inspector, the source pane, and the terminal in its own design system, and it renders the canvas's key: `StatechartCanvas` passes the marks that the chart draws to its `renderKey` prop, and `CANVAS_KEY_ENTRIES` gives each mark's name, gloss, and drawing. The app also supplies the conversion server's URL to `createConversionClient`.
107
+ The package draws the chart; the page around it is the app's. The app renders the load controls, the inspector, the source pane, and the terminal in its own design system, and it renders the canvas's key: `StatechartCanvas` passes the marks that the chart draws to its `renderKey` prop, and `CANVAS_KEY_ENTRIES` gives each mark's name, gloss, and drawing. The app also supplies the URL of the conversions resource to `./client`'s `createConversionClient`.
39
108
 
40
109
  ## Styling and theming
41
110
 
@@ -64,6 +133,7 @@ The properties, whose defaults [`styles.css`](src/react/styles.css) declares:
64
133
  pnpm dlx codeassembly-agent-logic rules
65
134
  pnpm dlx codeassembly-agent-logic convert prompt.md draft.json prompt.agent-logic.json
66
135
  pnpm dlx codeassembly-agent-logic check-coverage prompt.md coverage-map.json
136
+ pnpm dlx --package codeassembly-agent-logic --package @williamthorsen/toolbelt.acp --package @modelcontextprotocol/server agent-logic convert-with-agent --agent claude-code prompt.md
67
137
  ```
68
138
 
69
- `rules` prints the [extraction rules](docs/extraction-rules.md) by which a model drafts a prompt's logic; `convert` turns the draft into a config; `check-coverage` checks a map of the prompt's instructions against the prompt. `agent-logic <command> --help` describes each command's arguments. [Conversion agreement](docs/conversion-agreement.md) records how consistently a model converts the same prompt, and the [corpus](docs/corpus.md) measures conversions of real prompts.
139
+ `rules` prints the [extraction rules](docs/extraction-rules.md) by which a model drafts a prompt's logic; `convert` turns the draft into a config; `check-coverage` checks a map of the prompt's instructions against the prompt; `convert-with-agent` converts a prompt on an ACP agent through `convertWithAgent`, which needs the optional peers. `agent-logic <command> --help` describes each command's arguments. [Conversion agreement](docs/conversion-agreement.md) records how consistently a model converts the same prompt, and the [corpus](docs/corpus.md) measures conversions of real prompts.
@@ -20,6 +20,7 @@ if (!existsSync(entryPoint)) {
20
20
  try {
21
21
  await import(entryPoint.href);
22
22
  } catch (error) {
23
+ // eslint-disable-next-line no-restricted-syntax -- The shared helper is not a builtin; see the import note above.
23
24
  const message = error instanceof Error ? error.message : String(error);
24
25
  process.stderr.write(`agent-logic: failed to load: ${message}\n`);
25
26
  process.exit(1);
@@ -0,0 +1,53 @@
1
+ import { type AgentProfile, runPrompt } from '@williamthorsen/toolbelt.acp/proposed';
2
+ import type { ConvertResult } from '../convert/convert-prompt.js';
3
+ import { type SessionEvent } from './create-conversion-session.js';
4
+ /** The name of the MCP server through which the agent reaches the conversion's tools. */
5
+ export declare const CONVERSION_SERVER_NAME = "agent_logic";
6
+ /** What `convertWithAgent` converts, and on which agent. */
7
+ export interface ConvertWithAgentOptions {
8
+ /** The prompt, verbatim. */
9
+ readonly prompt: string;
10
+ /** The prompt's file name, from which the config's root id derives. */
11
+ readonly name: string;
12
+ /** The agent profile, which must define `isToolServerCall`. */
13
+ readonly agent: AgentProfile;
14
+ /** Ends the run, which then rejects with the signal's reason. */
15
+ readonly signal?: AbortSignal;
16
+ }
17
+ /** A step of a conversion, or its outcome, which is always the last event. */
18
+ export type ConversionEvent = SessionEvent | {
19
+ readonly type: 'message';
20
+ readonly text: string;
21
+ } | {
22
+ readonly type: 'result';
23
+ readonly result: ConvertResult;
24
+ /** Token counts, when the agent reports them. */
25
+ readonly usage?: {
26
+ readonly inputTokens: number;
27
+ readonly outputTokens: number;
28
+ readonly totalTokens: number;
29
+ };
30
+ /** The session's cost, when the agent reports one. */
31
+ readonly cost?: {
32
+ readonly amount: number;
33
+ readonly currency: string;
34
+ };
35
+ };
36
+ /**
37
+ * Converts a prompt by directing an ACP agent through the conversion: The agent receives the conversion's instructions
38
+ * and the extraction rules, checks its coverage map through a `check_coverage` tool, and submits each draft through a
39
+ * `submit_draft` tool, which converts it. The agent runs in an empty temporary directory, which is removed when the run
40
+ * ends, and every request other than a call of those tools is refused. Yields the agent's message text and each check
41
+ * and submission, then a `result` event that contains the outcome of the last submission.
42
+ *
43
+ * Rejects before the agent starts when the profile cannot identify calls of the conversion's tools, which
44
+ * `codexProfile` cannot; when the agent ends its turn without submitting a draft; with the signal's reason when the
45
+ * signal aborts; and, when the agent fails, with an error that names the cause, such as a harness that is not signed
46
+ * in.
47
+ *
48
+ * @stage proposed
49
+ * @experimental
50
+ */
51
+ export declare const convertWithAgent: (options: ConvertWithAgentOptions) => AsyncGenerator<ConversionEvent>;
52
+ /** Returns `convertWithAgent` running prompts through `runPromptImpl`, which tests replace. */
53
+ export declare function createConvertWithAgent(runPromptImpl: typeof runPrompt): (options: ConvertWithAgentOptions) => AsyncGenerator<ConversionEvent>;
@@ -0,0 +1,111 @@
1
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { McpServer } from '@modelcontextprotocol/server';
5
+ import { AgentRunError, runPrompt } from '@williamthorsen/toolbelt.acp/proposed';
6
+ import { z } from 'zod';
7
+ import { coverageMapSchema } from "../coverage-map/coverage-map-schema.js";
8
+ import { findPackageRoot } from "../package-files/find-package-root.js";
9
+ import { createConversionSession } from "./create-conversion-session.js";
10
+ export const CONVERSION_SERVER_NAME = 'agent_logic';
11
+ const AUTH_REQUIRED_CODE = -32_000;
12
+ export const convertWithAgent = createConvertWithAgent(runPrompt);
13
+ export function createConvertWithAgent(runPromptImpl) {
14
+ return async function* ({ prompt, name, agent, signal }) {
15
+ if (agent.isToolServerCall === undefined) {
16
+ throw new Error(`The agent \`${agent.command}\` cannot convert a prompt: Its profile cannot identify calls of the conversion's tools, so they would be refused.`);
17
+ }
18
+ signal?.throwIfAborted();
19
+ const pending = [];
20
+ const session = createConversionSession({
21
+ prompt,
22
+ name,
23
+ onEvent: (event) => {
24
+ pending.push(event);
25
+ },
26
+ });
27
+ const instructions = await readInstructions();
28
+ const cwd = await mkdtemp(path.join(os.tmpdir(), 'agent-logic-conversion-'));
29
+ try {
30
+ let stopped;
31
+ try {
32
+ const run = runPromptImpl({
33
+ agent,
34
+ cwd,
35
+ instructions,
36
+ prompt: `Prompt file: ${name}\n\n${prompt}`,
37
+ tools: {
38
+ name: CONVERSION_SERVER_NAME,
39
+ createServer: () => createConversionServer(session),
40
+ isPreapproved: true,
41
+ },
42
+ ...(signal !== undefined && { signal }),
43
+ });
44
+ for await (const event of run) {
45
+ yield* pending.splice(0);
46
+ if (event.type === 'stopped')
47
+ stopped = event;
48
+ else if (event.update.sessionUpdate === 'agent_message_chunk' && event.update.content.type === 'text') {
49
+ yield { type: 'message', text: event.update.content.text };
50
+ }
51
+ }
52
+ }
53
+ catch (error) {
54
+ if (signal?.aborted === true)
55
+ throw signal.reason;
56
+ throw describeRunError(error);
57
+ }
58
+ yield* pending.splice(0);
59
+ if (signal?.aborted === true)
60
+ throw signal.reason;
61
+ const { result } = session;
62
+ if (result === undefined) {
63
+ const stopReason = stopped?.stopReason ?? 'unknown';
64
+ throw new Error(`The agent ended its turn (stop reason: ${stopReason}) without submitting a draft.`);
65
+ }
66
+ yield {
67
+ type: 'result',
68
+ result,
69
+ ...(stopped?.usage !== undefined && {
70
+ usage: {
71
+ inputTokens: stopped.usage.inputTokens,
72
+ outputTokens: stopped.usage.outputTokens,
73
+ totalTokens: stopped.usage.totalTokens,
74
+ },
75
+ }),
76
+ ...(stopped?.cost !== undefined && { cost: { amount: stopped.cost.amount, currency: stopped.cost.currency } }),
77
+ };
78
+ }
79
+ finally {
80
+ await rm(cwd, { recursive: true, force: true });
81
+ }
82
+ };
83
+ }
84
+ function createConversionServer(session) {
85
+ const server = new McpServer({ name: CONVERSION_SERVER_NAME, version: '1.0.0' });
86
+ server.registerTool('check_coverage', {
87
+ description: 'Checks a coverage map of the prompt against the prompt.',
88
+ inputSchema: z.object({ map: coverageMapSchema }),
89
+ }, ({ map }) => ({ content: [{ type: 'text', text: session.checkCoverage(map) }] }));
90
+ server.registerTool('submit_draft', {
91
+ description: "Converts a draft of the prompt's logic into an agent-logic config, or reports its problems.",
92
+ inputSchema: z.object({ draft: z.string().describe("The draft's JSON text.") }),
93
+ }, ({ draft }) => ({ content: [{ type: 'text', text: session.submitDraft(draft) }] }));
94
+ return server;
95
+ }
96
+ function describeRunError(error) {
97
+ if (!(error instanceof AgentRunError))
98
+ return error;
99
+ const { cause } = error;
100
+ const isSignInRequired = typeof cause === 'object' && cause !== null && 'code' in cause && cause.code === AUTH_REQUIRED_CODE;
101
+ if (!isSignInRequired)
102
+ return error;
103
+ return new Error(`The agent \`${error.command}\` is not signed in: Sign in to its harness, then convert again.`, {
104
+ cause: error,
105
+ });
106
+ }
107
+ async function readInstructions() {
108
+ const docs = path.join(findPackageRoot(), 'docs');
109
+ const parts = await Promise.all(['agent-instructions.md', 'extraction-rules.md'].map((file) => readFile(path.join(docs, file), 'utf8')));
110
+ return parts.join('\n');
111
+ }
@@ -0,0 +1,34 @@
1
+ import { type ConvertResult } from '../convert/convert-prompt.js';
2
+ import type { CoverageMap } from '../coverage-map/coverage-map-schema.js';
3
+ /** The number of coverage checks that a session answers. */
4
+ export declare const MAX_COVERAGE_CHECKS = 3;
5
+ /** The number of drafts that a session accepts. */
6
+ export declare const MAX_SUBMISSIONS = 5;
7
+ /** A step of the conversion that the session reports as it happens. */
8
+ export type SessionEvent = {
9
+ readonly type: 'coverage-checked';
10
+ readonly check: number;
11
+ readonly unmapped: number;
12
+ readonly quoteProblems: number;
13
+ } | {
14
+ readonly type: 'draft-submitted';
15
+ readonly submission: number;
16
+ readonly outcome: 'config' | 'out-of-scope' | 'problems';
17
+ readonly problems: number;
18
+ };
19
+ /** The state of one conversion behind its tools: Each method returns the text that the tool answers the agent with. */
20
+ export interface ConversionSession {
21
+ /** The outcome of the last accepted submission, or `undefined` before the first. */
22
+ readonly result: ConvertResult | undefined;
23
+ checkCoverage(map: CoverageMap): string;
24
+ submitDraft(draftText: string): string;
25
+ }
26
+ /**
27
+ * Creates the session for converting `prompt`, whose file is named `name`. It answers {@link MAX_COVERAGE_CHECKS}
28
+ * coverage checks and accepts {@link MAX_SUBMISSIONS} drafts, and refuses every call after those.
29
+ */
30
+ export declare function createConversionSession({ prompt, name, onEvent, }: {
31
+ prompt: string;
32
+ name: string;
33
+ onEvent: (event: SessionEvent) => void;
34
+ }): ConversionSession;
@@ -0,0 +1,62 @@
1
+ import { convertPrompt } from "../convert/convert-prompt.js";
2
+ import { checkCoverage } from "../coverage-map/check-coverage.js";
3
+ import { formatCoverageResult } from "../coverage-map/format-coverage-result.js";
4
+ export const MAX_COVERAGE_CHECKS = 3;
5
+ export const MAX_SUBMISSIONS = 5;
6
+ export function createConversionSession({ prompt, name, onEvent, }) {
7
+ let checks = 0;
8
+ let submissions = 0;
9
+ let result;
10
+ return {
11
+ checkCoverage(map) {
12
+ if (checks >= MAX_COVERAGE_CHECKS) {
13
+ return 'The coverage checks are used up. Go on to the next check of the draft.';
14
+ }
15
+ checks += 1;
16
+ const coverage = checkCoverage(prompt, map);
17
+ onEvent({
18
+ type: 'coverage-checked',
19
+ check: checks,
20
+ unmapped: coverage.unmapped.length,
21
+ quoteProblems: coverage.quoteProblems.length,
22
+ });
23
+ const lines = formatCoverageResult(prompt, coverage);
24
+ if (lines.length === 0)
25
+ return 'Every block of the prompt is mapped. Go on to the next check of the draft.';
26
+ const left = MAX_COVERAGE_CHECKS - checks;
27
+ const next = left === 0
28
+ ? 'That was the last coverage check. Go on to the next check of the draft.'
29
+ : `Map every listed block, lengthen every listed quote, and check again. ${describeCount(left, 'check')} left.`;
30
+ return [...lines, next].join('\n');
31
+ },
32
+ submitDraft(draftText) {
33
+ if (submissions >= MAX_SUBMISSIONS)
34
+ return 'No more drafts are accepted. End your turn.';
35
+ submissions += 1;
36
+ result = convertPrompt(prompt, draftText, name);
37
+ const problems = 'problems' in result ? result.problems : [];
38
+ onEvent({
39
+ type: 'draft-submitted',
40
+ submission: submissions,
41
+ outcome: result.ok ? 'config' : 'outOfScope' in result ? 'out-of-scope' : 'problems',
42
+ problems: problems.length,
43
+ });
44
+ if (result.ok)
45
+ return 'The config is accepted. End your turn.';
46
+ if ('outOfScope' in result)
47
+ return 'The prompt is recorded as out of scope. End your turn.';
48
+ const left = MAX_SUBMISSIONS - submissions;
49
+ const lines = problems.map(({ path, message }) => (path === '' ? message : `${path}: ${message}`));
50
+ const next = left === 0
51
+ ? 'That was the last submission: No more drafts are accepted. End your turn.'
52
+ : `Correct every listed entry and submit the draft again. ${describeCount(left, 'submission')} left.`;
53
+ return [...lines, next].join('\n');
54
+ },
55
+ get result() {
56
+ return result;
57
+ },
58
+ };
59
+ }
60
+ function describeCount(count, noun) {
61
+ return `${count} ${noun}${count === 1 ? '' : 's'}`;
62
+ }
@@ -0,0 +1,3 @@
1
+ /** `./agent` entry: converts a prompt by directing an ACP agent through the conversion. */
2
+ export { CONVERSION_SERVER_NAME, type ConversionEvent, convertWithAgent, type ConvertWithAgentOptions, } from './convert-with-agent.js';
3
+ export { MAX_COVERAGE_CHECKS, MAX_SUBMISSIONS, type SessionEvent } from './create-conversion-session.js';
@@ -0,0 +1,2 @@
1
+ export { CONVERSION_SERVER_NAME, convertWithAgent, } from "./convert-with-agent.js";
2
+ export { MAX_COVERAGE_CHECKS, MAX_SUBMISSIONS } from "./create-conversion-session.js";
@@ -1,9 +1,10 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { parseArgs } from 'node:util';
3
3
  import { describeError } from '@williamthorsen/toolbelt.errors';
4
- import { checkCoverage, describeBlock } from "../coverage-map/check-coverage.js";
4
+ import { checkCoverage } from "../coverage-map/check-coverage.js";
5
5
  import { coverageMapSchema } from "../coverage-map/coverage-map-schema.js";
6
- import { readPackageVersion } from "./find-package-root.js";
6
+ import { formatCoverageResult } from "../coverage-map/format-coverage-result.js";
7
+ import { readPackageVersion } from "../package-files/find-package-root.js";
7
8
  const PROGRAM = 'agent-logic check-coverage';
8
9
  const HELP = `Lists the parts of a prompt that a coverage map does not quote.
9
10
 
@@ -85,14 +86,10 @@ function runCli(args, stdout, stderr) {
85
86
  }
86
87
  return 1;
87
88
  }
88
- const { unmapped, quoteProblems } = checkCoverage(prompt, map.data);
89
- for (const { index, quote, occurrences } of quoteProblems) {
90
- stdout.push(`map[${index}]: ${JSON.stringify(quote)} occurs ${occurrences} times\n`);
91
- }
92
- for (const block of unmapped) {
93
- stdout.push(`line ${block.line}: ${describeBlock(prompt, block)}\n`);
94
- }
95
- if (unmapped.length > 0 || quoteProblems.length > 0)
89
+ const lines = formatCoverageResult(prompt, checkCoverage(prompt, map.data));
90
+ for (const line of lines)
91
+ stdout.push(`${line}\n`);
92
+ if (lines.length > 0)
96
93
  return 1;
97
94
  stdout.push(`${PROGRAM}: every block is mapped\n`);
98
95
  return 0;
@@ -1,3 +1,11 @@
1
+ import { z } from 'zod';
1
2
  import type { CommandOutput } from './run.js';
2
3
  /** Runs `agent-logic convert`: converts a draft of a prompt's logic into a config and writes it. */
3
4
  export declare function runConvertCommand(args: readonly string[]): CommandOutput;
5
+ /** The shape of the problems file that `--problems-file` writes for a draft that cannot be converted. */
6
+ export declare const problemsFileSchema: z.ZodObject<{
7
+ problems: z.ZodArray<z.ZodObject<{
8
+ path: z.ZodString;
9
+ message: z.ZodString;
10
+ }, z.core.$strip>>;
11
+ }, z.core.$strip>;
@@ -1,8 +1,9 @@
1
1
  import { readFileSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { parseArgs } from 'node:util';
3
3
  import { describeError } from '@williamthorsen/toolbelt.errors';
4
+ import { z } from 'zod';
4
5
  import { convertPrompt } from "../convert/convert-prompt.js";
5
- import { readPackageVersion } from "./find-package-root.js";
6
+ import { readPackageVersion } from "../package-files/find-package-root.js";
6
7
  const PROGRAM = 'agent-logic convert';
7
8
  const HELP = `Converts a draft of an agent prompt's logic into an agent-logic config.
8
9
 
@@ -36,6 +37,7 @@ export function runConvertCommand(args) {
36
37
  const exitCode = runCli(args, stdout, stderr);
37
38
  return { exitCode, stderr: stderr.join(''), stdout: stdout.join('') };
38
39
  }
40
+ export const problemsFileSchema = z.object({ problems: z.array(z.object({ path: z.string(), message: z.string() })) });
39
41
  function runCli(args, stdout, stderr) {
40
42
  let parsed;
41
43
  try {
@@ -0,0 +1,11 @@
1
+ import type { ConversionEvent, ConvertWithAgentOptions } from '../agent/convert-with-agent.js';
2
+ import type { CommandOutput } from './run.js';
3
+ /** What the command uses that a test replaces. */
4
+ export interface ConvertWithAgentCommandDependencies {
5
+ /** Converts the prompt; defaults to `convertWithAgent`. */
6
+ convert?: (options: ConvertWithAgentOptions) => AsyncIterable<ConversionEvent>;
7
+ /** Writes a progress line as it happens; defaults to the process's stderr. */
8
+ writeProgress?: (line: string) => void;
9
+ }
10
+ /** Runs `agent-logic convert-with-agent`: converts a prompt file on a named agent profile and writes the config. */
11
+ export declare function runConvertWithAgentCommand(args: readonly string[], dependencies?: ConvertWithAgentCommandDependencies): Promise<CommandOutput>;