@kana-ai/edgar-sdk 0.0.0-stage → 0.1.1

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.
Files changed (61) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +430 -2
  3. package/dist/src/build/cli.d.ts +6 -0
  4. package/dist/src/build/cli.js +110 -0
  5. package/dist/src/build/json.d.ts +2 -0
  6. package/dist/src/build/json.js +71 -0
  7. package/dist/src/build/manifest.d.ts +15 -0
  8. package/dist/src/build/manifest.js +111 -0
  9. package/dist/src/define/card-block.d.ts +15 -0
  10. package/dist/src/define/card-block.js +66 -0
  11. package/dist/src/define/context.d.ts +60 -0
  12. package/dist/src/define/context.js +1 -0
  13. package/dist/src/define/extension.d.ts +58 -0
  14. package/dist/src/define/extension.js +14 -0
  15. package/dist/src/define/hook.d.ts +61 -0
  16. package/dist/src/define/hook.js +72 -0
  17. package/dist/src/define/service.d.ts +32 -0
  18. package/dist/src/define/service.js +33 -0
  19. package/dist/src/define/tool.d.ts +93 -0
  20. package/dist/src/define/tool.js +24 -0
  21. package/dist/src/define/tracker.d.ts +59 -0
  22. package/dist/src/define/tracker.js +27 -0
  23. package/dist/src/index.d.ts +15 -0
  24. package/dist/src/index.js +12 -0
  25. package/dist/src/outcome/end.d.ts +61 -0
  26. package/dist/src/outcome/end.js +292 -0
  27. package/dist/src/outcome/failures.d.ts +15 -0
  28. package/dist/src/outcome/failures.js +57 -0
  29. package/dist/src/outcome/limits.d.ts +13 -0
  30. package/dist/src/outcome/limits.js +115 -0
  31. package/dist/src/outcome/outcome.d.ts +32 -0
  32. package/dist/src/outcome/outcome.js +59 -0
  33. package/dist/src/outcome/plain.d.ts +7 -0
  34. package/dist/src/outcome/plain.js +55 -0
  35. package/dist/src/outcome/result.d.ts +35 -0
  36. package/dist/src/outcome/result.js +58 -0
  37. package/dist/src/provider/child.d.ts +51 -0
  38. package/dist/src/provider/child.js +152 -0
  39. package/dist/src/provider/serve.d.ts +42 -0
  40. package/dist/src/provider/serve.js +175 -0
  41. package/dist/src/runtime/index.d.ts +4 -0
  42. package/dist/src/runtime/index.js +3 -0
  43. package/dist/src/runtime/invoke.d.ts +10 -0
  44. package/dist/src/runtime/invoke.js +232 -0
  45. package/dist/src/runtime/network.d.ts +20 -0
  46. package/dist/src/runtime/network.js +120 -0
  47. package/dist/src/runtime/ports.d.ts +31 -0
  48. package/dist/src/runtime/ports.js +1 -0
  49. package/dist/src/runtime/secrets.d.ts +13 -0
  50. package/dist/src/runtime/secrets.js +33 -0
  51. package/dist/src/testing/context.d.ts +12 -0
  52. package/dist/src/testing/context.js +39 -0
  53. package/dist/src/testing/index.d.ts +3 -0
  54. package/dist/src/testing/index.js +3 -0
  55. package/dist/src/testing/mock.d.ts +16 -0
  56. package/dist/src/testing/mock.js +39 -0
  57. package/dist/src/wire/codec.d.ts +46 -0
  58. package/dist/src/wire/codec.js +134 -0
  59. package/dist/src/wire/lines.d.ts +10 -0
  60. package/dist/src/wire/lines.js +41 -0
  61. package/package.json +48 -3
