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.
- package/.meta/changelog.json +67 -0
- package/CHANGELOG.md +23 -0
- package/README.md +75 -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 +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 +22 -14
- 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,26 +0,0 @@
|
|
|
1
|
-
import type { HarnessList } from '@williamthorsen/telefactor/client';
|
|
2
|
-
import type { Problem } from '../../schema/validate-config.js';
|
|
3
|
-
import type { ConversionClient } from './conversion-client.js';
|
|
4
|
-
/** The harnesses that the server offers, without the problems that a malformed config file reports instead. */
|
|
5
|
-
export type HarnessOffer = Extract<HarnessList, {
|
|
6
|
-
harnesses: unknown;
|
|
7
|
-
}>;
|
|
8
|
-
/**
|
|
9
|
-
* The harness listing: `loading` until the server answers, `ready` with the harnesses, `malformed` with the problems of
|
|
10
|
-
* a config file that the server cannot use, or `unreachable` with the problems that kept the page from reading it.
|
|
11
|
-
*/
|
|
12
|
-
export type HarnessListing = {
|
|
13
|
-
state: 'loading';
|
|
14
|
-
} | {
|
|
15
|
-
state: 'ready';
|
|
16
|
-
list: HarnessOffer;
|
|
17
|
-
} | {
|
|
18
|
-
state: 'malformed';
|
|
19
|
-
configPath: string;
|
|
20
|
-
problems: Problem[];
|
|
21
|
-
} | {
|
|
22
|
-
state: 'unreachable';
|
|
23
|
-
problems: Problem[];
|
|
24
|
-
};
|
|
25
|
-
/** Reads the server's harnesses once, when the component mounts. */
|
|
26
|
-
export declare function useHarnessList(client: ConversionClient): HarnessListing;
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { useEffect, useState } from 'react';
|
|
2
|
-
export function useHarnessList(client) {
|
|
3
|
-
const [listing, setListing] = useState({ state: 'loading' });
|
|
4
|
-
useEffect(() => {
|
|
5
|
-
let isCurrent = true;
|
|
6
|
-
async function load() {
|
|
7
|
-
const outcome = await client.listHarnesses();
|
|
8
|
-
if (!isCurrent)
|
|
9
|
-
return;
|
|
10
|
-
if (!outcome.ok)
|
|
11
|
-
setListing({ state: 'unreachable', problems: outcome.problems });
|
|
12
|
-
else if ('problems' in outcome.list) {
|
|
13
|
-
setListing({ state: 'malformed', configPath: outcome.list.configPath, problems: outcome.list.problems });
|
|
14
|
-
}
|
|
15
|
-
else
|
|
16
|
-
setListing({ state: 'ready', list: outcome.list });
|
|
17
|
-
}
|
|
18
|
-
void load();
|
|
19
|
-
return () => {
|
|
20
|
-
isCurrent = false;
|
|
21
|
-
};
|
|
22
|
-
}, [client]);
|
|
23
|
-
return listing;
|
|
24
|
-
}
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import type { PromptEntry } from '../../server/prompt-directory-schemas.js';
|
|
2
|
-
import type { ConversionClient } from './conversion-client.js';
|
|
3
|
-
/**
|
|
4
|
-
* The prompts directory as the page shows it: `hidden` until the server first answers and whenever it does not serve
|
|
5
|
-
* the directory or cannot be reached, `ready` with its entries, `missing` when the directory does not exist, and
|
|
6
|
-
* `malformed` when the config file that names it cannot be used.
|
|
7
|
-
*/
|
|
8
|
-
export type PromptDirectoryState = {
|
|
9
|
-
state: 'hidden';
|
|
10
|
-
} | {
|
|
11
|
-
state: 'ready';
|
|
12
|
-
directory: string;
|
|
13
|
-
configPath: string;
|
|
14
|
-
entries: PromptEntry[];
|
|
15
|
-
} | {
|
|
16
|
-
state: 'missing';
|
|
17
|
-
directory: string;
|
|
18
|
-
configPath: string;
|
|
19
|
-
} | {
|
|
20
|
-
state: 'malformed';
|
|
21
|
-
};
|
|
22
|
-
/**
|
|
23
|
-
* Polls the prompts directory every `POLL_INTERVAL_MS`, so that a file saved there appears without a reload. A server
|
|
24
|
-
* that does not serve the directory stops the polling; one that cannot be reached does not, so that a restarted dev
|
|
25
|
-
* server shows the directory again.
|
|
26
|
-
*/
|
|
27
|
-
export declare function usePromptDirectory(client: ConversionClient): PromptDirectoryState;
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { useEffect, useState } from 'react';
|
|
2
|
-
import { POLL_INTERVAL_MS } from "./useConversion.js";
|
|
3
|
-
export function usePromptDirectory(client) {
|
|
4
|
-
const [directory, setDirectory] = useState({ state: 'hidden' });
|
|
5
|
-
useEffect(() => {
|
|
6
|
-
let isCurrent = true;
|
|
7
|
-
let timer;
|
|
8
|
-
void poll();
|
|
9
|
-
return () => {
|
|
10
|
-
isCurrent = false;
|
|
11
|
-
clearTimeout(timer);
|
|
12
|
-
};
|
|
13
|
-
async function poll() {
|
|
14
|
-
const outcome = await client.listPrompts();
|
|
15
|
-
if (!isCurrent)
|
|
16
|
-
return;
|
|
17
|
-
if (outcome.ok) {
|
|
18
|
-
const { list } = outcome;
|
|
19
|
-
const { directory, configPath } = list;
|
|
20
|
-
if ('entries' in list)
|
|
21
|
-
setDirectory({ state: 'ready', directory, configPath, entries: list.entries });
|
|
22
|
-
else
|
|
23
|
-
setDirectory({ state: 'missing', directory, configPath });
|
|
24
|
-
}
|
|
25
|
-
else {
|
|
26
|
-
setDirectory({ state: outcome.reason === 'malformed' ? 'malformed' : 'hidden' });
|
|
27
|
-
if (outcome.reason === 'absent')
|
|
28
|
-
return;
|
|
29
|
-
}
|
|
30
|
-
timer = setTimeout(() => void poll(), POLL_INTERVAL_MS);
|
|
31
|
-
}
|
|
32
|
-
}, [client]);
|
|
33
|
-
return directory;
|
|
34
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { type JobImplementation } from '@williamthorsen/telefactor/server';
|
|
2
|
-
import { conversionJob } from '../contract/conversion-job.js';
|
|
3
|
-
/**
|
|
4
|
-
* Implements the conversion job: Each run writes the prompt to a file in a directory of its own under
|
|
5
|
-
* `conversionsDirectory`, expands `{prompt}`, `{output}`, and `{problems}` in the harness command to absolute paths in
|
|
6
|
-
* that directory, and reads back the agent-logic file that the command writes or, when it writes none, the problems or
|
|
7
|
-
* out-of-scope verdict in the problems file.
|
|
8
|
-
*/
|
|
9
|
-
export declare function createConversionJobImplementation({ conversionsDirectory, }: {
|
|
10
|
-
conversionsDirectory: string;
|
|
11
|
-
}): JobImplementation<typeof conversionJob>;
|
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { implementJob } from '@williamthorsen/telefactor/server';
|
|
4
|
-
import { describeError } from '@williamthorsen/toolbelt.errors';
|
|
5
|
-
import { conversionJob, problemsFileSchema } from "../contract/conversion-job.js";
|
|
6
|
-
import { outOfScopeSchema } from "../convert/draft-schema.js";
|
|
7
|
-
import { sanitizeName } from "../convert/sanitize-name.js";
|
|
8
|
-
import { validateConfig } from "../schema/validate-config.js";
|
|
9
|
-
const TAIL_LINES = 20;
|
|
10
|
-
const RELEASED_OUTCOMES = new Set(['cancelled', 'done']);
|
|
11
|
-
export function createConversionJobImplementation({ conversionsDirectory, }) {
|
|
12
|
-
return implementJob(conversionJob, {
|
|
13
|
-
async prepare({ id, harness, prompt, input }) {
|
|
14
|
-
const baseName = sanitizeName(input.name);
|
|
15
|
-
const directory = path.join(conversionsDirectory, id);
|
|
16
|
-
const paths = {
|
|
17
|
-
prompt: path.join(directory, `${baseName}.md`),
|
|
18
|
-
output: path.join(directory, `${baseName}.agent-logic.json`),
|
|
19
|
-
problems: path.join(directory, `${baseName}.problems.json`),
|
|
20
|
-
};
|
|
21
|
-
try {
|
|
22
|
-
await mkdir(directory, { recursive: true });
|
|
23
|
-
await writeFile(paths.prompt, prompt);
|
|
24
|
-
}
|
|
25
|
-
catch (error) {
|
|
26
|
-
await rm(directory, { recursive: true, force: true });
|
|
27
|
-
throw error;
|
|
28
|
-
}
|
|
29
|
-
return {
|
|
30
|
-
placeholders: paths,
|
|
31
|
-
stdin: '',
|
|
32
|
-
async read({ stdout, stderrTail }) {
|
|
33
|
-
const result = (await readOutput(paths.output)) ?? (await readProblems(paths.problems));
|
|
34
|
-
if (result === undefined) {
|
|
35
|
-
const tail = formatOutputTail(stdout, stderrTail);
|
|
36
|
-
throw new Error(`The harness ${harness} exited without writing ${paths.output}.${tail}`);
|
|
37
|
-
}
|
|
38
|
-
return result;
|
|
39
|
-
},
|
|
40
|
-
async release(outcome) {
|
|
41
|
-
if (RELEASED_OUTCOMES.has(outcome))
|
|
42
|
-
await rm(directory, { recursive: true, force: true });
|
|
43
|
-
},
|
|
44
|
-
};
|
|
45
|
-
},
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
function formatOutputTail(stdout, stderrTail) {
|
|
49
|
-
const output = [stdout.trim(), stderrTail.trim()].filter((part) => part !== '').join('\n');
|
|
50
|
-
return output === '' ? '' : `\n${output.split('\n').slice(-TAIL_LINES).join('\n')}`;
|
|
51
|
-
}
|
|
52
|
-
async function readOutput(outputPath) {
|
|
53
|
-
let text;
|
|
54
|
-
try {
|
|
55
|
-
text = await readFile(outputPath, 'utf8');
|
|
56
|
-
}
|
|
57
|
-
catch {
|
|
58
|
-
return undefined;
|
|
59
|
-
}
|
|
60
|
-
let value;
|
|
61
|
-
try {
|
|
62
|
-
value = JSON.parse(text);
|
|
63
|
-
}
|
|
64
|
-
catch (error) {
|
|
65
|
-
const reason = describeError(error);
|
|
66
|
-
return { ok: false, problems: [{ path: '', message: `The agent-logic file is not valid JSON: ${reason}.` }] };
|
|
67
|
-
}
|
|
68
|
-
const validated = validateConfig(value);
|
|
69
|
-
return validated.ok ? { ok: true, config: validated.config, text } : validated;
|
|
70
|
-
}
|
|
71
|
-
async function readProblems(problemsPath) {
|
|
72
|
-
let value;
|
|
73
|
-
try {
|
|
74
|
-
value = JSON.parse(await readFile(problemsPath, 'utf8'));
|
|
75
|
-
}
|
|
76
|
-
catch {
|
|
77
|
-
return undefined;
|
|
78
|
-
}
|
|
79
|
-
const verdict = outOfScopeSchema.safeParse(value);
|
|
80
|
-
if (verdict.success)
|
|
81
|
-
return { ok: false, outOfScope: verdict.data.outOfScope };
|
|
82
|
-
const parsed = problemsFileSchema.safeParse(value);
|
|
83
|
-
return parsed.success ? { ok: false, problems: parsed.data.problems } : undefined;
|
|
84
|
-
}
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import type { HarnessSettingsResult } from '@williamthorsen/telefactor/server';
|
|
2
|
-
import { type Context, type Env, Hono } from 'hono';
|
|
3
|
-
import type { z } from 'zod';
|
|
4
|
-
import type { viewerConfigSchema } from '../contract/built-in-harnesses.js';
|
|
5
|
-
import type { PromptDirectoryListing, PromptFileRead } from './prompt-directory.js';
|
|
6
|
-
/** The harness settings with the viewer's own keys, as `readHarnessSettings` resolves them. */
|
|
7
|
-
export type ViewerSettingsResult = HarnessSettingsResult<z.output<typeof viewerConfigSchema>>;
|
|
8
|
-
interface PromptsAppOptions<E extends Env> {
|
|
9
|
-
/** Resolves the settings; called on each request, so that an edit applies at once. */
|
|
10
|
-
readSettings: () => Promise<ViewerSettingsResult>;
|
|
11
|
-
/** Decides whether a request may reach the routes; a rejected request gets `403`. */
|
|
12
|
-
isAllowed: (context: Context<E>) => boolean;
|
|
13
|
-
listPrompts: (directory: string) => Promise<PromptDirectoryListing>;
|
|
14
|
-
/** Returns the text of a file in the prompts directory, if a listing of the directory names it. */
|
|
15
|
-
readPromptFile: (directory: string, fileName: string) => Promise<PromptFileRead>;
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* Creates the HTTP app that lists the prompts directory that the settings name at `/` and returns the text of a listed
|
|
19
|
-
* file at `/files/:fileName`.
|
|
20
|
-
*/
|
|
21
|
-
export declare function createPromptsApp<E extends Env>({ readSettings, isAllowed, listPrompts, readPromptFile, }: PromptsAppOptions<E>): Hono<E>;
|
|
22
|
-
/** Returns the prompts directory as an absolute path, resolved against the config file's directory. */
|
|
23
|
-
export declare function resolvePromptsDirectory({ configPath, settings }: Extract<ViewerSettingsResult, {
|
|
24
|
-
ok: true;
|
|
25
|
-
}>): string;
|
|
26
|
-
export {};
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import path from 'node:path';
|
|
2
|
-
import { Hono } from 'hono';
|
|
3
|
-
export function createPromptsApp({ readSettings, isAllowed, listPrompts, readPromptFile, }) {
|
|
4
|
-
const app = new Hono();
|
|
5
|
-
app.use(async (context, next) => {
|
|
6
|
-
if (isAllowed(context)) {
|
|
7
|
-
await next();
|
|
8
|
-
}
|
|
9
|
-
else {
|
|
10
|
-
context.res = context.json({ error: 'The prompts routes accept only local requests.' }, 403);
|
|
11
|
-
}
|
|
12
|
-
});
|
|
13
|
-
app.get('/', async (context) => {
|
|
14
|
-
const resolved = await readSettings();
|
|
15
|
-
if (!resolved.ok)
|
|
16
|
-
return context.json({ problems: resolved.problems }, 400);
|
|
17
|
-
const { configPath } = resolved;
|
|
18
|
-
const directory = resolvePromptsDirectory(resolved);
|
|
19
|
-
const listing = await listPrompts(directory);
|
|
20
|
-
const list = listing.ok
|
|
21
|
-
? { directory, configPath, entries: listing.entries }
|
|
22
|
-
: { directory, configPath, missing: true };
|
|
23
|
-
return context.json(list);
|
|
24
|
-
});
|
|
25
|
-
app.get('/files/:fileName', async (context) => {
|
|
26
|
-
const resolved = await readSettings();
|
|
27
|
-
if (!resolved.ok)
|
|
28
|
-
return context.json({ problems: resolved.problems }, 400);
|
|
29
|
-
const fileName = context.req.param('fileName');
|
|
30
|
-
const read = await readPromptFile(resolvePromptsDirectory(resolved), fileName);
|
|
31
|
-
if (read.ok)
|
|
32
|
-
return context.json({ text: read.text });
|
|
33
|
-
return read.reason === 'too-large'
|
|
34
|
-
? context.json({ error: `${fileName} is larger than 1 MiB.` }, 413)
|
|
35
|
-
: context.json({ error: `The prompts directory does not list ${fileName}.` }, 404);
|
|
36
|
-
});
|
|
37
|
-
return app;
|
|
38
|
-
}
|
|
39
|
-
export function resolvePromptsDirectory({ configPath, settings }) {
|
|
40
|
-
return path.resolve(path.dirname(configPath), settings.app.promptsDirectory);
|
|
41
|
-
}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import type { Plugin } from 'vite';
|
|
2
|
-
/** The variable whose JSON argv replaces every other harness. */
|
|
3
|
-
export declare const HARNESS_COMMAND_VARIABLE = "AGENT_LOGIC_HARNESS_COMMAND";
|
|
4
|
-
/** The config file, resolved against the Vite root. */
|
|
5
|
-
export declare const HARNESS_CONFIG_FILE = "harness.config.json";
|
|
6
|
-
/** The path under which the prompts routes are mounted. */
|
|
7
|
-
export declare const PROMPTS_BASE_PATH = "/api/prompts";
|
|
8
|
-
/**
|
|
9
|
-
* Creates the dev-server plugins: telefactor's harness, job, terminal, and contract routes under `/api/telefactor`,
|
|
10
|
-
* running the conversion job with a directory of its own for each run under `conversionsDirectory`, and the prompts
|
|
11
|
-
* routes under `/api/prompts`.
|
|
12
|
-
*/
|
|
13
|
-
export declare function createViewerServerPlugins({ conversionsDirectory }: {
|
|
14
|
-
conversionsDirectory: string;
|
|
15
|
-
}): Plugin[];
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import { mkdirSync } from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { getRequestListener } from '@hono/node-server';
|
|
4
|
-
import { isLoopbackRequest, isSameOriginRequest, readHarnessSettings, readRequestHost, } from '@williamthorsen/telefactor/server';
|
|
5
|
-
import { telefactor } from '@williamthorsen/telefactor/vite';
|
|
6
|
-
import { DEFAULT_PROMPTS_DIRECTORY, viewerBuiltInHarnesses, viewerConfigSchema, } from "../contract/built-in-harnesses.js";
|
|
7
|
-
import { createConversionJobImplementation } from "./conversion-job-implementation.js";
|
|
8
|
-
import { createPromptsApp } from "./create-prompts-app.js";
|
|
9
|
-
import { listPromptDirectory, readPromptDirectoryFile } from "./prompt-directory.js";
|
|
10
|
-
import { createViewerContractImplementation } from "./viewer-contract-implementation.js";
|
|
11
|
-
export const HARNESS_COMMAND_VARIABLE = 'AGENT_LOGIC_HARNESS_COMMAND';
|
|
12
|
-
export const HARNESS_CONFIG_FILE = 'harness.config.json';
|
|
13
|
-
export const PROMPTS_BASE_PATH = '/api/prompts';
|
|
14
|
-
export function createViewerServerPlugins({ conversionsDirectory }) {
|
|
15
|
-
let root;
|
|
16
|
-
return [
|
|
17
|
-
{
|
|
18
|
-
name: 'agent-logic-root',
|
|
19
|
-
configResolved(config) {
|
|
20
|
-
root = config.root;
|
|
21
|
-
},
|
|
22
|
-
},
|
|
23
|
-
telefactor({
|
|
24
|
-
builtIn: viewerBuiltInHarnesses,
|
|
25
|
-
commandVariable: HARNESS_COMMAND_VARIABLE,
|
|
26
|
-
config: viewerConfigSchema,
|
|
27
|
-
configPath: HARNESS_CONFIG_FILE,
|
|
28
|
-
contract: createViewerContractImplementation({
|
|
29
|
-
readSettings: () => {
|
|
30
|
-
if (root === undefined)
|
|
31
|
-
throw new Error('The dev server has not resolved its root.');
|
|
32
|
-
return readViewerSettings(root);
|
|
33
|
-
},
|
|
34
|
-
}),
|
|
35
|
-
job: createConversionJobImplementation({ conversionsDirectory }),
|
|
36
|
-
}),
|
|
37
|
-
createPromptsServerPlugin(),
|
|
38
|
-
];
|
|
39
|
-
}
|
|
40
|
-
function createPromptsServerPlugin() {
|
|
41
|
-
return {
|
|
42
|
-
name: 'agent-logic-prompts',
|
|
43
|
-
apply: 'serve',
|
|
44
|
-
configureServer(server) {
|
|
45
|
-
const { root } = server.config;
|
|
46
|
-
mkdirSync(path.join(root, DEFAULT_PROMPTS_DIRECTORY), { recursive: true });
|
|
47
|
-
const app = createPromptsApp({
|
|
48
|
-
readSettings: () => readViewerSettings(root),
|
|
49
|
-
isAllowed: (context) => isLoopbackRequest({
|
|
50
|
-
host: readRequestHost(context.req.header('host'), context.env.incoming),
|
|
51
|
-
remoteAddress: context.env.incoming.socket.remoteAddress,
|
|
52
|
-
}) &&
|
|
53
|
-
isSameOriginRequest({
|
|
54
|
-
origin: context.req.header('origin'),
|
|
55
|
-
secFetchSite: context.req.header('sec-fetch-site'),
|
|
56
|
-
url: context.req.url,
|
|
57
|
-
}),
|
|
58
|
-
listPrompts: listPromptDirectory,
|
|
59
|
-
readPromptFile: readPromptDirectoryFile,
|
|
60
|
-
});
|
|
61
|
-
const listener = getRequestListener((request, env) => app.fetch(request, env), { overrideGlobalObjects: false });
|
|
62
|
-
server.middlewares.use(PROMPTS_BASE_PATH, (request, response) => {
|
|
63
|
-
void listener(request, response);
|
|
64
|
-
});
|
|
65
|
-
},
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
function readViewerSettings(root) {
|
|
69
|
-
return readHarnessSettings({
|
|
70
|
-
env: process.env,
|
|
71
|
-
configPath: path.join(root, HARNESS_CONFIG_FILE),
|
|
72
|
-
builtIn: viewerBuiltInHarnesses,
|
|
73
|
-
commandVariable: HARNESS_COMMAND_VARIABLE,
|
|
74
|
-
config: viewerConfigSchema,
|
|
75
|
-
});
|
|
76
|
-
}
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
/** A base name and the prompt and agent-logic files that share it. */
|
|
3
|
-
export declare const promptEntrySchema: z.ZodObject<{
|
|
4
|
-
name: z.ZodString;
|
|
5
|
-
promptFile: z.ZodOptional<z.ZodString>;
|
|
6
|
-
agentLogicFile: z.ZodOptional<z.ZodString>;
|
|
7
|
-
}, z.core.$strip>;
|
|
8
|
-
export type PromptEntry = z.infer<typeof promptEntrySchema>;
|
|
9
|
-
/**
|
|
10
|
-
* The body of a `200` from `GET /prompts`: the absolute directory, the config file that names it, and its entries, or
|
|
11
|
-
* `missing` when the directory does not exist.
|
|
12
|
-
*/
|
|
13
|
-
export declare const promptListSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
14
|
-
directory: z.ZodString;
|
|
15
|
-
configPath: z.ZodString;
|
|
16
|
-
entries: z.ZodArray<z.ZodObject<{
|
|
17
|
-
name: z.ZodString;
|
|
18
|
-
promptFile: z.ZodOptional<z.ZodString>;
|
|
19
|
-
agentLogicFile: z.ZodOptional<z.ZodString>;
|
|
20
|
-
}, z.core.$strip>>;
|
|
21
|
-
}, z.core.$strip>, z.ZodObject<{
|
|
22
|
-
directory: z.ZodString;
|
|
23
|
-
configPath: z.ZodString;
|
|
24
|
-
missing: z.ZodLiteral<true>;
|
|
25
|
-
}, z.core.$strip>]>;
|
|
26
|
-
export type PromptList = z.infer<typeof promptListSchema>;
|
|
27
|
-
/** The body of a `200` from `GET /prompts/files/{fileName}`. */
|
|
28
|
-
export declare const promptFileSchema: z.ZodObject<{
|
|
29
|
-
text: z.ZodString;
|
|
30
|
-
}, z.core.$strip>;
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
export const promptEntrySchema = z.object({
|
|
3
|
-
name: z.string(),
|
|
4
|
-
promptFile: z.string().optional(),
|
|
5
|
-
agentLogicFile: z.string().optional(),
|
|
6
|
-
});
|
|
7
|
-
export const promptListSchema = z.union([
|
|
8
|
-
z.object({ directory: z.string(), configPath: z.string(), entries: z.array(promptEntrySchema) }),
|
|
9
|
-
z.object({ directory: z.string(), configPath: z.string(), missing: z.literal(true) }),
|
|
10
|
-
]);
|
|
11
|
-
export const promptFileSchema = z.object({ text: z.string() });
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import type { PromptEntry } from './prompt-directory-schemas.js';
|
|
2
|
-
/** The largest file, in bytes, that the file route returns. */
|
|
3
|
-
export declare const MAX_PROMPT_FILE_BYTES: number;
|
|
4
|
-
/** A directory's entries, sorted by name, or `missing` when the directory does not exist. */
|
|
5
|
-
export type PromptDirectoryListing = {
|
|
6
|
-
ok: true;
|
|
7
|
-
entries: PromptEntry[];
|
|
8
|
-
} | {
|
|
9
|
-
ok: false;
|
|
10
|
-
reason: 'missing';
|
|
11
|
-
};
|
|
12
|
-
/** The text of a listed file, or why it is not returned. */
|
|
13
|
-
export type PromptFileRead = {
|
|
14
|
-
ok: true;
|
|
15
|
-
text: string;
|
|
16
|
-
} | {
|
|
17
|
-
ok: false;
|
|
18
|
-
reason: 'missing' | 'not-listed' | 'too-large';
|
|
19
|
-
};
|
|
20
|
-
/**
|
|
21
|
-
* Lists the prompts and agent-logic files in a directory, grouped by base name. Only regular files are listed, so a
|
|
22
|
-
* subdirectory or a symlink is not; a dotfile and a file with another name are not either.
|
|
23
|
-
*/
|
|
24
|
-
export declare function listPromptDirectory(directory: string): Promise<PromptDirectoryListing>;
|
|
25
|
-
/**
|
|
26
|
-
* Returns the text of a file that a fresh listing of the directory names, never joining an unlisted name onto the
|
|
27
|
-
* directory, so that a name cannot reach outside it.
|
|
28
|
-
*/
|
|
29
|
-
export declare function readPromptDirectoryFile(directory: string, fileName: string): Promise<PromptFileRead>;
|
|
30
|
-
/**
|
|
31
|
-
* Writes a new file to the directory, refusing a name that already exists so that a write never replaces a file. The
|
|
32
|
-
* name must not contain a path separator.
|
|
33
|
-
*/
|
|
34
|
-
export declare function writePromptDirectoryFile(directory: string, fileName: string, text: string): Promise<{
|
|
35
|
-
ok: true;
|
|
36
|
-
path: string;
|
|
37
|
-
} | {
|
|
38
|
-
ok: false;
|
|
39
|
-
reason: 'exists';
|
|
40
|
-
}>;
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { readdir, readFile, stat, writeFile } from 'node:fs/promises';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
export const MAX_PROMPT_FILE_BYTES = 1024 * 1024;
|
|
4
|
-
const AGENT_LOGIC_SUFFIX = '.agent-logic.json';
|
|
5
|
-
const PROMPT_EXTENSIONS = ['.md', '.txt'];
|
|
6
|
-
export async function listPromptDirectory(directory) {
|
|
7
|
-
let names;
|
|
8
|
-
try {
|
|
9
|
-
const dirents = await readdir(directory, { withFileTypes: true });
|
|
10
|
-
names = dirents.filter((dirent) => dirent.isFile() && !dirent.name.startsWith('.')).map((dirent) => dirent.name);
|
|
11
|
-
}
|
|
12
|
-
catch (error) {
|
|
13
|
-
if (isMissing(error))
|
|
14
|
-
return { ok: false, reason: 'missing' };
|
|
15
|
-
throw error;
|
|
16
|
-
}
|
|
17
|
-
const entries = new Map();
|
|
18
|
-
for (const name of names) {
|
|
19
|
-
const match = classify(name);
|
|
20
|
-
if (match === undefined)
|
|
21
|
-
continue;
|
|
22
|
-
const entry = entries.get(match.base) ?? { name: match.base };
|
|
23
|
-
if (match.kind === 'agent-logic')
|
|
24
|
-
entry.agentLogicFile = name;
|
|
25
|
-
else if (entry.promptFile === undefined || rankPrompt(name) < rankPrompt(entry.promptFile))
|
|
26
|
-
entry.promptFile = name;
|
|
27
|
-
entries.set(match.base, entry);
|
|
28
|
-
}
|
|
29
|
-
return {
|
|
30
|
-
ok: true,
|
|
31
|
-
entries: entries
|
|
32
|
-
.values()
|
|
33
|
-
.toArray()
|
|
34
|
-
.toSorted((a, b) => compareNames(a.name, b.name)),
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
export async function readPromptDirectoryFile(directory, fileName) {
|
|
38
|
-
const listing = await listPromptDirectory(directory);
|
|
39
|
-
if (!listing.ok)
|
|
40
|
-
return { ok: false, reason: 'missing' };
|
|
41
|
-
const isListed = listing.entries.some((entry) => entry.promptFile === fileName || entry.agentLogicFile === fileName);
|
|
42
|
-
if (!isListed)
|
|
43
|
-
return { ok: false, reason: 'not-listed' };
|
|
44
|
-
const filePath = path.join(directory, fileName);
|
|
45
|
-
try {
|
|
46
|
-
if ((await stat(filePath)).size > MAX_PROMPT_FILE_BYTES)
|
|
47
|
-
return { ok: false, reason: 'too-large' };
|
|
48
|
-
return { ok: true, text: await readFile(filePath, 'utf8') };
|
|
49
|
-
}
|
|
50
|
-
catch (error) {
|
|
51
|
-
if (isMissing(error))
|
|
52
|
-
return { ok: false, reason: 'not-listed' };
|
|
53
|
-
throw error;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
export async function writePromptDirectoryFile(directory, fileName, text) {
|
|
57
|
-
const filePath = path.join(directory, fileName);
|
|
58
|
-
try {
|
|
59
|
-
await writeFile(filePath, text, { encoding: 'utf8', flag: 'wx' });
|
|
60
|
-
}
|
|
61
|
-
catch (error) {
|
|
62
|
-
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'EEXIST') {
|
|
63
|
-
return { ok: false, reason: 'exists' };
|
|
64
|
-
}
|
|
65
|
-
throw error;
|
|
66
|
-
}
|
|
67
|
-
return { ok: true, path: filePath };
|
|
68
|
-
}
|
|
69
|
-
function classify(name) {
|
|
70
|
-
if (name.endsWith(AGENT_LOGIC_SUFFIX))
|
|
71
|
-
return toMatch(name.slice(0, -AGENT_LOGIC_SUFFIX.length), 'agent-logic');
|
|
72
|
-
const extension = PROMPT_EXTENSIONS.find((candidate) => name.endsWith(candidate));
|
|
73
|
-
return extension === undefined ? undefined : toMatch(name.slice(0, -extension.length), 'prompt');
|
|
74
|
-
}
|
|
75
|
-
function compareNames(a, b) {
|
|
76
|
-
return a.localeCompare(b, 'en', { numeric: true });
|
|
77
|
-
}
|
|
78
|
-
function isMissing(error) {
|
|
79
|
-
return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';
|
|
80
|
-
}
|
|
81
|
-
function rankPrompt(name) {
|
|
82
|
-
return PROMPT_EXTENSIONS.findIndex((extension) => name.endsWith(extension));
|
|
83
|
-
}
|
|
84
|
-
function toMatch(base, kind) {
|
|
85
|
-
return base === '' ? undefined : { base, kind };
|
|
86
|
-
}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { type ContractImplementation } from '@williamthorsen/telefactor/server';
|
|
2
|
-
import { type ViewerSettingsResult } from './create-prompts-app.js';
|
|
3
|
-
interface ViewerContractOptions {
|
|
4
|
-
/** Resolves the settings; called by each action that reaches the prompts directory, so that an edit applies at once. */
|
|
5
|
-
readSettings: () => Promise<ViewerSettingsResult>;
|
|
6
|
-
}
|
|
7
|
-
/**
|
|
8
|
-
* Implements the viewer's contract on the dev server: the prompts-directory actions read the directory that the
|
|
9
|
-
* settings name, and a refusal throws, which leaves the state unchanged and names the reason to the caller.
|
|
10
|
-
*/
|
|
11
|
-
export declare function createViewerContractImplementation({ readSettings }: ViewerContractOptions): ContractImplementation;
|
|
12
|
-
export {};
|
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
import { implementContract } from '@williamthorsen/telefactor/server';
|
|
2
|
-
import { viewerContract } from "../contract/viewer-contract.js";
|
|
3
|
-
import { sanitizeName } from "../convert/sanitize-name.js";
|
|
4
|
-
import { describeConfig } from "../layout/describe-config.js";
|
|
5
|
-
import { labelSource } from "../react/hooks/label-source.js";
|
|
6
|
-
import { parseConfigText } from "../react/hooks/parse-config-text.js";
|
|
7
|
-
import { validateConfig } from "../schema/validate-config.js";
|
|
8
|
-
import { resolvePromptsDirectory } from "./create-prompts-app.js";
|
|
9
|
-
import { listPromptDirectory, MAX_PROMPT_FILE_BYTES, readPromptDirectoryFile, writePromptDirectoryFile, } from "./prompt-directory.js";
|
|
10
|
-
export function createViewerContractImplementation({ readSettings }) {
|
|
11
|
-
return implementContract(viewerContract, {
|
|
12
|
-
initialState: {},
|
|
13
|
-
handlers: {
|
|
14
|
-
save_prompt: async (state, { name, text }) => {
|
|
15
|
-
if (name.trim() === '')
|
|
16
|
-
throw new Error('Enter a name.');
|
|
17
|
-
if (!/[a-z0-9]/i.test(name))
|
|
18
|
-
throw new Error('Enter a name that contains a letter from a to z or a digit.');
|
|
19
|
-
if (Buffer.byteLength(text, 'utf8') > MAX_PROMPT_FILE_BYTES) {
|
|
20
|
-
throw new Error('The prompt is larger than 1 MiB, which the prompts directory does not read.');
|
|
21
|
-
}
|
|
22
|
-
const directory = await readDirectory(readSettings);
|
|
23
|
-
const base = sanitizeName(name);
|
|
24
|
-
const listing = await listPromptDirectory(directory);
|
|
25
|
-
if (!listing.ok)
|
|
26
|
-
throw new Error(`The prompts directory ${directory} does not exist.`);
|
|
27
|
-
const taken = `The prompts directory already has files named ${base}. Choose another name.`;
|
|
28
|
-
if (listing.entries.some((entry) => entry.name === base))
|
|
29
|
-
throw new Error(taken);
|
|
30
|
-
const fileName = `${base}.md`;
|
|
31
|
-
const written = await writePromptDirectoryFile(directory, fileName, text);
|
|
32
|
-
if (!written.ok)
|
|
33
|
-
throw new Error(taken);
|
|
34
|
-
return { ...state, savedPrompt: { fileName, path: written.path } };
|
|
35
|
-
},
|
|
36
|
-
load_chart: async (state, { fileName }) => {
|
|
37
|
-
const directory = await readDirectory(readSettings);
|
|
38
|
-
const read = await readPromptDirectoryFile(directory, fileName);
|
|
39
|
-
if (!read.ok) {
|
|
40
|
-
throw new Error(read.reason === 'too-large'
|
|
41
|
-
? `${fileName} is larger than 1 MiB.`
|
|
42
|
-
: `The prompts directory does not list ${fileName}. Pass a file name from ${directory}, not a path.`);
|
|
43
|
-
}
|
|
44
|
-
const parsed = parseConfigText(read.text, 'file');
|
|
45
|
-
if (!parsed.ok)
|
|
46
|
-
throw new Error(formatProblems(fileName, parsed.problems));
|
|
47
|
-
const validated = validateConfig(parsed.value);
|
|
48
|
-
if (!validated.ok)
|
|
49
|
-
throw new Error(formatProblems(fileName, validated.problems));
|
|
50
|
-
return {
|
|
51
|
-
...state,
|
|
52
|
-
chart: { ...labelSource({ kind: 'file', fileName }), config: validated.config },
|
|
53
|
-
selectedPath: undefined,
|
|
54
|
-
};
|
|
55
|
-
},
|
|
56
|
-
show_chart: (state, chart) => ({ ...state, chart, selectedPath: undefined }),
|
|
57
|
-
select_element: (state, { path }) => {
|
|
58
|
-
if (path === undefined)
|
|
59
|
-
return { ...state, selectedPath: undefined };
|
|
60
|
-
if (state.chart === undefined)
|
|
61
|
-
throw new Error('No chart is loaded.');
|
|
62
|
-
if (!listElementPaths(state.chart.config).has(path)) {
|
|
63
|
-
throw new Error(`The loaded chart does not contain an element at ${path}.`);
|
|
64
|
-
}
|
|
65
|
-
return { ...state, selectedPath: path };
|
|
66
|
-
},
|
|
67
|
-
},
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
function formatProblems(fileName, problems) {
|
|
71
|
-
const lines = problems.map(({ path, message }) => (path === '' ? `- ${message}` : `- ${path}: ${message}`));
|
|
72
|
-
return [`${fileName} is not a valid agent-logic file:`, ...lines].join('\n');
|
|
73
|
-
}
|
|
74
|
-
function listElementPaths(config) {
|
|
75
|
-
const { states, transitions, ambient } = describeConfig(config);
|
|
76
|
-
return new Set([...states, ...transitions, ...ambient].map((element) => element.path));
|
|
77
|
-
}
|
|
78
|
-
async function readDirectory(readSettings) {
|
|
79
|
-
const resolved = await readSettings();
|
|
80
|
-
if (!resolved.ok) {
|
|
81
|
-
const lines = resolved.problems.map(({ path, message }) => (path === '' ? message : `${path}: ${message}`));
|
|
82
|
-
throw new Error(['The harness config file has problems:', ...lines].join('\n'));
|
|
83
|
-
}
|
|
84
|
-
return resolvePromptsDirectory(resolved);
|
|
85
|
-
}
|
|
File without changes
|
|
File without changes
|