@linnlabs/linnkit 0.32.3 → 0.34.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/CHANGELOG.md +40 -0
- package/dist/cli.cjs +458 -70
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +458 -70
- package/dist/cli.js.map +1 -1
- package/dist/context-manager.cjs +55 -0
- package/dist/context-manager.cjs.map +1 -1
- package/dist/context-manager.js +55 -0
- package/dist/context-manager.js.map +1 -1
- package/dist/contracts/agentSpec.d.cts +30 -30
- package/dist/contracts/agentSpec.d.ts +30 -30
- package/dist/contracts/audit.d.cts +24 -24
- package/dist/contracts/audit.d.ts +24 -24
- package/dist/contracts/contextPolicy.d.cts +36 -36
- package/dist/contracts/contextPolicy.d.ts +36 -36
- package/dist/contracts/events.d.cts +1083 -1083
- package/dist/contracts/events.d.ts +1083 -1083
- package/dist/contracts/execution.d.cts +8 -8
- package/dist/contracts/execution.d.ts +8 -8
- package/dist/contracts/messages.d.cts +1178 -1178
- package/dist/contracts/messages.d.ts +1178 -1178
- package/dist/contracts/provider-continuation.d.cts +28 -28
- package/dist/contracts/provider-continuation.d.ts +28 -28
- package/dist/contracts/sse.d.cts +899 -899
- package/dist/contracts/sse.d.ts +899 -899
- package/dist/contracts/sub-run-trace-payload.d.cts +26 -26
- package/dist/contracts/sub-run-trace-payload.d.ts +26 -26
- package/dist/contracts/token-accounting.d.cts +30 -30
- package/dist/contracts/token-accounting.d.ts +30 -30
- package/dist/index.cjs +538 -94
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +538 -94
- package/dist/index.js.map +1 -1
- package/dist/quickstart/toolRuntime.d.cts +1 -1
- package/dist/quickstart/toolRuntime.d.ts +1 -1
- package/dist/quickstart/types.d.cts +1 -1
- package/dist/quickstart/types.d.ts +1 -1
- package/dist/quickstart.cjs +458 -70
- package/dist/quickstart.cjs.map +1 -1
- package/dist/quickstart.js +458 -70
- package/dist/quickstart.js.map +1 -1
- package/dist/runtime-kernel/child-runs/childRunInvoker.d.cts +11 -0
- package/dist/runtime-kernel/child-runs/childRunInvoker.d.ts +11 -0
- package/dist/runtime-kernel/events/agentEvents.d.cts +172 -172
- package/dist/runtime-kernel/events/agentEvents.d.ts +172 -172
- package/dist/runtime-kernel/execution/eventBusEventPersistence.d.cts +15 -1
- package/dist/runtime-kernel/execution/eventBusEventPersistence.d.ts +15 -1
- package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.cts +34 -0
- package/dist/runtime-kernel/graph-engine/definitions/runContinuation.d.ts +34 -0
- package/dist/runtime-kernel/graph-engine/engine.d.cts +13 -2
- package/dist/runtime-kernel/graph-engine/engine.d.ts +13 -2
- package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.cts +6 -0
- package/dist/runtime-kernel/graph-engine/functions/parseEngineCheckpoint.d.ts +6 -0
- package/dist/runtime-kernel/graph-engine/index.d.cts +3 -1
- package/dist/runtime-kernel/graph-engine/index.d.ts +3 -1
- package/dist/runtime-kernel/graph-engine/types.d.cts +8 -0
- package/dist/runtime-kernel/graph-engine/types.d.ts +8 -0
- package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.cts +35 -6
- package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.ts +35 -6
- package/dist/runtime-kernel/run-supervisor/index.d.cts +1 -1
- package/dist/runtime-kernel/run-supervisor/index.d.ts +1 -1
- package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.cts +1 -0
- package/dist/runtime-kernel/run-supervisor/memoryRunRegistryStore.d.ts +1 -0
- package/dist/runtime-kernel/run-supervisor/runHandle.d.cts +9 -5
- package/dist/runtime-kernel/run-supervisor/runHandle.d.ts +9 -5
- package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.cts +2 -0
- package/dist/runtime-kernel/run-supervisor/runRegistryStorePort.d.ts +2 -0
- package/dist/runtime-kernel/run-supervisor/runSupervisor.d.cts +9 -2
- package/dist/runtime-kernel/run-supervisor/runSupervisor.d.ts +9 -2
- package/dist/runtime-kernel.cjs +535 -91
- package/dist/runtime-kernel.cjs.map +1 -1
- package/dist/runtime-kernel.d.cts +3 -1
- package/dist/runtime-kernel.d.ts +3 -1
- package/dist/runtime-kernel.js +532 -92
- package/dist/runtime-kernel.js.map +1 -1
- package/dist/testkit.cjs +535 -91
- package/dist/testkit.cjs.map +1 -1
- package/dist/testkit.js +535 -91
- package/dist/testkit.js.map +1 -1
- package/docs/integration/child-runs.md +12 -0
- package/docs/integration/persistence.md +24 -0
- package/docs/integration/run-supervisor.md +15 -2
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -7,6 +7,7 @@ import 'eventsource-parser';
|
|
|
7
7
|
import { get_encoding } from 'tiktoken';
|
|
8
8
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
9
9
|
import { createHash } from 'crypto';
|
|
10
|
+
import { isDeepStrictEqual } from 'util';
|
|
10
11
|
|
|
11
12
|
var __defProp = Object.defineProperty;
|
|
12
13
|
var __export = (target, all) => {
|
|
@@ -1891,13 +1892,17 @@ __export(graph_engine_exports, {
|
|
|
1891
1892
|
MemoryEventStore: () => MemoryEventStore,
|
|
1892
1893
|
PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
|
|
1893
1894
|
PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
|
|
1895
|
+
RunPauseRequested: () => RunPauseRequested,
|
|
1896
|
+
RunRecoveryBlockedError: () => RunRecoveryBlockedError,
|
|
1894
1897
|
ToolNode: () => ToolNode,
|
|
1895
1898
|
UserNode: () => UserNode,
|
|
1896
1899
|
WaitUserNode: () => WaitUserNode,
|
|
1897
1900
|
createHostToolCallBootstrap: () => createHostToolCallBootstrap,
|
|
1898
1901
|
createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
|
|
1899
1902
|
evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
|
|
1903
|
+
isRunPauseSignal: () => isRunPauseSignal,
|
|
1900
1904
|
isRuntimeFailureFact: () => isRuntimeFailureFact,
|
|
1905
|
+
parseEngineCheckpoint: () => parseEngineCheckpoint,
|
|
1901
1906
|
readCheckpointContextUsage: () => readCheckpointContextUsage,
|
|
1902
1907
|
requireEventStoreId: () => requireEventStoreId,
|
|
1903
1908
|
resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
|
|
@@ -2492,6 +2497,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
|
|
|
2492
2497
|
"memory",
|
|
2493
2498
|
"runtimeEventSink",
|
|
2494
2499
|
"runtimeEventCommitPort",
|
|
2500
|
+
"commitExecutionBoundary",
|
|
2501
|
+
"toolRecoveryPort",
|
|
2495
2502
|
"runtimeFailureFactSink",
|
|
2496
2503
|
"signal",
|
|
2497
2504
|
"summarizationCallbacks",
|
|
@@ -3042,6 +3049,7 @@ var GraphExecutor = class {
|
|
|
3042
3049
|
maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
|
|
3043
3050
|
};
|
|
3044
3051
|
this.telemetryPort = config.telemetryPort ?? noopTelemetry;
|
|
3052
|
+
this.executionCheckpointPort = config.executionCheckpointPort;
|
|
3045
3053
|
}
|
|
3046
3054
|
checkpointer;
|
|
3047
3055
|
nodes = /* @__PURE__ */ new Map();
|
|
@@ -3049,6 +3057,7 @@ var GraphExecutor = class {
|
|
|
3049
3057
|
checkpointQueues = /* @__PURE__ */ new Map();
|
|
3050
3058
|
config;
|
|
3051
3059
|
telemetryPort;
|
|
3060
|
+
executionCheckpointPort;
|
|
3052
3061
|
registerNode(node) {
|
|
3053
3062
|
this.nodes.set(node.id, node);
|
|
3054
3063
|
}
|
|
@@ -3057,6 +3066,7 @@ var GraphExecutor = class {
|
|
|
3057
3066
|
}
|
|
3058
3067
|
sanitize(state) {
|
|
3059
3068
|
return {
|
|
3069
|
+
...state,
|
|
3060
3070
|
nodeId: state.nodeId,
|
|
3061
3071
|
revision: state.revision ?? 0,
|
|
3062
3072
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
@@ -3076,8 +3086,9 @@ var GraphExecutor = class {
|
|
|
3076
3086
|
throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
|
|
3077
3087
|
}
|
|
3078
3088
|
this.ephemeralLocals.set(checkpointKey, { ...local });
|
|
3079
|
-
await this.
|
|
3089
|
+
await this.commitCheckpoint(checkpointKey, {
|
|
3080
3090
|
nodeId,
|
|
3091
|
+
...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
|
|
3081
3092
|
revision: 1,
|
|
3082
3093
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
3083
3094
|
local: sanitizeCheckpointLocal(local)
|
|
@@ -3088,6 +3099,33 @@ var GraphExecutor = class {
|
|
|
3088
3099
|
);
|
|
3089
3100
|
});
|
|
3090
3101
|
}
|
|
3102
|
+
/** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
|
|
3103
|
+
async continueSession(checkpointKey, input) {
|
|
3104
|
+
if (!this.executionCheckpointPort) {
|
|
3105
|
+
throw new Error("continueSession requires an ExecutionCheckpointPort");
|
|
3106
|
+
}
|
|
3107
|
+
return this.runWithCheckpointQueue(checkpointKey, async () => {
|
|
3108
|
+
const current = await this.checkpointer.load(checkpointKey);
|
|
3109
|
+
if (!current || current.revision !== input.expectedRevision) {
|
|
3110
|
+
throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
|
|
3111
|
+
}
|
|
3112
|
+
if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
|
|
3113
|
+
throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
|
|
3114
|
+
}
|
|
3115
|
+
if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
|
|
3116
|
+
return { checkpoint: current, events: [], stepCount: 0 };
|
|
3117
|
+
}
|
|
3118
|
+
this.ephemeralLocals.set(checkpointKey, input.capabilities);
|
|
3119
|
+
try {
|
|
3120
|
+
return await this.runUntilYieldQueued(
|
|
3121
|
+
checkpointKey,
|
|
3122
|
+
current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
|
|
3123
|
+
);
|
|
3124
|
+
} finally {
|
|
3125
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
3126
|
+
}
|
|
3127
|
+
});
|
|
3128
|
+
}
|
|
3091
3129
|
/** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
|
|
3092
3130
|
async resumeSession(checkpointKey, input) {
|
|
3093
3131
|
return this.runWithCheckpointQueue(checkpointKey, async () => {
|
|
@@ -3108,17 +3146,21 @@ var GraphExecutor = class {
|
|
|
3108
3146
|
);
|
|
3109
3147
|
}
|
|
3110
3148
|
const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
|
|
3149
|
+
if (this.executionCheckpointPort && current.local?.executorLocal) {
|
|
3150
|
+
resumedLocal.executorLocal = { ...current.local.executorLocal };
|
|
3151
|
+
}
|
|
3111
3152
|
this.ephemeralLocals.set(checkpointKey, resumedLocal);
|
|
3112
|
-
await this.
|
|
3153
|
+
await this.commitCheckpoint(checkpointKey, {
|
|
3113
3154
|
...current,
|
|
3114
3155
|
nodeId: input.nodeId ?? "llm",
|
|
3156
|
+
...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
|
|
3115
3157
|
revision: currentRevision + 1,
|
|
3116
3158
|
local: sanitizeCheckpointLocal(resumedLocal)
|
|
3117
3159
|
});
|
|
3118
3160
|
const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
|
|
3119
3161
|
return this.runUntilYieldQueued(
|
|
3120
3162
|
checkpointKey,
|
|
3121
|
-
input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
|
|
3163
|
+
this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
|
|
3122
3164
|
);
|
|
3123
3165
|
});
|
|
3124
3166
|
}
|
|
@@ -3209,16 +3251,23 @@ var GraphExecutor = class {
|
|
|
3209
3251
|
};
|
|
3210
3252
|
}
|
|
3211
3253
|
async saveCheckpoint(checkpointKey, state) {
|
|
3212
|
-
const
|
|
3254
|
+
const checkpoint2 = this.sanitize({
|
|
3213
3255
|
...state,
|
|
3214
3256
|
revision: (state.revision ?? 0) + 1
|
|
3215
3257
|
});
|
|
3216
|
-
await this.
|
|
3217
|
-
return
|
|
3258
|
+
await this.commitCheckpoint(checkpointKey, checkpoint2);
|
|
3259
|
+
return checkpoint2;
|
|
3260
|
+
}
|
|
3261
|
+
async commitCheckpoint(checkpointKey, checkpoint2) {
|
|
3262
|
+
if (this.executionCheckpointPort) {
|
|
3263
|
+
await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
|
|
3264
|
+
} else {
|
|
3265
|
+
await this.checkpointer.save(checkpointKey, checkpoint2);
|
|
3266
|
+
}
|
|
3218
3267
|
}
|
|
3219
3268
|
async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
|
|
3220
|
-
const
|
|
3221
|
-
return { events, checkpoint, stepCount };
|
|
3269
|
+
const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
|
|
3270
|
+
return { events, checkpoint: checkpoint2, stepCount };
|
|
3222
3271
|
}
|
|
3223
3272
|
async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
|
|
3224
3273
|
let state = initialState;
|
|
@@ -3228,6 +3277,15 @@ var GraphExecutor = class {
|
|
|
3228
3277
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
3229
3278
|
local: { ...state.local || {}, ...ephemeral }
|
|
3230
3279
|
};
|
|
3280
|
+
if (this.executionCheckpointPort) {
|
|
3281
|
+
state.local = {
|
|
3282
|
+
...state.local,
|
|
3283
|
+
commitExecutionBoundary: async (boundary) => {
|
|
3284
|
+
const saved = await this.saveCheckpoint(checkpointKey, boundary);
|
|
3285
|
+
boundary.revision = saved.revision;
|
|
3286
|
+
}
|
|
3287
|
+
};
|
|
3288
|
+
}
|
|
3231
3289
|
const isAbortSignal2 = (v) => {
|
|
3232
3290
|
return v !== null && typeof v === "object" && "aborted" in v;
|
|
3233
3291
|
};
|
|
@@ -3237,11 +3295,12 @@ var GraphExecutor = class {
|
|
|
3237
3295
|
throw err;
|
|
3238
3296
|
};
|
|
3239
3297
|
let stepCount = 0;
|
|
3298
|
+
const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
|
|
3240
3299
|
let allEvents = [];
|
|
3241
3300
|
logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
|
|
3242
3301
|
maxSteps
|
|
3243
3302
|
});
|
|
3244
|
-
while (stepCount < maxSteps) {
|
|
3303
|
+
while (previousSteps + stepCount < maxSteps) {
|
|
3245
3304
|
stepCount += 1;
|
|
3246
3305
|
reportStepsUsed(stepCount);
|
|
3247
3306
|
const signalRaw = state.local?.signal;
|
|
@@ -3253,7 +3312,7 @@ var GraphExecutor = class {
|
|
|
3253
3312
|
const stepPreparation = prepareGraphStep({
|
|
3254
3313
|
state,
|
|
3255
3314
|
maxSteps,
|
|
3256
|
-
stepCount
|
|
3315
|
+
stepCount: previousSteps + stepCount
|
|
3257
3316
|
});
|
|
3258
3317
|
state = stepPreparation.state;
|
|
3259
3318
|
const node = this.nodes.get(state.nodeId);
|
|
@@ -3262,6 +3321,7 @@ var GraphExecutor = class {
|
|
|
3262
3321
|
maxSteps,
|
|
3263
3322
|
stepCount
|
|
3264
3323
|
});
|
|
3324
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
3265
3325
|
const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
3266
3326
|
this.ephemeralLocals.delete(checkpointKey);
|
|
3267
3327
|
return result3;
|
|
@@ -3271,6 +3331,11 @@ var GraphExecutor = class {
|
|
|
3271
3331
|
stepCount,
|
|
3272
3332
|
nodeId: state.nodeId
|
|
3273
3333
|
});
|
|
3334
|
+
if (this.executionCheckpointPort) {
|
|
3335
|
+
state.executionStatus = "executing";
|
|
3336
|
+
const saved = await this.saveCheckpoint(checkpointKey, state);
|
|
3337
|
+
state.revision = saved.revision;
|
|
3338
|
+
}
|
|
3274
3339
|
const result2 = await runGraphNodeWithTelemetry({
|
|
3275
3340
|
node,
|
|
3276
3341
|
state,
|
|
@@ -3295,10 +3360,13 @@ var GraphExecutor = class {
|
|
|
3295
3360
|
fromNodeId: stepResolution.action.fromNodeId,
|
|
3296
3361
|
nextNodeId: stepResolution.action.nextNodeId
|
|
3297
3362
|
});
|
|
3298
|
-
|
|
3363
|
+
if (this.executionCheckpointPort) state.executionStatus = "ready";
|
|
3364
|
+
const saved = await this.saveCheckpoint(checkpointKey, state);
|
|
3365
|
+
state.revision = saved.revision;
|
|
3299
3366
|
continue;
|
|
3300
3367
|
}
|
|
3301
3368
|
if (stepResolution.action.kind === "yield") {
|
|
3369
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
3302
3370
|
logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
|
|
3303
3371
|
maxSteps,
|
|
3304
3372
|
stepCount
|
|
@@ -3309,6 +3377,7 @@ var GraphExecutor = class {
|
|
|
3309
3377
|
maxSteps,
|
|
3310
3378
|
stepCount
|
|
3311
3379
|
});
|
|
3380
|
+
if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
|
|
3312
3381
|
return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
3313
3382
|
}
|
|
3314
3383
|
logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
|
|
@@ -3329,6 +3398,7 @@ var GraphExecutor = class {
|
|
|
3329
3398
|
},
|
|
3330
3399
|
retryable: false
|
|
3331
3400
|
}), "GraphExecutor.engine_budget_exhausted"));
|
|
3401
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
3332
3402
|
const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
3333
3403
|
this.ephemeralLocals.delete(checkpointKey);
|
|
3334
3404
|
return result;
|
|
@@ -7004,10 +7074,11 @@ var LlmNode = class {
|
|
|
7004
7074
|
bridge.handle
|
|
7005
7075
|
);
|
|
7006
7076
|
} catch (error) {
|
|
7007
|
-
bridge.finalizePartialAnswer();
|
|
7077
|
+
if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
|
|
7008
7078
|
throw error;
|
|
7009
7079
|
}
|
|
7010
7080
|
const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
|
|
7081
|
+
if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
|
|
7011
7082
|
switch (decision.kind) {
|
|
7012
7083
|
case "tool_calls": {
|
|
7013
7084
|
if (forceFinalAnswer) {
|
|
@@ -8214,6 +8285,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
|
|
|
8214
8285
|
function recordToolProtocolError(params) {
|
|
8215
8286
|
}
|
|
8216
8287
|
|
|
8288
|
+
// src/runtime-kernel/graph-engine/definitions/runContinuation.ts
|
|
8289
|
+
var RunRecoveryBlockedError = class extends Error {
|
|
8290
|
+
code = "RUN_RECOVERY_BLOCKED";
|
|
8291
|
+
constructor(message) {
|
|
8292
|
+
super(message);
|
|
8293
|
+
this.name = "RunRecoveryBlockedError";
|
|
8294
|
+
}
|
|
8295
|
+
};
|
|
8296
|
+
var RunPauseRequested = class extends Error {
|
|
8297
|
+
code = "RUN_PAUSE_REQUESTED";
|
|
8298
|
+
constructor(message = "Run paused by user") {
|
|
8299
|
+
super(message);
|
|
8300
|
+
this.name = "RunPauseRequested";
|
|
8301
|
+
}
|
|
8302
|
+
};
|
|
8303
|
+
function isRunPauseSignal(signal) {
|
|
8304
|
+
const reason = signal?.reason;
|
|
8305
|
+
return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
|
|
8306
|
+
}
|
|
8307
|
+
|
|
8308
|
+
// src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
|
|
8309
|
+
async function executeRecoverableTool(input) {
|
|
8310
|
+
const local = input.state.local;
|
|
8311
|
+
if (!local?.commitExecutionBoundary) return input.execute();
|
|
8312
|
+
if (local.executingToolCallId) {
|
|
8313
|
+
if (local.executingToolCallId !== input.call.id) {
|
|
8314
|
+
throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
|
|
8315
|
+
}
|
|
8316
|
+
const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
|
|
8317
|
+
if (!decision || decision.kind === "blocked") {
|
|
8318
|
+
throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
|
|
8319
|
+
}
|
|
8320
|
+
if (decision.kind === "settled") return decision.result;
|
|
8321
|
+
}
|
|
8322
|
+
local.executingToolCallId = input.call.id;
|
|
8323
|
+
await local.commitExecutionBoundary(input.state);
|
|
8324
|
+
const result = await input.execute();
|
|
8325
|
+
if (!result.success && isRunPauseSignal(local.signal)) {
|
|
8326
|
+
const error = new Error("Tool execution paused before its outcome was confirmed");
|
|
8327
|
+
error.name = "AbortError";
|
|
8328
|
+
throw error;
|
|
8329
|
+
}
|
|
8330
|
+
return result;
|
|
8331
|
+
}
|
|
8332
|
+
async function commitToolBoundary(state, result) {
|
|
8333
|
+
if (!state.local?.commitExecutionBoundary) return;
|
|
8334
|
+
delete state.local.executingToolCallId;
|
|
8335
|
+
state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
|
|
8336
|
+
state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
|
|
8337
|
+
await state.local.commitExecutionBoundary(state);
|
|
8338
|
+
}
|
|
8339
|
+
|
|
8217
8340
|
// src/runtime-kernel/graph-engine/nodes/toolNode.ts
|
|
8218
8341
|
var logger11 = new Logger("ToolNode");
|
|
8219
8342
|
function isAbortSignal(value) {
|
|
@@ -8384,6 +8507,7 @@ var ToolNode = class {
|
|
|
8384
8507
|
const events = [];
|
|
8385
8508
|
while (true) {
|
|
8386
8509
|
const result = await this.runNextPendingToolCall(state);
|
|
8510
|
+
await commitToolBoundary(state, result);
|
|
8387
8511
|
if (Array.isArray(result.events) && result.events.length > 0) {
|
|
8388
8512
|
events.push(...result.events);
|
|
8389
8513
|
}
|
|
@@ -8400,11 +8524,9 @@ var ToolNode = class {
|
|
|
8400
8524
|
const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
|
|
8401
8525
|
const signalRaw = state.local?.signal;
|
|
8402
8526
|
if (isAbortSignal(signalRaw) && signalRaw.aborted) {
|
|
8403
|
-
|
|
8404
|
-
state,
|
|
8405
|
-
|
|
8406
|
-
toolCatalog: this.toolRuntime
|
|
8407
|
-
});
|
|
8527
|
+
if (!isRunPauseSignal(signalRaw)) {
|
|
8528
|
+
settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
|
|
8529
|
+
}
|
|
8408
8530
|
const abortError = new Error("The user aborted a request.");
|
|
8409
8531
|
abortError.name = "AbortError";
|
|
8410
8532
|
throw abortError;
|
|
@@ -8543,16 +8665,21 @@ var ToolNode = class {
|
|
|
8543
8665
|
tool_calls: [call]
|
|
8544
8666
|
});
|
|
8545
8667
|
try {
|
|
8546
|
-
const exec = await
|
|
8547
|
-
|
|
8548
|
-
|
|
8549
|
-
|
|
8550
|
-
|
|
8551
|
-
|
|
8552
|
-
|
|
8553
|
-
|
|
8554
|
-
|
|
8555
|
-
|
|
8668
|
+
const exec = await executeRecoverableTool({
|
|
8669
|
+
state,
|
|
8670
|
+
call,
|
|
8671
|
+
context: prepared.toolContext,
|
|
8672
|
+
execute: () => executeToolWithIdempotency({
|
|
8673
|
+
idempotencyKey: execution.idempotencyKey,
|
|
8674
|
+
inFlight: this.idempotencyInFlight,
|
|
8675
|
+
history: readHistoryEvents(prepared.local),
|
|
8676
|
+
toolName: execution.toolName,
|
|
8677
|
+
execute: () => this.toolRuntime.executeTool(
|
|
8678
|
+
execution.toolName,
|
|
8679
|
+
execution.toolArgs,
|
|
8680
|
+
prepared.toolContext
|
|
8681
|
+
)
|
|
8682
|
+
})
|
|
8556
8683
|
});
|
|
8557
8684
|
if (exec.success) {
|
|
8558
8685
|
const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
|
|
@@ -8632,7 +8759,7 @@ var ToolNode = class {
|
|
|
8632
8759
|
bridge: execution.bridge
|
|
8633
8760
|
});
|
|
8634
8761
|
} catch (error) {
|
|
8635
|
-
if (isToolExecutionAbort(error)) {
|
|
8762
|
+
if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
|
|
8636
8763
|
settleToolCallsAfterExecutionAbort({
|
|
8637
8764
|
state,
|
|
8638
8765
|
remainingCalls: calls.slice(1),
|
|
@@ -8692,7 +8819,7 @@ var ToolNode = class {
|
|
|
8692
8819
|
{
|
|
8693
8820
|
attachments: context.attachments,
|
|
8694
8821
|
metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
|
|
8695
|
-
|
|
8822
|
+
// 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
|
|
8696
8823
|
durationMs: context.exec.durationMs
|
|
8697
8824
|
}
|
|
8698
8825
|
);
|
|
@@ -8749,6 +8876,9 @@ var ToolNode = class {
|
|
|
8749
8876
|
return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
|
|
8750
8877
|
}
|
|
8751
8878
|
async handleError(context) {
|
|
8879
|
+
if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
|
|
8880
|
+
throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
|
|
8881
|
+
}
|
|
8752
8882
|
if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
|
|
8753
8883
|
await this.emitToolDecisionAudit({
|
|
8754
8884
|
action: "tool.deny",
|
|
@@ -8985,16 +9115,16 @@ function requireEventStoreId(eventStoreId) {
|
|
|
8985
9115
|
}
|
|
8986
9116
|
function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
|
|
8987
9117
|
let lastTimestamp = 0;
|
|
8988
|
-
let
|
|
9118
|
+
let counter2 = 0;
|
|
8989
9119
|
return () => {
|
|
8990
9120
|
const timestamp = Math.max(nowProvider(), lastTimestamp);
|
|
8991
9121
|
if (timestamp === lastTimestamp) {
|
|
8992
|
-
|
|
9122
|
+
counter2 += 1;
|
|
8993
9123
|
} else {
|
|
8994
9124
|
lastTimestamp = timestamp;
|
|
8995
|
-
|
|
9125
|
+
counter2 = 0;
|
|
8996
9126
|
}
|
|
8997
|
-
return `${String(timestamp).padStart(13, "0")}-${String(
|
|
9127
|
+
return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
|
|
8998
9128
|
};
|
|
8999
9129
|
}
|
|
9000
9130
|
|
|
@@ -9406,6 +9536,76 @@ function assertNonNegativeSafeInteger(value, field) {
|
|
|
9406
9536
|
throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
|
|
9407
9537
|
}
|
|
9408
9538
|
}
|
|
9539
|
+
var counter = z.number().int().nonnegative();
|
|
9540
|
+
var executor = z.object({
|
|
9541
|
+
stepCount: counter,
|
|
9542
|
+
phase: z.string().optional(),
|
|
9543
|
+
maxSteps: counter.optional(),
|
|
9544
|
+
remainingSteps: z.number().int().optional(),
|
|
9545
|
+
finalStepPolicy: z.enum(["final_answer", "force_tools"]).optional(),
|
|
9546
|
+
finalStepForcedTools: z.array(z.string()).optional(),
|
|
9547
|
+
lastStepsHintThreshold: counter.optional(),
|
|
9548
|
+
systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
|
|
9549
|
+
toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
|
|
9550
|
+
runLockedModelId: z.string().optional(),
|
|
9551
|
+
lastSuccessfulLlmModelId: z.string().optional(),
|
|
9552
|
+
llmInvocationKind: z.enum(["user_initiated", "continuation"]).optional(),
|
|
9553
|
+
llmInvocationCount: counter.optional(),
|
|
9554
|
+
lockRequestedModelId: z.boolean().optional(),
|
|
9555
|
+
contextCompaction: z.object({
|
|
9556
|
+
attemptCount: counter,
|
|
9557
|
+
committedCount: counter,
|
|
9558
|
+
lastCommittedFingerprint: z.string().optional()
|
|
9559
|
+
}).strict().optional()
|
|
9560
|
+
}).strict();
|
|
9561
|
+
var checkpoint = z.object({
|
|
9562
|
+
nodeId: z.string().min(1),
|
|
9563
|
+
schemaVersion: z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
|
|
9564
|
+
revision: counter.optional(),
|
|
9565
|
+
executionStatus: z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
|
|
9566
|
+
local: z.object({
|
|
9567
|
+
runId: RunIdSchema.optional(),
|
|
9568
|
+
parentRunId: RunIdSchema.optional(),
|
|
9569
|
+
conversationId: z.string().optional(),
|
|
9570
|
+
turnId: z.string().optional(),
|
|
9571
|
+
request: SerializableJsonRecord.optional(),
|
|
9572
|
+
history: z.array(RuntimeEvent).optional(),
|
|
9573
|
+
newEvents: z.array(RuntimeEvent).optional(),
|
|
9574
|
+
executorLocal: executor.optional(),
|
|
9575
|
+
pendingToolCalls: z.array(z.object({
|
|
9576
|
+
id: ToolCallIdSchema,
|
|
9577
|
+
type: z.literal("function"),
|
|
9578
|
+
function: z.object({ name: z.string().min(1), arguments: z.string() }).strict()
|
|
9579
|
+
}).strict()).optional(),
|
|
9580
|
+
executingToolCallId: ToolCallIdSchema.optional(),
|
|
9581
|
+
toolBatchCompletionMode: z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
|
|
9582
|
+
pendingInteractionSpec: SerializableJsonRecord.optional(),
|
|
9583
|
+
lastToolResult: SerializableJsonRecord.optional(),
|
|
9584
|
+
finalAnswer: z.string().optional(),
|
|
9585
|
+
answerId: z.string().optional(),
|
|
9586
|
+
chunkSeq: counter.optional(),
|
|
9587
|
+
contextUsage: ContextUsageSnapshot.optional()
|
|
9588
|
+
}).passthrough().optional()
|
|
9589
|
+
}).strict();
|
|
9590
|
+
function parseEngineCheckpoint(value) {
|
|
9591
|
+
const result = checkpoint.parse(SerializableJsonRecord.parse(value));
|
|
9592
|
+
for (const key of [
|
|
9593
|
+
"memory",
|
|
9594
|
+
"signal",
|
|
9595
|
+
"toolContext",
|
|
9596
|
+
"runtimeEventSink",
|
|
9597
|
+
"runtimeEventCommitPort",
|
|
9598
|
+
"runtimeFailureFactSink",
|
|
9599
|
+
"summarizationCallbacks",
|
|
9600
|
+
"commitExecutionBoundary",
|
|
9601
|
+
"toolRecoveryPort"
|
|
9602
|
+
]) {
|
|
9603
|
+
if (result.local && Object.hasOwn(result.local, key)) {
|
|
9604
|
+
throw new Error(`Checkpoint must not contain execution capability: ${key}`);
|
|
9605
|
+
}
|
|
9606
|
+
}
|
|
9607
|
+
return result;
|
|
9608
|
+
}
|
|
9409
9609
|
|
|
9410
9610
|
// src/runtime-kernel/execution/index.ts
|
|
9411
9611
|
var execution_exports = {};
|
|
@@ -9646,12 +9846,33 @@ var RuntimeEventPublisher = class {
|
|
|
9646
9846
|
var EventBusEventPersistence = class {
|
|
9647
9847
|
constructor(options) {
|
|
9648
9848
|
this.options = options;
|
|
9849
|
+
this.checkpointWritesActive = options.checkpointWriter !== void 0;
|
|
9649
9850
|
}
|
|
9650
9851
|
options;
|
|
9651
9852
|
scheduledEventIds = /* @__PURE__ */ new Set();
|
|
9652
9853
|
writeTail = Promise.resolve();
|
|
9653
9854
|
firstWriteError;
|
|
9654
9855
|
connected = false;
|
|
9856
|
+
checkpointWritesActive;
|
|
9857
|
+
checkpointEvents = [];
|
|
9858
|
+
/** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
|
|
9859
|
+
async commitCheckpoint(checkpointKey, checkpoint2) {
|
|
9860
|
+
const writer = this.options.checkpointWriter;
|
|
9861
|
+
if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
|
|
9862
|
+
const events = this.checkpointEvents;
|
|
9863
|
+
this.checkpointEvents = [];
|
|
9864
|
+
await this.enqueueWrite(() => writer({
|
|
9865
|
+
checkpointKey,
|
|
9866
|
+
checkpoint: checkpoint2,
|
|
9867
|
+
events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
|
|
9868
|
+
}));
|
|
9869
|
+
}
|
|
9870
|
+
/** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
|
|
9871
|
+
finishCheckpointWrites() {
|
|
9872
|
+
for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
|
|
9873
|
+
this.checkpointEvents = [];
|
|
9874
|
+
this.checkpointWritesActive = false;
|
|
9875
|
+
}
|
|
9655
9876
|
connect() {
|
|
9656
9877
|
if (this.connected) {
|
|
9657
9878
|
throw new Error("[EventBusEventPersistence] consumer is already connected");
|
|
@@ -9698,14 +9919,22 @@ var EventBusEventPersistence = class {
|
|
|
9698
9919
|
if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
|
|
9699
9920
|
return;
|
|
9700
9921
|
}
|
|
9922
|
+
if (this.checkpointWritesActive) {
|
|
9923
|
+
this.scheduledEventIds.add(event.id);
|
|
9924
|
+
this.checkpointEvents.push(event);
|
|
9925
|
+
return;
|
|
9926
|
+
}
|
|
9701
9927
|
void this.scheduleWrite(event).catch(() => void 0);
|
|
9702
9928
|
};
|
|
9703
9929
|
scheduleWrite(event) {
|
|
9704
9930
|
this.scheduledEventIds.add(event.id);
|
|
9705
|
-
|
|
9706
|
-
|
|
9707
|
-
|
|
9708
|
-
});
|
|
9931
|
+
return this.enqueueWrite(() => this.options.eventStore.append({
|
|
9932
|
+
eventStoreId: this.options.nextEventStoreId(),
|
|
9933
|
+
event
|
|
9934
|
+
}));
|
|
9935
|
+
}
|
|
9936
|
+
enqueueWrite(operation) {
|
|
9937
|
+
const write = this.writeTail.then(operation);
|
|
9709
9938
|
this.writeTail = write;
|
|
9710
9939
|
void write.catch((error) => {
|
|
9711
9940
|
this.firstWriteError ??= error;
|
|
@@ -11112,8 +11341,6 @@ __export(run_supervisor_exports, {
|
|
|
11112
11341
|
RunNotFoundError: () => RunNotFoundError,
|
|
11113
11342
|
runMetaFromRecord: () => runMetaFromRecord
|
|
11114
11343
|
});
|
|
11115
|
-
|
|
11116
|
-
// src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
|
|
11117
11344
|
function cloneRunRecord(record) {
|
|
11118
11345
|
return {
|
|
11119
11346
|
...record,
|
|
@@ -11133,6 +11360,11 @@ function matchesStatus(candidate, filter) {
|
|
|
11133
11360
|
}
|
|
11134
11361
|
var MemoryRunRegistryStore = class {
|
|
11135
11362
|
store = /* @__PURE__ */ new Map();
|
|
11363
|
+
async compareAndSwap(previous, next) {
|
|
11364
|
+
if (previous.runId !== next.runId || !isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
|
|
11365
|
+
this.store.set(next.runId, cloneRunRecord(next));
|
|
11366
|
+
return true;
|
|
11367
|
+
}
|
|
11136
11368
|
async save(record) {
|
|
11137
11369
|
this.store.set(record.runId, cloneRunRecord(record));
|
|
11138
11370
|
}
|
|
@@ -11280,6 +11512,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
|
|
|
11280
11512
|
}
|
|
11281
11513
|
};
|
|
11282
11514
|
|
|
11515
|
+
// src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
|
|
11516
|
+
async function persistRunTransition(store, previous, next) {
|
|
11517
|
+
if (store.compareAndSwap) {
|
|
11518
|
+
if (!await store.compareAndSwap(previous, next)) {
|
|
11519
|
+
throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
|
|
11520
|
+
}
|
|
11521
|
+
} else {
|
|
11522
|
+
await store.save(next);
|
|
11523
|
+
}
|
|
11524
|
+
}
|
|
11525
|
+
|
|
11283
11526
|
// src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
|
|
11284
11527
|
function isRunTerminalStatus(status) {
|
|
11285
11528
|
return status === "completed" || status === "failed" || status === "cancelled";
|
|
@@ -11335,6 +11578,7 @@ var DefaultRunHandle = class {
|
|
|
11335
11578
|
parentRunId;
|
|
11336
11579
|
runRecord;
|
|
11337
11580
|
abortController;
|
|
11581
|
+
executionId;
|
|
11338
11582
|
agentSpecSnapshot;
|
|
11339
11583
|
requestSnapshot;
|
|
11340
11584
|
transportEventBus;
|
|
@@ -11350,6 +11594,9 @@ var DefaultRunHandle = class {
|
|
|
11350
11594
|
this.runId = options.runRecord.runId;
|
|
11351
11595
|
this.parentRunId = options.runRecord.parentRunId;
|
|
11352
11596
|
this.abortController = options.abortController;
|
|
11597
|
+
const executionId = options.runRecord.metadata?.executionId;
|
|
11598
|
+
if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
|
|
11599
|
+
this.executionId = executionId;
|
|
11353
11600
|
this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
|
|
11354
11601
|
this.requestSnapshot = cloneRequest(options.request);
|
|
11355
11602
|
this.transportEventBus = options.eventBus;
|
|
@@ -11369,8 +11616,9 @@ var DefaultRunHandle = class {
|
|
|
11369
11616
|
* awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
|
|
11370
11617
|
* 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
|
|
11371
11618
|
*/
|
|
11372
|
-
replaceExecutionAbortController(controller) {
|
|
11619
|
+
replaceExecutionAbortController(controller, executionId) {
|
|
11373
11620
|
this.abortController = controller;
|
|
11621
|
+
this.executionId = executionId;
|
|
11374
11622
|
}
|
|
11375
11623
|
async spec() {
|
|
11376
11624
|
return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
|
|
@@ -11390,6 +11638,7 @@ var DefaultRunHandle = class {
|
|
|
11390
11638
|
this.abortController.abort(opts.reason);
|
|
11391
11639
|
const latestRecord = await this.registryStore.load(this.runId);
|
|
11392
11640
|
const baseRecord = latestRecord ?? this.runRecord;
|
|
11641
|
+
this.assertExecutionOwner(baseRecord);
|
|
11393
11642
|
const transition = decideRunLifecycleTransition(baseRecord.status);
|
|
11394
11643
|
if (transition.kind === "skip_terminal") {
|
|
11395
11644
|
if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
|
|
@@ -11399,7 +11648,7 @@ var DefaultRunHandle = class {
|
|
|
11399
11648
|
currentNode: patch.currentNode ?? baseRecord.currentNode,
|
|
11400
11649
|
iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
|
|
11401
11650
|
};
|
|
11402
|
-
await this.registryStore
|
|
11651
|
+
await persistRunTransition(this.registryStore, baseRecord, settledRecord);
|
|
11403
11652
|
this.runRecord = { ...settledRecord };
|
|
11404
11653
|
return;
|
|
11405
11654
|
}
|
|
@@ -11426,7 +11675,7 @@ var DefaultRunHandle = class {
|
|
|
11426
11675
|
}
|
|
11427
11676
|
}
|
|
11428
11677
|
};
|
|
11429
|
-
await this.registryStore
|
|
11678
|
+
await persistRunTransition(this.registryStore, baseRecord, nextRecord);
|
|
11430
11679
|
this.runRecord = { ...nextRecord };
|
|
11431
11680
|
await this.auditPort.emit({
|
|
11432
11681
|
envelopeId: generateAuditEnvelopeId(),
|
|
@@ -11534,21 +11783,35 @@ var DefaultRunHandle = class {
|
|
|
11534
11783
|
async markFailed(error, patch = {}) {
|
|
11535
11784
|
await this.saveLifecycleStatus("failed", patch, error);
|
|
11536
11785
|
}
|
|
11537
|
-
async pause(
|
|
11538
|
-
|
|
11786
|
+
async pause(reason = "Run paused by user") {
|
|
11787
|
+
const latest = await this.registryStore.load(this.runId);
|
|
11788
|
+
if (latest) this.assertExecutionOwner(latest);
|
|
11789
|
+
if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
|
|
11790
|
+
const next = {
|
|
11791
|
+
...latest,
|
|
11792
|
+
status: "paused",
|
|
11793
|
+
updatedAt: Date.now(),
|
|
11794
|
+
pauseReason: reason,
|
|
11795
|
+
pausedAt: void 0
|
|
11796
|
+
};
|
|
11797
|
+
await persistRunTransition(this.registryStore, latest, next);
|
|
11798
|
+
this.runRecord = next;
|
|
11799
|
+
this.abortController.abort(new RunPauseRequested(reason));
|
|
11539
11800
|
}
|
|
11540
|
-
async
|
|
11541
|
-
|
|
11801
|
+
async markPaused(patch = {}) {
|
|
11802
|
+
await this.saveLifecycleStatus("paused", patch);
|
|
11542
11803
|
}
|
|
11543
11804
|
async saveLifecycleStatus(status, patch, errorIfAny) {
|
|
11544
11805
|
const latestRecord = await this.registryStore.load(this.runId);
|
|
11545
11806
|
const baseRecord = latestRecord ?? this.runRecord;
|
|
11546
11807
|
const transition = decideRunLifecycleTransition(baseRecord.status);
|
|
11808
|
+
this.assertExecutionOwner(baseRecord);
|
|
11809
|
+
if (status === "running" && baseRecord.status === "paused") return;
|
|
11547
11810
|
if (transition.kind === "skip_terminal") {
|
|
11548
11811
|
this.runRecord = { ...baseRecord };
|
|
11549
11812
|
return;
|
|
11550
11813
|
}
|
|
11551
|
-
const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
|
|
11814
|
+
const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
|
|
11552
11815
|
const updatedAt = Date.now();
|
|
11553
11816
|
const nextRecord = {
|
|
11554
11817
|
...baseRecord,
|
|
@@ -11556,8 +11819,8 @@ var DefaultRunHandle = class {
|
|
|
11556
11819
|
updatedAt,
|
|
11557
11820
|
currentNode: patch.currentNode ?? baseRecord.currentNode,
|
|
11558
11821
|
iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
|
|
11559
|
-
pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
|
|
11560
|
-
pausedAt: status === "awaiting_user" ? updatedAt : void 0,
|
|
11822
|
+
pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
|
|
11823
|
+
pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
|
|
11561
11824
|
errorIfAny,
|
|
11562
11825
|
metadata: awaitingUserPatch?.eventId ? {
|
|
11563
11826
|
...baseRecord.metadata ?? {},
|
|
@@ -11568,7 +11831,7 @@ var DefaultRunHandle = class {
|
|
|
11568
11831
|
}
|
|
11569
11832
|
} : baseRecord.metadata
|
|
11570
11833
|
};
|
|
11571
|
-
await this.registryStore
|
|
11834
|
+
await persistRunTransition(this.registryStore, baseRecord, nextRecord);
|
|
11572
11835
|
this.runRecord = { ...nextRecord };
|
|
11573
11836
|
if (status === "completed" || status === "failed") {
|
|
11574
11837
|
this.closeObservationChannel();
|
|
@@ -11578,6 +11841,11 @@ var DefaultRunHandle = class {
|
|
|
11578
11841
|
forwardTransportEvent = (envelope) => {
|
|
11579
11842
|
this.observationEventBus.emit("event", envelope);
|
|
11580
11843
|
};
|
|
11844
|
+
assertExecutionOwner(record) {
|
|
11845
|
+
if (record.metadata?.executionId !== this.executionId) {
|
|
11846
|
+
throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
|
|
11847
|
+
}
|
|
11848
|
+
}
|
|
11581
11849
|
forwardTransportError = (error) => {
|
|
11582
11850
|
this.observationEventBus.emit("error", error);
|
|
11583
11851
|
};
|
|
@@ -11908,7 +12176,15 @@ function createRunConcurrencyKeyRegistry() {
|
|
|
11908
12176
|
runIdByKey.delete(concurrencyKey);
|
|
11909
12177
|
}
|
|
11910
12178
|
}
|
|
11911
|
-
|
|
12179
|
+
function transfer(previous, next, concurrencyKey) {
|
|
12180
|
+
if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
|
|
12181
|
+
throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
|
|
12182
|
+
}
|
|
12183
|
+
keyByRunId.delete(previous);
|
|
12184
|
+
keyByRunId.set(next, concurrencyKey);
|
|
12185
|
+
runIdByKey.set(concurrencyKey, next);
|
|
12186
|
+
}
|
|
12187
|
+
return { acquire, release, transfer };
|
|
11912
12188
|
}
|
|
11913
12189
|
|
|
11914
12190
|
// src/runtime-kernel/run-supervisor/functions/runRegistration.ts
|
|
@@ -11959,6 +12235,24 @@ async function recoverRunsOnBoot(options) {
|
|
|
11959
12235
|
const outcomes = [];
|
|
11960
12236
|
for (const record of activeRecords) {
|
|
11961
12237
|
const updatedAt = options.now();
|
|
12238
|
+
if (await options.canRestoreRun?.(record)) {
|
|
12239
|
+
const metadata = { ...record.metadata };
|
|
12240
|
+
const awaitingUser = metadata.awaitingUser;
|
|
12241
|
+
if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
|
|
12242
|
+
const restored = { ...awaitingUser };
|
|
12243
|
+
Reflect.deleteProperty(restored, "resumeClaim");
|
|
12244
|
+
metadata.awaitingUser = restored;
|
|
12245
|
+
}
|
|
12246
|
+
await persistRunTransition(options.registryStore, record, {
|
|
12247
|
+
...record,
|
|
12248
|
+
status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
|
|
12249
|
+
pausedAt: record.pausedAt ?? updatedAt,
|
|
12250
|
+
pauseReason: record.pauseReason ?? options.reason,
|
|
12251
|
+
updatedAt,
|
|
12252
|
+
metadata
|
|
12253
|
+
});
|
|
12254
|
+
continue;
|
|
12255
|
+
}
|
|
11962
12256
|
const nextRecord = {
|
|
11963
12257
|
...record,
|
|
11964
12258
|
status: "failed",
|
|
@@ -11976,7 +12270,7 @@ async function recoverRunsOnBoot(options) {
|
|
|
11976
12270
|
}
|
|
11977
12271
|
}
|
|
11978
12272
|
};
|
|
11979
|
-
await options.registryStore
|
|
12273
|
+
await persistRunTransition(options.registryStore, record, nextRecord);
|
|
11980
12274
|
const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
|
|
11981
12275
|
options.notifyTerminal(outcome);
|
|
11982
12276
|
outcomes.push(outcome);
|
|
@@ -12100,8 +12394,13 @@ var DefaultRunSupervisor = class {
|
|
|
12100
12394
|
inFlight = /* @__PURE__ */ new Map();
|
|
12101
12395
|
eventWatchDisposers = /* @__PURE__ */ new Map();
|
|
12102
12396
|
controlOperations = /* @__PURE__ */ new Map();
|
|
12397
|
+
canRestoreRun;
|
|
12103
12398
|
constructor(options) {
|
|
12399
|
+
if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
|
|
12400
|
+
throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
|
|
12401
|
+
}
|
|
12104
12402
|
this.registryStore = options.registryStore;
|
|
12403
|
+
this.canRestoreRun = options.canRestoreRun;
|
|
12105
12404
|
this.auditPort = options.auditPort;
|
|
12106
12405
|
this.executor = options.executor;
|
|
12107
12406
|
this.runIdFactory = options.runIdFactory ?? generateRunId;
|
|
@@ -12134,6 +12433,9 @@ var DefaultRunSupervisor = class {
|
|
|
12134
12433
|
});
|
|
12135
12434
|
}
|
|
12136
12435
|
async registerRun(spec) {
|
|
12436
|
+
if (spec.replacesPausedRun) {
|
|
12437
|
+
return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
|
|
12438
|
+
}
|
|
12137
12439
|
const runId = spec.runId ?? this.runIdFactory();
|
|
12138
12440
|
if (this.handles.has(runId) || await this.registryStore.load(runId)) {
|
|
12139
12441
|
throw new RunAlreadyRegisteredError(runId);
|
|
@@ -12144,11 +12446,66 @@ var DefaultRunSupervisor = class {
|
|
|
12144
12446
|
forwardParentAbortSignal(controller, spec.parentSignal);
|
|
12145
12447
|
const record = createInitialRunRecord({ runId, spec, startedAt });
|
|
12146
12448
|
try {
|
|
12147
|
-
await
|
|
12449
|
+
if (spec.admissionCommit) await spec.admissionCommit(record);
|
|
12450
|
+
else await this.registryStore.save(record);
|
|
12148
12451
|
} catch (error) {
|
|
12149
12452
|
this.releaseRunAdmission(runId);
|
|
12150
12453
|
throw error;
|
|
12151
12454
|
}
|
|
12455
|
+
return this.attachRun(record, spec, controller);
|
|
12456
|
+
}
|
|
12457
|
+
async registerPausedReplacement(spec) {
|
|
12458
|
+
const target = spec.replacesPausedRun;
|
|
12459
|
+
if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
|
|
12460
|
+
throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
|
|
12461
|
+
}
|
|
12462
|
+
this.getHandle(target.runId);
|
|
12463
|
+
const previous = await this.registryStore.load(target.runId);
|
|
12464
|
+
if (!previous || previous.status !== "paused" || previous.pausedAt === void 0 || previous.updatedAt !== target.expectedUpdatedAt || previous.metadata?.executionId !== target.expectedExecutionId || previous.conversationId !== spec.conversationId || previous.parentRunId !== spec.parentRunId) {
|
|
12465
|
+
throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
|
|
12466
|
+
}
|
|
12467
|
+
const runId = spec.runId ?? this.runIdFactory();
|
|
12468
|
+
if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
|
|
12469
|
+
this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
|
|
12470
|
+
this.runSlotLimiter.release(previous.runId);
|
|
12471
|
+
this.runSlotLimiter.acquire(runId);
|
|
12472
|
+
const now = this.now();
|
|
12473
|
+
const record = createInitialRunRecord({ runId, spec, startedAt: now });
|
|
12474
|
+
const next = {
|
|
12475
|
+
...previous,
|
|
12476
|
+
status: "cancelled",
|
|
12477
|
+
updatedAt: now,
|
|
12478
|
+
errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
|
|
12479
|
+
};
|
|
12480
|
+
try {
|
|
12481
|
+
await spec.admissionCommit(record, { previous, next });
|
|
12482
|
+
} catch (error) {
|
|
12483
|
+
this.runSlotLimiter.release(runId);
|
|
12484
|
+
this.runSlotLimiter.acquire(previous.runId);
|
|
12485
|
+
this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
|
|
12486
|
+
throw error;
|
|
12487
|
+
}
|
|
12488
|
+
this.cleanupRunResources(previous.runId);
|
|
12489
|
+
this.notifyTerminalWaiters(previous.runId);
|
|
12490
|
+
const controller = new AbortController();
|
|
12491
|
+
forwardParentAbortSignal(controller, spec.parentSignal);
|
|
12492
|
+
return this.attachRun(record, spec, controller);
|
|
12493
|
+
}
|
|
12494
|
+
async restoreRun(spec) {
|
|
12495
|
+
if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
|
|
12496
|
+
return this.withRunControlLock(spec.runId, async () => {
|
|
12497
|
+
if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
|
|
12498
|
+
const record = await this.registryStore.load(spec.runId);
|
|
12499
|
+
if (!record) throw new RunNotFoundError(spec.runId);
|
|
12500
|
+
if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
|
|
12501
|
+
throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
|
|
12502
|
+
}
|
|
12503
|
+
this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
|
|
12504
|
+
return this.attachRun(record, spec, new AbortController());
|
|
12505
|
+
});
|
|
12506
|
+
}
|
|
12507
|
+
attachRun(record, spec, controller) {
|
|
12508
|
+
const runId = record.runId;
|
|
12152
12509
|
try {
|
|
12153
12510
|
const handle = new DefaultRunHandle({
|
|
12154
12511
|
runRecord: record,
|
|
@@ -12246,11 +12603,36 @@ var DefaultRunSupervisor = class {
|
|
|
12246
12603
|
registryStore: this.registryStore,
|
|
12247
12604
|
reason,
|
|
12248
12605
|
now: this.now,
|
|
12249
|
-
notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
|
|
12606
|
+
notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
|
|
12607
|
+
canRestoreRun: this.canRestoreRun
|
|
12250
12608
|
});
|
|
12251
12609
|
}
|
|
12252
|
-
async pause(
|
|
12253
|
-
|
|
12610
|
+
async pause(runId, reason) {
|
|
12611
|
+
await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
|
|
12612
|
+
}
|
|
12613
|
+
async resumePausedRun(input) {
|
|
12614
|
+
return this.withRunControlLock(input.runId, async () => {
|
|
12615
|
+
const handle = this.getHandle(input.runId);
|
|
12616
|
+
const record = await this.registryStore.load(input.runId);
|
|
12617
|
+
if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
|
|
12618
|
+
throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
|
|
12619
|
+
}
|
|
12620
|
+
await persistRunTransition(this.registryStore, record, {
|
|
12621
|
+
...record,
|
|
12622
|
+
status: "running",
|
|
12623
|
+
updatedAt: this.now(),
|
|
12624
|
+
pausedAt: void 0,
|
|
12625
|
+
pauseReason: void 0,
|
|
12626
|
+
errorIfAny: void 0,
|
|
12627
|
+
metadata: { ...record.metadata, executionId: input.executionId }
|
|
12628
|
+
});
|
|
12629
|
+
const controller = new AbortController();
|
|
12630
|
+
handle.replaceExecutionAbortController(controller, input.executionId);
|
|
12631
|
+
handle.attachTransportEventBus(input.eventBus);
|
|
12632
|
+
this.controllers.set(input.runId, controller);
|
|
12633
|
+
this.attachAwaitingUserWatcher(input.runId, input.eventBus);
|
|
12634
|
+
return handle;
|
|
12635
|
+
});
|
|
12254
12636
|
}
|
|
12255
12637
|
async claimResume(runId, interaction, eventBus, parentSignal) {
|
|
12256
12638
|
return this.withRunControlLock(runId, async () => {
|
|
@@ -12285,7 +12667,7 @@ var DefaultRunSupervisor = class {
|
|
|
12285
12667
|
throw new RunNotFoundError(runId);
|
|
12286
12668
|
}
|
|
12287
12669
|
const claimId = generateRunResumeClaimId();
|
|
12288
|
-
await this.registryStore
|
|
12670
|
+
await persistRunTransition(this.registryStore, record, {
|
|
12289
12671
|
...record,
|
|
12290
12672
|
updatedAt: this.now(),
|
|
12291
12673
|
metadata: {
|
|
@@ -12373,7 +12755,7 @@ var DefaultRunSupervisor = class {
|
|
|
12373
12755
|
}
|
|
12374
12756
|
const awaitingUserWithoutClaim = { ...awaitingUser };
|
|
12375
12757
|
Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
|
|
12376
|
-
|
|
12758
|
+
const nextRecord = {
|
|
12377
12759
|
...record,
|
|
12378
12760
|
status: "running",
|
|
12379
12761
|
updatedAt: this.now(),
|
|
@@ -12383,6 +12765,10 @@ var DefaultRunSupervisor = class {
|
|
|
12383
12765
|
metadata: {
|
|
12384
12766
|
...record.metadata ?? {},
|
|
12385
12767
|
...execution ? { executionId: execution.executionId } : {},
|
|
12768
|
+
...execution?.inputEventIds ? { resumeInputs: {
|
|
12769
|
+
eventIds: [...execution.inputEventIds],
|
|
12770
|
+
checkpointRevision: pendingInteraction.checkpointRevision
|
|
12771
|
+
} } : {},
|
|
12386
12772
|
awaitingUser: {
|
|
12387
12773
|
...awaitingUserWithoutClaim,
|
|
12388
12774
|
interaction: {
|
|
@@ -12391,10 +12777,12 @@ var DefaultRunSupervisor = class {
|
|
|
12391
12777
|
}
|
|
12392
12778
|
}
|
|
12393
12779
|
}
|
|
12394
|
-
}
|
|
12780
|
+
};
|
|
12781
|
+
if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
|
|
12782
|
+
else await persistRunTransition(this.registryStore, record, nextRecord);
|
|
12395
12783
|
const executionController = new AbortController();
|
|
12396
12784
|
forwardParentAbortSignal(executionController, parentSignal);
|
|
12397
|
-
handle.replaceExecutionAbortController(executionController);
|
|
12785
|
+
handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
|
|
12398
12786
|
this.controllers.set(runId, executionController);
|
|
12399
12787
|
return handle;
|
|
12400
12788
|
});
|
|
@@ -12412,7 +12800,7 @@ var DefaultRunSupervisor = class {
|
|
|
12412
12800
|
}
|
|
12413
12801
|
const awaitingUserWithoutClaim = { ...awaitingUser };
|
|
12414
12802
|
Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
|
|
12415
|
-
await this.registryStore
|
|
12803
|
+
await persistRunTransition(this.registryStore, record, {
|
|
12416
12804
|
...record,
|
|
12417
12805
|
updatedAt: this.now(),
|
|
12418
12806
|
metadata: {
|
|
@@ -12462,13 +12850,13 @@ createConsoleAudit();
|
|
|
12462
12850
|
|
|
12463
12851
|
// src/runtime-kernel/testkit/defaultGraphExecutor.ts
|
|
12464
12852
|
function createDefaultGraphExecutor(options) {
|
|
12465
|
-
const
|
|
12853
|
+
const executor2 = new GraphExecutor(
|
|
12466
12854
|
options.checkpointer ?? new MemoryCheckpointer(),
|
|
12467
12855
|
{ maxSteps: options.maxSteps ?? 8 }
|
|
12468
12856
|
);
|
|
12469
|
-
|
|
12470
|
-
|
|
12471
|
-
|
|
12857
|
+
executor2.registerNode(new UserNode());
|
|
12858
|
+
executor2.registerNode(options.llmNode);
|
|
12859
|
+
executor2.registerNode(new ToolNode({
|
|
12472
12860
|
toolRuntime: options.toolRuntime,
|
|
12473
12861
|
observationPreview: options.observationPreview,
|
|
12474
12862
|
auditPort: options.auditPort,
|
|
@@ -12476,8 +12864,8 @@ function createDefaultGraphExecutor(options) {
|
|
|
12476
12864
|
modelInputCapabilityValidator: options.modelInputCapabilityValidator,
|
|
12477
12865
|
modelInputResolver: options.modelInputResolver
|
|
12478
12866
|
}));
|
|
12479
|
-
|
|
12480
|
-
return
|
|
12867
|
+
executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
|
|
12868
|
+
return executor2;
|
|
12481
12869
|
}
|
|
12482
12870
|
|
|
12483
12871
|
// src/quickstart/functions/contextTrace.ts
|
|
@@ -12756,7 +13144,7 @@ async function runAgent(agent, options) {
|
|
|
12756
13144
|
contextBuilder: new QuickstartContextBuilder(agent),
|
|
12757
13145
|
telemetryPort
|
|
12758
13146
|
});
|
|
12759
|
-
const
|
|
13147
|
+
const executor2 = createDefaultGraphExecutor({
|
|
12760
13148
|
llmNode: new LlmNode({ reasoner }),
|
|
12761
13149
|
toolRuntime,
|
|
12762
13150
|
observationPreview: createNoopObservationPreview(),
|
|
@@ -12792,7 +13180,7 @@ async function runAgent(agent, options) {
|
|
|
12792
13180
|
};
|
|
12793
13181
|
await handle.markRunning({ currentNode: "user" });
|
|
12794
13182
|
try {
|
|
12795
|
-
await
|
|
13183
|
+
await executor2.prime(checkpointKey, {
|
|
12796
13184
|
conversationId,
|
|
12797
13185
|
turnId,
|
|
12798
13186
|
request: {
|
|
@@ -12809,7 +13197,7 @@ async function runAgent(agent, options) {
|
|
|
12809
13197
|
signal: handle.signal,
|
|
12810
13198
|
runtimeEventSink: (event, source) => publisher.publish(event, source)
|
|
12811
13199
|
});
|
|
12812
|
-
const result = await
|
|
13200
|
+
const result = await executor2.runUntilYield(checkpointKey);
|
|
12813
13201
|
await Promise.all([callbackTail, persistenceTail]);
|
|
12814
13202
|
await handle.markCompleted({
|
|
12815
13203
|
currentNode: result.checkpoint.nodeId,
|