@listen-fire/engine 0.12.6 → 0.12.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.
@@ -2,26 +2,6 @@ import { type LanguageVersion } from '@listen-fire/movement-lang';
2
2
  import type { EngineHost, SegmentOpening } from '../movement_engine/host';
3
3
  import { type CostLine } from '../../lib/run_cost';
4
4
  import { type ClassifyHostError } from './engine/adapter_table';
5
- /** The systems that count against a ceiling. One entry per system that has its
6
- * own env var below; a system not listed here is simply not capped. */
7
- export type AdapterCallSystem = 'affinity' | 'remote';
8
- /**
9
- * An adapter call refused because its segment made as many calls to a
10
- * third-party system as one segment may — raised by the call that would have
11
- * gone one over, inside the host. The host answers the engine with it as a
12
- * `call_ceiling` error (`segmentScopedCalls`); an adapter that catches its own
13
- * failures lets this one through (`isAdapterCallCeilingExceeded`).
14
- */
15
- export declare class AdapterCallCeilingExceeded extends Error {
16
- /** The system that counts, e.g. `affinity`. */
17
- readonly system: string;
18
- readonly calls: number;
19
- readonly kind = "call_ceiling";
20
- constructor(
21
- /** The system that counts, e.g. `affinity`. */
22
- system: string, calls: number, message: string);
23
- }
24
- export declare function isAdapterCallCeilingExceeded(err: unknown): err is AdapterCallCeilingExceeded;
25
5
  /** Open a segment: a fresh memo, a fresh count. The host families version is
26
6
  * the host's to check, before it opens one (`openSegmentWith`). */
