@aitoroses/telar 0.0.0 → 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.
Files changed (94) hide show
  1. package/README.md +457 -3
  2. package/dist/compile.d.ts +48 -0
  3. package/dist/compile.js +1240 -0
  4. package/dist/contract.d.ts +109 -0
  5. package/dist/contract.js +491 -0
  6. package/dist/evaluator.d.ts +23 -0
  7. package/dist/evaluator.js +40 -0
  8. package/dist/evidence.d.ts +23 -0
  9. package/dist/evidence.js +74 -0
  10. package/dist/guide.d.ts +8 -0
  11. package/dist/guide.js +16 -0
  12. package/dist/install.d.ts +104 -0
  13. package/dist/install.js +402 -0
  14. package/dist/iso.d.ts +10 -0
  15. package/dist/iso.js +73 -0
  16. package/dist/node/build.d.ts +2 -0
  17. package/dist/node/build.js +56 -0
  18. package/dist/node/telar-module.d.ts +2 -0
  19. package/dist/node/telar-module.js +28 -0
  20. package/dist/observer.d.ts +38 -0
  21. package/dist/observer.js +53 -0
  22. package/dist/pieces.d.ts +230 -0
  23. package/dist/pieces.js +178 -0
  24. package/dist/powers.d.ts +46 -0
  25. package/dist/powers.js +126 -0
  26. package/dist/protocol.d.ts +220 -0
  27. package/dist/protocol.js +243 -0
  28. package/dist/query.d.ts +67 -0
  29. package/dist/query.js +102 -0
  30. package/dist/read.d.ts +37 -0
  31. package/dist/read.js +27 -0
  32. package/dist/runner.d.ts +113 -0
  33. package/dist/runner.js +134 -0
  34. package/dist/scenario/builder.d.ts +25 -0
  35. package/dist/scenario/builder.js +603 -0
  36. package/dist/scenario/templates.d.ts +35 -0
  37. package/dist/scenario/templates.js +64 -0
  38. package/dist/scenario/types.d.ts +432 -0
  39. package/dist/scenario/types.js +10 -0
  40. package/dist/scenario/validate.d.ts +7 -0
  41. package/dist/scenario/validate.js +19 -0
  42. package/dist/scenario.d.ts +4 -0
  43. package/dist/scenario.js +4 -0
  44. package/dist/schema.d.ts +221 -0
  45. package/dist/schema.js +227 -0
  46. package/dist/seating.d.ts +47 -0
  47. package/dist/seating.js +26 -0
  48. package/dist/send-hook.d.ts +46 -0
  49. package/dist/send-hook.js +123 -0
  50. package/dist/show.d.ts +34 -0
  51. package/dist/show.js +1 -0
  52. package/dist/source.d.ts +85 -0
  53. package/dist/source.js +104 -0
  54. package/dist/spec.d.ts +21 -0
  55. package/dist/spec.js +18 -0
  56. package/dist/standard-schema.d.ts +21 -0
  57. package/dist/standard-schema.js +1 -0
  58. package/dist/std/accuracy.d.ts +12 -0
  59. package/dist/std/accuracy.js +122 -0
  60. package/dist/std/ack.d.ts +14 -0
  61. package/dist/std/ack.js +43 -0
  62. package/dist/std/actions.d.ts +105 -0
  63. package/dist/std/actions.js +153 -0
  64. package/dist/std/brief.d.ts +36 -0
  65. package/dist/std/brief.js +78 -0
  66. package/dist/std/claude-code.d.ts +9 -0
  67. package/dist/std/claude-code.js +113 -0
  68. package/dist/std/compare.d.ts +29 -0
  69. package/dist/std/compare.js +36 -0
  70. package/dist/std/git-workspace.d.ts +44 -0
  71. package/dist/std/git-workspace.js +184 -0
  72. package/dist/std/judgment.d.ts +85 -0
  73. package/dist/std/judgment.js +462 -0
  74. package/dist/std/observe-command.d.ts +23 -0
  75. package/dist/std/observe-command.js +151 -0
  76. package/dist/std/observe-github-checks.d.ts +24 -0
  77. package/dist/std/observe-github-checks.js +289 -0
  78. package/dist/std/observe-http-status.d.ts +27 -0
  79. package/dist/std/observe-http-status.js +193 -0
  80. package/dist/std/plan.d.ts +7 -0
  81. package/dist/std/plan.js +28 -0
  82. package/dist/std/queries.d.ts +31 -0
  83. package/dist/std/queries.js +318 -0
  84. package/dist/std/reading.d.ts +17 -0
  85. package/dist/std/reading.js +88 -0
  86. package/dist/std/schedule.d.ts +19 -0
  87. package/dist/std/schedule.js +122 -0
  88. package/dist/std.d.ts +15 -0
  89. package/dist/std.js +15 -0
  90. package/dist/types.d.ts +370 -0
  91. package/dist/types.js +1 -0
  92. package/dist/values.d.ts +81 -0
  93. package/dist/values.js +129 -0
  94. package/package.json +62 -5
