@skedulo/memory-hub-mcp 0.2.38 → 0.2.40

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.
@@ -0,0 +1,195 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildRunReport = exports.MODE_LINES = void 0;
4
+ const INTERACTIVE_BASE = 'Before relying on any item under attention: call memory_get on it to see the flag in full, then: ' +
5
+ 'due → memory_checkStart with its uid; stale or upstream → the rules in memory_getSkillGuide ' +
6
+ 'section="Stale memories"; superseded → prefer the newer memory, found with memory_recall or as a ' +
7
+ '"superseded by" candidate from memory_related. Items under notJudged were only listed: memory_get ' +
8
+ 'each before relying on it.';
9
+ exports.MODE_LINES = {
10
+ interactive: INTERACTIVE_BASE +
11
+ ' forBackgroundCheck is read by the session-end hook, not by you; an item in it is still unchecked now.',
12
+ extension: INTERACTIVE_BASE,
13
+ capture: 'Capture run: these flags do not stop a correction the person stated or a merge a save refusal asks ' +
14
+ 'for. If the memory you would update is superseded, use the newer one instead (find it with ' +
15
+ 'memory_recall) and update it only if it is also wrong. Do not check, fix code drift, pass source or ' +
16
+ 'mark anything stale. Nothing from this run reaches the background check.',
17
+ cli: 'The background check does not see CLI runs. Before relying on an item under attention or ' +
18
+ 'notJudged, read it with memory_get in an MCP session and follow what that result says; with no MCP ' +
19
+ 'session, name it to the person as not checked.'
20
+ };
21
+ const ATTENTION_CAP = 20;
22
+ const NOT_JUDGED_CAP = 20;
23
+ const BACKGROUND_CHECK_CAP = 10;
24
+ const UID_PATTERN = /^[A-Za-z0-9_-]+$/;
25
+ const ITEM_TYPES = ['Fact', 'Skill', 'Scenario', 'Wiki'];
26
+ const RECALL_GROUPS = [
27
+ ['facts', 'Fact'],
28
+ ['skills', 'Skill'],
29
+ ['scenarios', 'Scenario'],
30
+ ['pages', 'Wiki']
31
+ ];
32
+ function asRecord(value) {
33
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
34
+ ? value
35
+ : null;
36
+ }
37
+ function asItemType(value) {
38
+ return typeof value === 'string' && ITEM_TYPES.includes(value) ? value : null;
39
+ }
40
+ function entriesOf(value) {
41
+ if (!Array.isArray(value))
42
+ return [];
43
+ const entries = [];
44
+ for (const entry of value) {
45
+ const record = asRecord(entry);
46
+ if (record)
47
+ entries.push(record);
48
+ }
49
+ return entries;
50
+ }
51
+ function flagsOf(entry) {
52
+ const check = asRecord(entry.check);
53
+ return {
54
+ due: check !== null && (check.due === true || check.unknown === true),
55
+ stale: asRecord(entry.staleness) !== null,
56
+ superseded: entry.superseded === true,
57
+ upstream: Array.isArray(entry.upstream) && entry.upstream.length > 0
58
+ };
59
+ }
60
+ function returnedStrings(returned) {
61
+ const strings = new Set();
62
+ const visited = new Set();
63
+ const pending = [returned];
64
+ while (pending.length > 0) {
65
+ const value = pending.pop();
66
+ if (typeof value === 'string') {
67
+ strings.add(value);
68
+ }
69
+ else if (typeof value === 'object' && value !== null && !visited.has(value)) {
70
+ visited.add(value);
71
+ for (const child of Object.values(value))
72
+ pending.push(child);
73
+ }
74
+ }
75
+ return strings;
76
+ }
77
+ function sortItems(items, returned) {
78
+ const way = (item) => (item.viaGet ? 0 : item.viaRecall ? 1 : 2);
79
+ const isReturned = (item) => (returned.has(item.uid) ? 0 : 1);
80
+ return [...items].sort((a, b) => isReturned(a) - isReturned(b) || way(a) - way(b) || a.firstRead - b.firstRead);
81
+ }
82
+ function statusSentence(report, judgedCount, repoName, leftOut) {
83
+ if (report.reads.finished === 0)
84
+ return 'No hub read finished. Nothing was checked; do not rely on this run.';
85
+ if (report.reads.failed > 0)
86
+ return `${report.reads.failed} hub reads failed; the result may be incomplete.`;
87
+ if (report.attentionMore > 0 || report.notJudgedMore > 0) {
88
+ return `${leftOut} more items are flagged but not listed: memory_get any item you rely on that is not listed here.`;
89
+ }
90
+ if (report.attention.length === 0 && report.notJudged.length === 0) {
91
+ return (`No flag was found on the ${judgedCount} items read with get or recall. ` +
92
+ 'This is not a verification: an item that cites no file is never marked stale, and staleness ' +
93
+ `covers only ${repoName ?? 'no repo here'}.`);
94
+ }
95
+ return '';
96
+ }
97
+ function buildRunReport(input) {
98
+ const items = new Map();
99
+ const observe = (readIndex, via, type, entry) => {
100
+ const uid = entry.uid;
101
+ if (!type || typeof uid !== 'string' || !UID_PATTERN.test(uid))
102
+ return;
103
+ const key = `${type}${uid}`;
104
+ let item = items.get(key);
105
+ if (!item) {
106
+ item = {
107
+ type,
108
+ uid,
109
+ firstRead: readIndex,
110
+ viaGet: false,
111
+ viaRecall: false,
112
+ flags: { due: false, stale: false, superseded: false, upstream: false }
113
+ };
114
+ items.set(key, item);
115
+ }
116
+ if (via === 'get')
117
+ item.viaGet = true;
118
+ else if (via === 'recall')
119
+ item.viaRecall = true;
120
+ else
121
+ item.listedVia ??= via;
122
+ const flags = flagsOf(entry);
123
+ for (const reason of Object.keys(flags))
124
+ item.flags[reason] ||= flags[reason];
125
+ };
126
+ input.reads.forEach((read, index) => {
127
+ if (!read.ok)
128
+ return;
129
+ const result = asRecord(read.result);
130
+ if (!result)
131
+ return;
132
+ const inputType = asItemType(read.input?.type);
133
+ switch (read.fn) {
134
+ case 'get':
135
+ observe(index, 'get', inputType, result);
136
+ break;
137
+ case 'recall':
138
+ for (const [group, groupType] of RECALL_GROUPS) {
139
+ for (const entry of entriesOf(result[group]))
140
+ observe(index, 'recall', inputType ?? groupType, entry);
141
+ }
142
+ break;
143
+ case 'list':
144
+ for (const entry of entriesOf(result.items)) {
145
+ observe(index, 'list', inputType, entry);
146
+ }
147
+ break;
148
+ case 'related':
149
+ for (const entry of entriesOf(result.related))
150
+ observe(index, 'related', asItemType(entry.type), entry);
151
+ break;
152
+ case 'checkSources':
153
+ for (const entry of entriesOf(result.items)) {
154
+ observe(index, 'checkSources', asItemType(entry.type), entry);
155
+ }
156
+ break;
157
+ }
158
+ });
159
+ const returned = returnedStrings(input.returned);
160
+ const all = [...items.values()];
161
+ const reasonsOf = (item) => ['due', 'stale', 'superseded', 'upstream'].filter(reason => item.flags[reason]);
162
+ const flagged = sortItems(all.filter(item => reasonsOf(item).length > 0), returned);
163
+ const notJudged = sortItems(all.filter(item => !item.viaGet && !item.viaRecall && item.listedVia), returned);
164
+ const background = input.mode === 'interactive'
165
+ ? sortItems(all.filter(item => (item.viaGet || item.viaRecall) && item.flags.due), returned)
166
+ : [];
167
+ const report = {
168
+ reads: {
169
+ finished: input.reads.filter(read => read.ok).length,
170
+ failed: input.reads.filter(read => !read.ok).length
171
+ },
172
+ attention: flagged
173
+ .slice(0, ATTENTION_CAP)
174
+ .map(item => ({ type: item.type, uid: item.uid, reasons: reasonsOf(item) })),
175
+ attentionMore: Math.max(0, flagged.length - ATTENTION_CAP),
176
+ notJudged: notJudged.slice(0, NOT_JUDGED_CAP).map(item => ({
177
+ type: item.type,
178
+ uid: item.uid,
179
+ seenVia: item.listedVia
180
+ })),
181
+ notJudgedMore: Math.max(0, notJudged.length - NOT_JUDGED_CAP),
182
+ forBackgroundCheck: background.slice(0, BACKGROUND_CHECK_CAP).map(item => ({
183
+ type: item.type,
184
+ uid: item.uid,
185
+ via: item.viaGet ? 'get' : 'recall'
186
+ })),
187
+ forBackgroundCheckMore: Math.max(0, background.length - BACKGROUND_CHECK_CAP),
188
+ notices: [...new Set(input.notices)]
189
+ };
190
+ const judgedCount = all.filter(item => item.viaGet || item.viaRecall).length;
191
+ const leftOut = new Set([...flagged.slice(ATTENTION_CAP), ...notJudged.slice(NOT_JUDGED_CAP)]).size;
192
+ const status = statusSentence(report, judgedCount, input.repoName, leftOut);
193
+ return { ...report, next: exports.MODE_LINES[input.mode] + (status ? ` ${status}` : '') };
194
+ }
195
+ exports.buildRunReport = buildRunReport;
@@ -0,0 +1,393 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const worker_threads_1 = require("worker_threads");
7
+ const quickjs_emscripten_core_1 = require("quickjs-emscripten-core");
8
+ const quickjs_singlefile_cjs_release_sync_1 = __importDefault(require("@jitl/quickjs-singlefile-cjs-release-sync"));
9
+ const SCRIPT_FILE = 'eval.js';
10
+ const SCRIPT_FRAME = /[\s(]eval\.js:(\d+):/;
11
+ const PRELUDE_FILE = 'prelude.js';
12
+ const JOB_BATCH = 100;
13
+ const DROPPED_POST_MS = 100;
14
+ const TIME = { kind: 'limit', limit: 'time' };
15
+ const MEMORY = { kind: 'limit', limit: 'memory' };
16
+ const WASM_PAGE = 65_536;
17
+ // The module's memory import declares 256 pages; fewer fail to link.
18
+ const INITIAL_PAGES = 256;
19
+ // Static data and stack take the first 5.2 MB, before QuickJS's heap starts.
20
+ const MODULE_HEADROOM_BYTES = 8 * 1024 * 1024;
21
+ // The glue retries a refused heap growth with two smaller sizes before malloc fails.
22
+ const REFUSALS_PER_FAILED_GROWTH = 3;
23
+ // QuickJS refuses an allocation over its own limit before malloc, out of the grow latch's sight, so its limit sits at the glue's 2 GiB ceiling.
24
+ const QUICKJS_LIMIT_BYTES = 2 ** 31;
25
+ // V8's overflow of the worker's smaller stack unwinds QuickJS uncaught, so QuickJS's own, catchable check is only a backstop inside its 5 MiB stack.
26
+ const QUICKJS_STACK_BYTES = 4 * 1024 * 1024;
27
+ const LIMIT_BY_MESSAGE = new Map([
28
+ ['interrupted', 'time'],
29
+ ['out of memory', 'memory'],
30
+ ['stack overflow', 'stack'],
31
+ ]);
32
+ const PRELUDE = `(function (call, log, unknownMember, namesJson) {
33
+ const { parse, stringify } = JSON
34
+ const BaseError = Error
35
+ const toText = String
36
+ const create = Object.create
37
+ const read = (get) => {
38
+ try {
39
+ return get()
40
+ } catch (error) {
41
+ return undefined
42
+ }
43
+ }
44
+ const text = (value) => {
45
+ if (typeof value === 'string') return value
46
+ const json = read(() => stringify(value))
47
+ if (json !== undefined) return json
48
+ try {
49
+ return toText(value)
50
+ } catch (error) {
51
+ return '[unloggable]'
52
+ }
53
+ }
54
+ const typed = (get, type) => {
55
+ const value = read(get)
56
+ return typeof value === type ? value : undefined
57
+ }
58
+ const functions = create(null)
59
+ for (const name of parse(namesJson)) {
60
+ functions[name] = async (input) => {
61
+ const json = stringify(input)
62
+ return call(name, json, json === undefined ? 0 : json.length)
63
+ }
64
+ }
65
+ globalThis.hub = new Proxy(create(null), {
66
+ get(target, name) {
67
+ if (typeof name === 'symbol' || name === 'then') return undefined
68
+ if (name in functions) return functions[name]
69
+ throw new BaseError(unknownMember(name))
70
+ },
71
+ })
72
+ globalThis.console = {
73
+ log: (...values) => {
74
+ let line = ''
75
+ for (let i = 0; i < values.length; i++) line += (i === 0 ? '' : ' ') + text(values[i])
76
+ log(line, line.length)
77
+ },
78
+ }
79
+ const toJson = (value) => stringify(value) ?? 'null'
80
+ const describe = (error) => {
81
+ const description = create(null)
82
+ if (read(() => error instanceof BaseError)) {
83
+ description.name = text(read(() => error.name))
84
+ description.message = text(read(() => error.message))
85
+ description.fileName = typed(() => error.fileName, 'string')
86
+ description.lineNumber = typed(() => error.lineNumber, 'number')
87
+ description.stack = typed(() => error.stack, 'string')
88
+ } else {
89
+ description.text = text(error)
90
+ }
91
+ return stringify(description)
92
+ }
93
+ return [toJson, describe, parse]
94
+ })`;
95
+ function messageOf(error) {
96
+ return error instanceof Error ? error.message : String(error);
97
+ }
98
+ function errorText(description) {
99
+ if (description.text !== undefined)
100
+ return description.text;
101
+ const name = description.name ?? 'Error';
102
+ if (!description.message)
103
+ return name;
104
+ return name === 'Error' ? description.message : `${name}: ${description.message}`;
105
+ }
106
+ function wrapperLine(description) {
107
+ if (description.name === 'SyntaxError' && description.fileName === SCRIPT_FILE && description.lineNumber !== undefined) {
108
+ return description.lineNumber;
109
+ }
110
+ const frame = description.stack === undefined ? null : SCRIPT_FRAME.exec(description.stack);
111
+ return frame ? Number(frame[1]) : undefined;
112
+ }
113
+ function scriptResult(description, scriptLines) {
114
+ const limit = description.name === 'InternalError' ? LIMIT_BY_MESSAGE.get(description.message ?? '') : undefined;
115
+ if (limit)
116
+ return { kind: 'limit', limit };
117
+ const message = errorText(description);
118
+ const line = wrapperLine(description);
119
+ if (line === undefined)
120
+ return { kind: 'error', message };
121
+ return { kind: 'error', message, line: Math.min(Math.max(line - 1, 1), scriptLines) };
122
+ }
123
+ function cutLine(line, room) {
124
+ const last = line.charCodeAt(room - 1);
125
+ return line.slice(0, last >= 0xd800 && last <= 0xdbff ? room - 1 : room);
126
+ }
127
+ function isHostStackOverflow(error) {
128
+ return error instanceof RangeError && error.message.includes('call stack');
129
+ }
130
+ function hostFailure(error) {
131
+ if (isHostStackOverflow(error))
132
+ return { kind: 'limit', limit: 'stack' };
133
+ return { kind: 'error', message: `The sandbox failed: ${messageOf(error)}` };
134
+ }
135
+ function unconvertible(reason) {
136
+ return { kind: 'error', message: `The script's return value could not be turned into JSON (${reason}).` };
137
+ }
138
+ // QuickJS cannot see allocation sizes in this build (no malloc_usable_size), so the WASM memory itself is the limit.
139
+ async function loadCapped(memoryBytes, onExhausted) {
140
+ const maximum = Math.max(INITIAL_PAGES, Math.ceil((memoryBytes + MODULE_HEADROOM_BYTES) / WASM_PAGE));
141
+ const memory = new WebAssembly.Memory({ initial: INITIAL_PAGES, maximum });
142
+ const grow = memory.grow.bind(memory);
143
+ let refusals = 0;
144
+ memory.grow = (delta) => {
145
+ try {
146
+ const previous = grow(delta);
147
+ refusals = 0;
148
+ return previous;
149
+ }
150
+ catch (error) {
151
+ if (++refusals >= REFUSALS_PER_FAILED_GROWTH)
152
+ onExhausted();
153
+ throw error;
154
+ }
155
+ };
156
+ let loaded;
157
+ const hooks = {
158
+ postRun: [
159
+ (module) => {
160
+ loaded = module;
161
+ },
162
+ ],
163
+ };
164
+ const QuickJS = await (0, quickjs_emscripten_core_1.newQuickJSWASMModuleFromVariant)((0, quickjs_emscripten_core_1.newVariant)(quickjs_singlefile_cjs_release_sync_1.default, { wasmMemory: memory, emscriptenModule: hooks }));
165
+ if (!loaded || loaded.HEAPU8.buffer !== memory.buffer)
166
+ throw new Error('its WASM memory could not be capped.');
167
+ const malloc = loaded._malloc;
168
+ // The core library writes through whatever pointer malloc returns, even 0.
169
+ loaded._malloc = (size) => {
170
+ const pointer = malloc(size);
171
+ if (pointer === 0 && size > 0) {
172
+ onExhausted();
173
+ throw new Error('out of memory');
174
+ }
175
+ return pointer;
176
+ };
177
+ return QuickJS;
178
+ }
179
+ async function run(port, input) {
180
+ const { script, names, unknownMember, deadline, maxLogChars, maxPendingCallChars } = input;
181
+ const scriptLines = script.split('\n').length;
182
+ const pending = new Map();
183
+ const outbox = [];
184
+ let nextId = 0;
185
+ let settled = false;
186
+ let interrupted = false;
187
+ let outOfMemory = false;
188
+ let forwardedChars = 0;
189
+ let droppedChars = 0;
190
+ let postedDropped = 0;
191
+ let nextDroppedPost = 0;
192
+ let pendingCallChars = 0;
193
+ const post = (message) => {
194
+ if (!settled)
195
+ port.postMessage(message);
196
+ };
197
+ // QuickJS turns its interrupt and out-of-memory errors into catchable rejections, so once either fires it decides the outcome.
198
+ const finish = (result) => {
199
+ if (settled)
200
+ return;
201
+ settled = true;
202
+ const done = { type: 'done', result: interrupted ? TIME : outOfMemory ? MEMORY : result, droppedChars };
203
+ try {
204
+ port.postMessage(done);
205
+ }
206
+ catch (error) {
207
+ // Posting copies the value, and the worker's stack runs out on one nested a few thousand levels deep.
208
+ const unsent = { type: 'done', result: unconvertible(messageOf(error)), droppedChars };
209
+ port.postMessage(unsent);
210
+ }
211
+ };
212
+ const postDropped = () => {
213
+ if (droppedChars === postedDropped)
214
+ return;
215
+ postedDropped = droppedChars;
216
+ nextDroppedPost = Date.now() + DROPPED_POST_MS;
217
+ post({ type: 'dropped', chars: droppedChars });
218
+ };
219
+ // A synchronous loop never ends its step, so drops are also posted every DROPPED_POST_MS; the host may terminate the worker at any point.
220
+ const drop = (chars) => {
221
+ droppedChars += chars;
222
+ if (Date.now() >= nextDroppedPost)
223
+ postDropped();
224
+ };
225
+ // Every line is charged one extra character for its line break, so empty lines use up the cap too.
226
+ const forward = (line) => {
227
+ const room = maxLogChars - forwardedChars - 1;
228
+ if (line.length <= room) {
229
+ forwardedChars += line.length + 1;
230
+ post({ type: 'log', line });
231
+ return;
232
+ }
233
+ forwardedChars = maxLogChars;
234
+ const sent = room > 0 ? cutLine(line, room) : '';
235
+ if (sent)
236
+ post({ type: 'log', line: sent });
237
+ drop(sent ? line.length - sent.length : line.length + 1);
238
+ };
239
+ try {
240
+ const QuickJS = await loadCapped(input.memoryBytes, () => {
241
+ outOfMemory = true;
242
+ });
243
+ const runtime = QuickJS.newRuntime();
244
+ runtime.setMemoryLimit(QUICKJS_LIMIT_BYTES);
245
+ runtime.setMaxStackSize(QUICKJS_STACK_BYTES);
246
+ runtime.setInterruptHandler(() => {
247
+ if (outOfMemory)
248
+ return true;
249
+ if (Date.now() < deadline)
250
+ return false;
251
+ interrupted = true;
252
+ return true;
253
+ });
254
+ const vm = runtime.newContext();
255
+ const args = [
256
+ // Payloads waiting for an answer live outside QuickJS's memory limit, and V8 may keep them off its heap too.
257
+ vm.newFunction('call', (nameHandle, inputHandle, lengthHandle) => {
258
+ if (settled)
259
+ throw new Error('The run has ended.');
260
+ const chars = vm.getNumber(lengthHandle);
261
+ if (pendingCallChars + chars > maxPendingCallChars) {
262
+ finish(MEMORY);
263
+ throw new Error('Pending hub calls hold more data than the run allows.');
264
+ }
265
+ pendingCallChars += chars;
266
+ const id = nextId++;
267
+ const deferred = vm.newPromise();
268
+ pending.set(id, { deferred, chars });
269
+ const json = vm.typeof(inputHandle) === 'string' ? vm.getString(inputHandle) : undefined;
270
+ outbox.push({ type: 'call', id, name: vm.getString(nameHandle), json });
271
+ return deferred.handle;
272
+ }),
273
+ vm.newFunction('log', (line, length) => {
274
+ if (vm.typeof(line) !== 'string')
275
+ return;
276
+ if (forwardedChars >= maxLogChars)
277
+ drop(vm.getNumber(length) + 1);
278
+ else
279
+ forward(vm.getString(line));
280
+ }),
281
+ vm.newFunction('unknownMember', (name) => vm.newString(unknownMember.split('{name}').join(vm.getString(name)))),
282
+ vm.newString(JSON.stringify(names)),
283
+ ];
284
+ const prelude = vm.unwrapResult(vm.evalCode(PRELUDE, PRELUDE_FILE, { type: 'global' }));
285
+ const helpers = prelude.consume((fn) => vm.unwrapResult(vm.callFunction(fn, vm.undefined, args)));
286
+ const toJson = vm.getProp(helpers, 0);
287
+ const describe = vm.getProp(helpers, 1);
288
+ const parse = vm.getProp(helpers, 2);
289
+ helpers.dispose();
290
+ for (const handle of args)
291
+ handle.dispose();
292
+ const explain = (error) => {
293
+ const described = vm.callFunction(describe, vm.undefined, error);
294
+ if (described.error) {
295
+ described.error.dispose();
296
+ return { kind: 'limit', limit: Date.now() >= deadline ? 'time' : 'memory' };
297
+ }
298
+ return scriptResult(JSON.parse(described.value.consume(vm.getString)), scriptLines);
299
+ };
300
+ const convert = (value) => {
301
+ const converted = vm.callFunction(toJson, vm.undefined, value);
302
+ if (converted.error) {
303
+ const result = converted.error.consume(explain);
304
+ if (result.kind !== 'error')
305
+ return result;
306
+ return { ...result, ...unconvertible(result.message) };
307
+ }
308
+ return { kind: 'ok', value: JSON.parse(converted.value.consume(vm.getString)) };
309
+ };
310
+ // Parsed here rather than in the prelude, so a failure ends the run instead of reaching the script's catch.
311
+ const deliver = (id, deferred, json) => {
312
+ const text = vm.newString(json);
313
+ if (vm.typeof(text) !== 'string') {
314
+ outOfMemory = true;
315
+ return;
316
+ }
317
+ const parsed = text.consume((handle) => vm.callFunction(parse, vm.undefined, handle));
318
+ if (parsed.error) {
319
+ const result = outOfMemory ? MEMORY : parsed.error.consume(explain);
320
+ return finish(result.kind === 'limit' ? result : MEMORY);
321
+ }
322
+ parsed.value.consume(deferred.resolve);
323
+ post({ type: 'delivered', id });
324
+ };
325
+ const evaluated = vm.evalCode(`(async () => {\n${script}\n})()`, SCRIPT_FILE, { type: 'global' });
326
+ if (evaluated.error)
327
+ return finish(evaluated.error.consume(explain));
328
+ const promise = evaluated.value;
329
+ // Bounded batches return to this loop, so a chain of jobs that never empties still meets the deadline.
330
+ const step = () => {
331
+ if (settled)
332
+ return;
333
+ for (;;) {
334
+ if (outOfMemory)
335
+ return finish(MEMORY);
336
+ const jobs = runtime.executePendingJobs(JOB_BATCH);
337
+ if (jobs.error)
338
+ return finish(outOfMemory ? MEMORY : jobs.error.consume(explain));
339
+ if (Date.now() >= deadline)
340
+ return finish(TIME);
341
+ if (jobs.value < JOB_BATCH)
342
+ break;
343
+ }
344
+ if (outOfMemory)
345
+ return finish(MEMORY);
346
+ const state = vm.getPromiseState(promise);
347
+ if (state.type === 'pending') {
348
+ for (const message of outbox.splice(0))
349
+ post(message);
350
+ postDropped();
351
+ return;
352
+ }
353
+ if (state.type === 'rejected')
354
+ return finish(state.error.consume(explain));
355
+ try {
356
+ finish(state.notAPromise ? convert(state.value) : state.value.consume(convert));
357
+ }
358
+ catch (error) {
359
+ // JSON.stringify runs out of V8 stack on a value nested a few thousand levels deep.
360
+ finish(isHostStackOverflow(error) ? unconvertible(messageOf(error)) : hostFailure(error));
361
+ }
362
+ };
363
+ port.on('message', (answer) => {
364
+ const call = pending.get(answer.id);
365
+ if (settled || !call)
366
+ return;
367
+ pending.delete(answer.id);
368
+ pendingCallChars -= call.chars;
369
+ const { deferred } = call;
370
+ try {
371
+ if (answer.ok)
372
+ deliver(answer.id, deferred, answer.json);
373
+ else
374
+ vm.newError(answer.message).consume(deferred.reject);
375
+ if (outOfMemory)
376
+ finish(MEMORY);
377
+ if (settled)
378
+ return;
379
+ deferred.dispose();
380
+ step();
381
+ }
382
+ catch (error) {
383
+ finish(hostFailure(error));
384
+ }
385
+ });
386
+ step();
387
+ }
388
+ catch (error) {
389
+ finish(hostFailure(error));
390
+ }
391
+ }
392
+ if (worker_threads_1.parentPort)
393
+ void run(worker_threads_1.parentPort, worker_threads_1.workerData);