@aidenhq/sdk 0.1.1 → 0.2.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/README.md CHANGED
@@ -1,10 +1,15 @@
1
1
  # @aidenhq/sdk
2
2
 
3
- Contract types, engine IO, the executor side of write kinds and the contract kit for AidenHQ modules. MIT.
3
+ The code AidenHQ modules share, one copy on npm. MIT. Entry points: `types`, `engine-io`, `kit`, `progress` (engines),
4
+ `caller` and `fence` (every module server: the kernel's caller assertion and the untrusted-text fence), `executor` (write
5
+ kinds), `reviewer` (reviewer@1), `source-store` (source writers; `pg` is a peer dependency) and `vendor/proxy`,
6
+ `vendor/oauth` (vendor connections; the MCP SDK, zod and pino are peer dependencies).
7
+
8
+ A module depends on an exact version (`"@aidenhq/sdk": "X.Y.Z"`). Our own scope is exempt from the 7-day rule, so a module
9
+ may pin a version the day it is published.
4
10
 
5
11
  ## Releasing
6
12
 
7
13
  Push a tag `sdk-vX.Y.Z` on a commit of `main`. `.github/workflows/sdk-publish.yml` takes the version from the tag and publishes
8
- with npm trusted publishing (provenance, no token). Pull requests that touch this folder dry-run the same publish.
9
-
10
- First version by hand: `node scripts/sdk-pack.mjs && cd kernel/sdk && npm publish --access public`.
14
+ with npm trusted publishing (provenance, no token). Pull requests that touch this folder dry-run the same publish. The pack
15
+ step (`scripts/sdk-pack.mjs`) compiles with this folder's own TypeScript: `npm ci` here first.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -2,7 +2,6 @@
2
2
  // The contract kit: `aidenhq-module-test <module dir>` runs the module's engines through engine@1.
3
3
  import { resolve } from "node:path";
4
4
  import { engineKit } from "../src/kit.js";
5
-
6
5
  const dir = resolve(process.argv[2] ?? ".");
7
6
  await engineKit(dir);
8
7
  console.log(`${dir}: engine@1 kit passed`);
@@ -0,0 +1,27 @@
1
+ import { type JsonWebKey } from "node:crypto";
2
+ import type { IncomingMessage } from "node:http";
3
+ /** The calling agent, as the kernel resolved it. `agent` is its control-plane id, `key` its agent key, `call` the call id. */
4
+ export interface Caller {
5
+ agent: string;
6
+ key: string;
7
+ name: string;
8
+ roles: string[];
9
+ task?: string;
10
+ run?: string;
11
+ tool: string;
12
+ call: string;
13
+ kind: string;
14
+ }
15
+ export type JWK = JsonWebKey & {
16
+ kid?: string;
17
+ };
18
+ export type JWKS = {
19
+ keys: JWK[];
20
+ };
21
+ export declare const CALLER_HEADER = "x-aidenhq-caller";
22
+ /** The kernel's keys from `url` (its /v1/jwks), fetched once and again at most once a minute when a key id is unknown. */
23
+ export declare function kernelJwks(url?: string): () => Promise<JWKS>;
24
+ /** The caller of this request, for module `aud`. Throws on a missing, forged, expired or misaddressed assertion. */
25
+ export declare function verifyCaller(req: IncomingMessage | {
26
+ headers: Record<string, unknown>;
27
+ }, jwks: JWKS | (() => Promise<JWKS>), aud: string, now?: number): Promise<Caller>;
@@ -1,62 +1,61 @@
1
1
  // Who a proxied tool call is for: the kernel's signed caller assertion (X-AidenHQ-Caller, an EdDSA JWT, 60 s), checked
2
2
  // against the kernel's keys (GET /v1/jwks). A module trusts nothing else about the caller: not a header, not an argument.
3
3
  //
