@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/quickstart.js
CHANGED
|
@@ -3,6 +3,7 @@ import 'eventsource-parser';
|
|
|
3
3
|
import { get_encoding } from 'tiktoken';
|
|
4
4
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
5
5
|
import { createHash } from 'crypto';
|
|
6
|
+
import { isDeepStrictEqual } from 'util';
|
|
6
7
|
import 'fs/promises';
|
|
7
8
|
import 'path';
|
|
8
9
|
|
|
@@ -2005,13 +2006,17 @@ __export(graph_engine_exports, {
|
|
|
2005
2006
|
MemoryEventStore: () => MemoryEventStore,
|
|
2006
2007
|
PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
|
|
2007
2008
|
PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
|
|
2009
|
+
RunPauseRequested: () => RunPauseRequested,
|
|
2010
|
+
RunRecoveryBlockedError: () => RunRecoveryBlockedError,
|
|
2008
2011
|
ToolNode: () => ToolNode,
|
|
2009
2012
|
UserNode: () => UserNode,
|
|
2010
2013
|
WaitUserNode: () => WaitUserNode,
|
|
2011
2014
|
createHostToolCallBootstrap: () => createHostToolCallBootstrap,
|
|
2012
2015
|
createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
|
|
2013
2016
|
evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
|
|
2017
|
+
isRunPauseSignal: () => isRunPauseSignal,
|
|
2014
2018
|
isRuntimeFailureFact: () => isRuntimeFailureFact,
|
|
2019
|
+
parseEngineCheckpoint: () => parseEngineCheckpoint,
|
|
2015
2020
|
readCheckpointContextUsage: () => readCheckpointContextUsage,
|
|
2016
2021
|
requireEventStoreId: () => requireEventStoreId,
|
|
2017
2022
|
resolveEffectivePromptBudget: () => resolveEffectivePromptBudget,
|
|
@@ -2606,6 +2611,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
|
|
|
2606
2611
|
"memory",
|
|
2607
2612
|
"runtimeEventSink",
|
|
2608
2613
|
"runtimeEventCommitPort",
|
|
2614
|
+
"commitExecutionBoundary",
|
|
2615
|
+
"toolRecoveryPort",
|
|
2609
2616
|
"runtimeFailureFactSink",
|
|
2610
2617
|
"signal",
|
|
2611
2618
|
"summarizationCallbacks",
|
|
@@ -3156,6 +3163,7 @@ var GraphExecutor = class {
|
|
|
3156
3163
|
maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
|
|
3157
3164
|
};
|
|
3158
3165
|
this.telemetryPort = config.telemetryPort ?? noopTelemetry;
|
|
3166
|
+
this.executionCheckpointPort = config.executionCheckpointPort;
|
|
3159
3167
|
}
|
|
3160
3168
|
checkpointer;
|
|
3161
3169
|
nodes = /* @__PURE__ */ new Map();
|
|
@@ -3163,6 +3171,7 @@ var GraphExecutor = class {
|
|
|
3163
3171
|
checkpointQueues = /* @__PURE__ */ new Map();
|
|
3164
3172
|
config;
|
|
3165
3173
|
telemetryPort;
|
|
3174
|
+
executionCheckpointPort;
|
|
3166
3175
|
registerNode(node) {
|
|
3167
3176
|
this.nodes.set(node.id, node);
|
|
3168
3177
|
}
|
|
@@ -3171,6 +3180,7 @@ var GraphExecutor = class {
|
|
|
3171
3180
|
}
|
|
3172
3181
|
sanitize(state) {
|
|
3173
3182
|
return {
|
|
3183
|
+
...state,
|
|
3174
3184
|
nodeId: state.nodeId,
|
|
3175
3185
|
revision: state.revision ?? 0,
|
|
3176
3186
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
@@ -3190,8 +3200,9 @@ var GraphExecutor = class {
|
|
|
3190
3200
|
throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
|
|
3191
3201
|
}
|
|
3192
3202
|
this.ephemeralLocals.set(checkpointKey, { ...local });
|
|
3193
|
-
await this.
|
|
3203
|
+
await this.commitCheckpoint(checkpointKey, {
|
|
3194
3204
|
nodeId,
|
|
3205
|
+
...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
|
|
3195
3206
|
revision: 1,
|
|
3196
3207
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
3197
3208
|
local: sanitizeCheckpointLocal(local)
|
|
@@ -3202,6 +3213,33 @@ var GraphExecutor = class {
|
|
|
3202
3213
|
);
|
|
3203
3214
|
});
|
|
3204
3215
|
}
|
|
3216
|
+
/** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
|
|
3217
|
+
async continueSession(checkpointKey, input) {
|
|
3218
|
+
if (!this.executionCheckpointPort) {
|
|
3219
|
+
throw new Error("continueSession requires an ExecutionCheckpointPort");
|
|
3220
|
+
}
|
|
3221
|
+
return this.runWithCheckpointQueue(checkpointKey, async () => {
|
|
3222
|
+
const current = await this.checkpointer.load(checkpointKey);
|
|
3223
|
+
if (!current || current.revision !== input.expectedRevision) {
|
|
3224
|
+
throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
|
|
3225
|
+
}
|
|
3226
|
+
if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
|
|
3227
|
+
throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
|
|
3228
|
+
}
|
|
3229
|
+
if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
|
|
3230
|
+
return { checkpoint: current, events: [], stepCount: 0 };
|
|
3231
|
+
}
|
|
3232
|
+
this.ephemeralLocals.set(checkpointKey, input.capabilities);
|
|
3233
|
+
try {
|
|
3234
|
+
return await this.runUntilYieldQueued(
|
|
3235
|
+
checkpointKey,
|
|
3236
|
+
current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
|
|
3237
|
+
);
|
|
3238
|
+
} finally {
|
|
3239
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
3240
|
+
}
|
|
3241
|
+
});
|
|
3242
|
+
}
|
|
3205
3243
|
/** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
|
|
3206
3244
|
async resumeSession(checkpointKey, input) {
|
|
3207
3245
|
return this.runWithCheckpointQueue(checkpointKey, async () => {
|
|
@@ -3222,17 +3260,21 @@ var GraphExecutor = class {
|
|
|
3222
3260
|
);
|
|
3223
3261
|
}
|
|
3224
3262
|
const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
|
|
3263
|
+
if (this.executionCheckpointPort && current.local?.executorLocal) {
|
|
3264
|
+
resumedLocal.executorLocal = { ...current.local.executorLocal };
|
|
3265
|
+
}
|
|
3225
3266
|
this.ephemeralLocals.set(checkpointKey, resumedLocal);
|
|
3226
|
-
await this.
|
|
3267
|
+
await this.commitCheckpoint(checkpointKey, {
|
|
3227
3268
|
...current,
|
|
3228
3269
|
nodeId: input.nodeId ?? "llm",
|
|
3270
|
+
...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
|
|
3229
3271
|
revision: currentRevision + 1,
|
|
3230
3272
|
local: sanitizeCheckpointLocal(resumedLocal)
|
|
3231
3273
|
});
|
|
3232
3274
|
const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
|
|
3233
3275
|
return this.runUntilYieldQueued(
|
|
3234
3276
|
checkpointKey,
|
|
3235
|
-
input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
|
|
3277
|
+
this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
|
|
3236
3278
|
);
|
|
3237
3279
|
});
|
|
3238
3280
|
}
|
|
@@ -3323,16 +3365,23 @@ var GraphExecutor = class {
|
|
|
3323
3365
|
};
|
|
3324
3366
|
}
|
|
3325
3367
|
async saveCheckpoint(checkpointKey, state) {
|
|
3326
|
-
const
|
|
3368
|
+
const checkpoint2 = this.sanitize({
|
|
3327
3369
|
...state,
|
|
3328
3370
|
revision: (state.revision ?? 0) + 1
|
|
3329
3371
|
});
|
|
3330
|
-
await this.
|
|
3331
|
-
return
|
|
3372
|
+
await this.commitCheckpoint(checkpointKey, checkpoint2);
|
|
3373
|
+
return checkpoint2;
|
|
3374
|
+
}
|
|
3375
|
+
async commitCheckpoint(checkpointKey, checkpoint2) {
|
|
3376
|
+
if (this.executionCheckpointPort) {
|
|
3377
|
+
await this.executionCheckpointPort.commit(checkpointKey, checkpoint2);
|
|
3378
|
+
} else {
|
|
3379
|
+
await this.checkpointer.save(checkpointKey, checkpoint2);
|
|
3380
|
+
}
|
|
3332
3381
|
}
|
|
3333
3382
|
async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
|
|
3334
|
-
const
|
|
3335
|
-
return { events, checkpoint, stepCount };
|
|
3383
|
+
const checkpoint2 = await this.saveCheckpoint(checkpointKey, state);
|
|
3384
|
+
return { events, checkpoint: checkpoint2, stepCount };
|
|
3336
3385
|
}
|
|
3337
3386
|
async runUntilYieldInternal(checkpointKey, initialState, reportStepsUsed, maxSteps) {
|
|
3338
3387
|
let state = initialState;
|
|
@@ -3342,6 +3391,15 @@ var GraphExecutor = class {
|
|
|
3342
3391
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
3343
3392
|
local: { ...state.local || {}, ...ephemeral }
|
|
3344
3393
|
};
|
|
3394
|
+
if (this.executionCheckpointPort) {
|
|
3395
|
+
state.local = {
|
|
3396
|
+
...state.local,
|
|
3397
|
+
commitExecutionBoundary: async (boundary) => {
|
|
3398
|
+
const saved = await this.saveCheckpoint(checkpointKey, boundary);
|
|
3399
|
+
boundary.revision = saved.revision;
|
|
3400
|
+
}
|
|
3401
|
+
};
|
|
3402
|
+
}
|
|
3345
3403
|
const isAbortSignal2 = (v) => {
|
|
3346
3404
|
return v !== null && typeof v === "object" && "aborted" in v;
|
|
3347
3405
|
};
|
|
@@ -3351,11 +3409,12 @@ var GraphExecutor = class {
|
|
|
3351
3409
|
throw err;
|
|
3352
3410
|
};
|
|
3353
3411
|
let stepCount = 0;
|
|
3412
|
+
const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
|
|
3354
3413
|
let allEvents = [];
|
|
3355
3414
|
logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
|
|
3356
3415
|
maxSteps
|
|
3357
3416
|
});
|
|
3358
|
-
while (stepCount < maxSteps) {
|
|
3417
|
+
while (previousSteps + stepCount < maxSteps) {
|
|
3359
3418
|
stepCount += 1;
|
|
3360
3419
|
reportStepsUsed(stepCount);
|
|
3361
3420
|
const signalRaw = state.local?.signal;
|
|
@@ -3367,7 +3426,7 @@ var GraphExecutor = class {
|
|
|
3367
3426
|
const stepPreparation = prepareGraphStep({
|
|
3368
3427
|
state,
|
|
3369
3428
|
maxSteps,
|
|
3370
|
-
stepCount
|
|
3429
|
+
stepCount: previousSteps + stepCount
|
|
3371
3430
|
});
|
|
3372
3431
|
state = stepPreparation.state;
|
|
3373
3432
|
const node = this.nodes.get(state.nodeId);
|
|
@@ -3376,6 +3435,7 @@ var GraphExecutor = class {
|
|
|
3376
3435
|
maxSteps,
|
|
3377
3436
|
stepCount
|
|
3378
3437
|
});
|
|
3438
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
3379
3439
|
const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
3380
3440
|
this.ephemeralLocals.delete(checkpointKey);
|
|
3381
3441
|
return result3;
|
|
@@ -3385,6 +3445,11 @@ var GraphExecutor = class {
|
|
|
3385
3445
|
stepCount,
|
|
3386
3446
|
nodeId: state.nodeId
|
|
3387
3447
|
});
|
|
3448
|
+
if (this.executionCheckpointPort) {
|
|
3449
|
+
state.executionStatus = "executing";
|
|
3450
|
+
const saved = await this.saveCheckpoint(checkpointKey, state);
|
|
3451
|
+
state.revision = saved.revision;
|
|
3452
|
+
}
|
|
3388
3453
|
const result2 = await runGraphNodeWithTelemetry({
|
|
3389
3454
|
node,
|
|
3390
3455
|
state,
|
|
@@ -3409,10 +3474,13 @@ var GraphExecutor = class {
|
|
|
3409
3474
|
fromNodeId: stepResolution.action.fromNodeId,
|
|
3410
3475
|
nextNodeId: stepResolution.action.nextNodeId
|
|
3411
3476
|
});
|
|
3412
|
-
|
|
3477
|
+
if (this.executionCheckpointPort) state.executionStatus = "ready";
|
|
3478
|
+
const saved = await this.saveCheckpoint(checkpointKey, state);
|
|
3479
|
+
state.revision = saved.revision;
|
|
3413
3480
|
continue;
|
|
3414
3481
|
}
|
|
3415
3482
|
if (stepResolution.action.kind === "yield") {
|
|
3483
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
3416
3484
|
logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
|
|
3417
3485
|
maxSteps,
|
|
3418
3486
|
stepCount
|
|
@@ -3423,6 +3491,7 @@ var GraphExecutor = class {
|
|
|
3423
3491
|
maxSteps,
|
|
3424
3492
|
stepCount
|
|
3425
3493
|
});
|
|
3494
|
+
if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
|
|
3426
3495
|
return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
3427
3496
|
}
|
|
3428
3497
|
logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
|
|
@@ -3443,6 +3512,7 @@ var GraphExecutor = class {
|
|
|
3443
3512
|
},
|
|
3444
3513
|
retryable: false
|
|
3445
3514
|
}), "GraphExecutor.engine_budget_exhausted"));
|
|
3515
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
3446
3516
|
const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
3447
3517
|
this.ephemeralLocals.delete(checkpointKey);
|
|
3448
3518
|
return result;
|
|
@@ -7118,10 +7188,11 @@ var LlmNode = class {
|
|
|
7118
7188
|
bridge.handle
|
|
7119
7189
|
);
|
|
7120
7190
|
} catch (error) {
|
|
7121
|
-
bridge.finalizePartialAnswer();
|
|
7191
|
+
if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
|
|
7122
7192
|
throw error;
|
|
7123
7193
|
}
|
|
7124
7194
|
const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
|
|
7195
|
+
if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
|
|
7125
7196
|
switch (decision.kind) {
|
|
7126
7197
|
case "tool_calls": {
|
|
7127
7198
|
if (forceFinalAnswer) {
|
|
@@ -8328,6 +8399,58 @@ function buildCancelledToolBatchLocalState(local, runtimeEvents) {
|
|
|
8328
8399
|
function recordToolProtocolError(params) {
|
|
8329
8400
|
}
|
|
8330
8401
|
|
|
8402
|
+
// src/runtime-kernel/graph-engine/definitions/runContinuation.ts
|
|
8403
|
+
var RunRecoveryBlockedError = class extends Error {
|
|
8404
|
+
code = "RUN_RECOVERY_BLOCKED";
|
|
8405
|
+
constructor(message) {
|
|
8406
|
+
super(message);
|
|
8407
|
+
this.name = "RunRecoveryBlockedError";
|
|
8408
|
+
}
|
|
8409
|
+
};
|
|
8410
|
+
var RunPauseRequested = class extends Error {
|
|
8411
|
+
code = "RUN_PAUSE_REQUESTED";
|
|
8412
|
+
constructor(message = "Run paused by user") {
|
|
8413
|
+
super(message);
|
|
8414
|
+
this.name = "RunPauseRequested";
|
|
8415
|
+
}
|
|
8416
|
+
};
|
|
8417
|
+
function isRunPauseSignal(signal) {
|
|
8418
|
+
const reason = signal?.reason;
|
|
8419
|
+
return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
|
|
8420
|
+
}
|
|
8421
|
+
|
|
8422
|
+
// src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
|
|
8423
|
+
async function executeRecoverableTool(input) {
|
|
8424
|
+
const local = input.state.local;
|
|
8425
|
+
if (!local?.commitExecutionBoundary) return input.execute();
|
|
8426
|
+
if (local.executingToolCallId) {
|
|
8427
|
+
if (local.executingToolCallId !== input.call.id) {
|
|
8428
|
+
throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
|
|
8429
|
+
}
|
|
8430
|
+
const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
|
|
8431
|
+
if (!decision || decision.kind === "blocked") {
|
|
8432
|
+
throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
|
|
8433
|
+
}
|
|
8434
|
+
if (decision.kind === "settled") return decision.result;
|
|
8435
|
+
}
|
|
8436
|
+
local.executingToolCallId = input.call.id;
|
|
8437
|
+
await local.commitExecutionBoundary(input.state);
|
|
8438
|
+
const result = await input.execute();
|
|
8439
|
+
if (!result.success && isRunPauseSignal(local.signal)) {
|
|
8440
|
+
const error = new Error("Tool execution paused before its outcome was confirmed");
|
|
8441
|
+
error.name = "AbortError";
|
|
8442
|
+
throw error;
|
|
8443
|
+
}
|
|
8444
|
+
return result;
|
|
8445
|
+
}
|
|
8446
|
+
async function commitToolBoundary(state, result) {
|
|
8447
|
+
if (!state.local?.commitExecutionBoundary) return;
|
|
8448
|
+
delete state.local.executingToolCallId;
|
|
8449
|
+
state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
|
|
8450
|
+
state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
|
|
8451
|
+
await state.local.commitExecutionBoundary(state);
|
|
8452
|
+
}
|
|
8453
|
+
|
|
8331
8454
|
// src/runtime-kernel/graph-engine/nodes/toolNode.ts
|
|
8332
8455
|
var logger11 = new Logger("ToolNode");
|
|
8333
8456
|
function isAbortSignal(value) {
|
|
@@ -8498,6 +8621,7 @@ var ToolNode = class {
|
|
|
8498
8621
|
const events = [];
|
|
8499
8622
|
while (true) {
|
|
8500
8623
|
const result = await this.runNextPendingToolCall(state);
|
|
8624
|
+
await commitToolBoundary(state, result);
|
|
8501
8625
|
if (Array.isArray(result.events) && result.events.length > 0) {
|
|
8502
8626
|
events.push(...result.events);
|
|
8503
8627
|
}
|
|
@@ -8514,11 +8638,9 @@ var ToolNode = class {
|
|
|
8514
8638
|
const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
|
|
8515
8639
|
const signalRaw = state.local?.signal;
|
|
8516
8640
|
if (isAbortSignal(signalRaw) && signalRaw.aborted) {
|
|
8517
|
-
|
|
8518
|
-
state,
|
|
8519
|
-
|
|
8520
|
-
toolCatalog: this.toolRuntime
|
|
8521
|
-
});
|
|
8641
|
+
if (!isRunPauseSignal(signalRaw)) {
|
|
8642
|
+
settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
|
|
8643
|
+
}
|
|
8522
8644
|
const abortError = new Error("The user aborted a request.");
|
|
8523
8645
|
abortError.name = "AbortError";
|
|
8524
8646
|
throw abortError;
|
|
@@ -8657,16 +8779,21 @@ var ToolNode = class {
|
|
|
8657
8779
|
tool_calls: [call]
|
|
8658
8780
|
});
|
|
8659
8781
|
try {
|
|
8660
|
-
const exec = await
|
|
8661
|
-
|
|
8662
|
-
|
|
8663
|
-
|
|
8664
|
-
|
|
8665
|
-
|
|
8666
|
-
|
|
8667
|
-
|
|
8668
|
-
|
|
8669
|
-
|
|
8782
|
+
const exec = await executeRecoverableTool({
|
|
8783
|
+
state,
|
|
8784
|
+
call,
|
|
8785
|
+
context: prepared.toolContext,
|
|
8786
|
+
execute: () => executeToolWithIdempotency({
|
|
8787
|
+
idempotencyKey: execution.idempotencyKey,
|
|
8788
|
+
inFlight: this.idempotencyInFlight,
|
|
8789
|
+
history: readHistoryEvents(prepared.local),
|
|
8790
|
+
toolName: execution.toolName,
|
|
8791
|
+
execute: () => this.toolRuntime.executeTool(
|
|
8792
|
+
execution.toolName,
|
|
8793
|
+
execution.toolArgs,
|
|
8794
|
+
prepared.toolContext
|
|
8795
|
+
)
|
|
8796
|
+
})
|
|
8670
8797
|
});
|
|
8671
8798
|
if (exec.success) {
|
|
8672
8799
|
const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
|
|
@@ -8746,7 +8873,7 @@ var ToolNode = class {
|
|
|
8746
8873
|
bridge: execution.bridge
|
|
8747
8874
|
});
|
|
8748
8875
|
} catch (error) {
|
|
8749
|
-
if (isToolExecutionAbort(error)) {
|
|
8876
|
+
if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
|
|
8750
8877
|
settleToolCallsAfterExecutionAbort({
|
|
8751
8878
|
state,
|
|
8752
8879
|
remainingCalls: calls.slice(1),
|
|
@@ -8806,7 +8933,7 @@ var ToolNode = class {
|
|
|
8806
8933
|
{
|
|
8807
8934
|
attachments: context.attachments,
|
|
8808
8935
|
metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
|
|
8809
|
-
|
|
8936
|
+
// 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
|
|
8810
8937
|
durationMs: context.exec.durationMs
|
|
8811
8938
|
}
|
|
8812
8939
|
);
|
|
@@ -8863,6 +8990,9 @@ var ToolNode = class {
|
|
|
8863
8990
|
return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
|
|
8864
8991
|
}
|
|
8865
8992
|
async handleError(context) {
|
|
8993
|
+
if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
|
|
8994
|
+
throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
|
|
8995
|
+
}
|
|
8866
8996
|
if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
|
|
8867
8997
|
await this.emitToolDecisionAudit({
|
|
8868
8998
|
action: "tool.deny",
|
|
@@ -9099,16 +9229,16 @@ function requireEventStoreId(eventStoreId) {
|
|
|
9099
9229
|
}
|
|
9100
9230
|
function createMonotonicEventStoreIdFactory(nowProvider = () => Date.now()) {
|
|
9101
9231
|
let lastTimestamp = 0;
|
|
9102
|
-
let
|
|
9232
|
+
let counter2 = 0;
|
|
9103
9233
|
return () => {
|
|
9104
9234
|
const timestamp = Math.max(nowProvider(), lastTimestamp);
|
|
9105
9235
|
if (timestamp === lastTimestamp) {
|
|
9106
|
-
|
|
9236
|
+
counter2 += 1;
|
|
9107
9237
|
} else {
|
|
9108
9238
|
lastTimestamp = timestamp;
|
|
9109
|
-
|
|
9239
|
+
counter2 = 0;
|
|
9110
9240
|
}
|
|
9111
|
-
return `${String(timestamp).padStart(13, "0")}-${String(
|
|
9241
|
+
return `${String(timestamp).padStart(13, "0")}-${String(counter2).padStart(4, "0")}`;
|
|
9112
9242
|
};
|
|
9113
9243
|
}
|
|
9114
9244
|
|
|
@@ -9520,6 +9650,76 @@ function assertNonNegativeSafeInteger(value, field) {
|
|
|
9520
9650
|
throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
|
|
9521
9651
|
}
|
|
9522
9652
|
}
|
|
9653
|
+
var counter = z.number().int().nonnegative();
|
|
9654
|
+
var executor = z.object({
|
|
9655
|
+
stepCount: counter,
|
|
9656
|
+
phase: z.string().optional(),
|
|
9657
|
+
maxSteps: counter.optional(),
|
|
9658
|
+
remainingSteps: z.number().int().optional(),
|
|
9659
|
+
finalStepPolicy: z.enum(["final_answer", "force_tools"]).optional(),
|
|
9660
|
+
finalStepForcedTools: z.array(z.string()).optional(),
|
|
9661
|
+
lastStepsHintThreshold: counter.optional(),
|
|
9662
|
+
systemReminderPolicy: AgentSpecSystemReminderPolicy.optional(),
|
|
9663
|
+
toolObservationPolicy: AgentSpecToolObservationGovernancePolicy.optional(),
|
|
9664
|
+
runLockedModelId: z.string().optional(),
|
|
9665
|
+
lastSuccessfulLlmModelId: z.string().optional(),
|
|
9666
|
+
llmInvocationKind: z.enum(["user_initiated", "continuation"]).optional(),
|
|
9667
|
+
llmInvocationCount: counter.optional(),
|
|
9668
|
+
lockRequestedModelId: z.boolean().optional(),
|
|
9669
|
+
contextCompaction: z.object({
|
|
9670
|
+
attemptCount: counter,
|
|
9671
|
+
committedCount: counter,
|
|
9672
|
+
lastCommittedFingerprint: z.string().optional()
|
|
9673
|
+
}).strict().optional()
|
|
9674
|
+
}).strict();
|
|
9675
|
+
var checkpoint = z.object({
|
|
9676
|
+
nodeId: z.string().min(1),
|
|
9677
|
+
schemaVersion: z.literal(ENGINE_STATE_SCHEMA_VERSION).optional(),
|
|
9678
|
+
revision: counter.optional(),
|
|
9679
|
+
executionStatus: z.enum(["ready", "executing", "yielded", "awaiting_user"]).optional(),
|
|
9680
|
+
local: z.object({
|
|
9681
|
+
runId: RunIdSchema.optional(),
|
|
9682
|
+
parentRunId: RunIdSchema.optional(),
|
|
9683
|
+
conversationId: z.string().optional(),
|
|
9684
|
+
turnId: z.string().optional(),
|
|
9685
|
+
request: SerializableJsonRecord.optional(),
|
|
9686
|
+
history: z.array(RuntimeEvent).optional(),
|
|
9687
|
+
newEvents: z.array(RuntimeEvent).optional(),
|
|
9688
|
+
executorLocal: executor.optional(),
|
|
9689
|
+
pendingToolCalls: z.array(z.object({
|
|
9690
|
+
id: ToolCallIdSchema,
|
|
9691
|
+
type: z.literal("function"),
|
|
9692
|
+
function: z.object({ name: z.string().min(1), arguments: z.string() }).strict()
|
|
9693
|
+
}).strict()).optional(),
|
|
9694
|
+
executingToolCallId: ToolCallIdSchema.optional(),
|
|
9695
|
+
toolBatchCompletionMode: z.enum(["continue_to_llm", "yield_after_batch"]).optional(),
|
|
9696
|
+
pendingInteractionSpec: SerializableJsonRecord.optional(),
|
|
9697
|
+
lastToolResult: SerializableJsonRecord.optional(),
|
|
9698
|
+
finalAnswer: z.string().optional(),
|
|
9699
|
+
answerId: z.string().optional(),
|
|
9700
|
+
chunkSeq: counter.optional(),
|
|
9701
|
+
contextUsage: ContextUsageSnapshot.optional()
|
|
9702
|
+
}).passthrough().optional()
|
|
9703
|
+
}).strict();
|
|
9704
|
+
function parseEngineCheckpoint(value) {
|
|
9705
|
+
const result = checkpoint.parse(SerializableJsonRecord.parse(value));
|
|
9706
|
+
for (const key of [
|
|
9707
|
+
"memory",
|
|
9708
|
+
"signal",
|
|
9709
|
+
"toolContext",
|
|
9710
|
+
"runtimeEventSink",
|
|
9711
|
+
"runtimeEventCommitPort",
|
|
9712
|
+
"runtimeFailureFactSink",
|
|
9713
|
+
"summarizationCallbacks",
|
|
9714
|
+
"commitExecutionBoundary",
|
|
9715
|
+
"toolRecoveryPort"
|
|
9716
|
+
]) {
|
|
9717
|
+
if (result.local && Object.hasOwn(result.local, key)) {
|
|
9718
|
+
throw new Error(`Checkpoint must not contain execution capability: ${key}`);
|
|
9719
|
+
}
|
|
9720
|
+
}
|
|
9721
|
+
return result;
|
|
9722
|
+
}
|
|
9523
9723
|
|
|
9524
9724
|
// src/runtime-kernel/execution/index.ts
|
|
9525
9725
|
var execution_exports = {};
|
|
@@ -9760,12 +9960,33 @@ var RuntimeEventPublisher = class {
|
|
|
9760
9960
|
var EventBusEventPersistence = class {
|
|
9761
9961
|
constructor(options) {
|
|
9762
9962
|
this.options = options;
|
|
9963
|
+
this.checkpointWritesActive = options.checkpointWriter !== void 0;
|
|
9763
9964
|
}
|
|
9764
9965
|
options;
|
|
9765
9966
|
scheduledEventIds = /* @__PURE__ */ new Set();
|
|
9766
9967
|
writeTail = Promise.resolve();
|
|
9767
9968
|
firstWriteError;
|
|
9768
9969
|
connected = false;
|
|
9970
|
+
checkpointWritesActive;
|
|
9971
|
+
checkpointEvents = [];
|
|
9972
|
+
/** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
|
|
9973
|
+
async commitCheckpoint(checkpointKey, checkpoint2) {
|
|
9974
|
+
const writer = this.options.checkpointWriter;
|
|
9975
|
+
if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
|
|
9976
|
+
const events = this.checkpointEvents;
|
|
9977
|
+
this.checkpointEvents = [];
|
|
9978
|
+
await this.enqueueWrite(() => writer({
|
|
9979
|
+
checkpointKey,
|
|
9980
|
+
checkpoint: checkpoint2,
|
|
9981
|
+
events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
|
|
9982
|
+
}));
|
|
9983
|
+
}
|
|
9984
|
+
/** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
|
|
9985
|
+
finishCheckpointWrites() {
|
|
9986
|
+
for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
|
|
9987
|
+
this.checkpointEvents = [];
|
|
9988
|
+
this.checkpointWritesActive = false;
|
|
9989
|
+
}
|
|
9769
9990
|
connect() {
|
|
9770
9991
|
if (this.connected) {
|
|
9771
9992
|
throw new Error("[EventBusEventPersistence] consumer is already connected");
|
|
@@ -9812,14 +10033,22 @@ var EventBusEventPersistence = class {
|
|
|
9812
10033
|
if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
|
|
9813
10034
|
return;
|
|
9814
10035
|
}
|
|
10036
|
+
if (this.checkpointWritesActive) {
|
|
10037
|
+
this.scheduledEventIds.add(event.id);
|
|
10038
|
+
this.checkpointEvents.push(event);
|
|
10039
|
+
return;
|
|
10040
|
+
}
|
|
9815
10041
|
void this.scheduleWrite(event).catch(() => void 0);
|
|
9816
10042
|
};
|
|
9817
10043
|
scheduleWrite(event) {
|
|
9818
10044
|
this.scheduledEventIds.add(event.id);
|
|
9819
|
-
|
|
9820
|
-
|
|
9821
|
-
|
|
9822
|
-
});
|
|
10045
|
+
return this.enqueueWrite(() => this.options.eventStore.append({
|
|
10046
|
+
eventStoreId: this.options.nextEventStoreId(),
|
|
10047
|
+
event
|
|
10048
|
+
}));
|
|
10049
|
+
}
|
|
10050
|
+
enqueueWrite(operation) {
|
|
10051
|
+
const write = this.writeTail.then(operation);
|
|
9823
10052
|
this.writeTail = write;
|
|
9824
10053
|
void write.catch((error) => {
|
|
9825
10054
|
this.firstWriteError ??= error;
|
|
@@ -11226,8 +11455,6 @@ __export(run_supervisor_exports, {
|
|
|
11226
11455
|
RunNotFoundError: () => RunNotFoundError,
|
|
11227
11456
|
runMetaFromRecord: () => runMetaFromRecord
|
|
11228
11457
|
});
|
|
11229
|
-
|
|
11230
|
-
// src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
|
|
11231
11458
|
function cloneRunRecord(record) {
|
|
11232
11459
|
return {
|
|
11233
11460
|
...record,
|
|
@@ -11247,6 +11474,11 @@ function matchesStatus(candidate, filter) {
|
|
|
11247
11474
|
}
|
|
11248
11475
|
var MemoryRunRegistryStore = class {
|
|
11249
11476
|
store = /* @__PURE__ */ new Map();
|
|
11477
|
+
async compareAndSwap(previous, next) {
|
|
11478
|
+
if (previous.runId !== next.runId || !isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
|
|
11479
|
+
this.store.set(next.runId, cloneRunRecord(next));
|
|
11480
|
+
return true;
|
|
11481
|
+
}
|
|
11250
11482
|
async save(record) {
|
|
11251
11483
|
this.store.set(record.runId, cloneRunRecord(record));
|
|
11252
11484
|
}
|
|
@@ -11394,6 +11626,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
|
|
|
11394
11626
|
}
|
|
11395
11627
|
};
|
|
11396
11628
|
|
|
11629
|
+
// src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
|
|
11630
|
+
async function persistRunTransition(store, previous, next) {
|
|
11631
|
+
if (store.compareAndSwap) {
|
|
11632
|
+
if (!await store.compareAndSwap(previous, next)) {
|
|
11633
|
+
throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
|
|
11634
|
+
}
|
|
11635
|
+
} else {
|
|
11636
|
+
await store.save(next);
|
|
11637
|
+
}
|
|
11638
|
+
}
|
|
11639
|
+
|
|
11397
11640
|
// src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
|
|
11398
11641
|
function isRunTerminalStatus(status) {
|
|
11399
11642
|
return status === "completed" || status === "failed" || status === "cancelled";
|
|
@@ -11449,6 +11692,7 @@ var DefaultRunHandle = class {
|
|
|
11449
11692
|
parentRunId;
|
|
11450
11693
|
runRecord;
|
|
11451
11694
|
abortController;
|
|
11695
|
+
executionId;
|
|
11452
11696
|
agentSpecSnapshot;
|
|
11453
11697
|
requestSnapshot;
|
|
11454
11698
|
transportEventBus;
|
|
@@ -11464,6 +11708,9 @@ var DefaultRunHandle = class {
|
|
|
11464
11708
|
this.runId = options.runRecord.runId;
|
|
11465
11709
|
this.parentRunId = options.runRecord.parentRunId;
|
|
11466
11710
|
this.abortController = options.abortController;
|
|
11711
|
+
const executionId = options.runRecord.metadata?.executionId;
|
|
11712
|
+
if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
|
|
11713
|
+
this.executionId = executionId;
|
|
11467
11714
|
this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
|
|
11468
11715
|
this.requestSnapshot = cloneRequest(options.request);
|
|
11469
11716
|
this.transportEventBus = options.eventBus;
|
|
@@ -11483,8 +11730,9 @@ var DefaultRunHandle = class {
|
|
|
11483
11730
|
* awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
|
|
11484
11731
|
* 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
|
|
11485
11732
|
*/
|
|
11486
|
-
replaceExecutionAbortController(controller) {
|
|
11733
|
+
replaceExecutionAbortController(controller, executionId) {
|
|
11487
11734
|
this.abortController = controller;
|
|
11735
|
+
this.executionId = executionId;
|
|
11488
11736
|
}
|
|
11489
11737
|
async spec() {
|
|
11490
11738
|
return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
|
|
@@ -11504,6 +11752,7 @@ var DefaultRunHandle = class {
|
|
|
11504
11752
|
this.abortController.abort(opts.reason);
|
|
11505
11753
|
const latestRecord = await this.registryStore.load(this.runId);
|
|
11506
11754
|
const baseRecord = latestRecord ?? this.runRecord;
|
|
11755
|
+
this.assertExecutionOwner(baseRecord);
|
|
11507
11756
|
const transition = decideRunLifecycleTransition(baseRecord.status);
|
|
11508
11757
|
if (transition.kind === "skip_terminal") {
|
|
11509
11758
|
if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
|
|
@@ -11513,7 +11762,7 @@ var DefaultRunHandle = class {
|
|
|
11513
11762
|
currentNode: patch.currentNode ?? baseRecord.currentNode,
|
|
11514
11763
|
iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
|
|
11515
11764
|
};
|
|
11516
|
-
await this.registryStore
|
|
11765
|
+
await persistRunTransition(this.registryStore, baseRecord, settledRecord);
|
|
11517
11766
|
this.runRecord = { ...settledRecord };
|
|
11518
11767
|
return;
|
|
11519
11768
|
}
|
|
@@ -11540,7 +11789,7 @@ var DefaultRunHandle = class {
|
|
|
11540
11789
|
}
|
|
11541
11790
|
}
|
|
11542
11791
|
};
|
|
11543
|
-
await this.registryStore
|
|
11792
|
+
await persistRunTransition(this.registryStore, baseRecord, nextRecord);
|
|
11544
11793
|
this.runRecord = { ...nextRecord };
|
|
11545
11794
|
await this.auditPort.emit({
|
|
11546
11795
|
envelopeId: generateAuditEnvelopeId(),
|
|
@@ -11648,21 +11897,35 @@ var DefaultRunHandle = class {
|
|
|
11648
11897
|
async markFailed(error, patch = {}) {
|
|
11649
11898
|
await this.saveLifecycleStatus("failed", patch, error);
|
|
11650
11899
|
}
|
|
11651
|
-
async pause(
|
|
11652
|
-
|
|
11900
|
+
async pause(reason = "Run paused by user") {
|
|
11901
|
+
const latest = await this.registryStore.load(this.runId);
|
|
11902
|
+
if (latest) this.assertExecutionOwner(latest);
|
|
11903
|
+
if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
|
|
11904
|
+
const next = {
|
|
11905
|
+
...latest,
|
|
11906
|
+
status: "paused",
|
|
11907
|
+
updatedAt: Date.now(),
|
|
11908
|
+
pauseReason: reason,
|
|
11909
|
+
pausedAt: void 0
|
|
11910
|
+
};
|
|
11911
|
+
await persistRunTransition(this.registryStore, latest, next);
|
|
11912
|
+
this.runRecord = next;
|
|
11913
|
+
this.abortController.abort(new RunPauseRequested(reason));
|
|
11653
11914
|
}
|
|
11654
|
-
async
|
|
11655
|
-
|
|
11915
|
+
async markPaused(patch = {}) {
|
|
11916
|
+
await this.saveLifecycleStatus("paused", patch);
|
|
11656
11917
|
}
|
|
11657
11918
|
async saveLifecycleStatus(status, patch, errorIfAny) {
|
|
11658
11919
|
const latestRecord = await this.registryStore.load(this.runId);
|
|
11659
11920
|
const baseRecord = latestRecord ?? this.runRecord;
|
|
11660
11921
|
const transition = decideRunLifecycleTransition(baseRecord.status);
|
|
11922
|
+
this.assertExecutionOwner(baseRecord);
|
|
11923
|
+
if (status === "running" && baseRecord.status === "paused") return;
|
|
11661
11924
|
if (transition.kind === "skip_terminal") {
|
|
11662
11925
|
this.runRecord = { ...baseRecord };
|
|
11663
11926
|
return;
|
|
11664
11927
|
}
|
|
11665
|
-
const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
|
|
11928
|
+
const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
|
|
11666
11929
|
const updatedAt = Date.now();
|
|
11667
11930
|
const nextRecord = {
|
|
11668
11931
|
...baseRecord,
|
|
@@ -11670,8 +11933,8 @@ var DefaultRunHandle = class {
|
|
|
11670
11933
|
updatedAt,
|
|
11671
11934
|
currentNode: patch.currentNode ?? baseRecord.currentNode,
|
|
11672
11935
|
iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
|
|
11673
|
-
pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
|
|
11674
|
-
pausedAt: status === "awaiting_user" ? updatedAt : void 0,
|
|
11936
|
+
pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
|
|
11937
|
+
pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
|
|
11675
11938
|
errorIfAny,
|
|
11676
11939
|
metadata: awaitingUserPatch?.eventId ? {
|
|
11677
11940
|
...baseRecord.metadata ?? {},
|
|
@@ -11682,7 +11945,7 @@ var DefaultRunHandle = class {
|
|
|
11682
11945
|
}
|
|
11683
11946
|
} : baseRecord.metadata
|
|
11684
11947
|
};
|
|
11685
|
-
await this.registryStore
|
|
11948
|
+
await persistRunTransition(this.registryStore, baseRecord, nextRecord);
|
|
11686
11949
|
this.runRecord = { ...nextRecord };
|
|
11687
11950
|
if (status === "completed" || status === "failed") {
|
|
11688
11951
|
this.closeObservationChannel();
|
|
@@ -11692,6 +11955,11 @@ var DefaultRunHandle = class {
|
|
|
11692
11955
|
forwardTransportEvent = (envelope) => {
|
|
11693
11956
|
this.observationEventBus.emit("event", envelope);
|
|
11694
11957
|
};
|
|
11958
|
+
assertExecutionOwner(record) {
|
|
11959
|
+
if (record.metadata?.executionId !== this.executionId) {
|
|
11960
|
+
throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
|
|
11961
|
+
}
|
|
11962
|
+
}
|
|
11695
11963
|
forwardTransportError = (error) => {
|
|
11696
11964
|
this.observationEventBus.emit("error", error);
|
|
11697
11965
|
};
|
|
@@ -12022,7 +12290,15 @@ function createRunConcurrencyKeyRegistry() {
|
|
|
12022
12290
|
runIdByKey.delete(concurrencyKey);
|
|
12023
12291
|
}
|
|
12024
12292
|
}
|
|
12025
|
-
|
|
12293
|
+
function transfer(previous, next, concurrencyKey) {
|
|
12294
|
+
if (runIdByKey.get(concurrencyKey) !== previous || keyByRunId.has(next)) {
|
|
12295
|
+
throw new RunConcurrencyKeyOccupiedError(concurrencyKey, runIdByKey.get(concurrencyKey) ?? previous, next);
|
|
12296
|
+
}
|
|
12297
|
+
keyByRunId.delete(previous);
|
|
12298
|
+
keyByRunId.set(next, concurrencyKey);
|
|
12299
|
+
runIdByKey.set(concurrencyKey, next);
|
|
12300
|
+
}
|
|
12301
|
+
return { acquire, release, transfer };
|
|
12026
12302
|
}
|
|
12027
12303
|
|
|
12028
12304
|
// src/runtime-kernel/run-supervisor/functions/runRegistration.ts
|
|
@@ -12073,6 +12349,24 @@ async function recoverRunsOnBoot(options) {
|
|
|
12073
12349
|
const outcomes = [];
|
|
12074
12350
|
for (const record of activeRecords) {
|
|
12075
12351
|
const updatedAt = options.now();
|
|
12352
|
+
if (await options.canRestoreRun?.(record)) {
|
|
12353
|
+
const metadata = { ...record.metadata };
|
|
12354
|
+
const awaitingUser = metadata.awaitingUser;
|
|
12355
|
+
if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
|
|
12356
|
+
const restored = { ...awaitingUser };
|
|
12357
|
+
Reflect.deleteProperty(restored, "resumeClaim");
|
|
12358
|
+
metadata.awaitingUser = restored;
|
|
12359
|
+
}
|
|
12360
|
+
await persistRunTransition(options.registryStore, record, {
|
|
12361
|
+
...record,
|
|
12362
|
+
status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
|
|
12363
|
+
pausedAt: record.pausedAt ?? updatedAt,
|
|
12364
|
+
pauseReason: record.pauseReason ?? options.reason,
|
|
12365
|
+
updatedAt,
|
|
12366
|
+
metadata
|
|
12367
|
+
});
|
|
12368
|
+
continue;
|
|
12369
|
+
}
|
|
12076
12370
|
const nextRecord = {
|
|
12077
12371
|
...record,
|
|
12078
12372
|
status: "failed",
|
|
@@ -12090,7 +12384,7 @@ async function recoverRunsOnBoot(options) {
|
|
|
12090
12384
|
}
|
|
12091
12385
|
}
|
|
12092
12386
|
};
|
|
12093
|
-
await options.registryStore
|
|
12387
|
+
await persistRunTransition(options.registryStore, record, nextRecord);
|
|
12094
12388
|
const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
|
|
12095
12389
|
options.notifyTerminal(outcome);
|
|
12096
12390
|
outcomes.push(outcome);
|
|
@@ -12214,8 +12508,13 @@ var DefaultRunSupervisor = class {
|
|
|
12214
12508
|
inFlight = /* @__PURE__ */ new Map();
|
|
12215
12509
|
eventWatchDisposers = /* @__PURE__ */ new Map();
|
|
12216
12510
|
controlOperations = /* @__PURE__ */ new Map();
|
|
12511
|
+
canRestoreRun;
|
|
12217
12512
|
constructor(options) {
|
|
12513
|
+
if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
|
|
12514
|
+
throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
|
|
12515
|
+
}
|
|
12218
12516
|
this.registryStore = options.registryStore;
|
|
12517
|
+
this.canRestoreRun = options.canRestoreRun;
|
|
12219
12518
|
this.auditPort = options.auditPort;
|
|
12220
12519
|
this.executor = options.executor;
|
|
12221
12520
|
this.runIdFactory = options.runIdFactory ?? generateRunId;
|
|
@@ -12248,6 +12547,9 @@ var DefaultRunSupervisor = class {
|
|
|
12248
12547
|
});
|
|
12249
12548
|
}
|
|
12250
12549
|
async registerRun(spec) {
|
|
12550
|
+
if (spec.replacesPausedRun) {
|
|
12551
|
+
return this.withRunControlLock(spec.replacesPausedRun.runId, () => this.registerPausedReplacement(spec));
|
|
12552
|
+
}
|
|
12251
12553
|
const runId = spec.runId ?? this.runIdFactory();
|
|
12252
12554
|
if (this.handles.has(runId) || await this.registryStore.load(runId)) {
|
|
12253
12555
|
throw new RunAlreadyRegisteredError(runId);
|
|
@@ -12258,11 +12560,66 @@ var DefaultRunSupervisor = class {
|
|
|
12258
12560
|
forwardParentAbortSignal(controller, spec.parentSignal);
|
|
12259
12561
|
const record = createInitialRunRecord({ runId, spec, startedAt });
|
|
12260
12562
|
try {
|
|
12261
|
-
await
|
|
12563
|
+
if (spec.admissionCommit) await spec.admissionCommit(record);
|
|
12564
|
+
else await this.registryStore.save(record);
|
|
12262
12565
|
} catch (error) {
|
|
12263
12566
|
this.releaseRunAdmission(runId);
|
|
12264
12567
|
throw error;
|
|
12265
12568
|
}
|
|
12569
|
+
return this.attachRun(record, spec, controller);
|
|
12570
|
+
}
|
|
12571
|
+
async registerPausedReplacement(spec) {
|
|
12572
|
+
const target = spec.replacesPausedRun;
|
|
12573
|
+
if (!target || !spec.concurrencyKey || !spec.admissionCommit || !this.registryStore.compareAndSwap) {
|
|
12574
|
+
throw new Error("Paused replacement requires concurrency identity and atomic admissionCommit");
|
|
12575
|
+
}
|
|
12576
|
+
this.getHandle(target.runId);
|
|
12577
|
+
const previous = await this.registryStore.load(target.runId);
|
|
12578
|
+
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) {
|
|
12579
|
+
throw new RunInteractionConflictError(target.runId, "replacement does not match the settled pause");
|
|
12580
|
+
}
|
|
12581
|
+
const runId = spec.runId ?? this.runIdFactory();
|
|
12582
|
+
if (this.handles.has(runId) || await this.registryStore.load(runId)) throw new RunAlreadyRegisteredError(runId);
|
|
12583
|
+
this.runConcurrencyKeys.transfer(previous.runId, runId, spec.concurrencyKey);
|
|
12584
|
+
this.runSlotLimiter.release(previous.runId);
|
|
12585
|
+
this.runSlotLimiter.acquire(runId);
|
|
12586
|
+
const now = this.now();
|
|
12587
|
+
const record = createInitialRunRecord({ runId, spec, startedAt: now });
|
|
12588
|
+
const next = {
|
|
12589
|
+
...previous,
|
|
12590
|
+
status: "cancelled",
|
|
12591
|
+
updatedAt: now,
|
|
12592
|
+
errorIfAny: { errorCode: "RUN_REPLACED", message: "Replaced by a newly accepted request", recoverable: false }
|
|
12593
|
+
};
|
|
12594
|
+
try {
|
|
12595
|
+
await spec.admissionCommit(record, { previous, next });
|
|
12596
|
+
} catch (error) {
|
|
12597
|
+
this.runSlotLimiter.release(runId);
|
|
12598
|
+
this.runSlotLimiter.acquire(previous.runId);
|
|
12599
|
+
this.runConcurrencyKeys.transfer(runId, previous.runId, spec.concurrencyKey);
|
|
12600
|
+
throw error;
|
|
12601
|
+
}
|
|
12602
|
+
this.cleanupRunResources(previous.runId);
|
|
12603
|
+
this.notifyTerminalWaiters(previous.runId);
|
|
12604
|
+
const controller = new AbortController();
|
|
12605
|
+
forwardParentAbortSignal(controller, spec.parentSignal);
|
|
12606
|
+
return this.attachRun(record, spec, controller);
|
|
12607
|
+
}
|
|
12608
|
+
async restoreRun(spec) {
|
|
12609
|
+
if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
|
|
12610
|
+
return this.withRunControlLock(spec.runId, async () => {
|
|
12611
|
+
if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
|
|
12612
|
+
const record = await this.registryStore.load(spec.runId);
|
|
12613
|
+
if (!record) throw new RunNotFoundError(spec.runId);
|
|
12614
|
+
if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
|
|
12615
|
+
throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
|
|
12616
|
+
}
|
|
12617
|
+
this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
|
|
12618
|
+
return this.attachRun(record, spec, new AbortController());
|
|
12619
|
+
});
|
|
12620
|
+
}
|
|
12621
|
+
attachRun(record, spec, controller) {
|
|
12622
|
+
const runId = record.runId;
|
|
12266
12623
|
try {
|
|
12267
12624
|
const handle = new DefaultRunHandle({
|
|
12268
12625
|
runRecord: record,
|
|
@@ -12360,11 +12717,36 @@ var DefaultRunSupervisor = class {
|
|
|
12360
12717
|
registryStore: this.registryStore,
|
|
12361
12718
|
reason,
|
|
12362
12719
|
now: this.now,
|
|
12363
|
-
notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
|
|
12720
|
+
notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
|
|
12721
|
+
canRestoreRun: this.canRestoreRun
|
|
12364
12722
|
});
|
|
12365
12723
|
}
|
|
12366
|
-
async pause(
|
|
12367
|
-
|
|
12724
|
+
async pause(runId, reason) {
|
|
12725
|
+
await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
|
|
12726
|
+
}
|
|
12727
|
+
async resumePausedRun(input) {
|
|
12728
|
+
return this.withRunControlLock(input.runId, async () => {
|
|
12729
|
+
const handle = this.getHandle(input.runId);
|
|
12730
|
+
const record = await this.registryStore.load(input.runId);
|
|
12731
|
+
if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt || input.expectedExecutionId !== void 0 && record.metadata?.executionId !== input.expectedExecutionId) {
|
|
12732
|
+
throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
|
|
12733
|
+
}
|
|
12734
|
+
await persistRunTransition(this.registryStore, record, {
|
|
12735
|
+
...record,
|
|
12736
|
+
status: "running",
|
|
12737
|
+
updatedAt: this.now(),
|
|
12738
|
+
pausedAt: void 0,
|
|
12739
|
+
pauseReason: void 0,
|
|
12740
|
+
errorIfAny: void 0,
|
|
12741
|
+
metadata: { ...record.metadata, executionId: input.executionId }
|
|
12742
|
+
});
|
|
12743
|
+
const controller = new AbortController();
|
|
12744
|
+
handle.replaceExecutionAbortController(controller, input.executionId);
|
|
12745
|
+
handle.attachTransportEventBus(input.eventBus);
|
|
12746
|
+
this.controllers.set(input.runId, controller);
|
|
12747
|
+
this.attachAwaitingUserWatcher(input.runId, input.eventBus);
|
|
12748
|
+
return handle;
|
|
12749
|
+
});
|
|
12368
12750
|
}
|
|
12369
12751
|
async claimResume(runId, interaction, eventBus, parentSignal) {
|
|
12370
12752
|
return this.withRunControlLock(runId, async () => {
|
|
@@ -12399,7 +12781,7 @@ var DefaultRunSupervisor = class {
|
|
|
12399
12781
|
throw new RunNotFoundError(runId);
|
|
12400
12782
|
}
|
|
12401
12783
|
const claimId = generateRunResumeClaimId();
|
|
12402
|
-
await this.registryStore
|
|
12784
|
+
await persistRunTransition(this.registryStore, record, {
|
|
12403
12785
|
...record,
|
|
12404
12786
|
updatedAt: this.now(),
|
|
12405
12787
|
metadata: {
|
|
@@ -12487,7 +12869,7 @@ var DefaultRunSupervisor = class {
|
|
|
12487
12869
|
}
|
|
12488
12870
|
const awaitingUserWithoutClaim = { ...awaitingUser };
|
|
12489
12871
|
Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
|
|
12490
|
-
|
|
12872
|
+
const nextRecord = {
|
|
12491
12873
|
...record,
|
|
12492
12874
|
status: "running",
|
|
12493
12875
|
updatedAt: this.now(),
|
|
@@ -12497,6 +12879,10 @@ var DefaultRunSupervisor = class {
|
|
|
12497
12879
|
metadata: {
|
|
12498
12880
|
...record.metadata ?? {},
|
|
12499
12881
|
...execution ? { executionId: execution.executionId } : {},
|
|
12882
|
+
...execution?.inputEventIds ? { resumeInputs: {
|
|
12883
|
+
eventIds: [...execution.inputEventIds],
|
|
12884
|
+
checkpointRevision: pendingInteraction.checkpointRevision
|
|
12885
|
+
} } : {},
|
|
12500
12886
|
awaitingUser: {
|
|
12501
12887
|
...awaitingUserWithoutClaim,
|
|
12502
12888
|
interaction: {
|
|
@@ -12505,10 +12891,12 @@ var DefaultRunSupervisor = class {
|
|
|
12505
12891
|
}
|
|
12506
12892
|
}
|
|
12507
12893
|
}
|
|
12508
|
-
}
|
|
12894
|
+
};
|
|
12895
|
+
if (execution?.admissionCommit) await execution.admissionCommit(record, nextRecord);
|
|
12896
|
+
else await persistRunTransition(this.registryStore, record, nextRecord);
|
|
12509
12897
|
const executionController = new AbortController();
|
|
12510
12898
|
forwardParentAbortSignal(executionController, parentSignal);
|
|
12511
|
-
handle.replaceExecutionAbortController(executionController);
|
|
12899
|
+
handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
|
|
12512
12900
|
this.controllers.set(runId, executionController);
|
|
12513
12901
|
return handle;
|
|
12514
12902
|
});
|
|
@@ -12526,7 +12914,7 @@ var DefaultRunSupervisor = class {
|
|
|
12526
12914
|
}
|
|
12527
12915
|
const awaitingUserWithoutClaim = { ...awaitingUser };
|
|
12528
12916
|
Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
|
|
12529
|
-
await this.registryStore
|
|
12917
|
+
await persistRunTransition(this.registryStore, record, {
|
|
12530
12918
|
...record,
|
|
12531
12919
|
updatedAt: this.now(),
|
|
12532
12920
|
metadata: {
|
|
@@ -12576,13 +12964,13 @@ createConsoleAudit();
|
|
|
12576
12964
|
|
|
12577
12965
|
// src/runtime-kernel/testkit/defaultGraphExecutor.ts
|
|
12578
12966
|
function createDefaultGraphExecutor(options) {
|
|
12579
|
-
const
|
|
12967
|
+
const executor2 = new GraphExecutor(
|
|
12580
12968
|
options.checkpointer ?? new MemoryCheckpointer(),
|
|
12581
12969
|
{ maxSteps: options.maxSteps ?? 8 }
|
|
12582
12970
|
);
|
|
12583
|
-
|
|
12584
|
-
|
|
12585
|
-
|
|
12971
|
+
executor2.registerNode(new UserNode());
|
|
12972
|
+
executor2.registerNode(options.llmNode);
|
|
12973
|
+
executor2.registerNode(new ToolNode({
|
|
12586
12974
|
toolRuntime: options.toolRuntime,
|
|
12587
12975
|
observationPreview: options.observationPreview,
|
|
12588
12976
|
auditPort: options.auditPort,
|
|
@@ -12590,8 +12978,8 @@ function createDefaultGraphExecutor(options) {
|
|
|
12590
12978
|
modelInputCapabilityValidator: options.modelInputCapabilityValidator,
|
|
12591
12979
|
modelInputResolver: options.modelInputResolver
|
|
12592
12980
|
}));
|
|
12593
|
-
|
|
12594
|
-
return
|
|
12981
|
+
executor2.registerNode(new WaitUserNode({ auditPort: options.auditPort }));
|
|
12982
|
+
return executor2;
|
|
12595
12983
|
}
|
|
12596
12984
|
|
|
12597
12985
|
// src/quickstart/functions/contextTrace.ts
|
|
@@ -12870,7 +13258,7 @@ async function runAgent(agent, options) {
|
|
|
12870
13258
|
contextBuilder: new QuickstartContextBuilder(agent),
|
|
12871
13259
|
telemetryPort
|
|
12872
13260
|
});
|
|
12873
|
-
const
|
|
13261
|
+
const executor2 = createDefaultGraphExecutor({
|
|
12874
13262
|
llmNode: new LlmNode({ reasoner }),
|
|
12875
13263
|
toolRuntime,
|
|
12876
13264
|
observationPreview: createNoopObservationPreview(),
|
|
@@ -12906,7 +13294,7 @@ async function runAgent(agent, options) {
|
|
|
12906
13294
|
};
|
|
12907
13295
|
await handle.markRunning({ currentNode: "user" });
|
|
12908
13296
|
try {
|
|
12909
|
-
await
|
|
13297
|
+
await executor2.prime(checkpointKey, {
|
|
12910
13298
|
conversationId,
|
|
12911
13299
|
turnId,
|
|
12912
13300
|
request: {
|
|
@@ -12923,7 +13311,7 @@ async function runAgent(agent, options) {
|
|
|
12923
13311
|
signal: handle.signal,
|
|
12924
13312
|
runtimeEventSink: (event, source) => publisher.publish(event, source)
|
|
12925
13313
|
});
|
|
12926
|
-
const result = await
|
|
13314
|
+
const result = await executor2.runUntilYield(checkpointKey);
|
|
12927
13315
|
await Promise.all([callbackTail, persistenceTail]);
|
|
12928
13316
|
await handle.markCompleted({
|
|
12929
13317
|
currentNode: result.checkpoint.nodeId,
|