@supa-media/tex-contract 0.0.0-stage → 0.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +11 -2
- package/package.json +16 -4
- package/texContract/aboutLines.cjs +117 -0
- package/texContract/aboutLines.d.cts +14 -0
- package/texContract/aboutNoteLimits.cjs +41 -0
- package/texContract/aboutNoteLimits.d.cts +5 -0
- package/texContract/actionManual.cjs +104 -0
- package/texContract/activityHint.cjs +40 -0
- package/texContract/activityHint.d.cts +4 -0
- package/texContract/asks.cjs +16 -0
- package/texContract/asks.d.cts +6 -0
- package/texContract/asksToFile.cjs +20 -0
- package/texContract/asksToFile.d.cts +2 -0
- package/texContract/attention.cjs +138 -0
- package/texContract/attention.d.cts +20 -0
- package/texContract/browserHandback.cjs +13 -0
- package/texContract/browserHandback.d.cts +3 -0
- package/texContract/browserOwner.cjs +31 -0
- package/texContract/browserOwner.d.cts +2 -0
- package/texContract/bytes.cjs +12 -0
- package/texContract/chatHistoryPath.cjs +38 -0
- package/texContract/chatHistoryPath.d.cts +5 -0
- package/texContract/chatLedger.cjs +91 -0
- package/texContract/chatLedger.d.cts +21 -0
- package/texContract/computerTool.cjs +102 -0
- package/texContract/computerTool.d.cts +16 -0
- package/texContract/consentYes.cjs +22 -0
- package/texContract/consentYes.d.cts +5 -0
- package/texContract/contextGateway.cjs +52 -0
- package/texContract/contextGateway.d.cts +19 -0
- package/texContract/deskEligible.cjs +20 -0
- package/texContract/deskEligible.d.cts +3 -0
- package/texContract/downloads.cjs +129 -0
- package/texContract/downloads.d.cts +15 -0
- package/texContract/egressLedger.cjs +114 -0
- package/texContract/egressLedger.d.cts +14 -0
- package/texContract/emailRead.cjs +38 -0
- package/texContract/emailRead.d.cts +5 -0
- package/texContract/eventWords.cjs +35 -0
- package/texContract/eventWords.d.cts +4 -0
- package/texContract/fileParts.cjs +43 -0
- package/texContract/fileParts.d.cts +6 -0
- package/texContract/fileTables.cjs +243 -0
- package/texContract/fileWords.cjs +169 -0
- package/texContract/folded.cjs +16 -0
- package/texContract/folded.d.cts +3 -0
- package/texContract/googleAiAccess.cjs +12 -0
- package/texContract/googleAiAccess.d.cts +2 -0
- package/texContract/graphWires.cjs +18 -0
- package/texContract/graphWires.d.cts +5 -0
- package/texContract/groupSession.cjs +28 -0
- package/texContract/groupSession.d.cts +7 -0
- package/texContract/guestNames.cjs +136 -0
- package/texContract/guestNames.d.cts +35 -0
- package/texContract/heard.cjs +19 -0
- package/texContract/heard.d.cts +4 -0
- package/texContract/heldOffer.cjs +57 -0
- package/texContract/heldOffer.d.cts +8 -0
- package/texContract/helperCallers.cjs +29 -0
- package/texContract/helperCallers.d.cts +4 -0
- package/texContract/identity.cjs +179 -0
- package/texContract/identity.d.cts +8 -0
- package/texContract/jobLogEntries.cjs +93 -0
- package/texContract/jobLogEntries.d.cts +12 -0
- package/texContract/judgedActions.cjs +20 -0
- package/texContract/judgedActions.d.cts +4 -0
- package/texContract/labSandboxGate.cjs +63 -0
- package/texContract/labSandboxGate.d.cts +9 -0
- package/texContract/ledgerReadChars.cjs +4 -0
- package/texContract/ledgerReadChars.d.cts +3 -0
- package/texContract/mailCheck.cjs +90 -0
- package/texContract/mailCheck.d.cts +12 -0
- package/texContract/mailEntries.cjs +64 -0
- package/texContract/mailEntries.d.cts +13 -0
- package/texContract/mailHealth.cjs +60 -0
- package/texContract/mailHealth.d.cts +10 -0
- package/texContract/notePath.cjs +99 -0
- package/texContract/notePath.d.cts +4 -0
- package/texContract/noteRunFacts.cjs +136 -0
- package/texContract/noteRunFacts.d.cts +32 -0
- package/texContract/objectEtag.cjs +84 -0
- package/texContract/objectEtag.d.cts +4 -0
- package/texContract/objectPlace.cjs +32 -0
- package/texContract/objectPlace.d.cts +5 -0
- package/texContract/pageJobs.cjs +226 -0
- package/texContract/pageJobs.d.cts +13 -0
- package/texContract/pdfLinks.cjs +135 -0
- package/texContract/pdfLinks.d.cts +4 -0
- package/texContract/personHub.cjs +38 -0
- package/texContract/personHub.d.cts +5 -0
- package/texContract/personNameText.cjs +18 -0
- package/texContract/personNameText.d.cts +3 -0
- package/texContract/pinnedContext.cjs +12 -0
- package/texContract/pinnedContext.d.cts +3 -0
- package/texContract/quietHoursWindow.cjs +36 -0
- package/texContract/quietHoursWindow.d.cts +3 -0
- package/texContract/scopeClamp.cjs +117 -0
- package/texContract/scopeClamp.d.cts +5 -0
- package/texContract/scopes.cjs +29 -0
- package/texContract/scopes.d.cts +7 -0
- package/texContract/searchSettings.cjs +54 -0
- package/texContract/searchSettings.d.cts +6 -0
- package/texContract/settingHabits.cjs +87 -0
- package/texContract/settingHabits.d.cts +20 -0
- package/texContract/settingsNotes.cjs +217 -0
- package/texContract/settingsNotes.d.cts +26 -0
- package/texContract/shownEmail.cjs +181 -0
- package/texContract/texClients.cjs +53 -0
- package/texContract/texClients.d.cts +12 -0
- package/texContract/texGraph.cjs +593 -0
- package/texContract/texGraph.d.cts +55 -0
- package/texContract/texKeys.cjs +100 -0
- package/texContract/texKeys.d.cts +13 -0
- package/texContract/texOwnSources.cjs +9 -0
- package/texContract/texOwnSources.d.cts +3 -0
- package/texContract/texStoreNames.cjs +26 -0
- package/texContract/texStoreNames.d.cts +12 -0
- package/texContract/texStoreWire.cjs +306 -0
- package/texContract/texStoreWire.d.cts +32 -0
- package/texContract/threadsFold.cjs +75 -0
- package/texContract/threadsFold.d.cts +22 -0
- package/texContract/toolActions.cjs +253 -0
- package/texContract/toolCatalog.cjs +49 -0
- package/texContract/toolCatalog.generated.json +90 -0
- package/texContract/toolContract.cjs +52 -0
- package/texContract/toolContract.d.cts +12 -0
- package/texContract/toolShapes.cjs +14 -0
- package/texContract/transcription.cjs +101 -0
- package/texContract/transcription.d.cts +3 -0
- package/texContract/treeJobs.cjs +31 -0
- package/texContract/treeJobs.d.cts +3 -0
- package/texContract/turnSession.cjs +90 -0
- package/texContract/turnSession.d.cts +19 -0
- package/texContract/turnWords.cjs +90 -0
- package/texContract/turnWords.d.cts +9 -0
- package/texContract/uploadImages.cjs +131 -0
- package/texContract/uploadImages.d.cts +13 -0
- package/texContract/v2Names.cjs +41 -0
- package/texContract/v2SearchFetch.cjs +316 -0
- package/texContract/v2Translate.cjs +123 -0
- package/texContract/vaultTools.cjs +112 -0
- package/texContract/vaultTools.d.cts +15 -0
- package/texContract/yesWords.cjs +91 -0
- package/texShared/argumentCoercion.cjs +93 -0
- package/texShared/cellComments.cjs +122 -0
- package/texShared/cellComments.d.cts +21 -0
- package/texShared/comments.cjs +586 -0
- package/texShared/comments.d.cts +115 -0
- package/texShared/contentTypes.cjs +85 -0
- package/texShared/fileKinds.cjs +123 -0
- package/texShared/flags.cjs +124 -0
- package/texShared/flags.d.cts +21 -0
- package/texShared/folderJobInfo.cjs +301 -0
- package/texShared/folderJobInfo.d.cts +40 -0
- package/texShared/folderRoles.cjs +512 -0
- package/texShared/folderRoles.d.cts +73 -0
- package/texShared/githubOidc.ts +98 -0
- package/texShared/groupRunQuestions.cjs +98 -0
- package/texShared/groupRunQuestions.d.cts +4 -0
- package/texShared/inboxFolders.cjs +49 -0
- package/texShared/inboxFolders.d.cts +5 -0
- package/texShared/ink/drawing.cjs +474 -0
- package/texShared/ink/texFigure.cjs +252 -0
- package/texShared/ink/texFigure.d.cts +36 -0
- package/texShared/ink/texPoses.cjs +180 -0
- package/texShared/ink/texPoses.d.cts +20 -0
- package/texShared/jobPartEnd.cjs +133 -0
- package/texShared/jobPartEnd.d.cts +13 -0
- package/texShared/jobResume.cjs +31 -0
- package/texShared/jobResume.d.cts +5 -0
- package/texShared/jobSplit.cjs +90 -0
- package/texShared/jobSplit.d.cts +6 -0
- package/texShared/jobStart.cjs +56 -0
- package/texShared/jobStart.d.cts +9 -0
- package/texShared/mail.cjs +400 -0
- package/texShared/mail.d.cts +56 -0
- package/texShared/messageAnchors.cjs +38 -0
- package/texShared/models/aiKeys.cjs +137 -0
- package/texShared/models/aiKeys.d.cts +42 -0
- package/texShared/models/aiKeys.json +56 -0
- package/texShared/models/creditRest.cjs +269 -0
- package/texShared/models/promptBudget.cjs +295 -0
- package/texShared/models/promptSections.cjs +29 -0
- package/texShared/noteAppLink.cjs +23 -0
- package/texShared/notePreview.cjs +219 -0
- package/texShared/notePreview.d.cts +21 -0
- package/texShared/pages/blocks.cjs +215 -0
- package/texShared/pages/cover.cjs +164 -0
- package/texShared/pages/css.cjs +181 -0
- package/texShared/pages/cssBlocks.cjs +264 -0
- package/texShared/pages/draw.cjs +212 -0
- package/texShared/pages/drawRich.cjs +232 -0
- package/texShared/pages/html.cjs +168 -0
- package/texShared/pages/inline.cjs +251 -0
- package/texShared/pages/layout.cjs +76 -0
- package/texShared/pages/parse.cjs +418 -0
- package/texShared/pages/render.cjs +200 -0
- package/texShared/pages/skill.cjs +147 -0
- package/texShared/pages/skill.d.cts +5 -0
- package/texShared/pages/templates.cjs +336 -0
- package/texShared/r2Store.cjs +163 -0
- package/texShared/remoteImage.cjs +177 -0
- package/texShared/routines.cjs +656 -0
- package/texShared/routines.d.cts +86 -0
- package/texShared/servedListing.cjs +250 -0
- package/texShared/servedListing.d.cts +17 -0
- package/texShared/sheetCsv.cjs +566 -0
- package/texShared/sheetCsv.d.cts +91 -0
- package/texShared/storageLayout.cjs +88 -0
- package/texShared/storeKeys.cjs +144 -0
- package/texShared/toolArguments.cjs +323 -0
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TEX RUNS ITS CONFIG'S GRAPH (Dev2, 2026-11-14: "it's fine for node to be code, but it's not fine for the connections
|
|
3
|
+
* between node to be code. They should be predefined").
|
|
4
|
+
*
|
|
5
|
+
* `texConfig.json` names every step (a node) and every wire between them (an edge). This file is the one interpreter of
|
|
6
|
+
* the wires, shared by the gateway (where every node runs, Dev2 2026-11-14) and the Lab, so what runs, in what order, what waits for what and
|
|
7
|
+
* what runs in the background is read from the config and never written as code. A node is code: one function, given its input
|
|
8
|
+
* and a handle to only the nodes its wires reach, that returns its output.
|
|
9
|
+
*
|
|
10
|
+
* Wires, by `mode`:
|
|
11
|
+
* wait the target runs after the source, given its output. A target several wires feed runs once, after every
|
|
12
|
+
* source that will feed it has run, on their outputs merged in wire order.
|
|
13
|
+
* background the target runs after the source and nothing waits for it (the `background` option).
|
|
14
|
+
* uses the source may call the target, through `io.use[target]`, any number of times. A node can call only what
|
|
15
|
+
* its `uses` wires reach: anything else throws.
|
|
16
|
+
* loop the source may send work back to the target, through `io.back[target]`, at most the wire's `rounds` times
|
|
17
|
+
* (the target's `rounds` when the wire names none). The target runs, then the `wait` path from it forward
|
|
18
|
+
* to the source, and the call returns what the last node before the source gave.
|
|
19
|
+
* job the source may start the target as a background job, through `io.job[target]`.
|
|
20
|
+
* provisional ("Provisional run") the target does not wait for the source to start: it starts once its other
|
|
21
|
+
* inputs allow, or at the run's start when every wire into it is `provisional`. The source's output is the
|
|
22
|
+
* target's verdict: tags matching the wire's `stop:<tag>` entries stop the running target, `restart:<tag>` stops
|
|
23
|
+
* and reruns it, and anything else says go. Until every `provisional` source into it has said go, the target
|
|
24
|
+
* may do only what the wire's `allow` lets it: "read" (reads only) or "revertible" (the default: reads, and writes
|
|
25
|
+
* that can be undone); anything that cannot be taken back always waits for the go. `unless` names the bursts
|
|
26
|
+
* that do not start it early (`firstLook`, `sms`, `unpaired`; `provisionalHeld`): any one of them on any
|
|
27
|
+
* provisional wire holds the run, and the step waits for those sources instead. The config check requires
|
|
28
|
+
* `firstLook` and `sms` on every provisional wire (`texConfigSchema.cjs`); this runner still reads a wire
|
|
29
|
+
* as written. One target per config; read
|
|
30
|
+
* by intake through `provisionalWiring`, never fired by `run` (Dev2, 2026-11-17).
|
|
31
|
+
* generator ("Starts a new run") the source starts a new run of its own that begins at the target, an input node
|
|
32
|
+
* (`kind: "input"`), in this chat or another; nothing in the current run waits for it. A background job, a
|
|
33
|
+
* routine, an ask sent to another chat: each output re-enters Tex as a new input (Dev2, 2026-11-16, the
|
|
34
|
+
* generators model). `when` tags work as on `wait` ("ask", "answer"). Never fired by `run`, never part of
|
|
35
|
+
* `orderFrom`, and ignored by the cycle check, so a generator may point back up the graph. A node starts one
|
|
36
|
+
* through `io.start[target]`, handed to the host's `start` option; the wire's `rounds` cap the chain.
|
|
37
|
+
* A `wait` or `background` wire whose `when` names "failed" catches its source's failure: the source's output is then
|
|
38
|
+
* `{ when: ["failed"], failed: { name, message } }` and the run goes on down that wire instead of throwing.
|
|
39
|
+
* `run`'s `progress` option (`{ get(nodeId), put(nodeId, output) }`, the host's durable store for one run) skips every
|
|
40
|
+
* node it already holds an output for and keeps each new one, so a run resumed after a crash or deploy picks up there.
|
|
41
|
+
* `when` on a wire: `["*"]`, or tags the source's output must carry (`output.when`, or `output.to` as one tag) for a
|
|
42
|
+
* `wait` or `background` wire to fire. A node that is off (`on: false`) never runs, and its wires never fire.
|
|
43
|
+
*
|
|
44
|
+
* A node's `inSchema` and `outSchema` are its contract, checked strictly (Dev2, 2026-11-14: "fail"): every field named
|
|
45
|
+
* must be there with its type unless marked `optional`, and no field may be there that is not named (but `when`, the
|
|
46
|
+
* output's routing tags, and `log`, the node's own detail for its row: both logged, neither carried on). A mismatch fails the node with a `GraphError` naming the field. Types: text, yesno, score
|
|
47
|
+
* (a number, in its `options` range "a-b" when given), number, choice (a string; one of its `options` when they are a
|
|
48
|
+
* list "a, b, c" of single words), ids (a list of strings), list, object, any.
|
|
49
|
+
*
|
|
50
|
+
* Every node run is logged by the runner (`log`): the node, its input and output (functions and cycles dropped, long
|
|
51
|
+
* values cut), how long it took, and whether it went. So no node logs by hand, and none can run unlogged.
|
|
52
|
+
*
|
|
53
|
+
* What every node shares (the store, the session, the turn so far) is `ctx`, never an input: inputs and outputs are the
|
|
54
|
+
* data the wires carry, kept small enough to log.
|
|
55
|
+
*/
|
|
56
|
+
"use strict";
|
|
57
|
+
|
|
58
|
+
// The wire modes and a provisional run's allows (reads only, or reads and writes that can be undone, the default) are
|
|
59
|
+
// the schema's (`packages/tex/src/texConfigSchema.cjs`), shared from `graphWires.cjs`.
|
|
60
|
+
const { MODES, ALLOW, START_FACTS } = require("./graphWires.cjs");
|
|
61
|
+
const MAX_LOG_CHARS = 3_500;
|
|
62
|
+
|
|
63
|
+
class GraphError extends Error {
|
|
64
|
+
constructor(message) {
|
|
65
|
+
super(`texGraph: ${message}`);
|
|
66
|
+
this.name = "GraphError";
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
71
|
+
|
|
72
|
+
/** The tags a node's output carries for its wires' `when`. */
|
|
73
|
+
function tagsOf(output) {
|
|
74
|
+
if (!plain(output)) return [];
|
|
75
|
+
const tags = Array.isArray(output.when) ? output.when.filter((t) => typeof t === "string") : [];
|
|
76
|
+
if (typeof output.to === "string") tags.push(output.to);
|
|
77
|
+
return tags;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Whether a wire fires on its source's output. */
|
|
81
|
+
function fires(edge, output) {
|
|
82
|
+
const when = Array.isArray(edge.when) && edge.when.length ? edge.when : ["*"];
|
|
83
|
+
if (when.includes("*")) return true;
|
|
84
|
+
const tags = tagsOf(output);
|
|
85
|
+
return when.some((t) => tags.includes(t));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A value as the log keeps it: the fields its shape names (all, with none named), functions and cycles dropped, long ones cut. */
|
|
89
|
+
function shaped(value, schema) {
|
|
90
|
+
let v = value;
|
|
91
|
+
if (plain(value) && Array.isArray(schema) && schema.length) {
|
|
92
|
+
v = {};
|
|
93
|
+
for (const f of schema) if (f && typeof f.name === "string" && value[f.name] !== undefined) v[f.name] = value[f.name];
|
|
94
|
+
}
|
|
95
|
+
const seen = new WeakSet();
|
|
96
|
+
let text;
|
|
97
|
+
try {
|
|
98
|
+
text = JSON.stringify(v, (_k, x) => {
|
|
99
|
+
if (typeof x === "function" || typeof x === "symbol" || typeof x === "bigint") return undefined;
|
|
100
|
+
if (x !== null && typeof x === "object") {
|
|
101
|
+
if (seen.has(x)) return undefined;
|
|
102
|
+
seen.add(x);
|
|
103
|
+
}
|
|
104
|
+
return x;
|
|
105
|
+
});
|
|
106
|
+
} catch {
|
|
107
|
+
return { unloggable: true };
|
|
108
|
+
}
|
|
109
|
+
if (text === undefined) return null;
|
|
110
|
+
return text.length > MAX_LOG_CHARS ? { cut: text.length, start: text.slice(0, 600) } : JSON.parse(text);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const WORD_LIST = /^[\w-]+(?:\s*,\s*[\w-]+)+$/;
|
|
114
|
+
|
|
115
|
+
/** Why a value does not match a field's type, or null when it does. */
|
|
116
|
+
function typeProblem(v, field) {
|
|
117
|
+
const t = field.type ?? "any";
|
|
118
|
+
const opts = typeof field.options === "string" ? field.options.trim() : "";
|
|
119
|
+
switch (t) {
|
|
120
|
+
case "any":
|
|
121
|
+
return null;
|
|
122
|
+
case "text":
|
|
123
|
+
return typeof v === "string" ? null : "is not text";
|
|
124
|
+
case "yesno":
|
|
125
|
+
return typeof v === "boolean" ? null : "is not yes or no";
|
|
126
|
+
case "number":
|
|
127
|
+
return typeof v === "number" && Number.isFinite(v) ? null : "is not a number";
|
|
128
|
+
case "score": {
|
|
129
|
+
if (!(typeof v === "number" && Number.isFinite(v))) return "is not a score";
|
|
130
|
+
const range = /^(-?\d+(?:\.\d+)?)\s*-\s*(-?\d+(?:\.\d+)?)$/.exec(opts);
|
|
131
|
+
return range && (v < Number(range[1]) || v > Number(range[2])) ? `is ${v}, outside ${opts}` : null;
|
|
132
|
+
}
|
|
133
|
+
case "choice": {
|
|
134
|
+
if (typeof v !== "string") return "is not one of its choices";
|
|
135
|
+
if (!WORD_LIST.test(opts)) return null;
|
|
136
|
+
const allowed = opts.split(",").map((o) => o.trim());
|
|
137
|
+
return allowed.includes(v) ? null : `is "${v}", not one of ${allowed.join(", ")}`;
|
|
138
|
+
}
|
|
139
|
+
case "ids":
|
|
140
|
+
return Array.isArray(v) && v.every((x) => typeof x === "string") ? null : "is not a list of ids";
|
|
141
|
+
case "list":
|
|
142
|
+
return Array.isArray(v) ? null : "is not a list";
|
|
143
|
+
case "object":
|
|
144
|
+
return plain(v) ? null : "is not an object";
|
|
145
|
+
default:
|
|
146
|
+
return `has a type the runner does not know ("${t}")`;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* What a wire hands on: the output without its `when`, which picked the wires and is not the next node's input (a node's
|
|
152
|
+
* input schema never names it, so a tagged output fed on as it is would fail the node it feeds), and without its `log`,
|
|
153
|
+
* the node's own detail, kept in its row only (the Door's parts handed to the Front door failed it, 2026-11-16).
|
|
154
|
+
*/
|
|
155
|
+
function carried(output) {
|
|
156
|
+
if (!plain(output) || !("when" in output || "log" in output)) return output;
|
|
157
|
+
const { when, log, ...rest } = output;
|
|
158
|
+
return rest;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Check a node's input or output against its schema (`which`: "input" or "output"). Throws a `GraphError` naming the
|
|
163
|
+
* node and the field; a node with no schema for it is not checked.
|
|
164
|
+
*/
|
|
165
|
+
function checkShape(id, which, value, schema) {
|
|
166
|
+
if (!Array.isArray(schema) || schema.length === 0) return;
|
|
167
|
+
if (!plain(value)) throw new GraphError(`"${id}" ${which} is not an object with the fields its schema names`);
|
|
168
|
+
const named = new Set(schema.map((f) => f.name));
|
|
169
|
+
for (const f of schema) {
|
|
170
|
+
if (value[f.name] === undefined || value[f.name] === null) {
|
|
171
|
+
if (f.optional === true) continue;
|
|
172
|
+
throw new GraphError(`"${id}" ${which} has no "${f.name}"`);
|
|
173
|
+
}
|
|
174
|
+
const why = typeProblem(value[f.name], f);
|
|
175
|
+
if (why) throw new GraphError(`"${id}" ${which} "${f.name}" ${why}`);
|
|
176
|
+
}
|
|
177
|
+
for (const k of Object.keys(value)) if (!named.has(k) && !(which === "output" && (k === "when" || k === "log")) && value[k] !== undefined) throw new GraphError(`"${id}" ${which} has "${k}", which its schema does not name`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Check a config's graph: every wire joins two nodes and has a known mode, and the `wait` wires have no cycle (a turn
|
|
182
|
+
* always ends). Returns the list of problems, empty when it is sound.
|
|
183
|
+
*/
|
|
184
|
+
function problemsOf(config) {
|
|
185
|
+
const problems = [];
|
|
186
|
+
const nodes = Array.isArray(config?.nodes) ? config.nodes : [];
|
|
187
|
+
const ids = new Set(nodes.map((n) => n.id));
|
|
188
|
+
if (ids.size !== nodes.length) problems.push("node ids are not unique");
|
|
189
|
+
for (const e of config?.edges ?? []) {
|
|
190
|
+
if (!ids.has(e.from) || !ids.has(e.to)) problems.push(`wire ${e.from} -> ${e.to} joins a node that is not there`);
|
|
191
|
+
if (!MODES.includes(e.mode)) problems.push(`wire ${e.from} -> ${e.to} has mode "${e.mode}"`);
|
|
192
|
+
if (e.mode === "provisional") for (const t of Array.isArray(e.when) ? e.when : [])
|
|
193
|
+
if (t !== "*" && !/^(stop|restart):[\w-]+$/.test(String(t))) problems.push(`provisional wire ${e.from} -> ${e.to} has when "${t}": only "*", "stop:<tag>" or "restart:<tag>"`);
|
|
194
|
+
if (e.allow !== undefined && !(e.mode === "provisional" && ALLOW.includes(e.allow)))
|
|
195
|
+
problems.push(`wire ${e.from} -> ${e.to} has allow "${e.allow}": only a provisional wire has one, "read" or "revertible"`);
|
|
196
|
+
if (e.unless !== undefined && !(e.mode === "provisional" && Array.isArray(e.unless) && e.unless.every((fact) => START_FACTS.includes(fact))))
|
|
197
|
+
problems.push(`wire ${e.from} -> ${e.to} has unless ${JSON.stringify(e.unless)}: only a provisional wire has one, a list of ${START_FACTS.join(", ")}`);
|
|
198
|
+
}
|
|
199
|
+
// A generator starts a new run, so it can only start one where runs start: an input node.
|
|
200
|
+
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
201
|
+
for (const e of config?.edges ?? []) if (e.mode === "generator" && byId.has(e.to) && byId.get(e.to).kind !== "input")
|
|
202
|
+
problems.push(`generator wire ${e.from} -> ${e.to} starts a run at "${e.to}", which is not an input node`);
|
|
203
|
+
const provisionalTargets = new Set((config?.edges ?? []).filter((e) => e.mode === "provisional").map((e) => e.to));
|
|
204
|
+
if (provisionalTargets.size > 1) problems.push(`provisional wires point at more than one step (${[...provisionalTargets].join(", ")}): one step may run provisionally`);
|
|
205
|
+
// Kahn over wait and background wires.
|
|
206
|
+
const flow = (config?.edges ?? []).filter((e) => e.mode === "wait" || e.mode === "background");
|
|
207
|
+
const indeg = new Map([...ids].map((id) => [id, 0]));
|
|
208
|
+
for (const e of flow) indeg.set(e.to, (indeg.get(e.to) ?? 0) + 1);
|
|
209
|
+
const ready = [...ids].filter((id) => indeg.get(id) === 0);
|
|
210
|
+
let done = 0;
|
|
211
|
+
while (ready.length) {
|
|
212
|
+
const id = ready.pop();
|
|
213
|
+
done += 1;
|
|
214
|
+
for (const e of flow) if (e.from === id) {
|
|
215
|
+
indeg.set(e.to, indeg.get(e.to) - 1);
|
|
216
|
+
if (indeg.get(e.to) === 0) ready.push(e.to);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (done !== ids.size) problems.push("the wait and background wires go round in a cycle");
|
|
220
|
+
return problems;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Every node a run from `start` could reach over `wait` and `background` wires, in an order where each comes after all that feed it. */
|
|
224
|
+
function orderFrom(config, start) {
|
|
225
|
+
const flow = config.edges.filter((e) => e.mode === "wait" || e.mode === "background");
|
|
226
|
+
const reach = new Set([start]);
|
|
227
|
+
const stack = [start];
|
|
228
|
+
while (stack.length) {
|
|
229
|
+
const id = stack.pop();
|
|
230
|
+
for (const e of flow) if (e.from === id && !reach.has(e.to)) {
|
|
231
|
+
reach.add(e.to);
|
|
232
|
+
stack.push(e.to);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const order = [];
|
|
236
|
+
const placed = new Set();
|
|
237
|
+
const visit = (id) => {
|
|
238
|
+
if (placed.has(id)) return;
|
|
239
|
+
placed.add(id);
|
|
240
|
+
for (const e of flow) if (e.to === id && reach.has(e.from)) visit(e.from);
|
|
241
|
+
order.push(id);
|
|
242
|
+
};
|
|
243
|
+
for (const id of reach) visit(id);
|
|
244
|
+
return order;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* How a config runs a step provisionally (Dev2, 2026-11-17): the target of its `provisional` wires and, for each wire
|
|
249
|
+
* whose two ends are on, its source, the tags that stop or restart the target (`when` entries "stop:<tag>",
|
|
250
|
+
* "restart:<tag>"; any other output is go), what the target may do before the go (`allow`, "revertible" when the
|
|
251
|
+
* wire names none) and which bursts do not start it early (`unless`; empty when the wire names none). `on` is false
|
|
252
|
+
* with no such wire. Read by intake; the runner never fires these wires.
|
|
253
|
+
*/
|
|
254
|
+
function provisionalWiring(config) {
|
|
255
|
+
const isOn = (id) => {
|
|
256
|
+
const n = (config?.nodes ?? []).find((x) => x.id === id);
|
|
257
|
+
return !!n && n.on !== false;
|
|
258
|
+
};
|
|
259
|
+
const wires = (Array.isArray(config?.edges) ? config.edges : []).filter((e) => e.mode === "provisional" && isOn(e.from) && isOn(e.to));
|
|
260
|
+
if (!wires.length) return { on: false, target: null, sources: [] };
|
|
261
|
+
const target = wires[0].to;
|
|
262
|
+
const tags = (e, kind) => (Array.isArray(e.when) ? e.when : []).filter((t) => typeof t === "string" && t.startsWith(`${kind}:`)).map((t) => t.slice(kind.length + 1));
|
|
263
|
+
const unlessOf = (e) => (Array.isArray(e.unless) ? e.unless.filter((fact) => typeof fact === "string") : []);
|
|
264
|
+
const sources = wires.filter((e) => e.to === target).map((e) => ({ from: e.from, stop: tags(e, "stop"), restart: tags(e, "restart"), allow: e.allow === "read" ? "read" : "revertible", unless: unlessOf(e) }));
|
|
265
|
+
return { on: true, target, sources };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Which of `facts` hold a provisional run back (`unless` on its wires, the union: one wire that names a fact holds
|
|
270
|
+
* every wire). Empty when the run starts. The texting Worker and the Lab both call this, so a burst the config holds
|
|
271
|
+
* is held in both (Dev2, 2026-11-17: the gate is the wire's, not code's).
|
|
272
|
+
*/
|
|
273
|
+
function provisionalHeld(unless, facts) {
|
|
274
|
+
const block = new Set(Array.isArray(unless) ? unless : []);
|
|
275
|
+
return (Array.isArray(facts) ? facts : []).filter((fact) => typeof fact === "string" && block.has(fact));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* The runner for one config and one process's nodes.
|
|
280
|
+
*
|
|
281
|
+
* impls { [nodeId]: async (input, io) => output }: the nodes this process runs.
|
|
282
|
+
* log ({ node, input, output, ms, own, ok, error, at, via }) => void: every node run (`ms` from start to end,
|
|
283
|
+
* `own` less its waits on the nodes it called); never awaited, never throws out.
|
|
284
|
+
* background (promise) => void: where a `background` wire's run goes (a Worker's `waitUntil`); awaited when absent.
|
|
285
|
+
* handOff (nodeId, input, ctx) => Promise: a node this process does not run (the gateway's, seen from the Worker);
|
|
286
|
+
* its result ends this process's part of the run. Without it, such a node throws.
|
|
287
|
+
* now () => number.
|
|
288
|
+
* onStart ({ node, id, parent, at, via, input }) => void: each node run as it starts, before its code runs (the
|
|
289
|
+
* Lab's test chat shows running steps); never awaited, never throws out.
|
|
290
|
+
* count (nodeId, output) => number | null: how many items a node handed on, counted from its whole output
|
|
291
|
+
* before the log cuts a long one, and kept on its entry as `count` (search's notes per step, Dev2
|
|
292
|
+
* 2026-11-21). Never throws out; a non-number is left off.
|
|
293
|
+
* concurrent true: a node starts as soon as every node that may feed it has finished, so two steps fed by the same
|
|
294
|
+
* one run side by side (search's word and meaning nominators, Dev2 2026-11-21). False (Tex's runs): one
|
|
295
|
+
* node at a time, in order. What runs, and on what input, is the same either way.
|
|
296
|
+
*
|
|
297
|
+
* Every run has an `id`, unique in this isolate, and the `parent` run that started it, recorded as it runs: the caller
|
|
298
|
+
* for a `uses`, `loop` or `job` handle, the node whose fired wire fed it on a `wait` or `background` path, none for the
|
|
299
|
+
* start. Both are on the log entry, so a run's cause is read from what ran, never inferred from times.
|
|
300
|
+
*/
|
|
301
|
+
let runSeq = 0;
|
|
302
|
+
/** A run id, unique in the isolate: every log entry gets its own, so a parent always names an entry that was kept. */
|
|
303
|
+
const nextRunId = () => ((runSeq = (runSeq + 1) % Number.MAX_SAFE_INTEGER), `r${runSeq}`);
|
|
304
|
+
function createGraph(config, impls, { log = () => {}, background = null, handOff = null, now = Date.now, onStart = null, start = null, concurrent = false, count = null } = {}) {
|
|
305
|
+
const problems = problemsOf(config);
|
|
306
|
+
if (problems.length) throw new GraphError(problems.join("; "));
|
|
307
|
+
const byId = new Map(config.nodes.map((n) => [n.id, n]));
|
|
308
|
+
const out = (id, mode) => config.edges.filter((e) => e.from === id && e.mode === mode);
|
|
309
|
+
|
|
310
|
+
const counted = (id, output) => {
|
|
311
|
+
if (!count) return {};
|
|
312
|
+
try {
|
|
313
|
+
const n = count(id, output);
|
|
314
|
+
return typeof n === "number" && Number.isFinite(n) ? { count: n } : {};
|
|
315
|
+
} catch {
|
|
316
|
+
return {};
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
const keep = (entry) => {
|
|
320
|
+
try {
|
|
321
|
+
const r = log(entry);
|
|
322
|
+
if (r && typeof r.catch === "function") r.catch(() => {});
|
|
323
|
+
} catch {
|
|
324
|
+
/* a log never stops a run */
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
const started = (entry) => {
|
|
329
|
+
if (typeof onStart !== "function") return;
|
|
330
|
+
try {
|
|
331
|
+
onStart(entry);
|
|
332
|
+
} catch {
|
|
333
|
+
/* a watcher never stops a run */
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
/** Run one node: its handles, its timing, its log. `parent` is the run that started it. */
|
|
338
|
+
async function runNode(id, input, ctx, via, parent) {
|
|
339
|
+
const node = byId.get(id);
|
|
340
|
+
if (!node) throw new GraphError(`no node "${id}"`);
|
|
341
|
+
if (node.on === false) return { ran: false };
|
|
342
|
+
const impl = impls[id];
|
|
343
|
+
const at = now();
|
|
344
|
+
const self = nextRunId();
|
|
345
|
+
const ids = { id: self, ...(typeof parent === "string" ? { parent } : {}) };
|
|
346
|
+
// Shaped only for a watcher: a real turn sets none, and shaping costs a serialisation of the whole input.
|
|
347
|
+
if (typeof onStart === "function") started({ node: id, ...ids, at, via, input: shaped(input) });
|
|
348
|
+
if (typeof impl !== "function") {
|
|
349
|
+
if (handOff) {
|
|
350
|
+
const output = await handOff(id, input, ctx);
|
|
351
|
+
keep({ node: id, input: shaped(input), output: shaped(output), ms: now() - at, own: now() - at, ok: true, at, via, handedOff: true, ...ids });
|
|
352
|
+
return { ran: true, output, handedOff: true, id: self };
|
|
353
|
+
}
|
|
354
|
+
throw new GraphError(`node "${id}" has no code in this process`);
|
|
355
|
+
}
|
|
356
|
+
let backs = 0;
|
|
357
|
+
// The node's own time is its run less the time it waited on other nodes it called (`use`, `back`; a `job`
|
|
358
|
+
// runs beside it), counted once however many were in flight, so a node that hands work on never shows that work as its own.
|
|
359
|
+
let inFlight = 0;
|
|
360
|
+
let since = 0;
|
|
361
|
+
let nested = 0;
|
|
362
|
+
const waited = async (work) => {
|
|
363
|
+
if (inFlight++ === 0) since = now();
|
|
364
|
+
try {
|
|
365
|
+
return await work();
|
|
366
|
+
} finally {
|
|
367
|
+
if (--inFlight === 0) nested += now() - since;
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
const timing = () => {
|
|
371
|
+
const ms = now() - at;
|
|
372
|
+
return { ms, own: Math.max(0, ms - nested - (inFlight > 0 ? now() - since : 0)) };
|
|
373
|
+
};
|
|
374
|
+
const handles = (mode, run) => Object.fromEntries(out(id, mode).map((e) => [e.to, run(e.to, e)]));
|
|
375
|
+
// `lend` (the second argument of `use` and `job`) is extra ctx for that one call: the callee's io.ctx gets it, and
|
|
376
|
+
// this node's ctx does not. It is never part of the input, so it is never logged.
|
|
377
|
+
const withLend = (lend) => (lend ? { ...ctx, ...lend } : ctx);
|
|
378
|
+
const io = {
|
|
379
|
+
node,
|
|
380
|
+
ctx,
|
|
381
|
+
// Whether a node this one may reach is on: a caller that would wait on other work before calling an off node
|
|
382
|
+
// (the Door waits on the Shape gate before the router) asks first, so an off node never holds anything up.
|
|
383
|
+
on: (to) => byId.get(to)?.on !== false,
|
|
384
|
+
use: handles("uses", (to) => async (arg, lend) => waited(async () => (await runNode(to, arg, withLend(lend), `${id}:uses`, self)).output)),
|
|
385
|
+
// A send-back spends one of the wire's rounds; a `release` (the caller letting the work go on unchanged, the
|
|
386
|
+
// answer check's "let it go") spends none, so a spent budget can always hand the work back. `left()` says how
|
|
387
|
+
// many sends remain: a node that sees 0 lets the work go instead of sending it back (Dev2, 2026-11-17: a part
|
|
388
|
+
// whose third notice crashed the turn threw its finished answer away ten times). Sending past the budget is
|
|
389
|
+
// still refused, as a bug in the node.
|
|
390
|
+
back: handles("loop", (to, wire) => {
|
|
391
|
+
const most = [wire.rounds, byId.get(to)?.rounds].find((r) => Number.isInteger(r) && r > 0) ?? 1;
|
|
392
|
+
const send = async (arg, how) => {
|
|
393
|
+
if (how?.release !== true) {
|
|
394
|
+
if (backs >= most) throw new GraphError(`"${id}" sent work back to "${to}" more than ${most} times`);
|
|
395
|
+
backs += 1;
|
|
396
|
+
}
|
|
397
|
+
return waited(() => sendBack(to, id, arg, ctx, self));
|
|
398
|
+
};
|
|
399
|
+
send.left = () => Math.max(0, most - backs);
|
|
400
|
+
return send;
|
|
401
|
+
}),
|
|
402
|
+
job: handles("job", (to) => (arg, lend) => {
|
|
403
|
+
const run = runNode(to, arg, withLend(lend), `${id}:job`, self);
|
|
404
|
+
if (background) background(run.catch(() => {}));
|
|
405
|
+
return run;
|
|
406
|
+
}),
|
|
407
|
+
// A generator wire starts a new run at its target, through the host's `start` (it persists and schedules it: a
|
|
408
|
+
// job's next part, an ask to another chat). The wire's rounds cap the chain: `ctx.generation` counts the runs
|
|
409
|
+
// before this one, and a start past the cap is answered `{ started: false, why: "spent" }`, never thrown, so the
|
|
410
|
+
// node can end the chain itself (Dev2, 2026-11-17, jobs as config).
|
|
411
|
+
start: handles("generator", (to, wire) => async (arg) => {
|
|
412
|
+
const generation = Number.isInteger(ctx?.generation) ? ctx.generation : 0;
|
|
413
|
+
if (Number.isInteger(wire.rounds) && wire.rounds > 0 && generation + 1 >= wire.rounds) return { started: false, why: "spent" };
|
|
414
|
+
if (typeof start !== "function") throw new GraphError(`"${id}" starts a run at "${to}", and this process has no start`);
|
|
415
|
+
if (!fires(wire, arg)) return { started: false, why: "when" };
|
|
416
|
+
keep({ node: to, input: shaped(arg), output: null, ms: 0, own: 0, ok: true, at: now(), via: `${id}:generator`, started: true, id: nextRunId(), parent: self });
|
|
417
|
+
const result = await start(to, carried(arg), { from: id, generation: generation + 1, parent: self });
|
|
418
|
+
return { started: true, ...(plain(result) ? result : {}) };
|
|
419
|
+
}),
|
|
420
|
+
};
|
|
421
|
+
// A handle to a node with no wire here is refused, not undefined, so a mistake fails loudly.
|
|
422
|
+
for (const kind of ["use", "back", "job", "start"]) {
|
|
423
|
+
io[kind] = new Proxy(io[kind], {
|
|
424
|
+
get(target, key) {
|
|
425
|
+
if (typeof key !== "string" || key in target || key === "then" || key === "toJSON") return target[key];
|
|
426
|
+
throw new GraphError(`"${id}" has no ${{ use: "uses", back: "loop", job: "job", start: "generator" }[kind]} wire to "${key}"`);
|
|
427
|
+
},
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
try {
|
|
431
|
+
checkShape(id, "input", input, node.inSchema);
|
|
432
|
+
const output = await impl(input, io);
|
|
433
|
+
checkShape(id, "output", output, node.outSchema);
|
|
434
|
+
keep({ node: id, input: shaped(input), output: shaped(output), ...counted(id, output), ...timing(), ok: true, at, via, ...ids });
|
|
435
|
+
return { ran: true, output, id: self };
|
|
436
|
+
} catch (error) {
|
|
437
|
+
keep({ node: id, input: shaped(input), output: null, ...timing(), ok: false, error: error?.name === "GraphError" ? error.message : String(error?.name ?? "error"), at, via, ...ids });
|
|
438
|
+
// The failed run's id rides on the error, so a `failed` wire's target names the entry that failed as its parent.
|
|
439
|
+
if (error && typeof error === "object" && !("runId" in error)) {
|
|
440
|
+
try {
|
|
441
|
+
Object.defineProperty(error, "runId", { value: self, enumerable: false });
|
|
442
|
+
} catch {
|
|
443
|
+
/* a frozen error keeps no id; its catcher falls back */
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
throw error;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Work sent back over a loop wire: the target runs, then every node on the `wait` path from it forward to the caller
|
|
452
|
+
* (each once, fed as in `run`), so a rewritten draft passes the same steps it passed the first time; returns the
|
|
453
|
+
* output of the last of them, the one that feeds the caller. Every run on the path is logged as via "caller:loop".
|
|
454
|
+
*/
|
|
455
|
+
async function sendBack(to, caller, arg, ctx, parent) {
|
|
456
|
+
const wait = config.edges.filter((e) => e.mode === "wait");
|
|
457
|
+
const reaches = new Set([caller]);
|
|
458
|
+
for (let grew = true; grew; ) {
|
|
459
|
+
grew = false;
|
|
460
|
+
for (const e of wait) if (reaches.has(e.to) && !reaches.has(e.from)) (reaches.add(e.from), (grew = true));
|
|
461
|
+
}
|
|
462
|
+
const path = orderFrom({ ...config, edges: wait }, to).filter((n) => n !== caller && (n === to || reaches.has(n)));
|
|
463
|
+
const fed = new Map([[to, [arg]]]);
|
|
464
|
+
// The run whose fired wire fed each node last: its parent. The target's is the caller that sent the work back.
|
|
465
|
+
const fedBy = new Map([[to, parent]]);
|
|
466
|
+
let last;
|
|
467
|
+
for (const n of path) {
|
|
468
|
+
const feeds = fed.get(n);
|
|
469
|
+
if (!feeds) continue;
|
|
470
|
+
const given = feeds.length === 1 ? feeds[0] : Object.assign({}, ...feeds.filter(plain));
|
|
471
|
+
const r = await runNode(n, given, ctx, `${caller}:loop`, fedBy.get(n));
|
|
472
|
+
if (!r.ran) continue;
|
|
473
|
+
last = r.output;
|
|
474
|
+
for (const e of wait) if (e.from === n && e.to !== caller && path.includes(e.to) && fires(e, r.output)) (fed.set(e.to, [...(fed.get(e.to) ?? []), carried(r.output)]), fedBy.set(e.to, r.id));
|
|
475
|
+
}
|
|
476
|
+
return last;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* Run from an input node: it, then every node its fired `wait` wires reach, each once, after all that feed it; a
|
|
481
|
+
* fired `background` wire's target runs in the background. Returns `{ outputs, ran }`: each node's output by id, in run
|
|
482
|
+
* order.
|
|
483
|
+
*/
|
|
484
|
+
async function run(begin, input, ctx = {}, { stopAt = [], progress = null } = {}) {
|
|
485
|
+
const start = begin;
|
|
486
|
+
const stops = new Set(stopAt);
|
|
487
|
+
if (!byId.has(start)) throw new GraphError(`no node "${start}"`);
|
|
488
|
+
const order = orderFrom(config, start);
|
|
489
|
+
const outputs = {};
|
|
490
|
+
const ran = [];
|
|
491
|
+
const fed = new Map([[start, [input]]]);
|
|
492
|
+
// The run whose fired wire fed each node last: its parent (`runNode`). The start has none.
|
|
493
|
+
const fedBy = new Map();
|
|
494
|
+
const later = new Map();
|
|
495
|
+
const step = async (id) => {
|
|
496
|
+
const feeds = fed.get(id);
|
|
497
|
+
if (!feeds) return; // nothing fired into it
|
|
498
|
+
// Merged in wire order; a lone input is passed as it is.
|
|
499
|
+
const given = feeds.length === 1 ? feeds[0] : Object.assign({}, ...feeds.filter(plain));
|
|
500
|
+
if (later.get(id)) {
|
|
501
|
+
const run = runNode(id, given, ctx, "background", fedBy.get(id)).catch(() => {});
|
|
502
|
+
if (background) background(run);
|
|
503
|
+
else await run;
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
// A node a durable run already finished (`progress`, the host's store for this run: a job part resumed after a
|
|
507
|
+
// crash or a deploy) is not run again: its kept output feeds on as it did (Dev2, 2026-11-17, jobs as config).
|
|
508
|
+
const kept = progress ? await progress.get(id) : undefined;
|
|
509
|
+
let r;
|
|
510
|
+
if (kept !== undefined) {
|
|
511
|
+
const resumedId = nextRunId();
|
|
512
|
+
keep({ node: id, input: shaped(given), output: shaped(kept), ms: 0, own: 0, ok: true, at: now(), via: "resumed", resumed: true, id: resumedId, ...(fedBy.get(id) ? { parent: fedBy.get(id) } : {}) });
|
|
513
|
+
r = { ran: true, output: kept, id: resumedId };
|
|
514
|
+
} else {
|
|
515
|
+
try {
|
|
516
|
+
r = await runNode(id, given, ctx, "wait", fedBy.get(id));
|
|
517
|
+
} catch (error) {
|
|
518
|
+
// A node that fails is an output when a wire from it says what happens then (`when: ["failed"]`): the run goes
|
|
519
|
+
// on down that wire with what failed, never thrown away. With no such wire it throws, as before.
|
|
520
|
+
const caught = [...out(id, "wait"), ...out(id, "background")].some((e) => Array.isArray(e.when) && e.when.includes("failed"));
|
|
521
|
+
if (!caught) throw error;
|
|
522
|
+
r = { ran: true, output: { when: ["failed"], failed: { name: String(error?.name ?? "Error"), message: String(error?.message ?? "").slice(0, 300) } }, id: error?.runId };
|
|
523
|
+
}
|
|
524
|
+
if (r.ran && progress && !r.output?.failed) await progress.put(id, r.output);
|
|
525
|
+
}
|
|
526
|
+
if (!r.ran) return;
|
|
527
|
+
outputs[id] = r.output;
|
|
528
|
+
ran.push(id);
|
|
529
|
+
if (r.handedOff || stops.has(id)) return;
|
|
530
|
+
for (const e of out(id, "wait")) if (fires(e, r.output)) (fed.set(e.to, [...(fed.get(e.to) ?? []), carried(r.output)]), fedBy.set(e.to, r.id));
|
|
531
|
+
for (const e of out(id, "background")) if (fires(e, r.output)) {
|
|
532
|
+
fed.set(e.to, [...(fed.get(e.to) ?? []), carried(r.output)]);
|
|
533
|
+
fedBy.set(e.to, r.id);
|
|
534
|
+
later.set(e.to, true);
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
if (!concurrent) {
|
|
538
|
+
for (const id of order) await step(id);
|
|
539
|
+
} else {
|
|
540
|
+
// Each node waits for every node in this run that has a wire into it, then runs (or finds nothing fed it).
|
|
541
|
+
const flow = config.edges.filter((e) => e.mode === "wait" || e.mode === "background");
|
|
542
|
+
const done = new Map();
|
|
543
|
+
for (const id of order) {
|
|
544
|
+
const before = [...new Set(flow.filter((e) => e.to === id && done.has(e.from)).map((e) => e.from))].map((from) => done.get(from));
|
|
545
|
+
done.set(id, Promise.all(before).then(() => step(id)));
|
|
546
|
+
}
|
|
547
|
+
await Promise.all(done.values());
|
|
548
|
+
}
|
|
549
|
+
return { outputs, ran };
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* Run one node over one config wire, for code not yet on the runner (the migration's bridge): throws unless the
|
|
554
|
+
* config has a `from` -> `to` wire; the caller keeps to its mode (awaits a `uses` or `wait`, hands a `background`
|
|
555
|
+
* run to `waitUntil`). Returns the node's output.
|
|
556
|
+
*/
|
|
557
|
+
async function fire(from, to, input, ctx = {}) {
|
|
558
|
+
const wire = config.edges.find((e) => e.from === from && e.to === to);
|
|
559
|
+
if (!wire) throw new GraphError(`the config has no wire from "${from}" to "${to}"`);
|
|
560
|
+
return (await runNode(to, input, ctx, `${from}:${wire.mode}`)).output;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** Whether the config has a `from` -> `to` wire, so code that may fire either of two wires picks the one drawn. */
|
|
564
|
+
const wired = (from, to) => config.edges.some((e) => e.from === from && e.to === to);
|
|
565
|
+
|
|
566
|
+
return { run, runNode, fire, wired, order: (start) => orderFrom(config, start) };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* What the code must match: every node has code in exactly one of the processes named (`{ gateway: [...ids], worker:
|
|
571
|
+
* [...ids] }`), and no process has code for a node the config does not have, unless that node is on the shelf
|
|
572
|
+
* (`texNodeShelf.json`: merged, not wired, never run; Dev2, 2026-11-16). A shelf node the config has is promoted and
|
|
573
|
+
* comes off the shelf; one with no code is a stale entry. Returns problems, empty when it matches.
|
|
574
|
+
*/
|
|
575
|
+
function coverageProblems(config, processes, shelf = []) {
|
|
576
|
+
const problems = [];
|
|
577
|
+
const ids = new Set(config.nodes.map((n) => n.id));
|
|
578
|
+
const shelved = new Set(shelf);
|
|
579
|
+
const where = new Map();
|
|
580
|
+
for (const id of shelved) if (ids.has(id)) problems.push(`"${id}" is in the config now: take it off the shelf (texNodeShelf.json)`);
|
|
581
|
+
for (const [name, list] of Object.entries(processes)) {
|
|
582
|
+
for (const id of list) {
|
|
583
|
+
if (!ids.has(id) && !shelved.has(id)) problems.push(`${name} has code for "${id}", which the config has no node for (a node merged before it is wired goes on the shelf, texNodeShelf.json)`);
|
|
584
|
+
if (where.has(id)) problems.push(`"${id}" has code in both ${where.get(id)} and ${name}`);
|
|
585
|
+
where.set(id, name);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
for (const id of ids) if (!where.has(id)) problems.push(`node "${id}" has no code in any process`);
|
|
589
|
+
for (const id of shelved) if (!ids.has(id) && !where.has(id)) problems.push(`shelf node "${id}" has no code in any process: take it off the shelf`);
|
|
590
|
+
return problems;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
module.exports = { MODES, GraphError, createGraph, problemsOf, coverageProblems, checkShape, fires, tagsOf, shaped, orderFrom, provisionalWiring, provisionalHeld, ALLOW, START_FACTS };
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** Types for `texGraph.cjs`; see that file for the rules and the reasons. */
|
|
2
|
+
|
|
3
|
+
export type WireMode = "wait" | "background" | "uses" | "loop" | "job" | "provisional" | "generator";
|
|
4
|
+
export interface GraphWire { from: string; to: string; mode: string; when?: string[]; rounds?: number; /** A provisional wire's: what its target may do before the go. */ allow?: ProvisionalAllow; /** Bursts that do not start a provisional run early (`firstLook`, `sms`, `unpaired`). Absent: every burst starts it. */ unless?: string[] }
|
|
5
|
+
export type ProvisionalAllow = "read" | "revertible";
|
|
6
|
+
export interface GraphField { name: string; type?: "text" | "yesno" | "score" | "number" | "choice" | "ids" | "list" | "object" | "any" | string; options?: string; optional?: boolean }
|
|
7
|
+
export interface GraphNode { id: string; on?: boolean; rounds?: number; kind?: string; inSchema?: GraphField[]; outSchema?: GraphField[]; [key: string]: unknown }
|
|
8
|
+
export interface GraphConfig { nodes: GraphNode[]; edges: GraphWire[] }
|
|
9
|
+
|
|
10
|
+
export interface NodeIO<Ctx = Record<string, unknown>> {
|
|
11
|
+
node: GraphNode;
|
|
12
|
+
ctx: Ctx;
|
|
13
|
+
/** The nodes this one's `uses` wires reach; any other name throws. */
|
|
14
|
+
use: Record<string, (input: unknown) => Promise<unknown>>;
|
|
15
|
+
/** The nodes this one's `loop` wires reach, at most their `rounds` times; the target runs, then the wait path back to this node. */
|
|
16
|
+
back: Record<string, ((input: unknown, how?: { release?: boolean }) => Promise<unknown>) & { left: () => number }>;
|
|
17
|
+
/** The nodes this one's `job` wires reach, started in the background. */
|
|
18
|
+
job: Record<string, (input: unknown) => Promise<unknown>>;
|
|
19
|
+
/** The input nodes this one's `generator` wires reach: starts a new run there through the host's `start`; past the wire's rounds it answers `{ started: false, why: "spent" }`. */
|
|
20
|
+
start: Record<string, (input: unknown) => Promise<{ started: boolean; why?: string; [key: string]: unknown }>>;
|
|
21
|
+
}
|
|
22
|
+
export type NodeImpl<Ctx = Record<string, unknown>> = (input: any, io: NodeIO<Ctx>) => Promise<any>;
|
|
23
|
+
|
|
24
|
+
export interface NodeRun { node: string; input: unknown; output: unknown; ms: number; /** `ms` less the time it waited on the nodes it called. */ own: number; ok: boolean; error?: string; at: number; via: string; handedOff?: boolean; /** This run's id, unique in the isolate (always set by the runner). */ id?: string; /** The run that started it (its caller, or the node whose wire fed it); none for the start. */ parent?: string }
|
|
25
|
+
/** A run as it starts, before its code runs: no output or time yet. */
|
|
26
|
+
export interface NodeStart { node: string; id: string; parent?: string; at: number; via: string; input: unknown }
|
|
27
|
+
|
|
28
|
+
export interface Graph<Ctx = Record<string, unknown>> {
|
|
29
|
+
run(start: string, input: unknown, ctx?: Ctx, options?: { stopAt?: string[]; progress?: { get(node: string): unknown | Promise<unknown>; put(node: string, output: unknown): unknown } }): Promise<{ outputs: Record<string, any>; ran: string[] }>;
|
|
30
|
+
fire(from: string, to: string, input: unknown, ctx?: Ctx): Promise<any>;
|
|
31
|
+
runNode(id: string, input: unknown, ctx: Ctx, via: string, parent?: string): Promise<{ ran: boolean; output?: any; handedOff?: boolean; id?: string }>;
|
|
32
|
+
order(start: string): string[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export declare const MODES: readonly WireMode[];
|
|
36
|
+
export declare class GraphError extends Error {}
|
|
37
|
+
export declare function createGraph<Ctx = Record<string, unknown>>(
|
|
38
|
+
config: GraphConfig,
|
|
39
|
+
impls: Record<string, NodeImpl<Ctx>>,
|
|
40
|
+
options?: { log?: (run: NodeRun) => unknown; background?: (p: Promise<unknown>) => void; handOff?: (id: string, input: unknown, ctx: Ctx) => Promise<unknown>; now?: () => number; onStart?: (run: NodeStart) => void; start?: (to: string, input: unknown, meta: { from: string; generation: number; parent: string }) => Promise<unknown> },
|
|
41
|
+
): Graph<Ctx>;
|
|
42
|
+
export declare function problemsOf(config: GraphConfig): string[];
|
|
43
|
+
export declare function coverageProblems(config: GraphConfig, processes: Record<string, string[]>, shelf?: string[]): string[];
|
|
44
|
+
export declare function checkShape(id: string, which: "input" | "output", value: unknown, schema?: GraphField[]): void;
|
|
45
|
+
export declare function fires(edge: GraphWire, output: unknown): boolean;
|
|
46
|
+
export declare function tagsOf(output: unknown): string[];
|
|
47
|
+
export declare function shaped(value: unknown, schema?: GraphField[]): unknown;
|
|
48
|
+
export declare function orderFrom(config: GraphConfig, start: string): string[];
|
|
49
|
+
|
|
50
|
+
/** How a config runs a step provisionally: its target and, per `provisional` wire with both ends on, the tags that stop or restart it, what it may do before the go, and which bursts do not start it early. */
|
|
51
|
+
export interface ProvisionalWiring { on: boolean; target: string | null; sources: { from: string; stop: string[]; restart: string[]; allow: ProvisionalAllow; unless: string[] }[] }
|
|
52
|
+
export declare const ALLOW: readonly ProvisionalAllow[];
|
|
53
|
+
export declare function provisionalWiring(config: GraphConfig): ProvisionalWiring;
|
|
54
|
+
/** The facts in `facts` that `unless` holds back. Empty when the provisional run starts. */
|
|
55
|
+
export declare function provisionalHeld(unless: readonly string[] | undefined, facts: readonly string[] | undefined): string[];
|