@milaboratories/pl-mcp-server 54.0.0 → 55.0.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 +15 -25
- package/dist/_virtual/_rolldown/runtime.cjs +22 -0
- package/dist/agent-tables.cjs +116 -0
- package/dist/agent-tables.cjs.map +1 -0
- package/dist/agent-tables.js +115 -0
- package/dist/agent-tables.js.map +1 -0
- package/dist/instructions.cjs +15 -12
- package/dist/instructions.cjs.map +1 -1
- package/dist/instructions.js +15 -12
- package/dist/instructions.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/project-holds.cjs +58 -8
- package/dist/project-holds.cjs.map +1 -1
- package/dist/project-holds.js +58 -8
- package/dist/project-holds.js.map +1 -1
- package/dist/project-list.cjs +16 -0
- package/dist/project-list.cjs.map +1 -0
- package/dist/project-list.js +16 -0
- package/dist/project-list.js.map +1 -0
- package/dist/server-log.cjs +40 -18
- package/dist/server-log.cjs.map +1 -1
- package/dist/server-log.js +40 -19
- package/dist/server-log.js.map +1 -1
- package/dist/server.cjs +48 -18
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +21 -20
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +48 -18
- package/dist/server.js.map +1 -1
- package/dist/tools/agent-tables.cjs +424 -0
- package/dist/tools/agent-tables.cjs.map +1 -0
- package/dist/tools/agent-tables.js +417 -0
- package/dist/tools/agent-tables.js.map +1 -0
- package/dist/tools/await.cjs +216 -73
- package/dist/tools/await.cjs.map +1 -1
- package/dist/tools/await.js +212 -75
- package/dist/tools/await.js.map +1 -1
- package/dist/tools/block-action-context.cjs +3 -0
- package/dist/tools/block-action-context.cjs.map +1 -1
- package/dist/tools/block-action-context.js +3 -0
- package/dist/tools/block-action-context.js.map +1 -1
- package/dist/tools/block-api.cjs +17 -2
- package/dist/tools/block-api.cjs.map +1 -1
- package/dist/tools/block-api.js +17 -3
- package/dist/tools/block-api.js.map +1 -1
- package/dist/tools/block-params.cjs +272 -4
- package/dist/tools/block-params.cjs.map +1 -1
- package/dist/tools/block-params.js +270 -6
- package/dist/tools/block-params.js.map +1 -1
- package/dist/tools/block-state.cjs +323 -42
- package/dist/tools/block-state.cjs.map +1 -1
- package/dist/tools/block-state.js +317 -46
- package/dist/tools/block-state.js.map +1 -1
- package/dist/tools/block-storage.cjs +153 -0
- package/dist/tools/block-storage.cjs.map +1 -0
- package/dist/tools/block-storage.js +147 -0
- package/dist/tools/block-storage.js.map +1 -0
- package/dist/tools/block-updates.cjs +405 -0
- package/dist/tools/block-updates.cjs.map +1 -0
- package/dist/tools/block-updates.js +397 -0
- package/dist/tools/block-updates.js.map +1 -0
- package/dist/tools/blocks.cjs +183 -70
- package/dist/tools/blocks.cjs.map +1 -1
- package/dist/tools/blocks.js +177 -70
- package/dist/tools/blocks.js.map +1 -1
- package/dist/tools/data-query.cjs +451 -113
- package/dist/tools/data-query.cjs.map +1 -1
- package/dist/tools/data-query.js +446 -118
- package/dist/tools/data-query.js.map +1 -1
- package/dist/tools/errors.cjs +21 -0
- package/dist/tools/errors.cjs.map +1 -0
- package/dist/tools/errors.js +20 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/files.cjs +643 -0
- package/dist/tools/files.cjs.map +1 -0
- package/dist/tools/files.js +613 -0
- package/dist/tools/files.js.map +1 -0
- package/dist/tools/ids.cjs +56 -0
- package/dist/tools/ids.cjs.map +1 -1
- package/dist/tools/ids.js +51 -2
- package/dist/tools/ids.js.map +1 -1
- package/dist/tools/imports.cjs +195 -0
- package/dist/tools/imports.cjs.map +1 -0
- package/dist/tools/imports.js +186 -0
- package/dist/tools/imports.js.map +1 -0
- package/dist/tools/logs.cjs +98 -19
- package/dist/tools/logs.cjs.map +1 -1
- package/dist/tools/logs.js +95 -20
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/paging.cjs +27 -0
- package/dist/tools/paging.cjs.map +1 -0
- package/dist/tools/paging.js +26 -0
- package/dist/tools/paging.js.map +1 -0
- package/dist/tools/params-merge.cjs +106 -0
- package/dist/tools/params-merge.cjs.map +1 -0
- package/dist/tools/params-merge.js +106 -0
- package/dist/tools/params-merge.js.map +1 -0
- package/dist/tools/project-template.cjs +75 -0
- package/dist/tools/project-template.cjs.map +1 -0
- package/dist/tools/project-template.js +72 -0
- package/dist/tools/project-template.js.map +1 -0
- package/dist/tools/projects.cjs +66 -19
- package/dist/tools/projects.cjs.map +1 -1
- package/dist/tools/projects.js +66 -20
- package/dist/tools/projects.js.map +1 -1
- package/dist/tools/readiness.cjs +104 -0
- package/dist/tools/readiness.cjs.map +1 -0
- package/dist/tools/readiness.js +99 -0
- package/dist/tools/readiness.js.map +1 -0
- package/dist/tools/result-pool.cjs +260 -0
- package/dist/tools/result-pool.cjs.map +1 -0
- package/dist/tools/result-pool.js +252 -0
- package/dist/tools/result-pool.js.map +1 -0
- package/dist/tools/sandbox.cjs +112 -14
- package/dist/tools/sandbox.cjs.map +1 -1
- package/dist/tools/sandbox.js +110 -15
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/sdk-types.cjs +24 -0
- package/dist/tools/sdk-types.cjs.map +1 -0
- package/dist/tools/sdk-types.js +24 -0
- package/dist/tools/sdk-types.js.map +1 -0
- package/dist/tools/settle.cjs +155 -0
- package/dist/tools/settle.cjs.map +1 -0
- package/dist/tools/settle.js +148 -0
- package/dist/tools/settle.js.map +1 -0
- package/dist/tools/tokens.cjs +49 -8
- package/dist/tools/tokens.cjs.map +1 -1
- package/dist/tools/tokens.js +45 -9
- package/dist/tools/tokens.js.map +1 -1
- package/dist/tools/types.cjs +62 -11
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js +60 -12
- package/dist/tools/types.js.map +1 -1
- package/dist/tools/value-outline.cjs +119 -0
- package/dist/tools/value-outline.cjs.map +1 -0
- package/dist/tools/value-outline.js +117 -0
- package/dist/tools/value-outline.js.map +1 -0
- package/package.json +9 -8
- package/src/agent-tables.test.ts +246 -0
- package/src/agent-tables.ts +145 -0
- package/src/instructions.ts +15 -12
- package/src/project-holds.test.ts +179 -0
- package/src/project-holds.ts +114 -12
- package/src/project-list.test.ts +38 -0
- package/src/project-list.ts +25 -0
- package/src/server-log.test.ts +54 -1
- package/src/server-log.ts +49 -27
- package/src/server.logging.test.ts +38 -46
- package/src/server.test.ts +151 -17
- package/src/server.ts +62 -34
- package/src/tools/agent-tables.test.ts +650 -0
- package/src/tools/agent-tables.ts +673 -0
- package/src/tools/await.test.ts +287 -0
- package/src/tools/await.ts +393 -123
- package/src/tools/block-action-context.ts +3 -0
- package/src/tools/block-api.ts +19 -4
- package/src/tools/block-params.test.ts +828 -0
- package/src/tools/block-params.ts +623 -8
- package/src/tools/block-state.test.ts +480 -0
- package/src/tools/block-state.ts +659 -66
- package/src/tools/block-storage.test.ts +270 -0
- package/src/tools/block-storage.ts +195 -0
- package/src/tools/block-updates.test.ts +605 -0
- package/src/tools/block-updates.ts +751 -0
- package/src/tools/blocks.test.ts +169 -22
- package/src/tools/blocks.ts +336 -105
- package/src/tools/data-query.test.ts +641 -0
- package/src/tools/data-query.ts +807 -157
- package/src/tools/errors.test.ts +33 -0
- package/src/tools/errors.ts +23 -0
- package/src/tools/files.test.ts +842 -0
- package/src/tools/files.ts +990 -0
- package/src/tools/ids.test.ts +87 -0
- package/src/tools/ids.ts +67 -0
- package/src/tools/imports.ts +304 -0
- package/src/tools/logs.test.ts +70 -0
- package/src/tools/logs.ts +130 -21
- package/src/tools/paging.test.ts +39 -0
- package/src/tools/paging.ts +39 -0
- package/src/tools/params-merge.test.ts +274 -0
- package/src/tools/params-merge.ts +149 -0
- package/src/tools/project-template.test.ts +230 -0
- package/src/tools/project-template.ts +135 -0
- package/src/tools/projects.test.ts +122 -0
- package/src/tools/projects.ts +135 -25
- package/src/tools/readiness.test.ts +195 -0
- package/src/tools/readiness.ts +189 -0
- package/src/tools/result-pool.test.ts +377 -0
- package/src/tools/result-pool.ts +483 -0
- package/src/tools/sandbox.test.ts +128 -10
- package/src/tools/sandbox.ts +132 -18
- package/src/tools/sdk-types.ts +54 -0
- package/src/tools/settle.test.ts +340 -0
- package/src/tools/settle.ts +312 -0
- package/src/tools/tokens.ts +74 -9
- package/src/tools/types.ts +77 -12
- package/src/tools/value-outline.ts +143 -0
- package/dist/tools/screenshot.cjs +0 -44
- package/dist/tools/screenshot.cjs.map +0 -1
- package/dist/tools/screenshot.js +0 -44
- package/dist/tools/screenshot.js.map +0 -1
- package/dist/tools/ui-interaction.cjs +0 -140
- package/dist/tools/ui-interaction.cjs.map +0 -1
- package/dist/tools/ui-interaction.js +0 -140
- package/dist/tools/ui-interaction.js.map +0 -1
- package/src/tools/screenshot.ts +0 -61
- package/src/tools/ui-interaction.ts +0 -184
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
let _milaboratories_helpers = require("@milaboratories/helpers");
|
|
2
|
+
let es_toolkit = require("es-toolkit");
|
|
3
|
+
let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
|
|
4
|
+
// src/tools/settle.ts
|
|
5
|
+
/** The shortest time one look at the block takes, so a computable that changes all the time does not spin. */
|
|
6
|
+
const MIN_ITERATION_MS = 100;
|
|
7
|
+
/**
|
|
8
|
+
* The longest one look at the block waits for a change before looking again: a wait on a block
|
|
9
|
+
* that does not change still wakes on schedule, so its progress notifications go out.
|
|
10
|
+
*/
|
|
11
|
+
const WAKE_INTERVAL_MS = 5e3;
|
|
12
|
+
/**
|
|
13
|
+
* Waits until every output of a block is either computed (stable) or failed. Only the outputs of
|
|
14
|
+
* this block count: the block state's own `stable` flag also waits for the titles of every other
|
|
15
|
+
* block of the project.
|
|
16
|
+
*
|
|
17
|
+
* Returns early, unsettled, when the pending outputs wait for an upstream block that is running
|
|
18
|
+
* or has not run: the block state is marked `prod_not_locked:<id>` or `no_data:<id>:<export>` and
|
|
19
|
+
* block `<id>` is running (the outputs settle only after it finishes, which may take longer than
|
|
20
|
+
* any wait here), or is not calculated or in limbo (they settle only after somebody runs it).
|
|
21
|
+
* (With `waitForRun` and the block itself running, the wait goes on: the run includes the
|
|
22
|
+
* upstream.)
|
|
23
|
+
*/
|
|
24
|
+
async function awaitBlockSettled(project, blockId, options) {
|
|
25
|
+
const start = Date.now();
|
|
26
|
+
return await withDeadline(options.timeoutMs, options.signal, (signal) => settleLoop(project, blockId, options, start, signal));
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Runs `wait` with a signal that fires when `signal` (the request's) does or `timeoutMs` runs
|
|
30
|
+
* out, whichever comes first.
|
|
31
|
+
*/
|
|
32
|
+
async function withDeadline(timeoutMs, signal, wait) {
|
|
33
|
+
const deadline = new AbortController();
|
|
34
|
+
const deadlineTimer = setTimeout(() => deadline.abort(), Math.max(0, timeoutMs));
|
|
35
|
+
try {
|
|
36
|
+
return await wait(signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal);
|
|
37
|
+
} finally {
|
|
38
|
+
clearTimeout(deadlineTimer);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* One wait of a waiting loop for a computable to change from `uTag`: it ends on the change, on
|
|
43
|
+
* `signal`, or after {@link WAKE_INTERVAL_MS} without a change (so the loop looks again and sends
|
|
44
|
+
* its progress), and not before {@link MIN_ITERATION_MS} after `iterationStart` (so a computable
|
|
45
|
+
* that changes all the time does not spin).
|
|
46
|
+
*/
|
|
47
|
+
async function awaitChangeOrWake(computable, uTag, signal, iterationStart) {
|
|
48
|
+
const wake = new AbortController();
|
|
49
|
+
const wakeTimer = setTimeout(() => wake.abort(), WAKE_INTERVAL_MS);
|
|
50
|
+
try {
|
|
51
|
+
await computable.awaitChange(AbortSignal.any([signal, wake.signal]), uTag);
|
|
52
|
+
} catch {} finally {
|
|
53
|
+
clearTimeout(wakeTimer);
|
|
54
|
+
}
|
|
55
|
+
const spent = Date.now() - iterationStart;
|
|
56
|
+
if (spent < MIN_ITERATION_MS && !signal.aborted) await (0, es_toolkit.delay)(MIN_ITERATION_MS - spent, { signal }).catch(() => {});
|
|
57
|
+
}
|
|
58
|
+
async function settleLoop(project, blockId, options, start, signal) {
|
|
59
|
+
const computable = project.getBlockState(blockId);
|
|
60
|
+
for (;;) {
|
|
61
|
+
const iterationStart = Date.now();
|
|
62
|
+
const full = await computable.getFullValue();
|
|
63
|
+
const overview = await project.overview.getValue();
|
|
64
|
+
const blocks = overview?.blocks ?? [];
|
|
65
|
+
const block = blocks.find((b) => b.id === blockId);
|
|
66
|
+
const status = block?.calculationStatus;
|
|
67
|
+
const running = new Set(blocks.filter((b) => b.calculationStatus === "Running").map((b) => b.id));
|
|
68
|
+
const pendingOutputs = pendingOutputKeys(full.value.outputs);
|
|
69
|
+
const runningUpstreams = (block?.upstreams ?? []).filter((id) => running.has(id)).map(_milaboratories_pl_model_common.asBlockId);
|
|
70
|
+
const markerUpstream = upstreamOfMarker(full.unstableMarker);
|
|
71
|
+
const markerStatus = blocks.find((b) => b.id === markerUpstream)?.calculationStatus;
|
|
72
|
+
const upstreamHalt = markerStatus === "Running" ? "upstream-running" : markerStatus === "NotCalculated" || markerStatus === "Limbo" ? "upstream-not-run" : void 0;
|
|
73
|
+
const waitingOn = upstreamHalt === void 0 ? void 0 : markerUpstream;
|
|
74
|
+
const result = (settled, stoppedBy) => ({
|
|
75
|
+
settled,
|
|
76
|
+
...stoppedBy === void 0 ? {} : { stoppedBy },
|
|
77
|
+
waitedMs: Date.now() - start,
|
|
78
|
+
calculationStatus: status,
|
|
79
|
+
state: full.value,
|
|
80
|
+
pendingOutputs,
|
|
81
|
+
...waitingOn !== void 0 ? {
|
|
82
|
+
waitingOn,
|
|
83
|
+
waitingOnStatus: markerStatus
|
|
84
|
+
} : {},
|
|
85
|
+
runningUpstreams
|
|
86
|
+
});
|
|
87
|
+
if (overview !== void 0 && block === void 0) return result(false, "block-gone");
|
|
88
|
+
if (options.waitForRun && status === "NotCalculated") return result(false, "not-calculated");
|
|
89
|
+
if (options.waitForRun && status === "Limbo") return result(false, "limbo");
|
|
90
|
+
const runPending = options.waitForRun && status === "Running";
|
|
91
|
+
if (!runPending && full.value.outputs !== void 0 && pendingOutputs.length === 0) return result(true);
|
|
92
|
+
if (!runPending && pendingOutputs.length > 0 && upstreamHalt !== void 0) return result(false, upstreamHalt);
|
|
93
|
+
if (signal.aborted) return result(false, options.signal?.aborted ? "aborted" : "timeout");
|
|
94
|
+
options.onProgress?.(Date.now() - start, options.timeoutMs);
|
|
95
|
+
await awaitChangeOrWake(computable, full.uTag, signal, iterationStart);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** The keys of outputs that are computed but not final yet (`stable: false`). */
|
|
99
|
+
function pendingOutputKeys(outputs) {
|
|
100
|
+
if (outputs === void 0) return [];
|
|
101
|
+
return Object.entries(outputs).filter(([, o]) => typeof o === "object" && o !== null && "ok" in o && o.ok === true && "stable" in o && o.stable === false).map(([key]) => key);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The upstream block an unstable marker of the result pool names: `prod_not_locked:<id>` (the
|
|
105
|
+
* block's results are not final yet) or `no_data:<id>:<export>` (an export of it has no data yet).
|
|
106
|
+
*/
|
|
107
|
+
function upstreamOfMarker(marker) {
|
|
108
|
+
if (marker === void 0) return void 0;
|
|
109
|
+
const match = /^(?:prod_not_locked:(.+)|no_data:([^:]+):)/.exec(marker);
|
|
110
|
+
const id = match?.[1] ?? match?.[2];
|
|
111
|
+
return id === void 0 ? void 0 : (0, _milaboratories_pl_model_common.asBlockId)(id);
|
|
112
|
+
}
|
|
113
|
+
/** How often a waiting tool sends a progress notification. */
|
|
114
|
+
const PROGRESS_INTERVAL_MS = 5e3;
|
|
115
|
+
/**
|
|
116
|
+
* Returns a progress callback (for {@link SettleOptions.onProgress} and the like) that sends a
|
|
117
|
+
* progress notification once the progress grew by at least `step` since the last one sent, when
|
|
118
|
+
* the request asked for progress (carries a `progressToken`); `undefined` otherwise. By default
|
|
119
|
+
* progress counts milliseconds waited, sent at most every {@link PROGRESS_INTERVAL_MS}; a count
|
|
120
|
+
* of items takes a `step` of 1. The progress a client sees only grows. `message` is the default
|
|
121
|
+
* text; a call may give its own (a later phase of the same wait).
|
|
122
|
+
*/
|
|
123
|
+
function progressReporter(ctx, message, step = PROGRESS_INTERVAL_MS) {
|
|
124
|
+
const token = ctx?.mcpReq._meta?.progressToken;
|
|
125
|
+
if (ctx === void 0 || token === void 0) return void 0;
|
|
126
|
+
let lastSent = 0;
|
|
127
|
+
return (progress, total, phase) => {
|
|
128
|
+
if (progress - lastSent < step) return;
|
|
129
|
+
lastSent = progress;
|
|
130
|
+
ctx.mcpReq.notify({
|
|
131
|
+
method: "notifications/progress",
|
|
132
|
+
params: {
|
|
133
|
+
progressToken: token,
|
|
134
|
+
progress,
|
|
135
|
+
total,
|
|
136
|
+
message: phase ?? message
|
|
137
|
+
}
|
|
138
|
+
}).catch(() => {});
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** Clamps a wait the caller asked for to `[min, max]`; `fallback` when none was asked for. */
|
|
142
|
+
function clampWait(requested, fallback, min, max) {
|
|
143
|
+
if (requested === void 0 || !Number.isFinite(requested)) return fallback;
|
|
144
|
+
return (0, _milaboratories_helpers.clamp)(Math.round(requested), min, max);
|
|
145
|
+
}
|
|
146
|
+
exports.WAKE_INTERVAL_MS = WAKE_INTERVAL_MS;
|
|
147
|
+
exports.awaitBlockSettled = awaitBlockSettled;
|
|
148
|
+
exports.awaitChangeOrWake = awaitChangeOrWake;
|
|
149
|
+
exports.clampWait = clampWait;
|
|
150
|
+
exports.pendingOutputKeys = pendingOutputKeys;
|
|
151
|
+
exports.progressReporter = progressReporter;
|
|
152
|
+
exports.upstreamOfMarker = upstreamOfMarker;
|
|
153
|
+
exports.withDeadline = withDeadline;
|
|
154
|
+
|
|
155
|
+
//# sourceMappingURL=settle.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"settle.cjs","names":["delay","asBlockId","clamp"],"sources":["../../src/tools/settle.ts"],"sourcesContent":["import { asBlockId, type BlockId } from \"@milaboratories/pl-model-common\";\nimport { clamp } from \"@milaboratories/helpers\";\nimport { delay } from \"es-toolkit\";\n\n/** What {@link awaitBlockSettled} reads of a block state. */\nexport type SettleBlockState = {\n outputs?: Record<string, unknown> | undefined;\n};\n\n/** What {@link awaitBlockSettled} reads of a block of the project overview. */\nexport type SettleOverviewBlock = {\n id: string;\n calculationStatus: string;\n upstreams: string[];\n};\n\n/** The block state computable as {@link awaitBlockSettled} uses it; a middle-layer `Computable`. */\nexport type SettleStateComputable<S extends SettleBlockState> = {\n getFullValue(): Promise<{ value: S; uTag: string; unstableMarker?: string | undefined }>;\n awaitChange(abortSignal?: AbortSignal, uTag?: string): Promise<void>;\n};\n\n/** What {@link awaitBlockSettled} needs of a project; a `Project` of the middle layer has it. */\nexport type SettleProject<S extends SettleBlockState> = {\n overview: { getValue(): Promise<{ blocks: SettleOverviewBlock[] } | undefined> };\n getBlockState(blockId: BlockId): SettleStateComputable<S>;\n};\n\n/** Options of {@link awaitBlockSettled}. */\nexport type SettleOptions = {\n /** The longest the wait takes. */\n timeoutMs: number;\n /** Ends the wait early: the request was cancelled. */\n signal?: AbortSignal;\n /**\n * Wait for the block's run as well: a running block is not settled, and a block that is not\n * calculated or is in limbo ends the wait (`stoppedBy`).\n */\n waitForRun: boolean;\n /**\n * Called on every look at the block, for progress notifications: at least every\n * {@link WAKE_INTERVAL_MS}, also while the block does not change.\n */\n onProgress?: (elapsedMs: number, timeoutMs: number) => void;\n};\n\n/** How {@link awaitBlockSettled} ended. */\nexport type SettleResult<S extends SettleBlockState> = {\n /** Every output of the block is computed or failed (and with `waitForRun`, the run is over). */\n settled: boolean;\n /**\n * Why the wait ended unsettled: out of time, the request was cancelled, the outputs wait for an\n * upstream block that is running or that has not run (not calculated, or in limbo), named by\n * `waitingOn`, or (with `waitForRun`) the block is not calculated or is in limbo. `block-gone`:\n * the block was removed while waiting.\n */\n stoppedBy?:\n | \"timeout\"\n | \"aborted\"\n | \"upstream-running\"\n | \"upstream-not-run\"\n | \"not-calculated\"\n | \"limbo\"\n | \"block-gone\";\n waitedMs: number;\n /** The block's calculation status when the wait ended. */\n calculationStatus: string | undefined;\n /** The last block state read. */\n state: S;\n /** The outputs that have no final value yet. */\n pendingOutputs: string[];\n /**\n * The upstream block the pending outputs wait for, when the block state names it and that\n * block is running or has not run (see `waitingOnStatus`).\n */\n waitingOn?: BlockId;\n /** The calculation status of the `waitingOn` block. */\n waitingOnStatus?: string;\n /** The blocks above that are running. */\n runningUpstreams: BlockId[];\n};\n\n/** The shortest time one look at the block takes, so a computable that changes all the time does not spin. */\nconst MIN_ITERATION_MS = 100;\n\n/**\n * The longest one look at the block waits for a change before looking again: a wait on a block\n * that does not change still wakes on schedule, so its progress notifications go out.\n */\nexport const WAKE_INTERVAL_MS = 5000;\n\n/**\n * Waits until every output of a block is either computed (stable) or failed. Only the outputs of\n * this block count: the block state's own `stable` flag also waits for the titles of every other\n * block of the project.\n *\n * Returns early, unsettled, when the pending outputs wait for an upstream block that is running\n * or has not run: the block state is marked `prod_not_locked:<id>` or `no_data:<id>:<export>` and\n * block `<id>` is running (the outputs settle only after it finishes, which may take longer than\n * any wait here), or is not calculated or in limbo (they settle only after somebody runs it).\n * (With `waitForRun` and the block itself running, the wait goes on: the run includes the\n * upstream.)\n */\nexport async function awaitBlockSettled<S extends SettleBlockState>(\n project: SettleProject<S>,\n blockId: BlockId,\n options: SettleOptions,\n): Promise<SettleResult<S>> {\n const start = Date.now();\n return await withDeadline(options.timeoutMs, options.signal, (signal) =>\n settleLoop(project, blockId, options, start, signal),\n );\n}\n\n/**\n * Runs `wait` with a signal that fires when `signal` (the request's) does or `timeoutMs` runs\n * out, whichever comes first.\n */\nexport async function withDeadline<T>(\n timeoutMs: number,\n signal: AbortSignal | undefined,\n wait: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const deadline = new AbortController();\n const deadlineTimer = setTimeout(() => deadline.abort(), Math.max(0, timeoutMs));\n try {\n return await wait(signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal);\n } finally {\n clearTimeout(deadlineTimer);\n }\n}\n\n/**\n * One wait of a waiting loop for a computable to change from `uTag`: it ends on the change, on\n * `signal`, or after {@link WAKE_INTERVAL_MS} without a change (so the loop looks again and sends\n * its progress), and not before {@link MIN_ITERATION_MS} after `iterationStart` (so a computable\n * that changes all the time does not spin).\n */\nexport async function awaitChangeOrWake(\n computable: { awaitChange(abortSignal?: AbortSignal, uTag?: string): Promise<void> },\n uTag: string,\n signal: AbortSignal,\n iterationStart: number,\n): Promise<void> {\n const wake = new AbortController();\n const wakeTimer = setTimeout(() => wake.abort(), WAKE_INTERVAL_MS);\n try {\n await computable.awaitChange(AbortSignal.any([signal, wake.signal]), uTag);\n } catch {\n // the wait ended or the wake-up came; the next look decides\n } finally {\n clearTimeout(wakeTimer);\n }\n const spent = Date.now() - iterationStart;\n if (spent < MIN_ITERATION_MS && !signal.aborted)\n // An abort ends the pause early (`delay` rejects then); the next look sees the signal.\n await delay(MIN_ITERATION_MS - spent, { signal }).catch(() => {});\n}\n\nasync function settleLoop<S extends SettleBlockState>(\n project: SettleProject<S>,\n blockId: BlockId,\n options: SettleOptions,\n start: number,\n signal: AbortSignal,\n): Promise<SettleResult<S>> {\n const computable = project.getBlockState(blockId);\n\n for (;;) {\n const iterationStart = Date.now();\n const full = await computable.getFullValue();\n const overview = await project.overview.getValue();\n const blocks = overview?.blocks ?? [];\n const block = blocks.find((b) => b.id === blockId);\n const status = block?.calculationStatus;\n const running = new Set(\n blocks.filter((b) => b.calculationStatus === \"Running\").map((b) => b.id),\n );\n const pendingOutputs = pendingOutputKeys(full.value.outputs);\n const runningUpstreams = (block?.upstreams ?? [])\n .filter((id) => running.has(id))\n .map(asBlockId);\n const markerUpstream = upstreamOfMarker(full.unstableMarker);\n const markerStatus = blocks.find((b) => b.id === markerUpstream)?.calculationStatus;\n const upstreamHalt =\n markerStatus === \"Running\"\n ? \"upstream-running\"\n : markerStatus === \"NotCalculated\" || markerStatus === \"Limbo\"\n ? \"upstream-not-run\"\n : undefined;\n const waitingOn = upstreamHalt === undefined ? undefined : markerUpstream;\n\n const result = (\n settled: boolean,\n stoppedBy?: SettleResult<S>[\"stoppedBy\"],\n ): SettleResult<S> => ({\n settled,\n ...(stoppedBy === undefined ? {} : { stoppedBy }),\n waitedMs: Date.now() - start,\n calculationStatus: status,\n state: full.value,\n pendingOutputs,\n ...(waitingOn !== undefined ? { waitingOn, waitingOnStatus: markerStatus } : {}),\n runningUpstreams,\n });\n\n if (overview !== undefined && block === undefined) return result(false, \"block-gone\");\n\n if (options.waitForRun && status === \"NotCalculated\") return result(false, \"not-calculated\");\n if (options.waitForRun && status === \"Limbo\") return result(false, \"limbo\");\n const runPending = options.waitForRun && status === \"Running\";\n\n if (!runPending && full.value.outputs !== undefined && pendingOutputs.length === 0)\n return result(true);\n\n if (!runPending && pendingOutputs.length > 0 && upstreamHalt !== undefined)\n return result(false, upstreamHalt);\n\n if (signal.aborted) return result(false, options.signal?.aborted ? \"aborted\" : \"timeout\");\n options.onProgress?.(Date.now() - start, options.timeoutMs);\n\n await awaitChangeOrWake(computable, full.uTag, signal, iterationStart);\n }\n}\n\n/** The keys of outputs that are computed but not final yet (`stable: false`). */\nexport function pendingOutputKeys(outputs: Record<string, unknown> | undefined): string[] {\n if (outputs === undefined) return [];\n return Object.entries(outputs)\n .filter(\n ([, o]) =>\n typeof o === \"object\" &&\n o !== null &&\n \"ok\" in o &&\n o.ok === true &&\n \"stable\" in o &&\n o.stable === false,\n )\n .map(([key]) => key);\n}\n\n/**\n * The upstream block an unstable marker of the result pool names: `prod_not_locked:<id>` (the\n * block's results are not final yet) or `no_data:<id>:<export>` (an export of it has no data yet).\n */\nexport function upstreamOfMarker(marker: string | undefined): BlockId | undefined {\n if (marker === undefined) return undefined;\n const match = /^(?:prod_not_locked:(.+)|no_data:([^:]+):)/.exec(marker);\n const id = match?.[1] ?? match?.[2];\n return id === undefined ? undefined : asBlockId(id);\n}\n\n/** The context of a tool call, as far as a waiting tool uses it. */\nexport type WaitContext = {\n mcpReq: {\n signal: AbortSignal;\n _meta?: { progressToken?: string | number; [key: string]: unknown } | undefined;\n notify: (notification: {\n method: \"notifications/progress\";\n params: {\n progressToken: string | number;\n progress: number;\n total?: number;\n message?: string;\n };\n }) => Promise<void>;\n };\n};\n\n/** How often a waiting tool sends a progress notification. */\nconst PROGRESS_INTERVAL_MS = 5000;\n\n/**\n * Returns a progress callback (for {@link SettleOptions.onProgress} and the like) that sends a\n * progress notification once the progress grew by at least `step` since the last one sent, when\n * the request asked for progress (carries a `progressToken`); `undefined` otherwise. By default\n * progress counts milliseconds waited, sent at most every {@link PROGRESS_INTERVAL_MS}; a count\n * of items takes a `step` of 1. The progress a client sees only grows. `message` is the default\n * text; a call may give its own (a later phase of the same wait).\n */\nexport function progressReporter(\n ctx: WaitContext | undefined,\n message: string,\n step: number = PROGRESS_INTERVAL_MS,\n): ((progress: number, total: number, phase?: string) => void) | undefined {\n const token = ctx?.mcpReq._meta?.progressToken;\n if (ctx === undefined || token === undefined) return undefined;\n let lastSent = 0;\n return (progress, total, phase) => {\n if (progress - lastSent < step) return;\n lastSent = progress;\n ctx.mcpReq\n .notify({\n method: \"notifications/progress\",\n params: { progressToken: token, progress, total, message: phase ?? message },\n })\n .catch(() => {\n // the client went away; the wait ends on the abort signal\n });\n };\n}\n\n/** Clamps a wait the caller asked for to `[min, max]`; `fallback` when none was asked for. */\nexport function clampWait(\n requested: number | undefined,\n fallback: number,\n min: number,\n max: number,\n): number {\n if (requested === undefined || !Number.isFinite(requested)) return fallback;\n return clamp(Math.round(requested), min, max);\n}\n"],"mappings":";;;;;AAmFA,MAAM,mBAAmB;;;;;AAMzB,MAAa,mBAAmB;;;;;;;;;;;;;AAchC,eAAsB,kBACpB,SACA,SACA,SAC0B;CAC1B,MAAM,QAAQ,KAAK,IAAI;CACvB,OAAO,MAAM,aAAa,QAAQ,WAAW,QAAQ,SAAS,WAC5D,WAAW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+
import { asBlockId } from "@milaboratories/pl-model-common";
|
|
4
|
+
// src/tools/settle.ts
|
|
5
|
+
/** The shortest time one look at the block takes, so a computable that changes all the time does not spin. */
|
|
6
|
+
const MIN_ITERATION_MS = 100;
|
|
7
|
+
/**
|
|
8
|
+
* The longest one look at the block waits for a change before looking again: a wait on a block
|
|
9
|
+
* that does not change still wakes on schedule, so its progress notifications go out.
|
|
10
|
+
*/
|
|
11
|
+
const WAKE_INTERVAL_MS = 5e3;
|
|
12
|
+
/**
|
|
13
|
+
* Waits until every output of a block is either computed (stable) or failed. Only the outputs of
|
|
14
|
+
* this block count: the block state's own `stable` flag also waits for the titles of every other
|
|
15
|
+
* block of the project.
|
|
16
|
+
*
|
|
17
|
+
* Returns early, unsettled, when the pending outputs wait for an upstream block that is running
|
|
18
|
+
* or has not run: the block state is marked `prod_not_locked:<id>` or `no_data:<id>:<export>` and
|
|
19
|
+
* block `<id>` is running (the outputs settle only after it finishes, which may take longer than
|
|
20
|
+
* any wait here), or is not calculated or in limbo (they settle only after somebody runs it).
|
|
21
|
+
* (With `waitForRun` and the block itself running, the wait goes on: the run includes the
|
|
22
|
+
* upstream.)
|
|
23
|
+
*/
|
|
24
|
+
async function awaitBlockSettled(project, blockId, options) {
|
|
25
|
+
const start = Date.now();
|
|
26
|
+
return await withDeadline(options.timeoutMs, options.signal, (signal) => settleLoop(project, blockId, options, start, signal));
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Runs `wait` with a signal that fires when `signal` (the request's) does or `timeoutMs` runs
|
|
30
|
+
* out, whichever comes first.
|
|
31
|
+
*/
|
|
32
|
+
async function withDeadline(timeoutMs, signal, wait) {
|
|
33
|
+
const deadline = new AbortController();
|
|
34
|
+
const deadlineTimer = setTimeout(() => deadline.abort(), Math.max(0, timeoutMs));
|
|
35
|
+
try {
|
|
36
|
+
return await wait(signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal);
|
|
37
|
+
} finally {
|
|
38
|
+
clearTimeout(deadlineTimer);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* One wait of a waiting loop for a computable to change from `uTag`: it ends on the change, on
|
|
43
|
+
* `signal`, or after {@link WAKE_INTERVAL_MS} without a change (so the loop looks again and sends
|
|
44
|
+
* its progress), and not before {@link MIN_ITERATION_MS} after `iterationStart` (so a computable
|
|
45
|
+
* that changes all the time does not spin).
|
|
46
|
+
*/
|
|
47
|
+
async function awaitChangeOrWake(computable, uTag, signal, iterationStart) {
|
|
48
|
+
const wake = new AbortController();
|
|
49
|
+
const wakeTimer = setTimeout(() => wake.abort(), WAKE_INTERVAL_MS);
|
|
50
|
+
try {
|
|
51
|
+
await computable.awaitChange(AbortSignal.any([signal, wake.signal]), uTag);
|
|
52
|
+
} catch {} finally {
|
|
53
|
+
clearTimeout(wakeTimer);
|
|
54
|
+
}
|
|
55
|
+
const spent = Date.now() - iterationStart;
|
|
56
|
+
if (spent < MIN_ITERATION_MS && !signal.aborted) await delay(MIN_ITERATION_MS - spent, { signal }).catch(() => {});
|
|
57
|
+
}
|
|
58
|
+
async function settleLoop(project, blockId, options, start, signal) {
|
|
59
|
+
const computable = project.getBlockState(blockId);
|
|
60
|
+
for (;;) {
|
|
61
|
+
const iterationStart = Date.now();
|
|
62
|
+
const full = await computable.getFullValue();
|
|
63
|
+
const overview = await project.overview.getValue();
|
|
64
|
+
const blocks = overview?.blocks ?? [];
|
|
65
|
+
const block = blocks.find((b) => b.id === blockId);
|
|
66
|
+
const status = block?.calculationStatus;
|
|
67
|
+
const running = new Set(blocks.filter((b) => b.calculationStatus === "Running").map((b) => b.id));
|
|
68
|
+
const pendingOutputs = pendingOutputKeys(full.value.outputs);
|
|
69
|
+
const runningUpstreams = (block?.upstreams ?? []).filter((id) => running.has(id)).map(asBlockId);
|
|
70
|
+
const markerUpstream = upstreamOfMarker(full.unstableMarker);
|
|
71
|
+
const markerStatus = blocks.find((b) => b.id === markerUpstream)?.calculationStatus;
|
|
72
|
+
const upstreamHalt = markerStatus === "Running" ? "upstream-running" : markerStatus === "NotCalculated" || markerStatus === "Limbo" ? "upstream-not-run" : void 0;
|
|
73
|
+
const waitingOn = upstreamHalt === void 0 ? void 0 : markerUpstream;
|
|
74
|
+
const result = (settled, stoppedBy) => ({
|
|
75
|
+
settled,
|
|
76
|
+
...stoppedBy === void 0 ? {} : { stoppedBy },
|
|
77
|
+
waitedMs: Date.now() - start,
|
|
78
|
+
calculationStatus: status,
|
|
79
|
+
state: full.value,
|
|
80
|
+
pendingOutputs,
|
|
81
|
+
...waitingOn !== void 0 ? {
|
|
82
|
+
waitingOn,
|
|
83
|
+
waitingOnStatus: markerStatus
|
|
84
|
+
} : {},
|
|
85
|
+
runningUpstreams
|
|
86
|
+
});
|
|
87
|
+
if (overview !== void 0 && block === void 0) return result(false, "block-gone");
|
|
88
|
+
if (options.waitForRun && status === "NotCalculated") return result(false, "not-calculated");
|
|
89
|
+
if (options.waitForRun && status === "Limbo") return result(false, "limbo");
|
|
90
|
+
const runPending = options.waitForRun && status === "Running";
|
|
91
|
+
if (!runPending && full.value.outputs !== void 0 && pendingOutputs.length === 0) return result(true);
|
|
92
|
+
if (!runPending && pendingOutputs.length > 0 && upstreamHalt !== void 0) return result(false, upstreamHalt);
|
|
93
|
+
if (signal.aborted) return result(false, options.signal?.aborted ? "aborted" : "timeout");
|
|
94
|
+
options.onProgress?.(Date.now() - start, options.timeoutMs);
|
|
95
|
+
await awaitChangeOrWake(computable, full.uTag, signal, iterationStart);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** The keys of outputs that are computed but not final yet (`stable: false`). */
|
|
99
|
+
function pendingOutputKeys(outputs) {
|
|
100
|
+
if (outputs === void 0) return [];
|
|
101
|
+
return Object.entries(outputs).filter(([, o]) => typeof o === "object" && o !== null && "ok" in o && o.ok === true && "stable" in o && o.stable === false).map(([key]) => key);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The upstream block an unstable marker of the result pool names: `prod_not_locked:<id>` (the
|
|
105
|
+
* block's results are not final yet) or `no_data:<id>:<export>` (an export of it has no data yet).
|
|
106
|
+
*/
|
|
107
|
+
function upstreamOfMarker(marker) {
|
|
108
|
+
if (marker === void 0) return void 0;
|
|
109
|
+
const match = /^(?:prod_not_locked:(.+)|no_data:([^:]+):)/.exec(marker);
|
|
110
|
+
const id = match?.[1] ?? match?.[2];
|
|
111
|
+
return id === void 0 ? void 0 : asBlockId(id);
|
|
112
|
+
}
|
|
113
|
+
/** How often a waiting tool sends a progress notification. */
|
|
114
|
+
const PROGRESS_INTERVAL_MS = 5e3;
|
|
115
|
+
/**
|
|
116
|
+
* Returns a progress callback (for {@link SettleOptions.onProgress} and the like) that sends a
|
|
117
|
+
* progress notification once the progress grew by at least `step` since the last one sent, when
|
|
118
|
+
* the request asked for progress (carries a `progressToken`); `undefined` otherwise. By default
|
|
119
|
+
* progress counts milliseconds waited, sent at most every {@link PROGRESS_INTERVAL_MS}; a count
|
|
120
|
+
* of items takes a `step` of 1. The progress a client sees only grows. `message` is the default
|
|
121
|
+
* text; a call may give its own (a later phase of the same wait).
|
|
122
|
+
*/
|
|
123
|
+
function progressReporter(ctx, message, step = PROGRESS_INTERVAL_MS) {
|
|
124
|
+
const token = ctx?.mcpReq._meta?.progressToken;
|
|
125
|
+
if (ctx === void 0 || token === void 0) return void 0;
|
|
126
|
+
let lastSent = 0;
|
|
127
|
+
return (progress, total, phase) => {
|
|
128
|
+
if (progress - lastSent < step) return;
|
|
129
|
+
lastSent = progress;
|
|
130
|
+
ctx.mcpReq.notify({
|
|
131
|
+
method: "notifications/progress",
|
|
132
|
+
params: {
|
|
133
|
+
progressToken: token,
|
|
134
|
+
progress,
|
|
135
|
+
total,
|
|
136
|
+
message: phase ?? message
|
|
137
|
+
}
|
|
138
|
+
}).catch(() => {});
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** Clamps a wait the caller asked for to `[min, max]`; `fallback` when none was asked for. */
|
|
142
|
+
function clampWait(requested, fallback, min, max) {
|
|
143
|
+
if (requested === void 0 || !Number.isFinite(requested)) return fallback;
|
|
144
|
+
return clamp(Math.round(requested), min, max);
|
|
145
|
+
}
|
|
146
|
+
export { WAKE_INTERVAL_MS, awaitBlockSettled, awaitChangeOrWake, clampWait, pendingOutputKeys, progressReporter, upstreamOfMarker, withDeadline };
|
|
147
|
+
|
|
148
|
+
//# sourceMappingURL=settle.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"settle.js","names":[],"sources":["../../src/tools/settle.ts"],"sourcesContent":["import { asBlockId, type BlockId } from \"@milaboratories/pl-model-common\";\nimport { clamp } from \"@milaboratories/helpers\";\nimport { delay } from \"es-toolkit\";\n\n/** What {@link awaitBlockSettled} reads of a block state. */\nexport type SettleBlockState = {\n outputs?: Record<string, unknown> | undefined;\n};\n\n/** What {@link awaitBlockSettled} reads of a block of the project overview. */\nexport type SettleOverviewBlock = {\n id: string;\n calculationStatus: string;\n upstreams: string[];\n};\n\n/** The block state computable as {@link awaitBlockSettled} uses it; a middle-layer `Computable`. */\nexport type SettleStateComputable<S extends SettleBlockState> = {\n getFullValue(): Promise<{ value: S; uTag: string; unstableMarker?: string | undefined }>;\n awaitChange(abortSignal?: AbortSignal, uTag?: string): Promise<void>;\n};\n\n/** What {@link awaitBlockSettled} needs of a project; a `Project` of the middle layer has it. */\nexport type SettleProject<S extends SettleBlockState> = {\n overview: { getValue(): Promise<{ blocks: SettleOverviewBlock[] } | undefined> };\n getBlockState(blockId: BlockId): SettleStateComputable<S>;\n};\n\n/** Options of {@link awaitBlockSettled}. */\nexport type SettleOptions = {\n /** The longest the wait takes. */\n timeoutMs: number;\n /** Ends the wait early: the request was cancelled. */\n signal?: AbortSignal;\n /**\n * Wait for the block's run as well: a running block is not settled, and a block that is not\n * calculated or is in limbo ends the wait (`stoppedBy`).\n */\n waitForRun: boolean;\n /**\n * Called on every look at the block, for progress notifications: at least every\n * {@link WAKE_INTERVAL_MS}, also while the block does not change.\n */\n onProgress?: (elapsedMs: number, timeoutMs: number) => void;\n};\n\n/** How {@link awaitBlockSettled} ended. */\nexport type SettleResult<S extends SettleBlockState> = {\n /** Every output of the block is computed or failed (and with `waitForRun`, the run is over). */\n settled: boolean;\n /**\n * Why the wait ended unsettled: out of time, the request was cancelled, the outputs wait for an\n * upstream block that is running or that has not run (not calculated, or in limbo), named by\n * `waitingOn`, or (with `waitForRun`) the block is not calculated or is in limbo. `block-gone`:\n * the block was removed while waiting.\n */\n stoppedBy?:\n | \"timeout\"\n | \"aborted\"\n | \"upstream-running\"\n | \"upstream-not-run\"\n | \"not-calculated\"\n | \"limbo\"\n | \"block-gone\";\n waitedMs: number;\n /** The block's calculation status when the wait ended. */\n calculationStatus: string | undefined;\n /** The last block state read. */\n state: S;\n /** The outputs that have no final value yet. */\n pendingOutputs: string[];\n /**\n * The upstream block the pending outputs wait for, when the block state names it and that\n * block is running or has not run (see `waitingOnStatus`).\n */\n waitingOn?: BlockId;\n /** The calculation status of the `waitingOn` block. */\n waitingOnStatus?: string;\n /** The blocks above that are running. */\n runningUpstreams: BlockId[];\n};\n\n/** The shortest time one look at the block takes, so a computable that changes all the time does not spin. */\nconst MIN_ITERATION_MS = 100;\n\n/**\n * The longest one look at the block waits for a change before looking again: a wait on a block\n * that does not change still wakes on schedule, so its progress notifications go out.\n */\nexport const WAKE_INTERVAL_MS = 5000;\n\n/**\n * Waits until every output of a block is either computed (stable) or failed. Only the outputs of\n * this block count: the block state's own `stable` flag also waits for the titles of every other\n * block of the project.\n *\n * Returns early, unsettled, when the pending outputs wait for an upstream block that is running\n * or has not run: the block state is marked `prod_not_locked:<id>` or `no_data:<id>:<export>` and\n * block `<id>` is running (the outputs settle only after it finishes, which may take longer than\n * any wait here), or is not calculated or in limbo (they settle only after somebody runs it).\n * (With `waitForRun` and the block itself running, the wait goes on: the run includes the\n * upstream.)\n */\nexport async function awaitBlockSettled<S extends SettleBlockState>(\n project: SettleProject<S>,\n blockId: BlockId,\n options: SettleOptions,\n): Promise<SettleResult<S>> {\n const start = Date.now();\n return await withDeadline(options.timeoutMs, options.signal, (signal) =>\n settleLoop(project, blockId, options, start, signal),\n );\n}\n\n/**\n * Runs `wait` with a signal that fires when `signal` (the request's) does or `timeoutMs` runs\n * out, whichever comes first.\n */\nexport async function withDeadline<T>(\n timeoutMs: number,\n signal: AbortSignal | undefined,\n wait: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const deadline = new AbortController();\n const deadlineTimer = setTimeout(() => deadline.abort(), Math.max(0, timeoutMs));\n try {\n return await wait(signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal);\n } finally {\n clearTimeout(deadlineTimer);\n }\n}\n\n/**\n * One wait of a waiting loop for a computable to change from `uTag`: it ends on the change, on\n * `signal`, or after {@link WAKE_INTERVAL_MS} without a change (so the loop looks again and sends\n * its progress), and not before {@link MIN_ITERATION_MS} after `iterationStart` (so a computable\n * that changes all the time does not spin).\n */\nexport async function awaitChangeOrWake(\n computable: { awaitChange(abortSignal?: AbortSignal, uTag?: string): Promise<void> },\n uTag: string,\n signal: AbortSignal,\n iterationStart: number,\n): Promise<void> {\n const wake = new AbortController();\n const wakeTimer = setTimeout(() => wake.abort(), WAKE_INTERVAL_MS);\n try {\n await computable.awaitChange(AbortSignal.any([signal, wake.signal]), uTag);\n } catch {\n // the wait ended or the wake-up came; the next look decides\n } finally {\n clearTimeout(wakeTimer);\n }\n const spent = Date.now() - iterationStart;\n if (spent < MIN_ITERATION_MS && !signal.aborted)\n // An abort ends the pause early (`delay` rejects then); the next look sees the signal.\n await delay(MIN_ITERATION_MS - spent, { signal }).catch(() => {});\n}\n\nasync function settleLoop<S extends SettleBlockState>(\n project: SettleProject<S>,\n blockId: BlockId,\n options: SettleOptions,\n start: number,\n signal: AbortSignal,\n): Promise<SettleResult<S>> {\n const computable = project.getBlockState(blockId);\n\n for (;;) {\n const iterationStart = Date.now();\n const full = await computable.getFullValue();\n const overview = await project.overview.getValue();\n const blocks = overview?.blocks ?? [];\n const block = blocks.find((b) => b.id === blockId);\n const status = block?.calculationStatus;\n const running = new Set(\n blocks.filter((b) => b.calculationStatus === \"Running\").map((b) => b.id),\n );\n const pendingOutputs = pendingOutputKeys(full.value.outputs);\n const runningUpstreams = (block?.upstreams ?? [])\n .filter((id) => running.has(id))\n .map(asBlockId);\n const markerUpstream = upstreamOfMarker(full.unstableMarker);\n const markerStatus = blocks.find((b) => b.id === markerUpstream)?.calculationStatus;\n const upstreamHalt =\n markerStatus === \"Running\"\n ? \"upstream-running\"\n : markerStatus === \"NotCalculated\" || markerStatus === \"Limbo\"\n ? \"upstream-not-run\"\n : undefined;\n const waitingOn = upstreamHalt === undefined ? undefined : markerUpstream;\n\n const result = (\n settled: boolean,\n stoppedBy?: SettleResult<S>[\"stoppedBy\"],\n ): SettleResult<S> => ({\n settled,\n ...(stoppedBy === undefined ? {} : { stoppedBy }),\n waitedMs: Date.now() - start,\n calculationStatus: status,\n state: full.value,\n pendingOutputs,\n ...(waitingOn !== undefined ? { waitingOn, waitingOnStatus: markerStatus } : {}),\n runningUpstreams,\n });\n\n if (overview !== undefined && block === undefined) return result(false, \"block-gone\");\n\n if (options.waitForRun && status === \"NotCalculated\") return result(false, \"not-calculated\");\n if (options.waitForRun && status === \"Limbo\") return result(false, \"limbo\");\n const runPending = options.waitForRun && status === \"Running\";\n\n if (!runPending && full.value.outputs !== undefined && pendingOutputs.length === 0)\n return result(true);\n\n if (!runPending && pendingOutputs.length > 0 && upstreamHalt !== undefined)\n return result(false, upstreamHalt);\n\n if (signal.aborted) return result(false, options.signal?.aborted ? \"aborted\" : \"timeout\");\n options.onProgress?.(Date.now() - start, options.timeoutMs);\n\n await awaitChangeOrWake(computable, full.uTag, signal, iterationStart);\n }\n}\n\n/** The keys of outputs that are computed but not final yet (`stable: false`). */\nexport function pendingOutputKeys(outputs: Record<string, unknown> | undefined): string[] {\n if (outputs === undefined) return [];\n return Object.entries(outputs)\n .filter(\n ([, o]) =>\n typeof o === \"object\" &&\n o !== null &&\n \"ok\" in o &&\n o.ok === true &&\n \"stable\" in o &&\n o.stable === false,\n )\n .map(([key]) => key);\n}\n\n/**\n * The upstream block an unstable marker of the result pool names: `prod_not_locked:<id>` (the\n * block's results are not final yet) or `no_data:<id>:<export>` (an export of it has no data yet).\n */\nexport function upstreamOfMarker(marker: string | undefined): BlockId | undefined {\n if (marker === undefined) return undefined;\n const match = /^(?:prod_not_locked:(.+)|no_data:([^:]+):)/.exec(marker);\n const id = match?.[1] ?? match?.[2];\n return id === undefined ? undefined : asBlockId(id);\n}\n\n/** The context of a tool call, as far as a waiting tool uses it. */\nexport type WaitContext = {\n mcpReq: {\n signal: AbortSignal;\n _meta?: { progressToken?: string | number; [key: string]: unknown } | undefined;\n notify: (notification: {\n method: \"notifications/progress\";\n params: {\n progressToken: string | number;\n progress: number;\n total?: number;\n message?: string;\n };\n }) => Promise<void>;\n };\n};\n\n/** How often a waiting tool sends a progress notification. */\nconst PROGRESS_INTERVAL_MS = 5000;\n\n/**\n * Returns a progress callback (for {@link SettleOptions.onProgress} and the like) that sends a\n * progress notification once the progress grew by at least `step` since the last one sent, when\n * the request asked for progress (carries a `progressToken`); `undefined` otherwise. By default\n * progress counts milliseconds waited, sent at most every {@link PROGRESS_INTERVAL_MS}; a count\n * of items takes a `step` of 1. The progress a client sees only grows. `message` is the default\n * text; a call may give its own (a later phase of the same wait).\n */\nexport function progressReporter(\n ctx: WaitContext | undefined,\n message: string,\n step: number = PROGRESS_INTERVAL_MS,\n): ((progress: number, total: number, phase?: string) => void) | undefined {\n const token = ctx?.mcpReq._meta?.progressToken;\n if (ctx === undefined || token === undefined) return undefined;\n let lastSent = 0;\n return (progress, total, phase) => {\n if (progress - lastSent < step) return;\n lastSent = progress;\n ctx.mcpReq\n .notify({\n method: \"notifications/progress\",\n params: { progressToken: token, progress, total, message: phase ?? message },\n })\n .catch(() => {\n // the client went away; the wait ends on the abort signal\n });\n };\n}\n\n/** Clamps a wait the caller asked for to `[min, max]`; `fallback` when none was asked for. */\nexport function clampWait(\n requested: number | undefined,\n fallback: number,\n min: number,\n max: number,\n): number {\n if (requested === undefined || !Number.isFinite(requested)) return fallback;\n return clamp(Math.round(requested), min, max);\n}\n"],"mappings":";;;;;AAmFA,MAAM,mBAAmB;;;;;AAMzB,MAAa,mBAAmB;;;;;;;;;;;;;AAchC,eAAsB,kBACpB,SACA,SACA,SAC0B;CAC1B,MAAM,QAAQ,KAAK,IAAI;CACvB,OAAO,MAAM,aAAa,QAAQ,WAAW,QAAQ,SAAS,WAC5D,WAAW,SAAS,SAAS,SAAS,OAAO,MAAM,CACrD;AACF;;;;;AAMA,eAAsB,aACpB,WACA,QACA,MACY;CACZ,MAAM,WAAW,IAAI,gBAAgB;CACrC,MAAM,gBAAgB,iBAAiB,SAAS,MAAM,GAAG,KAAK,IAAI,GAAG,SAAS,CAAC;CAC/E,IAAI;EACF,OAAO,MAAM,KAAK,SAAS,YAAY,IAAI,CAAC,QAAQ,SAAS,MAAM,CAAC,IAAI,SAAS,MAAM;CACzF,UAAU;EACR,aAAa,aAAa;CAC5B;AACF;;;;;;;AAQA,eAAsB,kBACpB,YACA,MACA,QACA,gBACe;CACf,MAAM,OAAO,IAAI,gBAAgB;CACjC,MAAM,YAAY,iBAAiB,KAAK,MAAM,GAAG,gBAAgB;CACjE,IAAI;EACF,MAAM,WAAW,YAAY,YAAY,IAAI,CAAC,QAAQ,KAAK,MAAM,CAAC,GAAG,IAAI;CAC3E,QAAQ,CAER,UAAU;EACR,aAAa,SAAS;CACxB;CACA,MAAM,QAAQ,KAAK,IAAI,IAAI;CAC3B,IAAI,QAAQ,oBAAoB,CAAC,OAAO,SAEtC,MAAM,MAAM,mBAAmB,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;AACpE;AAEA,eAAe,WACb,SACA,SACA,SACA,OACA,QAC0B;CAC1B,MAAM,aAAa,QAAQ,cAAc,OAAO;CAEhD,SAAS;EACP,MAAM,iBAAiB,K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AAGA,SAAgB,UACd,WACA,UACA,KACA,KACQ;CACR,IAAI,cAAc,KAAA,KAAa,CAAC,OAAO,SAAS,SAAS,GAAG,OAAO;CACnE,OAAO,MAAM,KAAK,MAAM,SAAS,GAAG,KAAK,GAAG;AAC9C"}
|
package/dist/tools/tokens.cjs
CHANGED
|
@@ -60,22 +60,63 @@ function estimateTokens(value, nodeLimit = NODE_LIMIT) {
|
|
|
60
60
|
const tokens = Math.ceil(chars / CHARS_PER_TOKEN);
|
|
61
61
|
return overflow ? `>${tokens} (truncated at ${nodeLimit} nodes)` : tokens;
|
|
62
62
|
}
|
|
63
|
-
/**
|
|
63
|
+
/** Cuts `text` to `max` characters, marking the cut. */
|
|
64
|
+
function clip(text, max) {
|
|
65
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
66
|
+
}
|
|
67
|
+
/** Cuts `text` to `max` characters in the middle, keeping its start and its end. */
|
|
68
|
+
function clipMiddle(text, max) {
|
|
69
|
+
if (text.length <= max) return text;
|
|
70
|
+
const head = Math.ceil((max - 1) / 2);
|
|
71
|
+
return `${text.slice(0, head)}…${text.slice(text.length - (max - 1 - head))}`;
|
|
72
|
+
}
|
|
73
|
+
/** The error text of a failed output: the messages of its errors, one per line. */
|
|
74
|
+
function outputErrorText(output) {
|
|
75
|
+
const errors = typeof output === "object" && output !== null && "errors" in output ? output.errors : void 0;
|
|
76
|
+
if (!Array.isArray(errors) || errors.length === 0) return void 0;
|
|
77
|
+
return errors.map((e) => typeof e === "object" && e !== null && "message" in e && typeof e.message === "string" ? e.message : String(e)).join("\n");
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Sums up block outputs: per output its status, whether it has a value and the estimated tokens of
|
|
81
|
+
* that value. Error texts are left out: one failed run fails every output with the same text.
|
|
82
|
+
*/
|
|
64
83
|
function summarizeOutputs(outputs) {
|
|
65
84
|
if (!outputs) return [];
|
|
66
85
|
return Object.entries(outputs).map(([key, out]) => {
|
|
67
|
-
const o = out;
|
|
68
|
-
const
|
|
69
|
-
const
|
|
70
|
-
|
|
86
|
+
const o = typeof out === "object" && out !== null ? out : {};
|
|
87
|
+
const ok = "ok" in o && o.ok === true;
|
|
88
|
+
const value = "value" in o ? o.value : void 0;
|
|
89
|
+
const hasValue = ok && value != null;
|
|
90
|
+
const summary = {
|
|
71
91
|
key,
|
|
72
|
-
ok: o
|
|
73
|
-
hasValue
|
|
74
|
-
tokensEstimate
|
|
92
|
+
status: !ok ? "error" : "stable" in o && o.stable === false ? "pending" : "ok",
|
|
93
|
+
hasValue
|
|
75
94
|
};
|
|
95
|
+
if (hasValue) summary.tokensEstimate = estimateTokens(value);
|
|
96
|
+
return summary;
|
|
76
97
|
});
|
|
77
98
|
}
|
|
99
|
+
/** Sums up block outputs ({@link summarizeOutputs}); a failed output adds `outputsNote`. */
|
|
100
|
+
function outputsView(outputs) {
|
|
101
|
+
const summaries = summarizeOutputs(outputs);
|
|
102
|
+
const failed = summaries.filter((s) => s.status === "error");
|
|
103
|
+
const first = failed[0];
|
|
104
|
+
if (first === void 0) return { outputs: summaries };
|
|
105
|
+
return {
|
|
106
|
+
outputs: summaries,
|
|
107
|
+
outputsNote: failedOutputsNote(failed.length, first.key)
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** Says how many outputs failed and how to read the error of one of them, `key`. */
|
|
111
|
+
function failedOutputsNote(failed, key) {
|
|
112
|
+
return `${failed} ${failed === 1 ? "output" : "outputs"} failed; get_block_outputs with \`keys: [${JSON.stringify(key)}]\` gives its error.`;
|
|
113
|
+
}
|
|
114
|
+
exports.clip = clip;
|
|
115
|
+
exports.clipMiddle = clipMiddle;
|
|
78
116
|
exports.estimateTokens = estimateTokens;
|
|
117
|
+
exports.failedOutputsNote = failedOutputsNote;
|
|
118
|
+
exports.outputErrorText = outputErrorText;
|
|
119
|
+
exports.outputsView = outputsView;
|
|
79
120
|
exports.summarizeOutputs = summarizeOutputs;
|
|
80
121
|
|
|
81
122
|
//# sourceMappingURL=tokens.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokens.cjs","names":[],"sources":["../../src/tools/tokens.ts"],"sourcesContent":["const NODE_LIMIT = 10_000;\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * Estimate the number of LLM tokens needed to represent a value as JSON,\n * without actually serializing it. Walks the object tree and sums up\n * the JSON character lengths, then divides by ~4 chars/token.\n *\n * Returns token estimate, or a string like \">1234 (truncated at 10000 nodes)\"\n * if the object graph is too large to fully traverse.\n */\nexport function estimateTokens(value: unknown, nodeLimit = NODE_LIMIT): number | string {\n let nodes = 0;\n let chars = 0;\n\n /** Returns true if node limit exceeded. */\n function walk(v: unknown): boolean {\n if (++nodes > nodeLimit) return true;\n if (v === null || v === undefined) {\n chars += 4; // \"null\"\n return false;\n }\n switch (typeof v) {\n case \"string\":\n chars += v.length + 2; // content + quotes\n return false;\n case \"number\":\n chars += String(v).length;\n return false;\n case \"boolean\":\n chars += v ? 4 : 5; // \"true\" or \"false\"\n return false;\n case \"bigint\":\n chars += String(v).length;\n return false;\n default:\n break;\n }\n if (v instanceof Uint8Array || ArrayBuffer.isView(v)) {\n // serialized as array of numbers\n const arr = v as Uint8Array;\n chars += 2 + Math.max(0, arr.length - 1); // [] + commas\n for (let i = 0; i < arr.length; i++) {\n chars += String(arr[i]).length;\n }\n return false;\n }\n if (Array.isArray(v)) {\n chars += 2; // []\n if (v.length > 1) chars += v.length - 1; // commas\n for (const item of v) {\n if (walk(item)) return true;\n }\n return false;\n }\n if (typeof v === \"object\") {\n const entries = Object.entries(v as Record<string, unknown>);\n chars += 2; // {}\n if (entries.length > 1) chars += entries.length - 1; // commas\n for (const [k, val] of entries) {\n chars += k.length + 3; // \"key\":\n if (walk(val)) return true;\n }\n }\n return false;\n }\n\n const overflow = walk(value);\n const tokens = Math.ceil(chars / CHARS_PER_TOKEN);\n return overflow ? `>${tokens} (truncated at ${nodeLimit} nodes)` : tokens;\n}\n\n/**
|
|
1
|
+
{"version":3,"file":"tokens.cjs","names":[],"sources":["../../src/tools/tokens.ts"],"sourcesContent":["const NODE_LIMIT = 10_000;\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * Estimate the number of LLM tokens needed to represent a value as JSON,\n * without actually serializing it. Walks the object tree and sums up\n * the JSON character lengths, then divides by ~4 chars/token.\n *\n * Returns token estimate, or a string like \">1234 (truncated at 10000 nodes)\"\n * if the object graph is too large to fully traverse.\n */\nexport function estimateTokens(value: unknown, nodeLimit = NODE_LIMIT): number | string {\n let nodes = 0;\n let chars = 0;\n\n /** Returns true if node limit exceeded. */\n function walk(v: unknown): boolean {\n if (++nodes > nodeLimit) return true;\n if (v === null || v === undefined) {\n chars += 4; // \"null\"\n return false;\n }\n switch (typeof v) {\n case \"string\":\n chars += v.length + 2; // content + quotes\n return false;\n case \"number\":\n chars += String(v).length;\n return false;\n case \"boolean\":\n chars += v ? 4 : 5; // \"true\" or \"false\"\n return false;\n case \"bigint\":\n chars += String(v).length;\n return false;\n default:\n break;\n }\n if (v instanceof Uint8Array || ArrayBuffer.isView(v)) {\n // serialized as array of numbers\n const arr = v as Uint8Array;\n chars += 2 + Math.max(0, arr.length - 1); // [] + commas\n for (let i = 0; i < arr.length; i++) {\n chars += String(arr[i]).length;\n }\n return false;\n }\n if (Array.isArray(v)) {\n chars += 2; // []\n if (v.length > 1) chars += v.length - 1; // commas\n for (const item of v) {\n if (walk(item)) return true;\n }\n return false;\n }\n if (typeof v === \"object\") {\n const entries = Object.entries(v as Record<string, unknown>);\n chars += 2; // {}\n if (entries.length > 1) chars += entries.length - 1; // commas\n for (const [k, val] of entries) {\n chars += k.length + 3; // \"key\":\n if (walk(val)) return true;\n }\n }\n return false;\n }\n\n const overflow = walk(value);\n const tokens = Math.ceil(chars / CHARS_PER_TOKEN);\n return overflow ? `>${tokens} (truncated at ${nodeLimit} nodes)` : tokens;\n}\n\n/** One block output, summed up without its value or its error. */\nexport type OutputSummary = {\n key: string;\n /**\n * `error`: the output failed; `pending`: it has no final value yet (the model marks it not\n * stable); `ok`: it is computed.\n */\n status: \"ok\" | \"pending\" | \"error\";\n hasValue: boolean;\n tokensEstimate?: number | string;\n};\n\n/** Cuts `text` to `max` characters, marking the cut. */\nexport function clip(text: string, max: number): string {\n return text.length <= max ? text : `${text.slice(0, max - 1)}…`;\n}\n\n/** Cuts `text` to `max` characters in the middle, keeping its start and its end. */\nexport function clipMiddle(text: string, max: number): string {\n if (text.length <= max) return text;\n const head = Math.ceil((max - 1) / 2);\n return `${text.slice(0, head)}…${text.slice(text.length - (max - 1 - head))}`;\n}\n\n/** The error text of a failed output: the messages of its errors, one per line. */\nexport function outputErrorText(output: unknown): string | undefined {\n const errors =\n typeof output === \"object\" && output !== null && \"errors\" in output ? output.errors : undefined;\n if (!Array.isArray(errors) || errors.length === 0) return undefined;\n const messages = errors.map((e: unknown) =>\n typeof e === \"object\" && e !== null && \"message\" in e && typeof e.message === \"string\"\n ? e.message\n : String(e),\n );\n return messages.join(\"\\n\");\n}\n\n/**\n * Sums up block outputs: per output its status, whether it has a value and the estimated tokens of\n * that value. Error texts are left out: one failed run fails every output with the same text.\n */\nexport function summarizeOutputs(outputs: Record<string, unknown> | undefined): OutputSummary[] {\n if (!outputs) return [];\n return Object.entries(outputs).map(([key, out]): OutputSummary => {\n const o = typeof out === \"object\" && out !== null ? out : {};\n const ok = \"ok\" in o && o.ok === true;\n const value = \"value\" in o ? o.value : undefined;\n const hasValue = ok && value != null;\n const summary: OutputSummary = {\n key,\n status: !ok ? \"error\" : \"stable\" in o && o.stable === false ? \"pending\" : \"ok\",\n hasValue,\n };\n if (hasValue) summary.tokensEstimate = estimateTokens(value);\n return summary;\n });\n}\n\n/** The output summary of a block view, and when outputs failed a note on where to read why. */\nexport type OutputsView = { outputs: OutputSummary[]; outputsNote?: string };\n\n/** Sums up block outputs ({@link summarizeOutputs}); a failed output adds `outputsNote`. */\nexport function outputsView(outputs: Record<string, unknown> | undefined): OutputsView {\n const summaries = summarizeOutputs(outputs);\n const failed = summaries.filter((s) => s.status === \"error\");\n const first = failed[0];\n if (first === undefined) return { outputs: summaries };\n return { outputs: summaries, outputsNote: failedOutputsNote(failed.length, first.key) };\n}\n\n/** Says how many outputs failed and how to read the error of one of them, `key`. */\nexport function failedOutputsNote(failed: number, key: string): string {\n return (\n `${failed} ${failed === 1 ? \"output\" : \"outputs\"} failed; get_block_outputs with ` +\n `\\`keys: [${JSON.stringify(key)}]\\` gives its error.`\n );\n}\n"],"mappings":";AAAA,MAAM,aAAa;AACnB,MAAM,kBAAkB;;;;;;;;;AAUxB,SAAgB,eAAe,OAAgB,YAAY,YAA6B;CACtF,IAAI,QAAQ;CACZ,IAAI,QAAQ;;CAGZ,SAAS,KAAK,GAAqB;EACjC,IAAI,EAAE,QAAQ,WAAW,OAAO;EAChC,IAAI,MAAM,QAAQ,MAAM,KAAA,GAAW;GACjC,SAAS;GACT,OAAO;EACT;EACA,QAAQ,OAAO,GAAf;GACE,KAAK;IACH,SAAS,EAAE,SAAS;IACpB,OAAO;GACT,KAAK;IACH,SAAS,OAAO,CAAC,CAAC,CAAC;IACnB,OAAO;GACT,KAAK;IACH,SAAS,IAAI,IAAI;IACjB,OAAO;GACT,KAAK;IACH,SAAS,OAAO,CAAC,CAAC,CAAC;IACnB,OAAO;EAGX;EACA,IAAI,aAAa,cAAc,YAAY,OAAO,CAAC,GAAG;GAEpD,MAAM,MAAM;GACZ,SAAS,IAAI,KAAK,IAAI,GAAG,IAAI,SAAS,CAAC;GACvC,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAC9B,SAAS,OAAO,IAAI,EAAE,CAAC,CAAC;GAE1B,OAAO;EACT;EACA,IAAI,MAAM,QAAQ,CAAC,GAAG;GACpB,SAAS;GACT,IAAI,EAAE,SAAS,GAAG,SAAS,EAAE,SAAS;GACtC,KAAK,MAAM,QAAQ,GACjB,IAAI,KAAK,IAAI,GAAG,OAAO;GAEzB,OAAO;EACT;EACA,IAAI,OAAO,MAAM,UAAU;G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,OAAO,MAAM,CAAC;EAC3D,MAAM,KAAK,QAAQ,KAAK,EAAE,OAAO;EACjC,MAAM,QAAQ,WAAW,IAAI,EAAE,QAAQ,KAAA;EACvC,MAAM,WAAW,MAAM,SAAS;EAChC,MAAM,UAAyB;GAC7B;GACA,QAAQ,CAAC,KAAK,UAAU,YAAY,KAAK,EAAE,WAAW,QAAQ,YAAY;GAC1E;EACF;EACA,IAAI,UAAU,QAAQ,iBAAiB,eAAe,KAAK;EAC3D,OAAO;CACT,CAAC;AACH;;AAMA,SAAgB,YAAY,SAA2D;CACrF,MAAM,YAAY,iBAAiB,OAAO;CAC1C,MAAM,SAAS,UAAU,QAAQ,MAAM,EAAE,WAAW,OAAO;CAC3D,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,KAAA,GAAW,OAAO,EAAE,SAAS,UAAU;CACrD,OAAO;EAAE,SAAS;EAAW,aAAa,kBAAkB,OAAO,QAAQ,MAAM,GAAG;CAAE;AACxF;;AAGA,SAAgB,kBAAkB,QAAgB,KAAqB;CACrE,OACE,GAAG,OAAO,GAAG,WAAW,IAAI,WAAW,UAAU,2CACrC,KAAK,UAAU,GAAG,EAAE;AAEpC"}
|
package/dist/tools/tokens.js
CHANGED
|
@@ -60,21 +60,57 @@ function estimateTokens(value, nodeLimit = NODE_LIMIT) {
|
|
|
60
60
|
const tokens = Math.ceil(chars / CHARS_PER_TOKEN);
|
|
61
61
|
return overflow ? `>${tokens} (truncated at ${nodeLimit} nodes)` : tokens;
|
|
62
62
|
}
|
|
63
|
-
/**
|
|
63
|
+
/** Cuts `text` to `max` characters, marking the cut. */
|
|
64
|
+
function clip(text, max) {
|
|
65
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
66
|
+
}
|
|
67
|
+
/** Cuts `text` to `max` characters in the middle, keeping its start and its end. */
|
|
68
|
+
function clipMiddle(text, max) {
|
|
69
|
+
if (text.length <= max) return text;
|
|
70
|
+
const head = Math.ceil((max - 1) / 2);
|
|
71
|
+
return `${text.slice(0, head)}…${text.slice(text.length - (max - 1 - head))}`;
|
|
72
|
+
}
|
|
73
|
+
/** The error text of a failed output: the messages of its errors, one per line. */
|
|
74
|
+
function outputErrorText(output) {
|
|
75
|
+
const errors = typeof output === "object" && output !== null && "errors" in output ? output.errors : void 0;
|
|
76
|
+
if (!Array.isArray(errors) || errors.length === 0) return void 0;
|
|
77
|
+
return errors.map((e) => typeof e === "object" && e !== null && "message" in e && typeof e.message === "string" ? e.message : String(e)).join("\n");
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Sums up block outputs: per output its status, whether it has a value and the estimated tokens of
|
|
81
|
+
* that value. Error texts are left out: one failed run fails every output with the same text.
|
|
82
|
+
*/
|
|
64
83
|
function summarizeOutputs(outputs) {
|
|
65
84
|
if (!outputs) return [];
|
|
66
85
|
return Object.entries(outputs).map(([key, out]) => {
|
|
67
|
-
const o = out;
|
|
68
|
-
const
|
|
69
|
-
const
|
|
70
|
-
|
|
86
|
+
const o = typeof out === "object" && out !== null ? out : {};
|
|
87
|
+
const ok = "ok" in o && o.ok === true;
|
|
88
|
+
const value = "value" in o ? o.value : void 0;
|
|
89
|
+
const hasValue = ok && value != null;
|
|
90
|
+
const summary = {
|
|
71
91
|
key,
|
|
72
|
-
ok: o
|
|
73
|
-
hasValue
|
|
74
|
-
tokensEstimate
|
|
92
|
+
status: !ok ? "error" : "stable" in o && o.stable === false ? "pending" : "ok",
|
|
93
|
+
hasValue
|
|
75
94
|
};
|
|
95
|
+
if (hasValue) summary.tokensEstimate = estimateTokens(value);
|
|
96
|
+
return summary;
|
|
76
97
|
});
|
|
77
98
|
}
|
|
78
|
-
|
|
99
|
+
/** Sums up block outputs ({@link summarizeOutputs}); a failed output adds `outputsNote`. */
|
|
100
|
+
function outputsView(outputs) {
|
|
101
|
+
const summaries = summarizeOutputs(outputs);
|
|
102
|
+
const failed = summaries.filter((s) => s.status === "error");
|
|
103
|
+
const first = failed[0];
|
|
104
|
+
if (first === void 0) return { outputs: summaries };
|
|
105
|
+
return {
|
|
106
|
+
outputs: summaries,
|
|
107
|
+
outputsNote: failedOutputsNote(failed.length, first.key)
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** Says how many outputs failed and how to read the error of one of them, `key`. */
|
|
111
|
+
function failedOutputsNote(failed, key) {
|
|
112
|
+
return `${failed} ${failed === 1 ? "output" : "outputs"} failed; get_block_outputs with \`keys: [${JSON.stringify(key)}]\` gives its error.`;
|
|
113
|
+
}
|
|
114
|
+
export { clip, clipMiddle, estimateTokens, failedOutputsNote, outputErrorText, outputsView, summarizeOutputs };
|
|
79
115
|
|
|
80
116
|
//# sourceMappingURL=tokens.js.map
|
package/dist/tools/tokens.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokens.js","names":[],"sources":["../../src/tools/tokens.ts"],"sourcesContent":["const NODE_LIMIT = 10_000;\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * Estimate the number of LLM tokens needed to represent a value as JSON,\n * without actually serializing it. Walks the object tree and sums up\n * the JSON character lengths, then divides by ~4 chars/token.\n *\n * Returns token estimate, or a string like \">1234 (truncated at 10000 nodes)\"\n * if the object graph is too large to fully traverse.\n */\nexport function estimateTokens(value: unknown, nodeLimit = NODE_LIMIT): number | string {\n let nodes = 0;\n let chars = 0;\n\n /** Returns true if node limit exceeded. */\n function walk(v: unknown): boolean {\n if (++nodes > nodeLimit) return true;\n if (v === null || v === undefined) {\n chars += 4; // \"null\"\n return false;\n }\n switch (typeof v) {\n case \"string\":\n chars += v.length + 2; // content + quotes\n return false;\n case \"number\":\n chars += String(v).length;\n return false;\n case \"boolean\":\n chars += v ? 4 : 5; // \"true\" or \"false\"\n return false;\n case \"bigint\":\n chars += String(v).length;\n return false;\n default:\n break;\n }\n if (v instanceof Uint8Array || ArrayBuffer.isView(v)) {\n // serialized as array of numbers\n const arr = v as Uint8Array;\n chars += 2 + Math.max(0, arr.length - 1); // [] + commas\n for (let i = 0; i < arr.length; i++) {\n chars += String(arr[i]).length;\n }\n return false;\n }\n if (Array.isArray(v)) {\n chars += 2; // []\n if (v.length > 1) chars += v.length - 1; // commas\n for (const item of v) {\n if (walk(item)) return true;\n }\n return false;\n }\n if (typeof v === \"object\") {\n const entries = Object.entries(v as Record<string, unknown>);\n chars += 2; // {}\n if (entries.length > 1) chars += entries.length - 1; // commas\n for (const [k, val] of entries) {\n chars += k.length + 3; // \"key\":\n if (walk(val)) return true;\n }\n }\n return false;\n }\n\n const overflow = walk(value);\n const tokens = Math.ceil(chars / CHARS_PER_TOKEN);\n return overflow ? `>${tokens} (truncated at ${nodeLimit} nodes)` : tokens;\n}\n\n/**
|
|
1
|
+
{"version":3,"file":"tokens.js","names":[],"sources":["../../src/tools/tokens.ts"],"sourcesContent":["const NODE_LIMIT = 10_000;\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * Estimate the number of LLM tokens needed to represent a value as JSON,\n * without actually serializing it. Walks the object tree and sums up\n * the JSON character lengths, then divides by ~4 chars/token.\n *\n * Returns token estimate, or a string like \">1234 (truncated at 10000 nodes)\"\n * if the object graph is too large to fully traverse.\n */\nexport function estimateTokens(value: unknown, nodeLimit = NODE_LIMIT): number | string {\n let nodes = 0;\n let chars = 0;\n\n /** Returns true if node limit exceeded. */\n function walk(v: unknown): boolean {\n if (++nodes > nodeLimit) return true;\n if (v === null || v === undefined) {\n chars += 4; // \"null\"\n return false;\n }\n switch (typeof v) {\n case \"string\":\n chars += v.length + 2; // content + quotes\n return false;\n case \"number\":\n chars += String(v).length;\n return false;\n case \"boolean\":\n chars += v ? 4 : 5; // \"true\" or \"false\"\n return false;\n case \"bigint\":\n chars += String(v).length;\n return false;\n default:\n break;\n }\n if (v instanceof Uint8Array || ArrayBuffer.isView(v)) {\n // serialized as array of numbers\n const arr = v as Uint8Array;\n chars += 2 + Math.max(0, arr.length - 1); // [] + commas\n for (let i = 0; i < arr.length; i++) {\n chars += String(arr[i]).length;\n }\n return false;\n }\n if (Array.isArray(v)) {\n chars += 2; // []\n if (v.length > 1) chars += v.length - 1; // commas\n for (const item of v) {\n if (walk(item)) return true;\n }\n return false;\n }\n if (typeof v === \"object\") {\n const entries = Object.entries(v as Record<string, unknown>);\n chars += 2; // {}\n if (entries.length > 1) chars += entries.length - 1; // commas\n for (const [k, val] of entries) {\n chars += k.length + 3; // \"key\":\n if (walk(val)) return true;\n }\n }\n return false;\n }\n\n const overflow = walk(value);\n const tokens = Math.ceil(chars / CHARS_PER_TOKEN);\n return overflow ? `>${tokens} (truncated at ${nodeLimit} nodes)` : tokens;\n}\n\n/** One block output, summed up without its value or its error. */\nexport type OutputSummary = {\n key: string;\n /**\n * `error`: the output failed; `pending`: it has no final value yet (the model marks it not\n * stable); `ok`: it is computed.\n */\n status: \"ok\" | \"pending\" | \"error\";\n hasValue: boolean;\n tokensEstimate?: number | string;\n};\n\n/** Cuts `text` to `max` characters, marking the cut. */\nexport function clip(text: string, max: number): string {\n return text.length <= max ? text : `${text.slice(0, max - 1)}…`;\n}\n\n/** Cuts `text` to `max` characters in the middle, keeping its start and its end. */\nexport function clipMiddle(text: string, max: number): string {\n if (text.length <= max) return text;\n const head = Math.ceil((max - 1) / 2);\n return `${text.slice(0, head)}…${text.slice(text.length - (max - 1 - head))}`;\n}\n\n/** The error text of a failed output: the messages of its errors, one per line. */\nexport function outputErrorText(output: unknown): string | undefined {\n const errors =\n typeof output === \"object\" && output !== null && \"errors\" in output ? output.errors : undefined;\n if (!Array.isArray(errors) || errors.length === 0) return undefined;\n const messages = errors.map((e: unknown) =>\n typeof e === \"object\" && e !== null && \"message\" in e && typeof e.message === \"string\"\n ? e.message\n : String(e),\n );\n return messages.join(\"\\n\");\n}\n\n/**\n * Sums up block outputs: per output its status, whether it has a value and the estimated tokens of\n * that value. Error texts are left out: one failed run fails every output with the same text.\n */\nexport function summarizeOutputs(outputs: Record<string, unknown> | undefined): OutputSummary[] {\n if (!outputs) return [];\n return Object.entries(outputs).map(([key, out]): OutputSummary => {\n const o = typeof out === \"object\" && out !== null ? out : {};\n const ok = \"ok\" in o && o.ok === true;\n const value = \"value\" in o ? o.value : undefined;\n const hasValue = ok && value != null;\n const summary: OutputSummary = {\n key,\n status: !ok ? \"error\" : \"stable\" in o && o.stable === false ? \"pending\" : \"ok\",\n hasValue,\n };\n if (hasValue) summary.tokensEstimate = estimateTokens(value);\n return summary;\n });\n}\n\n/** The output summary of a block view, and when outputs failed a note on where to read why. */\nexport type OutputsView = { outputs: OutputSummary[]; outputsNote?: string };\n\n/** Sums up block outputs ({@link summarizeOutputs}); a failed output adds `outputsNote`. */\nexport function outputsView(outputs: Record<string, unknown> | undefined): OutputsView {\n const summaries = summarizeOutputs(outputs);\n const failed = summaries.filter((s) => s.status === \"error\");\n const first = failed[0];\n if (first === undefined) return { outputs: summaries };\n return { outputs: summaries, outputsNote: failedOutputsNote(failed.length, first.key) };\n}\n\n/** Says how many outputs failed and how to read the error of one of them, `key`. */\nexport function failedOutputsNote(failed: number, key: string): string {\n return (\n `${failed} ${failed === 1 ? \"output\" : \"outputs\"} failed; get_block_outputs with ` +\n `\\`keys: [${JSON.stringify(key)}]\\` gives its error.`\n );\n}\n"],"mappings":";AAAA,MAAM,aAAa;AACnB,MAAM,kBAAkB;;;;;;;;;AAUxB,SAAgB,eAAe,OAAgB,YAAY,YAA6B;CACtF,IAAI,QAAQ;CACZ,IAAI,QAAQ;;CAGZ,SAAS,KAAK,GAAqB;EACjC,IAAI,EAAE,QAAQ,WAAW,OAAO;EAChC,IAAI,MAAM,QAAQ,MAAM,KAAA,GAAW;GACjC,SAAS;GACT,OAAO;EACT;EACA,QAAQ,OAAO,GAAf;GACE,KAAK;IACH,SAAS,EAAE,SAAS;IACpB,OAAO;GACT,KAAK;IACH,SAAS,OAAO,CAAC,CAAC,CAAC;IACnB,OAAO;GACT,KAAK;IACH,SAAS,IAAI,IAAI;IACjB,OAAO;GACT,KAAK;IACH,SAAS,OAAO,CAAC,CAAC,CAAC;IACnB,OAAO;EAGX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