@culture.dev/agents 0.15.2 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/contract-schemas/api.json +73 -15
- package/dist/contract-schemas/branches.json +163 -0
- package/dist/contract-schemas/capabilities.json +133 -6
- package/dist/contract-schemas/common.json +9 -3
- package/dist/contract-schemas/control-action.json +91 -14
- package/dist/contract-schemas/error.json +189 -48
- package/dist/contract-schemas/event.json +185 -2
- package/dist/contract-schemas/run.json +111 -4
- package/dist/contract-schemas/version.json +2 -2
- package/dist/src/contract/generated/branches.d.ts +34 -0
- package/dist/src/contract/generated/branches.js +3 -0
- package/dist/src/contract/generated/branches.js.map +1 -0
- package/dist/src/contract/generated/capabilities.d.ts +39 -7
- package/dist/src/contract/generated/common.d.ts +5 -3
- package/dist/src/contract/generated/control-action.d.ts +30 -11
- package/dist/src/contract/generated/error.d.ts +31 -7
- package/dist/src/contract/generated/event.d.ts +57 -8
- package/dist/src/contract/generated/index.d.ts +37 -12
- package/dist/src/contract/generated/run.d.ts +23 -5
- package/dist/src/contract/generated/version.d.ts +2 -2
- package/dist/src/contract/ids.d.ts +6 -3
- package/dist/src/contract/ids.js +5 -2
- package/dist/src/contract/ids.js.map +1 -1
- package/dist/src/contract/index.d.ts +1 -1
- package/dist/src/contract/index.js +1 -1
- package/dist/src/contract/index.js.map +1 -1
- package/dist/src/daemon/branch-routes.d.ts +13 -0
- package/dist/src/daemon/branch-routes.js +41 -0
- package/dist/src/daemon/branch-routes.js.map +1 -0
- package/dist/src/daemon/daemon.js +10 -2
- package/dist/src/daemon/daemon.js.map +1 -1
- package/dist/src/daemon/harness-catalog.d.ts +6 -0
- package/dist/src/daemon/harness-catalog.js +20 -0
- package/dist/src/daemon/harness-catalog.js.map +1 -1
- package/dist/src/daemon/limits.d.ts +31 -0
- package/dist/src/daemon/limits.js +61 -0
- package/dist/src/daemon/limits.js.map +1 -0
- package/dist/src/daemon/main.d.ts +10 -0
- package/dist/src/daemon/main.js +161 -41
- package/dist/src/daemon/main.js.map +1 -1
- package/dist/src/daemon/ports.d.ts +21 -11
- package/dist/src/daemon/routes.d.ts +3 -0
- package/dist/src/daemon/routes.js +26 -5
- package/dist/src/daemon/routes.js.map +1 -1
- package/dist/src/daemon/secrets.d.ts +24 -0
- package/dist/src/daemon/secrets.js +52 -0
- package/dist/src/daemon/secrets.js.map +1 -0
- package/dist/src/daemon/submitter.d.ts +9 -0
- package/dist/src/daemon/submitter.js +23 -0
- package/dist/src/daemon/submitter.js.map +1 -0
- package/dist/src/harness/claude-code/index.js +1 -1
- package/dist/src/harness/claude-code/index.js.map +1 -1
- package/dist/src/harness/common/capabilities.d.ts +26 -2
- package/dist/src/harness/common/capabilities.js +31 -6
- package/dist/src/harness/common/capabilities.js.map +1 -1
- package/dist/src/harness/common/guard.d.ts +2 -1
- package/dist/src/harness/common/guard.js +6 -0
- package/dist/src/harness/common/guard.js.map +1 -1
- package/dist/src/harness/common/run-driver.d.ts +6 -1
- package/dist/src/harness/common/run-driver.js +20 -3
- package/dist/src/harness/common/run-driver.js.map +1 -1
- package/dist/src/harness/common/sandbox-workspace.d.ts +5 -1
- package/dist/src/harness/common/sandbox-workspace.js +12 -3
- package/dist/src/harness/common/sandbox-workspace.js.map +1 -1
- package/dist/src/harness/common/types.d.ts +8 -0
- package/dist/src/harness/config.d.ts +5 -0
- package/dist/src/harness/config.js +7 -3
- package/dist/src/harness/config.js.map +1 -1
- package/dist/src/harness/index.js +2 -2
- package/dist/src/harness/index.js.map +1 -1
- package/dist/src/harness/opencode/index.js +1 -1
- package/dist/src/harness/opencode/index.js.map +1 -1
- package/dist/src/harness/stub/backend.d.ts +3 -0
- package/dist/src/harness/stub/backend.js +50 -1
- package/dist/src/harness/stub/backend.js.map +1 -1
- package/dist/src/harness/stub/index.d.ts +7 -1
- package/dist/src/harness/stub/index.js +10 -2
- package/dist/src/harness/stub/index.js.map +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/publish/config.d.ts +25 -0
- package/dist/src/publish/config.js +47 -0
- package/dist/src/publish/config.js.map +1 -0
- package/dist/src/publish/envelope.d.ts +61 -0
- package/dist/src/publish/envelope.js +109 -0
- package/dist/src/publish/envelope.js.map +1 -0
- package/dist/src/publish/index.d.ts +22 -0
- package/dist/src/publish/index.js +35 -0
- package/dist/src/publish/index.js.map +1 -0
- package/dist/src/publish/log-tail.d.ts +31 -0
- package/dist/src/publish/log-tail.js +172 -0
- package/dist/src/publish/log-tail.js.map +1 -0
- package/dist/src/publish/publisher.d.ts +34 -0
- package/dist/src/publish/publisher.js +207 -0
- package/dist/src/publish/publisher.js.map +1 -0
- package/dist/src/publish/transport.d.ts +14 -0
- package/dist/src/publish/transport.js +69 -0
- package/dist/src/publish/transport.js.map +1 -0
- package/dist/src/runs/admission.d.ts +27 -0
- package/dist/src/runs/admission.js +97 -0
- package/dist/src/runs/admission.js.map +1 -0
- package/dist/src/runs/answer.d.ts +24 -0
- package/dist/src/runs/answer.js +99 -0
- package/dist/src/runs/answer.js.map +1 -0
- package/dist/src/runs/base-commit.d.ts +6 -0
- package/dist/src/runs/base-commit.js +23 -0
- package/dist/src/runs/base-commit.js.map +1 -0
- package/dist/src/runs/branches.d.ts +23 -0
- package/dist/src/runs/branches.js +115 -0
- package/dist/src/runs/branches.js.map +1 -0
- package/dist/src/runs/control.d.ts +12 -4
- package/dist/src/runs/control.js +14 -6
- package/dist/src/runs/control.js.map +1 -1
- package/dist/src/runs/gateway.d.ts +25 -0
- package/dist/src/runs/gateway.js +122 -0
- package/dist/src/runs/gateway.js.map +1 -0
- package/dist/src/runs/keys.d.ts +21 -0
- package/dist/src/runs/keys.js +50 -0
- package/dist/src/runs/keys.js.map +1 -0
- package/dist/src/runs/limits.d.ts +15 -0
- package/dist/src/runs/limits.js +37 -0
- package/dist/src/runs/limits.js.map +1 -0
- package/dist/src/runs/ports.d.ts +3 -0
- package/dist/src/runs/ports.js.map +1 -1
- package/dist/src/runs/reattach.d.ts +37 -0
- package/dist/src/runs/reattach.js +70 -0
- package/dist/src/runs/reattach.js.map +1 -0
- package/dist/src/runs/scan.d.ts +11 -6
- package/dist/src/runs/scan.js +12 -15
- package/dist/src/runs/scan.js.map +1 -1
- package/dist/src/runs/service.d.ts +57 -7
- package/dist/src/runs/service.js +160 -95
- package/dist/src/runs/service.js.map +1 -1
- package/dist/src/runs/submit.d.ts +34 -0
- package/dist/src/runs/submit.js +92 -0
- package/dist/src/runs/submit.js.map +1 -0
- package/dist/src/sandbox/host-command.js +5 -1
- package/dist/src/sandbox/host-command.js.map +1 -1
- package/dist/src/sandbox/run-sandbox.d.ts +8 -2
- package/dist/src/sandbox/run-sandbox.js +10 -3
- package/dist/src/sandbox/run-sandbox.js.map +1 -1
- package/dist/src/store/derive.js +3 -0
- package/dist/src/store/derive.js.map +1 -1
- package/dist/src/store/entries.d.ts +29 -0
- package/dist/src/store/entries.js +41 -0
- package/dist/src/store/entries.js.map +1 -0
- package/dist/src/store/event-log.d.ts +3 -3
- package/dist/src/store/event-log.js +2 -2
- package/dist/src/store/event-log.js.map +1 -1
- package/dist/src/store/files.d.ts +4 -0
- package/dist/src/store/files.js +4 -0
- package/dist/src/store/files.js.map +1 -1
- package/dist/src/store/idempotency.d.ts +79 -0
- package/dist/src/store/idempotency.js +281 -0
- package/dist/src/store/idempotency.js.map +1 -0
- package/dist/src/store/index.d.ts +8 -0
- package/dist/src/store/index.js +5 -0
- package/dist/src/store/index.js.map +1 -1
- package/dist/src/store/questions.d.ts +40 -0
- package/dist/src/store/questions.js +90 -0
- package/dist/src/store/questions.js.map +1 -0
- package/dist/src/store/retention.d.ts +13 -0
- package/dist/src/store/retention.js +74 -0
- package/dist/src/store/retention.js.map +1 -0
- package/dist/src/store/run-store.d.ts +4 -0
- package/dist/src/store/run-store.js +20 -4
- package/dist/src/store/run-store.js.map +1 -1
- package/dist/src/store/startup.d.ts +9 -0
- package/dist/src/store/startup.js +92 -0
- package/dist/src/store/startup.js.map +1 -0
- package/dist/src/store/summary.d.ts +7 -0
- package/dist/src/store/summary.js +126 -0
- package/dist/src/store/summary.js.map +1 -0
- package/dist/src/store/version.d.ts +10 -0
- package/dist/src/store/version.js +46 -0
- package/dist/src/store/version.js.map +1 -0
- package/dist/src/trace/config.d.ts +31 -0
- package/dist/src/trace/config.js +69 -0
- package/dist/src/trace/config.js.map +1 -0
- package/dist/src/trace/follower.d.ts +20 -0
- package/dist/src/trace/follower.js +196 -0
- package/dist/src/trace/follower.js.map +1 -0
- package/dist/src/trace/index.d.ts +21 -0
- package/dist/src/trace/index.js +42 -0
- package/dist/src/trace/index.js.map +1 -0
- package/dist/src/trace/otlp.d.ts +11 -0
- package/dist/src/trace/otlp.js +52 -0
- package/dist/src/trace/otlp.js.map +1 -0
- package/dist/src/trace/spans.d.ts +28 -0
- package/dist/src/trace/spans.js +120 -0
- package/dist/src/trace/spans.js.map +1 -0
- package/dist/src/worker/answer.d.ts +29 -0
- package/dist/src/worker/answer.js +53 -0
- package/dist/src/worker/answer.js.map +1 -0
- package/dist/src/worker/asking.d.ts +22 -0
- package/dist/src/worker/asking.js +21 -0
- package/dist/src/worker/asking.js.map +1 -0
- package/dist/src/worker/control.d.ts +7 -1
- package/dist/src/worker/control.js +22 -10
- package/dist/src/worker/control.js.map +1 -1
- package/dist/src/worker/delivery.d.ts +2 -2
- package/dist/src/worker/delivery.js +1 -1
- package/dist/src/worker/delivery.js.map +1 -1
- package/dist/src/worker/driver.d.ts +46 -1
- package/dist/src/worker/fake-driver.d.ts +35 -1
- package/dist/src/worker/fake-driver.js +45 -0
- package/dist/src/worker/fake-driver.js.map +1 -1
- package/dist/src/worker/main.js +4 -1
- package/dist/src/worker/main.js.map +1 -1
- package/dist/src/worker/questions.d.ts +67 -0
- package/dist/src/worker/questions.js +152 -0
- package/dist/src/worker/questions.js.map +1 -0
- package/dist/src/worker/run-loop.d.ts +19 -1
- package/dist/src/worker/run-loop.js +91 -25
- package/dist/src/worker/run-loop.js.map +1 -1
- package/dist/src/worker/spawn.d.ts +9 -1
- package/dist/src/worker/spawn.js +12 -3
- package/dist/src/worker/spawn.js.map +1 -1
- package/package.json +3 -2
- package/policy/profiles/culture-agents-claude-subscription.yaml +1 -1
- package/policy/profiles/culture-agents-local-gateway.yaml +1 -1
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a run's event log for publishing, and the on-disk record of how far a run is published.
|
|
3
|
+
*
|
|
4
|
+
* The reader takes only what is published from each line: run id, cursor, time, kind and, for a
|
|
5
|
+
* state transition, the new state. It never keeps or returns the rest of a line. Like every reader
|
|
6
|
+
* of the log it counts only newline-terminated lines, so a torn final line is not an event.
|
|
7
|
+
*
|
|
8
|
+
* The position is `<run directory>/published.json`: the cursor of the last event the broker
|
|
9
|
+
* acknowledged, the byte offset just past that event's line, and the run's state at that point.
|
|
10
|
+
* The log is append-only (only a torn tail is ever truncated), so the offset stays valid; it is
|
|
11
|
+
* checked all the same, and a position that does not match the log is replaced by a read from the
|
|
12
|
+
* start that still skips nothing past the recorded cursor.
|
|
13
|
+
*/
|
|
14
|
+
import { closeSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { atomicWriteJson, runFile } from "../store/files.js";
|
|
17
|
+
/** File name of the publish position inside a run directory. */
|
|
18
|
+
export const POSITION_FILE = "published.json";
|
|
19
|
+
export const START = Object.freeze({ cursor: 0, offset: 0, state: null });
|
|
20
|
+
/** The log cannot be published past this point: a complete line breaks a rule of the log. */
|
|
21
|
+
export class LogHeldError extends Error {
|
|
22
|
+
name = "LogHeldError";
|
|
23
|
+
}
|
|
24
|
+
/** The recorded position; `START` when the file is absent or does not hold a usable position. */
|
|
25
|
+
export function readPosition(dir) {
|
|
26
|
+
let value;
|
|
27
|
+
try {
|
|
28
|
+
value = JSON.parse(readFileSync(join(dir, POSITION_FILE), "utf8"));
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return START;
|
|
32
|
+
}
|
|
33
|
+
if (value === null || typeof value !== "object")
|
|
34
|
+
return START;
|
|
35
|
+
const { cursor, offset, state } = value;
|
|
36
|
+
const whole = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
|
|
37
|
+
if (!whole(cursor) || !whole(offset) || !(state === null || typeof state === "string"))
|
|
38
|
+
return START;
|
|
39
|
+
if ((cursor === 0) !== (offset === 0) || (cursor === 0) !== (state === null))
|
|
40
|
+
return START;
|
|
41
|
+
return { cursor, offset, state };
|
|
42
|
+
}
|
|
43
|
+
/** Record the position (0600, replaced atomically). */
|
|
44
|
+
export function writePosition(dir, position) {
|
|
45
|
+
atomicWriteJson(join(dir, POSITION_FILE), { cursor: position.cursor, offset: position.offset, state: position.state });
|
|
46
|
+
}
|
|
47
|
+
const CHUNK = 256 * 1024;
|
|
48
|
+
/** Bytes of the log from `offset` up to its last newline, at most about `CHUNK` unless one line is longer. */
|
|
49
|
+
function readLines(fd, offset, size) {
|
|
50
|
+
let want = Math.min(CHUNK, size - offset);
|
|
51
|
+
for (;;) {
|
|
52
|
+
const buf = Buffer.alloc(want);
|
|
53
|
+
const got = readSync(fd, buf, 0, want, offset);
|
|
54
|
+
const end = buf.subarray(0, got).lastIndexOf(0x0a) + 1;
|
|
55
|
+
if (end > 0 || offset + got >= size || got < want)
|
|
56
|
+
return buf.subarray(0, end);
|
|
57
|
+
want = Math.min(want * 2, size - offset); // one line longer than the chunk: read more of it
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function factOf(runId, line, previous) {
|
|
61
|
+
let value;
|
|
62
|
+
try {
|
|
63
|
+
value = JSON.parse(line);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
throw new LogHeldError(`the line after cursor ${previous.cursor} is not JSON`);
|
|
67
|
+
}
|
|
68
|
+
if (value === null || typeof value !== "object")
|
|
69
|
+
throw new LogHeldError(`the line after cursor ${previous.cursor} is not an event`);
|
|
70
|
+
const { run_id, cursor, time, kind, data } = value;
|
|
71
|
+
if (run_id !== runId)
|
|
72
|
+
throw new LogHeldError(`the line after cursor ${previous.cursor} belongs to another run`);
|
|
73
|
+
if (cursor !== previous.cursor + 1)
|
|
74
|
+
throw new LogHeldError(`cursor ${typeof cursor === "number" ? cursor : "?"} follows cursor ${previous.cursor}`);
|
|
75
|
+
if (typeof time !== "string" || typeof kind !== "string")
|
|
76
|
+
throw new LogHeldError(`event ${previous.cursor + 1} has no time or kind`);
|
|
77
|
+
let state = previous.state;
|
|
78
|
+
if (kind === "run.state") {
|
|
79
|
+
const to = data !== null && typeof data === "object" ? data["to"] : undefined;
|
|
80
|
+
if (typeof to !== "string")
|
|
81
|
+
throw new LogHeldError(`event ${previous.cursor + 1} is a state transition without a state`);
|
|
82
|
+
state = to;
|
|
83
|
+
}
|
|
84
|
+
if (state === null)
|
|
85
|
+
throw new LogHeldError("the first event is not a state transition");
|
|
86
|
+
return { run_id: runId, kind, state, cursor: previous.cursor + 1, time };
|
|
87
|
+
}
|
|
88
|
+
/** The run's event log, open for reading, or null when it has none yet. */
|
|
89
|
+
function openLog(dir) {
|
|
90
|
+
try {
|
|
91
|
+
return openSync(runFile(dir, "events"), "r");
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
if (err.code === "ENOENT")
|
|
95
|
+
return null;
|
|
96
|
+
throw err;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The events of `buf` (whole lines read at `from`) into `out`, up to `max`. Returns the position
|
|
101
|
+
* after the last line read, or null when a line that breaks a rule of the log ends the read after
|
|
102
|
+
* some events: those are published, and the next call reports the line.
|
|
103
|
+
*/
|
|
104
|
+
function readChunk(runId, buf, from, skipThrough, out, max) {
|
|
105
|
+
let at = from;
|
|
106
|
+
let start = 0;
|
|
107
|
+
while (out.length < max && start < buf.length) {
|
|
108
|
+
const end = buf.indexOf(0x0a, start);
|
|
109
|
+
let fact;
|
|
110
|
+
try {
|
|
111
|
+
fact = factOf(runId, buf.subarray(start, end).toString("utf8"), at);
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
if (out.length > 0 && err instanceof LogHeldError)
|
|
115
|
+
return null; // publish what precedes it; the next call reports it
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
|
+
at = { cursor: fact.cursor, offset: at.offset + (end + 1 - start), state: fact.state };
|
|
119
|
+
if (fact.cursor > skipThrough)
|
|
120
|
+
out.push({ fact, after: at });
|
|
121
|
+
start = end + 1;
|
|
122
|
+
}
|
|
123
|
+
return at;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Up to `max` events after `from`, in cursor order. A complete line that breaks a rule of the log
|
|
127
|
+
* ends the read: the events before it are returned, and the call that finds it first throws
|
|
128
|
+
* `LogHeldError`. Nothing after it is ever returned.
|
|
129
|
+
*/
|
|
130
|
+
function readFrom(dir, runId, from, skipThrough, max) {
|
|
131
|
+
const fd = openLog(dir);
|
|
132
|
+
if (fd === null)
|
|
133
|
+
return [];
|
|
134
|
+
try {
|
|
135
|
+
const size = fstatSync(fd).size;
|
|
136
|
+
if (from.offset > size)
|
|
137
|
+
throw new LogHeldError(`the log is shorter than the recorded offset ${from.offset}`);
|
|
138
|
+
const out = [];
|
|
139
|
+
let at = from;
|
|
140
|
+
while (out.length < max && at.offset < size) {
|
|
141
|
+
const buf = readLines(fd, at.offset, size);
|
|
142
|
+
if (buf.length === 0)
|
|
143
|
+
break; // only a torn tail is left
|
|
144
|
+
const next = readChunk(runId, buf, at, skipThrough, out, max);
|
|
145
|
+
if (next === null)
|
|
146
|
+
return out;
|
|
147
|
+
at = next;
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
finally {
|
|
152
|
+
closeSync(fd);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* The next events to publish after `position`, at most `max`. A position whose offset does not
|
|
157
|
+
* match the log (the file was edited, or the position is damaged) is not trusted: the log is read
|
|
158
|
+
* from its start and events up to `position.cursor` are passed over, so none is skipped.
|
|
159
|
+
*/
|
|
160
|
+
export function pendingFacts(dir, runId, position, max) {
|
|
161
|
+
if (position.offset === 0)
|
|
162
|
+
return readFrom(dir, runId, START, position.cursor, max);
|
|
163
|
+
try {
|
|
164
|
+
return readFrom(dir, runId, position, position.cursor, max);
|
|
165
|
+
}
|
|
166
|
+
catch (err) {
|
|
167
|
+
if (!(err instanceof LogHeldError))
|
|
168
|
+
throw err;
|
|
169
|
+
return readFrom(dir, runId, START, position.cursor, max);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
//# sourceMappingURL=log-tail.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"log-tail.js","sourceRoot":"","sources":["../../../src/publish/log-tail.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACjF,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAG7D,gEAAgE;AAChE,MAAM,CAAC,MAAM,aAAa,GAAG,gBAAgB,CAAC;AAW9C,MAAM,CAAC,MAAM,KAAK,GAAoB,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAE3F,6FAA6F;AAC7F,MAAM,OAAO,YAAa,SAAQ,KAAK;IACnB,IAAI,GAAG,cAAc,CAAC;CACzC;AAED,iGAAiG;AACjG,MAAM,UAAU,YAAY,CAAC,GAAW;IACtC,IAAI,KAAc,CAAC;IACnB,IAAI,CAAC;QACH,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,C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,KAAK,CAAC;QAAE,OAAO,QAAQ,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACpF,IAAI,CAAC;QACH,OAAO,QAAQ,CAAC,GAAG,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC9D,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,CAAC,GAAG,YAAY,YAAY,CAAC;YAAE,MAAM,GAAG,CAAC;QAC9C,OAAO,QAAQ,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC3D,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** The connection to the broker, as the follower needs it. */
|
|
2
|
+
export interface BrokerTransport {
|
|
3
|
+
/**
|
|
4
|
+
* Resolves once the broker acknowledged the message. Rejects when it did not: at once without a
|
|
5
|
+
* connection, or after the transport's own time limit. It never waits without bound.
|
|
6
|
+
*/
|
|
7
|
+
publish(topic: string, payload: string): Promise<void>;
|
|
8
|
+
close(): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
export interface PublisherOptions {
|
|
11
|
+
stateDir: string;
|
|
12
|
+
/** The envelope `source` of this core (`sourceFor(node)`). */
|
|
13
|
+
source: string;
|
|
14
|
+
transport: BrokerTransport;
|
|
15
|
+
/** Where one-line diagnostics go (the core's stderr). */
|
|
16
|
+
warn: (line: string) => void;
|
|
17
|
+
/** How long the loop sleeps when no run had anything new. Default 250 ms. */
|
|
18
|
+
pollMs?: number;
|
|
19
|
+
/** How long the loop sleeps after the broker refused an event. Default 1000 ms. */
|
|
20
|
+
retryMs?: number;
|
|
21
|
+
/** Most events published for one run before the next run gets its turn. Default 200. */
|
|
22
|
+
batch?: number;
|
|
23
|
+
/** How long `stop` waits for a publish in flight. Default 1000 ms. */
|
|
24
|
+
stopTimeoutMs?: number;
|
|
25
|
+
}
|
|
26
|
+
export interface Publisher {
|
|
27
|
+
/** Follow the logs until `stop`. */
|
|
28
|
+
start(): void;
|
|
29
|
+
/** One round over every run; resolves to the number of events published. */
|
|
30
|
+
pass(): Promise<number>;
|
|
31
|
+
/** Stop following and close the transport. Events not yet published stay in their logs. */
|
|
32
|
+
stop(): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
export declare function createPublisher(options: PublisherOptions): Publisher;
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The follower that publishes run events to the broker.
|
|
3
|
+
*
|
|
4
|
+
* It belongs to the core, never to a worker: workers append to their logs and know nothing of the
|
|
5
|
+
* broker. The follower reads each run's log, publishes each event it has not published yet, in
|
|
6
|
+
* cursor order, waits for the broker's acknowledgement, and only then records the new position on
|
|
7
|
+
* disk. So:
|
|
8
|
+
*
|
|
9
|
+
* - an event is published after its append, never before, and the log stays the source of truth;
|
|
10
|
+
* - a broker that is down or slow costs nothing but lateness: no request to the core and no worker
|
|
11
|
+
* waits on this loop, and the events stay in their logs until the broker takes them;
|
|
12
|
+
* - after an outage or a core restart the follower goes on from the recorded position, so missed
|
|
13
|
+
* events are published with the ids they always had and none is skipped;
|
|
14
|
+
* - a core that dies between the acknowledgement and the position write publishes that one event
|
|
15
|
+
* again, as the same bytes with the same id (delivery is at-least-once; consumers dedupe on id).
|
|
16
|
+
*
|
|
17
|
+
* A run whose log cannot be read past some point is held there with one warning. Nothing after
|
|
18
|
+
* that point is published under a guessed cursor.
|
|
19
|
+
*/
|
|
20
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
21
|
+
import { isTerminal } from "../contract/index.js";
|
|
22
|
+
import { runDir } from "../store/files.js";
|
|
23
|
+
import { listRunIds } from "../store/run-store.js";
|
|
24
|
+
import { EnvelopeError, buildMessage } from "./envelope.js";
|
|
25
|
+
import { pendingFacts, readPosition, writePosition } from "./log-tail.js";
|
|
26
|
+
const reasonOf = (err) => (err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "";
|
|
27
|
+
export function createPublisher(options) {
|
|
28
|
+
const { stateDir, source, transport, warn } = options;
|
|
29
|
+
const pollMs = options.pollMs ?? 250;
|
|
30
|
+
const retryMs = options.retryMs ?? 1000;
|
|
31
|
+
const batch = options.batch ?? 200;
|
|
32
|
+
/** Position of every run this core is still following (read from disk the first time). */
|
|
33
|
+
const positions = new Map();
|
|
34
|
+
/** Runs with nothing left to publish, now or ever: terminal and fully published. */
|
|
35
|
+
const finished = new Set();
|
|
36
|
+
/** Runs held at a point in their log, and runs whose position could not be written: warned once each. */
|
|
37
|
+
const held = new Set();
|
|
38
|
+
const unwritable = new Set();
|
|
39
|
+
/** Whether the broker took the last event offered; null before the first attempt. */
|
|
40
|
+
let up = null;
|
|
41
|
+
let stopped = false;
|
|
42
|
+
let loop = null;
|
|
43
|
+
const abort = new AbortController();
|
|
44
|
+
const hold = (runId, err) => {
|
|
45
|
+
held.add(runId);
|
|
46
|
+
positions.delete(runId);
|
|
47
|
+
warn(`culture-agents core: run ${runId} is not published past this point: ${reasonOf(err)}. Its log is unchanged.`);
|
|
48
|
+
};
|
|
49
|
+
/** The envelope of one fact, or null after holding the run on a fact that has none. */
|
|
50
|
+
function messageFor(runId, item) {
|
|
51
|
+
try {
|
|
52
|
+
return buildMessage(item.fact, source);
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
if (!(err instanceof EnvelopeError))
|
|
56
|
+
throw err;
|
|
57
|
+
hold(runId, err);
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Offer one message to the broker; true once it acknowledged. Warns when the broker goes away or comes back. */
|
|
62
|
+
async function offer(message) {
|
|
63
|
+
try {
|
|
64
|
+
await transport.publish(message.topic, message.payload);
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
if (up !== false && !stopped)
|
|
68
|
+
warn(`culture-agents core: the broker is not taking run events (${reasonOf(err)}); they stay in the run logs and are published when it is back.`);
|
|
69
|
+
up = false;
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
if (up === false)
|
|
73
|
+
warn("culture-agents core: the broker takes run events again; publishing what was missed.");
|
|
74
|
+
up = true;
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
/** Record the position after an acknowledged event: in memory, then on disk. */
|
|
78
|
+
function record(runId, dir, position) {
|
|
79
|
+
positions.set(runId, position); // kept in memory first: a failed write below must not make this core publish the event again
|
|
80
|
+
try {
|
|
81
|
+
writePosition(dir, position);
|
|
82
|
+
unwritable.delete(runId);
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
if (!unwritable.has(runId))
|
|
86
|
+
warn(`culture-agents core: cannot record how far run ${runId} is published (${reasonOf(err)}); after a restart some of its events are published again with the same ids.`);
|
|
87
|
+
unwritable.add(runId);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Publish one pending event and record the position only once the broker acknowledged it. */
|
|
91
|
+
async function publishItem(runId, dir, item) {
|
|
92
|
+
const message = messageFor(runId, item);
|
|
93
|
+
if (message === null)
|
|
94
|
+
return "held";
|
|
95
|
+
if (!(await offer(message)))
|
|
96
|
+
return "refused";
|
|
97
|
+
record(runId, dir, item.after);
|
|
98
|
+
return "published";
|
|
99
|
+
}
|
|
100
|
+
/** The events `runId` has pending, or null when it has none now or ever (finished) or is held. */
|
|
101
|
+
function pendingOf(runId, dir) {
|
|
102
|
+
const position = positions.get(runId) ?? readPosition(dir);
|
|
103
|
+
if (position.state !== null && isTerminal(position.state)) {
|
|
104
|
+
finished.add(runId);
|
|
105
|
+
positions.delete(runId);
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
positions.set(runId, position);
|
|
109
|
+
try {
|
|
110
|
+
return pendingFacts(dir, runId, position, batch);
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
hold(runId, err);
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** Publish what `runId` has pending. `refused` is true when the broker did not take an event. */
|
|
118
|
+
async function publishRun(runId) {
|
|
119
|
+
const dir = runDir(stateDir, runId);
|
|
120
|
+
const pending = pendingOf(runId, dir);
|
|
121
|
+
if (pending === null)
|
|
122
|
+
return { count: 0, refused: false };
|
|
123
|
+
let count = 0;
|
|
124
|
+
for (const item of pending) {
|
|
125
|
+
const outcome = await publishItem(runId, dir, item);
|
|
126
|
+
if (outcome !== "published")
|
|
127
|
+
return { count, refused: outcome === "refused" };
|
|
128
|
+
count += 1;
|
|
129
|
+
if (stopped)
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
return { count, refused: false };
|
|
133
|
+
}
|
|
134
|
+
async function pass() {
|
|
135
|
+
let total = 0;
|
|
136
|
+
for (const runId of listRunIds(stateDir)) {
|
|
137
|
+
if (stopped)
|
|
138
|
+
break;
|
|
139
|
+
if (finished.has(runId) || held.has(runId))
|
|
140
|
+
continue;
|
|
141
|
+
let result;
|
|
142
|
+
try {
|
|
143
|
+
result = await publishRun(runId);
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
if (!held.has(runId))
|
|
147
|
+
hold(runId, err);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
total += result.count;
|
|
151
|
+
if (result.refused)
|
|
152
|
+
break; // try again later, from the same event
|
|
153
|
+
}
|
|
154
|
+
return total;
|
|
155
|
+
}
|
|
156
|
+
/** How long to sleep after a round that published `count` events. */
|
|
157
|
+
function waitAfter(count) {
|
|
158
|
+
if (up === false)
|
|
159
|
+
return retryMs;
|
|
160
|
+
// More may be waiting after a full batch: go on at once, but let other work in between.
|
|
161
|
+
return count > 0 ? 0 : pollMs;
|
|
162
|
+
}
|
|
163
|
+
/** One round of `follow`: a pass, then the sleep before the next one (none once stopped). */
|
|
164
|
+
async function round() {
|
|
165
|
+
let count = 0;
|
|
166
|
+
try {
|
|
167
|
+
count = await pass();
|
|
168
|
+
}
|
|
169
|
+
catch (err) {
|
|
170
|
+
warn(`culture-agents core: publishing run events failed for this round: ${reasonOf(err)}`);
|
|
171
|
+
}
|
|
172
|
+
if (stopped)
|
|
173
|
+
return;
|
|
174
|
+
await delay(waitAfter(count), undefined, { signal: abort.signal }).catch(() => undefined);
|
|
175
|
+
}
|
|
176
|
+
/** Rounds one after the other until `stop`; each round starts when the one before has finished. */
|
|
177
|
+
function follow() {
|
|
178
|
+
return new Promise((resolve, reject) => {
|
|
179
|
+
const next = () => {
|
|
180
|
+
if (stopped)
|
|
181
|
+
return resolve();
|
|
182
|
+
round().then(next, reject);
|
|
183
|
+
};
|
|
184
|
+
next();
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
start() {
|
|
189
|
+
loop ??= follow();
|
|
190
|
+
},
|
|
191
|
+
pass,
|
|
192
|
+
async stop() {
|
|
193
|
+
if (stopped)
|
|
194
|
+
return;
|
|
195
|
+
stopped = true;
|
|
196
|
+
abort.abort();
|
|
197
|
+
if (loop) {
|
|
198
|
+
// A publish the broker never acknowledges must not keep the core from stopping.
|
|
199
|
+
const limit = new AbortController();
|
|
200
|
+
await Promise.race([loop, delay(options.stopTimeoutMs ?? 1000, undefined, { signal: limit.signal }).catch(() => undefined)]);
|
|
201
|
+
limit.abort();
|
|
202
|
+
}
|
|
203
|
+
await transport.close().catch(() => undefined);
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
//# sourceMappingURL=publisher.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"publisher.js","sourceRoot":"","sources":["../../../src/publish/publisher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EAAE,UAAU,EAAiB,MAAM,sBAAsB,CAAC;AACjE,OAAO,EAAE,MAA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I,EAAE,MAAM,CAAC,CAAC;YAC7B,CAAC,CAAC;YACF,IAAI,EAAE,CAAC;QACT,CAAC,CAAC,CAAC;IACL,CAAC;IAED,OAAO;QACL,KAAK;YACH,IAAI,KAAK,MAAM,EAAE,CAAC;QACpB,CAAC;QACD,IAAI;QACJ,KAAK,CAAC,IAAI;YACR,IAAI,OAAO;gBAAE,OAAO;YACpB,OAAO,GAAG,IAAI,CAAC;YACf,KAAK,CAAC,KAAK,EAAE,CAAC;YACd,IAAI,IAAI,EAAE,CAAC;gBACT,gFAAgF;gBAChF,MAAM,KAAK,GAAG,IAAI,eAAe,EAAE,CAAC;gBACpC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,OAAO,CAAC,aAAa,IAAI,IAAI,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;gBAC7H,KAAK,CAAC,KAAK,EAAE,CAAC;YAChB,CAAC;YACD,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QACjD,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { PublishConfig } from "./config.js";
|
|
2
|
+
import type { BrokerTransport } from "./publisher.js";
|
|
3
|
+
export interface TransportOptions {
|
|
4
|
+
/** How long one publish may wait for the broker's acknowledgement. Default 10 s. */
|
|
5
|
+
ackTimeoutMs?: number;
|
|
6
|
+
/** Pause between connection attempts. Default 1 s. */
|
|
7
|
+
reconnectMs?: number;
|
|
8
|
+
}
|
|
9
|
+
/** The broker did not take the message. */
|
|
10
|
+
export declare class BrokerUnavailableError extends Error {
|
|
11
|
+
readonly name = "BrokerUnavailableError";
|
|
12
|
+
}
|
|
13
|
+
/** Start connecting (in the background) and return the transport. Never throws for a broker that is down. */
|
|
14
|
+
export declare function connectBroker(config: PublishConfig, options?: TransportOptions): BrokerTransport;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The MQTT connection to the broker. This is the only module that loads the MQTT client, and only
|
|
3
|
+
* the core's publisher loads this module: no worker opens a broker connection.
|
|
4
|
+
*
|
|
5
|
+
* Messages go out at QoS 1 and not retained, as the broker's own envelope publisher sends them
|
|
6
|
+
* (events-cli `EventClient.publish_event`): a QoS 0 envelope is never queued for a subscriber that
|
|
7
|
+
* is offline. The client reconnects on its own. A publish without a connection is refused at
|
|
8
|
+
* once and nothing is queued in memory: the run log is the queue, and the follower offers the
|
|
9
|
+
* event again.
|
|
10
|
+
*/
|
|
11
|
+
import { randomBytes } from "node:crypto";
|
|
12
|
+
import { connect } from "mqtt";
|
|
13
|
+
/** The broker did not take the message. */
|
|
14
|
+
export class BrokerUnavailableError extends Error {
|
|
15
|
+
name = "BrokerUnavailableError";
|
|
16
|
+
}
|
|
17
|
+
/** Start connecting (in the background) and return the transport. Never throws for a broker that is down. */
|
|
18
|
+
export function connectBroker(config, options = {}) {
|
|
19
|
+
const ackTimeoutMs = options.ackTimeoutMs ?? 10_000;
|
|
20
|
+
const client = connect({
|
|
21
|
+
protocol: "mqtt",
|
|
22
|
+
host: config.host,
|
|
23
|
+
port: config.port,
|
|
24
|
+
clientId: `culture-agents-core-${randomBytes(6).toString("hex")}`,
|
|
25
|
+
clean: true,
|
|
26
|
+
reconnectPeriod: options.reconnectMs ?? 1000,
|
|
27
|
+
connectTimeout: 5000,
|
|
28
|
+
queueQoSZero: false,
|
|
29
|
+
resubscribe: false,
|
|
30
|
+
});
|
|
31
|
+
let lastError = "not connected";
|
|
32
|
+
// Without a listener an `error` event would be an uncaught exception in the core.
|
|
33
|
+
client.on("error", (err) => {
|
|
34
|
+
lastError = err.message.split("\n")[0] ?? "error";
|
|
35
|
+
});
|
|
36
|
+
return {
|
|
37
|
+
publish(topic, payload) {
|
|
38
|
+
if (!client.connected)
|
|
39
|
+
return Promise.reject(new BrokerUnavailableError(lastError));
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
let settled = false;
|
|
42
|
+
const timer = setTimeout(() => {
|
|
43
|
+
if (settled)
|
|
44
|
+
return;
|
|
45
|
+
settled = true;
|
|
46
|
+
// Take it out of the client's resend store: the follower offers the event again itself.
|
|
47
|
+
if (messageId !== undefined)
|
|
48
|
+
client.removeOutgoingMessage(messageId);
|
|
49
|
+
reject(new BrokerUnavailableError(`no acknowledgement within ${ackTimeoutMs} ms`));
|
|
50
|
+
}, ackTimeoutMs);
|
|
51
|
+
client.publish(topic, payload, { qos: 1, retain: false }, (err) => {
|
|
52
|
+
if (settled)
|
|
53
|
+
return;
|
|
54
|
+
settled = true;
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
if (err)
|
|
57
|
+
reject(new BrokerUnavailableError(err.message.split("\n")[0] ?? "publish failed"));
|
|
58
|
+
else
|
|
59
|
+
resolve();
|
|
60
|
+
});
|
|
61
|
+
const messageId = client.getLastMessageId();
|
|
62
|
+
});
|
|
63
|
+
},
|
|
64
|
+
async close() {
|
|
65
|
+
await client.endAsync(true);
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=transport.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../src/publish/transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,OAAO,EAAmB,MAAM,MAAM,CAAC;AAYhD,2CAA2C;AAC3C,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IAC7B,IAAI,GAAG,wBAAwB,CAAC;CACnD;AAED,6GAA6G;AAC7G,MAAM,UAAU,aAAa,CAAC,MAAqB,EAAE,UAA4B,EAAE;IACjF,MAAM,YAAY,GAAG,OAAO,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AE,YAAY,CAAC,CAAC;gBACjB,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,GAAG,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE;oBAChE,IAAI,OAAO;wBAAE,OAAO;oBACpB,OAAO,GAAG,IAAI,CAAC;oBACf,YAAY,CAAC,KAAK,CAAC,CAAC;oBACpB,IAAI,GAAG;wBAAE,MAAM,CAAC,IAAI,sBAAsB,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,gBAAgB,CAAC,CAAC,CAAC;;wBACvF,OAAO,EAAE,CAAC;gBACjB,CAAC,CAAC,CAAC;gBACH,MAAM,SAAS,GAAuB,MAAM,CAAC,gBAAgB,EAAE,CAAC;YAClE,CAAC,CAAC,CAAC;QACL,CAAC;QACD,KAAK,CAAC,KAAK;YACT,MAAM,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC9B,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Admission, Capabilities, Limits, Signal, Warning } from "../contract/index.js";
|
|
2
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
3
|
+
import { type GatewaySource } from "./gateway.js";
|
|
4
|
+
/** The heat-governor state file path, or null when neither variable names a place. */
|
|
5
|
+
export declare function heatStatePath(env: Env): string | null;
|
|
6
|
+
/** Interpret one heat payload (the text of state.json) at `now`. */
|
|
7
|
+
export declare function heatFromPayload(text: string, now: Date): Signal;
|
|
8
|
+
/** Read the heat signal now. `read` is injectable (default: the file at `heatStatePath`). */
|
|
9
|
+
export declare function readHeat(env: Env, now: Date, read?: (path: string) => string): Signal;
|
|
10
|
+
/** Both signals now. The gateway is read (under a short timeout) only for a harness that uses it. */
|
|
11
|
+
export declare function readAdmission(env: Env, now: Date, read?: (path: string) => string, gateway?: GatewaySource, harness?: string): Promise<Admission>;
|
|
12
|
+
/** What a capability document says about this core's host. */
|
|
13
|
+
export interface HostReport {
|
|
14
|
+
limits: Limits;
|
|
15
|
+
stateDir: string;
|
|
16
|
+
env: Env;
|
|
17
|
+
now: Date;
|
|
18
|
+
readHeatFile?: (path: string) => string;
|
|
19
|
+
gateway?: GatewaySource;
|
|
20
|
+
}
|
|
21
|
+
/** The number of active runs on the host. The tracing gauge counts through the same list. */
|
|
22
|
+
export declare function countActiveRuns(stateDir: string): number;
|
|
23
|
+
/** The document with `limits`, `active_runs` and `admission` added (this core's own host only). */
|
|
24
|
+
export declare function withHostReport(doc: Capabilities, report: HostReport): Promise<Capabilities>;
|
|
25
|
+
/** Warnings for a local submit: one per consulted signal that reads unknown. */
|
|
26
|
+
export declare function submitWarnings(admission: Admission): Warning[];
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host's admission state for the capability report (contract README: limits, load and
|
|
3
|
+
* admission). Every signal reads admit, hold or unknown; a missing, stale, unreadable or
|
|
4
|
+
* malformed reading is unknown, never admit, and never a failure of the control plane.
|
|
5
|
+
*
|
|
6
|
+
* Heat is read as its publisher writes it. heat-governor's daemon writes `state.json` about once a
|
|
7
|
+
* second (heat-governor docs/contracts/state.md and heat_governor/client.py, 0.20.1, as recorded
|
|
8
|
+
* in the spec, s10): `host`, `at` (epoch seconds, a number), `stale_after_s`, `level`, `admit`
|
|
9
|
+
* (false in hot and critical) and `concurrency_factor`. Path: `$HEAT_GOVERNOR_STATE`, else
|
|
10
|
+
* `$XDG_RUNTIME_DIR/heat-governor/state.json`. NOT VERIFIED on a live host: the publisher is not
|
|
11
|
+
* on the host this was written on, so the format is the spec's citation of it; readers take
|
|
12
|
+
* the payload through an injectable `read`.
|
|
13
|
+
*/
|
|
14
|
+
import { readFileSync } from "node:fs";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { activeRunList } from "../store/entries.js";
|
|
17
|
+
import { GATEWAY_NOT_USED, readGateway } from "./gateway.js";
|
|
18
|
+
/** The heat-governor state file path, or null when neither variable names a place. */
|
|
19
|
+
export function heatStatePath(env) {
|
|
20
|
+
const explicit = env["HEAT_GOVERNOR_STATE"];
|
|
21
|
+
if (explicit)
|
|
22
|
+
return explicit;
|
|
23
|
+
const runtime = env["XDG_RUNTIME_DIR"];
|
|
24
|
+
return runtime ? join(runtime, "heat-governor", "state.json") : null;
|
|
25
|
+
}
|
|
26
|
+
const unknownHeat = (reason, observedAt = null) => ({ state: "unknown", consulted: true, reason, observed_at: observedAt });
|
|
27
|
+
/** Interpret one heat payload (the text of state.json) at `now`. */
|
|
28
|
+
export function heatFromPayload(text, now) {
|
|
29
|
+
let doc;
|
|
30
|
+
try {
|
|
31
|
+
doc = JSON.parse(text);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return unknownHeat("the heat-governor state file is not valid JSON");
|
|
35
|
+
}
|
|
36
|
+
const o = doc !== null && typeof doc === "object" && !Array.isArray(doc) ? doc : null;
|
|
37
|
+
const at = o?.["at"];
|
|
38
|
+
const window = o?.["stale_after_s"];
|
|
39
|
+
if (o === null || typeof at !== "number" || !Number.isFinite(at) || typeof window !== "number" || !Number.isFinite(window) || window <= 0 || typeof o["admit"] !== "boolean") {
|
|
40
|
+
return unknownHeat("the heat-governor state file lacks a numeric at, a positive stale_after_s or a boolean admit");
|
|
41
|
+
}
|
|
42
|
+
const observed = new Date(at * 1000);
|
|
43
|
+
if (Number.isNaN(observed.getTime()))
|
|
44
|
+
return unknownHeat("the heat-governor state file has an unusable at");
|
|
45
|
+
const observedAt = observed.toISOString();
|
|
46
|
+
const ageMs = now.getTime() - observed.getTime();
|
|
47
|
+
if (ageMs > window * 1000)
|
|
48
|
+
return unknownHeat(`the heat reading is stale: ${Math.round(ageMs / 1000)}s old, stale after ${window}s`, observedAt);
|
|
49
|
+
if (ageMs < -window * 1000)
|
|
50
|
+
return unknownHeat("the heat reading is stamped in the future", observedAt);
|
|
51
|
+
if (o["admit"])
|
|
52
|
+
return { state: "admit", consulted: true, reason: null, observed_at: observedAt };
|
|
53
|
+
const level = typeof o["level"] === "string" ? o["level"] : "unreported";
|
|
54
|
+
return { state: "hold", consulted: true, reason: `heat-governor says hold (level ${level})`, observed_at: observedAt };
|
|
55
|
+
}
|
|
56
|
+
/** Read the heat signal now. `read` is injectable (default: the file at `heatStatePath`). */
|
|
57
|
+
export function readHeat(env, now, read = (p) => readFileSync(p, "utf8")) {
|
|
58
|
+
const path = heatStatePath(env);
|
|
59
|
+
if (path === null)
|
|
60
|
+
return unknownHeat("no heat-governor state path: neither HEAT_GOVERNOR_STATE nor XDG_RUNTIME_DIR is set");
|
|
61
|
+
let text;
|
|
62
|
+
try {
|
|
63
|
+
text = read(path);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return unknownHeat(`the heat-governor state file ${path} is missing or unreadable`);
|
|
67
|
+
}
|
|
68
|
+
return heatFromPayload(text, now);
|
|
69
|
+
}
|
|
70
|
+
/** Both signals now. The gateway is read (under a short timeout) only for a harness that uses it. */
|
|
71
|
+
export async function readAdmission(env, now, read, gateway, harness) {
|
|
72
|
+
const uses = gateway !== undefined && harness !== undefined && gateway.harnesses.includes(harness);
|
|
73
|
+
return {
|
|
74
|
+
heat: readHeat(env, now, read),
|
|
75
|
+
gateway: uses ? await readGateway(gateway, now) : { state: "unknown", consulted: false, reason: GATEWAY_NOT_USED, observed_at: null },
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** The number of active runs on the host. The tracing gauge counts through the same list. */
|
|
79
|
+
export function countActiveRuns(stateDir) {
|
|
80
|
+
return activeRunList(stateDir).length;
|
|
81
|
+
}
|
|
82
|
+
/** The document with `limits`, `active_runs` and `admission` added (this core's own host only). */
|
|
83
|
+
export async function withHostReport(doc, report) {
|
|
84
|
+
return { ...doc, limits: { ...report.limits }, active_runs: countActiveRuns(report.stateDir), admission: await readAdmission(report.env, report.now, report.readHeatFile, report.gateway, doc.harness) };
|
|
85
|
+
}
|
|
86
|
+
/** Warnings for a local submit: one per consulted signal that reads unknown. */
|
|
87
|
+
export function submitWarnings(admission) {
|
|
88
|
+
const out = [];
|
|
89
|
+
for (const name of ["heat", "gateway"]) {
|
|
90
|
+
const signal = admission[name];
|
|
91
|
+
if (signal.consulted && signal.state === "unknown") {
|
|
92
|
+
out.push({ code: "signal_unknown", signal: name, message: `The ${name} signal reads unknown (${signal.reason ?? "no reading"}); this local submit was admitted without it.` });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=admission.js.map
|