@@ -0,0 +1,23 @@
1
+ export interface EvidenceRef {
2
+ readonly kind: string;
3
+ readonly id?: string | undefined;
4
+ readonly url?: string | undefined;
5
+ }
6
+ export interface Readings {
7
+ readonly "tokens.input"?: number | undefined;
8
+ readonly "tokens.output"?: number | undefined;
9
+ readonly "tokens.cacheRead"?: number | undefined;
10
+ readonly "tokens.cacheWrite"?: number | undefined;
11
+ readonly usd?: number | undefined;
12
+ readonly [key: string]: number | undefined;
13
+ }
14
+ export interface Evidence {
15
+ readonly at?: string | undefined;
16
+ readonly refs?: readonly EvidenceRef[] | undefined;
17
+ readonly status?: number | undefined;
18
+ readonly durationMs?: number | undefined;
19
+ readonly readings?: Readings | undefined;
20
+ }
21
+ export type WorkEvidence = Omit<Evidence, "at" | "durationMs">;
22
+ export declare function evidenceProblems(raw: unknown): string[];
23
+ export declare function workEvidenceProblems(raw: unknown): string[];
@@ -0,0 +1,74 @@
1
+ import { formatIsoUtc, isCanonicalIsoUtc, parseIsoUtc } from "./iso.js";
2
+ const EV_KEYS = new Set(["at", "refs", "status", "durationMs", "readings"]);
3
+ const REF_KEYS = new Set(["kind", "id", "url"]);
4
+ const isRec = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
5
+ const nonEmpty = (v) => typeof v === "string" && v.length > 0;
6
+ const isIntIn = (v, min, max) => typeof v === "number" && Number.isInteger(v) && v >= min && v <= max;
7
+ export function evidenceProblems(raw) {
8
+ if (!isRec(raw))
9
+ return ["evidence must be an object"];
10
+ const out = [];
11
+ for (const k of Object.keys(raw))
12
+ if (!EV_KEYS.has(k))
13
+ out.push(`unknown evidence key ${JSON.stringify(k)}`);
14
+ const { at, refs, status, durationMs, readings } = raw;
15
+ if (at !== undefined)
16
+ checkAt(at, out);
17
+ if (refs !== undefined)
18
+ checkRefs(refs, out);
19
+ if (status !== undefined && !isIntIn(status, 100, 599))
20
+ out.push(`status ${JSON.stringify(status)} is not an HTTP status`);
21
+ if (durationMs !== undefined && !isIntIn(durationMs, 0, Number.MAX_SAFE_INTEGER))
22
+ out.push(`durationMs ${JSON.stringify(durationMs)} is not a non-negative integer`);
23
+ if (readings !== undefined)
24
+ checkReadings(readings, out);
25
+ return out;
26
+ }
27
+ export function workEvidenceProblems(raw) {
28
+ if (!isRec(raw))
29
+ return ["evidence must be an object"];
30
+ const out = [];
31
+ for (const f of ["at", "durationMs"])
32
+ if (raw[f] !== undefined)
33
+ out.push(`work evidence must not carry ${f} (work time is startedAt/endedAt; the host measures actions)`);
34
+ return out.concat(evidenceProblems(raw));
35
+ }
36
+ function checkAt(at, out) {
37
+ if (typeof at !== "string")
38
+ return void out.push("at must be canonical UTC (YYYY-MM-DDTHH:MM:SS.sssZ)");
39
+ if (!isCanonicalIsoUtc(at)) {
40
+ const p = parseIsoUtc(at);
41
+ const ex = p !== undefined ? `, e.g. ${JSON.stringify(formatIsoUtc(p))}` : "";
42
+ out.push(`at ${JSON.stringify(at)} is not canonical UTC (use YYYY-MM-DDTHH:MM:SS.sssZ${ex})`);
43
+ }
44
+ }
45
+ function checkRefs(refs, out) {
46
+ if (!Array.isArray(refs))
47
+ return void out.push("refs must be an array");
48
+ for (const ref of refs) {
49
+ if (!isRec(ref)) {
50
+ out.push("a ref must be an object");
51
+ continue;
52
+ }
53
+ for (const k of Object.keys(ref))
54
+ if (!REF_KEYS.has(k))
55
+ out.push(`unknown ref key ${JSON.stringify(k)}`);
56
+ if (!nonEmpty(ref["kind"]))
57
+ out.push("a ref needs a non-empty kind");
58
+ for (const f of ["id", "url"])
59
+ if (ref[f] !== undefined && !nonEmpty(ref[f]))
60
+ out.push(`ref.${f} must be a non-empty string`);
61
+ }
62
+ }
63
+ function checkReadings(readings, out) {
64
+ if (!isRec(readings))
65
+ return void out.push("readings must be an object");
66
+ for (const [k, v] of Object.entries(readings)) {
67
+ if (!k)
68
+ out.push("reading key must be non-empty");
69
+ if (k === "durationMs")
70
+ out.push("readings must not carry durationMs; use evidence.durationMs (observers)");
71
+ if (typeof v !== "number" || !Number.isFinite(v))
72
+ out.push(`reading ${JSON.stringify(k)} is not a finite number`);
73
+ }
74
+ }
@@ -0,0 +1,8 @@
1
+ import type { FieldRef } from "./values.js";
2
+ export interface Guide {
3
+ readonly kind: "guide";
4
+ readonly text: readonly string[];
5
+ readonly holes: readonly FieldRef[];
6
+ readonly template: string;
7
+ }
8
+ export declare function guide(text: TemplateStringsArray, ...holes: readonly FieldRef[]): Guide;
package/dist/guide.js ADDED
@@ -0,0 +1,16 @@
1
+ export function guide(text, ...holes) {
2
+ const parts = [];
3
+ for (let i = 0; i < text.length; i += 1) {
4
+ parts.push(text[i] ?? "");
5
+ const hole = holes[i];
6
+ if (hole !== undefined) {
7
+ parts.push(`{{${hole.name}}}`);
8
+ }
9
+ }
10
+ return Object.freeze({
11
+ kind: "guide",
12
+ text: Object.freeze([...text]),
13
+ holes: Object.freeze([...holes]),
14
+ template: parts.join(""),
15
+ });
16
+ }
@@ -0,0 +1,104 @@
1
+ import { type Installation } from "./compile.js";
2
+ import { type AnyEvaluator } from "./evaluator.js";
3
+ import { type Query, type QueryArgInput, type QueryArgs } from "./query.js";
4
+ import { type AnyObserver } from "./observer.js";
5
+ import { type RunnableAction } from "./pieces.js";
6
+ import { type AnyRunner } from "./runner.js";
7
+ import { type AnySource, type SourcesConfig } from "./source.js";
8
+ import type { TelarScenarioV1 } from "./scenario/types.js";
9
+ import { type Seating } from "./seating.js";
10
+ import type { TelarSpecV1 } from "./types.js";
11
+ export interface AdmissionProblem {
12
+ readonly path: string;
13
+ readonly message: string;
14
+ readonly fix: string;
15
+ }
16
+ export interface InstallationConfigBase<Runners extends readonly AnyRunner[] = readonly [], Sources extends readonly AnySource[] = readonly []> {
17
+ readonly name: string;
18
+ readonly seating?: Seating<Runners> | undefined;
19
+ readonly sources?: SourcesConfig<Sources> | undefined;
20
+ }
21
+ /** Runs a declared query on the scenario's trail, as `telar query` runs it, and expects its decoded rows. */
22
+ export interface TrailProof<Row = unknown, A extends QueryArgs = QueryArgs> {
23
+ readonly query: Query<Row, A>;
24
+ readonly args?: QueryArgInput<A>;
25
+ readonly rows: readonly Row[];
26
+ }
27
+ /**
28
+ * One scenario `telar test` runs. With `failsWith` it is a mutant: it must fail, and its failure
29
+ * output must contain that text (name the refusal code where the failure has one). A test that
30
+ * must fail takes no proofs.
31
+ */
32
+ export type InstallationTest = {
33
+ readonly scenario: TelarScenarioV1;
34
+ readonly proofs?: readonly TrailProof[];
35
+ readonly failsWith?: undefined;
36
+ } | {
37
+ readonly scenario: TelarScenarioV1;
38
+ readonly failsWith: string;
39
+ readonly proofs?: undefined;
40
+ };
41
+ export interface DeclareFrame<Name extends string = string> {
42
+ readonly type: "declare";
43
+ readonly v: 1;
44
+ readonly name: Name;
45
+ readonly capabilities: readonly string[];
46
+ readonly opens: readonly string[];
47
+ readonly fills: readonly string[];
48
+ readonly wraps: readonly string[];
49
+ }
50
+ export type InstallationCallReply = {
51
+ readonly type: "answer";
52
+ readonly id: string;
53
+ readonly value: unknown;
54
+ } | {
55
+ readonly type: "error";
56
+ readonly id: string;
57
+ readonly code: string;
58
+ readonly message: string;
59
+ };
60
+ export declare class PluginCallError extends Error {
61
+ readonly name: string;
62
+ readonly code: string;
63
+ constructor(code: string, message: string);
64
+ }
65
+ export interface DefineInstallationInput<Name extends string = string, InputConfig extends InstallationConfigBase<Runners, Sources> = InstallationConfigBase, OutputConfig extends InstallationConfigBase<Runners, Sources> = InputConfig, Runners extends readonly AnyRunner[] = readonly [], Sources extends readonly AnySource[] = readonly []> {
66
+ readonly name: Name;
67
+ readonly config?: (settings: InputConfig) => OutputConfig;
68
+ readonly spec: (config: OutputConfig) => Installation | TelarSpecV1;
69
+ readonly pack?: (config: OutputConfig, spec: TelarSpecV1) => readonly unknown[];
70
+ readonly test?: (config: OutputConfig, spec: TelarSpecV1) => readonly InstallationTest[];
71
+ readonly admit?: (config: OutputConfig) => readonly AdmissionProblem[];
72
+ readonly fills?: Readonly<Record<string, (args: unknown) => unknown>>;
73
+ readonly queries?: readonly Query[];
74
+ readonly runners?: Runners;
75
+ readonly sources?: Sources;
76
+ readonly evaluators?: readonly AnyEvaluator[];
77
+ readonly observers?: readonly AnyObserver[];
78
+ readonly actions?: readonly RunnableAction[];
79
+ readonly seating?: Seating<Runners>;
80
+ readonly capabilities?: readonly string[];
81
+ readonly opens?: readonly string[];
82
+ readonly wraps?: readonly string[];
83
+ }
84
+ export type ConfiguredInstallation<OutputConfig extends InstallationConfigBase<Runners, Sources>, Runners extends readonly AnyRunner[] = readonly [], Sources extends readonly AnySource[] = readonly []> = OutputConfig & {
85
+ readonly spec: TelarSpecV1;
86
+ };
87
+ export interface DefinedInstallation<Name extends string = string, InputConfig extends InstallationConfigBase<Runners, Sources> = InstallationConfigBase, OutputConfig extends InstallationConfigBase<Runners, Sources> = InputConfig, Runners extends readonly AnyRunner[] = readonly [], Sources extends readonly AnySource[] = readonly []> {
88
+ readonly name: Name;
89
+ readonly runners: Runners;
90
+ readonly sources: Sources;
91
+ readonly declare: DeclareFrame<Name>;
92
+ readonly config: (settings: InputConfig) => ConfiguredInstallation<OutputConfig, Runners, Sources>;
93
+ readonly call: (frame: unknown) => InstallationCallReply;
94
+ }
95
+ export type SeatingFor<I> = I extends DefinedInstallation<string, never, never, infer Runners, readonly AnySource[]> ? Seating<Runners> : I extends {
96
+ readonly runners: infer Runners extends readonly AnyRunner[];
97
+ } ? Seating<Runners> : never;
98
+ export type SourcesFor<I> = I extends {
99
+ readonly sources: infer Sources extends readonly AnySource[];
100
+ } ? SourcesConfig<Sources> : never;
101
+ export declare function defineInstallation<const Name extends string, InputConfig extends InstallationConfigBase<Runners, Sources>, OutputConfig extends InstallationConfigBase<Runners, Sources> = InputConfig, const Runners extends readonly AnyRunner[] = readonly [], const Sources extends readonly AnySource[] = readonly []>(input: DefineInstallationInput<Name, InputConfig, OutputConfig, Runners, Sources> & {
102
+ readonly config: (settings: InputConfig) => OutputConfig;
103
+ }): DefinedInstallation<Name, InputConfig, OutputConfig, Runners, Sources>;
104
+ export declare function defineInstallation<const Name extends string, const Runners extends readonly AnyRunner[] = readonly [], const Sources extends readonly AnySource[] = readonly []>(input: Omit<DefineInstallationInput<Name, InstallationConfigBase<Runners, Sources>, InstallationConfigBase<Runners, Sources>, Runners, Sources>, "config">): DefinedInstallation<Name, InstallationConfigBase<Runners, Sources>, InstallationConfigBase<Runners, Sources>, Runners, Sources>;
@@ -0,0 +1,402 @@
1
+ import { compile } from "./compile.js";
2
+ import { EvaluatorError, decodeEvaluation, } from "./evaluator.js";
3
+ import { QueryError, bindQuery, decodeQueryRows, issueText, queryUsage, } from "./query.js";
4
+ import { ObserverError } from "./observer.js";
5
+ import { ActionError } from "./pieces.js";
6
+ import { PowerError, hostWorldPowers } from "./powers.js";
7
+ import { RunnerError } from "./runner.js";
8
+ import { SourceError } from "./source.js";
9
+ import { mergeSeating } from "./seating.js";
10
+ export class PluginCallError extends Error {
11
+ name = "PluginCallError";
12
+ code;
13
+ constructor(code, message) {
14
+ super(message);
15
+ this.code = code;
16
+ }
17
+ }
18
+ function isRec(value) {
19
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20
+ }
21
+ function isConfigBase(value) {
22
+ return isRec(value) && typeof value["name"] === "string";
23
+ }
24
+ function isCompiledSpec(value) {
25
+ return isRec(value) && value["format"] === "telar.spec/1";
26
+ }
27
+ function existingCompiledSpec(value) {
28
+ if (!("spec" in value))
29
+ return undefined;
30
+ return isCompiledSpec(value.spec) ? value.spec : undefined;
31
+ }
32
+ function compileSpecValue(value) {
33
+ return "kind" in value ? compile(value) : value;
34
+ }
35
+ function errorReply(id, code, message) {
36
+ const clean = message.trim();
37
+ return { type: "error", id, code, message: clean.length > 0 ? clean : code };
38
+ }
39
+ function readConfigArg(args, input) {
40
+ const raw = isRec(args) && isConfigBase(args["config"]) ? args["config"] : { name: input.name };
41
+ if (input.config !== undefined && existingCompiledSpec(raw) === undefined) {
42
+ return input.config(raw);
43
+ }
44
+ return raw;
45
+ }
46
+ function queryTable(queries) {
47
+ const table = new Map();
48
+ for (const query of queries) {
49
+ if (table.has(query.name)) {
50
+ throw new QueryError("INVALID_QUERY", `query ${query.name} is declared twice`);
51
+ }
52
+ table.set(query.name, query);
53
+ }
54
+ return table;
55
+ }
56
+ function resolveQuery(queries, args) {
57
+ const name = isRec(args) ? args["name"] : undefined;
58
+ const raw = isRec(args) ? args["args"] : undefined;
59
+ const given = Array.isArray(raw)
60
+ ? raw.filter((arg) => typeof arg === "string")
61
+ : [];
62
+ const query = typeof name === "string" ? queries.get(name) : undefined;
63
+ if (query === undefined) {
64
+ const known = [...queries.values()].map(queryUsage);
65
+ return {
66
+ ok: false,
67
+ code: "UNKNOWN_QUERY",
68
+ message: `the installation declares no query ${JSON.stringify(name)}`,
69
+ fix: `${known.length > 0 ? `Run one of: ${known.join(", ")}. ` : ""}Declare a query in defineInstallation({ queries }); telar/std ships cases and caseStory.`,
70
+ };
71
+ }
72
+ const usage = `Run ${queryUsage(query)}.`;
73
+ const names = Object.keys(query.args);
74
+ if (given.length !== names.length) {
75
+ const message = `query ${query.name} takes ${String(names.length)} argument(s), got ${String(given.length)}`;
76
+ return { ok: false, code: "INVALID_QUERY_ARGS", message, fix: usage };
77
+ }
78
+ const bound = bindQuery(query, Object.fromEntries(names.map((arg, i) => [arg, given[i] ?? ""])));
79
+ if (!bound.ok) {
80
+ const message = `query ${query.name}: ${bound.issues.map(issueText).join("; ")}`;
81
+ return { ok: false, code: "INVALID_QUERY_ARGS", message, fix: usage };
82
+ }
83
+ return bound;
84
+ }
85
+ function proofWire(queries, proof) {
86
+ const { query } = proof;
87
+ if (queries.get(query.name) !== query) {
88
+ throw new QueryError("UNKNOWN_QUERY", `proof query ${query.name} is not declared; list it in defineInstallation({ queries })`);
89
+ }
90
+ const bound = bindQuery(query, proof.args ?? {});
91
+ if (!bound.ok) {
92
+ const detail = bound.issues.map(issueText).join("; ");
93
+ throw new QueryError("INVALID_QUERY_ARGS", `proof of ${query.name}: ${detail}`);
94
+ }
95
+ return { query: query.name, sql: bound.sql, params: bound.params, rows: proof.rows };
96
+ }
97
+ function queryRows(queries, args) {
98
+ const name = isRec(args) ? args["name"] : undefined;
99
+ const query = typeof name === "string" ? queries.get(name) : undefined;
100
+ if (query === undefined) {
101
+ throw new QueryError("UNKNOWN_QUERY", `no declared query named ${JSON.stringify(name)}`);
102
+ }
103
+ return decodeQueryRows(query, isRec(args) ? args["rows"] : undefined);
104
+ }
105
+ const RUNNER_FILL_POINTS = ["runner:wake", "runner:poll", "runner:end"];
106
+ function runnerTable(installationName, runners, fills) {
107
+ const table = new Map();
108
+ const prefix = `${installationName}/runner/`;
109
+ for (const runner of runners) {
110
+ if (!runner.id.startsWith(prefix) && !runner.id.startsWith("telar.std/runner/")) {
111
+ throw new RunnerError("INVALID_RUNNER", `runner id ${JSON.stringify(runner.id)} must belong to installation ${JSON.stringify(installationName)} or telar.std`);
112
+ }
113
+ if (table.has(runner.id)) {
114
+ throw new RunnerError("INVALID_RUNNER", `runner ${runner.id} is declared twice`);
115
+ }
116
+ table.set(runner.id, runner);
117
+ }
118
+ if (table.size > 0) {
119
+ for (const point of RUNNER_FILL_POINTS) {
120
+ if (point in fills) {
121
+ throw new RunnerError("INVALID_RUNNER", `do not declare both runners and fills[${JSON.stringify(point)}]`);
122
+ }
123
+ }
124
+ }
125
+ return table;
126
+ }
127
+ function resolveRunner(runners, args) {
128
+ const id = isRec(args) ? args["runner"] : undefined;
129
+ const runner = typeof id === "string" ? runners.get(id) : undefined;
130
+ if (runner === undefined) {
131
+ throw new RunnerError("UNKNOWN_RUNNER", `no declared runner named ${JSON.stringify(id)}`);
132
+ }
133
+ return runner;
134
+ }
135
+ function callRunnerPoint(runners, point, args) {
136
+ return resolveRunner(runners, args).dispatch(point, args, hostWorldPowers());
137
+ }
138
+ function sourceTable(sources) {
139
+ const table = new Map();
140
+ for (const source of sources) {
141
+ if (table.has(source.id)) {
142
+ throw new SourceError("INVALID_SOURCE", `source ${source.id} is declared twice`);
143
+ }
144
+ table.set(source.id, source);
145
+ }
146
+ return table;
147
+ }
148
+ const EVALUATOR_POINT = "evaluator:";
149
+ function evaluatorTable(installationName, evaluators, fills) {
150
+ for (const point of Object.keys(fills)) {
151
+ if (point.startsWith("check:") || point.startsWith(EVALUATOR_POINT)) {
152
+ throw new EvaluatorError("INVALID_EVALUATOR", `fills[${JSON.stringify(point)}] is not a fill point; declare the evaluator with defineEvaluator and list it in evaluators`);
153
+ }
154
+ }
155
+ const table = new Map();
156
+ for (const evaluator of evaluators) {
157
+ if (!evaluator.id.startsWith(`${installationName}/evaluator/`)) {
158
+ throw new EvaluatorError("INVALID_EVALUATOR", `evaluator id ${JSON.stringify(evaluator.id)} must belong to installation ${JSON.stringify(installationName)}`);
159
+ }
160
+ if (table.has(evaluator.id)) {
161
+ throw new EvaluatorError("INVALID_EVALUATOR", `evaluator ${evaluator.id} is declared twice`);
162
+ }
163
+ table.set(evaluator.id, evaluator);
164
+ }
165
+ return table;
166
+ }
167
+ function callEvaluator(evaluators, point, args) {
168
+ const id = point.slice(EVALUATOR_POINT.length);
169
+ const evaluator = evaluators.get(id);
170
+ if (evaluator === undefined) {
171
+ throw new EvaluatorError("UNKNOWN_EVALUATOR", `no declared evaluator named ${JSON.stringify(id)}`);
172
+ }
173
+ if (!isRec(args)) {
174
+ throw new EvaluatorError("INVALID_INPUT", `evaluator ${id} args must be an object`);
175
+ }
176
+ return decodeEvaluation(id, evaluator.evaluate(args));
177
+ }
178
+ function actionTable(installationName, actions) {
179
+ const table = new Map();
180
+ for (const action of actions) {
181
+ const ns = action.id.slice(0, action.id.indexOf("/action/"));
182
+ if (ns !== installationName && ns !== "telar.std") {
183
+ throw new ActionError("INVALID_ACTION", `action id ${JSON.stringify(action.id)} must belong to installation ${JSON.stringify(installationName)} or be a std action`);
184
+ }
185
+ if (table.has(action.id)) {
186
+ throw new ActionError("INVALID_ACTION", `action ${action.id} is declared twice`);
187
+ }
188
+ table.set(action.id, action);
189
+ }
190
+ return table;
191
+ }
192
+ function runAction(actions, args) {
193
+ const id = isRec(args) ? args["action"] : undefined;
194
+ const action = typeof id === "string" ? actions.get(id) : undefined;
195
+ if (action === undefined) {
196
+ throw new ActionError("UNKNOWN_ACTION", `no declared action named ${JSON.stringify(id)}`);
197
+ }
198
+ const input = isRec(args) ? args["input"] : undefined;
199
+ if (!isRec(input)) {
200
+ throw new ActionError("INVALID_INPUT", `action ${action.id} input must be an object`);
201
+ }
202
+ return action.run(input, hostWorldPowers());
203
+ }
204
+ function observerTable(observers) {
205
+ const table = new Map();
206
+ for (const observer of observers) {
207
+ if (table.has(observer.id)) {
208
+ throw new ObserverError("INVALID_OBSERVER", `observer ${observer.id} is declared twice`);
209
+ }
210
+ table.set(observer.id, observer);
211
+ }
212
+ return table;
213
+ }
214
+ function resolveObserver(observers, args) {
215
+ const id = isRec(args) ? args["observer"] : undefined;
216
+ const observer = typeof id === "string" ? observers.get(id) : undefined;
217
+ if (observer === undefined) {
218
+ throw new ObserverError("UNKNOWN_OBSERVER", `no declared observer named ${JSON.stringify(id)}`);
219
+ }
220
+ return observer;
221
+ }
222
+ function resolveSource(sources, args) {
223
+ const id = isRec(args) ? args["source"] : undefined;
224
+ const source = typeof id === "string" ? sources.get(id) : undefined;
225
+ if (source === undefined) {
226
+ throw new SourceError("UNKNOWN_SOURCE", `no declared source named ${JSON.stringify(id)}`);
227
+ }
228
+ return source;
229
+ }
230
+ export function defineInstallation(input) {
231
+ const fills = input.fills ?? {};
232
+ const queries = queryTable(input.queries ?? []);
233
+ const runnerList = Object.freeze([...(input.runners ?? [])]);
234
+ const runners = runnerTable(input.name, runnerList, fills);
235
+ const sourceList = Object.freeze([...(input.sources ?? [])]);
236
+ const sources = sourceTable(sourceList);
237
+ const evaluators = evaluatorTable(input.name, input.evaluators ?? [], fills);
238
+ const observers = observerTable(input.observers ?? []);
239
+ const actions = actionTable(input.name, input.actions ?? []);
240
+ const fillKeys = [
241
+ ...Object.keys(fills),
242
+ ...(runners.size > 0 ? RUNNER_FILL_POINTS : []),
243
+ ...(sources.size > 0 ? ["source:poll"] : []),
244
+ ...[...evaluators.keys()].map((id) => `${EVALUATOR_POINT}${id}`),
245
+ ...(observers.size > 0 ? ["observer:observe"] : []),
246
+ ...(actions.size > 0 ? ["action:run"] : []),
247
+ ];
248
+ const declare = Object.freeze({
249
+ type: "declare",
250
+ v: 1,
251
+ name: input.name,
252
+ capabilities: Object.freeze([...(input.capabilities ?? [])]),
253
+ opens: Object.freeze([...(input.opens ?? [])]),
254
+ fills: Object.freeze(fillKeys),
255
+ wraps: Object.freeze([...(input.wraps ?? [])]),
256
+ });
257
+ const resolveCompiledSpec = (cfg) => {
258
+ const existing = existingCompiledSpec(cfg);
259
+ if (existing !== undefined)
260
+ return existing;
261
+ return compileSpecValue(input.spec(cfg));
262
+ };
263
+ const config = (settings) => {
264
+ const normalized = input.config !== undefined ? input.config(settings) : settings;
265
+ const compiled = resolveCompiledSpec(normalized);
266
+ const seating = mergeSeating(input.seating, normalized.seating);
267
+ return { ...normalized, ...(seating !== undefined ? { seating } : {}), spec: compiled };
268
+ };
269
+ const call = (frame) => {
270
+ const id = isRec(frame) && typeof frame["id"] === "string" ? frame["id"] : "unknown";
271
+ if (!isRec(frame) || frame["type"] !== "call") {
272
+ const got = isRec(frame) ? frame["type"] : typeof frame;
273
+ return errorReply(id, "UNEXPECTED_FRAME", `Expected call frame, got ${String(got)}`);
274
+ }
275
+ if (frame["wrap"] === true) {
276
+ return errorReply(id, "UNSUPPORTED_WRAP", "wrap calls are not supported");
277
+ }
278
+ const point = frame["point"];
279
+ const args = frame["args"];
280
+ if (typeof point !== "string") {
281
+ return errorReply(id, "UNKNOWN_POINT", `Unsupported extension point ${String(point)}`);
282
+ }
283
+ try {
284
+ if (point === "install:admit") {
285
+ const cfg = readConfigArg(args, input);
286
+ const problems = input.admit !== undefined ? [...input.admit(cfg)] : [];
287
+ return { type: "answer", id, value: problems };
288
+ }
289
+ if (point === "install:spec") {
290
+ const cfg = readConfigArg(args, input);
291
+ return { type: "answer", id, value: resolveCompiledSpec(cfg) };
292
+ }
293
+ if (point === "install:pack") {
294
+ const cfg = readConfigArg(args, input);
295
+ const compiled = resolveCompiledSpec(cfg);
296
+ const scenarios = input.pack !== undefined ? [...input.pack(cfg, compiled)] : [];
297
+ return { type: "answer", id, value: scenarios };
298
+ }
299
+ if (point === "install:test") {
300
+ const cfg = readConfigArg(args, input);
301
+ const compiled = resolveCompiledSpec(cfg);
302
+ const tests = (input.test !== undefined ? [...input.test(cfg, compiled)] : []).map((test) => test.proofs === undefined
303
+ ? test
304
+ : { ...test, proofs: test.proofs.map((proof) => proofWire(queries, proof)) });
305
+ return { type: "answer", id, value: tests };
306
+ }
307
+ if (point === "install:query") {
308
+ return { type: "answer", id, value: resolveQuery(queries, args) };
309
+ }
310
+ if (point === "install:query-rows") {
311
+ return { type: "answer", id, value: queryRows(queries, args) };
312
+ }
313
+ if (point === "install:runners") {
314
+ return { type: "answer", id, value: [...runners.keys()] };
315
+ }
316
+ if (point === "install:runner-admit") {
317
+ const runner = resolveRunner(runners, args);
318
+ const rawOptions = isRec(args) ? args["options"] : undefined;
319
+ const checked = runner.admitOptions(rawOptions);
320
+ return {
321
+ type: "answer",
322
+ id,
323
+ value: checked.ok ? { ok: true } : { ok: false, issues: checked.issues },
324
+ };
325
+ }
326
+ if (point === "install:sources") {
327
+ const declared = [...sources.values()].map((s) => ({
328
+ id: s.id,
329
+ eventFields: s.eventFields,
330
+ }));
331
+ return { type: "answer", id, value: declared };
332
+ }
333
+ if (point === "install:source-admit") {
334
+ const checked = resolveSource(sources, args).admitOptions(isRec(args) ? args["options"] : undefined);
335
+ return {
336
+ type: "answer",
337
+ id,
338
+ value: checked.ok ? { ok: true } : { ok: false, issues: checked.issues },
339
+ };
340
+ }
341
+ if (point === "install:observers") {
342
+ return { type: "answer", id, value: [...observers.keys()] };
343
+ }
344
+ if (point === "install:observer-admit") {
345
+ const checked = resolveObserver(observers, args).admitParams(isRec(args) ? args["params"] : undefined);
346
+ return {
347
+ type: "answer",
348
+ id,
349
+ value: checked.ok ? { ok: true } : { ok: false, issues: checked.issues },
350
+ };
351
+ }
352
+ if (point === "install:actions") {
353
+ return { type: "answer", id, value: [...actions.keys()] };
354
+ }
355
+ if (actions.size > 0 && point === "action:run") {
356
+ return { type: "answer", id, value: runAction(actions, args) };
357
+ }
358
+ if (observers.size > 0 && point === "observer:observe") {
359
+ const value = resolveObserver(observers, args).dispatch(args, hostWorldPowers());
360
+ return { type: "answer", id, value };
361
+ }
362
+ if (sources.size > 0 && point === "source:poll") {
363
+ const value = resolveSource(sources, args).dispatch(args, hostWorldPowers());
364
+ return { type: "answer", id, value };
365
+ }
366
+ if (runners.size > 0 &&
367
+ (point === "runner:wake" || point === "runner:poll" || point === "runner:end")) {
368
+ return { type: "answer", id, value: callRunnerPoint(runners, point, args) };
369
+ }
370
+ if (point.startsWith(EVALUATOR_POINT)) {
371
+ return { type: "answer", id, value: callEvaluator(evaluators, point, args) };
372
+ }
373
+ const handler = fills[point];
374
+ if (handler !== undefined) {
375
+ return { type: "answer", id, value: handler(args) };
376
+ }
377
+ return errorReply(id, "UNKNOWN_POINT", `Unsupported extension point ${point}`);
378
+ }
379
+ catch (err) {
380
+ if (err instanceof PluginCallError ||
381
+ err instanceof ActionError ||
382
+ err instanceof EvaluatorError ||
383
+ err instanceof QueryError ||
384
+ err instanceof RunnerError ||
385
+ err instanceof SourceError ||
386
+ err instanceof ObserverError ||
387
+ err instanceof PowerError) {
388
+ return errorReply(id, err.code, err.message);
389
+ }
390
+ const message = err instanceof Error ? err.message : String(err);
391
+ return errorReply(id, "HANDLER_ERROR", message);
392
+ }
393
+ };
394
+ return Object.freeze({
395
+ name: input.name,
396
+ runners: runnerList,
397
+ sources: sourceList,
398
+ declare,
399
+ config,
400
+ call,
401
+ });
402
+ }
package/dist/iso.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** Milliseconds since the epoch of an ISO-UTC instant, or undefined. Pure: telar's QuickJS has no `Date`. */
2
+ export declare function parseIsoUtc(value: string): number | undefined;
3
+ /** True iff `value` is the single canonical UTC form (`YYYY-MM-DDTHH:MM:SS.sssZ`) and a real instant. */
4
+ export declare function isCanonicalIsoUtc(value: string): boolean;
5
+ export declare function formatIsoUtc(ms: number): string;
6
+ /**
7
+ * The UTC offset of an IANA zone at an instant, in minutes, or undefined for an unknown zone.
8
+ * telar's host answers it from the tzdb bundled with the telar release.
9
+ */
10
+ export declare function zoneOffset(zone: string, epochMs: number): number | undefined;