@@ -0,0 +1,57 @@
1
+ import { limitFromHeaders } from "#outcome/limits";
2
+ import { failure, permanentFailure, temporaryFailure } from "#outcome/outcome";
3
+ /** The failure of a `fetch` that threw: `cancelled`, `refused` for a host outside the call's capabilities, or `provider_unavailable`. */
4
+ export function fetchFailure(error, signal, context) {
5
+ if (signal.aborted)
6
+ return permanentFailure("cancelled", `${context}: cancelled`);
7
+ const cause = error instanceof Error ? error.cause : undefined;
8
+ if (cause instanceof Error && "_tag" in cause && cause._tag === "NetworkRefused") {
9
+ return permanentFailure("refused", `${context}: ${cause.message}`, { cause: "NetworkRefused" });
10
+ }
11
+ const code = cause instanceof Error && "code" in cause && typeof cause.code === "string"
12
+ ? cause.code
13
+ : error instanceof Error
14
+ ? error.name
15
+ : "unknown";
16
+ return temporaryFailure("provider_unavailable", `${context}: network error`, { cause: code });
17
+ }
18
+ /** The failure of a vendor answer of `kind`, with the limit its headers report. A rate limit waits until the limit resets (`Retry-After` first, then the scheme's reset header), else one minute, and its limit is used up until then. */
19
+ export function vendorFailure(kind, context, cause, headers, from, now = Date.now()) {
20
+ const limit = limitFromHeaders(headers, from.scheme, from.source, now);
21
+ if (kind !== "rate_limited") {
22
+ return failure(kind, `${context}: ${kind}`, {
23
+ cause,
24
+ ...(limit === undefined ? {} : { limit }),
25
+ });
26
+ }
27
+ const resetsAt = limit?.resets_at ?? now + 60_000;
28
+ const retryAfterSeconds = Math.max(0, Math.ceil((resetsAt - now) / 1000));
29
+ return temporaryFailure(kind, `${context}: rate limited`, {
30
+ cause,
31
+ retryAfterSeconds,
32
+ limit: {
33
+ ...(limit ?? { source: from.source }),
34
+ remaining: 0,
35
+ resets_at: Math.max(now, resetsAt),
36
+ },
37
+ });
38
+ }
39
+ /** A port call that the engine refused or could not answer, as the failure of the tool that made it. */
40
+ export function portFailure(error) {
41
+ switch (error.code) {
42
+ case "capability_refused":
43
+ case "sandbox_refused":
44
+ return permanentFailure("refused", error.message, { cause: error.code });
45
+ case "runtime_payload_too_large":
46
+ return permanentFailure("runtime_payload_too_large", error.message, { cause: error.code });
47
+ case "unknown_id":
48
+ return permanentFailure("not_found", error.message, { cause: error.code });
49
+ case "call_ended":
50
+ return permanentFailure("cancelled", error.message, { cause: error.code });
51
+ case "engine_error":
52
+ return temporaryFailure("runtime_crashed", error.message, { cause: error.code });
53
+ default:
54
+ error.code;
55
+ throw new Error("unreachable");
56
+ }
57
+ }
@@ -0,0 +1,13 @@
1
+ import type { Limit } from "@kana-ai/edgar-contracts/outcome";
2
+ import type { Outcome } from "#outcome/outcome";
3
+ export type { Limit };
4
+ /** The header family a vendor reports its limits in; `retry_after` reads only `Retry-After`. */
5
+ export type LimitScheme = "github" | "linear" | "anthropic" | "draft" | "retry_after";
6
+ /** The limit the headers of one answer report, the tightest of the scheme's families; `Retry-After` makes it used up until the time it names. `undefined` when the answer reports none. */
7
+ export declare function limitFromHeaders(headers: Headers, scheme: LimitScheme, source: string, now?: number): Limit | undefined;
8
+ /** Records the limit one answer of a vendor reported during the call that `ctx` belongs to; the newest one goes on the call's outcome when the outcome carries none. `undefined` changes nothing. */
9
+ export declare function reportLimit(ctx: object, limit: Limit | undefined): void;
10
+ /** The newest limit reported on `ctx`, for the runtime and for unit tests. */
11
+ export declare function reportedLimit(ctx: object): Limit | undefined;
12
+ /** `outcome` with the limit reported on `ctx`, unless it has its own or cannot carry one. */
13
+ export declare function withReportedLimit(outcome: Outcome, ctx: object): Outcome;
@@ -0,0 +1,115 @@
1
+ const anthropic = (window) => ({
2
+ prefix: `anthropic-ratelimit-${window}-`,
3
+ reset: "date",
4
+ window,
5
+ });
6
+ const families = {
7
+ github: [{ prefix: "x-ratelimit-", reset: "epoch", windowHeader: "x-ratelimit-resource" }],
8
+ linear: [
9
+ { prefix: "x-ratelimit-requests-", reset: "epoch", window: "requests" },
10
+ { prefix: "x-ratelimit-complexity-", reset: "epoch", window: "complexity" },
11
+ ],
12
+ anthropic: [
13
+ anthropic("requests"),
14
+ anthropic("tokens"),
15
+ anthropic("input-tokens"),
16
+ anthropic("output-tokens"),
17
+ ],
18
+ draft: [{ prefix: "ratelimit-", reset: "delta" }],
19
+ retry_after: [],
20
+ };
21
+ function count(headers, name) {
22
+ const raw = headers.get(name);
23
+ if (raw === null || raw.trim() === "")
24
+ return undefined;
25
+ const value = Number(raw);
26
+ return Number.isInteger(value) && value >= 0 ? value : undefined;
27
+ }
28
+ function resetAt(raw, reset, now) {
29
+ if (raw === null || raw.trim() === "")
30
+ return undefined;
31
+ if (reset === "date") {
32
+ const at = Date.parse(raw);
33
+ return Number.isNaN(at) ? undefined : at;
34
+ }
35
+ const value = Number(raw);
36
+ if (!Number.isFinite(value) || value < 0)
37
+ return undefined;
38
+ if (reset === "delta")
39
+ return now + Math.ceil(value * 1000);
40
+ return value > 1e12 ? Math.round(value) : Math.round(value * 1000);
41
+ }
42
+ /** `Retry-After` as the time it names: seconds from now, or an HTTP date. */
43
+ function retryAt(headers, now) {
44
+ const raw = headers.get("retry-after");
45
+ if (raw === null || raw.trim() === "")
46
+ return undefined;
47
+ const seconds = Number(raw);
48
+ if (Number.isFinite(seconds))
49
+ return now + Math.max(0, Math.ceil(seconds)) * 1000;
50
+ const at = Date.parse(raw);
51
+ return Number.isNaN(at) ? undefined : at;
52
+ }
53
+ function read(headers, family, source, now) {
54
+ const remaining = count(headers, `${family.prefix}remaining`);
55
+ const limit = count(headers, `${family.prefix}limit`);
56
+ const resets_at = resetAt(headers.get(`${family.prefix}reset`), family.reset, now);
57
+ if (remaining === undefined && limit === undefined && resets_at === undefined)
58
+ return undefined;
59
+ const window = (family.windowHeader === undefined ? null : headers.get(family.windowHeader)) ?? family.window;
60
+ return {
61
+ source,
62
+ ...(remaining === undefined ? {} : { remaining }),
63
+ ...(limit === undefined ? {} : { limit }),
64
+ ...(resets_at === undefined ? {} : { resets_at }),
65
+ ...(window === undefined || window === "" ? {} : { window }),
66
+ };
67
+ }
68
+ /** The share of the window left: a count with no size is full unless it is zero. */
69
+ function left(limit) {
70
+ if (limit.remaining === undefined)
71
+ return 1;
72
+ if (limit.limit === undefined || limit.limit === 0)
73
+ return limit.remaining === 0 ? 0 : 1;
74
+ return limit.remaining / limit.limit;
75
+ }
76
+ /** The limit the headers of one answer report, the tightest of the scheme's families; `Retry-After` makes it used up until the time it names. `undefined` when the answer reports none. */
77
+ export function limitFromHeaders(headers, scheme, source, now = Date.now()) {
78
+ const list = families[scheme];
79
+ const found = list
80
+ .map((family) => read(headers, family, source, now))
81
+ .filter((limit) => limit !== undefined);
82
+ const tightest = found.reduce((best, limit) => (best === undefined || left(limit) < left(best) ? limit : best), undefined);
83
+ const retry = retryAt(headers, now);
84
+ if (retry === undefined)
85
+ return tightest;
86
+ return { ...(tightest ?? { source }), remaining: 0, resets_at: retry };
87
+ }
88
+ const reported = new WeakMap();
89
+ /** Records the limit one answer of a vendor reported during the call that `ctx` belongs to; the newest one goes on the call's outcome when the outcome carries none. `undefined` changes nothing. */
90
+ export function reportLimit(ctx, limit) {
91
+ if (limit !== undefined)
92
+ reported.set(ctx, limit);
93
+ }
94
+ /** The newest limit reported on `ctx`, for the runtime and for unit tests. */
95
+ export function reportedLimit(ctx) {
96
+ return reported.get(ctx);
97
+ }
98
+ /** `outcome` with the limit reported on `ctx`, unless it has its own or cannot carry one. */
99
+ export function withReportedLimit(outcome, ctx) {
100
+ const limit = reportedLimit(ctx);
101
+ if (limit === undefined)
102
+ return outcome;
103
+ switch (outcome.outcome) {
104
+ case "done":
105
+ case "temporary_failure":
106
+ case "permanent_failure":
107
+ return outcome.limit === undefined ? { ...outcome, limit } : outcome;
108
+ case "skipped":
109
+ case "waiting":
110
+ return outcome;
111
+ default:
112
+ outcome;
113
+ throw new Error("unreachable");
114
+ }
115
+ }
@@ -0,0 +1,32 @@
1
+ import type { Done as DoneWire, Limit, PermanentFailure, PermanentKind, Skipped, TemporaryFailure, TemporaryKind, Waiting } from "@kana-ai/edgar-contracts/outcome";
2
+ import type { FailureKind } from "@kana-ai/edgar-contracts/provider";
3
+ /** A `done` outcome whose output has the tool's output type. */
4
+ export type Done<O> = DoneWire & {
5
+ readonly output: O;
6
+ };
7
+ /** Every way a stage or a tool call ends: done, skipped, waiting, or a temporary or permanent failure. */
8
+ export type Outcome<O = unknown> = Done<O> | Skipped | TemporaryFailure | PermanentFailure | Waiting;
9
+ /** A failure as the outcome a tool returns. */
10
+ export type Failure = TemporaryFailure | PermanentFailure;
11
+ /** The stage did its work; `limit` is what the vendor said is left, so the engine tracks it while calls succeed. */
12
+ export declare function done<O>(output: O, options?: {
13
+ readonly limit?: Limit;
14
+ }): Done<O>;
15
+ /** Nothing to do. */
16
+ export declare function skipped(): Skipped;
17
+ /** The options of a failure: the wait a rate limit asks for, the raw vendor code, and the limit the vendor reported. */
18
+ export interface FailureOptions {
19
+ readonly retryAfterSeconds?: number;
20
+ readonly cause?: string;
21
+ readonly limit?: Limit;
22
+ }
23
+ /** Try again later; `retryAfterSeconds` wins over the stage's retry interval when longer. */
24
+ export declare function temporaryFailure(kind: TemporaryKind, message: string, options?: FailureOptions): TemporaryFailure;
25
+ /** Trying again cannot help; `cause` keeps the raw vendor code. */
26
+ export declare function permanentFailure(kind: PermanentKind, message: string, options?: Omit<FailureOptions, "retryAfterSeconds">): PermanentFailure;
27
+ /** True for a kind that may lead to another attempt. */
28
+ export declare function isTemporary(kind: FailureKind): kind is TemporaryKind;
29
+ /** A temporary or a permanent failure, picked by the retry state of `kind`. */
30
+ export declare function failure(kind: FailureKind, message: string, options?: FailureOptions): Failure;
31
+ /** Park until something completes `key`, or until `timeoutAt`. */
32
+ export declare function waiting(key: string, timeoutAt: Date): Waiting;
@@ -0,0 +1,59 @@
1
+ /** The stage did its work; `limit` is what the vendor said is left, so the engine tracks it while calls succeed. */
2
+ export function done(output, options = {}) {
3
+ return { outcome: "done", output, ...limitOf(options) };
4
+ }
5
+ function limitOf(options) {
6
+ return options.limit === undefined ? {} : { limit: options.limit };
7
+ }
8
+ /** Nothing to do. */
9
+ export function skipped() {
10
+ return { outcome: "skipped" };
11
+ }
12
+ /** Try again later; `retryAfterSeconds` wins over the stage's retry interval when longer. */
13
+ export function temporaryFailure(kind, message, options = {}) {
14
+ return {
15
+ outcome: "temporary_failure",
16
+ kind,
17
+ message,
18
+ ...(options.retryAfterSeconds === undefined ? {} : { retry_after: options.retryAfterSeconds }),
19
+ ...(options.cause === undefined ? {} : { cause: options.cause }),
20
+ ...limitOf(options),
21
+ };
22
+ }
23
+ /** Trying again cannot help; `cause` keeps the raw vendor code. */
24
+ export function permanentFailure(kind, message, options = {}) {
25
+ return {
26
+ outcome: "permanent_failure",
27
+ kind,
28
+ message,
29
+ ...(options.cause === undefined ? {} : { cause: options.cause }),
30
+ ...limitOf(options),
31
+ };
32
+ }
33
+ const temporaryKinds = {
34
+ provider_unavailable: true,
35
+ rate_limited: true,
36
+ network: true,
37
+ timeout: true,
38
+ silence: true,
39
+ lost_lease: true,
40
+ runtime_crashed: true,
41
+ disk_full: true,
42
+ interrupted: true,
43
+ not_performed: true,
44
+ };
45
+ /** True for a kind that may lead to another attempt. */
46
+ export function isTemporary(kind) {
47
+ return Object.hasOwn(temporaryKinds, kind);
48
+ }
49
+ /** A temporary or a permanent failure, picked by the retry state of `kind`. */
50
+ export function failure(kind, message, options = {}) {
51
+ const { retryAfterSeconds: _, ...permanent } = options;
52
+ return isTemporary(kind)
53
+ ? temporaryFailure(kind, message, options)
54
+ : permanentFailure(kind, message, permanent);
55
+ }
56
+ /** Park until something completes `key`, or until `timeoutAt`. */
57
+ export function waiting(key, timeoutAt) {
58
+ return { outcome: "waiting", key, timeout_at: timeoutAt.getTime() };
59
+ }
@@ -0,0 +1,7 @@
1
+ /** A failure in plain words, when `message` is or starts with a failure kind or a refusal of the engine, as in `capability_refused: the call does not hold a capability`. None for any other message. */
2
+ export declare function plainFailure(message: string): string | undefined;
3
+ /** A step that hit a limit of uncharged tries, as `edgar-core` writes it: why it stopped, in plain words, and what a person checks before a replay. None for any other message. */
4
+ export declare function plainLimit(message: string): {
5
+ why: string;
6
+ next: string;
7
+ } | undefined;
@@ -0,0 +1,55 @@
1
+ /** Each failure kind as one sentence that EDGAR says to a person who does not know the engine: what went wrong, in the first person, with no engine word. */
2
+ const kinds = {
3
+ provider_unavailable: "A service I rely on didn't answer.",
4
+ rate_limited: "A service I rely on told me to slow down.",
5
+ network: "I lost the network connection.",
6
+ timeout: "The step took longer than its time limit.",
7
+ silence: "The step went quiet for too long, so I stopped waiting.",
8
+ lost_lease: "Another worker took this step over.",
9
+ runtime_crashed: "The program that runs this step crashed.",
10
+ disk_full: "The disk is full.",
11
+ interrupted: "I was stopped while the step was running.",
12
+ not_performed: "The step never started.",
13
+ invalid_input: "The step got an input it can't use.",
14
+ invalid: "One of my requests wasn't valid.",
15
+ tool_error: "One of my tools hit an error.",
16
+ refused: "I'm not allowed to do this step.",
17
+ attempts_exhausted: "I tried this step as often as I'm allowed, and it failed each time.",
18
+ denied_by_hook: "A rule of the project didn't let me do this step.",
19
+ denied_by_person: "Someone said no to this step.",
20
+ exposed: "The step would have shown a secret, so I stopped it.",
21
+ stale_base: "The code changed while I was working, so my change no longer fits.",
22
+ manifest_drift: "An extension changed after it was approved, so I can't use it yet.",
23
+ context_exhausted: "The task is too big for me to keep in mind at once.",
24
+ token_budget: "I used up the token budget of this run.",
25
+ unauthenticated: "A key or sign-in I need is missing or no longer valid.",
26
+ forbidden: "One of my keys doesn't have the permission this step needs.",
27
+ not_found: "Something this step needs doesn't exist.",
28
+ cancelled: "The step was stopped.",
29
+ runtime_payload_too_large: "The step made an answer that's too large.",
30
+ };
31
+ /** The refusals of the engine itself, which are not failure kinds, in the same voice. */
32
+ const refusals = {
33
+ capability_refused: "One of my extensions isn't allowed to do what this step needs.",
34
+ sandbox_refused: "The step tried to work outside its work folder.",
35
+ };
36
+ const plain = new Map(Object.entries({ ...kinds, ...refusals }));
37
+ /** A failure in plain words, when `message` is or starts with a failure kind or a refusal of the engine, as in `capability_refused: the call does not hold a capability`. None for any other message. */
38
+ export function plainFailure(message) {
39
+ const word = /^[a-z_]+(?=:|$)/.exec(message.trim())?.[0];
40
+ return word === undefined ? undefined : plain.get(word);
41
+ }
42
+ /** The words of the engine for a step that it stopped trying after too many uncharged tries, each with what a person checks before a replay. The first sentence after the word is already in plain words. */
43
+ const limits = new Map(Object.entries({
44
+ interrupted_limit: "Check why EDGAR keeps stopping with `edgar status` and the service log",
45
+ unavailable_limit: "Wait until it answers again",
46
+ }));
47
+ /** A step that hit a limit of uncharged tries, as `edgar-core` writes it: why it stopped, in plain words, and what a person checks before a replay. None for any other message. */
48
+ export function plainLimit(message) {
49
+ const [, word = "", rest = ""] = /^([a-z_]+): (.+)$/s.exec(message.trim()) ?? [];
50
+ const next = limits.get(word);
51
+ const said = rest.split(/(?<=[.!?])\s+(?=\p{Lu})/u)[0]?.replace(/[.!?]+$/, "") ?? "";
52
+ return next === undefined || said === ""
53
+ ? undefined
54
+ : { why: `${said.charAt(0).toUpperCase()}${said.slice(1)}, so I stopped trying.`, next };
55
+ }
@@ -0,0 +1,35 @@
1
+ /** The success side of a `Result`: read `value` only after `ok` is `true`. */
2
+ export interface Ok<T> {
3
+ readonly ok: true;
4
+ readonly value: T;
5
+ }
6
+ /** The failure side of a `Result`: read `error` only after `ok` is `false`. */
7
+ export interface Err<E> {
8
+ readonly ok: false;
9
+ readonly error: E;
10
+ }
11
+ /**
12
+ * A failure that correct code expects, as a value: validation, not found, a conflict, a vendor refusal, a network error.
13
+ * Narrow it with `if (!r.ok) return r;` before you read `r.value`. A bug is a `throw`, never an `Err`.
14
+ */
15
+ export type Result<T, E> = Ok<T> | Err<E>;
16
+ /** Makes the success side; use it where a function returns a `Result`. */
17
+ export declare function ok<T>(value: T): Ok<T>;
18
+ /** Makes the failure side; use it for a failure the caller is expected to handle. */
19
+ export declare function err<E>(error: E): Err<E>;
20
+ /** Calls `run` at a boundary that throws for an expected failure, such as `JSON.parse`, and maps the caught value with `onThrow`. */
21
+ export declare function attempt<T, E>(run: () => T, onThrow: (caught: unknown) => E): Result<T, E>;
22
+ /** Awaits `run` at a boundary that rejects for an expected failure, such as `fetch`; a synchronous throw in `run` is caught too. */
23
+ export declare function attemptAsync<T, E>(run: () => PromiseLike<T>, onThrow: (caught: unknown) => E): Promise<Result<T, E>>;
24
+ /** Changes the value of a success with `f`; a failure passes through unchanged. */
25
+ export declare function map<T, U, E>(result: Result<T, E>, f: (value: T) => U): Result<U, E>;
26
+ /** Changes the error of a failure with `f`, such as a port error into a tool `Failure`; a success passes through unchanged. */
27
+ export declare function mapError<T, E, F>(result: Result<T, E>, f: (error: E) => F): Result<T, F>;
28
+ /** Runs the next step `f`, which can fail, on the value of a success; the first failure stops the chain. */
29
+ export declare function andThen<T, U, E, F>(result: Result<T, E>, f: (value: T) => Result<U, F>): Result<U, E | F>;
30
+ /** The value of a success, or `fallback` for a failure; use it only when the failure needs no report. */
31
+ export declare function unwrapOr<T, E>(result: Result<T, E>, fallback: T): T;
32
+ /** Every value in order, or the first failure; use it to check a list of inputs that must all be valid. */
33
+ export declare function all<T, E>(results: Iterable<Result<T, E>>): Result<T[], E>;
34
+ /** The value of a success; a failure is a bug here, so it throws an `Error` with `message` and the failure's error as `cause`. Never use it for a failure that correct code expects. */
35
+ export declare function expectOk<T, E>(result: Result<T, E>, message: string): T;
@@ -0,0 +1,58 @@
1
+ /** Makes the success side; use it where a function returns a `Result`. */
2
+ export function ok(value) {
3
+ return { ok: true, value };
4
+ }
5
+ /** Makes the failure side; use it for a failure the caller is expected to handle. */
6
+ export function err(error) {
7
+ return { ok: false, error };
8
+ }
9
+ /** Calls `run` at a boundary that throws for an expected failure, such as `JSON.parse`, and maps the caught value with `onThrow`. */
10
+ export function attempt(run, onThrow) {
11
+ try {
12
+ return ok(run());
13
+ }
14
+ catch (caught) {
15
+ return err(onThrow(caught));
16
+ }
17
+ }
18
+ /** Awaits `run` at a boundary that rejects for an expected failure, such as `fetch`; a synchronous throw in `run` is caught too. */
19
+ export async function attemptAsync(run, onThrow) {
20
+ try {
21
+ return ok(await run());
22
+ }
23
+ catch (caught) {
24
+ return err(onThrow(caught));
25
+ }
26
+ }
27
+ /** Changes the value of a success with `f`; a failure passes through unchanged. */
28
+ export function map(result, f) {
29
+ return result.ok ? ok(f(result.value)) : result;
30
+ }
31
+ /** Changes the error of a failure with `f`, such as a port error into a tool `Failure`; a success passes through unchanged. */
32
+ export function mapError(result, f) {
33
+ return result.ok ? result : err(f(result.error));
34
+ }
35
+ /** Runs the next step `f`, which can fail, on the value of a success; the first failure stops the chain. */
36
+ export function andThen(result, f) {
37
+ return result.ok ? f(result.value) : result;
38
+ }
39
+ /** The value of a success, or `fallback` for a failure; use it only when the failure needs no report. */
40
+ export function unwrapOr(result, fallback) {
41
+ return result.ok ? result.value : fallback;
42
+ }
43
+ /** Every value in order, or the first failure; use it to check a list of inputs that must all be valid. */
44
+ export function all(results) {
45
+ const values = [];
46
+ for (const result of results) {
47
+ if (!result.ok)
48
+ return result;
49
+ values.push(result.value);
50
+ }
51
+ return ok(values);
52
+ }
53
+ /** The value of a success; a failure is a bug here, so it throws an `Error` with `message` and the failure's error as `cause`. Never use it for a failure that correct code expects. */
54
+ export function expectOk(result, message) {
55
+ if (result.ok)
56
+ return result.value;
57
+ throw new Error(message, { cause: result.error });
58
+ }
@@ -0,0 +1,51 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import { type Answer, type JsonObject } from "#wire/codec";
3
+ /** A started vendor program; `exited` resolves with the error code of a start that failed, such as `ENOENT`, or `undefined`. */
4
+ export interface Child {
5
+ readonly stdin: Writable;
6
+ readonly stdout: Readable;
7
+ kill(): void;
8
+ readonly exited: Promise<string | undefined>;
9
+ }
10
+ /**
11
+ * Starts `program` from `PATH` with exactly `env`, in its own process group, each stderr line in `log` after `<prefix>: `.
12
+ * It runs through `env -u NODE_OPTIONS`, because Node passes the runtime's permission model to every Node child through that variable, and the model binds EDGAR's runtime, not the vendor's program.
13
+ * Starts a child process, so no unit test calls it.
14
+ */
15
+ export declare function spawnVendor(program: string, args: readonly string[], env: Readonly<Record<string, string>>, prefix: string, log: (line: string) => void): Child;
16
+ /** What this side answers to a request of the child. */
17
+ export type Reply = {
18
+ readonly result: unknown;
19
+ } | {
20
+ readonly error: {
21
+ readonly code: number;
22
+ readonly message: string;
23
+ };
24
+ };
25
+ /** How the channel reads and answers the child. */
26
+ export interface ChannelOptions {
27
+ /** `false` for a vendor that sends and expects no `"jsonrpc": "2.0"` field. */
28
+ readonly jsonrpc: boolean;
29
+ readonly onRequest: (method: string, params: JsonObject) => Promise<Reply>;
30
+ readonly onNotify: (method: string, params: JsonObject) => void;
31
+ readonly log: (line: string) => void;
32
+ /** A child that sends no line for this long while a request waits is silent. */
33
+ readonly silenceMs: number;
34
+ /** Called once when the child is silent; the caller kills it. */
35
+ readonly onSilent: () => void;
36
+ }
37
+ /** JSON-RPC 2.0 lines with a vendor child over its stdio, from the client side. */
38
+ export interface Channel {
39
+ /** The child's answer, or an error answer once its output ended or it went silent. */
40
+ request(method: string, params: unknown): Promise<Answer>;
41
+ notify(method: string, params: unknown): void;
42
+ /**
43
+ * Stops the silence clock until the returned function is called. Use it while the child
44
+ * waits for this side, for example for a tool answer: it then has nothing to send.
45
+ */
46
+ hold(): () => void;
47
+ /** Resolves once the child's output ended. */
48
+ readonly ended: Promise<void>;
49
+ }
50
+ /** The channel that writes to the child's `stdin` and reads its `stdout` until it ends. */
51
+ export declare function channel(stdout: Readable, stdin: Writable, options: ChannelOptions): Channel;
@@ -0,0 +1,152 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createInterface } from "node:readline";
3
+ import { readLines } from "#wire/codec";
4
+ import { encode } from "#wire/lines";
5
+ /** `env`'s exit code for a program it cannot find on `PATH`. */
6
+ const NOT_FOUND = 127;
7
+ /**
8
+ * Starts `program` from `PATH` with exactly `env`, in its own process group, each stderr line in `log` after `<prefix>: `.
9
+ * It runs through `env -u NODE_OPTIONS`, because Node passes the runtime's permission model to every Node child through that variable, and the model binds EDGAR's runtime, not the vendor's program.
10
+ * Starts a child process, so no unit test calls it.
11
+ */
12
+ export function spawnVendor(program, args, env, prefix, log) {
13
+ const child = spawn("env", ["-u", "NODE_OPTIONS", program, ...args], {
14
+ env,
15
+ stdio: ["pipe", "pipe", "pipe"],
16
+ detached: true,
17
+ });
18
+ const exited = new Promise((resolve) => {
19
+ child.once("error", (error) => resolve(error.code ?? error.message));
20
+ child.once("exit", (code) => resolve(code === NOT_FOUND ? "ENOENT" : undefined));
21
+ });
22
+ child.stdin.on("error", () => { });
23
+ createInterface({ input: child.stderr }).on("line", (line) => log(`${prefix}: ${line}`));
24
+ return {
25
+ stdin: child.stdin,
26
+ stdout: child.stdout,
27
+ kill: () => {
28
+ if (child.pid === undefined || child.exitCode !== null)
29
+ return;
30
+ try {
31
+ process.kill(-child.pid, "SIGKILL");
32
+ }
33
+ catch {
34
+ child.kill("SIGKILL");
35
+ }
36
+ },
37
+ exited,
38
+ };
39
+ }
40
+ function isRecord(value) {
41
+ return typeof value === "object" && value !== null && !Array.isArray(value);
42
+ }
43
+ function answerOf(message) {
44
+ const error = message["error"];
45
+ if (!isRecord(error))
46
+ return { ok: true, result: message["result"] };
47
+ return {
48
+ ok: false,
49
+ code: typeof error["code"] === "number" ? error["code"] : undefined,
50
+ message: typeof error["message"] === "string" ? error["message"] : "the child answered an error",
51
+ };
52
+ }
53
+ /** The channel that writes to the child's `stdin` and reads its `stdout` until it ends. */
54
+ export function channel(stdout, stdin, options) {
55
+ const pending = new Map();
56
+ const version = options.jsonrpc ? { jsonrpc: "2.0" } : {};
57
+ let nextId = 1;
58
+ let open = true;
59
+ let silence;
60
+ let holds = 0;
61
+ const settle = (answer) => {
62
+ for (const resolve of pending.values())
63
+ resolve(answer);
64
+ pending.clear();
65
+ };
66
+ const arm = () => {
67
+ clearTimeout(silence);
68
+ if (pending.size === 0 || holds > 0)
69
+ return;
70
+ silence = setTimeout(() => {
71
+ open = false;
72
+ options.onSilent();
73
+ settle({
74
+ ok: false,
75
+ code: undefined,
76
+ message: `the child sent nothing for ${options.silenceMs / 1000} s`,
77
+ });
78
+ }, options.silenceMs).unref();
79
+ };
80
+ const write = (message) => {
81
+ const line = encode({ ...version, ...message });
82
+ if (line === undefined || !open)
83
+ return false;
84
+ stdin.write(line);
85
+ return true;
86
+ };
87
+ const answer = (id, method, params) => {
88
+ options.onRequest(method, params).then((reply) => write({ id, ...reply }), (error) => write({
89
+ id,
90
+ error: {
91
+ code: -32603,
92
+ message: error instanceof Error ? error.message : `${method} failed`,
93
+ },
94
+ }));
95
+ };
96
+ const ended = (async () => {
97
+ for await (const line of readLines(stdout)) {
98
+ if (!line.ok || !isRecord(line.value)) {
99
+ options.log("the child sent a line that is not a JSON object");
100
+ continue;
101
+ }
102
+ arm();
103
+ const message = line.value;
104
+ const method = message["method"];
105
+ const id = message["id"];
106
+ if (typeof method === "string") {
107
+ const params = isRecord(message["params"]) ? message["params"] : {};
108
+ if (id === undefined)
109
+ options.onNotify(method, params);
110
+ else
111
+ answer(id, method, params);
112
+ }
113
+ else if (typeof id === "number") {
114
+ const resolve = pending.get(id);
115
+ pending.delete(id);
116
+ resolve?.(answerOf(message));
117
+ arm();
118
+ }
119
+ }
120
+ open = false;
121
+ clearTimeout(silence);
122
+ settle({ ok: false, code: undefined, message: "the child's output ended" });
123
+ })();
124
+ return {
125
+ request: async (method, params) => {
126
+ const id = nextId++;
127
+ const answered = new Promise((resolve) => pending.set(id, resolve));
128
+ if (!write({ id, method, params })) {
129
+ pending.delete(id);
130
+ return { ok: false, code: undefined, message: `${method} was not sent to the child` };
131
+ }
132
+ arm();
133
+ return await answered;
134
+ },
135
+ notify: (method, params) => {
136
+ write({ method, params });
137
+ },
138
+ hold: () => {
139
+ holds += 1;
140
+ arm();
141
+ let held = true;
142
+ return () => {
143
+ if (!held)
144
+ return;
145
+ held = false;
146
+ holds -= 1;
147
+ arm();
148
+ };
149
+ },
150
+ ended,
151
+ };
152
+ }