codeassembly-agent-logic 0.2.0 → 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.
- package/.meta/changelog.json +72 -0
- package/CHANGELOG.md +29 -0
- package/README.md +69 -7
- package/bin/agent-logic.js +1 -0
- package/dist/esm/agent/convert-with-agent.d.ts +53 -0
- package/dist/esm/agent/convert-with-agent.js +111 -0
- package/dist/esm/agent/create-conversion-session.d.ts +34 -0
- package/dist/esm/agent/create-conversion-session.js +62 -0
- package/dist/esm/agent/index.d.ts +3 -0
- package/dist/esm/agent/index.js +2 -0
- package/dist/esm/cli/check-coverage-command.js +7 -10
- package/dist/esm/cli/convert-command.d.ts +8 -0
- package/dist/esm/cli/convert-command.js +3 -1
- package/dist/esm/cli/convert-with-agent-command.d.ts +11 -0
- package/dist/esm/cli/convert-with-agent-command.js +183 -0
- package/dist/esm/cli/index.js +3 -3
- package/dist/esm/cli/run.d.ts +1 -1
- package/dist/esm/cli/run.js +9 -5
- package/dist/esm/client/create-conversion-client.d.ts +44 -0
- package/dist/esm/client/create-conversion-client.js +86 -0
- package/dist/esm/client/index.d.ts +3 -0
- package/dist/esm/client/index.js +1 -0
- package/dist/esm/conversion-protocol/conversion-schemas.d.ts +70 -0
- package/dist/esm/conversion-protocol/conversion-schemas.js +32 -0
- package/dist/esm/coverage-map/format-coverage-result.d.ts +6 -0
- package/dist/esm/coverage-map/format-coverage-result.js +7 -0
- package/dist/esm/react/hooks/describe-load-outcome.d.ts +0 -2
- package/dist/esm/react/hooks/describe-load-outcome.js +0 -3
- package/dist/esm/react/index.d.ts +0 -7
- package/dist/esm/react/index.js +0 -7
- package/dist/esm/server/conversion-store.d.ts +13 -0
- package/dist/esm/server/conversion-store.js +1 -0
- package/dist/esm/server/create-conversion-handler.d.ts +36 -0
- package/dist/esm/server/create-conversion-handler.js +199 -0
- package/dist/esm/server/create-memory-conversion-store.d.ts +12 -0
- package/dist/esm/server/create-memory-conversion-store.js +30 -0
- package/dist/esm/server/index.d.ts +5 -7
- package/dist/esm/server/index.js +2 -6
- package/docs/agent-instructions.md +19 -0
- package/package.json +24 -16
- package/dist/esm/contract/built-in-harnesses.d.ts +0 -22
- package/dist/esm/contract/built-in-harnesses.js +0 -30
- package/dist/esm/contract/conversion-job.d.ts +0 -36
- package/dist/esm/contract/conversion-job.js +0 -17
- package/dist/esm/contract/index.d.ts +0 -4
- package/dist/esm/contract/index.js +0 -3
- package/dist/esm/contract/viewer-contract.d.ts +0 -804
- package/dist/esm/contract/viewer-contract.js +0 -38
- package/dist/esm/react/hooks/conversion-client.d.ts +0 -77
- package/dist/esm/react/hooks/conversion-client.js +0 -132
- package/dist/esm/react/hooks/describe-agent-selection.d.ts +0 -6
- package/dist/esm/react/hooks/describe-agent-selection.js +0 -18
- package/dist/esm/react/hooks/useAgentBridge.d.ts +0 -28
- package/dist/esm/react/hooks/useAgentBridge.js +0 -52
- package/dist/esm/react/hooks/useAgentSync.d.ts +0 -29
- package/dist/esm/react/hooks/useAgentSync.js +0 -75
- package/dist/esm/react/hooks/useConversion.d.ts +0 -31
- package/dist/esm/react/hooks/useConversion.js +0 -177
- package/dist/esm/react/hooks/useHarnessList.d.ts +0 -26
- package/dist/esm/react/hooks/useHarnessList.js +0 -24
- package/dist/esm/react/hooks/usePromptDirectory.d.ts +0 -27
- package/dist/esm/react/hooks/usePromptDirectory.js +0 -34
- package/dist/esm/server/conversion-job-implementation.d.ts +0 -11
- package/dist/esm/server/conversion-job-implementation.js +0 -84
- package/dist/esm/server/create-prompts-app.d.ts +0 -26
- package/dist/esm/server/create-prompts-app.js +0 -41
- package/dist/esm/server/create-viewer-server-plugins.d.ts +0 -15
- package/dist/esm/server/create-viewer-server-plugins.js +0 -76
- package/dist/esm/server/prompt-directory-schemas.d.ts +0 -30
- package/dist/esm/server/prompt-directory-schemas.js +0 -11
- package/dist/esm/server/prompt-directory.d.ts +0 -40
- package/dist/esm/server/prompt-directory.js +0 -86
- package/dist/esm/server/viewer-contract-implementation.d.ts +0 -12
- package/dist/esm/server/viewer-contract-implementation.js +0 -85
- /package/dist/esm/{cli → package-files}/find-package-root.d.ts +0 -0
- /package/dist/esm/{cli → package-files}/find-package-root.js +0 -0
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { describeError } from '@williamthorsen/toolbelt.errors';
|
|
5
|
+
import { readPackageVersion } from "../package-files/find-package-root.js";
|
|
6
|
+
const PROGRAM = 'agent-logic convert-with-agent';
|
|
7
|
+
const AGENT_NAMES = ['antigravity', 'claude-code', 'codex'];
|
|
8
|
+
const INTERRUPTED_EXIT_CODE = 130;
|
|
9
|
+
const HELP = `Converts an agent prompt into an agent-logic config by directing an ACP agent through the conversion.
|
|
10
|
+
|
|
11
|
+
Usage: ${PROGRAM} [options] <prompt-file> [output-file]
|
|
12
|
+
|
|
13
|
+
Arguments:
|
|
14
|
+
prompt-file the prompt, read verbatim
|
|
15
|
+
output-file where to write the config; written only when the config is valid.
|
|
16
|
+
Default: <base>.agent-logic.json beside the prompt
|
|
17
|
+
|
|
18
|
+
Options:
|
|
19
|
+
--agent <name> the agent profile: ${AGENT_NAMES.join(', ')} (required)
|
|
20
|
+
-h, --help print this help
|
|
21
|
+
-V, --version print the version
|
|
22
|
+
|
|
23
|
+
The command needs the optional peers @williamthorsen/toolbelt.acp and
|
|
24
|
+
@modelcontextprotocol/server, and the agent's harness installed and signed in.
|
|
25
|
+
It reports each coverage check and draft submission on stderr as it happens.
|
|
26
|
+
|
|
27
|
+
Exit codes:
|
|
28
|
+
0 the config was written
|
|
29
|
+
1 the agent's last draft has problems, which are listed
|
|
30
|
+
2 the arguments or files are wrong, or the run failed
|
|
31
|
+
3 the agent reports the prompt out of scope
|
|
32
|
+
130 the run was interrupted, and the conversion stopped its agent
|
|
33
|
+
|
|
34
|
+
Example:
|
|
35
|
+
${PROGRAM} --agent claude-code prompts/refund-request.md
|
|
36
|
+
`;
|
|
37
|
+
export async function runConvertWithAgentCommand(args, dependencies = {}) {
|
|
38
|
+
const stdout = [];
|
|
39
|
+
const stderr = [];
|
|
40
|
+
const exitCode = await runCli(args, dependencies, stdout, stderr);
|
|
41
|
+
return { exitCode, stderr: stderr.join(''), stdout: stdout.join('') };
|
|
42
|
+
}
|
|
43
|
+
function deriveOutputPath(promptFile) {
|
|
44
|
+
const base = path.basename(promptFile, path.extname(promptFile));
|
|
45
|
+
return path.join(path.dirname(promptFile), `${base}.agent-logic.json`);
|
|
46
|
+
}
|
|
47
|
+
function describeEvent(event) {
|
|
48
|
+
switch (event.type) {
|
|
49
|
+
case 'coverage-checked':
|
|
50
|
+
return `coverage check ${event.check}: ${event.unmapped} unmapped blocks, ${event.quoteProblems} quote problems`;
|
|
51
|
+
case 'draft-submitted':
|
|
52
|
+
return `draft ${event.submission}: ${event.outcome === 'problems' ? `${event.problems} problems` : event.outcome}`;
|
|
53
|
+
case 'message':
|
|
54
|
+
return undefined;
|
|
55
|
+
case 'result': {
|
|
56
|
+
const usage = event.usage === undefined ? undefined : `${event.usage.totalTokens} tokens`;
|
|
57
|
+
const cost = event.cost === undefined ? undefined : `${event.cost.amount} ${event.cost.currency}`;
|
|
58
|
+
const parts = [usage, cost].filter((part) => part !== undefined);
|
|
59
|
+
return parts.length === 0 ? undefined : `used ${parts.join(', ')}`;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function isAgentName(value) {
|
|
64
|
+
return AGENT_NAMES.some((name) => name === value);
|
|
65
|
+
}
|
|
66
|
+
async function loadAgent(agentName, convert) {
|
|
67
|
+
const acp = await import('@williamthorsen/toolbelt.acp/proposed');
|
|
68
|
+
const agent = agentName === 'antigravity'
|
|
69
|
+
? acp.antigravityProfile()
|
|
70
|
+
: agentName === 'claude-code'
|
|
71
|
+
? acp.claudeCodeProfile()
|
|
72
|
+
: acp.codexProfile();
|
|
73
|
+
return { agent, convert: convert ?? (await import("../agent/convert-with-agent.js")).convertWithAgent };
|
|
74
|
+
}
|
|
75
|
+
function reportResult(result, outputFile, stdout, stderr) {
|
|
76
|
+
if ('outOfScope' in result) {
|
|
77
|
+
stderr.push(`${PROGRAM}: the prompt is out of scope: ${result.outOfScope.reason}\n`);
|
|
78
|
+
return 3;
|
|
79
|
+
}
|
|
80
|
+
if (!result.ok) {
|
|
81
|
+
for (const { path: problemPath, message } of result.problems) {
|
|
82
|
+
stderr.push(`${PROGRAM}: ${problemPath === '' ? '' : `${problemPath}: `}${message}\n`);
|
|
83
|
+
}
|
|
84
|
+
stderr.push(`${PROGRAM}: wrote nothing; the agent's last draft has these problems\n`);
|
|
85
|
+
return 1;
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
writeFileSync(outputFile, result.text);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
stderr.push(`${PROGRAM}: ${describeError(error)}; pass a path in a directory that exists and is writable\n`);
|
|
92
|
+
return 2;
|
|
93
|
+
}
|
|
94
|
+
stdout.push(`${PROGRAM}: wrote ${outputFile}\n`);
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
async function runCli(args, dependencies, stdout, stderr) {
|
|
98
|
+
let parsed;
|
|
99
|
+
try {
|
|
100
|
+
parsed = parseArgs({
|
|
101
|
+
args: [...args],
|
|
102
|
+
allowPositionals: true,
|
|
103
|
+
options: {
|
|
104
|
+
agent: { type: 'string' },
|
|
105
|
+
help: { type: 'boolean', short: 'h' },
|
|
106
|
+
version: { type: 'boolean', short: 'V' },
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
stderr.push(`${PROGRAM}: ${describeError(error)}; run ${PROGRAM} --help for usage\n`);
|
|
112
|
+
return 2;
|
|
113
|
+
}
|
|
114
|
+
if (parsed.values.help === true) {
|
|
115
|
+
stdout.push(HELP);
|
|
116
|
+
return 0;
|
|
117
|
+
}
|
|
118
|
+
if (parsed.values.version === true) {
|
|
119
|
+
stdout.push(`${readPackageVersion()}\n`);
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
const [promptFile, outputArgument, ...extra] = parsed.positionals;
|
|
123
|
+
if (promptFile === undefined || extra.length > 0) {
|
|
124
|
+
stderr.push(`${PROGRAM}: expected 1 or 2 arguments, received ${parsed.positionals.length}; run ${PROGRAM} --help for usage\n`);
|
|
125
|
+
return 2;
|
|
126
|
+
}
|
|
127
|
+
const agentName = parsed.values.agent;
|
|
128
|
+
if (!isAgentName(agentName)) {
|
|
129
|
+
const received = agentName === undefined ? 'none' : JSON.stringify(agentName);
|
|
130
|
+
stderr.push(`${PROGRAM}: --agent must be one of ${AGENT_NAMES.join(', ')}, received ${received}\n`);
|
|
131
|
+
return 2;
|
|
132
|
+
}
|
|
133
|
+
const outputFile = outputArgument ?? deriveOutputPath(promptFile);
|
|
134
|
+
let prompt;
|
|
135
|
+
try {
|
|
136
|
+
prompt = readFileSync(promptFile, 'utf8');
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
stderr.push(`${PROGRAM}: ${describeError(error)}; pass the path of an existing file\n`);
|
|
140
|
+
return 2;
|
|
141
|
+
}
|
|
142
|
+
const result = await runConversion({ agentName, prompt, name: path.basename(promptFile) }, dependencies, stderr);
|
|
143
|
+
return typeof result === 'number' ? result : reportResult(result, outputFile, stdout, stderr);
|
|
144
|
+
}
|
|
145
|
+
async function runConversion({ agentName, prompt, name }, dependencies, stderr) {
|
|
146
|
+
const writeProgress = dependencies.writeProgress ??
|
|
147
|
+
((line) => {
|
|
148
|
+
process.stderr.write(`${line}\n`);
|
|
149
|
+
});
|
|
150
|
+
const controller = new AbortController();
|
|
151
|
+
function interrupt() {
|
|
152
|
+
controller.abort(new Error('Interrupted.'));
|
|
153
|
+
}
|
|
154
|
+
process.once('SIGINT', interrupt);
|
|
155
|
+
let result;
|
|
156
|
+
try {
|
|
157
|
+
const { agent, convert } = await loadAgent(agentName, dependencies.convert);
|
|
158
|
+
const events = convert({ prompt, name, agent, signal: controller.signal });
|
|
159
|
+
for await (const event of events) {
|
|
160
|
+
const line = describeEvent(event);
|
|
161
|
+
if (line !== undefined)
|
|
162
|
+
writeProgress(`${PROGRAM}: ${line}`);
|
|
163
|
+
if (event.type === 'result')
|
|
164
|
+
result = event.result;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
if (controller.signal.aborted) {
|
|
169
|
+
stderr.push(`${PROGRAM}: interrupted; wrote nothing\n`);
|
|
170
|
+
return INTERRUPTED_EXIT_CODE;
|
|
171
|
+
}
|
|
172
|
+
stderr.push(`${PROGRAM}: ${describeError(error)}\n`);
|
|
173
|
+
return 2;
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
process.off('SIGINT', interrupt);
|
|
177
|
+
}
|
|
178
|
+
if (result === undefined) {
|
|
179
|
+
stderr.push(`${PROGRAM}: the conversion ended without a result\n`);
|
|
180
|
+
return 2;
|
|
181
|
+
}
|
|
182
|
+
return result;
|
|
183
|
+
}
|
package/dist/esm/cli/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import process from 'node:process';
|
|
2
2
|
import { run } from "./run.js";
|
|
3
|
-
function main() {
|
|
4
|
-
const output = run(process.argv.slice(2));
|
|
3
|
+
async function main() {
|
|
4
|
+
const output = await run(process.argv.slice(2));
|
|
5
5
|
if (output.stdout !== '')
|
|
6
6
|
process.stdout.write(output.stdout);
|
|
7
7
|
if (output.stderr !== '')
|
|
8
8
|
process.stderr.write(output.stderr);
|
|
9
9
|
process.exit(output.exitCode);
|
|
10
10
|
}
|
|
11
|
-
main();
|
|
11
|
+
await main();
|
package/dist/esm/cli/run.d.ts
CHANGED
|
@@ -5,4 +5,4 @@ export interface CommandOutput {
|
|
|
5
5
|
stdout: string;
|
|
6
6
|
}
|
|
7
7
|
/** Dispatches the bin's arguments to a command and returns its output without touching the process. */
|
|
8
|
-
export declare function run(argv: readonly string[]): CommandOutput
|
|
8
|
+
export declare function run(argv: readonly string[]): Promise<CommandOutput>;
|
package/dist/esm/cli/run.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
+
import { findPackageRoot, readPackageVersion } from "../package-files/find-package-root.js";
|
|
3
4
|
import { runCheckCoverageCommand } from "./check-coverage-command.js";
|
|
4
5
|
import { runConvertCommand } from "./convert-command.js";
|
|
5
|
-
import {
|
|
6
|
+
import { runConvertWithAgentCommand } from "./convert-with-agent-command.js";
|
|
6
7
|
const USAGE = `Usage: agent-logic <command> [arguments]
|
|
7
8
|
|
|
8
9
|
Commands:
|
|
9
|
-
convert
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
convert convert a draft of a prompt's logic into an agent-logic config
|
|
11
|
+
convert-with-agent convert a prompt into an agent-logic config on an ACP agent
|
|
12
|
+
check-coverage check a coverage map of a prompt against the prompt
|
|
13
|
+
rules print the extraction rules by which a model drafts a prompt's logic
|
|
12
14
|
|
|
13
15
|
Run agent-logic <command> --help for a command's arguments and options.
|
|
14
16
|
|
|
@@ -16,7 +18,7 @@ Options:
|
|
|
16
18
|
-h, --help print this help
|
|
17
19
|
-V, --version print the version
|
|
18
20
|
`;
|
|
19
|
-
export function run(argv) {
|
|
21
|
+
export async function run(argv) {
|
|
20
22
|
const [command, ...args] = argv;
|
|
21
23
|
switch (command) {
|
|
22
24
|
case undefined:
|
|
@@ -30,6 +32,8 @@ export function run(argv) {
|
|
|
30
32
|
return runCheckCoverageCommand(args);
|
|
31
33
|
case 'convert':
|
|
32
34
|
return runConvertCommand(args);
|
|
35
|
+
case 'convert-with-agent':
|
|
36
|
+
return runConvertWithAgentCommand(args);
|
|
33
37
|
case 'rules':
|
|
34
38
|
return runRulesCommand(args);
|
|
35
39
|
default:
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type ConversionState, type StartConversionRequest } from '../conversion-protocol/conversion-schemas.js';
|
|
2
|
+
import type { Problem } from '../schema/validate-config.js';
|
|
3
|
+
/**
|
|
4
|
+
* A request's outcome: the conversion's state, or why there is none. `not-found` is a conversion that the server does
|
|
5
|
+
* not have, such as one that it dropped after its retention period; `failed` covers every other failure, the problems
|
|
6
|
+
* naming why.
|
|
7
|
+
*/
|
|
8
|
+
export type ConversionOutcome = {
|
|
9
|
+
ok: true;
|
|
10
|
+
conversion: ConversionState;
|
|
11
|
+
} | {
|
|
12
|
+
ok: false;
|
|
13
|
+
reason: 'failed' | 'not-found';
|
|
14
|
+
problems: Problem[];
|
|
15
|
+
};
|
|
16
|
+
/** Starts, reads, cancels, and watches conversions on a server that `createConversionHandler` serves. */
|
|
17
|
+
export interface ConversionClient {
|
|
18
|
+
/** Cancels a conversion; a conversion that had already ended is reported with its ended state. */
|
|
19
|
+
cancel(id: string): Promise<ConversionOutcome>;
|
|
20
|
+
/** Returns the conversion's current state. */
|
|
21
|
+
read(id: string): Promise<ConversionOutcome>;
|
|
22
|
+
/** Starts a conversion and returns its `running` state. */
|
|
23
|
+
start(request: StartConversionRequest): Promise<ConversionOutcome>;
|
|
24
|
+
/**
|
|
25
|
+
* Reads the conversion every `intervalMs` (2 s by default) and yields each outcome, stopping after an ended state or
|
|
26
|
+
* a failed outcome. Returns without yielding again once the signal aborts.
|
|
27
|
+
*/
|
|
28
|
+
watch(id: string, options?: {
|
|
29
|
+
signal?: AbortSignal;
|
|
30
|
+
intervalMs?: number;
|
|
31
|
+
}): AsyncGenerator<ConversionOutcome>;
|
|
32
|
+
}
|
|
33
|
+
export interface ConversionClientOptions {
|
|
34
|
+
/** The URL of the conversions resource, at which the server's handler serves its `basePath`. */
|
|
35
|
+
url: string;
|
|
36
|
+
fetch?: typeof globalThis.fetch;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Creates a client for the conversion routes, which validates every response body.
|
|
40
|
+
*
|
|
41
|
+
* @stage proposed
|
|
42
|
+
* @experimental
|
|
43
|
+
*/
|
|
44
|
+
export declare function createConversionClient({ url, fetch, }: ConversionClientOptions): ConversionClient;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { describeError } from '@williamthorsen/toolbelt.errors';
|
|
2
|
+
import { conversionStateSchema, problemsBodySchema, } from "../conversion-protocol/conversion-schemas.js";
|
|
3
|
+
const DEFAULT_WATCH_INTERVAL_MS = 2000;
|
|
4
|
+
export function createConversionClient({ url, fetch = globalThis.fetch.bind(globalThis), }) {
|
|
5
|
+
const collectionUrl = url.replace(/\/+$/, '');
|
|
6
|
+
async function send(target, init, successStatuses) {
|
|
7
|
+
let response;
|
|
8
|
+
try {
|
|
9
|
+
response = await fetch(target, init);
|
|
10
|
+
}
|
|
11
|
+
catch (error) {
|
|
12
|
+
return fail(`The conversion server could not be reached (${describeError(error)}).`);
|
|
13
|
+
}
|
|
14
|
+
let body;
|
|
15
|
+
try {
|
|
16
|
+
body = await response.json();
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return fail(`The conversion server answered ${response.status} with a body that is not JSON.`);
|
|
20
|
+
}
|
|
21
|
+
const { status } = response;
|
|
22
|
+
if (successStatuses.includes(status)) {
|
|
23
|
+
return readBody(conversionStateSchema, body, status, (conversion) => ({ ok: true, conversion }));
|
|
24
|
+
}
|
|
25
|
+
const reason = status === 404 ? 'not-found' : 'failed';
|
|
26
|
+
return readBody(problemsBodySchema, body, status, ({ problems }) => ({ ok: false, reason, problems }));
|
|
27
|
+
}
|
|
28
|
+
async function readOnce(id, signal) {
|
|
29
|
+
if (isAborted(signal))
|
|
30
|
+
return undefined;
|
|
31
|
+
const outcome = await send(toConversionUrl(id), { method: 'GET', ...(signal !== undefined && { signal }) }, [200]);
|
|
32
|
+
return isAborted(signal) ? undefined : outcome;
|
|
33
|
+
}
|
|
34
|
+
function toConversionUrl(id) {
|
|
35
|
+
return `${collectionUrl}/${encodeURIComponent(id)}`;
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
async cancel(id) {
|
|
39
|
+
return send(toConversionUrl(id), { method: 'DELETE' }, [200, 409]);
|
|
40
|
+
},
|
|
41
|
+
async read(id) {
|
|
42
|
+
return send(toConversionUrl(id), { method: 'GET' }, [200]);
|
|
43
|
+
},
|
|
44
|
+
async start(request) {
|
|
45
|
+
const init = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(request) };
|
|
46
|
+
return send(collectionUrl, init, [201]);
|
|
47
|
+
},
|
|
48
|
+
async *watch(id, { signal, intervalMs = DEFAULT_WATCH_INTERVAL_MS } = {}) {
|
|
49
|
+
let outcome = await readOnce(id, signal);
|
|
50
|
+
while (outcome !== undefined) {
|
|
51
|
+
yield outcome;
|
|
52
|
+
if (!outcome.ok || outcome.conversion.status !== 'running')
|
|
53
|
+
return;
|
|
54
|
+
await waitFor(intervalMs, signal);
|
|
55
|
+
outcome = await readOnce(id, signal);
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function fail(message) {
|
|
61
|
+
return { ok: false, reason: 'failed', problems: [{ path: '', message }] };
|
|
62
|
+
}
|
|
63
|
+
function isAborted(signal) {
|
|
64
|
+
return signal?.aborted === true;
|
|
65
|
+
}
|
|
66
|
+
function readBody(schema, body, status, toOutcome) {
|
|
67
|
+
const parsed = schema.safeParse(body);
|
|
68
|
+
return parsed.success
|
|
69
|
+
? toOutcome(parsed.data)
|
|
70
|
+
: fail(`The conversion server answered ${status} with a body of an unexpected shape.`);
|
|
71
|
+
}
|
|
72
|
+
function waitFor(durationMs, signal) {
|
|
73
|
+
return new Promise((resolve) => {
|
|
74
|
+
if (isAborted(signal)) {
|
|
75
|
+
resolve();
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const timer = setTimeout(finish, durationMs);
|
|
79
|
+
signal?.addEventListener('abort', finish, { once: true });
|
|
80
|
+
function finish() {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
signal?.removeEventListener('abort', finish);
|
|
83
|
+
resolve();
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** `./client` entry: the browser client of the conversion routes that `./server`'s handler serves. */
|
|
2
|
+
export type { ConversionResult, ConversionState, EndedConversionState, StartConversionRequest, } from '../conversion-protocol/conversion-schemas.js';
|
|
3
|
+
export { type ConversionClient, type ConversionClientOptions, type ConversionOutcome, createConversionClient, } from './create-conversion-client.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createConversionClient, } from "./create-conversion-client.js";
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { Problem } from '../schema/validate-config.js';
|
|
3
|
+
/** The largest prompt that a start request accepts, in bytes of UTF-8. */
|
|
4
|
+
export declare const MAX_PROMPT_BYTES: number;
|
|
5
|
+
/** The longest name that a start request accepts, in characters. */
|
|
6
|
+
export declare const MAX_NAME_LENGTH = 100;
|
|
7
|
+
/** The body of every error response: the problems that refused the request. */
|
|
8
|
+
export declare const problemsBodySchema: z.ZodObject<{
|
|
9
|
+
problems: z.ZodArray<z.ZodType<Problem, unknown, z.core.$ZodTypeInternals<Problem, unknown>>>;
|
|
10
|
+
}, z.core.$strip>;
|
|
11
|
+
/**
|
|
12
|
+
* The body that starts a conversion: the prompt, verbatim, and its file name, from which the config's root id derives.
|
|
13
|
+
*/
|
|
14
|
+
export declare const startConversionRequestSchema: z.ZodObject<{
|
|
15
|
+
prompt: z.ZodString;
|
|
16
|
+
name: z.ZodString;
|
|
17
|
+
}, z.core.$strip>;
|
|
18
|
+
/** A conversion's result: the config text, the problems of the last draft, or an out-of-scope verdict. */
|
|
19
|
+
export declare const conversionResultSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
20
|
+
ok: z.ZodLiteral<true>;
|
|
21
|
+
text: z.ZodString;
|
|
22
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
23
|
+
ok: z.ZodLiteral<false>;
|
|
24
|
+
problems: z.ZodArray<z.ZodType<Problem, unknown, z.core.$ZodTypeInternals<Problem, unknown>>>;
|
|
25
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
26
|
+
ok: z.ZodLiteral<false>;
|
|
27
|
+
outOfScope: z.ZodObject<{
|
|
28
|
+
reason: z.ZodString;
|
|
29
|
+
}, z.core.$strip>;
|
|
30
|
+
}, z.core.$strip>]>;
|
|
31
|
+
/** A conversion's state: `running` until its deadline, then one of the ended states, which never change. */
|
|
32
|
+
export declare const conversionStateSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
33
|
+
status: z.ZodLiteral<"running">;
|
|
34
|
+
id: z.ZodString;
|
|
35
|
+
name: z.ZodString;
|
|
36
|
+
startedAt: z.ZodISODateTime;
|
|
37
|
+
deadline: z.ZodISODateTime;
|
|
38
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
39
|
+
status: z.ZodLiteral<"done">;
|
|
40
|
+
id: z.ZodString;
|
|
41
|
+
name: z.ZodString;
|
|
42
|
+
result: z.ZodUnion<readonly [z.ZodObject<{
|
|
43
|
+
ok: z.ZodLiteral<true>;
|
|
44
|
+
text: z.ZodString;
|
|
45
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
46
|
+
ok: z.ZodLiteral<false>;
|
|
47
|
+
problems: z.ZodArray<z.ZodType<Problem, unknown, z.core.$ZodTypeInternals<Problem, unknown>>>;
|
|
48
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
49
|
+
ok: z.ZodLiteral<false>;
|
|
50
|
+
outOfScope: z.ZodObject<{
|
|
51
|
+
reason: z.ZodString;
|
|
52
|
+
}, z.core.$strip>;
|
|
53
|
+
}, z.core.$strip>]>;
|
|
54
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
55
|
+
status: z.ZodLiteral<"failed">;
|
|
56
|
+
id: z.ZodString;
|
|
57
|
+
name: z.ZodString;
|
|
58
|
+
reason: z.ZodString;
|
|
59
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
60
|
+
status: z.ZodLiteral<"cancelled">;
|
|
61
|
+
id: z.ZodString;
|
|
62
|
+
name: z.ZodString;
|
|
63
|
+
}, z.core.$strip>], "status">;
|
|
64
|
+
export type ConversionResult = z.output<typeof conversionResultSchema>;
|
|
65
|
+
export type ConversionState = z.output<typeof conversionStateSchema>;
|
|
66
|
+
export type EndedConversionState = Exclude<ConversionState, {
|
|
67
|
+
status: 'running';
|
|
68
|
+
}>;
|
|
69
|
+
export type ProblemsBody = z.output<typeof problemsBodySchema>;
|
|
70
|
+
export type StartConversionRequest = z.output<typeof startConversionRequestSchema>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export const MAX_PROMPT_BYTES = 1024 * 1024;
|
|
3
|
+
export const MAX_NAME_LENGTH = 100;
|
|
4
|
+
const problemSchema = z.object({ path: z.string(), message: z.string() });
|
|
5
|
+
export const problemsBodySchema = z.object({ problems: z.array(problemSchema) });
|
|
6
|
+
export const startConversionRequestSchema = z.object({
|
|
7
|
+
prompt: z
|
|
8
|
+
.string()
|
|
9
|
+
.refine((value) => value !== '', 'Enter a prompt')
|
|
10
|
+
.refine((value) => new TextEncoder().encode(value).byteLength <= MAX_PROMPT_BYTES, `The prompt must not exceed ${MAX_PROMPT_BYTES} bytes`),
|
|
11
|
+
name: z
|
|
12
|
+
.string()
|
|
13
|
+
.max(MAX_NAME_LENGTH)
|
|
14
|
+
.refine((value) => value.trim() !== '', 'Enter a name'),
|
|
15
|
+
});
|
|
16
|
+
export const conversionResultSchema = z.union([
|
|
17
|
+
z.object({ ok: z.literal(true), text: z.string() }),
|
|
18
|
+
z.object({ ok: z.literal(false), problems: z.array(problemSchema) }),
|
|
19
|
+
z.object({ ok: z.literal(false), outOfScope: z.object({ reason: z.string() }) }),
|
|
20
|
+
]);
|
|
21
|
+
export const conversionStateSchema = z.discriminatedUnion('status', [
|
|
22
|
+
z.object({
|
|
23
|
+
status: z.literal('running'),
|
|
24
|
+
id: z.string(),
|
|
25
|
+
name: z.string(),
|
|
26
|
+
startedAt: z.iso.datetime(),
|
|
27
|
+
deadline: z.iso.datetime(),
|
|
28
|
+
}),
|
|
29
|
+
z.object({ status: z.literal('done'), id: z.string(), name: z.string(), result: conversionResultSchema }),
|
|
30
|
+
z.object({ status: z.literal('failed'), id: z.string(), name: z.string(), reason: z.string() }),
|
|
31
|
+
z.object({ status: z.literal('cancelled'), id: z.string(), name: z.string() }),
|
|
32
|
+
]);
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type CoverageResult } from './check-coverage.js';
|
|
2
|
+
/**
|
|
3
|
+
* Formats a coverage check's findings as lines: each quote that does not occur exactly once, as `map[<index>]: …`,
|
|
4
|
+
* then each unmapped block, as `line <N>: <opening words>`. Returns no lines when every block is mapped.
|
|
5
|
+
*/
|
|
6
|
+
export declare function formatCoverageResult(prompt: string, { unmapped, quoteProblems }: CoverageResult): string[];
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { describeBlock } from "./check-coverage.js";
|
|
2
|
+
export function formatCoverageResult(prompt, { unmapped, quoteProblems }) {
|
|
3
|
+
return [
|
|
4
|
+
...quoteProblems.map(({ index, quote, occurrences }) => `map[${index}]: ${JSON.stringify(quote)} occurs ${occurrences} times`),
|
|
5
|
+
...unmapped.map((block) => `line ${block.line}: ${describeBlock(prompt, block)}`),
|
|
6
|
+
];
|
|
7
|
+
}
|
|
@@ -5,8 +5,6 @@ import type { Problem } from '../../schema/validate-config.js';
|
|
|
5
5
|
* findings.
|
|
6
6
|
*/
|
|
7
7
|
export declare function describeLoaded(source: string, config: AgentLogicConfig): string;
|
|
8
|
-
/** Returns the announcement of a chart that the agent loaded, with the same counts as `describeLoaded`. */
|
|
9
|
-
export declare function describeLoadedByAgent(source: string, config: AgentLogicConfig): string;
|
|
10
8
|
/** Returns the announcement of a failed load: its problem, or the count of its problems. */
|
|
11
9
|
export declare function describeNotLoaded(source: string, problems: Problem[]): string;
|
|
12
10
|
/** Returns the message for a URL that names an example that does not exist, with the names of those that do. */
|
|
@@ -3,9 +3,6 @@ import { describeConfig, listGaps } from "../../layout/describe-config.js";
|
|
|
3
3
|
export function describeLoaded(source, config) {
|
|
4
4
|
return [`${source} loaded.`, ...countListed(config)].join(' ');
|
|
5
5
|
}
|
|
6
|
-
export function describeLoadedByAgent(source, config) {
|
|
7
|
-
return [`Agent loaded ${source}.`, ...countListed(config)].join(' ');
|
|
8
|
-
}
|
|
9
6
|
export function describeNotLoaded(source, problems) {
|
|
10
7
|
const [first, second] = problems;
|
|
11
8
|
if (first !== undefined && second === undefined)
|
|
@@ -3,22 +3,15 @@ export * from './canvas/canvas-key-entries.js';
|
|
|
3
3
|
export * from './canvas/list-chart-marks.js';
|
|
4
4
|
export * from './canvas/marks.js';
|
|
5
5
|
export * from './canvas/StatechartCanvas.js';
|
|
6
|
-
export * from './hooks/conversion-client.js';
|
|
7
|
-
export * from './hooks/describe-agent-selection.js';
|
|
8
6
|
export * from './hooks/describe-load-outcome.js';
|
|
9
7
|
export * from './hooks/download-config.js';
|
|
10
8
|
export * from './hooks/example-location.js';
|
|
11
9
|
export * from './hooks/label-source.js';
|
|
12
10
|
export * from './hooks/parse-config-text.js';
|
|
13
|
-
export * from './hooks/useAgentBridge.js';
|
|
14
|
-
export * from './hooks/useAgentSync.js';
|
|
15
11
|
export * from './hooks/useChartLayout.js';
|
|
16
|
-
export * from './hooks/useConversion.js';
|
|
17
12
|
export * from './hooks/useConvertDraft.js';
|
|
18
13
|
export * from './hooks/useDocumentTitle.js';
|
|
19
14
|
export * from './hooks/useEscapeToClear.js';
|
|
20
|
-
export * from './hooks/useHarnessList.js';
|
|
21
|
-
export * from './hooks/usePromptDirectory.js';
|
|
22
15
|
export * from './hooks/useSelection.js';
|
|
23
16
|
export * from './hooks/useShowAmbient.js';
|
|
24
17
|
export * from './hooks/useUnknownExample.js';
|
package/dist/esm/react/index.js
CHANGED
|
@@ -2,22 +2,15 @@ export * from "./canvas/canvas-key-entries.js";
|
|
|
2
2
|
export * from "./canvas/list-chart-marks.js";
|
|
3
3
|
export * from "./canvas/marks.js";
|
|
4
4
|
export * from "./canvas/StatechartCanvas.js";
|
|
5
|
-
export * from "./hooks/conversion-client.js";
|
|
6
|
-
export * from "./hooks/describe-agent-selection.js";
|
|
7
5
|
export * from "./hooks/describe-load-outcome.js";
|
|
8
6
|
export * from "./hooks/download-config.js";
|
|
9
7
|
export * from "./hooks/example-location.js";
|
|
10
8
|
export * from "./hooks/label-source.js";
|
|
11
9
|
export * from "./hooks/parse-config-text.js";
|
|
12
|
-
export * from "./hooks/useAgentBridge.js";
|
|
13
|
-
export * from "./hooks/useAgentSync.js";
|
|
14
10
|
export * from "./hooks/useChartLayout.js";
|
|
15
|
-
export * from "./hooks/useConversion.js";
|
|
16
11
|
export * from "./hooks/useConvertDraft.js";
|
|
17
12
|
export * from "./hooks/useDocumentTitle.js";
|
|
18
13
|
export * from "./hooks/useEscapeToClear.js";
|
|
19
|
-
export * from "./hooks/useHarnessList.js";
|
|
20
|
-
export * from "./hooks/usePromptDirectory.js";
|
|
21
14
|
export * from "./hooks/useSelection.js";
|
|
22
15
|
export * from "./hooks/useShowAmbient.js";
|
|
23
16
|
export * from "./hooks/useUnknownExample.js";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ConversionState, EndedConversionState } from '../conversion-protocol/conversion-schemas.js';
|
|
2
|
+
/**
|
|
3
|
+
* Where the conversion handler keeps each conversion's state. An ended state is written only over a running one, so
|
|
4
|
+
* that a cancel, a timeout, and a run's own end cannot overwrite each other.
|
|
5
|
+
*/
|
|
6
|
+
export interface ConversionStore {
|
|
7
|
+
/** Adds a conversion, whose id is new. */
|
|
8
|
+
create(state: ConversionState): Promise<void>;
|
|
9
|
+
/** Returns the conversion's state, or `undefined` when the store does not have it. */
|
|
10
|
+
read(id: string): Promise<ConversionState | undefined>;
|
|
11
|
+
/** Replaces the conversion's state with the ended one only when it is `running`, and reports whether it did. */
|
|
12
|
+
finish(id: string, ended: EndedConversionState): Promise<boolean>;
|
|
13
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { AgentProfile } from '@williamthorsen/toolbelt.acp/proposed';
|
|
2
|
+
import { type ConversionEvent, type ConvertWithAgentOptions } from '../agent/convert-with-agent.js';
|
|
3
|
+
import type { ConversionStore } from './conversion-store.js';
|
|
4
|
+
/** How the host serves conversions. */
|
|
5
|
+
export interface ConversionHandlerOptions {
|
|
6
|
+
/** The agent profile on which every conversion runs. */
|
|
7
|
+
readonly agent: AgentProfile;
|
|
8
|
+
/** Where the handler keeps each conversion's state. */
|
|
9
|
+
readonly store: ConversionStore;
|
|
10
|
+
/** Reports whether the handler may serve the request; a refused request is answered `403`. */
|
|
11
|
+
readonly authorize: (request: Request) => boolean | Promise<boolean>;
|
|
12
|
+
/** How long a conversion may run before it fails. */
|
|
13
|
+
readonly timeoutMs: number;
|
|
14
|
+
/** The path of the conversions resource, such as `/api/conversions`; `''`, the root, by default. */
|
|
15
|
+
readonly basePath?: string;
|
|
16
|
+
}
|
|
17
|
+
/** A conversion run, as `convertWithAgent` runs it. */
|
|
18
|
+
export type ConvertFunction = (options: ConvertWithAgentOptions) => AsyncIterable<ConversionEvent>;
|
|
19
|
+
/**
|
|
20
|
+
* Creates a Fetch handler that serves conversions under `basePath`: `POST {basePath}` starts one and answers `201` with
|
|
21
|
+
* its `running` state and a `Location` of `{basePath}/{id}`; `GET {basePath}/{id}` answers `200` with its state; and
|
|
22
|
+
* `DELETE {basePath}/{id}` cancels it, answering `200` with the `cancelled` state, or `409` with the ended state when
|
|
23
|
+
* it had already ended. Every conversion runs in this process through `convertWithAgent` and fails once `timeoutMs`
|
|
24
|
+
* elapses; a read of a `running` conversion past its deadline reports it failed even when another process holds the
|
|
25
|
+
* run.
|
|
26
|
+
*
|
|
27
|
+
* Every error body is `{ problems }`: `400` for a body that is not a valid start request, `403` for a request that
|
|
28
|
+
* `authorize` refuses, `404` for an unknown path or conversion, `405` for a method that the path does not serve, `413`
|
|
29
|
+
* for a body past 4 MiB, and `500` for a store or an `authorize` that fails.
|
|
30
|
+
*
|
|
31
|
+
* @stage proposed
|
|
32
|
+
* @experimental
|
|
33
|
+
*/
|
|
34
|
+
export declare const createConversionHandler: (options: ConversionHandlerOptions) => (request: Request) => Promise<Response>;
|
|
35
|
+
/** Returns `createConversionHandler` running conversions through `convert`, which tests replace. */
|
|
36
|
+
export declare function createConversionHandlerWith(convert: ConvertFunction): (options: ConversionHandlerOptions) => (request: Request) => Promise<Response>;
|