4
- // Canonical copy: kernel/sdk/src/caller.ts. Each consumer holds a byte-identical copy at src/aidenhq-sdk/caller.ts:
5
- // edit this one, then run `node scripts/sync-shared.mjs` (scripts/test/shared.test.mjs fails on drift).
6
- import { createPublicKey, verify, } from "node:crypto";
7
-
8
-
9
- /** The calling agent, as the kernel resolved it. `agent` is its control-plane id, `key` its agent key, `call` the call id. */
10
-
11
-
12
-
13
-
4
+ // Modules import it as @aidenhq/sdk/caller.
5
+ import { createPublicKey, verify } from "node:crypto";
14
6
  export const CALLER_HEADER = "x-aidenhq-caller";
15
- const b64 = (s ) => Buffer.from(s, "base64url");
16
-
7
+ const b64 = (s) => Buffer.from(s, "base64url");
17
8
  /** The kernel's keys from `url` (its /v1/jwks), fetched once and again at most once a minute when a key id is unknown. */
18
- export function kernelJwks(url = `${process.env.AIDENHQ_KERNEL_URL ?? "http://10.231.0.1:3130"}/v1/jwks`) {
19
- let cached , at = 0;
20
- return async () => {
21
- if (cached && Date.now() - at < 60_000) return cached;
22
- const res = await fetch(url, { signal: AbortSignal.timeout(10_000) });
23
- if (!res.ok) throw new Error(`the kernel's keys are unavailable (${res.status})`);
24
- cached = (await res.json()) ;
25
- at = Date.now();
26
- return cached;
27
- };
9
+ export function kernelJwks(url = `${process.env.AIDENHQ_KERNEL_URL ?? "http://10.231.0.1:3130"}/v1/jwks`) {
10
+ let cached, at = 0;
11
+ return async () => {
12
+ if (cached && Date.now() - at < 60_000)
13
+ return cached;
14
+ const res = await fetch(url, { signal: AbortSignal.timeout(10_000) });
15
+ if (!res.ok)
16
+ throw new Error(`the kernel's keys are unavailable (${res.status})`);
17
+ cached = (await res.json());
18
+ at = Date.now();
19
+ return cached;
20
+ };
28
21
  }
29
-
30
22
  /** The caller of this request, for module `aud`. Throws on a missing, forged, expired or misaddressed assertion. */
31
- export async function verifyCaller(req , jwks , aud , now = Date.now()) {
32
- const jwt = String(req.headers[CALLER_HEADER] ?? "");
33
- const [h, p, s] = jwt.split(".");
34
- if (!h || !p || !s) throw new Error("no caller assertion");
35
- let header , claims ;
36
- try {
37
- header = JSON.parse(b64(h).toString("utf8"));
38
- claims = JSON.parse(b64(p).toString("utf8"));
39
- } catch {
40
- throw new Error("the caller assertion is malformed");
41
- }
42
- if (header.alg !== "EdDSA") throw new Error("the caller assertion isn't EdDSA");
43
- const keys = typeof jwks === "function" ? await jwks() : jwks;
44
- const jwk = keys.keys.find((k) => !header.kid || k.kid === header.kid);
45
- if (!jwk) throw new Error("the caller assertion's key is unknown");
46
- const { kid: _kid, ...material } = jwk;
47
- if (!verify(null, Buffer.from(`${h}.${p}`), createPublicKey({ key: material, format: "jwk" }), b64(s))) throw new Error("the caller assertion's signature is wrong");
48
- if (claims.aud !== aud) throw new Error(`the caller assertion is for ${String(claims.aud)}, not ${aud}`);
49
- if (typeof claims.exp !== "number" || claims.exp * 1000 <= now) throw new Error("the caller assertion has expired");
50
- const str = (v ) => (typeof v === "string" && v ? v : undefined);
51
- return {
52
- agent: str(claims.agent) ?? "",
53
- key: str(claims.key) ?? "",
54
- name: str(claims.name) ?? str(claims.key) ?? "",
55
- roles: Array.isArray(claims.roles) ? claims.roles.map(String) : [],
56
- ...(str(claims.task) ? { task: str(claims.task) } : {}),
57
- ...(str(claims.run) ? { run: str(claims.run) } : {}),
58
- tool: str(claims.tool) ?? "",
59
- call: str(claims.jti) ?? "",
60
- kind: str(claims.kind) ?? "run",
61
- };
23
+ export async function verifyCaller(req, jwks, aud, now = Date.now()) {
24
+ const jwt = String(req.headers[CALLER_HEADER] ?? "");
25
+ const [h, p, s] = jwt.split(".");
26
+ if (!h || !p || !s)
27
+ throw new Error("no caller assertion");
28
+ let header, claims;
29
+ try {
30
+ header = JSON.parse(b64(h).toString("utf8"));
31
+ claims = JSON.parse(b64(p).toString("utf8"));
32
+ }
33
+ catch {
34
+ throw new Error("the caller assertion is malformed");
35
+ }
36
+ if (header.alg !== "EdDSA")
37
+ throw new Error("the caller assertion isn't EdDSA");
38
+ const keys = typeof jwks === "function" ? await jwks() : jwks;
39
+ const jwk = keys.keys.find((k) => !header.kid || k.kid === header.kid);
40
+ if (!jwk)
41
+ throw new Error("the caller assertion's key is unknown");
42
+ const { kid: _kid, ...material } = jwk;
43
+ if (!verify(null, Buffer.from(`${h}.${p}`), createPublicKey({ key: material, format: "jwk" }), b64(s)))
44
+ throw new Error("the caller assertion's signature is wrong");
45
+ if (claims.aud !== aud)
46
+ throw new Error(`the caller assertion is for ${String(claims.aud)}, not ${aud}`);
47
+ if (typeof claims.exp !== "number" || claims.exp * 1000 <= now)
48
+ throw new Error("the caller assertion has expired");
49
+ const str = (v) => (typeof v === "string" && v ? v : undefined);
50
+ return {
51
+ agent: str(claims.agent) ?? "",
52
+ key: str(claims.key) ?? "",
53
+ name: str(claims.name) ?? str(claims.key) ?? "",
54
+ roles: Array.isArray(claims.roles) ? claims.roles.map(String) : [],
55
+ ...(str(claims.task) ? { task: str(claims.task) } : {}),
56
+ ...(str(claims.run) ? { run: str(claims.run) } : {}),
57
+ tool: str(claims.tool) ?? "",
58
+ call: str(claims.jti) ?? "",
59
+ kind: str(claims.kind) ?? "run",
60
+ };
62
61
  }
@@ -0,0 +1,35 @@
1
+ import type { EngineEvent, InboxLine, JobSpec } from "./types.js";
2
+ export declare const LINE_MAX: number;
3
+ /** A regular file's bytes from `offset`, at most `max`: never through a link. Empty when it doesn't exist yet. */
4
+ export declare function readFrom(path: string, offset?: number, max?: number): Buffer;
5
+ /** Append one line to a regular file (made 0600 if missing), never through a link. */
6
+ export declare function appendLine(path: string, value: unknown): void;
7
+ /** Whole lines from a byte buffer: the parsed ones and how many bytes they took (a partial last line waits). */
8
+ export declare function lines(buf: Buffer): {
9
+ values: unknown[];
10
+ used: number;
11
+ };
12
+ export declare function engineIO(jobDir: string, { pollMs }?: {
13
+ pollMs?: number | undefined;
14
+ }): {
15
+ spec: JobSpec;
16
+ emit: (ev: EngineEvent) => void;
17
+ /** The runner's comments, as they arrive; ends when the caller stops iterating. */
18
+ comments(): AsyncGenerator<InboxLine>;
19
+ };
20
+ /**
21
+ * Run the engine's own program: its output goes on to ours (the job log) as it is, each JSON line to `onJson`. `input`: text
22
+ * for its stdin (none: no stdin), or a function given a writer that keeps stdin open (live input) until it calls end(). Resolves with the exit
23
+ * code, or 127 with `error` when the program couldn't start.
24
+ */
25
+ export declare function runProgram(argv: string[], { env, input, onJson }: {
26
+ env: NodeJS.ProcessEnv;
27
+ input?: string | ((w: {
28
+ write(s: string): boolean;
29
+ end(): void;
30
+ }) => void);
31
+ onJson: (e: any) => void;
32
+ }): Promise<{
33
+ code: number;
34
+ error?: string;
35
+ }>;
@@ -1,114 +1,124 @@
1
1
  // An engine's side of engine@1: read job.json, append events, follow inbox.jsonl. Every file is opened without following
2
2
  // a link and without blocking (the job dir is the job's to write: a FIFO there must not hang the reader), and each event line
3
3
  // is capped.
4
- import { spawn, } from "node:child_process";
4
+ import { spawn } from "node:child_process";
5
5
  import { closeSync, constants, fstatSync, openSync, readSync, writeSync } from "node:fs";
6
6
  import { join } from "node:path";
7
-
8
-
9
7
  export const LINE_MAX = 256 * 1024;
10
8
  const NOFOLLOW = constants.O_NOFOLLOW | constants.O_NONBLOCK;
11
-
12
9
  /** A regular file's bytes from `offset`, at most `max`: never through a link. Empty when it doesn't exist yet. */
13
- export function readFrom(path , offset = 0, max = 4 << 20) {
14
- let fd ;
15
- try {
16
- fd = openSync(path, constants.O_RDONLY | NOFOLLOW);
17
- } catch (e ) {
18
- if (e.code === "ENOENT") return Buffer.alloc(0);
19
- throw e;
20
- }
21
- try {
22
- const st = fstatSync(fd);
23
- if (!st.isFile()) throw new Error(`${path} is not a regular file`);
24
- const n = Math.max(0, Math.min(st.size - offset, max));
25
- const buf = Buffer.alloc(n);
26
- if (n) readSync(fd, buf, 0, n, offset);
27
- return buf;
28
- } finally {
29
- closeSync(fd);
30
- }
10
+ export function readFrom(path, offset = 0, max = 4 << 20) {
11
+ let fd;
12
+ try {
13
+ fd = openSync(path, constants.O_RDONLY | NOFOLLOW);
14
+ }
15
+ catch (e) {
16
+ if (e.code === "ENOENT")
17
+ return Buffer.alloc(0);
18
+ throw e;
19
+ }
20
+ try {
21
+ const st = fstatSync(fd);
22
+ if (!st.isFile())
23
+ throw new Error(`${path} is not a regular file`);
24
+ const n = Math.max(0, Math.min(st.size - offset, max));
25
+ const buf = Buffer.alloc(n);
26
+ if (n)
27
+ readSync(fd, buf, 0, n, offset);
28
+ return buf;
29
+ }
30
+ finally {
31
+ closeSync(fd);
32
+ }
31
33
  }
32
-
33
34
  /** Append one line to a regular file (made 0600 if missing), never through a link. */
34
- export function appendLine(path , value ) {
35
- let line = JSON.stringify(value);
36
- if (Buffer.byteLength(line) >= LINE_MAX) {
37
- const v = value ;
38
- line = JSON.stringify({ ...v, text: String(v.text ?? "").slice(0, LINE_MAX / 8), plan: undefined, steps: undefined });
39
- }
40
- const fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | NOFOLLOW, 0o600);
41
- try {
42
- if (!fstatSync(fd).isFile()) throw new Error(`${path} is not a regular file`);
43
- writeSync(fd, `${line}\n`);
44
- } finally {
45
- closeSync(fd);
46
- }
35
+ export function appendLine(path, value) {
36
+ let line = JSON.stringify(value);
37
+ if (Buffer.byteLength(line) >= LINE_MAX) {
38
+ const v = value;
39
+ line = JSON.stringify({ ...v, text: String(v.text ?? "").slice(0, LINE_MAX / 8), plan: undefined, steps: undefined });
40
+ }
41
+ const fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | NOFOLLOW, 0o600);
42
+ try {
43
+ if (!fstatSync(fd).isFile())
44
+ throw new Error(`${path} is not a regular file`);
45
+ writeSync(fd, `${line}\n`);
46
+ }
47
+ finally {
48
+ closeSync(fd);
49
+ }
47
50
  }
48
-
49
51
  /** Whole lines from a byte buffer: the parsed ones and how many bytes they took (a partial last line waits). */
50
- export function lines(buf ) {
51
- const values = [];
52
- let start = 0;
53
- for (let i = buf.indexOf(10); i >= 0; i = buf.indexOf(10, start)) {
54
- const text = buf.subarray(start, i).toString("utf8");
55
- start = i + 1;
56
- if (text.length > LINE_MAX) continue;
57
- try {
58
- values.push(JSON.parse(text));
59
- } catch {}
60
- }
61
- return { values, used: start };
52
+ export function lines(buf) {
53
+ const values = [];
54
+ let start = 0;
55
+ for (let i = buf.indexOf(10); i >= 0; i = buf.indexOf(10, start)) {
56
+ const text = buf.subarray(start, i).toString("utf8");
57
+ start = i + 1;
58
+ if (text.length > LINE_MAX)
59
+ continue;
60
+ try {
61
+ values.push(JSON.parse(text));
62
+ }
63
+ catch { }
64
+ }
65
+ return { values, used: start };
62
66
  }
63
-
64
- export function engineIO(jobDir , { pollMs = 200 } = {}) {
65
- const spec = JSON.parse(readFrom(join(jobDir, "job.json")).toString("utf8")) ;
66
- if (spec.contract !== "engine@1") throw new Error(`job.json is ${spec.contract}, not engine@1`);
67
- const inbox = join(jobDir, "inbox.jsonl");
68
- return {
69
- spec,
70
- emit: (ev ) => appendLine(join(jobDir, "events.jsonl"), ev),
71
- /** The runner's comments, as they arrive; ends when the caller stops iterating. */
72
- async *comments() {
73
- let offset = 0;
74
- for (;;) {
75
- const { values, used } = lines(readFrom(inbox, offset));
76
- offset += used;
77
- for (const v of values) if ((v )?.t === "comment" && typeof (v ).text === "string") yield v ;
78
- if (!values.length) await new Promise((r) => setTimeout(r, pollMs));
79
- }
80
- },
81
- };
67
+ export function engineIO(jobDir, { pollMs = 200 } = {}) {
68
+ const spec = JSON.parse(readFrom(join(jobDir, "job.json")).toString("utf8"));
69
+ if (spec.contract !== "engine@1")
70
+ throw new Error(`job.json is ${spec.contract}, not engine@1`);
71
+ const inbox = join(jobDir, "inbox.jsonl");
72
+ return {
73
+ spec,
74
+ emit: (ev) => appendLine(join(jobDir, "events.jsonl"), ev),
75
+ /** The runner's comments, as they arrive; ends when the caller stops iterating. */
76
+ async *comments() {
77
+ let offset = 0;
78
+ for (;;) {
79
+ const { values, used } = lines(readFrom(inbox, offset));
80
+ offset += used;
81
+ for (const v of values)
82
+ if (v?.t === "comment" && typeof v.text === "string")
83
+ yield v;
84
+ if (!values.length)
85
+ await new Promise((r) => setTimeout(r, pollMs));
86
+ }
87
+ },
88
+ };
82
89
  }
83
-
84
90
  /**
85
91
  * Run the engine's own program: its output goes on to ours (the job log) as it is, each JSON line to `onJson`. `input`: text
86
92
  * for its stdin (none: no stdin), or a function given a writer that keeps stdin open (live input) until it calls end(). Resolves with the exit
87
93
  * code, or 127 with `error` when the program couldn't start.
88
94
  */
89
- export function runProgram(argv , { env, input, onJson } ) {
90
- return new Promise((resolve) => {
91
- const [cmd = "", ...args] = argv;
92
- const child = spawn(cmd, args, { env, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "inherit"] });
93
- let buf = "";
94
- child.stdout?.setEncoding("utf8");
95
- child.stdout?.on("data", (d ) => {
96
- process.stdout.write(d);
97
- buf += d;
98
- for (let i = buf.indexOf("\n"); i >= 0; i = buf.indexOf("\n")) {
99
- const line = buf.slice(0, i);
100
- buf = buf.slice(i + 1);
101
- if (!line.startsWith("{")) continue;
102
- try {
103
- onJson(JSON.parse(line));
104
- } catch {}
105
- }
95
+ export function runProgram(argv, { env, input, onJson }) {
96
+ return new Promise((resolve) => {
97
+ const [cmd = "", ...args] = argv;
98
+ const child = spawn(cmd, args, { env, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "inherit"] });
99
+ let buf = "";
100
+ child.stdout?.setEncoding("utf8");
101
+ child.stdout?.on("data", (d) => {
102
+ process.stdout.write(d);
103
+ buf += d;
104
+ for (let i = buf.indexOf("\n"); i >= 0; i = buf.indexOf("\n")) {
105
+ const line = buf.slice(0, i);
106
+ buf = buf.slice(i + 1);
107
+ if (!line.startsWith("{"))
108
+ continue;
109
+ try {
110
+ onJson(JSON.parse(line));
111
+ }
112
+ catch { }
113
+ }
114
+ });
115
+ const stdin = child.stdin;
116
+ stdin?.on("error", () => { });
117
+ if (stdin && typeof input === "function")
118
+ input({ write: (s) => !stdin.writableEnded && (stdin.write(s), true), end: () => stdin.end() });
119
+ else
120
+ stdin?.end(input);
121
+ child.on("error", (e) => resolve({ code: 127, error: `couldn't start ${argv[0]}: ${e.code ?? e.message}` }));
122
+ child.on("close", (code, signal) => resolve({ code: code ?? (signal ? 128 + 15 : 1) }));
106
123
  });
107
- const stdin = child.stdin;
108
- stdin?.on("error", () => {});
109
- if (stdin && typeof input === "function") input({ write: (s) => !stdin.writableEnded && (stdin.write(s), true), end: () => stdin.end() });
110
- else stdin?.end(input);
111
- child.on("error", (e ) => resolve({ code: 127, error: `couldn't start ${argv[0]}: ${e.code ?? e.message}` }));
112
- child.on("close", (code , signal ) => resolve({ code: code ?? (signal ? 128 + 15 : 1) }));
113
- });
114
124
  }
@@ -0,0 +1,56 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ export interface Requester {
3
+ agent: string;
4
+ key: string;
5
+ name: string;
6
+ roles: string[];
7
+ kind: string;
8
+ task?: string;
9
+ run?: string;
10
+ module?: string;
11
+ }
12
+ export interface PlanRequest {
13
+ kind: string;
14
+ args: any;
15
+ requester: Requester;
16
+ task: string;
17
+ evidence?: unknown;
18
+ revalidate?: boolean;
19
+ }
20
+ export interface PlanResult {
21
+ args: unknown;
22
+ targets?: Record<string, unknown>;
23
+ facts?: Record<string, unknown>;
24
+ raise?: {
25
+ tier: 1 | 2;
26
+ panel?: boolean;
27
+ reason: string;
28
+ rule: string;
29
+ };
30
+ card?: Record<string, string>;
31
+ satisfied?: {
32
+ evidence: string;
33
+ };
34
+ }
35
+ export interface ExecuteRequest {
36
+ id: string;
37
+ kind: string;
38
+ args: any;
39
+ digest: string;
40
+ idempotency_key: string;
41
+ }
42
+ export interface Executor {
43
+ plan(req: PlanRequest): Promise<PlanResult>;
44
+ /** Runs the write; its result is the outcome the kernel records and tells the task. Throwing is a failed outcome. */
45
+ execute(rec: ExecuteRequest): Promise<{
46
+ ok: boolean;
47
+ text: string;
48
+ }>;
49
+ }
50
+ /** A handler for `<path>/*`: answers and returns true, or returns false for any other path. */
51
+ export declare function serveExecutor(ex: Executor, { key, kernelUrl, path, log }: {
52
+ key: string;
53
+ kernelUrl?: string;
54
+ path?: string;
55
+ log?: (msg: string, f?: Record<string, unknown>) => void;
56
+ }): (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;
@@ -5,72 +5,72 @@
5
5
  // POST <path>/status { id, idempotency_key } → { state: running | done | failed | unknown, text? }
6
6
  // The kernel calls execute only for an approved, claimed and revalidated record; plan never changes anything.
7
7
  //
8
- // Canonical copy: kernel/sdk/src/executor.ts. Each consumer holds a byte-identical copy at src/aidenhq-sdk/executor.ts:
9
- // edit this one, then run `node scripts/sync-shared.mjs`.
8
+ // Modules import it as @aidenhq/sdk/executor.
10
9
  import { timingSafeEqual } from "node:crypto";
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
10
  /** A handler for `<path>/*`: answers and returns true, or returns false for any other path. */
27
- export function serveExecutor(ex , { key, kernelUrl = process.env.AIDENHQ_KERNEL_URL ?? "http://10.231.0.1:3130", path = "/aidenhq/v1/executor", log = () => {} }
28
-
29
- ) {
30
- const runs = new Map ();
31
- const send = (res , status , body ) => void res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
32
- const keyed = (req ) => {
33
- const a = Buffer.from(String(req.headers.authorization ?? "").replace(/^Bearer\s+/i, "")), b = Buffer.from(key);
34
- return b.length > 0 && a.length === b.length && timingSafeEqual(a, b);
35
- };
36
- async function report(id , ok , text ) {
37
- for (let i = 0; i < 5; i++) {
38
- const r = await fetch(`${kernelUrl}/v1/writes/${id}/outcome`, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json" }, body: JSON.stringify({ ok, text }), signal: AbortSignal.timeout(15_000) }).catch(() => undefined);
39
- if (r && (r.ok || r.status === 409)) return;
40
- await new Promise((ok) => setTimeout(ok, 2000 * 2 ** i));
11
+ export function serveExecutor(ex, { key, kernelUrl = process.env.AIDENHQ_KERNEL_URL ?? "http://10.231.0.1:3130", path = "/aidenhq/v1/executor", log = () => { } }) {
12
+ const runs = new Map();
13
+ const send = (res, status, body) => void res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
14
+ const keyed = (req) => {
15
+ const a = Buffer.from(String(req.headers.authorization ?? "").replace(/^Bearer\s+/i, "")), b = Buffer.from(key);
16
+ return b.length > 0 && a.length === b.length && timingSafeEqual(a, b);
17
+ };
18
+ async function report(id, ok, text) {
19
+ for (let i = 0; i < 5; i++) {
20
+ const r = await fetch(`${kernelUrl}/v1/writes/${id}/outcome`, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json" }, body: JSON.stringify({ ok, text }), signal: AbortSignal.timeout(15_000) }).catch(() => undefined);
21
+ if (r && (r.ok || r.status === 409))
22
+ return;
23
+ await new Promise((ok) => setTimeout(ok, 2000 * 2 ** i));
24
+ }
25
+ log("executor outcome not delivered", { id });
41
26
  }
42
- log("executor outcome not delivered", { id });
43
- }
44
- return async function handle(req , res ) {
45
- const url = String(req.url ?? "");
46
- if (!url.startsWith(`${path}/`)) return false;
47
- if (req.method !== "POST") return send(res, 405, { error: "POST only" }), true;
48
- if (!keyed(req)) return send(res, 401, { error: "unauthorized" }), true;
49
- let body ;
50
- try {
51
- const chunks = [];
52
- let n = 0;
53
- for await (const c of req) { n += c.length; if (n > 1_000_000) throw new Error("too large"); chunks.push(c); }
54
- body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
55
- } catch (e) { return send(res, 400, { error: (e ).message }), true; }
56
- const op = url.slice(path.length + 1);
57
- const id = String(body?.id ?? "");
58
- try {
59
- if (op === "plan") return send(res, 200, await ex.plan(body)), true;
60
- if (op === "status") return send(res, 200, runs.get(id) ?? { state: "unknown" }), true;
61
- if (op !== "execute") return send(res, 404, { error: "no such operation" }), true;
62
- if (!/^k-[0-9a-f]{16}$/.test(id)) return send(res, 400, { error: "bad id" }), true;
63
- if (!runs.has(id)) {
64
- if (runs.size >= 1000) runs.delete(runs.keys().next().value );
65
- runs.set(id, { state: "running" });
66
- void ex.execute(body).catch((e ) => ({ ok: false, text: e.message })).then(async (o) => {
67
- runs.set(id, { state: o.ok ? "done" : "failed", text: o.text });
68
- await report(id, o.ok, o.text);
69
- });
70
- }
71
- return send(res, 200, { accepted: true }), true;
72
- } catch (e) {
73
- return send(res, 422, { error: String((e ).message ?? e).slice(0, 1000) }), true;
74
- }
75
- };
27
+ return async function handle(req, res) {
28
+ const url = String(req.url ?? "");
29
+ if (!url.startsWith(`${path}/`))
30
+ return false;
31
+ if (req.method !== "POST")
32
+ return send(res, 405, { error: "POST only" }), true;
33
+ if (!keyed(req))
34
+ return send(res, 401, { error: "unauthorized" }), true;
35
+ let body;
36
+ try {
37
+ const chunks = [];
38
+ let n = 0;
39
+ for await (const c of req) {
40
+ n += c.length;
41
+ if (n > 1_000_000)
42
+ throw new Error("too large");
43
+ chunks.push(c);
44
+ }
45
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
46
+ }
47
+ catch (e) {
48
+ return send(res, 400, { error: e.message }), true;
49
+ }
50
+ const op = url.slice(path.length + 1);
51
+ const id = String(body?.id ?? "");
52
+ try {
53
+ if (op === "plan")
54
+ return send(res, 200, await ex.plan(body)), true;
55
+ if (op === "status")
56
+ return send(res, 200, runs.get(id) ?? { state: "unknown" }), true;
57
+ if (op !== "execute")
58
+ return send(res, 404, { error: "no such operation" }), true;
59
+ if (!/^k-[0-9a-f]{16}$/.test(id))
60
+ return send(res, 400, { error: "bad id" }), true;
61
+ if (!runs.has(id)) {
62
+ if (runs.size >= 1000)
63
+ runs.delete(runs.keys().next().value);
64
+ runs.set(id, { state: "running" });
65
+ void ex.execute(body).catch((e) => ({ ok: false, text: e.message })).then(async (o) => {
66
+ runs.set(id, { state: o.ok ? "done" : "failed", text: o.text });
67
+ await report(id, o.ok, o.text);
68
+ });
69
+ }
70
+ return send(res, 200, { accepted: true }), true;
71
+ }
72
+ catch (e) {
73
+ return send(res, 422, { error: String(e.message ?? e).slice(0, 1000) }), true;
74
+ }
75
+ };
76
76
  }