27
7
  export declare function openSegment(input: Omit<SegmentOpening, 'hostFamiliesVersion'>): Promise<{
@@ -67,44 +47,4 @@ export declare const segmentScopedCalls: {
67
47
  * describe, tests) there is no pin and this is the current version.
68
48
  */
69
49
  export declare function currentLanguageVersion(): LanguageVersion;
70
- /**
71
- * Serve `key` from what this segment has already read, or read it and
72
- * remember.
73
- *
74
- * Outside a segment — CLI scripts, catalog describe, the MCP connection
75
- * describer, tests — there is no memo and this is exactly `load()`.
76
- *
77
- * The key must name the CREDENTIAL as well as the record: one run may speak to
78
- * two workspaces of the same system, and `person 41` is a different person in
79
- * each.
80
- */
81
- export declare function memoisedRead<T>(key: string, load: () => Promise<T>): Promise<T>;
82
- /** File a record the system just handed back (a create's or an update's own
83
- * response), so the next read of it is free. No-op outside a segment. */
84
- export declare function fillMemoisedRead(key: string, value: unknown): void;
85
- /** Drop what this segment's own write just made wrong. No-op outside one. */
86
- export declare function forgetMemoisedReads(...keys: string[]): void;
87
- /** Drop a whole family of reads — used where a write invalidates an unknown
88
- * number of them (a field-value row names its own id, not its owner). */
89
- export declare function forgetMemoisedReadsUnder(prefix: string): void;
90
- /**
91
- * Record one outbound HTTP attempt, throwing once the segment is over its
92
- * ceiling.
93
- *
94
- * Outside a segment — CLI scripts, catalog describe, the MCP connection
95
- * describer, tests — there is no ledger and this does nothing.
96
- */
97
- export declare function countAdapterCall(system: AdapterCallSystem): void;
98
- /**
99
- * Bind the CURRENT segment's counter for a call that will execute later, in
100
- * someone else's async context.
101
- *
102
- * The API clients queue their requests behind a shared concurrency limiter, so
103
- * a queued job is dequeued by whichever other job happened to finish — in that
104
- * job's async context, not its own. Reading the ledger at that point would
105
- * charge the wrong segment (or none). Capturing it where the call was ISSUED
106
- * keeps the count with the segment that asked for it.
107
- */
108
- export declare function bindAdapterCallCounter(system: AdapterCallSystem): () => void;
109
- /** The calls charged to the current segment so far — diagnostics and tests. */
110
- export declare function currentSegmentCallCount(system: AdapterCallSystem): number;
50
+ export { AdapterCallCeilingExceeded, bindAdapterCallCounter, countAdapterCall, currentRunCallCount as currentSegmentCallCount, fillMemoisedRead, forgetMemoisedReads, forgetMemoisedReadsUnder, isAdapterCallCeilingExceeded, memoisedRead, type AdapterCallSystem, } from '@listen-fire/module-runtime/run_scope';
@@ -1,181 +1,38 @@
1
1
  "use strict";
2
- // The host's half of a run SEGMENT: what its adapter calls have already read
3
- // (the memo below), how many third-party calls they have made (the ceiling),
4
- // which language version they answer under, and what they spent on priced
5
- // work of their own. The engine opens a segment through the host's `segment`
6
- // family and names it on every adapter call; the host runs each call inside
7
- // the segment's scope (`segmentScopedCalls`).
2
+ // The host's half of a run SEGMENT: its run scope (what its adapter calls
3
+ // have already read, and how many third-party calls they have made:
4
+ // `module-runtime/run_scope`), which language version they answer under, and
5
+ // what they spent on priced work of their own. The engine opens a segment
6
+ // through the host's `segment` family and names it on every adapter call; the
7
+ // host runs each call inside the segment's scope (`segmentScopedCalls`).
8
8
  //
9
9
  // The scope is ambient INSIDE the host, on purpose: the API clients are
10
10
  // process-wide singletons shared by every run in the process, far below the
11
11
  // adapter method that reached them, so the segment has to arrive the way the
12
12
  // billing context does. The engine never reads it — it only holds the
13
13
  // segment's id.
14
- //
15
- // ── The ceiling ─────────────────────────────────────────────────────────────
16
- //
17
- // A ceiling on how many network calls one segment may make to a third-party
18
- // system.
19
- //
20
- // The failure this catches is a read that was supposed to be narrowed and
21
- // wasn't: a filter that didn't push down turns "the three organizations this
22
- // person works at" into a walk of the whole workspace, one page at a time,
23
- // forever. Nothing else notices — the run is not stuck, it is working, and it
24
- // is burning someone's API quota to do it. The ceiling stops it and says so:
25
- // the engine is answered with a `call_ceiling` error.
26
- //
27
- // One segment, one count. A run that parks on an `ask` and resumes hours later
28
- // starts fresh: a spiral happens inside a single segment, and carrying a count
29
- // across processes would cost machinery that buys nothing.
30
14
  Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.segmentScopedCalls = exports.hostSegments = exports.AdapterCallCeilingExceeded = void 0;
32
- exports.isAdapterCallCeilingExceeded = isAdapterCallCeilingExceeded;
15
+ exports.memoisedRead = exports.isAdapterCallCeilingExceeded = exports.forgetMemoisedReadsUnder = exports.forgetMemoisedReads = exports.fillMemoisedRead = exports.currentSegmentCallCount = exports.countAdapterCall = exports.bindAdapterCallCounter = exports.AdapterCallCeilingExceeded = exports.segmentScopedCalls = exports.hostSegments = void 0;
33
16
  exports.openSegment = openSegment;
34
17
  exports.closeSegment = closeSegment;
35
18
  exports.inSegment = inSegment;
36
19
  exports.withSegment = withSegment;
37
20
  exports.currentLanguageVersion = currentLanguageVersion;
38
- exports.memoisedRead = memoisedRead;
39
- exports.fillMemoisedRead = fillMemoisedRead;
40
- exports.forgetMemoisedReads = forgetMemoisedReads;
41
- exports.forgetMemoisedReadsUnder = forgetMemoisedReadsUnder;
42
- exports.countAdapterCall = countAdapterCall;
43
- exports.bindAdapterCallCounter = bindAdapterCallCounter;
44
- exports.currentSegmentCallCount = currentSegmentCallCount;
45
21
  const node_crypto_1 = require("node:crypto");
46
22
  const node_async_hooks_1 = require("node:async_hooks");
23
+ const run_scope_1 = require("@listen-fire/module-runtime/run_scope");
47
24
  const movement_lang_1 = require("@listen-fire/movement-lang");
48
25
  const engine_contracts_1 = require("@listen-fire/engine-contracts");
49
26
  const run_cost_1 = require("../../lib/run_cost");
50
27
  const run_spend_1 = require("../../lib/run_spend");
51
28
  const logger_1 = require("../logger");
52
29
  const adapter_table_1 = require("./engine/adapter_table");
53
- const CEILING_ENV_VAR = {
54
- affinity: 'AFFINITY_MAX_CALLS_PER_RUN',
55
- remote: 'REMOTE_ADAPTER_MAX_CALLS_PER_RUN',
56
- };
57
- // A remote adapter (an external speaking the adapter protocol) is a third
58
- // party like any other: an unnarrowed walk through it spirals the same way.
59
- const DEFAULT_CEILING = {
60
- affinity: 2000,
61
- remote: 2000,
62
- };
63
- const SYSTEM_LABEL = {
64
- affinity: 'Affinity',
65
- remote: 'Remote adapter',
66
- };
67
- /** Read per call so ops (and tests) can move the ceiling without a restart.
68
- * A missing, zero, or unparseable value means the default — the safeguard is
69
- * always on, there is no "unlimited". */
70
- function ceilingFor(system) {
71
- const fromEnv = Number(process.env[CEILING_ENV_VAR[system]]);
72
- return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : DEFAULT_CEILING[system];
73
- }
74
- /**
75
- * An adapter call refused because its segment made as many calls to a
76
- * third-party system as one segment may — raised by the call that would have
77
- * gone one over, inside the host. The host answers the engine with it as a
78
- * `call_ceiling` error (`segmentScopedCalls`); an adapter that catches its own
79
- * failures lets this one through (`isAdapterCallCeilingExceeded`).
80
- */
81
- class AdapterCallCeilingExceeded extends Error {
82
- system;
83
- calls;
84
- kind = 'call_ceiling';
85
- constructor(
86
- /** The system that counts, e.g. `affinity`. */
87
- system, calls, message) {
88
- super(message);
89
- this.system = system;
90
- this.calls = calls;
91
- this.name = 'AdapterCallCeilingExceeded';
92
- }
93
- }
94
- exports.AdapterCallCeilingExceeded = AdapterCallCeilingExceeded;
95
- function isAdapterCallCeilingExceeded(err) {
96
- return err instanceof AdapterCallCeilingExceeded;
97
- }
98
- /** The call that would have gone one over. Its message is the whole failure
99
- * surface an author sees, so it says the number, the knob, and why the run
100
- * stopped. */
101
- function ceilingExceeded(system, calls) {
102
- return new AdapterCallCeilingExceeded(system, calls, `${SYSTEM_LABEL[system]} call ceiling reached: this run made ${calls} ${SYSTEM_LABEL[system]} API calls, ` +
103
- `the limit set by ${CEILING_ENV_VAR[system]}. The run was stopped in case something was looping.`);
104
- }
105
- class SegmentCallLedger {
106
- counts = new Map();
107
- count(system) {
108
- const ceiling = ceilingFor(system);
109
- const next = (this.counts.get(system) ?? 0) + 1;
110
- if (next > ceiling)
111
- throw ceilingExceeded(system, ceiling);
112
- this.counts.set(system, next);
113
- }
114
- calls(system) {
115
- return this.counts.get(system) ?? 0;
116
- }
117
- }
118
- // ── The read memo ───────────────────────────────────────────────────────────
119
- /**
120
- * What this segment has already READ from a third party.
121
- *
122
- * Inside one run the same record is asked for over and over: the engine reads
123
- * it to decide whether anything changed, the adapter reads it again to write
124
- * it, and a second write to the same record reads it a third time. Nothing
125
- * happened in between except our own writes — so the answer is already in the
126
- * process, and asking again spends someone's API quota to be told what we
127
- * know.
128
- *
129
- * The lifetime is the segment, deliberately. A memo that outlived the run would
130
- * have to reason about who else might be editing the workspace; a memo that
131
- * dies with it only has to reason about what the run ITSELF wrote — which it
132
- * can, exactly, because it did the writing. That is what `forget` is for: every
133
- * write evicts the reads it invalidated, so "stale" here means "stale by
134
- * someone else's hand, within one run", which is the same window a single
135
- * uncached read already has.
136
- *
137
- * The PROMISE is stored, so callers asking at the same moment share one flight.
138
- */
139
- class SegmentReadMemo {
140
- reads = new Map();
141
- read(key, load) {
142
- const hit = this.reads.get(key);
143
- if (hit)
144
- return hit;
145
- // A rejected read is not an answer. Remembering it would serve the failure
146
- // to every later caller and never retry.
147
- const pending = load().catch((err) => {
148
- if (this.reads.get(key) === pending)
149
- this.reads.delete(key);
150
- throw err;
151
- });
152
- this.reads.set(key, pending);
153
- return pending;
154
- }
155
- /** File a record we were HANDED rather than asked for — a create's or an
156
- * update's own response is the record, and the next read of it should not
157
- * be a request. */
158
- fill(key, value) {
159
- this.reads.set(key, Promise.resolve(value));
160
- }
161
- forget(keys) {
162
- for (const key of keys)
163
- this.reads.delete(key);
164
- }
165
- forgetUnder(prefix) {
166
- for (const key of [...this.reads.keys()]) {
167
- if (key.startsWith(prefix))
168
- this.reads.delete(key);
169
- }
170
- }
171
- }
172
30
  // ── The segment ─────────────────────────────────────────────────────────────
173
31
  class SegmentScope {
174
32
  tenantId;
175
33
  languageVersion;
176
34
  runId;
177
- ledger = new SegmentCallLedger();
178
- memo = new SegmentReadMemo();
35
+ run = new run_scope_1.RunScope();
179
36
  /** What the segment's adapter calls spent on priced work of their own — a
180
37
  * model call an adapter makes to match a record. Unbudgeted: an adapter
181
38
  * call carries no budget, so the run's cap meets this spend when the
@@ -214,7 +71,7 @@ async function closeSegment(input) {
214
71
  /** The host's `segment` family. */
215
72
  exports.hostSegments = { open: openSegment, close: closeSegment };
216
73
  function inScope(scope, fn) {
217
- return asyncLocalStorage.run(scope, () => (0, run_spend_1.underSpendMeter)(scope.spend, fn));
74
+ return asyncLocalStorage.run(scope, () => (0, run_scope_1.inRunScope)(scope.run, () => (0, run_spend_1.underSpendMeter)(scope.spend, fn)));
218
75
  }
219
76
  /** Run `fn` inside an open segment's scope — what every call into a
220
77
  * segment-bound adapter does. */
@@ -251,7 +108,7 @@ async function withSegment(input, fn) {
251
108
  exports.segmentScopedCalls = {
252
109
  around: (segmentId, call) => inSegment(segmentId, call),
253
110
  classify: (error, { segmentId }) => {
254
- if (isAdapterCallCeilingExceeded(error))
111
+ if ((0, run_scope_1.isAdapterCallCeilingExceeded)(error))
255
112
  return { kind: 'call_ceiling', message: error.message };
256
113
  logger_1.logger.warn('[segment_scope] adapter call failed', {
257
114
  segmentId,
@@ -270,62 +127,14 @@ exports.segmentScopedCalls = {
270
127
  function currentLanguageVersion() {
271
128
  return asyncLocalStorage.getStore()?.languageVersion ?? movement_lang_1.LANGUAGE_VERSION;
272
129
  }
273
- /**
274
- * Serve `key` from what this segment has already read, or read it and
275
- * remember.
276
- *
277
- * Outside a segment — CLI scripts, catalog describe, the MCP connection
278
- * describer, tests — there is no memo and this is exactly `load()`.
279
- *
280
- * The key must name the CREDENTIAL as well as the record: one run may speak to
281
- * two workspaces of the same system, and `person 41` is a different person in
282
- * each.
283
- */
284
- function memoisedRead(key, load) {
285
- const memo = asyncLocalStorage.getStore()?.memo;
286
- return memo ? memo.read(key, load) : load();
287
- }
288
- /** File a record the system just handed back (a create's or an update's own
289
- * response), so the next read of it is free. No-op outside a segment. */
290
- function fillMemoisedRead(key, value) {
291
- asyncLocalStorage.getStore()?.memo.fill(key, value);
292
- }
293
- /** Drop what this segment's own write just made wrong. No-op outside one. */
294
- function forgetMemoisedReads(...keys) {
295
- asyncLocalStorage.getStore()?.memo.forget(keys);
296
- }
297
- /** Drop a whole family of reads — used where a write invalidates an unknown
298
- * number of them (a field-value row names its own id, not its owner). */
299
- function forgetMemoisedReadsUnder(prefix) {
300
- asyncLocalStorage.getStore()?.memo.forgetUnder(prefix);
301
- }
302
- /**
303
- * Record one outbound HTTP attempt, throwing once the segment is over its
304
- * ceiling.
305
- *
306
- * Outside a segment — CLI scripts, catalog describe, the MCP connection
307
- * describer, tests — there is no ledger and this does nothing.
308
- */
309
- function countAdapterCall(system) {
310
- asyncLocalStorage.getStore()?.ledger.count(system);
311
- }
312
- /**
313
- * Bind the CURRENT segment's counter for a call that will execute later, in
314
- * someone else's async context.
315
- *
316
- * The API clients queue their requests behind a shared concurrency limiter, so
317
- * a queued job is dequeued by whichever other job happened to finish — in that
318
- * job's async context, not its own. Reading the ledger at that point would
319
- * charge the wrong segment (or none). Capturing it where the call was ISSUED
320
- * keeps the count with the segment that asked for it.
321
- */
322
- function bindAdapterCallCounter(system) {
323
- const ledger = asyncLocalStorage.getStore()?.ledger;
324
- if (ledger === undefined)
325
- return () => { };
326
- return () => ledger.count(system);
327
- }
328
- /** The calls charged to the current segment so far — diagnostics and tests. */
329
- function currentSegmentCallCount(system) {
330
- return asyncLocalStorage.getStore()?.ledger.calls(system) ?? 0;
331
- }
130
+ // What an adapter reads off its run: the segment's run scope, ambient.
131
+ var run_scope_2 = require("@listen-fire/module-runtime/run_scope");
132
+ Object.defineProperty(exports, "AdapterCallCeilingExceeded", { enumerable: true, get: function () { return run_scope_2.AdapterCallCeilingExceeded; } });
133
+ Object.defineProperty(exports, "bindAdapterCallCounter", { enumerable: true, get: function () { return run_scope_2.bindAdapterCallCounter; } });
134
+ Object.defineProperty(exports, "countAdapterCall", { enumerable: true, get: function () { return run_scope_2.countAdapterCall; } });
135
+ Object.defineProperty(exports, "currentSegmentCallCount", { enumerable: true, get: function () { return run_scope_2.currentRunCallCount; } });
136
+ Object.defineProperty(exports, "fillMemoisedRead", { enumerable: true, get: function () { return run_scope_2.fillMemoisedRead; } });
137
+ Object.defineProperty(exports, "forgetMemoisedReads", { enumerable: true, get: function () { return run_scope_2.forgetMemoisedReads; } });
138
+ Object.defineProperty(exports, "forgetMemoisedReadsUnder", { enumerable: true, get: function () { return run_scope_2.forgetMemoisedReadsUnder; } });
139
+ Object.defineProperty(exports, "isAdapterCallCeilingExceeded", { enumerable: true, get: function () { return run_scope_2.isAdapterCallCeilingExceeded; } });
140
+ Object.defineProperty(exports, "memoisedRead", { enumerable: true, get: function () { return run_scope_2.memoisedRead; } });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@listen-fire/engine",
3
3
  "license": "Apache-2.0",
4
- "version": "0.12.6",
4
+ "version": "0.12.7",
5
5
  "description": "The movement engine for this release's language and its host contract: the Rust engine's shim, the EngineHost families, the run host, the embed kit, and the adapter and model types they reach. Every shell (the hosted product, the `lf` command line, an embedder) runs the same engine. A run pinned to a release this one does not read is refused by name. Embedders reach it only through public/* (the exports map); the internals resolve only under the `movement-engine-internals` condition, which only test runners set",
6
6
  "engines": {
7
7
  "node": ">=22.23.4 <23"
@@ -17,9 +17,9 @@
17
17
  "dependencies": {
18
18
  "safe-stable-stringify": "2.5.0",
19
19
  "zod": "4.1.12",
20
- "@listen-fire/module-runtime": "^0.12.6",
21
- "@listen-fire/engine-contracts": "^0.12.6",
22
- "@listen-fire/movement-lang": "^0.12.6"
20
+ "@listen-fire/module-runtime": "^0.12.7",
21
+ "@listen-fire/engine-contracts": "^0.12.7",
22
+ "@listen-fire/movement-lang": "^0.12.7"
23
23
  },
24
24
  "devDependencies": {
25
25
  "@types/jest": "29.5.14",