@kana-ai/edgar-sdk 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/README.md +430 -2
- package/dist/src/build/cli.d.ts +6 -0
- package/dist/src/build/cli.js +110 -0
- package/dist/src/build/json.d.ts +2 -0
- package/dist/src/build/json.js +71 -0
- package/dist/src/build/manifest.d.ts +15 -0
- package/dist/src/build/manifest.js +111 -0
- package/dist/src/define/card-block.d.ts +15 -0
- package/dist/src/define/card-block.js +66 -0
- package/dist/src/define/context.d.ts +60 -0
- package/dist/src/define/context.js +1 -0
- package/dist/src/define/extension.d.ts +58 -0
- package/dist/src/define/extension.js +14 -0
- package/dist/src/define/hook.d.ts +61 -0
- package/dist/src/define/hook.js +72 -0
- package/dist/src/define/service.d.ts +32 -0
- package/dist/src/define/service.js +33 -0
- package/dist/src/define/tool.d.ts +93 -0
- package/dist/src/define/tool.js +24 -0
- package/dist/src/define/tracker.d.ts +59 -0
- package/dist/src/define/tracker.js +27 -0
- package/dist/src/index.d.ts +15 -0
- package/dist/src/index.js +12 -0
- package/dist/src/outcome/end.d.ts +61 -0
- package/dist/src/outcome/end.js +292 -0
- package/dist/src/outcome/failures.d.ts +15 -0
- package/dist/src/outcome/failures.js +57 -0
- package/dist/src/outcome/limits.d.ts +13 -0
- package/dist/src/outcome/limits.js +115 -0
- package/dist/src/outcome/outcome.d.ts +32 -0
- package/dist/src/outcome/outcome.js +59 -0
- package/dist/src/outcome/plain.d.ts +7 -0
- package/dist/src/outcome/plain.js +55 -0
- package/dist/src/outcome/result.d.ts +35 -0
- package/dist/src/outcome/result.js +58 -0
- package/dist/src/provider/child.d.ts +51 -0
- package/dist/src/provider/child.js +152 -0
- package/dist/src/provider/serve.d.ts +42 -0
- package/dist/src/provider/serve.js +175 -0
- package/dist/src/runtime/index.d.ts +4 -0
- package/dist/src/runtime/index.js +3 -0
- package/dist/src/runtime/invoke.d.ts +10 -0
- package/dist/src/runtime/invoke.js +232 -0
- package/dist/src/runtime/network.d.ts +20 -0
- package/dist/src/runtime/network.js +120 -0
- package/dist/src/runtime/ports.d.ts +31 -0
- package/dist/src/runtime/ports.js +1 -0
- package/dist/src/runtime/secrets.d.ts +13 -0
- package/dist/src/runtime/secrets.js +33 -0
- package/dist/src/testing/context.d.ts +12 -0
- package/dist/src/testing/context.js +39 -0
- package/dist/src/testing/index.d.ts +3 -0
- package/dist/src/testing/index.js +3 -0
- package/dist/src/testing/mock.d.ts +16 -0
- package/dist/src/testing/mock.js +39 -0
- package/dist/src/wire/codec.d.ts +46 -0
- package/dist/src/wire/codec.js +134 -0
- package/dist/src/wire/lines.d.ts +10 -0
- package/dist/src/wire/lines.js +41 -0
- package/package.json +48 -3
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
const WIDTH = 100;
|
|
2
|
+
function isRecord(value) {
|
|
3
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
function entries(value) {
|
|
6
|
+
return Object.entries(value).filter(([, v]) => v !== undefined);
|
|
7
|
+
}
|
|
8
|
+
function flat(value) {
|
|
9
|
+
if (Array.isArray(value)) {
|
|
10
|
+
const parts = value.map(flat);
|
|
11
|
+
return parts.every((part) => part !== undefined) ? `[${parts.join(", ")}]` : undefined;
|
|
12
|
+
}
|
|
13
|
+
if (isRecord(value))
|
|
14
|
+
return entries(value).length === 0 ? "{}" : undefined;
|
|
15
|
+
return JSON.stringify(value);
|
|
16
|
+
}
|
|
17
|
+
function nested(value) {
|
|
18
|
+
if (Array.isArray(value))
|
|
19
|
+
return value.length > 1 ? 2 : 0;
|
|
20
|
+
return isRecord(value) && entries(value).length > 1 ? 1 : 0;
|
|
21
|
+
}
|
|
22
|
+
/** The numbers of a broken array, as many to a line as fit in 100 columns with their commas. */
|
|
23
|
+
function fill(numbers, inner) {
|
|
24
|
+
const lines = [];
|
|
25
|
+
let line = "";
|
|
26
|
+
for (const [i, item] of numbers.entries()) {
|
|
27
|
+
const part = `${JSON.stringify(item)}${i < numbers.length - 1 ? "," : ""}`;
|
|
28
|
+
const next = line === "" ? inner + part : `${line} ${part}`;
|
|
29
|
+
if (line !== "" && next.length > WIDTH) {
|
|
30
|
+
lines.push(line);
|
|
31
|
+
line = inner + part;
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
line = next;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
lines.push(line);
|
|
38
|
+
return lines;
|
|
39
|
+
}
|
|
40
|
+
function print(value, indent, used) {
|
|
41
|
+
const inner = `${indent} `;
|
|
42
|
+
if (Array.isArray(value)) {
|
|
43
|
+
if (value.length === 0)
|
|
44
|
+
return "[]";
|
|
45
|
+
const first = nested(value[0]);
|
|
46
|
+
const grid = value.length > 1 && first > 0 && value.every((item) => nested(item) === first);
|
|
47
|
+
const line = grid ? undefined : flat(value);
|
|
48
|
+
if (line !== undefined && used + line.length <= WIDTH)
|
|
49
|
+
return line;
|
|
50
|
+
if (value.length > 1 && value.every((item) => typeof item === "number")) {
|
|
51
|
+
return `[\n${fill(value, inner).join("\n")}\n${indent}]`;
|
|
52
|
+
}
|
|
53
|
+
const items = value.map((item, i) => inner + print(item, inner, inner.length + (i < value.length - 1 ? 1 : 0)));
|
|
54
|
+
return `[\n${items.join(",\n")}\n${indent}]`;
|
|
55
|
+
}
|
|
56
|
+
if (isRecord(value)) {
|
|
57
|
+
const pairs = entries(value);
|
|
58
|
+
if (pairs.length === 0)
|
|
59
|
+
return "{}";
|
|
60
|
+
const lines = pairs.map(([key, item], i) => {
|
|
61
|
+
const head = `${inner}${JSON.stringify(key)}: `;
|
|
62
|
+
return head + print(item, inner, head.length + (i < pairs.length - 1 ? 1 : 0));
|
|
63
|
+
});
|
|
64
|
+
return `{\n${lines.join(",\n")}\n${indent}}`;
|
|
65
|
+
}
|
|
66
|
+
return JSON.stringify(value);
|
|
67
|
+
}
|
|
68
|
+
/** `value` as the JSON text oxfmt keeps as it is: each object key on its own line, an array on one line when it fits in 100 columns, and a longer array of numbers filled several to a line. */
|
|
69
|
+
export function formatJson(value) {
|
|
70
|
+
return `${print(value, "", 0)}\n`;
|
|
71
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Manifest } from "@kana-ai/edgar-contracts/manifest";
|
|
2
|
+
import type { Extension } from "#define/extension";
|
|
3
|
+
/** A manifest and the schema files it names, by path relative to the extension's folder. */
|
|
4
|
+
export interface Built {
|
|
5
|
+
readonly manifest: Manifest;
|
|
6
|
+
readonly files: ReadonlyMap<string, Record<string, unknown>>;
|
|
7
|
+
}
|
|
8
|
+
/** Turns an extension value into its manifest and schema files; it never runs `execute`. */
|
|
9
|
+
export declare function toManifest(extension: Extension, version: string): Built;
|
|
10
|
+
/**
|
|
11
|
+
* One line for each `network:<host>` of a tool, hook, service, tracker or environment step that holds a secret
|
|
12
|
+
* while no secret that it holds lists the host. The engine gives such a call only the hosts of its secrets,
|
|
13
|
+
* so the capability is removed at each call and the code fails where no unit test looks.
|
|
14
|
+
*/
|
|
15
|
+
export declare function unlistedHosts(manifest: Manifest): string[];
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { trackerMethods } from "#define/tracker";
|
|
2
|
+
import { CONTRACT } from "#wire/codec";
|
|
3
|
+
/** An event hook's kinds; `defineEventHook` takes at least one. */
|
|
4
|
+
function eventKinds(kinds) {
|
|
5
|
+
const [first, ...rest] = kinds;
|
|
6
|
+
if (first === undefined)
|
|
7
|
+
throw new Error("an event hook takes at least one event kind");
|
|
8
|
+
return [first, ...rest];
|
|
9
|
+
}
|
|
10
|
+
/** Turns an extension value into its manifest and schema files; it never runs `execute`. */
|
|
11
|
+
export function toManifest(extension, version) {
|
|
12
|
+
const files = new Map();
|
|
13
|
+
const schema = (path, value) => {
|
|
14
|
+
files.set(path, value["~standard"].jsonSchema.input({ target: "draft-2020-12" }));
|
|
15
|
+
return path;
|
|
16
|
+
};
|
|
17
|
+
const step = (prefix, tool) => ({
|
|
18
|
+
description: tool.description,
|
|
19
|
+
input_schema: schema(`schemas/${prefix}.in.json`, tool.input),
|
|
20
|
+
output_schema: schema(`schemas/${prefix}.out.json`, tool.output),
|
|
21
|
+
secrets: [...tool.secrets],
|
|
22
|
+
capabilities: [...tool.capabilities],
|
|
23
|
+
});
|
|
24
|
+
const tool = (name, value) => ({
|
|
25
|
+
name,
|
|
26
|
+
...step(name, value),
|
|
27
|
+
side_effect: value.side_effect,
|
|
28
|
+
...(value.compensate === undefined ? {} : { compensate: value.compensate }),
|
|
29
|
+
...(value.lookup === undefined ? {} : { lookup: value.lookup }),
|
|
30
|
+
...(value.undo === undefined ? {} : { undo: value.undo }),
|
|
31
|
+
...(value.undo_reason === undefined ? {} : { undo_reason: value.undo_reason }),
|
|
32
|
+
approval: typeof value.approval === "object" ? "auto" : value.approval,
|
|
33
|
+
disabled: value.disabled,
|
|
34
|
+
});
|
|
35
|
+
const tracker = extension.tracker;
|
|
36
|
+
const requires = [...(extension.executables?.requires ?? [])];
|
|
37
|
+
const provides = [...(extension.executables?.provides ?? [])];
|
|
38
|
+
const manifest = {
|
|
39
|
+
contract: CONTRACT,
|
|
40
|
+
name: extension.name,
|
|
41
|
+
version,
|
|
42
|
+
config_schema: extension.config === undefined ? null : schema("schemas/config.json", extension.config),
|
|
43
|
+
secrets: Object.entries(extension.secrets ?? {}).map(([name, s]) => ({
|
|
44
|
+
name,
|
|
45
|
+
hosts: [...s.hosts],
|
|
46
|
+
...(s.help === undefined ? {} : { help: s.help }),
|
|
47
|
+
})),
|
|
48
|
+
capabilities: [...(extension.capabilities ?? [])],
|
|
49
|
+
tools: Object.entries(extension.tools ?? {}).map(([name, value]) => tool(name, value)),
|
|
50
|
+
webhooks: Object.entries(extension.webhooks ?? {}).map(([route, w]) => ({ route, ...w })),
|
|
51
|
+
workflows: [...(extension.workflows ?? [])],
|
|
52
|
+
roles: [...(extension.roles ?? [])],
|
|
53
|
+
skills: [...(extension.skills ?? [])],
|
|
54
|
+
tracker: tracker === undefined
|
|
55
|
+
? null
|
|
56
|
+
: {
|
|
57
|
+
methods: [...trackerMethods],
|
|
58
|
+
secrets: [...tracker.secrets],
|
|
59
|
+
capabilities: [...tracker.capabilities],
|
|
60
|
+
},
|
|
61
|
+
environments: Object.entries(extension.environments ?? {}).map(([name, e]) => ({
|
|
62
|
+
name,
|
|
63
|
+
prepare: step(`environment.${name}.prepare`, e.prepare),
|
|
64
|
+
start: step(`environment.${name}.start`, e.start),
|
|
65
|
+
health: step(`environment.${name}.health`, e.health),
|
|
66
|
+
stop: step(`environment.${name}.stop`, e.stop),
|
|
67
|
+
})),
|
|
68
|
+
hooks: Object.entries(extension.hooks ?? {}).map(([name, h]) => ({
|
|
69
|
+
name,
|
|
70
|
+
on: h.on,
|
|
71
|
+
...(h.on === "event" ? { events: eventKinds(h.events) } : {}),
|
|
72
|
+
secrets: [...h.secrets],
|
|
73
|
+
capabilities: [...h.capabilities],
|
|
74
|
+
})),
|
|
75
|
+
...(extension.service === undefined
|
|
76
|
+
? {}
|
|
77
|
+
: {
|
|
78
|
+
service: {
|
|
79
|
+
secrets: [...extension.service.secrets],
|
|
80
|
+
capabilities: [...extension.service.capabilities],
|
|
81
|
+
},
|
|
82
|
+
}),
|
|
83
|
+
...(requires.length + provides.length === 0 ? {} : { executables: { requires, provides } }),
|
|
84
|
+
};
|
|
85
|
+
return { manifest, files };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* One line for each `network:<host>` of a tool, hook, service, tracker or environment step that holds a secret
|
|
89
|
+
* while no secret that it holds lists the host. The engine gives such a call only the hosts of its secrets,
|
|
90
|
+
* so the capability is removed at each call and the code fails where no unit test looks.
|
|
91
|
+
*/
|
|
92
|
+
export function unlistedHosts(manifest) {
|
|
93
|
+
const callables = [
|
|
94
|
+
...manifest.tools.map((tool) => [`the tool ${tool.name}`, tool]),
|
|
95
|
+
...manifest.hooks.map((hook) => [`the hook ${hook.name}`, hook]),
|
|
96
|
+
...manifest.environments.flatMap((environment) => ["prepare", "start", "health", "stop"].map((name) => [`the ${name} step of the environment ${environment.name}`, environment[name]])),
|
|
97
|
+
...(manifest.tracker === null ? [] : [["the tracker", manifest.tracker]]),
|
|
98
|
+
...(manifest.service === undefined ? [] : [["the service", manifest.service]]),
|
|
99
|
+
];
|
|
100
|
+
return callables.flatMap(([name, { secrets, capabilities }]) => {
|
|
101
|
+
const [first] = secrets;
|
|
102
|
+
if (first === undefined)
|
|
103
|
+
return [];
|
|
104
|
+
const listed = new Set(manifest.secrets.filter((s) => secrets.includes(s.name)).flatMap((s) => s.hosts));
|
|
105
|
+
return capabilities
|
|
106
|
+
.filter((capability) => capability.startsWith("network:"))
|
|
107
|
+
.map((capability) => capability.slice("network:".length))
|
|
108
|
+
.filter((host) => !listed.has(host))
|
|
109
|
+
.map((host) => `${name} holds ${secrets.join(", ")} and asks for network:${host}, which no secret that it holds lists, so the engine removes that host at each call; add "${host}" to the hosts of ${first}`);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { CardBlock } from "@kana-ai/edgar-contracts/rpc";
|
|
2
|
+
import type { PermanentFailure } from "@kana-ai/edgar-contracts/outcome";
|
|
3
|
+
import { type Result } from "#outcome/result";
|
|
4
|
+
/** A fingerprint of 16 or more hex characters, lowercased and cut to 16; anything else is returned as given for the schema to refuse. */
|
|
5
|
+
export declare function normalFingerprint(raw: string): string;
|
|
6
|
+
/** The TOML line the block writes for `key`, which a description search can find. */
|
|
7
|
+
export declare function blockLine(key: "batch" | "fingerprint" | "waits_for", value: string): string;
|
|
8
|
+
/** Reads the `edgar:v0` block of a description; no block is `null`, a block that fails the schema is `invalid` with the fields in `cause`. */
|
|
9
|
+
export declare function readBlock(description: string): Result<CardBlock | null, PermanentFailure>;
|
|
10
|
+
/** The description with `block` as its `edgar:v0` block, replacing the old one or added at the end. */
|
|
11
|
+
export declare function withBlock(description: string, block: CardBlock): string;
|
|
12
|
+
/** The holder's block after one more sighting at `at`, or `null` when `at` is no newer than the holder's `last_seen`, as a retried sighting is. */
|
|
13
|
+
export declare function sighted(held: CardBlock, at: string): CardBlock | null;
|
|
14
|
+
/** Runs `run` once every earlier call of `key` in this process has settled, so two calls that file one fingerprint cannot both miss the card the other files. */
|
|
15
|
+
export declare function oneAtATime<T>(key: string, run: () => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { cardBlock } from "@kana-ai/edgar-contracts/card";
|
|
2
|
+
import { permanentFailure } from "#outcome/outcome";
|
|
3
|
+
import { attempt, err, ok } from "#outcome/result";
|
|
4
|
+
import { TomlError, parse, stringify } from "smol-toml";
|
|
5
|
+
/** The block as written (`# edgar:v0` as the first TOML line, since a tracker such as Linear drops a fence's info string after the language) or in the old form. */
|
|
6
|
+
const fence = /```toml(?: edgar:v0|\n# edgar:v0)\n([\s\S]*?)```/;
|
|
7
|
+
/** A fingerprint of 16 or more hex characters, lowercased and cut to 16; anything else is returned as given for the schema to refuse. */
|
|
8
|
+
export function normalFingerprint(raw) {
|
|
9
|
+
const hex = raw.trim().toLowerCase();
|
|
10
|
+
return /^[0-9a-f]{16,}$/.test(hex) ? hex.slice(0, 16) : raw;
|
|
11
|
+
}
|
|
12
|
+
/** The TOML line the block writes for `key`, which a description search can find. */
|
|
13
|
+
export function blockLine(key, value) {
|
|
14
|
+
return stringify({ [key]: value }).trim();
|
|
15
|
+
}
|
|
16
|
+
/** Reads the `edgar:v0` block of a description; no block is `null`, a block that fails the schema is `invalid` with the fields in `cause`. */
|
|
17
|
+
export function readBlock(description) {
|
|
18
|
+
const text = fence.exec(description)?.[1];
|
|
19
|
+
if (text === undefined)
|
|
20
|
+
return ok(null);
|
|
21
|
+
const table = attempt(() => parse(text), (caught) => permanentFailure("invalid", "the edgar:v0 block is not TOML", {
|
|
22
|
+
cause: caught instanceof TomlError ? `line ${String(caught.line)}` : "toml",
|
|
23
|
+
}));
|
|
24
|
+
if (!table.ok)
|
|
25
|
+
return table;
|
|
26
|
+
const values = Object.fromEntries(Object.entries(table.value).map(([key, value]) => [
|
|
27
|
+
key,
|
|
28
|
+
value instanceof Date
|
|
29
|
+
? value.toISOString()
|
|
30
|
+
: key === "fingerprint" && typeof value === "string"
|
|
31
|
+
? normalFingerprint(value)
|
|
32
|
+
: value,
|
|
33
|
+
]));
|
|
34
|
+
const block = cardBlock.safeParse(values);
|
|
35
|
+
if (block.success)
|
|
36
|
+
return ok(block.data);
|
|
37
|
+
const fields = block.error.issues.map((issue) => issue.path.join(".") || "block").join(", ");
|
|
38
|
+
return err(permanentFailure("invalid", "the edgar:v0 block does not match its schema", { cause: fields }));
|
|
39
|
+
}
|
|
40
|
+
/** The description with `block` as its `edgar:v0` block, replacing the old one or added at the end. */
|
|
41
|
+
export function withBlock(description, block) {
|
|
42
|
+
const fenced = `\`\`\`toml\n# edgar:v0\n${stringify(block).trim()}\n\`\`\``;
|
|
43
|
+
return fence.test(description)
|
|
44
|
+
? description.replace(fence, () => fenced)
|
|
45
|
+
: `${description.trimEnd()}\n\n${fenced}`.trimStart();
|
|
46
|
+
}
|
|
47
|
+
/** The holder's block after one more sighting at `at`, or `null` when `at` is no newer than the holder's `last_seen`, as a retried sighting is. */
|
|
48
|
+
export function sighted(held, at) {
|
|
49
|
+
if (held.last_seen !== undefined && Date.parse(at) <= Date.parse(held.last_seen))
|
|
50
|
+
return null;
|
|
51
|
+
return { ...held, occurrences: (held.occurrences ?? 1) + 1, last_seen: at };
|
|
52
|
+
}
|
|
53
|
+
const pending = new Map();
|
|
54
|
+
/** Runs `run` once every earlier call of `key` in this process has settled, so two calls that file one fingerprint cannot both miss the card the other files. */
|
|
55
|
+
export async function oneAtATime(key, run) {
|
|
56
|
+
const mine = (pending.get(key) ?? Promise.resolve()).then(run);
|
|
57
|
+
const settled = mine.then(() => undefined, () => undefined);
|
|
58
|
+
pending.set(key, settled);
|
|
59
|
+
try {
|
|
60
|
+
return await mine;
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
if (pending.get(key) === settled)
|
|
64
|
+
pending.delete(key);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { CardSpec, CompleteResult, Created, Encoding, MoveResult, Origin, RunsReadResult, SandboxExecResult } from "@kana-ai/edgar-contracts/rpc";
|
|
2
|
+
import type { TrackerPort } from "#define/tracker";
|
|
3
|
+
import type { Outcome } from "#outcome/outcome";
|
|
4
|
+
import type { Result } from "#outcome/result";
|
|
5
|
+
/** Why a call to an engine port did not return a value. */
|
|
6
|
+
export interface PortError {
|
|
7
|
+
readonly code: "capability_refused" | "sandbox_refused" | "runtime_payload_too_large" | "unknown_id" | "call_ended" | "engine_error";
|
|
8
|
+
readonly message: string;
|
|
9
|
+
}
|
|
10
|
+
/** The answer of an engine port: refusals are values, never throws. */
|
|
11
|
+
export type PortResult<T> = Result<T, PortError>;
|
|
12
|
+
/** The secrets of one call; their bytes are zeroed when `execute` returns. */
|
|
13
|
+
export interface Secrets<S extends string> {
|
|
14
|
+
get(name: S): string;
|
|
15
|
+
bytes(name: S): Uint8Array;
|
|
16
|
+
}
|
|
17
|
+
/** What a tool receives besides its input. */
|
|
18
|
+
export interface Ctx<S extends string = never> {
|
|
19
|
+
/** The id of this operation: the same on every retry of it, and unique across stores. A tool with an effect keys its write on it. */
|
|
20
|
+
readonly operation_id: string;
|
|
21
|
+
readonly run_id: string;
|
|
22
|
+
readonly stage: string;
|
|
23
|
+
readonly attempt: number;
|
|
24
|
+
readonly signal: AbortSignal;
|
|
25
|
+
/** The project's table for this extension, validated by the engine against `config_schema`; `undefined` when it has none. */
|
|
26
|
+
readonly config: unknown;
|
|
27
|
+
readonly secrets: Secrets<S>;
|
|
28
|
+
readonly sandbox: {
|
|
29
|
+
read(path: string, encoding?: Encoding): Promise<PortResult<string>>;
|
|
30
|
+
write(path: string, content: string, encoding?: Encoding): Promise<PortResult<number>>;
|
|
31
|
+
exec(command: string, args: readonly string[], cwd?: string): Promise<PortResult<SandboxExecResult>>;
|
|
32
|
+
};
|
|
33
|
+
readonly tracker: TrackerPort;
|
|
34
|
+
/** Only a service may open a card; a tool call gets `capability_refused`. */
|
|
35
|
+
readonly cards: {
|
|
36
|
+
open(card: CardSpec): Promise<PortResult<Outcome<Created>>>;
|
|
37
|
+
/** Puts what the person `by` wrote in the service's own place on the card of `to.run`, or on `to.card` when the place names a card and has no run; EDGAR then reads it as that person's comment. With `origin`, the run that the comment starts names that place as `relayed`. Only a service may. */
|
|
38
|
+
reply(to: {
|
|
39
|
+
readonly run: string;
|
|
40
|
+
} | {
|
|
41
|
+
readonly card: string;
|
|
42
|
+
}, text: string, by: string, origin?: Origin): Promise<PortResult<MoveResult>>;
|
|
43
|
+
};
|
|
44
|
+
/** Moves a service makes on a person's word; `by` must be in `[roles] operator`, or the move answers `applied: false`. A tool call gets `capability_refused`. */
|
|
45
|
+
readonly moves: {
|
|
46
|
+
complete(key: string, outcome: Outcome, by: string): Promise<PortResult<MoveResult>>;
|
|
47
|
+
approve(operation: string, by: string): Promise<PortResult<MoveResult>>;
|
|
48
|
+
deny(operation: string, by: string, reason: string): Promise<PortResult<MoveResult>>;
|
|
49
|
+
};
|
|
50
|
+
readonly runs: {
|
|
51
|
+
read(runId: string): Promise<PortResult<RunsReadResult>>;
|
|
52
|
+
/** Cancels every unfinished run whose card came from `origin`; only a service may. */
|
|
53
|
+
cancel(origin: Origin, by: string, reason: string): Promise<PortResult<MoveResult>>;
|
|
54
|
+
/** Starts the workflow `chat` on what the person `by`, an id with no space, wrote at `origin` with no card: it answers a question there and opens `card` for work. Only a service may. */
|
|
55
|
+
chat(text: string, by: string, origin: Origin, card: CardSpec): Promise<PortResult<MoveResult>>;
|
|
56
|
+
};
|
|
57
|
+
complete(key: string, outcome: Outcome): Promise<PortResult<CompleteResult>>;
|
|
58
|
+
progress(snapshot: Readonly<Record<string, unknown>>): void;
|
|
59
|
+
log(line: string): void;
|
|
60
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Executables, Webhook } from "@kana-ai/edgar-contracts/manifest";
|
|
2
|
+
import type { EventHook, Hook } from "#define/hook";
|
|
3
|
+
import type { Service } from "#define/service";
|
|
4
|
+
import type { Capability, Schema, Tool } from "#define/tool";
|
|
5
|
+
import type { Tracker } from "#define/tracker";
|
|
6
|
+
declare const extensionBrand: unique symbol;
|
|
7
|
+
declare const environmentBrand: unique symbol;
|
|
8
|
+
/** What `defineEnvironment` takes: its four steps, each a tool. */
|
|
9
|
+
export interface EnvironmentSpec {
|
|
10
|
+
readonly prepare: Tool;
|
|
11
|
+
readonly start: Tool;
|
|
12
|
+
readonly health: Tool;
|
|
13
|
+
readonly stop: Tool;
|
|
14
|
+
}
|
|
15
|
+
/** An environment provider value; only `defineEnvironment` makes one. */
|
|
16
|
+
export interface Environment extends EnvironmentSpec {
|
|
17
|
+
readonly [environmentBrand]: true;
|
|
18
|
+
}
|
|
19
|
+
/** Defines an environment provider, named by its key in `defineExtension({ environments })`. */
|
|
20
|
+
export declare function defineEnvironment(spec: EnvironmentSpec): Environment;
|
|
21
|
+
/** What `defineExtension` takes; the version comes from the package's `package.json`. */
|
|
22
|
+
export interface ExtensionSpec {
|
|
23
|
+
readonly name: string;
|
|
24
|
+
readonly config?: Schema;
|
|
25
|
+
/** Each secret's hosts, and `help`, which `edgar check` prints when the project has no source for it. */
|
|
26
|
+
readonly secrets?: Readonly<Record<string, {
|
|
27
|
+
readonly hosts: readonly string[];
|
|
28
|
+
readonly help?: string;
|
|
29
|
+
}>>;
|
|
30
|
+
readonly capabilities?: readonly Capability[];
|
|
31
|
+
readonly tools?: Readonly<Record<string, Tool>>;
|
|
32
|
+
readonly webhooks?: Readonly<Record<string, Omit<Webhook, "route">>>;
|
|
33
|
+
readonly workflows?: readonly string[];
|
|
34
|
+
readonly roles?: readonly string[];
|
|
35
|
+
readonly skills?: readonly string[];
|
|
36
|
+
readonly tracker?: Tracker;
|
|
37
|
+
readonly environments?: Readonly<Record<string, Environment>>;
|
|
38
|
+
readonly hooks?: Readonly<Record<string, Hook | EventHook>>;
|
|
39
|
+
readonly service?: Service;
|
|
40
|
+
/**
|
|
41
|
+
* The programs that the extension runs. `requires` names each program that the machine must have on `PATH`, with the
|
|
42
|
+
* sentence that `edgar check` prints when it is missing. `provides` names each executable file that the package ships,
|
|
43
|
+
* by its command name and its path inside the package. No file is a command because of the folder that holds it.
|
|
44
|
+
*/
|
|
45
|
+
readonly executables?: {
|
|
46
|
+
readonly requires?: readonly Readonly<Executables["requires"][number]>[];
|
|
47
|
+
readonly provides?: readonly Readonly<Executables["provides"][number]>[];
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** An extension value; the module's default export. */
|
|
51
|
+
export interface Extension extends ExtensionSpec {
|
|
52
|
+
readonly [extensionBrand]: true;
|
|
53
|
+
}
|
|
54
|
+
/** Defines an extension; export the result as the module's default export. */
|
|
55
|
+
export declare function defineExtension(spec: ExtensionSpec): Extension;
|
|
56
|
+
/** True for a value `defineExtension` made; raw objects are refused. */
|
|
57
|
+
export declare function isExtension(value: unknown): value is Extension;
|
|
58
|
+
export {};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
const extensionBrand = Symbol.for("edgar.sdk.extension");
|
|
2
|
+
const environmentBrand = Symbol.for("edgar.sdk.environment");
|
|
3
|
+
/** Defines an environment provider, named by its key in `defineExtension({ environments })`. */
|
|
4
|
+
export function defineEnvironment(spec) {
|
|
5
|
+
return { ...spec, [environmentBrand]: true };
|
|
6
|
+
}
|
|
7
|
+
/** Defines an extension; export the result as the module's default export. */
|
|
8
|
+
export function defineExtension(spec) {
|
|
9
|
+
return { ...spec, [extensionBrand]: true };
|
|
10
|
+
}
|
|
11
|
+
/** True for a value `defineExtension` made; raw objects are refused. */
|
|
12
|
+
export function isExtension(value) {
|
|
13
|
+
return typeof value === "object" && value !== null && Object.hasOwn(value, extensionBrand);
|
|
14
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { HookCall, HookDecision, Origin } from "@kana-ai/edgar-contracts/rpc";
|
|
2
|
+
import type { Ctx } from "#define/context";
|
|
3
|
+
import type { Capability } from "#define/tool";
|
|
4
|
+
import type { Outcome } from "#outcome/outcome";
|
|
5
|
+
declare const hookBrand: unique symbol;
|
|
6
|
+
/** The hook lets the call go on. */
|
|
7
|
+
export declare function pass(): HookDecision;
|
|
8
|
+
/** The hook refuses the call; the engine returns `permanent_failure(denied_by_hook)` with the reason. */
|
|
9
|
+
export declare function deny(code: string, reason: string): HookDecision;
|
|
10
|
+
/** What `defineHook` takes. */
|
|
11
|
+
export interface HookSpec<S extends string> {
|
|
12
|
+
readonly on: "before_tool" | "after_tool";
|
|
13
|
+
readonly secrets?: readonly S[];
|
|
14
|
+
readonly capabilities?: readonly Capability[];
|
|
15
|
+
check(call: HookCall, ctx: Ctx<S>): Promise<HookDecision>;
|
|
16
|
+
}
|
|
17
|
+
/** A hook value; only `defineHook` makes one. */
|
|
18
|
+
export interface Hook {
|
|
19
|
+
readonly [hookBrand]: true;
|
|
20
|
+
readonly on: "before_tool" | "after_tool";
|
|
21
|
+
readonly secrets: readonly string[];
|
|
22
|
+
readonly capabilities: readonly Capability[];
|
|
23
|
+
check(call: HookCall, ctx: Ctx<string>): Promise<HookDecision>;
|
|
24
|
+
}
|
|
25
|
+
/** Defines a guardrail hook, named by its key in `defineExtension({ hooks })`. */
|
|
26
|
+
export declare function defineHook<const S extends string = never>(spec: HookSpec<S>): Hook;
|
|
27
|
+
declare const eventHookBrand: unique symbol;
|
|
28
|
+
/** The event kinds an event hook may take: those written on a run. */
|
|
29
|
+
export type RunEventKind = "run_created" | "run_state" | "run_outcome" | "attempt_created" | "attempt_started" | "attempt_state" | "attempt_outcome" | "stage_started" | "call_started" | "call_result" | "model_message" | "tool_output" | "check_line" | "approval_requested" | "approval_answered" | "kept_work" | "forced";
|
|
30
|
+
/** One run event as an event hook gets it: the `events` row, with the origin of the run's card (`null` for a card with none) and the stage of its attempt (`null` on a run event). */
|
|
31
|
+
export interface RunEvent {
|
|
32
|
+
readonly id: number;
|
|
33
|
+
readonly run: string;
|
|
34
|
+
readonly attempt: string | null;
|
|
35
|
+
readonly kind: RunEventKind;
|
|
36
|
+
readonly payload: Readonly<Record<string, unknown>>;
|
|
37
|
+
readonly at: number;
|
|
38
|
+
readonly origin: Origin | null;
|
|
39
|
+
readonly stage: string | null;
|
|
40
|
+
}
|
|
41
|
+
/** What `defineEventHook` takes. `deliver` answers `done` once it took the event; a failure has it handed again, up to five times, and a `permanent_failure` drops it with an alert. */
|
|
42
|
+
export interface EventHookSpec<S extends string> {
|
|
43
|
+
readonly events: readonly [RunEventKind, ...RunEventKind[]];
|
|
44
|
+
readonly secrets?: readonly S[];
|
|
45
|
+
readonly capabilities?: readonly Capability[];
|
|
46
|
+
deliver(event: RunEvent, ctx: Ctx<S>): Promise<Outcome>;
|
|
47
|
+
}
|
|
48
|
+
/** An event hook value; only `defineEventHook` makes one. */
|
|
49
|
+
export interface EventHook {
|
|
50
|
+
readonly [eventHookBrand]: true;
|
|
51
|
+
readonly on: "event";
|
|
52
|
+
readonly events: readonly RunEventKind[];
|
|
53
|
+
readonly secrets: readonly string[];
|
|
54
|
+
readonly capabilities: readonly Capability[];
|
|
55
|
+
deliver(event: RunEvent, ctx: Ctx<string>): Promise<Outcome>;
|
|
56
|
+
}
|
|
57
|
+
/** Defines a hook the engine feeds with the events of the runs whose card came from this extension, at least once and in order, named by its key in `defineExtension({ hooks })`. */
|
|
58
|
+
export declare function defineEventHook<const S extends string = never>(spec: EventHookSpec<S>): EventHook;
|
|
59
|
+
/** The value the engine handed, read as a run event; `undefined` for any other shape. */
|
|
60
|
+
export declare function runEvent(value: unknown): RunEvent | undefined;
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const hookBrand = Symbol.for("edgar.sdk.hook");
|
|
2
|
+
/** The hook lets the call go on. */
|
|
3
|
+
export function pass() {
|
|
4
|
+
return { decision: "pass" };
|
|
5
|
+
}
|
|
6
|
+
/** The hook refuses the call; the engine returns `permanent_failure(denied_by_hook)` with the reason. */
|
|
7
|
+
export function deny(code, reason) {
|
|
8
|
+
return { decision: "deny", code, reason };
|
|
9
|
+
}
|
|
10
|
+
/** Defines a guardrail hook, named by its key in `defineExtension({ hooks })`. */
|
|
11
|
+
export function defineHook(spec) {
|
|
12
|
+
return {
|
|
13
|
+
[hookBrand]: true,
|
|
14
|
+
on: spec.on,
|
|
15
|
+
secrets: spec.secrets ?? [],
|
|
16
|
+
capabilities: spec.capabilities ?? [],
|
|
17
|
+
check: async (call, ctx) => await spec.check(call, ctx),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
const eventHookBrand = Symbol.for("edgar.sdk.event_hook");
|
|
21
|
+
/** Defines a hook the engine feeds with the events of the runs whose card came from this extension, at least once and in order, named by its key in `defineExtension({ hooks })`. */
|
|
22
|
+
export function defineEventHook(spec) {
|
|
23
|
+
return {
|
|
24
|
+
[eventHookBrand]: true,
|
|
25
|
+
on: "event",
|
|
26
|
+
events: [...spec.events],
|
|
27
|
+
secrets: spec.secrets ?? [],
|
|
28
|
+
capabilities: spec.capabilities ?? [],
|
|
29
|
+
deliver: async (event, ctx) => await spec.deliver(event, ctx),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const kinds = new Set([
|
|
33
|
+
"run_created",
|
|
34
|
+
"run_state",
|
|
35
|
+
"run_outcome",
|
|
36
|
+
"attempt_created",
|
|
37
|
+
"attempt_started",
|
|
38
|
+
"attempt_state",
|
|
39
|
+
"attempt_outcome",
|
|
40
|
+
"stage_started",
|
|
41
|
+
"call_started",
|
|
42
|
+
"call_result",
|
|
43
|
+
"model_message",
|
|
44
|
+
"tool_output",
|
|
45
|
+
"check_line",
|
|
46
|
+
"approval_requested",
|
|
47
|
+
"approval_answered",
|
|
48
|
+
"kept_work",
|
|
49
|
+
"forced",
|
|
50
|
+
]);
|
|
51
|
+
const isKind = (value) => typeof value === "string" && kinds.has(value);
|
|
52
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
53
|
+
/** The value the engine handed, read as a run event; `undefined` for any other shape. */
|
|
54
|
+
export function runEvent(value) {
|
|
55
|
+
if (!isRecord(value))
|
|
56
|
+
return undefined;
|
|
57
|
+
const { id, run, attempt, kind, payload, at, origin, stage } = value;
|
|
58
|
+
if (typeof id !== "number" || typeof run !== "string" || typeof at !== "number")
|
|
59
|
+
return undefined;
|
|
60
|
+
if (!(attempt === null || typeof attempt === "string") || !isKind(kind) || !isRecord(payload))
|
|
61
|
+
return undefined;
|
|
62
|
+
if (!(stage === null || typeof stage === "string"))
|
|
63
|
+
return undefined;
|
|
64
|
+
if (origin === null)
|
|
65
|
+
return { id, run, attempt, kind, payload, at, origin: null, stage };
|
|
66
|
+
if (!isRecord(origin))
|
|
67
|
+
return undefined;
|
|
68
|
+
const { extension, channel, thread } = origin;
|
|
69
|
+
if (typeof extension !== "string" || typeof channel !== "string" || typeof thread !== "string")
|
|
70
|
+
return undefined;
|
|
71
|
+
return { id, run, attempt, kind, payload, at, origin: { extension, channel, thread }, stage };
|
|
72
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Ctx } from "#define/context";
|
|
2
|
+
import type { Capability } from "#define/tool";
|
|
3
|
+
import type { Outcome } from "#outcome/outcome";
|
|
4
|
+
declare const serviceBrand: unique symbol;
|
|
5
|
+
/** One entry of the project's `[services]`. */
|
|
6
|
+
export interface ProjectService {
|
|
7
|
+
readonly name: string;
|
|
8
|
+
readonly repo: string;
|
|
9
|
+
readonly default_branch: string;
|
|
10
|
+
}
|
|
11
|
+
/** What the engine hands a service when it starts it. */
|
|
12
|
+
export interface ServiceInput {
|
|
13
|
+
readonly services: readonly ProjectService[];
|
|
14
|
+
}
|
|
15
|
+
/** What `defineService` takes: the grant it runs under, and `run`, which answers once `ctx.signal` aborts; a `permanent_failure`, such as a refused token, opens the service's breaker at once. With `tracker:write`, `ctx.tracker.comment` posts on a card. */
|
|
16
|
+
export interface ServiceSpec<S extends string> {
|
|
17
|
+
readonly secrets?: readonly S[];
|
|
18
|
+
readonly capabilities?: readonly Capability[];
|
|
19
|
+
run(ctx: Ctx<S>, input: ServiceInput): Promise<Outcome>;
|
|
20
|
+
}
|
|
21
|
+
/** A service value; only `defineService` makes one. `input` is the project's services, none when a test leaves it out. */
|
|
22
|
+
export interface Service {
|
|
23
|
+
readonly [serviceBrand]: true;
|
|
24
|
+
readonly secrets: readonly string[];
|
|
25
|
+
readonly capabilities: readonly Capability[];
|
|
26
|
+
run(ctx: Ctx<string>, input?: ServiceInput): Promise<Outcome>;
|
|
27
|
+
}
|
|
28
|
+
/** Defines the extension's long-lived service, such as a listener on a chat platform's socket; `edgar start` runs it once the manifest is approved and restarts it when it stops by itself. */
|
|
29
|
+
export declare function defineService<const S extends string = never>(spec: ServiceSpec<S>): Service;
|
|
30
|
+
/** The value the engine handed a service, read as its input; `undefined` for any other shape. */
|
|
31
|
+
export declare function serviceInput(value: unknown): ServiceInput | undefined;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
const serviceBrand = Symbol.for("edgar.sdk.service");
|
|
2
|
+
const noServices = { services: [] };
|
|
3
|
+
/** Defines the extension's long-lived service, such as a listener on a chat platform's socket; `edgar start` runs it once the manifest is approved and restarts it when it stops by itself. */
|
|
4
|
+
export function defineService(spec) {
|
|
5
|
+
return {
|
|
6
|
+
[serviceBrand]: true,
|
|
7
|
+
secrets: spec.secrets ?? [],
|
|
8
|
+
capabilities: spec.capabilities ?? [],
|
|
9
|
+
run: async (ctx, input = noServices) => await spec.run(ctx, input),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
13
|
+
function projectService(value) {
|
|
14
|
+
if (!isRecord(value))
|
|
15
|
+
return undefined;
|
|
16
|
+
const { name, repo, default_branch } = value;
|
|
17
|
+
if (typeof name !== "string" || typeof repo !== "string" || typeof default_branch !== "string")
|
|
18
|
+
return undefined;
|
|
19
|
+
return { name, repo, default_branch };
|
|
20
|
+
}
|
|
21
|
+
/** The value the engine handed a service, read as its input; `undefined` for any other shape. */
|
|
22
|
+
export function serviceInput(value) {
|
|
23
|
+
if (!isRecord(value) || !Array.isArray(value["services"]))
|
|
24
|
+
return undefined;
|
|
25
|
+
const services = [];
|
|
26
|
+
for (const entry of value["services"]) {
|
|
27
|
+
const service = projectService(entry);
|
|
28
|
+
if (service === undefined)
|
|
29
|
+
return undefined;
|
|
30
|
+
services.push(service);
|
|
31
|
+
}
|
|
32
|
+
return { services };
|
|
33
|
+
}
|