@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.cjs
CHANGED
|
@@ -9,6 +9,7 @@ require('eventsource-parser');
|
|
|
9
9
|
var tiktoken = require('tiktoken');
|
|
10
10
|
var async_hooks = require('async_hooks');
|
|
11
11
|
var crypto = require('crypto');
|
|
12
|
+
var util = require('util');
|
|
12
13
|
|
|
13
14
|
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
14
15
|
var __defProp = Object.defineProperty;
|
|
@@ -1894,13 +1895,17 @@ __export(graph_engine_exports, {
|
|
|
1894
1895
|
MemoryEventStore: () => MemoryEventStore,
|
|
1895
1896
|
PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
|
|
1896
1897
|
PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
|
|
1898
|
+
RunPauseRequested: () => RunPauseRequested,
|
|
1899
|
+
RunRecoveryBlockedError: () => RunRecoveryBlockedError,
|
|
1897
1900
|
ToolNode: () => ToolNode,
|
|
1898
1901
|
UserNode: () => UserNode,
|
|
1899
1902
|
WaitUserNode: () => WaitUserNode,
|
|
1900
1903
|
createHostToolCallBootstrap: () => createHostToolCallBootstrap,
|
|
1901
1904
|
createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
|
|
1902
1905
|
evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
|
|
1906
|
+
isRunPauseSignal: () => isRunPauseSignal,
|
|
1903
1907
|
isRuntimeFailureFact: () => isRuntimeFailureFact,
|
|
1908
|
+
parseEngineCheckpoint: () => parseEngineCheckpoint,
|
|
1904
1909
|
readCheckpointContextUsage: () => readCheckpointContextUsage,
|
|
1905
1910
|
requireEventStoreId: () => requireEventStoreId,
|
|
1906
1911
|
resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
|
|
@@ -2495,6 +2500,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
|
|
|
2495
2500
|
"memory",
|
|
2496
2501
|
"runtimeEventSink",
|
|
2497
2502
|
"runtimeEventCommitPort",
|
|
2503
|
+
"commitExecutionBoundary",
|
|
2504
|
+
"toolRecoveryPort",
|
|
2498
2505
|
"runtimeFailureFactSink",
|
|
2499
2506
|
"signal",
|
|
2500
2507
|
"summarizationCallbacks",
|
|
@@ -3045,6 +3052,7 @@ var GraphExecutor = class {
|
|
|
3045
3052
|
maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
|
|
3046
3053
|
};
|
|
3047
3054
|
this.telemetryPort = config.telemetryPort ?? noopTelemetry;
|
|
3055
|
+
this.executionCheckpointPort = config.executionCheckpointPort;
|
|
3048
3056
|
}
|
|
3049
3057
|
checkpointer;
|
|
3050
3058
|
nodes = /* @__PURE__ */ new Map();
|
|
@@ -3052,6 +3060,7 @@ var GraphExecutor = class {
|
|
|
3052
3060
|
checkpointQueues = /* @__PURE__ */ new Map();
|
|
3053
3061
|
config;
|
|
3054
3062
|
telemetryPort;
|
|
3063
|
+
executionCheckpointPort;
|
|
3055
3064
|
registerNode(node) {
|
|
3056
3065
|
this.nodes.set(node.id, node);
|
|
3057
3066
|
}
|
|
@@ -3060,6 +3069,7 @@ var GraphExecutor = class {
|
|
|
3060
3069
|
}
|
|
3061
3070
|
sanitize(state) {
|
|
3062
3071
|
return {
|
|
3072
|
+
...state,
|
|
3063
3073
|
nodeId: state.nodeId,
|
|
3064
3074
|
revision: state.revision ?? 0,
|
|
3065
3075
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
@@ -3079,8 +3089,9 @@ var GraphExecutor = class {
|
|
|
3079
3089
|
throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
|
|
3080
3090
|
}
|
|
3081
3091
|
this.ephemeralLocals.set(checkpointKey, { ...local });
|
|
3082
|
-
await this.
|
|
3092
|
+
await this.commitCheckpoint(checkpointKey, {
|
|
3083
3093
|
nodeId,
|
|
3094
|
+
...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
|
|
3084
3095
|
revision: 1,
|
|
3085
3096
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
3086
3097
|
local: sanitizeCheckpointLocal(local)
|
|
@@ -3091,6 +3102,33 @@ var GraphExecutor = class {
|
|
|
3091
3102
|
);
|
|
3092
3103
|
});
|
|
3093
3104
|
}
|
|
3105
|
+
/** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
|
|
3106
|
+
async continueSession(checkpointKey, input) {
|
|
3107
|
+
if (!this.executionCheckpointPort) {
|
|
3108
|
+
throw new Error("continueSession requires an ExecutionCheckpointPort");
|
|
3109
|
+
}
|
|
3110
|
+
return this.runWithCheckpointQueue(checkpointKey, async () => {
|
|
3111
|
+
const current = await this.checkpointer.load(checkpointKey);
|
|
3112
|
+
if (!current || current.revision !== input.expectedRevision) {
|
|
3113
|
+
throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
|
|
3114
|
+
}
|
|
3115
|
+
if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
|
|
3116
|
+
throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
|
|
3117
|
+
}
|
|
3118
|
+
if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
|
|
3119
|
+
return { checkpoint: current, events: [], stepCount: 0 };
|
|
3120
|
+
}
|
|
3121
|
+
this.ephemeralLocals.set(checkpointKey, input.capabilities);
|
|
3122
|
+
try {
|
|
3123
|
+
return await this.runUntilYieldQueued(
|
|
3124
|
+
checkpointKey,
|
|
3125
|
+
current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
|
|
3126
|
+
);
|
|
3127
|
+
} finally {
|
|
3128
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
3129
|
+
}
|
|
3130
|
+
});
|
|
3131
|
+
}
|
|
3094
3132
|
/** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
|
|
3095
3133
|
async resumeSession(checkpointKey, input) {
|
|
3096
3134
|
return this.runWithCheckpointQueue(checkpointKey, async () => {
|
|
@@ -3111,17 +3149,21 @@ var GraphExecutor = class {
|
|
|
3111
3149
|
);
|
|
3112
3150
|
}
|
|
3113
3151
|
const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
|
|
3152
|
+
if (this.executionCheckpointPort && current.local?.executorLocal) {
|
|
3153
|
+
resumedLocal.executorLocal = { ...current.local.executorLocal };
|
|
3154
|
+
}
|
|
3114
3155
|
this.ephemeralLocals.set(checkpointKey, resumedLocal);
|
|
3115
|
-
await this.
|
|
3156
|
+
await this.commitCheckpoint(checkpointKey, {
|
|
3116
3157
|
...current,
|
|
3117
3158
|
nodeId: input.nodeId ?? "llm",
|
|
3159
|
+
...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
|
|
3118
3160
|
revision: currentRevision + 1,
|
|
3119
3161
|
local: sanitizeCheckpointLocal(resumedLocal)
|
|
3120
3162
|
});
|
|
3121
3163
|
const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
|
|
3122
3164
|
return this.runUntilYieldQueued(
|
|
3123
3165
|
checkpointKey,
|
|
3124
|
-
input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
|
|
3166
|
+
this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
|
|
3125
3167
|
);
|
|
3126
3168
|
});
|
|
3127
3169
|
}
|
|
@@ -3212,16 +3254,23 @@ var GraphExecutor = class {
|
|
|
3212
3254
|
};
|
|
3213
3255
|
}
|
|
3214
3256
|
async saveCheckpoint(checkpointKey, state) {
|
|
3215
|
-
const
|
|
3257
|
+
const checkpoint2 = this.sanitize({
|
|
3216
3258
|
...state,
|
|
3217
3259
|
revision: (state.revision ?? 0) + 1
|
|
3218
3260
|
});
|
|
3219
|
-
await this.
|
|
3220
|
-
return
|
|
3261
|
+
await this.commitCheckpoint(checkpointKey, checkpoint2);
|
|
3262
|
+
return checkpoint2;
|
|
3263
|
+
}
|
|
3264
|
+
async commitCheckpoint(checkpointKey, checkpoint2) {
|
|
3265
|
+
if (this.executionCheckpointPort) {
|
|
3266
|
+
await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
|
|
3267
|
+
} else {
|
|
3268
|
+
await this.checkpointer.save(checkpointKey, checkpoint2);
|
|
3269
|
+
}
|
|
3221
3270
|
}
|
|
3222
3271
|
async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
|
|
3223
|
-
const
|
|
3224
|
-
return { events, checkpoint, stepCount };
|
|
3272
|
+
const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
|
|
3273
|
+
return { events, checkpoint: checkpoint2, stepCount };
|
|
3225
3274
|
}
|
|
3226
3275
|
async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
|
|
3227
3276
|
let state = initialState;
|
|
@@ -3231,6 +3280,15 @@ var GraphExecutor = class {
|
|
|
3231
3280
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
3232
3281
|
local: { ...state.local || {}, ...ephemeral }
|
|
3233
3282
|
};
|
|
3283
|
+
if (this.executionCheckpointPort) {
|
|
3284
|
+
state.local = {
|
|
3285
|
+
...state.local,
|
|
3286
|
+
commitExecutionBoundary: async (boundary) => {
|
|
3287
|
+
const saved = await this.saveCheckpoint(checkpointKey, boundary);
|
|
3288
|
+
boundary.revision = saved.revision;
|
|
3289
|
+
}
|
|
3290
|
+
};
|
|
3291
|
+
}
|
|
3234
3292
|
const isAbortSignal2 = (v) => {
|
|
3235
3293
|
return v !== null && typeof v === "object" && "aborted" in v;
|
|
3236
3294
|
};
|
|
@@ -3240,11 +3298,12 @@ var GraphExecutor = class {
|
|
|
3240
3298
|
throw err;
|
|
3241
3299
|
};
|
|
3242
3300
|
let stepCount = 0;
|
|
3301
|
+
const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
|
|
3243
3302
|
let allEvents = [];
|
|
3244
3303
|
logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
|
|
3245
3304
|
maxSteps
|
|
3246
3305
|
});
|
|
3247
|
-
while (stepCount < maxSteps) {
|
|
3306
|
+
while (previousSteps + stepCount < maxSteps) {
|
|
3248
3307
|
stepCount += 1;
|
|
3249
3308
|
reportStepsUsed(stepCount);
|
|
3250
3309
|
const signalRaw = state.local?.signal;
|
|
@@ -3256,7 +3315,7 @@ var GraphExecutor = class {
|
|
|
3256
3315
|
const stepPreparation = prepareGraphStep({
|
|
3257
3316
|
state,
|
|
3258
3317
|
maxSteps,
|
|
3259
|
-
stepCount
|
|
3318
|
+
stepCount: previousSteps + stepCount
|
|
3260
3319
|
});
|
|
3261
3320
|
state = stepPreparation.state;
|
|
3262
3321
|
const node = this.nodes.get(state.nodeId);
|
|
@@ -3265,6 +3324,7 @@ var GraphExecutor = class {
|
|
|
3265
3324
|
maxSteps,
|
|
3266
3325
|
stepCount
|
|
3267
3326
|
});
|
|
3327
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
3268
3328
|
const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
3269
3329
|
this.ephemeralLocals.delete(checkpointKey);
|
|
3270
3330
|
return result3;
|
|
@@ -3274,6 +3334,11 @@ var GraphExecutor = class {
|
|
|
3274
3334
|
stepCount,
|
|
3275
3335
|
nodeId: state.nodeId
|
|
3276
3336
|
});
|
|
3337
|
+
if (this.executionCheckpointPort) {
|
|
3338
|
+
state.executionStatus = "executing";
|
|
3339
|
+
const saved = await this.saveCheckpoint(checkpointKey, state);
|
|
3340
|
+
state.revision = saved.revision;
|
|
3341
|
+
}
|
|
3277
3342
|
const result2 = await runGraphNodeWithTelemetry({
|
|
3278
3343
|
node,
|
|
3279
3344
|
state,
|
|
@@ -3298,10 +3363,13 @@ var GraphExecutor = class {
|
|
|
3298
3363
|
fromNodeId: stepResolution.action.fromNodeId,
|
|
3299
3364
|
nextNodeId: stepResolution.action.nextNodeId
|
|
3300
3365
|
});
|
|
3301
|
-
|
|
3366
|
+
if (this.executionCheckpointPort) state.executionStatus = "ready";
|
|
3367
|
+
const saved = await this.saveCheckpoint(checkpointKey, state);
|
|
3368
|
+
state.revision = saved.revision;
|
|
3302
3369
|
continue;
|
|
3303
3370
|
}
|
|
3304
3371
|
if (stepResolution.action.kind === "yield") {
|
|
3372
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
3305
3373
|
logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
|
|
3306
3374
|
maxSteps,
|
|
3307
3375
|
stepCount
|
|
@@ -3312,6 +3380,7 @@ var GraphExecutor = class {
|
|
|
3312
3380
|
maxSteps,
|
|
3313
3381
|
stepCount
|
|
3314
3382
|
});
|
|
3383
|
+
if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
|
|
3315
3384
|
return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
3316
3385
|
}
|
|
3317
3386
|
logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
|
|
@@ -3332,6 +3401,7 @@ var GraphExecutor = class {
|
|
|
3332
3401
|
},
|
|
3333
3402
|
retryable: false
|
|
3334
3403
|
}), "GraphExecutor.engine_budget_exhausted"));
|
|
3404
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
3335
3405
|
const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
3336
3406
|
this.ephemeralLocals.delete(checkpointKey);
|
|
3337
3407
|
return result;
|
|
@@ -7007,10 +7077,11 @@ var LlmNode = class {
|
|
|
7007
7077
|
bridge.handle
|
|
7008
7078
|
);
|
|
7009
7079
|
} catch (error) {
|
|
7010
|
-
bridge.finalizePartialAnswer();
|
|
7080
|
+
if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
|
|
7011
7081
|
throw error;
|
|
7012
7082
|
}
|
|
7013
7083
|
const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
|
|
7084
|
+
if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
|
|
7014
7085
|
switch (decision.kind) {
|
|
7015
7086
|
case "tool_calls": {
|
|
7016
7087
|
if (forceFinalAnswer) {
|
|
@@ -8217,6 +8288,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
|
|
|
8217
8288
|
function recordToolProtocolError(params) {
|
|
8218
8289
|
}
|
|
8219
8290
|
|
|
8291
|
+
// src/runtime-kernel/graph-engine/definitions/runContinuation.ts
|
|
8292
|
+
var RunRecoveryBlockedError = class extends Error {
|
|
8293
|
+
code = "RUN_RECOVERY_BLOCKED";
|
|
8294
|
+
constructor(message) {
|
|
8295
|
+
super(message);
|
|
8296
|
+
this.name = "RunRecoveryBlockedError";
|
|
8297
|
+
}
|
|
8298
|
+
};
|
|
8299
|
+
var RunPauseRequested = class extends Error {
|
|
8300
|
+
code = "RUN_PAUSE_REQUESTED";
|
|
8301
|
+
constructor(message = "Run paused by user") {
|
|
8302
|
+
super(message);
|
|
8303
|
+
this.name = "RunPauseRequested";
|
|
8304
|
+
}
|
|
8305
|
+
};
|
|
8306
|
+
function isRunPauseSignal(signal) {
|
|
8307
|
+
const reason = signal?.reason;
|
|
8308
|
+
return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
|
|
8309
|
+
}
|
|
8310
|
+
|
|
8311
|
+
// src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
|
|
8312
|
+
async function executeRecoverableTool(input) {
|
|
8313
|
+
const local = input.state.local;
|
|
8314
|
+
if (!local?.commitExecutionBoundary) return input.execute();
|
|
8315
|
+
if (local.executingToolCallId) {
|
|
8316
|
+
if (local.executingToolCallId !== input.call.id) {
|
|
8317
|
+
throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
|
|
8318
|
+
}
|
|
8319
|
+
const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
|
|
8320
|
+
if (!decision || decision.kind === "blocked") {
|
|
8321
|
+
throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
|
|
8322
|
+
}
|
|
8323
|
+
if (decision.kind === "settled") return decision.result;
|
|
8324
|
+
}
|
|
8325
|
+
local.executingToolCallId = input.call.id;
|
|
8326
|
+
await local.commitExecutionBoundary(input.state);
|
|
8327
|
+
const result = await input.execute();
|
|
8328
|
+
if (!result.success && isRunPauseSignal(local.signal)) {
|
|
8329
|
+
const error = new Error("Tool execution paused before its outcome was confirmed");
|
|
8330
|
+
error.name = "AbortError";
|
|
8331
|
+
throw error;
|
|
8332
|
+
}
|
|
8333
|
+
return result;
|
|
8334
|
+
}
|
|
8335
|
+
async function commitToolBoundary(state, result) {
|
|
8336
|
+
if (!state.local?.commitExecutionBoundary) return;
|
|
8337
|
+
delete state.local.executingToolCallId;
|
|
8338
|
+
state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
|
|
8339
|
+
state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
|
|
8340
|
+
await state.local.commitExecutionBoundary(state);
|
|
8341
|
+
}
|
|
8342
|
+
|
|
8220
8343
|
// src/runtime-kernel/graph-engine/nodes/toolNode.ts
|
|
8221
8344
|
var logger11 = new Logger("ToolNode");
|
|
8222
8345
|
function isAbortSignal(value) {
|
|
@@ -8387,6 +8510,7 @@ var ToolNode = class {
|
|
|
8387
8510
|
const events = [];
|
|
8388
8511
|
while (true) {
|
|
8389
8512
|
const result = await this.runNextPendingToolCall(state);
|
|
8513
|
+
await commitToolBoundary(state, result);
|
|
8390
8514
|
if (Array.isArray(result.events) && result.events.length > 0) {
|
|
8391
8515
|
events.push(...result.events);
|
|
8392
8516
|
}
|
|
@@ -8403,11 +8527,9 @@ var ToolNode = class {
|
|
|
8403
8527
|
const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
|
|
8404
8528
|
const signalRaw = state.local?.signal;
|
|
8405
8529
|
if (isAbortSignal(signalRaw) && signalRaw.aborted) {
|
|
8406
|
-
|
|
8407
|
-
state,
|
|
8408
|
-
|
|
8409
|
-
toolCatalog: this.toolRuntime
|
|
8410
|
-
});
|
|
8530
|
+
if (!isRunPauseSignal(signalRaw)) {
|
|
8531
|
+
settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
|
|
8532
|
+
}
|
|
8411
8533
|
const abortError = new Error("The user aborted a request.");
|
|
8412
8534
|
abortError.name = "AbortError";
|
|
8413
8535
|
throw abortError;
|
|
@@ -8546,16 +8668,21 @@ var ToolNode = class {
|
|
|
8546
8668
|
tool_calls: [call]
|
|
8547
8669
|
});
|
|
8548
8670
|
try {
|
|
8549
|
-
const exec = await
|
|
8550
|
-
|
|
8551
|
-
|
|
8552
|
-
|
|
8553
|
-
|
|
8554
|
-
|
|
8555
|
-
|
|
8556
|
-
|
|
8557
|
-
|
|
8558
|
-
|
|
8671
|
+
const exec = await executeRecoverableTool({
|
|
8672
|
+
state,
|
|
8673
|
+
call,
|
|
8674
|
+
context: prepared.toolContext,
|
|
8675
|
+
execute: () => executeToolWithIdempotency({
|
|
8676
|
+
idempotencyKey: execution.idempotencyKey,
|
|
8677
|
+
inFlight: this.idempotencyInFlight,
|
|
8678
|
+
history: readHistoryEvents(prepared.local),
|
|
8679
|
+
toolName: execution.toolName,
|
|
8680
|
+
execute: () => this.toolRuntime.executeTool(
|
|
8681
|
+
execution.toolName,
|
|
8682
|
+
execution.toolArgs,
|
|
8683
|
+
prepared.toolContext
|
|
8684
|
+
)
|
|
8685
|
+
})
|
|
8559
8686
|
});
|
|
8560
8687
|
if (exec.success) {
|
|
8561
8688
|
const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
|
|
@@ -8635,7 +8762,7 @@ var ToolNode = class {
|
|
|
8635
8762
|
bridge: execution.bridge
|
|
8636
8763
|
});
|
|
8637
8764
|
} catch (error) {
|
|
8638
|
-
if (isToolExecutionAbort(error)) {
|
|
8765
|
+
if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
|
|
8639
8766
|
settleToolCallsAfterExecutionAbort({
|
|
8640
8767
|
state,
|
|
8641
8768
|
remainingCalls: calls.slice(1),
|
|
@@ -8695,7 +8822,7 @@ var ToolNode = class {
|
|
|
8695
8822
|
{
|
|
8696
8823
|
attachments: context.attachments,
|
|
8697
8824
|
metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
|
|
8698
|
-
|
|
8825
|
+
// 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
|
|
8699
8826
|
durationMs: context.exec.durationMs
|
|
8700
8827
|
}
|
|
8701
8828
|
);
|
|
@@ -8752,6 +8879,9 @@ var ToolNode = class {
|
|
|
8752
8879
|
return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
|
|
8753
8880
|
}
|
|
8754
8881
|
async handleError(context) {
|
|
8882
|
+
if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
|
|
8883
|
+
throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
|
|
8884
|
+
}
|
|
8755
8885
|
if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
|
|
8756
8886
|
await this.emitToolDecisionAudit({
|
|
8757
8887
|
action: "tool.deny",
|
|
@@ -8988,16 +9118,16 @@ function requireEventStoreId(eventStoreId) {
|
|
|
8988
9118
|
}
|
|
8989
9119
|
function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
|
|
8990
9120
|
let lastTimestamp = 0;
|
|
8991
|
-
let
|
|
9121
|
+
let counter2 = 0;
|
|
8992
9122
|
return () => {
|
|
8993
9123
|
const timestamp = Math.max(nowProvider(), lastTimestamp);
|
|
8994
9124
|
if (timestamp === lastTimestamp) {
|
|
8995
|
-
|
|
9125
|
+
counter2 += 1;
|
|
8996
9126
|
} else {
|
|
8997
9127
|
lastTimestamp = timestamp;
|
|
8998
|
-
|
|
9128
|
+
counter2 = 0;
|
|
8999
9129
|
}
|
|
9000
|
-
return `${String(timestamp).padStart(13, "0")}-${String(
|
|
9130
|
+
return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
|
|
9001
9131
|
};
|
|
9002
9132
|
}
|
|
9003
9133
|
|
|
@@ -9409,6 +9539,76 @@ function assertNonNegativeSafeInteger(value, field) {
|
|
|
9409
9539
|
throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
|
|
9410
9540
|
}
|
|
9411
9541
|
}
|
|
9542
|
+
var counter = zod.z.number().int().nonnegative();
|
|
9543
|
+
var executor = zod.z.object({
|
|
9544
|
+
stepCount: counter,
|
|
9545
|
+
phase: zod.z.string().optional(),
|
|
9546
|
+
maxSteps: counter.optional(),
|
|
9547
|
+
remainingSteps: zod.z.number().int().optional(),
|
|
9548
|
+
finalStepPolicy: zod.z.enum(["final_answer", "force_tools"]).optional(),
|
|
9549
|
+
finalStepForcedTools: zod.z.array(zod.z.string()).optional(),
|
|
9550
|
+
lastStepsHintThreshold: counter.optional(),
|
|
9551
|
+
systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
|
|
9552
|
+
toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
|
|
9553
|
+
runLockedModelId: zod.z.string().optional(),
|
|
9554
|
+
lastSuccessfulLlmModelId: zod.z.string().optional(),
|
|
9555
|
+
llmInvocationKind: zod.z.enum(["user_initiated", "continuation"]).optional(),
|
|
9556
|
+
llmInvocationCount: counter.optional(),
|
|
9557
|
+
lockRequestedModelId: zod.z.boolean().optional(),
|
|
9558
|
+
contextCompaction: zod.z.object({
|
|
9559
|
+
attemptCount: counter,
|
|
9560
|
+
committedCount: counter,
|
|
9561
|
+
lastCommittedFingerprint: zod.z.string().optional()
|
|
9562
|
+
}).strict().optional()
|
|
9563
|
+
}).strict();
|
|
9564
|
+
var checkpoint = zod.z.object({
|
|
9565
|
+
nodeId: zod.z.string().min(1),
|
|
9566
|
+
schemaVersion: zod.z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
|
|
9567
|
+
revision: counter.optional(),
|
|
9568
|
+
executionStatus: zod.z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
|
|
9569
|
+
local: zod.z.object({
|
|
9570
|
+
runId: RunIdSchema.optional(),
|
|
9571
|
+
parentRunId: RunIdSchema.optional(),
|
|
9572
|
+
conversationId: zod.z.string().optional(),
|
|
9573
|
+
turnId: zod.z.string().optional(),
|
|
9574
|
+
request: SerializableJsonRecord.optional(),
|
|
9575
|
+
history: zod.z.array(RuntimeEvent).optional(),
|
|
9576
|
+
newEvents: zod.z.array(RuntimeEvent).optional(),
|
|
9577
|
+
executorLocal: executor.optional(),
|
|
9578
|
+
pendingToolCalls: zod.z.array(zod.z.object({
|
|
9579
|
+
id: ToolCallIdSchema,
|
|
9580
|
+
type: zod.z.literal("function"),
|
|
9581
|
+
function: zod.z.object({ name: zod.z.string().min(1), arguments: zod.z.string() }).strict()
|
|
9582
|
+
}).strict()).optional(),
|
|
9583
|
+
executingToolCallId: ToolCallIdSchema.optional(),
|
|
9584
|
+
toolBatchCompletionMode: zod.z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
|
|
9585
|
+
pendingInteractionSpec: SerializableJsonRecord.optional(),
|
|
9586
|
+
lastToolResult: SerializableJsonRecord.optional(),
|
|
9587
|
+
finalAnswer: zod.z.string().optional(),
|
|
9588
|
+
answerId: zod.z.string().optional(),
|
|
9589
|
+
chunkSeq: counter.optional(),
|
|
9590
|
+
contextUsage: ContextUsageSnapshot.optional()
|
|
9591
|
+
}).passthrough().optional()
|
|
9592
|
+
}).strict();
|
|
9593
|
+
function parseEngineCheckpoint(value) {
|
|
9594
|
+
const result = checkpoint.parse(SerializableJsonRecord.parse(value));
|
|
9595
|
+
for (const key of [
|
|
9596
|
+
"memory",
|
|
9597
|
+
"signal",
|
|
9598
|
+
"toolContext",
|
|
9599
|
+
"runtimeEventSink",
|
|
9600
|
+
"runtimeEventCommitPort",
|
|
9601
|
+
"runtimeFailureFactSink",
|
|
9602
|
+
"summarizationCallbacks",
|
|
9603
|
+
"commitExecutionBoundary",
|
|
9604
|
+
"toolRecoveryPort"
|
|
9605
|
+
]) {
|
|
9606
|
+
if (result.local && Object.hasOwn(result.local, key)) {
|
|
9607
|
+
throw new Error(`Checkpoint must not contain execution capability: ${key}`);
|
|
9608
|
+
}
|
|
9609
|
+
}
|
|
9610
|
+
return result;
|
|
9611
|
+
}
|
|
9412
9612
|
|
|
9413
9613
|
// src/runtime-kernel/execution/index.ts
|
|
9414
9614
|
var execution_exports = {};
|
|
@@ -9649,12 +9849,33 @@ var RuntimeEventPublisher = class {
|
|
|
9649
9849
|
var EventBusEventPersistence = class {
|
|
9650
9850
|
constructor(options) {
|
|
9651
9851
|
this.options = options;
|
|
9852
|
+
this.checkpointWritesActive = options.checkpointWriter !== void 0;
|
|
9652
9853
|
}
|
|
9653
9854
|
options;
|
|
9654
9855
|
scheduledEventIds = /* @__PURE__ */ new Set();
|
|
9655
9856
|
writeTail = Promise.resolve();
|
|
9656
9857
|
firstWriteError;
|
|
9657
9858
|
connected = false;
|
|
9859
|
+
checkpointWritesActive;
|
|
9860
|
+
checkpointEvents = [];
|
|
9861
|
+
/** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
|
|
9862
|
+
async commitCheckpoint(checkpointKey, checkpoint2) {
|
|
9863
|
+
const writer = this.options.checkpointWriter;
|
|
9864
|
+
if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
|
|
9865
|
+
const events = this.checkpointEvents;
|
|
9866
|
+
this.checkpointEvents = [];
|
|
9867
|
+
await this.enqueueWrite(() => writer({
|
|
9868
|
+
checkpointKey,
|
|
9869
|
+
checkpoint: checkpoint2,
|
|
9870
|
+
events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
|
|
9871
|
+
}));
|
|
9872
|
+
}
|
|
9873
|
+
/** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
|
|
9874
|
+
finishCheckpointWrites() {
|
|
9875
|
+
for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
|
|
9876
|
+
this.checkpointEvents = [];
|
|
9877
|
+
this.checkpointWritesActive = false;
|
|
9878
|
+
}
|
|
9658
9879
|
connect() {
|
|
9659
9880
|
if (this.connected) {
|
|
9660
9881
|
throw new Error("[EventBusEventPersistence] consumer is already connected");
|
|
@@ -9701,14 +9922,22 @@ var EventBusEventPersistence = class {
|
|
|
9701
9922
|
if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
|
|
9702
9923
|
return;
|
|
9703
9924
|
}
|
|
9925
|
+
if (this.checkpointWritesActive) {
|
|
9926
|
+
this.scheduledEventIds.add(event.id);
|
|
9927
|
+
this.checkpointEvents.push(event);
|
|
9928
|
+
return;
|
|
9929
|
+
}
|
|
9704
9930
|
void this.scheduleWrite(event).catch(() => void 0);
|
|
9705
9931
|
};
|
|
9706
9932
|
scheduleWrite(event) {
|
|
9707
9933
|
this.scheduledEventIds.add(event.id);
|
|
9708
|
-
|
|
9709
|
-
|
|
9710
|
-
|
|
9711
|
-
});
|
|
9934
|
+
return this.enqueueWrite(() => this.options.eventStore.append({
|
|
9935
|
+
eventStoreId: this.options.nextEventStoreId(),
|
|
9936
|
+
event
|
|
9937
|
+
}));
|
|
9938
|
+
}
|
|
9939
|
+
enqueueWrite(operation) {
|
|
9940
|
+
const write = this.writeTail.then(operation);
|
|
9712
9941
|
this.writeTail = write;
|
|
9713
9942
|
void write.catch((error) => {
|
|
9714
9943
|
this.firstWriteError ??= error;
|
|
@@ -11115,8 +11344,6 @@ __export(run_supervisor_exports, {
|
|
|
11115
11344
|
RunNotFoundError: () => RunNotFoundError,
|
|
11116
11345
|
runMetaFromRecord: () => runMetaFromRecord
|
|
11117
11346
|
});
|
|
11118
|
-
|
|
11119
|
-
// src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
|
|
11120
11347
|
function cloneRunRecord(record) {
|
|
11121
11348
|
return {
|
|
11122
11349
|
...record,
|
|
@@ -11136,6 +11363,11 @@ function matchesStatus(candidate, filter) {
|
|
|
11136
11363
|
}
|
|
11137
11364
|
var MemoryRunRegistryStore = class {
|
|
11138
11365
|
store = /* @__PURE__ */ new Map();
|
|
11366
|
+
async compareAndSwap(previous, next) {
|
|
11367
|
+
if (previous.runId !== next.runId || !util.isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
|
|
11368
|
+
this.store.set(next.runId, cloneRunRecord(next));
|
|
11369
|
+
return true;
|
|
11370
|
+
}
|
|
11139
11371
|
async save(record) {
|
|
11140
11372
|
this.store.set(record.runId, cloneRunRecord(record));
|
|
11141
11373
|
}
|
|
@@ -11283,6 +11515,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
|
|
|
11283
11515
|
}
|
|
11284
11516
|
};
|
|
11285
11517
|
|
|
11518
|
+
// src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
|
|
11519
|
+
async function persistRunTransition(store, previous, next) {
|
|
11520
|
+
if (store.compareAndSwap) {
|
|
11521
|
+
if (!await store.compareAndSwap(previous, next)) {
|
|
11522
|
+
throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
|
|
11523
|
+
}
|
|
11524
|
+
} else {
|
|
11525
|
+
await store.save(next);
|
|
11526
|
+
}
|
|
11527
|
+
}
|
|
11528
|
+
|
|
11286
11529
|
// src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
|
|
11287
11530
|
function isRunTerminalStatus(status) {
|
|
11288
11531
|
return status === "completed" || status === "failed" || status === "cancelled";
|
|
@@ -11338,6 +11581,7 @@ var DefaultRunHandle = class {
|
|
|
11338
11581
|
parentRunId;
|
|
11339
11582
|
runRecord;
|
|
11340
11583
|
abortController;
|
|
11584
|
+
executionId;
|
|
11341
11585
|
agentSpecSnapshot;
|
|
11342
11586
|
requestSnapshot;
|
|
11343
11587
|
transportEventBus;
|
|
@@ -11353,6 +11597,9 @@ var DefaultRunHandle = class {
|
|
|
11353
11597
|
this.runId = options.runRecord.runId;
|
|
11354
11598
|
this.parentRunId = options.runRecord.parentRunId;
|
|
11355
11599
|
this.abortController = options.abortController;
|
|
11600
|
+
const executionId = options.runRecord.metadata?.executionId;
|
|
11601
|
+
if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
|
|
11602
|
+
this.executionId = executionId;
|
|
11356
11603
|
this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
|
|
11357
11604
|
this.requestSnapshot = cloneRequest(options.request);
|
|
11358
11605
|
this.transportEventBus = options.eventBus;
|
|
@@ -11372,8 +11619,9 @@ var DefaultRunHandle = class {
|
|
|
11372
11619
|
* awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
|
|
11373
11620
|
* 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
|
|
11374
11621
|
*/
|
|
11375
|
-
replaceExecutionAbortController(controller) {
|
|
11622
|
+
replaceExecutionAbortController(controller, executionId) {
|
|
11376
11623
|
this.abortController = controller;
|
|
11624
|
+
this.executionId = executionId;
|
|
11377
11625
|
}
|
|
11378
11626
|
async spec() {
|
|
11379
11627
|
return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
|
|
@@ -11393,6 +11641,7 @@ var DefaultRunHandle = class {
|
|
|
11393
11641
|
this.abortController.abort(opts.reason);
|
|
11394
11642
|
const latestRecord = await this.registryStore.load(this.runId);
|
|
11395
11643
|
const baseRecord = latestRecord ?? this.runRecord;
|
|
11644
|
+
this.assertExecutionOwner(baseRecord);
|
|
11396
11645
|
const transition = decideRunLifecycleTransition(baseRecord.status);
|
|
11397
11646
|
if (transition.kind === "skip_terminal") {
|
|
11398
11647
|
if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
|
|
@@ -11402,7 +11651,7 @@ var DefaultRunHandle = class {
|
|
|
11402
11651
|
currentNode: patch.currentNode ?? baseRecord.currentNode,
|
|
11403
11652
|
iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
|
|
11404
11653
|
};
|
|
11405
|
-
await this.registryStore
|
|
11654
|
+
await persistRunTransition(this.registryStore, baseRecord, settledRecord);
|
|
11406
11655
|
this.runRecord = { ...settledRecord };
|
|
11407
11656
|
return;
|
|
11408
11657
|
}
|
|
@@ -11429,7 +11678,7 @@ var DefaultRunHandle = class {
|
|
|
11429
11678
|
}
|
|
11430
11679
|
}
|
|
11431
11680
|
};
|
|
11432
|
-
await this.registryStore
|
|
11681
|
+
await persistRunTransition(this.registryStore, baseRecord, nextRecord);
|
|
11433
11682
|
this.runRecord = { ...nextRecord };
|
|
11434
11683
|
await this.auditPort.emit({
|
|
11435
11684
|
envelopeId: generateAuditEnvelopeId(),
|
|
@@ -11537,21 +11786,35 @@ var DefaultRunHandle = class {
|
|
|
11537
11786
|
async markFailed(error, patch = {}) {
|
|
11538
11787
|
await this.saveLifecycleStatus("failed", patch, error);
|
|
11539
11788
|
}
|
|
11540
|
-
async pause(
|
|
11541
|
-
|
|
11789
|
+
async pause(reason = "Run paused by user") {
|
|
11790
|
+
const latest = await this.registryStore.load(this.runId);
|
|
11791
|
+
if (latest) this.assertExecutionOwner(latest);
|
|
11792
|
+
if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
|
|
11793
|
+
const next = {
|
|
11794
|
+
...latest,
|
|
11795
|
+
status: "paused",
|
|
11796
|
+
updatedAt: Date.now(),
|
|
11797
|
+
pauseReason: reason,
|
|
11798
|
+
pausedAt: void 0
|
|
11799
|
+
};
|
|
11800
|
+
await persistRunTransition(this.registryStore, latest, next);
|
|
11801
|
+
this.runRecord = next;
|
|
11802
|
+
this.abortController.abort(new RunPauseRequested(reason));
|
|
11542
11803
|
}
|
|
11543
|
-
async
|
|
11544
|
-
|
|
11804
|
+
async markPaused(patch = {}) {
|
|
11805
|
+
await this.saveLifecycleStatus("paused", patch);
|
|
11545
11806
|
}
|
|
11546
11807
|
async saveLifecycleStatus(status, patch, errorIfAny) {
|
|
11547
11808
|
const latestRecord = await this.registryStore.load(this.runId);
|
|
11548
11809
|
const baseRecord = latestRecord ?? this.runRecord;
|
|
11549
11810
|
const transition = decideRunLifecycleTransition(baseRecord.status);
|
|
11811
|
+
this.assertExecutionOwner(baseRecord);
|
|
11812
|
+
if (status === "running" && baseRecord.status === "paused") return;
|
|
11550
11813
|
if (transition.kind === "skip_terminal") {
|
|
11551
11814
|
this.runRecord = { ...baseRecord };
|
|
11552
11815
|
return;
|
|
11553
11816
|
}
|
|
11554
|
-
const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
|
|
11817
|
+
const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
|
|
11555
11818
|
const updatedAt = Date.now();
|
|
11556
11819
|
const nextRecord = {
|
|
11557
11820
|
...baseRecord,
|
|
@@ -11559,8 +11822,8 @@ var DefaultRunHandle = class {
|
|
|
11559
11822
|
updatedAt,
|
|
11560
11823
|
currentNode: patch.currentNode ?? baseRecord.currentNode,
|
|
11561
11824
|
iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
|
|
11562
|
-
pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
|
|
11563
|
-
pausedAt: status === "awaiting_user" ? updatedAt : void 0,
|
|
11825
|
+
pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
|
|
11826
|
+
pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
|
|
11564
11827
|
errorIfAny,
|
|
11565
11828
|
metadata: awaitingUserPatch?.eventId ? {
|
|
11566
11829
|
...baseRecord.metadata ?? {},
|
|
@@ -11571,7 +11834,7 @@ var DefaultRunHandle = class {
|
|
|
11571
11834
|
}
|
|
11572
11835
|
} : baseRecord.metadata
|
|
11573
11836
|
};
|
|
11574
|
-
await this.registryStore
|
|
11837
|
+
await persistRunTransition(this.registryStore, baseRecord, nextRecord);
|
|
11575
11838
|
this.runRecord = { ...nextRecord };
|
|
11576
11839
|
if (status === "completed" || status === "failed") {
|
|
11577
11840
|
this.closeObservationChannel();
|
|
@@ -11581,6 +11844,11 @@ var DefaultRunHandle = class {
|
|
|
11581
11844
|
forwardTransportEvent = (envelope) => {
|
|
11582
11845
|
this.observationEventBus.emit("event", envelope);
|
|
11583
11846
|
};
|
|
11847
|
+
assertExecutionOwner(record) {
|
|
11848
|
+
if (record.metadata?.executionId !== this.executionId) {
|
|
11849
|
+
throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
|
|
11850
|
+
}
|
|
11851
|
+
}
|
|
11584
11852
|
forwardTransportError = (error) => {
|
|
11585
11853
|
this.observationEventBus.emit("error", error);
|
|
11586
11854
|
};
|
|
@@ -11911,7 +12179,15 @@ function createRunConcurrencyKeyRegistry() {
|
|
|
11911
12179
|
runIdByKey.delete(concurrencyKey);
|
|
11912
12180
|
}
|
|
11913
12181
|
}
|
|
11914
|
-
|
|
12182
|
+
function transfer(previous, next, concurrencyKey) {
|
|
12183
|
+
if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
|
|
12184
|
+
throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
|
|
12185
|
+
}
|
|
12186
|
+
keyByRunId.delete(previous);
|
|
12187
|
+
keyByRunId.set(next, concurrencyKey);
|
|
12188
|
+
runIdByKey.set(concurrencyKey, next);
|
|
12189
|
+
}
|
|
12190
|
+
return { acquire, release, transfer };
|
|
11915
12191
|
}
|
|
11916
12192
|
|
|
11917
12193
|
// src/runtime-kernel/run-supervisor/functions/runRegistration.ts
|
|
@@ -11962,6 +12238,24 @@ async function recoverRunsOnBoot(options) {
|
|
|
11962
12238
|
const outcomes = [];
|
|
11963
12239
|
for (const record of activeRecords) {
|
|
11964
12240
|
const updatedAt = options.now();
|
|
12241
|
+
if (await options.canRestoreRun?.(record)) {
|
|
12242
|
+
const metadata = { ...record.metadata };
|
|
12243
|
+
const awaitingUser = metadata.awaitingUser;
|
|
12244
|
+
if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
|
|
12245
|
+
const restored = { ...awaitingUser };
|
|
12246
|
+
Reflect.deleteProperty(restored, "resumeClaim");
|
|
12247
|
+
metadata.awaitingUser = restored;
|
|
12248
|
+
}
|
|
12249
|
+
await persistRunTransition(options.registryStore, record, {
|
|
12250
|
+
...record,
|
|
12251
|
+
status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
|
|
12252
|
+
pausedAt: record.pausedAt ?? updatedAt,
|
|
12253
|
+
pauseReason: record.pauseReason ?? options.reason,
|
|
12254
|
+
updatedAt,
|
|
12255
|
+
metadata
|
|
12256
|
+
});
|
|
12257
|
+
continue;
|
|
12258
|
+
}
|
|
11965
12259
|
const nextRecord = {
|
|
11966
12260
|
...record,
|
|
11967
12261
|
status: "failed",
|
|
@@ -11979,7 +12273,7 @@ async function recoverRunsOnBoot(options) {
|
|
|
11979
12273
|
}
|
|
11980
12274
|
}
|
|
11981
12275
|
};
|
|
11982
|
-
await options.registryStore
|
|
12276
|
+
await persistRunTransition(options.registryStore, record, nextRecord);
|
|
11983
12277
|
const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
|
|
11984
12278
|
options.notifyTerminal(outcome);
|
|
11985
12279
|
outcomes.push(outcome);
|
|
@@ -12103,8 +12397,13 @@ var DefaultRunSupervisor = class {
|
|
|
12103
12397
|
inFlight = /* @__PURE__ */ new Map();
|
|
12104
12398
|
eventWatchDisposers = /* @__PURE__ */ new Map();
|
|
12105
12399
|
controlOperations = /* @__PURE__ */ new Map();
|
|
12400
|
+
canRestoreRun;
|
|
12106
12401
|
constructor(options) {
|
|
12402
|
+
if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
|
|
12403
|
+
throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
|
|
12404
|
+
}
|
|
12107
12405
|
this.registryStore = options.registryStore;
|
|
12406
|
+
this.canRestoreRun = options.canRestoreRun;
|
|
12108
12407
|
this.auditPort = options.auditPort;
|
|
12109
12408
|
this.executor = options.executor;
|
|
12110
12409
|
this.runIdFactory = options.runIdFactory ?? generateRunId;
|
|
@@ -12137,6 +12436,9 @@ var DefaultRunSupervisor = class {
|
|
|
12137
12436
|
});
|
|
12138
12437
|
}
|
|
12139
12438
|
async registerRun(spec) {
|
|
12439
|
+
if (spec.replacesPausedRun) {
|
|
12440
|
+
return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
|
|
12441
|
+
}
|
|
12140
12442
|
const runId = spec.runId ?? this.runIdFactory();
|
|
12141
12443
|
if (this.handles.has(runId) || await this.registryStore.load(runId)) {
|
|
12142
12444
|
throw new RunAlreadyRegisteredError(runId);
|
|
@@ -12147,11 +12449,66 @@ var DefaultRunSupervisor = class {
|
|
|
12147
12449
|
forwardParentAbortSignal(controller, spec.parentSignal);
|
|
12148
12450
|
const record = createInitialRunRecord({ runId, spec, startedAt });
|
|
12149
12451
|
try {
|
|
12150
|
-
await
|
|
12452
|
+
if (spec.admissionCommit) await spec.admissionCommit(record);
|
|
12453
|
+
else await this.registryStore.save(record);
|
|
12151
12454
|
} catch (error) {
|
|
12152
12455
|
this.releaseRunAdmission(runId);
|
|
12153
12456
|
throw error;
|
|
12154
12457
|
}
|
|
12458
|
+
return this.attachRun(record, spec, controller);
|
|
12459
|
+
}
|
|
12460
|
+
async registerPausedReplacement(spec) {
|
|
12461
|
+
const target = spec.replacesPausedRun;
|
|
12462
|
+
if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
|
|
12463
|
+
throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
|
|
12464
|
+
}
|
|
12465
|
+
this.getHandle(target.runId);
|
|
12466
|
+
const previous = await this.registryStore.load(target.runId);
|
|
12467
|
+
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) {
|
|
12468
|
+
throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
|
|
12469
|
+
}
|
|
12470
|
+
const runId = spec.runId ?? this.runIdFactory();
|
|
12471
|
+
if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
|
|
12472
|
+
this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
|
|
12473
|
+
this.runSlotLimiter.release(previous.runId);
|
|
12474
|
+
this.runSlotLimiter.acquire(runId);
|
|
12475
|
+
const now = this.now();
|
|
12476
|
+
const record = createInitialRunRecord({ runId, spec, startedAt: now });
|
|
12477
|
+
const next = {
|
|
12478
|
+
...previous,
|
|
12479
|
+
status: "cancelled",
|
|
12480
|
+
updatedAt: now,
|
|
12481
|
+
errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
|
|
12482
|
+
};
|
|
12483
|
+
try {
|
|
12484
|
+
await spec.admissionCommit(record, { previous, next });
|
|
12485
|
+
} catch (error) {
|
|
12486
|
+
this.runSlotLimiter.release(runId);
|
|
12487
|
+
this.runSlotLimiter.acquire(previous.runId);
|
|
12488
|
+
this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
|
|
12489
|
+
throw error;
|
|
12490
|
+
}
|
|
12491
|
+
this.cleanupRunResources(previous.runId);
|
|
12492
|
+
this.notifyTerminalWaiters(previous.runId);
|
|
12493
|
+
const controller = new AbortController();
|
|
12494
|
+
forwardParentAbortSignal(controller, spec.parentSignal);
|
|
12495
|
+
return this.attachRun(record, spec, controller);
|
|
12496
|
+
}
|
|
12497
|
+
async restoreRun(spec) {
|
|
12498
|
+
if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
|
|
12499
|
+
return this.withRunControlLock(spec.runId, async () => {
|
|
12500
|
+
if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
|
|
12501
|
+
const record = await this.registryStore.load(spec.runId);
|
|
12502
|
+
if (!record) throw new RunNotFoundError(spec.runId);
|
|
12503
|
+
if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
|
|
12504
|
+
throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
|
|
12505
|
+
}
|
|
12506
|
+
this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
|
|
12507
|
+
return this.attachRun(record, spec, new AbortController());
|
|
12508
|
+
});
|
|
12509
|
+
}
|
|
12510
|
+
attachRun(record, spec, controller) {
|
|
12511
|
+
const runId = record.runId;
|
|
12155
12512
|
try {
|
|
12156
12513
|
const handle = new DefaultRunHandle({
|
|
12157
12514
|
runRecord: record,
|
|
@@ -12249,11 +12606,36 @@ var DefaultRunSupervisor = class {
|
|
|
12249
12606
|
registryStore: this.registryStore,
|
|
12250
12607
|
reason,
|
|
12251
12608
|
now: this.now,
|
|
12252
|
-
notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
|
|
12609
|
+
notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
|
|
12610
|
+
canRestoreRun: this.canRestoreRun
|
|
12253
12611
|
});
|
|
12254
12612
|
}
|
|
12255
|
-
async pause(
|
|
12256
|
-
|
|
12613
|
+
async pause(runId, reason) {
|
|
12614
|
+
await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
|
|
12615
|
+
}
|
|
12616
|
+
async resumePausedRun(input) {
|
|
12617
|
+
return this.withRunControlLock(input.runId, async () => {
|
|
12618
|
+
const handle = this.getHandle(input.runId);
|
|
12619
|
+
const record = await this.registryStore.load(input.runId);
|
|
12620
|
+
if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
|
|
12621
|
+
throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
|
|
12622
|
+
}
|
|
12623
|
+
await persistRunTransition(this.registryStore, record, {
|
|
12624
|
+
...record,
|
|
12625
|
+
status: "running",
|
|
12626
|
+
updatedAt: this.now(),
|
|
12627
|
+
pausedAt: void 0,
|
|
12628
|
+
pauseReason: void 0,
|
|
12629
|
+
errorIfAny: void 0,
|
|
12630
|
+
metadata: { ...record.metadata, executionId: input.executionId }
|
|
12631
|
+
});
|
|
12632
|
+
const controller = new AbortController();
|
|
12633
|
+
handle.replaceExecutionAbortController(controller, input.executionId);
|
|
12634
|
+
handle.attachTransportEventBus(input.eventBus);
|
|
12635
|
+
this.controllers.set(input.runId, controller);
|
|
12636
|
+
this.attachAwaitingUserWatcher(input.runId, input.eventBus);
|
|
12637
|
+
return handle;
|
|
12638
|
+
});
|
|
12257
12639
|
}
|
|
12258
12640
|
async claimResume(runId, interaction, eventBus, parentSignal) {
|
|
12259
12641
|
return this.withRunControlLock(runId, async () => {
|
|
@@ -12288,7 +12670,7 @@ var DefaultRunSupervisor = class {
|
|
|
12288
12670
|
throw new RunNotFoundError(runId);
|
|
12289
12671
|
}
|
|
12290
12672
|
const claimId = generateRunResumeClaimId();
|
|
12291
|
-
await this.registryStore
|
|
12673
|
+
await persistRunTransition(this.registryStore, record, {
|
|
12292
12674
|
...record,
|
|
12293
12675
|
updatedAt: this.now(),
|
|
12294
12676
|
metadata: {
|
|
@@ -12376,7 +12758,7 @@ var DefaultRunSupervisor = class {
|
|
|
12376
12758
|
}
|
|
12377
12759
|
const awaitingUserWithoutClaim = { ...awaitingUser };
|
|
12378
12760
|
Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
|
|
12379
|
-
|
|
12761
|
+
const nextRecord = {
|
|
12380
12762
|
...record,
|
|
12381
12763
|
status: "running",
|
|
12382
12764
|
updatedAt: this.now(),
|
|
@@ -12386,6 +12768,10 @@ var DefaultRunSupervisor = class {
|
|
|
12386
12768
|
metadata: {
|
|
12387
12769
|
...record.metadata ?? {},
|
|
12388
12770
|
...execution ? { executionId: execution.executionId } : {},
|
|
12771
|
+
...execution?.inputEventIds ? { resumeInputs: {
|
|
12772
|
+
eventIds: [...execution.inputEventIds],
|
|
12773
|
+
checkpointRevision: pendingInteraction.checkpointRevision
|
|
12774
|
+
} } : {},
|
|
12389
12775
|
awaitingUser: {
|
|
12390
12776
|
...awaitingUserWithoutClaim,
|
|
12391
12777
|
interaction: {
|
|
@@ -12394,10 +12780,12 @@ var DefaultRunSupervisor = class {
|
|
|
12394
12780
|
}
|
|
12395
12781
|
}
|
|
12396
12782
|
}
|
|
12397
|
-
}
|
|
12783
|
+
};
|
|
12784
|
+
if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
|
|
12785
|
+
else await persistRunTransition(this.registryStore, record, nextRecord);
|
|
12398
12786
|
const executionController = new AbortController();
|
|
12399
12787
|
forwardParentAbortSignal(executionController, parentSignal);
|
|
12400
|
-
handle.replaceExecutionAbortController(executionController);
|
|
12788
|
+
handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
|
|
12401
12789
|
this.controllers.set(runId, executionController);
|
|
12402
12790
|
return handle;
|
|
12403
12791
|
});
|
|
@@ -12415,7 +12803,7 @@ var DefaultRunSupervisor = class {
|
|
|
12415
12803
|
}
|
|
12416
12804
|
const awaitingUserWithoutClaim = { ...awaitingUser };
|
|
12417
12805
|
Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
|
|
12418
|
-
await this.registryStore
|
|
12806
|
+
await persistRunTransition(this.registryStore, record, {
|
|
12419
12807
|
...record,
|
|
12420
12808
|
updatedAt: this.now(),
|
|
12421
12809
|
metadata: {
|
|
@@ -12465,13 +12853,13 @@ createConsoleAudit();
|
|
|
12465
12853
|
|
|
12466
12854
|
// src/runtime-kernel/testkit/defaultGraphExecutor.ts
|
|
12467
12855
|
function createDefaultGraphExecutor(options) {
|
|
12468
|
-
const
|
|
12856
|
+
const executor2 = new GraphExecutor(
|
|
12469
12857
|
options.checkpointer ?? new MemoryCheckpointer(),
|
|
12470
12858
|
{ maxSteps: options.maxSteps ?? 8 }
|
|
12471
12859
|
);
|
|
12472
|
-
|
|
12473
|
-
|
|
12474
|
-
|
|
12860
|
+
executor2.registerNode(new UserNode());
|
|
12861
|
+
executor2.registerNode(options.llmNode);
|
|
12862
|
+
executor2.registerNode(new ToolNode({
|
|
12475
12863
|
toolRuntime: options.toolRuntime,
|
|
12476
12864
|
observationPreview: options.observationPreview,
|
|
12477
12865
|
auditPort: options.auditPort,
|
|
@@ -12479,8 +12867,8 @@ function createDefaultGraphExecutor(options) {
|
|
|
12479
12867
|
modelInputCapabilityValidator: options.modelInputCapabilityValidator,
|
|
12480
12868
|
modelInputResolver: options.modelInputResolver
|
|
12481
12869
|
}));
|
|
12482
|
-
|
|
12483
|
-
return
|
|
12870
|
+
executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
|
|
12871
|
+
return executor2;
|
|
12484
12872
|
}
|
|
12485
12873
|
|
|
12486
12874
|
// src/quickstart/functions/contextTrace.ts
|
|
@@ -12759,7 +13147,7 @@ async function runAgent(agent, options) {
|
|
|
12759
13147
|
contextBuilder: new QuickstartContextBuilder(agent),
|
|
12760
13148
|
telemetryPort
|
|
12761
13149
|
});
|
|
12762
|
-
const
|
|
13150
|
+
const executor2 = createDefaultGraphExecutor({
|
|
12763
13151
|
llmNode: new LlmNode({ reasoner }),
|
|
12764
13152
|
toolRuntime,
|
|
12765
13153
|
observationPreview: createNoopObservationPreview(),
|
|
@@ -12795,7 +13183,7 @@ async function runAgent(agent, options) {
|
|
|
12795
13183
|
};
|
|
12796
13184
|
await handle.markRunning({ currentNode: "user" });
|
|
12797
13185
|
try {
|
|
12798
|
-
await
|
|
13186
|
+
await executor2.prime(checkpointKey, {
|
|
12799
13187
|
conversationId,
|
|
12800
13188
|
turnId,
|
|
12801
13189
|
request: {
|
|
@@ -12812,7 +13200,7 @@ async function runAgent(agent, options) {
|
|
|
12812
13200
|
signal: handle.signal,
|
|
12813
13201
|
runtimeEventSink: (event, source) => publisher.publish(event, source)
|
|
12814
13202
|
});
|
|
12815
|
-
const result = await
|
|
13203
|
+
const result = await executor2.runUntilYield(checkpointKey);
|
|
12816
13204
|
await Promise.all([callbackTail, persistenceTail]);
|
|
12817
13205
|
await handle.markCompleted({
|
|
12818
13206
|
currentNode: result.checkpoint.nodeId,
|