codeassembly-agent-logic 0.2.1 → 0.4.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 +95 -0
- package/CHANGELOG.md +33 -0
- package/README.md +85 -5
- 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 +107 -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/conversion-session/conversion-tools.d.ts +4 -0
- package/dist/esm/conversion-session/conversion-tools.js +2 -0
- package/dist/esm/conversion-session/create-conversion-session.d.ts +39 -0
- package/dist/esm/conversion-session/create-conversion-session.js +67 -0
- package/dist/esm/conversion-session/format-conversion-input.d.ts +4 -0
- package/dist/esm/conversion-session/format-conversion-input.js +3 -0
- package/dist/esm/convert/convert-prompt.js +8 -3
- 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/instructions/conversion-instructions.d.ts +2 -0
- package/dist/esm/instructions/conversion-instructions.js +1 -0
- package/dist/esm/instructions/write-conversion-instructions.d.ts +6 -0
- package/dist/esm/instructions/write-conversion-instructions.js +20 -0
- package/dist/esm/job/create-conversion-job.d.ts +28 -0
- package/dist/esm/job/create-conversion-job.js +33 -0
- package/dist/esm/job/index.d.ts +4 -0
- package/dist/esm/job/index.js +2 -0
- package/dist/esm/react/canvas/FocusNavigation.js +5 -5
- package/dist/esm/react/canvas/StateNode.js +3 -3
- package/dist/esm/react/canvas/StatechartCanvas.js +26 -26
- 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/react/styles.css +1 -1
- 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 +33 -15
- 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
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { defineContract } from '@williamthorsen/telefactor/contract';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { agentLogicConfigSchema } from "../schema/agent-logic-schema.js";
|
|
4
|
-
export const contractChartSchema = z.object({
|
|
5
|
-
source: z.string(),
|
|
6
|
-
downloadName: z.string(),
|
|
7
|
-
config: agentLogicConfigSchema,
|
|
8
|
-
});
|
|
9
|
-
export const viewerContract = defineContract({
|
|
10
|
-
state: z.object({
|
|
11
|
-
chart: contractChartSchema.optional(),
|
|
12
|
-
selectedPath: z.string().optional(),
|
|
13
|
-
savedPrompt: z.object({ fileName: z.string(), path: z.string() }).optional(),
|
|
14
|
-
}),
|
|
15
|
-
actions: {
|
|
16
|
-
save_prompt: {
|
|
17
|
-
description: "Saves a prompt to the viewer's prompts directory as \"<name>.md\", the name reduced to lowercase letters, digits, and hyphens; refuses a name that a saved prompt or agent-logic file already uses. The state's `savedPrompt.path` is the saved file. To chart it, run the convert-agent-prompt skill on that path with its default output, which it writes beside the prompt, then call `load_chart` with the output's file name.",
|
|
18
|
-
input: z.object({
|
|
19
|
-
name: z.string().describe('The prompt\'s name, such as "refund triage".'),
|
|
20
|
-
text: z.string().describe('The prompt text.'),
|
|
21
|
-
}),
|
|
22
|
-
},
|
|
23
|
-
load_chart: {
|
|
24
|
-
description: 'Loads an agent-logic file from the prompts directory into the page, such as the "<name>.agent-logic.json" that convert-agent-prompt wrote beside a saved prompt, and clears the selection. Refuses a file that the directory does not list or that does not validate, naming its problems.',
|
|
25
|
-
input: z.object({
|
|
26
|
-
fileName: z.string().describe('A file name in the prompts directory, not a path.'),
|
|
27
|
-
}),
|
|
28
|
-
},
|
|
29
|
-
show_chart: {
|
|
30
|
-
description: 'Shows a chart given as its config, and clears the selection. The page calls it to publish a chart that it loaded; prefer `load_chart` for a saved file.',
|
|
31
|
-
input: contractChartSchema,
|
|
32
|
-
},
|
|
33
|
-
select_element: {
|
|
34
|
-
description: 'Selects an element of the loaded chart by its path into the config, such as `states.greeting` or `states.greeting.on["user.replied"]`, or clears the selection when `path` is omitted. Refuses a path that the chart does not contain.',
|
|
35
|
-
input: z.object({ path: z.string().optional() }),
|
|
36
|
-
},
|
|
37
|
-
},
|
|
38
|
-
});
|
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
import { type HarnessList, type HarnessTestResult } from '@williamthorsen/telefactor/client';
|
|
2
|
-
import { type ConversionJob, type ConversionRequest } from '../../contract/conversion-job.js';
|
|
3
|
-
import type { Problem } from '../../schema/validate-config.js';
|
|
4
|
-
import { type PromptList } from '../../server/prompt-directory-schemas.js';
|
|
5
|
-
/**
|
|
6
|
-
* A request's outcome. `not-found` is a `404`, which the page reads as the server no longer having the job, and
|
|
7
|
-
* `finished` is a cancel that came after the job ended; `failed` covers every other failure, the problems naming why.
|
|
8
|
-
*/
|
|
9
|
-
export type ClientResult = {
|
|
10
|
-
ok: true;
|
|
11
|
-
job: ConversionJob;
|
|
12
|
-
} | {
|
|
13
|
-
ok: false;
|
|
14
|
-
reason: 'failed' | 'finished' | 'not-found';
|
|
15
|
-
problems: Problem[];
|
|
16
|
-
};
|
|
17
|
-
/** The harnesses that the server offers, or the problems that kept the page from reading them. */
|
|
18
|
-
export type HarnessListOutcome = {
|
|
19
|
-
ok: true;
|
|
20
|
-
list: HarnessList;
|
|
21
|
-
} | {
|
|
22
|
-
ok: false;
|
|
23
|
-
problems: Problem[];
|
|
24
|
-
};
|
|
25
|
-
/** A harness test's result, or the problems that kept it from running; `cancelled` marks a test that the page aborted. */
|
|
26
|
-
export type HarnessTestOutcome = {
|
|
27
|
-
ok: true;
|
|
28
|
-
result: HarnessTestResult;
|
|
29
|
-
} | {
|
|
30
|
-
ok: false;
|
|
31
|
-
cancelled: boolean;
|
|
32
|
-
problems: Problem[];
|
|
33
|
-
};
|
|
34
|
-
/**
|
|
35
|
-
* The prompts directory's listing, or why the page has none: `absent` when the server does not serve the directory,
|
|
36
|
-
* `malformed` with the problems of a config file that the server cannot use, and `failed` for every other failure.
|
|
37
|
-
*/
|
|
38
|
-
export type PromptListOutcome = {
|
|
39
|
-
ok: true;
|
|
40
|
-
list: PromptList;
|
|
41
|
-
} | {
|
|
42
|
-
ok: false;
|
|
43
|
-
reason: 'absent' | 'failed' | 'malformed';
|
|
44
|
-
problems: Problem[];
|
|
45
|
-
};
|
|
46
|
-
/** The text of a file in the prompts directory, or the problems that kept the page from reading it. */
|
|
47
|
-
export type PromptFileOutcome = {
|
|
48
|
-
ok: true;
|
|
49
|
-
text: string;
|
|
50
|
-
} | {
|
|
51
|
-
ok: false;
|
|
52
|
-
problems: Problem[];
|
|
53
|
-
};
|
|
54
|
-
/**
|
|
55
|
-
* Starts, reads, and cancels conversions on the conversion server, lists and tests its harnesses, and lists and reads
|
|
56
|
-
* its prompts directory.
|
|
57
|
-
*/
|
|
58
|
-
export interface ConversionClient {
|
|
59
|
-
cancel(id: string): Promise<ClientResult>;
|
|
60
|
-
listHarnesses(): Promise<HarnessListOutcome>;
|
|
61
|
-
listPrompts(): Promise<PromptListOutcome>;
|
|
62
|
-
read(id: string): Promise<ClientResult>;
|
|
63
|
-
readPromptFile(fileName: string): Promise<PromptFileOutcome>;
|
|
64
|
-
start(request: ConversionRequest): Promise<ClientResult>;
|
|
65
|
-
testHarness(name: string, signal: AbortSignal): Promise<HarnessTestOutcome>;
|
|
66
|
-
}
|
|
67
|
-
interface ConversionClientOptions {
|
|
68
|
-
/** The server's origin, under which telefactor's routes are served at `/api/telefactor` and the prompts at `/api/prompts`. */
|
|
69
|
-
baseUrl: string;
|
|
70
|
-
fetch?: typeof globalThis.fetch;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Creates a client for the conversion server: telefactor's client for the job and harness routes, and requests of its
|
|
74
|
-
* own for the prompts routes.
|
|
75
|
-
*/
|
|
76
|
-
export declare function createConversionClient({ baseUrl, fetch, }: ConversionClientOptions): ConversionClient;
|
|
77
|
-
export {};
|
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
import { createTelefactorClient, TelefactorRequestError, } from '@williamthorsen/telefactor/client';
|
|
2
|
-
import { describeError } from '@williamthorsen/toolbelt.errors';
|
|
3
|
-
import { z } from 'zod';
|
|
4
|
-
import { conversionJob } from "../../contract/conversion-job.js";
|
|
5
|
-
import { promptFileSchema, promptListSchema } from "../../server/prompt-directory-schemas.js";
|
|
6
|
-
export function createConversionClient({ baseUrl, fetch = globalThis.fetch.bind(globalThis), }) {
|
|
7
|
-
const apiRoot = `${baseUrl.replace(/\/+$/, '')}/api`;
|
|
8
|
-
const telefactorClient = createTelefactorClient({ basePath: `${apiRoot}/telefactor`, fetch, job: conversionJob });
|
|
9
|
-
async function receive(url) {
|
|
10
|
-
let response;
|
|
11
|
-
try {
|
|
12
|
-
response = await fetch(url, { method: 'GET' });
|
|
13
|
-
}
|
|
14
|
-
catch (error) {
|
|
15
|
-
return { ok: false, notJsonStatus: undefined, problems: toProblems(describeUnreachable(error)) };
|
|
16
|
-
}
|
|
17
|
-
try {
|
|
18
|
-
return { ok: true, status: response.status, body: await response.json() };
|
|
19
|
-
}
|
|
20
|
-
catch {
|
|
21
|
-
const message = `The conversion server answered ${response.status} with a body that is not JSON.`;
|
|
22
|
-
return { ok: false, notJsonStatus: response.status, problems: toProblems(message) };
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
return {
|
|
26
|
-
cancel(id) {
|
|
27
|
-
return sendJobRequest(() => telefactorClient.cancelJob(id));
|
|
28
|
-
},
|
|
29
|
-
async listHarnesses() {
|
|
30
|
-
try {
|
|
31
|
-
return { ok: true, list: await telefactorClient.listHarnesses() };
|
|
32
|
-
}
|
|
33
|
-
catch (error) {
|
|
34
|
-
return { ok: false, problems: describeFailure(error) };
|
|
35
|
-
}
|
|
36
|
-
},
|
|
37
|
-
async listPrompts() {
|
|
38
|
-
const received = await receive(`${apiRoot}/prompts`);
|
|
39
|
-
if (!received.ok)
|
|
40
|
-
return failPromptList(isPageInPlaceOfApi(received.notJsonStatus) ? 'absent' : 'failed', received.problems);
|
|
41
|
-
const { status, body } = received;
|
|
42
|
-
if (status === 200) {
|
|
43
|
-
const failed = failPromptListRead;
|
|
44
|
-
return readBody({ schema: promptListSchema, body, status, failed }, (list) => ({ ok: true, list }));
|
|
45
|
-
}
|
|
46
|
-
if (status === 400) {
|
|
47
|
-
const failed = failMalformedPromptList;
|
|
48
|
-
return readBody({ schema: problemsBodySchema, body, status, failed }, ({ problems }) => failed(problems));
|
|
49
|
-
}
|
|
50
|
-
const reason = status === 404 ? 'absent' : 'failed';
|
|
51
|
-
return failPromptList(reason, toProblems(`The conversion server answered ${status}.`));
|
|
52
|
-
},
|
|
53
|
-
read(id) {
|
|
54
|
-
return sendJobRequest(() => telefactorClient.getJob(id));
|
|
55
|
-
},
|
|
56
|
-
async readPromptFile(fileName) {
|
|
57
|
-
const received = await receive(`${apiRoot}/prompts/files/${encodeURIComponent(fileName)}`);
|
|
58
|
-
if (!received.ok)
|
|
59
|
-
return { ok: false, problems: received.problems };
|
|
60
|
-
const { status, body } = received;
|
|
61
|
-
const failed = failPromptFile;
|
|
62
|
-
if (status === 200) {
|
|
63
|
-
return readBody({ schema: promptFileSchema, body, status, failed }, ({ text }) => ({ ok: true, text }));
|
|
64
|
-
}
|
|
65
|
-
if (status === 400) {
|
|
66
|
-
return readBody({ schema: problemsBodySchema, body, status, failed }, ({ problems }) => failed(problems));
|
|
67
|
-
}
|
|
68
|
-
return readBody({ schema: errorBodySchema, body, status, failed }, ({ error }) => failed(toProblems(error)));
|
|
69
|
-
},
|
|
70
|
-
start(request) {
|
|
71
|
-
return sendJobRequest(() => telefactorClient.startJob(request));
|
|
72
|
-
},
|
|
73
|
-
async testHarness(name, signal) {
|
|
74
|
-
try {
|
|
75
|
-
return { ok: true, result: await telefactorClient.testHarness(name, { signal }) };
|
|
76
|
-
}
|
|
77
|
-
catch (error) {
|
|
78
|
-
if (signal.aborted)
|
|
79
|
-
return { ok: false, cancelled: true, problems: toProblems('The request was cancelled.') };
|
|
80
|
-
return { ok: false, cancelled: false, problems: describeFailure(error) };
|
|
81
|
-
}
|
|
82
|
-
},
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
const JOB_REASONS = { 404: 'not-found', 409: 'finished' };
|
|
86
|
-
const problemSchema = z.object({ path: z.string(), message: z.string() });
|
|
87
|
-
const problemsBodySchema = z.object({ problems: z.array(problemSchema) });
|
|
88
|
-
const errorBodySchema = z.object({ error: z.string() });
|
|
89
|
-
function describeFailure(error) {
|
|
90
|
-
if (error instanceof TelefactorRequestError) {
|
|
91
|
-
return error.problems.length > 0 ? error.problems : toProblems(error.message);
|
|
92
|
-
}
|
|
93
|
-
if (error instanceof z.ZodError)
|
|
94
|
-
return toProblems('The conversion server answered with a body of an unexpected shape.');
|
|
95
|
-
return toProblems(describeUnreachable(error));
|
|
96
|
-
}
|
|
97
|
-
function describeUnreachable(error) {
|
|
98
|
-
return `The conversion server could not be reached (${describeError(error)}).`;
|
|
99
|
-
}
|
|
100
|
-
function failMalformedPromptList(problems) {
|
|
101
|
-
return failPromptList('malformed', problems);
|
|
102
|
-
}
|
|
103
|
-
function failPromptFile(problems) {
|
|
104
|
-
return { ok: false, problems };
|
|
105
|
-
}
|
|
106
|
-
function failPromptList(reason, problems) {
|
|
107
|
-
return { ok: false, reason, problems };
|
|
108
|
-
}
|
|
109
|
-
function failPromptListRead(problems) {
|
|
110
|
-
return failPromptList('failed', problems);
|
|
111
|
-
}
|
|
112
|
-
function isPageInPlaceOfApi(notJsonStatus) {
|
|
113
|
-
return notJsonStatus !== undefined && notJsonStatus < 500;
|
|
114
|
-
}
|
|
115
|
-
function readBody({ schema, body, status, failed, }, toResult) {
|
|
116
|
-
const parsed = schema.safeParse(body);
|
|
117
|
-
return parsed.success
|
|
118
|
-
? toResult(parsed.data)
|
|
119
|
-
: failed(toProblems(`The conversion server answered ${status} with a body of an unexpected shape.`));
|
|
120
|
-
}
|
|
121
|
-
async function sendJobRequest(request) {
|
|
122
|
-
try {
|
|
123
|
-
return { ok: true, job: await request() };
|
|
124
|
-
}
|
|
125
|
-
catch (error) {
|
|
126
|
-
const reason = error instanceof TelefactorRequestError ? (JOB_REASONS[error.status] ?? 'failed') : 'failed';
|
|
127
|
-
return { ok: false, reason, problems: describeFailure(error) };
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
function toProblems(message) {
|
|
131
|
-
return [{ path: '', message }];
|
|
132
|
-
}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { type ConfigDescription } from '../../layout/describe-config.js';
|
|
2
|
-
/**
|
|
3
|
-
* Returns the announcement of a selection that the agent made, naming the element as the page shows it, or `undefined`
|
|
4
|
-
* when the chart does not contain the path.
|
|
5
|
-
*/
|
|
6
|
-
export declare function describeAgentSelection(description: ConfigDescription, path: string | undefined): string | undefined;
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import { buildTransitionLabel } from "../../layout/describe-config.js";
|
|
2
|
-
export function describeAgentSelection(description, path) {
|
|
3
|
-
if (path === undefined)
|
|
4
|
-
return 'Agent cleared the selection.';
|
|
5
|
-
const state = description.states.find((candidate) => candidate.path === path);
|
|
6
|
-
if (state !== undefined)
|
|
7
|
-
return `Agent selected ${state.name}.`;
|
|
8
|
-
const transition = description.transitions.find((candidate) => candidate.path === path);
|
|
9
|
-
if (transition !== undefined) {
|
|
10
|
-
const { trigger } = buildTransitionLabel(transition);
|
|
11
|
-
const route = `${transition.sourceName} to ${transition.targetName}`;
|
|
12
|
-
return `Agent selected the transition from ${route}${trigger === undefined ? '' : ` on ${trigger}`}.`;
|
|
13
|
-
}
|
|
14
|
-
const ambient = description.ambient.find((candidate) => candidate.path === path);
|
|
15
|
-
if (ambient !== undefined)
|
|
16
|
-
return `Agent selected an ambient instruction of ${ambient.containerName}.`;
|
|
17
|
-
return undefined;
|
|
18
|
-
}
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import type { ContractClient } from '@williamthorsen/telefactor/client';
|
|
2
|
-
import type { ContractState } from '@williamthorsen/telefactor/contract';
|
|
3
|
-
import type { viewerContract } from '../../contract/viewer-contract.js';
|
|
4
|
-
import type { AgentLogicConfig } from '../../schema/agent-logic-schema.js';
|
|
5
|
-
import type { SourceLabel } from './label-source.js';
|
|
6
|
-
export type ViewerContract = typeof viewerContract;
|
|
7
|
-
export type ViewerContractClient = ContractClient<ViewerContract>;
|
|
8
|
-
export type ViewerState = ContractState<ViewerContract>;
|
|
9
|
-
interface AgentBridgeHandlers {
|
|
10
|
-
/** Receives the session state once the dev server first answers. */
|
|
11
|
-
onConnect: (state: ViewerState) => void;
|
|
12
|
-
/** Receives each commit that the agent makes, with the name of the action that made it. */
|
|
13
|
-
onAgentChange: (action: string, state: ViewerState) => void;
|
|
14
|
-
}
|
|
15
|
-
/** The page's link to the session state that it shares with an agent. */
|
|
16
|
-
export interface AgentBridge {
|
|
17
|
-
/** Whether the dev server serves the contract; a built page never connects. */
|
|
18
|
-
isConnected: boolean;
|
|
19
|
-
publishChart: (label: SourceLabel, config: AgentLogicConfig) => void;
|
|
20
|
-
publishSelection: (path: string | undefined) => void;
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* Subscribes to the viewer's session state, reports the agent's commits, and publishes the page's loads and selections
|
|
24
|
-
* in the order in which the page makes them. A stream that fails before its first snapshot ends the subscription, as
|
|
25
|
-
* under `vite build` or `vite preview`, which do not serve the contract.
|
|
26
|
-
*/
|
|
27
|
-
export declare function useAgentBridge(client: ViewerContractClient | undefined, handlers: AgentBridgeHandlers): AgentBridge;
|
|
28
|
-
export {};
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
|
2
|
-
export function useAgentBridge(client, handlers) {
|
|
3
|
-
const [isConnected, setIsConnected] = useState(false);
|
|
4
|
-
const handlersRef = useRef(handlers);
|
|
5
|
-
useLayoutEffect(() => {
|
|
6
|
-
handlersRef.current = handlers;
|
|
7
|
-
});
|
|
8
|
-
const isConnectedRef = useRef(false);
|
|
9
|
-
const queue = useRef(Promise.resolve());
|
|
10
|
-
useEffect(() => {
|
|
11
|
-
if (client === undefined)
|
|
12
|
-
return;
|
|
13
|
-
let hasSnapshot = false;
|
|
14
|
-
const unsubscribe = client.subscribe((snapshot) => {
|
|
15
|
-
if (!hasSnapshot) {
|
|
16
|
-
hasSnapshot = true;
|
|
17
|
-
isConnectedRef.current = true;
|
|
18
|
-
setIsConnected(true);
|
|
19
|
-
handlersRef.current.onConnect(snapshot.state);
|
|
20
|
-
return;
|
|
21
|
-
}
|
|
22
|
-
if (snapshot.change?.origin === 'agent')
|
|
23
|
-
handlersRef.current.onAgentChange(snapshot.change.action, snapshot.state);
|
|
24
|
-
}, {
|
|
25
|
-
onError: () => {
|
|
26
|
-
if (!hasSnapshot)
|
|
27
|
-
unsubscribe();
|
|
28
|
-
},
|
|
29
|
-
});
|
|
30
|
-
return unsubscribe;
|
|
31
|
-
}, [client]);
|
|
32
|
-
const send = useCallback((call) => {
|
|
33
|
-
if (client === undefined || !isConnectedRef.current)
|
|
34
|
-
return;
|
|
35
|
-
const previous = queue.current;
|
|
36
|
-
queue.current = (async () => {
|
|
37
|
-
await previous;
|
|
38
|
-
try {
|
|
39
|
-
await call(client);
|
|
40
|
-
}
|
|
41
|
-
catch {
|
|
42
|
-
}
|
|
43
|
-
})();
|
|
44
|
-
}, [client]);
|
|
45
|
-
const publishChart = useCallback((label, config) => {
|
|
46
|
-
send((connected) => connected.call('show_chart', { ...label, config }));
|
|
47
|
-
}, [send]);
|
|
48
|
-
const publishSelection = useCallback((path) => {
|
|
49
|
-
send((connected) => connected.call('select_element', path === undefined ? {} : { path }));
|
|
50
|
-
}, [send]);
|
|
51
|
-
return { isConnected, publishChart, publishSelection };
|
|
52
|
-
}
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import type { AgentLogicConfig } from '../../schema/agent-logic-schema.js';
|
|
2
|
-
import type { SourceLabel } from './label-source.js';
|
|
3
|
-
import { type ViewerContractClient } from './useAgentBridge.js';
|
|
4
|
-
/** The page's operations that apply the agent's commits; the hook reads them when a commit arrives. */
|
|
5
|
-
export interface AgentSyncPage {
|
|
6
|
-
announce: (text: string) => void;
|
|
7
|
-
/** Returns the chart that the page shows, if any. */
|
|
8
|
-
readChart: () => (SourceLabel & {
|
|
9
|
-
config: AgentLogicConfig;
|
|
10
|
-
}) | undefined;
|
|
11
|
-
/** Shows a chart without a history entry. */
|
|
12
|
-
showChart: (label: SourceLabel, config: AgentLogicConfig) => void;
|
|
13
|
-
/** Shows a chart with a history entry of its own, as a conversion does. */
|
|
14
|
-
showLoadedInput: (label: SourceLabel, config: AgentLogicConfig) => void;
|
|
15
|
-
/** Selects an element, or clears the selection, and clears any passages shown. */
|
|
16
|
-
selectElement: (path: string | undefined) => void;
|
|
17
|
-
}
|
|
18
|
-
/** The page's link to the agent: whether it is connected, and the publishers that skip a commit being applied. */
|
|
19
|
-
export interface AgentSync {
|
|
20
|
-
isConnected: boolean;
|
|
21
|
-
publishChart: (label: SourceLabel, config: AgentLogicConfig) => void;
|
|
22
|
-
publishSelection: (path: string | undefined) => void;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Keeps the page and the session state that it shares with an agent in step: applies and announces the agent's
|
|
26
|
-
* commits through the page's operations, and on connect adopts the session's chart when the page shows none, else
|
|
27
|
-
* publishes the page's chart, which wins. A change made while a commit is applied is not published back.
|
|
28
|
-
*/
|
|
29
|
-
export declare function useAgentSync(client: ViewerContractClient | undefined, page: AgentSyncPage): AgentSync;
|
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { useCallback, useRef } from 'react';
|
|
2
|
-
import { describeConfig } from "../../layout/describe-config.js";
|
|
3
|
-
import { describeAgentSelection } from "./describe-agent-selection.js";
|
|
4
|
-
import { describeLoadedByAgent } from "./describe-load-outcome.js";
|
|
5
|
-
import { findExampleInSearch } from "./example-location.js";
|
|
6
|
-
import { useAgentBridge } from "./useAgentBridge.js";
|
|
7
|
-
export function useAgentSync(client, page) {
|
|
8
|
-
const isApplying = useRef(false);
|
|
9
|
-
const bridge = useAgentBridge(client, {
|
|
10
|
-
onConnect: (state) => {
|
|
11
|
-
const pageChart = page.readChart();
|
|
12
|
-
if (pageChart !== undefined) {
|
|
13
|
-
bridge.publishChart(toLabel(pageChart), pageChart.config);
|
|
14
|
-
return;
|
|
15
|
-
}
|
|
16
|
-
const { chart } = state;
|
|
17
|
-
if (chart === undefined || findExampleInSearch(globalThis.location.search) !== undefined)
|
|
18
|
-
return;
|
|
19
|
-
applying(() => page.showChart(toLabel(chart), chart.config));
|
|
20
|
-
},
|
|
21
|
-
onAgentChange: (action, state) => {
|
|
22
|
-
applying(() => applyAgentChange(page, action, state));
|
|
23
|
-
},
|
|
24
|
-
});
|
|
25
|
-
function applying(change) {
|
|
26
|
-
isApplying.current = true;
|
|
27
|
-
try {
|
|
28
|
-
change();
|
|
29
|
-
}
|
|
30
|
-
finally {
|
|
31
|
-
isApplying.current = false;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
const { isConnected, publishChart: sendChart, publishSelection: sendSelection } = bridge;
|
|
35
|
-
const publishChart = useCallback((label, config) => {
|
|
36
|
-
if (!isApplying.current)
|
|
37
|
-
sendChart(label, config);
|
|
38
|
-
}, [sendChart]);
|
|
39
|
-
const publishSelection = useCallback((path) => {
|
|
40
|
-
if (!isApplying.current)
|
|
41
|
-
sendSelection(path);
|
|
42
|
-
}, [sendSelection]);
|
|
43
|
-
return { isConnected, publishChart, publishSelection };
|
|
44
|
-
}
|
|
45
|
-
function applyAgentChange(page, action, state) {
|
|
46
|
-
switch (action) {
|
|
47
|
-
case 'load_chart':
|
|
48
|
-
case 'show_chart': {
|
|
49
|
-
if (state.chart === undefined)
|
|
50
|
-
return;
|
|
51
|
-
const { config } = state.chart;
|
|
52
|
-
page.showLoadedInput(toLabel(state.chart), config);
|
|
53
|
-
page.announce(describeLoadedByAgent(state.chart.source, config));
|
|
54
|
-
return;
|
|
55
|
-
}
|
|
56
|
-
case 'select_element': {
|
|
57
|
-
const pageChart = page.readChart();
|
|
58
|
-
if (pageChart === undefined)
|
|
59
|
-
return;
|
|
60
|
-
const text = describeAgentSelection(describeConfig(pageChart.config), state.selectedPath);
|
|
61
|
-
if (text === undefined)
|
|
62
|
-
return;
|
|
63
|
-
page.selectElement(state.selectedPath);
|
|
64
|
-
page.announce(text);
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
case 'save_prompt':
|
|
68
|
-
if (state.savedPrompt !== undefined)
|
|
69
|
-
page.announce(`Agent saved ${state.savedPrompt.fileName}.`);
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
function toLabel({ source, downloadName }) {
|
|
74
|
-
return { source, downloadName };
|
|
75
|
-
}
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import type { ConversionRequest } from '../../contract/conversion-job.js';
|
|
2
|
-
import type { Problem } from '../../schema/validate-config.js';
|
|
3
|
-
import type { ConversionClient } from './conversion-client.js';
|
|
4
|
-
/** The time between two reads of a running job. */
|
|
5
|
-
export declare const POLL_INTERVAL_MS = 2000;
|
|
6
|
-
/** The `sessionStorage` key under which the running job's id and name are kept, so that a reload resumes it. */
|
|
7
|
-
export declare const CONVERSION_STORAGE_KEY = "agent-logic.conversion";
|
|
8
|
-
/** What the page does with a conversion's outcome, each call naming the prompt. */
|
|
9
|
-
export interface ConversionHandlers {
|
|
10
|
-
/** Learns that a conversion was cancelled, by the user or on the server. */
|
|
11
|
-
onCancelled: (name: string) => void;
|
|
12
|
-
/** Takes the agent-logic file's text of a conversion that succeeded. */
|
|
13
|
-
onConverted: (name: string, text: string) => void;
|
|
14
|
-
/** Takes the problems of a conversion that did not produce a file, or of a request that failed. */
|
|
15
|
-
onProblems: (name: string, problems: Problem[]) => void;
|
|
16
|
-
/** Learns that a conversion started running, or that the page resumed one after a reload. */
|
|
17
|
-
onRunning: (name: string) => void;
|
|
18
|
-
}
|
|
19
|
-
/** The running conversion, if any, and the functions that start and cancel one. */
|
|
20
|
-
export interface Conversion {
|
|
21
|
-
running: {
|
|
22
|
-
name: string;
|
|
23
|
-
} | undefined;
|
|
24
|
-
cancel: () => void;
|
|
25
|
-
start: (request: ConversionRequest) => void;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Runs one conversion at a time on the conversion server, polling it until it ends. Starting another cancels the
|
|
29
|
-
* current one. The running job's id is kept in `sessionStorage`, and the page resumes it when it loads.
|
|
30
|
-
*/
|
|
31
|
-
export declare function useConversion(client: ConversionClient, handlers: ConversionHandlers): Conversion;
|
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
2
|
-
export const POLL_INTERVAL_MS = 2000;
|
|
3
|
-
export const CONVERSION_STORAGE_KEY = 'agent-logic.conversion';
|
|
4
|
-
export function useConversion(client, handlers) {
|
|
5
|
-
const [running, setRunning] = useState();
|
|
6
|
-
const clientRef = useRef(client);
|
|
7
|
-
const handlersRef = useRef(handlers);
|
|
8
|
-
useEffect(() => {
|
|
9
|
-
clientRef.current = client;
|
|
10
|
-
handlersRef.current = handlers;
|
|
11
|
-
});
|
|
12
|
-
const runRef = useRef(0);
|
|
13
|
-
const currentRef = useRef(undefined);
|
|
14
|
-
const timerRef = useRef(undefined);
|
|
15
|
-
useEffect(() => {
|
|
16
|
-
const stored = readStoredJob();
|
|
17
|
-
if (stored !== undefined) {
|
|
18
|
-
const run = begin(stored);
|
|
19
|
-
void poll(stored, run, { isResumed: true });
|
|
20
|
-
}
|
|
21
|
-
return () => {
|
|
22
|
-
runRef.current += 1;
|
|
23
|
-
clearTimeout(timerRef.current);
|
|
24
|
-
};
|
|
25
|
-
}, []);
|
|
26
|
-
function begin(job) {
|
|
27
|
-
runRef.current += 1;
|
|
28
|
-
clearTimeout(timerRef.current);
|
|
29
|
-
currentRef.current = job;
|
|
30
|
-
setRunning({ name: job.name });
|
|
31
|
-
return runRef.current;
|
|
32
|
-
}
|
|
33
|
-
function end() {
|
|
34
|
-
runRef.current += 1;
|
|
35
|
-
clearTimeout(timerRef.current);
|
|
36
|
-
currentRef.current = undefined;
|
|
37
|
-
setRunning(undefined);
|
|
38
|
-
writeStoredJob(undefined);
|
|
39
|
-
}
|
|
40
|
-
function follow(job, name, run, { isResumed }) {
|
|
41
|
-
if (job.status === 'running') {
|
|
42
|
-
const isNew = currentRef.current?.id !== job.id || isResumed;
|
|
43
|
-
currentRef.current = { id: job.id, name };
|
|
44
|
-
writeStoredJob({ id: job.id, name });
|
|
45
|
-
if (isNew)
|
|
46
|
-
handlersRef.current.onRunning(name);
|
|
47
|
-
timerRef.current = setTimeout(() => {
|
|
48
|
-
void poll({ id: job.id, name }, run, { isResumed: false });
|
|
49
|
-
}, POLL_INTERVAL_MS);
|
|
50
|
-
return;
|
|
51
|
-
}
|
|
52
|
-
end();
|
|
53
|
-
settle(job, name);
|
|
54
|
-
}
|
|
55
|
-
async function poll(job, run, options) {
|
|
56
|
-
const result = await clientRef.current.read(job.id);
|
|
57
|
-
if (run !== runRef.current)
|
|
58
|
-
return;
|
|
59
|
-
if (result.ok) {
|
|
60
|
-
follow(result.job, job.name, run, options);
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
end();
|
|
64
|
-
if (options.isResumed && result.reason === 'not-found')
|
|
65
|
-
return;
|
|
66
|
-
report(job.name, result);
|
|
67
|
-
}
|
|
68
|
-
function report(name, result) {
|
|
69
|
-
handlersRef.current.onProblems(name, result.reason === 'not-found'
|
|
70
|
-
? [
|
|
71
|
-
{
|
|
72
|
-
path: '',
|
|
73
|
-
message: 'The conversion server no longer has the conversion, as after a restart. Convert the prompt again.',
|
|
74
|
-
},
|
|
75
|
-
]
|
|
76
|
-
: result.problems);
|
|
77
|
-
}
|
|
78
|
-
function settle(job, name) {
|
|
79
|
-
const { onCancelled, onConverted, onProblems } = handlersRef.current;
|
|
80
|
-
if (job.status === 'cancelled')
|
|
81
|
-
onCancelled(name);
|
|
82
|
-
else if (job.status === 'done' && job.result?.ok === true)
|
|
83
|
-
onConverted(name, job.result.text);
|
|
84
|
-
else if (job.status === 'done' && job.result !== undefined && 'outOfScope' in job.result)
|
|
85
|
-
onProblems(name, [{ path: '', message: `Out of scope: ${job.result.outOfScope.reason}` }]);
|
|
86
|
-
else if (job.status === 'done' && job.result !== undefined && 'problems' in job.result)
|
|
87
|
-
onProblems(name, job.result.problems);
|
|
88
|
-
else
|
|
89
|
-
onProblems(name, [{ path: '', message: describeEnd(job) }]);
|
|
90
|
-
}
|
|
91
|
-
async function start(request) {
|
|
92
|
-
const previous = currentRef.current;
|
|
93
|
-
if (previous?.id !== undefined)
|
|
94
|
-
void clientRef.current.cancel(previous.id);
|
|
95
|
-
const run = begin({ name: request.name });
|
|
96
|
-
const result = await clientRef.current.start(request);
|
|
97
|
-
if (run !== runRef.current) {
|
|
98
|
-
if (result.ok)
|
|
99
|
-
void clientRef.current.cancel(result.job.id);
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
if (result.ok) {
|
|
103
|
-
follow(result.job, request.name, run, { isResumed: false });
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
end();
|
|
107
|
-
report(request.name, result);
|
|
108
|
-
}
|
|
109
|
-
async function cancel() {
|
|
110
|
-
const current = currentRef.current;
|
|
111
|
-
if (current === undefined)
|
|
112
|
-
return;
|
|
113
|
-
end();
|
|
114
|
-
if (current.id === undefined) {
|
|
115
|
-
handlersRef.current.onCancelled(current.name);
|
|
116
|
-
return;
|
|
117
|
-
}
|
|
118
|
-
const result = await clientRef.current.cancel(current.id);
|
|
119
|
-
if (result.ok) {
|
|
120
|
-
settle(result.job, current.name);
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
if (result.reason !== 'finished') {
|
|
124
|
-
report(current.name, result);
|
|
125
|
-
return;
|
|
126
|
-
}
|
|
127
|
-
const read = await clientRef.current.read(current.id);
|
|
128
|
-
if (read.ok)
|
|
129
|
-
settle(read.job, current.name);
|
|
130
|
-
else
|
|
131
|
-
report(current.name, read);
|
|
132
|
-
}
|
|
133
|
-
const handleCancel = useCallback(() => void cancel(), []);
|
|
134
|
-
const handleStart = useCallback((request) => void start(request), []);
|
|
135
|
-
return { running, cancel: handleCancel, start: handleStart };
|
|
136
|
-
}
|
|
137
|
-
function describeEnd(job) {
|
|
138
|
-
if (job.status === 'failed')
|
|
139
|
-
return job.error ?? 'The conversion failed.';
|
|
140
|
-
return 'The conversion ended without a result.';
|
|
141
|
-
}
|
|
142
|
-
function readStoredJob() {
|
|
143
|
-
let raw;
|
|
144
|
-
try {
|
|
145
|
-
raw = globalThis.sessionStorage.getItem(CONVERSION_STORAGE_KEY);
|
|
146
|
-
}
|
|
147
|
-
catch {
|
|
148
|
-
return undefined;
|
|
149
|
-
}
|
|
150
|
-
if (raw === null)
|
|
151
|
-
return undefined;
|
|
152
|
-
let value;
|
|
153
|
-
try {
|
|
154
|
-
value = JSON.parse(raw);
|
|
155
|
-
}
|
|
156
|
-
catch {
|
|
157
|
-
return undefined;
|
|
158
|
-
}
|
|
159
|
-
return typeof value === 'object' &&
|
|
160
|
-
value !== null &&
|
|
161
|
-
'id' in value &&
|
|
162
|
-
typeof value.id === 'string' &&
|
|
163
|
-
'name' in value &&
|
|
164
|
-
typeof value.name === 'string'
|
|
165
|
-
? { id: value.id, name: value.name }
|
|
166
|
-
: undefined;
|
|
167
|
-
}
|
|
168
|
-
function writeStoredJob(job) {
|
|
169
|
-
try {
|
|
170
|
-
if (job === undefined)
|
|
171
|
-
globalThis.sessionStorage.removeItem(CONVERSION_STORAGE_KEY);
|
|
172
|
-
else
|
|
173
|
-
globalThis.sessionStorage.setItem(CONVERSION_STORAGE_KEY, JSON.stringify(job));
|
|
174
|
-
}
|
|
175
|
-
catch {
|
|
176
|
-
}
|
|
177
|
-
}
|