@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,462 @@
1
+ import { SpecCompileError, answer, check, compile, contract, defineClass, engine, fields, fromAnswer, installation, literal, protocol, role, seat, set, step, t, } from "../spec.js";
2
+ import { typedRef } from "./brief.js";
3
+ import { compareNumber } from "./compare.js";
4
+ export const LADDER_EVALUATOR_ID = "telar.std/ladder/1";
5
+ const ID_RE = /^[a-z][a-z0-9-]*$/;
6
+ const RESERVED_KIND_FIELDS = new Set(["cost", "rationale"]);
7
+ const RESERVED_RECORD_FIELDS = new Set([
8
+ "question",
9
+ "questionVersion",
10
+ "inputHash",
11
+ "seat",
12
+ "rung",
13
+ "cost",
14
+ ]);
15
+ function failJudgment(path, message) {
16
+ throw new SpecCompileError(path, message);
17
+ }
18
+ function assertIdentifier(value, path) {
19
+ if (!ID_RE.test(value)) {
20
+ failJudgment(path, `invalid identifier ${JSON.stringify(value)}`);
21
+ }
22
+ }
23
+ export function choiceKind(opts) {
24
+ return Object.freeze({
25
+ kind: "choice",
26
+ options: opts.options,
27
+ evidenceRequired: opts.evidenceRequired ?? false,
28
+ ...(opts.typedRef !== undefined ? { typedRef: opts.typedRef } : {}),
29
+ annotated: opts.annotated ?? false,
30
+ });
31
+ }
32
+ export function customKind(opts) {
33
+ return Object.freeze({
34
+ kind: "custom",
35
+ fields: opts.fields,
36
+ outcomes: opts.outcomes,
37
+ record: Object.freeze([...opts.record]),
38
+ });
39
+ }
40
+ const ladderParamsSchema = t.struct({
41
+ thresholds: t.array(t.number({ min: 0, max: 1 })),
42
+ });
43
+ export function ladder(rungs, last) {
44
+ const thresholds = [];
45
+ const allRungs = [];
46
+ const seen = new Set();
47
+ for (const r of rungs) {
48
+ if (!Number.isFinite(r.threshold) || r.threshold < 0 || r.threshold > 1) {
49
+ failJudgment("ladder.rungs", `threshold ${String(r.threshold)} must be in [0, 1]`);
50
+ }
51
+ thresholds.push(r.threshold);
52
+ allRungs.push({ role: r.role, label: r.label });
53
+ }
54
+ allRungs.push(last);
55
+ for (const r of allRungs) {
56
+ assertIdentifier(r.label, "ladder.rungs");
57
+ const key = `${r.role.name}/${r.label}`;
58
+ if (seen.has(key)) {
59
+ failJudgment("ladder.rungs", `duplicate rung ${key}`);
60
+ }
61
+ seen.add(key);
62
+ }
63
+ const [first, ...rest] = allRungs;
64
+ if (first === undefined) {
65
+ failJudgment("ladder.rungs", "ladder requires at least one rung");
66
+ }
67
+ const rungsTuple = Object.freeze([first, ...rest]);
68
+ return Object.freeze({
69
+ rungs: rungsTuple,
70
+ policy: Object.freeze({
71
+ evaluator: LADDER_EVALUATOR_ID,
72
+ params: Object.freeze({ thresholds }),
73
+ paramsSchema: ladderParamsSchema,
74
+ }),
75
+ });
76
+ }
77
+ export function withRungLabels(base, labels) {
78
+ const merged = new Set(base.seatLabels?.["rung"] ?? []);
79
+ for (const label of labels)
80
+ merged.add(label);
81
+ const sorted = [...merged].toSorted();
82
+ const [first, ...rest] = sorted;
83
+ if (first === undefined) {
84
+ failJudgment(`roles.${base.name}`, "rung labels must be non-empty");
85
+ }
86
+ return role(base.name, {
87
+ view: base.view,
88
+ ...(base.includePredecessor !== undefined
89
+ ? { includePredecessor: base.includePredecessor }
90
+ : {}),
91
+ seatLabels: { rung: [first, ...rest] },
92
+ });
93
+ }
94
+ function resolveKind(kind, q) {
95
+ if (kind.kind === "choice") {
96
+ const seen = new Set();
97
+ for (const o of kind.options) {
98
+ assertIdentifier(o, `${q}.kind.options`);
99
+ if (seen.has(o))
100
+ failJudgment(`${q}.kind.options`, `duplicate option ${JSON.stringify(o)}`);
101
+ seen.add(o);
102
+ }
103
+ const nonEmpty = t.string({ nonEmpty: true });
104
+ const refSchema = kind.typedRef ??
105
+ (kind.annotated ? typedRef : t.struct({ kind: nonEmpty, id: nonEmpty, title: nonEmpty }));
106
+ const evidenceArr = t.array(refSchema, kind.annotated
107
+ ? { description: "Typed references supporting the answer", audience: "agent" }
108
+ : undefined);
109
+ const fieldsMap = {
110
+ option: t.enum(kind.options, kind.annotated
111
+ ? { description: "Chosen option id from the question", audience: "agent" }
112
+ : undefined),
113
+ probability: t.number({
114
+ min: 0,
115
+ max: 1,
116
+ ...(kind.annotated
117
+ ? { description: "Confidence in the chosen option between 0 and 1", audience: "agent" }
118
+ : {}),
119
+ }),
120
+ evidence: kind.evidenceRequired ? evidenceArr : t.optional(evidenceArr),
121
+ };
122
+ return { fields: fieldsMap, outcomes: kind.options, record: ["option", "probability"] };
123
+ }
124
+ const seenOutcomes = new Set();
125
+ for (const o of kind.outcomes) {
126
+ assertIdentifier(o, `${q}.kind.outcomes`);
127
+ if (seenOutcomes.has(o)) {
128
+ failJudgment(`${q}.kind.outcomes`, `duplicate outcome ${JSON.stringify(o)}`);
129
+ }
130
+ seenOutcomes.add(o);
131
+ }
132
+ for (const fieldName of Object.keys(kind.fields)) {
133
+ if (RESERVED_KIND_FIELDS.has(fieldName)) {
134
+ failJudgment(`${q}.kind.fields.${fieldName}`, `reserved kind field ${JSON.stringify(fieldName)}`);
135
+ }
136
+ }
137
+ const seenRecord = new Set();
138
+ for (const recField of kind.record) {
139
+ if (RESERVED_RECORD_FIELDS.has(recField)) {
140
+ failJudgment(`${q}.kind.record`, `reserved record field ${JSON.stringify(recField)}`);
141
+ }
142
+ const decl = kind.fields[recField];
143
+ if (decl === undefined || decl.kind === "optional") {
144
+ failJudgment(`${q}.kind.record`, `record field ${JSON.stringify(recField)} must name a required kind field`);
145
+ }
146
+ if (seenRecord.has(recField)) {
147
+ failJudgment(`${q}.kind.record`, `duplicate record field ${JSON.stringify(recField)}`);
148
+ }
149
+ seenRecord.add(recField);
150
+ }
151
+ return { fields: kind.fields, outcomes: kind.outcomes, record: kind.record };
152
+ }
153
+ function collectRungLabels(rungs, q) {
154
+ const byRole = new Map();
155
+ for (const r of rungs) {
156
+ assertIdentifier(r.label, `${q}.rungs`);
157
+ const setForRole = byRole.get(r.role.name) ?? new Set();
158
+ if (setForRole.has(r.label)) {
159
+ failJudgment(`${q}.rungs`, `duplicate rung label ${r.role.name}/${r.label}`);
160
+ }
161
+ setForRole.add(r.label);
162
+ byRole.set(r.role.name, setForRole);
163
+ }
164
+ const out = {};
165
+ for (const [roleName, labels] of [...byRole.entries()].toSorted(([a], [b]) => a.localeCompare(b))) {
166
+ const sorted = [...labels].toSorted();
167
+ const [first, ...rest] = sorted;
168
+ if (first !== undefined) {
169
+ out[roleName] = [first, ...rest];
170
+ }
171
+ }
172
+ return out;
173
+ }
174
+ export function judgmentProtocol(def) {
175
+ assertIdentifier(def.question, "question");
176
+ const q = def.question;
177
+ const resolved = resolveKind(def.kind, q);
178
+ const rungLabels = collectRungLabels(def.rungs, q);
179
+ const nonEmpty = t.string({ nonEmpty: true });
180
+ const annotated = def.kind.kind === "choice" && def.kind.annotated;
181
+ const rationale = def.rationale ??
182
+ (annotated
183
+ ? t.string({
184
+ nonEmpty: true,
185
+ description: "Why this option was chosen",
186
+ audience: "agent",
187
+ })
188
+ : nonEmpty);
189
+ const outcomeSchema = t.enum(resolved.outcomes);
190
+ const rungIndex = t.int({ min: 0 });
191
+ const costSchema = t.number({
192
+ min: 0,
193
+ ...(annotated
194
+ ? { description: "Estimated cost of this answer in USD", audience: "agent" }
195
+ : {}),
196
+ });
197
+ const answerFields = {
198
+ ...resolved.fields,
199
+ cost: costSchema,
200
+ rationale,
201
+ };
202
+ const answerContract = contract(`${q}-answer`, answerFields);
203
+ const recordFields = {
204
+ question: nonEmpty,
205
+ questionVersion: nonEmpty,
206
+ inputHash: nonEmpty,
207
+ seat: nonEmpty,
208
+ rung: rungIndex,
209
+ cost: costSchema,
210
+ };
211
+ for (const name of resolved.record) {
212
+ const decl = resolved.fields[name];
213
+ if (decl !== undefined) {
214
+ recordFields[name] = decl;
215
+ }
216
+ }
217
+ const recordContract = contract(`${q}-record`, recordFields);
218
+ const policyArgsContract = contract(`${q}-policy-args`, {
219
+ answers: t.array(recordContract),
220
+ params: def.policy.paramsSchema,
221
+ rung: rungIndex,
222
+ rungCount: t.int({ min: 1 }),
223
+ expect: t.union({
224
+ continue: {},
225
+ settle: { outcome: outcomeSchema },
226
+ }, { tag: "kind" }),
227
+ });
228
+ const policyCheck = check(`${q}.policy`, {
229
+ input: policyArgsContract,
230
+ evaluator: def.policy.evaluator,
231
+ });
232
+ const dataFields = fields({
233
+ question: def.questionVersion !== undefined ? t.literal(q) : nonEmpty,
234
+ questionVersion: def.questionVersion !== undefined ? t.literal(def.questionVersion) : nonEmpty,
235
+ outcomes: t.array(outcomeSchema, { nonEmpty: true }),
236
+ input: def.input,
237
+ subject: t.optional(nonEmpty),
238
+ inputHash: engine.digestOf(nonEmpty, "input", { allowFromParentEffect: false }),
239
+ answers: engine(t.array(recordContract), { default: [], allowFromParentEffect: false }),
240
+ lastRationale: engine(t.optional(rationale)),
241
+ settled: engine(t.optional(outcomeSchema)),
242
+ settledRungIndex: engine(t.optional(rungIndex)),
243
+ });
244
+ const statesList = [];
245
+ const stepsList = [];
246
+ const rungCount = def.rungs.length;
247
+ def.rungs.forEach((r, k) => {
248
+ const askingState = `asking-${String(k)}`;
249
+ const decidingState = `deciding-${String(k)}`;
250
+ statesList.push(askingState, decidingState);
251
+ const recordValue = {
252
+ question: dataFields.question,
253
+ questionVersion: dataFields.questionVersion,
254
+ inputHash: dataFields.inputHash,
255
+ seat: seat.id,
256
+ rung: literal(k),
257
+ cost: fromAnswer("cost"),
258
+ };
259
+ for (const recField of resolved.record) {
260
+ recordValue[recField] = fromAnswer(recField);
261
+ }
262
+ const rungRole = withRungLabels(r.role, [r.label]);
263
+ const appendRecordEffect = Object.freeze({
264
+ kind: "record-data-effect",
265
+ mode: "append",
266
+ targetField: dataFields.answers.name,
267
+ source: recordValue,
268
+ });
269
+ stepsList.push(step(`answer-${String(k)}`, {
270
+ from: askingState,
271
+ to: decidingState,
272
+ needs: [
273
+ answer(rungRole, answerContract, {
274
+ seatLabel: { key: "rung", values: [r.label] },
275
+ }),
276
+ ],
277
+ then: [appendRecordEffect, set(dataFields.lastRationale, fromAnswer("rationale"))],
278
+ }));
279
+ for (const o of resolved.outcomes) {
280
+ const extraEffects = def.outcomeEffects?.[o] ?? [];
281
+ stepsList.push(step(`settle-${String(k)}-${o}`, {
282
+ from: decidingState,
283
+ to: `settled-${o}`,
284
+ needs: [
285
+ policyCheck({
286
+ answers: dataFields.answers,
287
+ params: literal(def.policy.params),
288
+ rung: literal(k),
289
+ rungCount: literal(rungCount),
290
+ expect: literal({ kind: "settle", outcome: o }),
291
+ }),
292
+ ],
293
+ then: [
294
+ set(dataFields.settled, literal(o)),
295
+ set(dataFields.settledRungIndex, literal(k)),
296
+ ...extraEffects,
297
+ ],
298
+ }));
299
+ }
300
+ if (k < rungCount - 1) {
301
+ stepsList.push(step(`continue-${String(k)}`, {
302
+ from: decidingState,
303
+ to: `asking-${String(k + 1)}`,
304
+ needs: [
305
+ policyCheck({
306
+ answers: dataFields.answers,
307
+ params: literal(def.policy.params),
308
+ rung: literal(k),
309
+ rungCount: literal(rungCount),
310
+ expect: literal({ kind: "continue" }),
311
+ }),
312
+ ],
313
+ }));
314
+ }
315
+ });
316
+ const finals = [
317
+ `settled-${resolved.outcomes[0]}`,
318
+ ...resolved.outcomes.slice(1).map((o) => `settled-${o}`),
319
+ ];
320
+ const allStates = [...statesList, ...finals];
321
+ const [st0, st1, ...stRest] = allStates;
322
+ const [step0, ...stepRest] = stepsList;
323
+ if (st0 === undefined || st1 === undefined || step0 === undefined) {
324
+ failJudgment(q, "judgment requires at least one rung");
325
+ }
326
+ const built = protocol(q, {
327
+ states: [st0, st1, ...stRest],
328
+ start: "asking-0",
329
+ final: finals,
330
+ data: dataFields,
331
+ dataName: `${q}-data`,
332
+ openDataName: `${q}-open`,
333
+ steps: [step0, ...stepRest],
334
+ });
335
+ return Object.freeze({
336
+ question: q,
337
+ outcomes: resolved.outcomes,
338
+ protocol: built,
339
+ policyCheck,
340
+ rungLabels,
341
+ });
342
+ }
343
+ export function compileJudgmentFragment(def) {
344
+ const bundle = judgmentProtocol(def);
345
+ const roleMap = new Map();
346
+ for (const r of def.rungs) {
347
+ if (!roleMap.has(r.role.name)) {
348
+ const labels = bundle.rungLabels[r.role.name];
349
+ roleMap.set(r.role.name, labels !== undefined ? withRungLabels(r.role, labels) : r.role);
350
+ }
351
+ }
352
+ const rolesList = [...roleMap.values()];
353
+ const [firstRole] = rolesList;
354
+ if (firstRole === undefined) {
355
+ failJudgment(def.question, "judgment requires at least one rung");
356
+ }
357
+ const gov = defineClass("ops", { authorized: [firstRole] });
358
+ const spec = compile(installation({
359
+ name: `${def.question}-fragment`,
360
+ governedBy: gov,
361
+ roles: rolesList,
362
+ classes: [gov],
363
+ root: bundle.protocol,
364
+ protocols: [bundle.protocol],
365
+ roster: { seating: {}, caps: {}, grants: {} },
366
+ }));
367
+ const roles = {};
368
+ for (const [roleName, labels] of Object.entries(bundle.rungLabels)) {
369
+ const [first, ...rest] = labels;
370
+ roles[roleName] = { seatLabels: { rung: [first, ...rest] } };
371
+ }
372
+ return Object.freeze({
373
+ checks: spec.checks,
374
+ protocols: spec.protocols,
375
+ roles,
376
+ schemas: spec.schemas,
377
+ });
378
+ }
379
+ export function judgmentOverrideProtocol(def) {
380
+ if (def.rungs.length < 2)
381
+ return undefined;
382
+ assertIdentifier(def.question, "question");
383
+ const protoName = `${def.question}-override`;
384
+ const nonEmpty = t.string({ nonEmpty: true });
385
+ const optionSchema = t.enum(def.outcomes);
386
+ const rationale = def.rationale ?? nonEmpty;
387
+ const cmpNum = def.compareNumberCheck ?? compareNumber;
388
+ const overrideAnswer = contract(`${protoName}-answer`, {
389
+ option: t.enum(def.outcomes, {
390
+ description: "Option id that replaces the settled option",
391
+ audience: "agent",
392
+ }),
393
+ rationale,
394
+ });
395
+ const dataFields = fields({
396
+ judgment: nonEmpty,
397
+ settled: engine.fromPredecessor(optionSchema, "settled"),
398
+ settledRungIndex: engine.fromPredecessor(t.int({ min: 0 }), "settledRungIndex"),
399
+ option: engine(t.optional(optionSchema)),
400
+ rationale: engine(t.optional(rationale)),
401
+ });
402
+ const belowCount = def.rungs.length - 1;
403
+ const overridingStates = [];
404
+ const stepsList = [];
405
+ for (let k = 0; k < belowCount; k += 1) {
406
+ const stateName = `overriding-${String(k)}`;
407
+ overridingStates.push(stateName);
408
+ stepsList.push(step(`route-${String(k)}`, {
409
+ from: "routing",
410
+ to: stateName,
411
+ needs: [cmpNum({ left: dataFields.settledRungIndex, op: "eq", right: k })],
412
+ }));
413
+ }
414
+ for (let k = 0; k < belowCount; k += 1) {
415
+ const higher = new Map();
416
+ for (const r of def.rungs.slice(k + 1)) {
417
+ const existing = higher.get(r.role.name);
418
+ if (existing !== undefined) {
419
+ existing.labels.push(r.label);
420
+ }
421
+ else {
422
+ higher.set(r.role.name, { role: r.role, labels: [r.label] });
423
+ }
424
+ }
425
+ for (const [roleName, entry] of higher) {
426
+ const [l0, ...lRest] = entry.labels;
427
+ if (l0 === undefined)
428
+ continue;
429
+ const rungRole = withRungLabels(entry.role, [l0, ...lRest]);
430
+ stepsList.push(step(`override-${String(k)}-${roleName}`, {
431
+ from: `overriding-${String(k)}`,
432
+ to: "overridden",
433
+ needs: [
434
+ answer(rungRole, overrideAnswer, {
435
+ seatLabel: { key: "rung", values: [l0, ...lRest] },
436
+ }),
437
+ ],
438
+ then: [
439
+ set(dataFields.option, fromAnswer("option")),
440
+ set(dataFields.rationale, fromAnswer("rationale")),
441
+ ],
442
+ }));
443
+ }
444
+ }
445
+ const [step0, ...stepRest] = stepsList;
446
+ const [ov0, ...ovRest] = overridingStates;
447
+ if (step0 === undefined || ov0 === undefined)
448
+ return undefined;
449
+ return protocol(protoName, {
450
+ states: ["routing", ov0, ...ovRest, "overridden"],
451
+ start: "routing",
452
+ final: ["overridden"],
453
+ data: dataFields,
454
+ dataName: `${protoName}-data`,
455
+ openDataName: `${protoName}-open`,
456
+ predecessor: {
457
+ field: dataFields.judgment,
458
+ protocol: { kind: "protocol-ref", name: def.question },
459
+ },
460
+ steps: [step0, ...stepRest],
461
+ });
462
+ }
@@ -0,0 +1,23 @@
1
+ import { type Observer } from "../observer.js";
2
+ /** One command: a granted executable, its arguments, and a working directory inside the checkout. */
3
+ export interface CommandEntry {
4
+ readonly executable: string;
5
+ readonly args?: readonly string[];
6
+ readonly cwd?: string;
7
+ }
8
+ /** A command, or a table of commands chosen by the check's `repo` or `project`. */
9
+ export type CommandParams = CommandEntry | {
10
+ readonly byRepo: Readonly<Record<string, CommandEntry>>;
11
+ readonly repo?: string;
12
+ readonly cwd?: string;
13
+ } | {
14
+ readonly byProject: Readonly<Record<string, CommandEntry>>;
15
+ readonly project?: string;
16
+ readonly cwd?: string;
17
+ };
18
+ export declare const COMMAND_OBSERVER_ID = "telar.std/observe/command/1";
19
+ /**
20
+ * std's command observer, written on the public SDK like any installation's observer.
21
+ * It runs one granted executable with `{ check, args }` on stdin and reads `{ ok, evidence? }` from stdout.
22
+ */
23
+ export declare const commandObserver: Observer<typeof COMMAND_OBSERVER_ID, CommandParams>;
@@ -0,0 +1,151 @@
1
+ import { defineObserver, ObserverError } from "../observer.js";
2
+ export const COMMAND_OBSERVER_ID = "telar.std/observe/command/1";
3
+ function isRec(value) {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+ function parseEntry(raw, path) {
7
+ if (!isRec(raw))
8
+ return { issues: [{ path, message: "a command entry must be an object" }] };
9
+ const { executable, args, cwd } = raw;
10
+ if (typeof executable !== "string" || executable.length === 0) {
11
+ return {
12
+ issues: [{ path: [...path, "executable"], message: "executable must be a non-empty string" }],
13
+ };
14
+ }
15
+ const list = Array.isArray(args) ? args.filter((a) => typeof a === "string") : [];
16
+ if (args !== undefined && (!Array.isArray(args) || list.length !== args.length)) {
17
+ return { issues: [{ path: [...path, "args"], message: "args must be a list of strings" }] };
18
+ }
19
+ if (cwd !== undefined && typeof cwd !== "string") {
20
+ return { issues: [{ path: [...path, "cwd"], message: "cwd must be a string" }] };
21
+ }
22
+ return {
23
+ value: {
24
+ executable,
25
+ ...(args === undefined ? {} : { args: list }),
26
+ ...(typeof cwd === "string" ? { cwd } : {}),
27
+ },
28
+ };
29
+ }
30
+ function parseTable(raw, key) {
31
+ if (!isRec(raw))
32
+ return { issues: [{ path: [key], message: `${key} must be an object of command entries` }] };
33
+ const table = {};
34
+ for (const [name, entry] of Object.entries(raw)) {
35
+ const parsed = parseEntry(entry, [key, name]);
36
+ if ("issues" in parsed)
37
+ return parsed;
38
+ table[name] = parsed.value;
39
+ }
40
+ return { value: table };
41
+ }
42
+ function optionalString(raw, key) {
43
+ const value = raw[key];
44
+ if (value === undefined)
45
+ return { value: {} };
46
+ return typeof value === "string"
47
+ ? { value: { [key]: value } }
48
+ : { issues: [{ path: [key], message: `${key} must be a string` }] };
49
+ }
50
+ function parseParams(raw) {
51
+ if (!isRec(raw))
52
+ return { issues: [{ path: [], message: "params must be an object" }] };
53
+ const cwd = optionalString(raw, "cwd");
54
+ if ("issues" in cwd)
55
+ return cwd;
56
+ if ("byRepo" in raw) {
57
+ const table = parseTable(raw["byRepo"], "byRepo");
58
+ const repo = optionalString(raw, "repo");
59
+ if ("issues" in table)
60
+ return table;
61
+ if ("issues" in repo)
62
+ return repo;
63
+ return { value: { byRepo: table.value, ...repo.value, ...cwd.value } };
64
+ }
65
+ if ("byProject" in raw) {
66
+ const table = parseTable(raw["byProject"], "byProject");
67
+ const project = optionalString(raw, "project");
68
+ if ("issues" in table)
69
+ return table;
70
+ if ("issues" in project)
71
+ return project;
72
+ return { value: { byProject: table.value, ...project.value, ...cwd.value } };
73
+ }
74
+ return parseEntry(raw, []);
75
+ }
76
+ const params = {
77
+ "~standard": { version: 1, vendor: "telar.std", validate: parseParams },
78
+ };
79
+ function lookup(table, key, given, args) {
80
+ const name = given ?? args[key];
81
+ const tableKey = key === "repo" ? "byRepo" : "byProject";
82
+ if (typeof name !== "string") {
83
+ throw new ObserverError("INVALID_OBSERVER_PARAMS", `missing string "${key}" for ${tableKey} lookup`);
84
+ }
85
+ const entry = table[name];
86
+ if (entry === undefined) {
87
+ throw new ObserverError("INVALID_OBSERVER_PARAMS", `no observer entry in ${tableKey} for "${name}"`);
88
+ }
89
+ return entry;
90
+ }
91
+ function selectEntry(p, args) {
92
+ if ("byRepo" in p) {
93
+ const entry = lookup(p.byRepo, "repo", p.repo, args);
94
+ return entry.cwd === undefined && p.cwd !== undefined ? { ...entry, cwd: p.cwd } : entry;
95
+ }
96
+ if ("byProject" in p) {
97
+ const entry = lookup(p.byProject, "project", p.project, args);
98
+ return entry.cwd === undefined && p.cwd !== undefined ? { ...entry, cwd: p.cwd } : entry;
99
+ }
100
+ return p;
101
+ }
102
+ /**
103
+ * Reads `{ ok, evidence? }` from stdout. Empty stdout, `ok: null`, and a reply that is not an object
104
+ * (such as `[1]`) read as "not yet", as the Rust observer did. Evidence that is present must be an object.
105
+ */
106
+ function parseReply(stdout) {
107
+ const text = stdout.trim();
108
+ if (text.length === 0)
109
+ return { ok: null };
110
+ let reply;
111
+ try {
112
+ reply = JSON.parse(text);
113
+ }
114
+ catch {
115
+ throw new ObserverError("INVALID_OBSERVER_RESPONSE", "invalid observer JSON");
116
+ }
117
+ const ok = isRec(reply) ? reply["ok"] : undefined;
118
+ if (ok === null || ok === undefined)
119
+ return { ok: null };
120
+ if (typeof ok !== "boolean") {
121
+ throw new ObserverError("INVALID_OBSERVER_RESPONSE", 'observer reply "ok" must be boolean or null');
122
+ }
123
+ const evidence = isRec(reply) ? reply["evidence"] : undefined;
124
+ if (evidence === undefined || evidence === null)
125
+ return { ok };
126
+ if (!isRec(evidence)) {
127
+ throw new ObserverError("INVALID_OBSERVER_RESPONSE", 'observer reply "evidence" must be an object');
128
+ }
129
+ return { ok, evidence };
130
+ }
131
+ /**
132
+ * std's command observer, written on the public SDK like any installation's observer.
133
+ * It runs one granted executable with `{ check, args }` on stdin and reads `{ ok, evidence? }` from stdout.
134
+ */
135
+ export const commandObserver = defineObserver({
136
+ id: COMMAND_OBSERVER_ID,
137
+ params,
138
+ observe: ({ check, args, params: p }, powers) => {
139
+ const entry = selectEntry(p, args);
140
+ const out = powers.process({
141
+ executable: entry.executable,
142
+ args: entry.args ?? [],
143
+ stdin: JSON.stringify({ check, args }),
144
+ ...(entry.cwd !== undefined ? { cwd: entry.cwd } : {}),
145
+ });
146
+ if (out.exitCode !== 0) {
147
+ throw new ObserverError("OBSERVER_COMMAND_FAILED", `observer command exited ${String(out.exitCode)}: ${out.stderr.trim()}`);
148
+ }
149
+ return parseReply(out.stdout);
150
+ },
151
+ });
@@ -0,0 +1,24 @@
1
+ import { type Observer } from "../observer.js";
2
+ /** One GitHub repo check-runs configuration. */
3
+ export interface GithubChecksEntry {
4
+ readonly owner: string;
5
+ readonly name: string;
6
+ readonly required: readonly string[];
7
+ readonly head?: string;
8
+ readonly apiScheme?: "http" | "https";
9
+ readonly apiAuthority?: string;
10
+ }
11
+ /** Direct GitHub repo config or a table keyed by the check's `repo`. */
12
+ export type GithubChecksParams = GithubChecksEntry | {
13
+ readonly byRepo: Readonly<Record<string, GithubChecksEntry>>;
14
+ readonly repo?: string;
15
+ readonly head?: string;
16
+ readonly apiScheme?: "http" | "https";
17
+ readonly apiAuthority?: string;
18
+ };
19
+ export declare const GITHUB_CHECKS_OBSERVER_ID = "telar.std/observe/github-checks/1";
20
+ /**
21
+ * std's github-checks observer, written on the public SDK over `powers.network`.
22
+ * Reads GitHub check-runs and commit statuses for a commit SHA and evaluates `required`.
23
+ */
24
+ export declare const githubChecksObserver: Observer<typeof GITHUB_CHECKS_OBSERVER_ID, GithubChecksParams>;