@linnlabs/linnkit 0.32.2 → 0.33.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 +31 -0
- package/dist/cli.cjs +312 -50
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +312 -50
- package/dist/cli.js.map +1 -1
- package/dist/context-manager.cjs +1 -0
- package/dist/context-manager.cjs.map +1 -1
- package/dist/context-manager.js +1 -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 +32 -32
- package/dist/contracts/audit.d.ts +32 -32
- package/dist/contracts/contextPolicy.d.cts +36 -36
- package/dist/contracts/contextPolicy.d.ts +36 -36
- package/dist/contracts/events.d.cts +968 -968
- package/dist/contracts/events.d.ts +968 -968
- package/dist/contracts/execution.d.cts +8 -8
- package/dist/contracts/execution.d.ts +8 -8
- package/dist/contracts/messages.d.cts +204 -204
- package/dist/contracts/messages.d.ts +204 -204
- package/dist/contracts/sse.d.cts +891 -891
- package/dist/contracts/sse.d.ts +891 -891
- 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 +28 -28
- package/dist/contracts/token-accounting.d.ts +28 -28
- package/dist/index.cjs +383 -66
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +383 -66
- 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 +312 -50
- package/dist/quickstart.cjs.map +1 -1
- package/dist/quickstart.js +312 -50
- 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 +98 -98
- package/dist/runtime-kernel/events/agentEvents.d.ts +98 -98
- 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/index.d.cts +2 -1
- package/dist/runtime-kernel/graph-engine/index.d.ts +2 -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 +14 -2
- package/dist/runtime-kernel/run-supervisor/definitions/runSupervisorContracts.d.ts +14 -2
- 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 +7 -1
- package/dist/runtime-kernel/run-supervisor/runSupervisor.d.ts +7 -1
- package/dist/runtime-kernel.cjs +383 -66
- package/dist/runtime-kernel.cjs.map +1 -1
- package/dist/runtime-kernel.d.cts +2 -1
- package/dist/runtime-kernel.d.ts +2 -1
- package/dist/runtime-kernel.js +381 -67
- package/dist/runtime-kernel.js.map +1 -1
- package/dist/testkit.cjs +383 -66
- package/dist/testkit.cjs.map +1 -1
- package/dist/testkit.js +383 -66
- package/dist/testkit.js.map +1 -1
- package/docs/integration/01-installation.md +1 -1
- package/docs/integration/child-runs.md +12 -0
- package/docs/integration/persistence.md +23 -0
- package/docs/integration/run-supervisor.md +12 -2
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -5,6 +5,7 @@ var eventsourceParser = require('eventsource-parser');
|
|
|
5
5
|
var tiktoken = require('tiktoken');
|
|
6
6
|
var async_hooks = require('async_hooks');
|
|
7
7
|
var crypto = require('crypto');
|
|
8
|
+
var util = require('util');
|
|
8
9
|
var promises = require('fs/promises');
|
|
9
10
|
var path = require('path');
|
|
10
11
|
|
|
@@ -52,6 +53,8 @@ __export(runtime_kernel_exports, {
|
|
|
52
53
|
PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
|
|
53
54
|
PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
|
|
54
55
|
REASONING_EFFORTS: () => REASONING_EFFORTS,
|
|
56
|
+
RunPauseRequested: () => RunPauseRequested,
|
|
57
|
+
RunRecoveryBlockedError: () => RunRecoveryBlockedError,
|
|
55
58
|
RuntimeEventSubRunTracePublisher: () => RuntimeEventSubRunTracePublisher,
|
|
56
59
|
SYSTEM_REMINDER_RULES: () => SYSTEM_REMINDER_RULES,
|
|
57
60
|
SystemReminderRegistry: () => SystemReminderRegistry,
|
|
@@ -109,6 +112,7 @@ __export(runtime_kernel_exports, {
|
|
|
109
112
|
getToolContextRuntimeBinding: () => getToolContextRuntimeBinding,
|
|
110
113
|
graph: () => graph_engine_exports,
|
|
111
114
|
hostReminderTextTemplate: () => hostReminderTextTemplate,
|
|
115
|
+
isRunPauseSignal: () => isRunPauseSignal,
|
|
112
116
|
isRuntimeFailureFact: () => isRuntimeFailureFact,
|
|
113
117
|
isValidReasoningEffort: () => isValidReasoningEffort,
|
|
114
118
|
lastStepsHintTemplate: () => lastStepsHintTemplate,
|
|
@@ -156,12 +160,15 @@ __export(graph_engine_exports, {
|
|
|
156
160
|
MemoryEventStore: () => MemoryEventStore,
|
|
157
161
|
PRIMARY_PROMPT_CAPACITY_ERROR_CODE: () => PRIMARY_PROMPT_CAPACITY_ERROR_CODE,
|
|
158
162
|
PrimaryPromptCapacityError: () => PrimaryPromptCapacityError,
|
|
163
|
+
RunPauseRequested: () => RunPauseRequested,
|
|
164
|
+
RunRecoveryBlockedError: () => RunRecoveryBlockedError,
|
|
159
165
|
ToolNode: () => ToolNode,
|
|
160
166
|
UserNode: () => UserNode,
|
|
161
167
|
WaitUserNode: () => WaitUserNode,
|
|
162
168
|
createHostToolCallBootstrap: () => createHostToolCallBootstrap,
|
|
163
169
|
createMonotonicEventStoreIdFactory: () => createMonotonicEventStoreIdFactory,
|
|
164
170
|
evaluatePrimaryPromptCapacity: () => evaluatePrimaryPromptCapacity,
|
|
171
|
+
isRunPauseSignal: () => isRunPauseSignal,
|
|
165
172
|
isRuntimeFailureFact: () => isRuntimeFailureFact,
|
|
166
173
|
readCheckpointContextUsage: () => readCheckpointContextUsage,
|
|
167
174
|
requireEventStoreId: () => requireEventStoreId,
|
|
@@ -3385,6 +3392,8 @@ var NON_CHECKPOINT_LOCAL_KEYS = [
|
|
|
3385
3392
|
"memory",
|
|
3386
3393
|
"runtimeEventSink",
|
|
3387
3394
|
"runtimeEventCommitPort",
|
|
3395
|
+
"commitExecutionBoundary",
|
|
3396
|
+
"toolRecoveryPort",
|
|
3388
3397
|
"runtimeFailureFactSink",
|
|
3389
3398
|
"signal",
|
|
3390
3399
|
"summarizationCallbacks",
|
|
@@ -3935,6 +3944,7 @@ var GraphExecutor = class {
|
|
|
3935
3944
|
maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS
|
|
3936
3945
|
};
|
|
3937
3946
|
this.telemetryPort = config.telemetryPort ?? noopTelemetry;
|
|
3947
|
+
this.executionCheckpointPort = config.executionCheckpointPort;
|
|
3938
3948
|
}
|
|
3939
3949
|
checkpointer;
|
|
3940
3950
|
nodes = /* @__PURE__ */ new Map();
|
|
@@ -3942,6 +3952,7 @@ var GraphExecutor = class {
|
|
|
3942
3952
|
checkpointQueues = /* @__PURE__ */ new Map();
|
|
3943
3953
|
config;
|
|
3944
3954
|
telemetryPort;
|
|
3955
|
+
executionCheckpointPort;
|
|
3945
3956
|
registerNode(node) {
|
|
3946
3957
|
this.nodes.set(node.id, node);
|
|
3947
3958
|
}
|
|
@@ -3950,6 +3961,7 @@ var GraphExecutor = class {
|
|
|
3950
3961
|
}
|
|
3951
3962
|
sanitize(state) {
|
|
3952
3963
|
return {
|
|
3964
|
+
...state,
|
|
3953
3965
|
nodeId: state.nodeId,
|
|
3954
3966
|
revision: state.revision ?? 0,
|
|
3955
3967
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
@@ -3969,8 +3981,9 @@ var GraphExecutor = class {
|
|
|
3969
3981
|
throw new Error(`Graph checkpoint already exists: ${checkpointKey}`);
|
|
3970
3982
|
}
|
|
3971
3983
|
this.ephemeralLocals.set(checkpointKey, { ...local });
|
|
3972
|
-
await this.
|
|
3984
|
+
await this.commitCheckpoint(checkpointKey, {
|
|
3973
3985
|
nodeId,
|
|
3986
|
+
...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
|
|
3974
3987
|
revision: 1,
|
|
3975
3988
|
schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
|
|
3976
3989
|
local: sanitizeCheckpointLocal(local)
|
|
@@ -3981,6 +3994,33 @@ var GraphExecutor = class {
|
|
|
3981
3994
|
);
|
|
3982
3995
|
});
|
|
3983
3996
|
}
|
|
3997
|
+
/** 从原提交边界继续,和提交 HITL response 的 resumeSession 是不同控制操作。 */
|
|
3998
|
+
async continueSession(checkpointKey, input) {
|
|
3999
|
+
if (!this.executionCheckpointPort) {
|
|
4000
|
+
throw new Error("continueSession requires an ExecutionCheckpointPort");
|
|
4001
|
+
}
|
|
4002
|
+
return this.runWithCheckpointQueue(checkpointKey, async () => {
|
|
4003
|
+
const current = await this.checkpointer.load(checkpointKey);
|
|
4004
|
+
if (!current || current.revision !== input.expectedRevision) {
|
|
4005
|
+
throw new Error(`Graph continuation checkpoint conflict: ${checkpointKey}`);
|
|
4006
|
+
}
|
|
4007
|
+
if (current.schemaVersion !== ENGINE_STATE_SCHEMA_VERSION || !current.executionStatus) {
|
|
4008
|
+
throw new Error(`Graph checkpoint has no supported execution boundary: ${checkpointKey}`);
|
|
4009
|
+
}
|
|
4010
|
+
if (current.executionStatus === "yielded" || current.executionStatus === "awaiting_user") {
|
|
4011
|
+
return { checkpoint: current, events: [], stepCount: 0 };
|
|
4012
|
+
}
|
|
4013
|
+
this.ephemeralLocals.set(checkpointKey, input.capabilities);
|
|
4014
|
+
try {
|
|
4015
|
+
return await this.runUntilYieldQueued(
|
|
4016
|
+
checkpointKey,
|
|
4017
|
+
current.local?.executorLocal?.maxSteps ?? this.config.maxSteps
|
|
4018
|
+
);
|
|
4019
|
+
} finally {
|
|
4020
|
+
this.ephemeralLocals.delete(checkpointKey);
|
|
4021
|
+
}
|
|
4022
|
+
});
|
|
4023
|
+
}
|
|
3984
4024
|
/** 同一个 run 从已持久化 wait_user checkpoint 继续执行。 */
|
|
3985
4025
|
async resumeSession(checkpointKey, input) {
|
|
3986
4026
|
return this.runWithCheckpointQueue(checkpointKey, async () => {
|
|
@@ -4001,17 +4041,21 @@ var GraphExecutor = class {
|
|
|
4001
4041
|
);
|
|
4002
4042
|
}
|
|
4003
4043
|
const resumedLocal = mergeResumeSessionLocal(current.local, input.localPatch);
|
|
4044
|
+
if (this.executionCheckpointPort && current.local?.executorLocal) {
|
|
4045
|
+
resumedLocal.executorLocal = { ...current.local.executorLocal };
|
|
4046
|
+
}
|
|
4004
4047
|
this.ephemeralLocals.set(checkpointKey, resumedLocal);
|
|
4005
|
-
await this.
|
|
4048
|
+
await this.commitCheckpoint(checkpointKey, {
|
|
4006
4049
|
...current,
|
|
4007
4050
|
nodeId: input.nodeId ?? "llm",
|
|
4051
|
+
...this.executionCheckpointPort ? { executionStatus: "ready" } : {},
|
|
4008
4052
|
revision: currentRevision + 1,
|
|
4009
4053
|
local: sanitizeCheckpointLocal(resumedLocal)
|
|
4010
4054
|
});
|
|
4011
4055
|
const persistedMaxSteps = current.local?.executorLocal?.maxSteps;
|
|
4012
4056
|
return this.runUntilYieldQueued(
|
|
4013
4057
|
checkpointKey,
|
|
4014
|
-
input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
|
|
4058
|
+
this.executionCheckpointPort ? persistedMaxSteps ?? this.config.maxSteps : input.maxSteps ?? persistedMaxSteps ?? this.config.maxSteps
|
|
4015
4059
|
);
|
|
4016
4060
|
});
|
|
4017
4061
|
}
|
|
@@ -4106,9 +4150,16 @@ var GraphExecutor = class {
|
|
|
4106
4150
|
...state,
|
|
4107
4151
|
revision: (state.revision ?? 0) + 1
|
|
4108
4152
|
});
|
|
4109
|
-
await this.
|
|
4153
|
+
await this.commitCheckpoint(checkpointKey, checkpoint);
|
|
4110
4154
|
return checkpoint;
|
|
4111
4155
|
}
|
|
4156
|
+
async commitCheckpoint(checkpointKey, checkpoint) {
|
|
4157
|
+
if (this.executionCheckpointPort) {
|
|
4158
|
+
await this.executionCheckpointPort.commit(checkpointKey, checkpoint);
|
|
4159
|
+
} else {
|
|
4160
|
+
await this.checkpointer.save(checkpointKey, checkpoint);
|
|
4161
|
+
}
|
|
4162
|
+
}
|
|
4112
4163
|
async saveCheckpointAndBuildResult(checkpointKey, state, events, stepCount) {
|
|
4113
4164
|
const checkpoint = await this.saveCheckpoint(checkpointKey, state);
|
|
4114
4165
|
return { events, checkpoint, stepCount };
|
|
@@ -4121,6 +4172,15 @@ var GraphExecutor = class {
|
|
|
4121
4172
|
schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
|
|
4122
4173
|
local: { ...state.local || {}, ...ephemeral }
|
|
4123
4174
|
};
|
|
4175
|
+
if (this.executionCheckpointPort) {
|
|
4176
|
+
state.local = {
|
|
4177
|
+
...state.local,
|
|
4178
|
+
commitExecutionBoundary: async (boundary) => {
|
|
4179
|
+
const saved = await this.saveCheckpoint(checkpointKey, boundary);
|
|
4180
|
+
boundary.revision = saved.revision;
|
|
4181
|
+
}
|
|
4182
|
+
};
|
|
4183
|
+
}
|
|
4124
4184
|
const isAbortSignal2 = (v) => {
|
|
4125
4185
|
return v !== null && typeof v === "object" && "aborted" in v;
|
|
4126
4186
|
};
|
|
@@ -4130,11 +4190,12 @@ var GraphExecutor = class {
|
|
|
4130
4190
|
throw err;
|
|
4131
4191
|
};
|
|
4132
4192
|
let stepCount = 0;
|
|
4193
|
+
const previousSteps = this.executionCheckpointPort ? state.local?.executorLocal?.stepCount ?? 0 : 0;
|
|
4133
4194
|
let allEvents = [];
|
|
4134
4195
|
logger2.info("[GraphExecutor] \u5F00\u59CB\u63A8\u7406\u5FAA\u73AF", {
|
|
4135
4196
|
maxSteps
|
|
4136
4197
|
});
|
|
4137
|
-
while (stepCount < maxSteps) {
|
|
4198
|
+
while (previousSteps + stepCount < maxSteps) {
|
|
4138
4199
|
stepCount += 1;
|
|
4139
4200
|
reportStepsUsed(stepCount);
|
|
4140
4201
|
const signalRaw = state.local?.signal;
|
|
@@ -4146,7 +4207,7 @@ var GraphExecutor = class {
|
|
|
4146
4207
|
const stepPreparation = prepareGraphStep({
|
|
4147
4208
|
state,
|
|
4148
4209
|
maxSteps,
|
|
4149
|
-
stepCount
|
|
4210
|
+
stepCount: previousSteps + stepCount
|
|
4150
4211
|
});
|
|
4151
4212
|
state = stepPreparation.state;
|
|
4152
4213
|
const node = this.nodes.get(state.nodeId);
|
|
@@ -4155,6 +4216,7 @@ var GraphExecutor = class {
|
|
|
4155
4216
|
maxSteps,
|
|
4156
4217
|
stepCount
|
|
4157
4218
|
});
|
|
4219
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
4158
4220
|
const result3 = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
4159
4221
|
this.ephemeralLocals.delete(checkpointKey);
|
|
4160
4222
|
return result3;
|
|
@@ -4164,6 +4226,11 @@ var GraphExecutor = class {
|
|
|
4164
4226
|
stepCount,
|
|
4165
4227
|
nodeId: state.nodeId
|
|
4166
4228
|
});
|
|
4229
|
+
if (this.executionCheckpointPort) {
|
|
4230
|
+
state.executionStatus = "executing";
|
|
4231
|
+
const saved = await this.saveCheckpoint(checkpointKey, state);
|
|
4232
|
+
state.revision = saved.revision;
|
|
4233
|
+
}
|
|
4167
4234
|
const result2 = await runGraphNodeWithTelemetry({
|
|
4168
4235
|
node,
|
|
4169
4236
|
state,
|
|
@@ -4188,10 +4255,13 @@ var GraphExecutor = class {
|
|
|
4188
4255
|
fromNodeId: stepResolution.action.fromNodeId,
|
|
4189
4256
|
nextNodeId: stepResolution.action.nextNodeId
|
|
4190
4257
|
});
|
|
4191
|
-
|
|
4258
|
+
if (this.executionCheckpointPort) state.executionStatus = "ready";
|
|
4259
|
+
const saved = await this.saveCheckpoint(checkpointKey, state);
|
|
4260
|
+
state.revision = saved.revision;
|
|
4192
4261
|
continue;
|
|
4193
4262
|
}
|
|
4194
4263
|
if (stepResolution.action.kind === "yield") {
|
|
4264
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
4195
4265
|
logger2.info("[GraphExecutor] \u63A8\u7406\u6682\u505C\uFF0C\u7B49\u5F85\u5916\u90E8\u8F93\u5165", {
|
|
4196
4266
|
maxSteps,
|
|
4197
4267
|
stepCount
|
|
@@ -4202,6 +4272,7 @@ var GraphExecutor = class {
|
|
|
4202
4272
|
maxSteps,
|
|
4203
4273
|
stepCount
|
|
4204
4274
|
});
|
|
4275
|
+
if (this.executionCheckpointPort) state.executionStatus = "awaiting_user";
|
|
4205
4276
|
return await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
4206
4277
|
}
|
|
4207
4278
|
logger2.warn("[GraphExecutor] \u8FBE\u5230\u6B65\u6570\u4E0A\u9650\uFF0C\u5F3A\u5236\u7ED3\u675F", {
|
|
@@ -4222,6 +4293,7 @@ var GraphExecutor = class {
|
|
|
4222
4293
|
},
|
|
4223
4294
|
retryable: false
|
|
4224
4295
|
}), "GraphExecutor.engine_budget_exhausted"));
|
|
4296
|
+
if (this.executionCheckpointPort) state.executionStatus = "yielded";
|
|
4225
4297
|
const result = await this.saveCheckpointAndBuildResult(checkpointKey, state, allEvents, stepCount);
|
|
4226
4298
|
this.ephemeralLocals.delete(checkpointKey);
|
|
4227
4299
|
return result;
|
|
@@ -8125,10 +8197,11 @@ var LlmNode = class {
|
|
|
8125
8197
|
bridge.handle
|
|
8126
8198
|
);
|
|
8127
8199
|
} catch (error) {
|
|
8128
|
-
bridge.finalizePartialAnswer();
|
|
8200
|
+
if (!local.commitExecutionBoundary) bridge.finalizePartialAnswer();
|
|
8129
8201
|
throw error;
|
|
8130
8202
|
}
|
|
8131
8203
|
const { decision, executorLocalPatch, contextTrace, contextUsage } = tickOutput;
|
|
8204
|
+
if (decision.kind === "error" && local.commitExecutionBoundary) throw decision.error;
|
|
8132
8205
|
switch (decision.kind) {
|
|
8133
8206
|
case "tool_calls": {
|
|
8134
8207
|
if (forceFinalAnswer) {
|
|
@@ -9403,6 +9476,58 @@ function recordToolProtocolError(params) {
|
|
|
9403
9476
|
recorder?.recordToolProtocolError?.(params);
|
|
9404
9477
|
}
|
|
9405
9478
|
|
|
9479
|
+
// src/runtime-kernel/graph-engine/definitions/runContinuation.ts
|
|
9480
|
+
var RunRecoveryBlockedError = class extends Error {
|
|
9481
|
+
code = "RUN_RECOVERY_BLOCKED";
|
|
9482
|
+
constructor(message) {
|
|
9483
|
+
super(message);
|
|
9484
|
+
this.name = "RunRecoveryBlockedError";
|
|
9485
|
+
}
|
|
9486
|
+
};
|
|
9487
|
+
var RunPauseRequested = class extends Error {
|
|
9488
|
+
code = "RUN_PAUSE_REQUESTED";
|
|
9489
|
+
constructor(message = "Run paused by user") {
|
|
9490
|
+
super(message);
|
|
9491
|
+
this.name = "RunPauseRequested";
|
|
9492
|
+
}
|
|
9493
|
+
};
|
|
9494
|
+
function isRunPauseSignal(signal) {
|
|
9495
|
+
const reason = signal?.reason;
|
|
9496
|
+
return signal?.aborted === true && typeof reason === "object" && reason !== null && "code" in reason && reason.code === "RUN_PAUSE_REQUESTED";
|
|
9497
|
+
}
|
|
9498
|
+
|
|
9499
|
+
// src/runtime-kernel/graph-engine/nodes/toolNode.recovery.ts
|
|
9500
|
+
async function executeRecoverableTool(input) {
|
|
9501
|
+
const local = input.state.local;
|
|
9502
|
+
if (!local?.commitExecutionBoundary) return input.execute();
|
|
9503
|
+
if (local.executingToolCallId) {
|
|
9504
|
+
if (local.executingToolCallId !== input.call.id) {
|
|
9505
|
+
throw new RunRecoveryBlockedError("Pending tool identity does not match execution intent");
|
|
9506
|
+
}
|
|
9507
|
+
const decision = await local.toolRecoveryPort?.reconcile(input.call, input.context);
|
|
9508
|
+
if (!decision || decision.kind === "blocked") {
|
|
9509
|
+
throw new RunRecoveryBlockedError(decision?.reason ?? `Tool outcome is unknown: ${input.call.id}`);
|
|
9510
|
+
}
|
|
9511
|
+
if (decision.kind === "settled") return decision.result;
|
|
9512
|
+
}
|
|
9513
|
+
local.executingToolCallId = input.call.id;
|
|
9514
|
+
await local.commitExecutionBoundary(input.state);
|
|
9515
|
+
const result = await input.execute();
|
|
9516
|
+
if (!result.success && isRunPauseSignal(local.signal)) {
|
|
9517
|
+
const error = new Error("Tool execution paused before its outcome was confirmed");
|
|
9518
|
+
error.name = "AbortError";
|
|
9519
|
+
throw error;
|
|
9520
|
+
}
|
|
9521
|
+
return result;
|
|
9522
|
+
}
|
|
9523
|
+
async function commitToolBoundary(state, result) {
|
|
9524
|
+
if (!state.local?.commitExecutionBoundary) return;
|
|
9525
|
+
delete state.local.executingToolCallId;
|
|
9526
|
+
state.nodeId = result.kind === "route" ? result.nextNodeId ?? "user" : state.nodeId;
|
|
9527
|
+
state.executionStatus = result.kind === "yield" ? "yielded" : "ready";
|
|
9528
|
+
await state.local.commitExecutionBoundary(state);
|
|
9529
|
+
}
|
|
9530
|
+
|
|
9406
9531
|
// src/runtime-kernel/graph-engine/nodes/toolNode.ts
|
|
9407
9532
|
var logger11 = new Logger("ToolNode");
|
|
9408
9533
|
function isAbortSignal(value) {
|
|
@@ -9573,6 +9698,7 @@ var ToolNode = class {
|
|
|
9573
9698
|
const events = [];
|
|
9574
9699
|
while (true) {
|
|
9575
9700
|
const result = await this.runNextPendingToolCall(state);
|
|
9701
|
+
await commitToolBoundary(state, result);
|
|
9576
9702
|
if (Array.isArray(result.events) && result.events.length > 0) {
|
|
9577
9703
|
events.push(...result.events);
|
|
9578
9704
|
}
|
|
@@ -9589,11 +9715,9 @@ var ToolNode = class {
|
|
|
9589
9715
|
const calls = parsePendingToolCalls(state.local?.pendingToolCalls ?? []);
|
|
9590
9716
|
const signalRaw = state.local?.signal;
|
|
9591
9717
|
if (isAbortSignal(signalRaw) && signalRaw.aborted) {
|
|
9592
|
-
|
|
9593
|
-
state,
|
|
9594
|
-
|
|
9595
|
-
toolCatalog: this.toolRuntime
|
|
9596
|
-
});
|
|
9718
|
+
if (!isRunPauseSignal(signalRaw)) {
|
|
9719
|
+
settlePendingToolCallsAfterAbort({ state, calls, toolCatalog: this.toolRuntime });
|
|
9720
|
+
}
|
|
9597
9721
|
const abortError = new Error("The user aborted a request.");
|
|
9598
9722
|
abortError.name = "AbortError";
|
|
9599
9723
|
throw abortError;
|
|
@@ -9732,16 +9856,21 @@ var ToolNode = class {
|
|
|
9732
9856
|
tool_calls: [call]
|
|
9733
9857
|
});
|
|
9734
9858
|
try {
|
|
9735
|
-
const exec = await
|
|
9736
|
-
|
|
9737
|
-
|
|
9738
|
-
|
|
9739
|
-
|
|
9740
|
-
|
|
9741
|
-
|
|
9742
|
-
|
|
9743
|
-
|
|
9744
|
-
|
|
9859
|
+
const exec = await executeRecoverableTool({
|
|
9860
|
+
state,
|
|
9861
|
+
call,
|
|
9862
|
+
context: prepared.toolContext,
|
|
9863
|
+
execute: () => executeToolWithIdempotency({
|
|
9864
|
+
idempotencyKey: execution.idempotencyKey,
|
|
9865
|
+
inFlight: this.idempotencyInFlight,
|
|
9866
|
+
history: readHistoryEvents(prepared.local),
|
|
9867
|
+
toolName: execution.toolName,
|
|
9868
|
+
execute: () => this.toolRuntime.executeTool(
|
|
9869
|
+
execution.toolName,
|
|
9870
|
+
execution.toolArgs,
|
|
9871
|
+
prepared.toolContext
|
|
9872
|
+
)
|
|
9873
|
+
})
|
|
9745
9874
|
});
|
|
9746
9875
|
if (exec.success) {
|
|
9747
9876
|
const parsed = typeof exec.result === "string" ? parseJsonSafe(exec.result) : exec.result;
|
|
@@ -9821,7 +9950,7 @@ var ToolNode = class {
|
|
|
9821
9950
|
bridge: execution.bridge
|
|
9822
9951
|
});
|
|
9823
9952
|
} catch (error) {
|
|
9824
|
-
if (isToolExecutionAbort(error)) {
|
|
9953
|
+
if (isToolExecutionAbort(error) && !isRunPauseSignal(state.local?.signal)) {
|
|
9825
9954
|
settleToolCallsAfterExecutionAbort({
|
|
9826
9955
|
state,
|
|
9827
9956
|
remainingCalls: calls.slice(1),
|
|
@@ -9881,7 +10010,7 @@ var ToolNode = class {
|
|
|
9881
10010
|
{
|
|
9882
10011
|
attachments: context.attachments,
|
|
9883
10012
|
metadata: Object.keys(toolOutputMetadata).length > 0 ? toolOutputMetadata : void 0,
|
|
9884
|
-
|
|
10013
|
+
// 缓存复用的是业务结果,不是当前 call 的终态身份;每个新 call 都必须可持久化配对。
|
|
9885
10014
|
durationMs: context.exec.durationMs
|
|
9886
10015
|
}
|
|
9887
10016
|
);
|
|
@@ -9938,6 +10067,9 @@ var ToolNode = class {
|
|
|
9938
10067
|
return { kind: "route", nextNodeId: "wait_user", events: context.bridge.getRuntimeEvents() };
|
|
9939
10068
|
}
|
|
9940
10069
|
async handleError(context) {
|
|
10070
|
+
if (context.state.local?.executingToolCallId && (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability")) {
|
|
10071
|
+
throw new RunRecoveryBlockedError(context.exec.error ?? "Tool recovery capability is unavailable");
|
|
10072
|
+
}
|
|
9941
10073
|
if (context.exec.errorKind === "protocol" || context.exec.errorKind === "capability") {
|
|
9942
10074
|
await this.emitToolDecisionAudit({
|
|
9943
10075
|
action: "tool.deny",
|
|
@@ -11046,12 +11178,33 @@ var RuntimeEventPublisher = class {
|
|
|
11046
11178
|
var EventBusEventPersistence = class {
|
|
11047
11179
|
constructor(options) {
|
|
11048
11180
|
this.options = options;
|
|
11181
|
+
this.checkpointWritesActive = options.checkpointWriter !== void 0;
|
|
11049
11182
|
}
|
|
11050
11183
|
options;
|
|
11051
11184
|
scheduledEventIds = /* @__PURE__ */ new Set();
|
|
11052
11185
|
writeTail = Promise.resolve();
|
|
11053
11186
|
firstWriteError;
|
|
11054
11187
|
connected = false;
|
|
11188
|
+
checkpointWritesActive;
|
|
11189
|
+
checkpointEvents = [];
|
|
11190
|
+
/** Graph 的执行边界复用同一有序队列;没有第二条事件写入链。 */
|
|
11191
|
+
async commitCheckpoint(checkpointKey, checkpoint) {
|
|
11192
|
+
const writer = this.options.checkpointWriter;
|
|
11193
|
+
if (!writer || !this.checkpointWritesActive) throw new Error("Checkpoint writer is not active");
|
|
11194
|
+
const events = this.checkpointEvents;
|
|
11195
|
+
this.checkpointEvents = [];
|
|
11196
|
+
await this.enqueueWrite(() => writer({
|
|
11197
|
+
checkpointKey,
|
|
11198
|
+
checkpoint,
|
|
11199
|
+
events: events.map((event) => ({ event, eventStoreId: this.options.nextEventStoreId() }))
|
|
11200
|
+
}));
|
|
11201
|
+
}
|
|
11202
|
+
/** 离开 Graph 后,未提交的 attempt 事实作废;随后 settlement metrics 走普通写入。 */
|
|
11203
|
+
finishCheckpointWrites() {
|
|
11204
|
+
for (const event of this.checkpointEvents) this.scheduledEventIds.delete(event.id);
|
|
11205
|
+
this.checkpointEvents = [];
|
|
11206
|
+
this.checkpointWritesActive = false;
|
|
11207
|
+
}
|
|
11055
11208
|
connect() {
|
|
11056
11209
|
if (this.connected) {
|
|
11057
11210
|
throw new Error("[EventBusEventPersistence] consumer is already connected");
|
|
@@ -11098,14 +11251,22 @@ var EventBusEventPersistence = class {
|
|
|
11098
11251
|
if (!shouldPersistRuntimeEvent(event) || this.scheduledEventIds.has(event.id)) {
|
|
11099
11252
|
return;
|
|
11100
11253
|
}
|
|
11254
|
+
if (this.checkpointWritesActive) {
|
|
11255
|
+
this.scheduledEventIds.add(event.id);
|
|
11256
|
+
this.checkpointEvents.push(event);
|
|
11257
|
+
return;
|
|
11258
|
+
}
|
|
11101
11259
|
void this.scheduleWrite(event).catch(() => void 0);
|
|
11102
11260
|
};
|
|
11103
11261
|
scheduleWrite(event) {
|
|
11104
11262
|
this.scheduledEventIds.add(event.id);
|
|
11105
|
-
|
|
11106
|
-
|
|
11107
|
-
|
|
11108
|
-
});
|
|
11263
|
+
return this.enqueueWrite(() => this.options.eventStore.append({
|
|
11264
|
+
eventStoreId: this.options.nextEventStoreId(),
|
|
11265
|
+
event
|
|
11266
|
+
}));
|
|
11267
|
+
}
|
|
11268
|
+
enqueueWrite(operation) {
|
|
11269
|
+
const write = this.writeTail.then(operation);
|
|
11109
11270
|
this.writeTail = write;
|
|
11110
11271
|
void write.catch((error) => {
|
|
11111
11272
|
this.firstWriteError ??= error;
|
|
@@ -12826,6 +12987,9 @@ var ChildRunInvoker = class {
|
|
|
12826
12987
|
explicitConversationId: conversationId,
|
|
12827
12988
|
parentToolContext
|
|
12828
12989
|
});
|
|
12990
|
+
if (config.persistence?.expectedRevision !== void 0) {
|
|
12991
|
+
return this.continueChild(config, childRunId, runtimeConversationId);
|
|
12992
|
+
}
|
|
12829
12993
|
const turnId = generateTurnId();
|
|
12830
12994
|
logger17.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
|
|
12831
12995
|
conversationId: runtimeConversationId,
|
|
@@ -12833,21 +12997,8 @@ var ChildRunInvoker = class {
|
|
|
12833
12997
|
maxSteps,
|
|
12834
12998
|
userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
|
|
12835
12999
|
});
|
|
12836
|
-
const checkpointer = new MemoryCheckpointer();
|
|
12837
|
-
const graphExecutor =
|
|
12838
|
-
const llmNode = this.createLlmNode();
|
|
12839
|
-
const toolNode = new ToolNode({
|
|
12840
|
-
toolRuntime: this.toolRuntime,
|
|
12841
|
-
observationPreview: this.observationPreview,
|
|
12842
|
-
telemetryPort: this.telemetryPort,
|
|
12843
|
-
auditPort: this.auditPort,
|
|
12844
|
-
modelInputCapabilityValidator: this.modelInputCapabilityValidator,
|
|
12845
|
-
modelInputResolver: this.modelInputResolver
|
|
12846
|
-
});
|
|
12847
|
-
const waitUserNode = new WaitUserNode({ auditPort: this.auditPort });
|
|
12848
|
-
graphExecutor.registerNode(llmNode);
|
|
12849
|
-
graphExecutor.registerNode(toolNode);
|
|
12850
|
-
graphExecutor.registerNode(waitUserNode);
|
|
13000
|
+
const checkpointer = config.persistence?.checkpointer ?? new MemoryCheckpointer();
|
|
13001
|
+
const graphExecutor = this.createGraph(checkpointer, maxSteps, config.persistence?.executionCheckpointPort);
|
|
12851
13002
|
const childUserInput = createChildRunUserInput({
|
|
12852
13003
|
id: generateRuntimeEventId(),
|
|
12853
13004
|
conversationId: runtimeConversationId,
|
|
@@ -12927,6 +13078,7 @@ var ChildRunInvoker = class {
|
|
|
12927
13078
|
...abortSignal ? { signal: abortSignal } : {},
|
|
12928
13079
|
...Object.keys(executorLocalPolicy).length > 0 ? { executorLocal: executorLocalPolicy } : {},
|
|
12929
13080
|
runtimeEventSink,
|
|
13081
|
+
toolRecoveryPort: config.persistence?.toolRecoveryPort,
|
|
12930
13082
|
...runtimeEventCommitPort ? { runtimeEventCommitPort } : {},
|
|
12931
13083
|
systemPrompt
|
|
12932
13084
|
};
|
|
@@ -12967,6 +13119,7 @@ var ChildRunInvoker = class {
|
|
|
12967
13119
|
eventToMessageConverter: this.eventToMessageConverter
|
|
12968
13120
|
});
|
|
12969
13121
|
} catch (err) {
|
|
13122
|
+
if (config.persistence) throw err;
|
|
12970
13123
|
const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
|
|
12971
13124
|
checkpointer,
|
|
12972
13125
|
checkpointKey: internalCheckpointKey,
|
|
@@ -13005,7 +13158,7 @@ var ChildRunInvoker = class {
|
|
|
13005
13158
|
events: allEvents,
|
|
13006
13159
|
eventToMessageConverter: this.eventToMessageConverter
|
|
13007
13160
|
});
|
|
13008
|
-
await checkpointer.clear(internalCheckpointKey);
|
|
13161
|
+
if (!config.persistence) await checkpointer.clear(internalCheckpointKey);
|
|
13009
13162
|
return {
|
|
13010
13163
|
success: !error && !cancelled,
|
|
13011
13164
|
runId: childRunId,
|
|
@@ -13022,6 +13175,66 @@ var ChildRunInvoker = class {
|
|
|
13022
13175
|
error
|
|
13023
13176
|
};
|
|
13024
13177
|
}
|
|
13178
|
+
createGraph(checkpointer, maxSteps, executionCheckpointPort) {
|
|
13179
|
+
const graph = new GraphExecutor(checkpointer, { maxSteps, executionCheckpointPort });
|
|
13180
|
+
graph.registerNode(this.createLlmNode());
|
|
13181
|
+
graph.registerNode(new ToolNode({
|
|
13182
|
+
toolRuntime: this.toolRuntime,
|
|
13183
|
+
observationPreview: this.observationPreview,
|
|
13184
|
+
telemetryPort: this.telemetryPort,
|
|
13185
|
+
auditPort: this.auditPort,
|
|
13186
|
+
modelInputCapabilityValidator: this.modelInputCapabilityValidator,
|
|
13187
|
+
modelInputResolver: this.modelInputResolver
|
|
13188
|
+
}));
|
|
13189
|
+
graph.registerNode(new WaitUserNode({ auditPort: this.auditPort }));
|
|
13190
|
+
return graph;
|
|
13191
|
+
}
|
|
13192
|
+
async continueChild(config, runId, conversationId) {
|
|
13193
|
+
const persistence = config.persistence;
|
|
13194
|
+
if (!persistence || persistence.expectedRevision === void 0) throw new Error("Missing child continuation contract");
|
|
13195
|
+
const checkpoint = await persistence.checkpointer.load(runId);
|
|
13196
|
+
if (!checkpoint || checkpoint.local?.conversationId !== conversationId) throw new Error("Child checkpoint identity mismatch");
|
|
13197
|
+
const local = readGraphAgentLocal({ ...checkpoint.local, runtimeEventSink: config.runtimeEventSink });
|
|
13198
|
+
const request = local.request;
|
|
13199
|
+
if (!request || !local.turnId || !request.model_id) throw new Error("Child recovery input is incomplete");
|
|
13200
|
+
const context = createChildRunToolContext({
|
|
13201
|
+
parentToolContext: config.parentToolContext,
|
|
13202
|
+
conversationId,
|
|
13203
|
+
turnId: local.turnId,
|
|
13204
|
+
runId,
|
|
13205
|
+
parentRunId: config.parentRunId,
|
|
13206
|
+
userQuery: request.query,
|
|
13207
|
+
modelId: request.model_id,
|
|
13208
|
+
seedHistory: local.history,
|
|
13209
|
+
abortSignal: config.abortSignal
|
|
13210
|
+
});
|
|
13211
|
+
const graph = this.createGraph(persistence.checkpointer, request.maxSteps ?? 8, persistence.executionCheckpointPort);
|
|
13212
|
+
const result = await graph.continueSession(runId, {
|
|
13213
|
+
expectedRevision: persistence.expectedRevision,
|
|
13214
|
+
capabilities: {
|
|
13215
|
+
toolContext: context,
|
|
13216
|
+
signal: config.abortSignal,
|
|
13217
|
+
runtimeEventSink: config.runtimeEventSink,
|
|
13218
|
+
runtimeEventCommitPort: config.runtimeEventCommitPort,
|
|
13219
|
+
toolRecoveryPort: persistence.toolRecoveryPort
|
|
13220
|
+
}
|
|
13221
|
+
});
|
|
13222
|
+
if (result.checkpoint.nodeId === "wait_user") throw new Error("Interactive tools require a foreground run");
|
|
13223
|
+
const events = (result.checkpoint.local?.history ?? []).filter((event) => event.run_id === runId && event.type !== "user_input").map((event) => parseRoutedRuntimeEvent(event));
|
|
13224
|
+
const finalAnswer = extractFinalAnswer(events);
|
|
13225
|
+
return {
|
|
13226
|
+
runId,
|
|
13227
|
+
parentRunId: config.parentRunId,
|
|
13228
|
+
subrunId: runId,
|
|
13229
|
+
success: true,
|
|
13230
|
+
events,
|
|
13231
|
+
finalAnswer,
|
|
13232
|
+
lastProgress: finalAnswer ? void 0 : extractLastProgress(events),
|
|
13233
|
+
judgeToolOutput: extractJudgeToolOutput(events, config.agentConfig.judgeToolName ?? this.defaultJudgeToolName),
|
|
13234
|
+
stepCount: result.checkpoint.local?.executorLocal?.stepCount ?? 0,
|
|
13235
|
+
toolset: { availableTools: request.availableTools }
|
|
13236
|
+
};
|
|
13237
|
+
}
|
|
13025
13238
|
};
|
|
13026
13239
|
function isAbortError2(error) {
|
|
13027
13240
|
return error instanceof Error && error.name === "AbortError";
|
|
@@ -13423,8 +13636,6 @@ __export(run_supervisor_exports, {
|
|
|
13423
13636
|
RunNotFoundError: () => RunNotFoundError,
|
|
13424
13637
|
runMetaFromRecord: () => runMetaFromRecord
|
|
13425
13638
|
});
|
|
13426
|
-
|
|
13427
|
-
// src/runtime-kernel/run-supervisor/memoryRunRegistryStore.ts
|
|
13428
13639
|
function cloneRunRecord(record) {
|
|
13429
13640
|
return {
|
|
13430
13641
|
...record,
|
|
@@ -13444,6 +13655,11 @@ function matchesStatus(candidate, filter) {
|
|
|
13444
13655
|
}
|
|
13445
13656
|
var MemoryRunRegistryStore = class {
|
|
13446
13657
|
store = /* @__PURE__ */ new Map();
|
|
13658
|
+
async compareAndSwap(previous, next) {
|
|
13659
|
+
if (previous.runId !== next.runId || !util.isDeepStrictEqual(this.store.get(previous.runId), previous)) return false;
|
|
13660
|
+
this.store.set(next.runId, cloneRunRecord(next));
|
|
13661
|
+
return true;
|
|
13662
|
+
}
|
|
13447
13663
|
async save(record) {
|
|
13448
13664
|
this.store.set(record.runId, cloneRunRecord(record));
|
|
13449
13665
|
}
|
|
@@ -13591,6 +13807,17 @@ var RunConcurrencyKeyOccupiedError = class extends Error {
|
|
|
13591
13807
|
}
|
|
13592
13808
|
};
|
|
13593
13809
|
|
|
13810
|
+
// src/runtime-kernel/run-supervisor/functions/persistRunTransition.ts
|
|
13811
|
+
async function persistRunTransition(store, previous, next) {
|
|
13812
|
+
if (store.compareAndSwap) {
|
|
13813
|
+
if (!await store.compareAndSwap(previous, next)) {
|
|
13814
|
+
throw new RunInteractionConflictError(previous.runId, "run changed before lifecycle commit");
|
|
13815
|
+
}
|
|
13816
|
+
} else {
|
|
13817
|
+
await store.save(next);
|
|
13818
|
+
}
|
|
13819
|
+
}
|
|
13820
|
+
|
|
13594
13821
|
// src/runtime-kernel/run-supervisor/functions/runLifecycleTransition.ts
|
|
13595
13822
|
function isRunTerminalStatus(status) {
|
|
13596
13823
|
return status === "completed" || status === "failed" || status === "cancelled";
|
|
@@ -13646,6 +13873,7 @@ var DefaultRunHandle = class {
|
|
|
13646
13873
|
parentRunId;
|
|
13647
13874
|
runRecord;
|
|
13648
13875
|
abortController;
|
|
13876
|
+
executionId;
|
|
13649
13877
|
agentSpecSnapshot;
|
|
13650
13878
|
requestSnapshot;
|
|
13651
13879
|
transportEventBus;
|
|
@@ -13661,6 +13889,9 @@ var DefaultRunHandle = class {
|
|
|
13661
13889
|
this.runId = options.runRecord.runId;
|
|
13662
13890
|
this.parentRunId = options.runRecord.parentRunId;
|
|
13663
13891
|
this.abortController = options.abortController;
|
|
13892
|
+
const executionId = options.runRecord.metadata?.executionId;
|
|
13893
|
+
if (executionId !== void 0 && typeof executionId !== "string") throw new Error("Run executionId must be a string");
|
|
13894
|
+
this.executionId = executionId;
|
|
13664
13895
|
this.agentSpecSnapshot = AgentSpec.parse(structuredClone(options.agentSpec));
|
|
13665
13896
|
this.requestSnapshot = cloneRequest(options.request);
|
|
13666
13897
|
this.transportEventBus = options.eventBus;
|
|
@@ -13680,8 +13911,9 @@ var DefaultRunHandle = class {
|
|
|
13680
13911
|
* awaiting_user 之后的 resume 是同一逻辑 run 的新 execution。
|
|
13681
13912
|
* 必须切换取消控制器,避免旧 transport 的迟到 abort 污染新 execution。
|
|
13682
13913
|
*/
|
|
13683
|
-
replaceExecutionAbortController(controller) {
|
|
13914
|
+
replaceExecutionAbortController(controller, executionId) {
|
|
13684
13915
|
this.abortController = controller;
|
|
13916
|
+
this.executionId = executionId;
|
|
13685
13917
|
}
|
|
13686
13918
|
async spec() {
|
|
13687
13919
|
return AgentSpec.parse(structuredClone(this.agentSpecSnapshot));
|
|
@@ -13701,6 +13933,7 @@ var DefaultRunHandle = class {
|
|
|
13701
13933
|
this.abortController.abort(opts.reason);
|
|
13702
13934
|
const latestRecord = await this.registryStore.load(this.runId);
|
|
13703
13935
|
const baseRecord = latestRecord ?? this.runRecord;
|
|
13936
|
+
this.assertExecutionOwner(baseRecord);
|
|
13704
13937
|
const transition = decideRunLifecycleTransition(baseRecord.status);
|
|
13705
13938
|
if (transition.kind === "skip_terminal") {
|
|
13706
13939
|
if (transition.terminalStatus === "cancelled" && hasLifecyclePatch(patch)) {
|
|
@@ -13710,7 +13943,7 @@ var DefaultRunHandle = class {
|
|
|
13710
13943
|
currentNode: patch.currentNode ?? baseRecord.currentNode,
|
|
13711
13944
|
iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed
|
|
13712
13945
|
};
|
|
13713
|
-
await this.registryStore
|
|
13946
|
+
await persistRunTransition(this.registryStore, baseRecord, settledRecord);
|
|
13714
13947
|
this.runRecord = { ...settledRecord };
|
|
13715
13948
|
return;
|
|
13716
13949
|
}
|
|
@@ -13737,7 +13970,7 @@ var DefaultRunHandle = class {
|
|
|
13737
13970
|
}
|
|
13738
13971
|
}
|
|
13739
13972
|
};
|
|
13740
|
-
await this.registryStore
|
|
13973
|
+
await persistRunTransition(this.registryStore, baseRecord, nextRecord);
|
|
13741
13974
|
this.runRecord = { ...nextRecord };
|
|
13742
13975
|
await this.auditPort.emit({
|
|
13743
13976
|
envelopeId: generateAuditEnvelopeId(),
|
|
@@ -13845,21 +14078,35 @@ var DefaultRunHandle = class {
|
|
|
13845
14078
|
async markFailed(error, patch = {}) {
|
|
13846
14079
|
await this.saveLifecycleStatus("failed", patch, error);
|
|
13847
14080
|
}
|
|
13848
|
-
async pause(
|
|
13849
|
-
|
|
14081
|
+
async pause(reason = "Run paused by user") {
|
|
14082
|
+
const latest = await this.registryStore.load(this.runId);
|
|
14083
|
+
if (latest) this.assertExecutionOwner(latest);
|
|
14084
|
+
if (!latest || latest.status === "paused" || latest.status === "awaiting_user" || decideRunLifecycleTransition(latest.status).kind === "skip_terminal") return;
|
|
14085
|
+
const next = {
|
|
14086
|
+
...latest,
|
|
14087
|
+
status: "paused",
|
|
14088
|
+
updatedAt: Date.now(),
|
|
14089
|
+
pauseReason: reason,
|
|
14090
|
+
pausedAt: void 0
|
|
14091
|
+
};
|
|
14092
|
+
await persistRunTransition(this.registryStore, latest, next);
|
|
14093
|
+
this.runRecord = next;
|
|
14094
|
+
this.abortController.abort(new RunPauseRequested(reason));
|
|
13850
14095
|
}
|
|
13851
|
-
async
|
|
13852
|
-
|
|
14096
|
+
async markPaused(patch = {}) {
|
|
14097
|
+
await this.saveLifecycleStatus("paused", patch);
|
|
13853
14098
|
}
|
|
13854
14099
|
async saveLifecycleStatus(status, patch, errorIfAny) {
|
|
13855
14100
|
const latestRecord = await this.registryStore.load(this.runId);
|
|
13856
14101
|
const baseRecord = latestRecord ?? this.runRecord;
|
|
13857
14102
|
const transition = decideRunLifecycleTransition(baseRecord.status);
|
|
14103
|
+
this.assertExecutionOwner(baseRecord);
|
|
14104
|
+
if (status === "running" && baseRecord.status === "paused") return;
|
|
13858
14105
|
if (transition.kind === "skip_terminal") {
|
|
13859
14106
|
this.runRecord = { ...baseRecord };
|
|
13860
14107
|
return;
|
|
13861
14108
|
}
|
|
13862
|
-
const awaitingUserPatch = status === "awaiting_user" ? patch : void 0;
|
|
14109
|
+
const awaitingUserPatch = status === "awaiting_user" || status === "paused" ? patch : void 0;
|
|
13863
14110
|
const updatedAt = Date.now();
|
|
13864
14111
|
const nextRecord = {
|
|
13865
14112
|
...baseRecord,
|
|
@@ -13867,8 +14114,8 @@ var DefaultRunHandle = class {
|
|
|
13867
14114
|
updatedAt,
|
|
13868
14115
|
currentNode: patch.currentNode ?? baseRecord.currentNode,
|
|
13869
14116
|
iterationsUsed: patch.iterationsUsed ?? baseRecord.iterationsUsed,
|
|
13870
|
-
pauseReason: status === "awaiting_user" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
|
|
13871
|
-
pausedAt: status === "awaiting_user" ? updatedAt : void 0,
|
|
14117
|
+
pauseReason: status === "awaiting_user" || status === "paused" ? awaitingUserPatch?.reason ?? baseRecord.pauseReason : void 0,
|
|
14118
|
+
pausedAt: status === "awaiting_user" || status === "paused" ? updatedAt : void 0,
|
|
13872
14119
|
errorIfAny,
|
|
13873
14120
|
metadata: awaitingUserPatch?.eventId ? {
|
|
13874
14121
|
...baseRecord.metadata ?? {},
|
|
@@ -13879,7 +14126,7 @@ var DefaultRunHandle = class {
|
|
|
13879
14126
|
}
|
|
13880
14127
|
} : baseRecord.metadata
|
|
13881
14128
|
};
|
|
13882
|
-
await this.registryStore
|
|
14129
|
+
await persistRunTransition(this.registryStore, baseRecord, nextRecord);
|
|
13883
14130
|
this.runRecord = { ...nextRecord };
|
|
13884
14131
|
if (status === "completed" || status === "failed") {
|
|
13885
14132
|
this.closeObservationChannel();
|
|
@@ -13889,6 +14136,11 @@ var DefaultRunHandle = class {
|
|
|
13889
14136
|
forwardTransportEvent = (envelope) => {
|
|
13890
14137
|
this.observationEventBus.emit("event", envelope);
|
|
13891
14138
|
};
|
|
14139
|
+
assertExecutionOwner(record) {
|
|
14140
|
+
if (record.metadata?.executionId !== this.executionId) {
|
|
14141
|
+
throw new RunInteractionConflictError(this.runId, "execution ownership has changed");
|
|
14142
|
+
}
|
|
14143
|
+
}
|
|
13892
14144
|
forwardTransportError = (error) => {
|
|
13893
14145
|
this.observationEventBus.emit("error", error);
|
|
13894
14146
|
};
|
|
@@ -14270,6 +14522,24 @@ async function recoverRunsOnBoot(options) {
|
|
|
14270
14522
|
const outcomes = [];
|
|
14271
14523
|
for (const record of activeRecords) {
|
|
14272
14524
|
const updatedAt = options.now();
|
|
14525
|
+
if (await options.canRestoreRun?.(record)) {
|
|
14526
|
+
const metadata = { ...record.metadata };
|
|
14527
|
+
const awaitingUser = metadata.awaitingUser;
|
|
14528
|
+
if (awaitingUser && typeof awaitingUser === "object" && !Array.isArray(awaitingUser)) {
|
|
14529
|
+
const restored = { ...awaitingUser };
|
|
14530
|
+
Reflect.deleteProperty(restored, "resumeClaim");
|
|
14531
|
+
metadata.awaitingUser = restored;
|
|
14532
|
+
}
|
|
14533
|
+
await persistRunTransition(options.registryStore, record, {
|
|
14534
|
+
...record,
|
|
14535
|
+
status: record.status === "awaiting_user" ? "awaiting_user" : "paused",
|
|
14536
|
+
pausedAt: record.pausedAt ?? updatedAt,
|
|
14537
|
+
pauseReason: record.pauseReason ?? options.reason,
|
|
14538
|
+
updatedAt,
|
|
14539
|
+
metadata
|
|
14540
|
+
});
|
|
14541
|
+
continue;
|
|
14542
|
+
}
|
|
14273
14543
|
const nextRecord = {
|
|
14274
14544
|
...record,
|
|
14275
14545
|
status: "failed",
|
|
@@ -14287,7 +14557,7 @@ async function recoverRunsOnBoot(options) {
|
|
|
14287
14557
|
}
|
|
14288
14558
|
}
|
|
14289
14559
|
};
|
|
14290
|
-
await options.registryStore
|
|
14560
|
+
await persistRunTransition(options.registryStore, record, nextRecord);
|
|
14291
14561
|
const outcome = runRecordToTerminalOutcome(nextRecord, updatedAt);
|
|
14292
14562
|
options.notifyTerminal(outcome);
|
|
14293
14563
|
outcomes.push(outcome);
|
|
@@ -14411,8 +14681,13 @@ var DefaultRunSupervisor = class {
|
|
|
14411
14681
|
inFlight = /* @__PURE__ */ new Map();
|
|
14412
14682
|
eventWatchDisposers = /* @__PURE__ */ new Map();
|
|
14413
14683
|
controlOperations = /* @__PURE__ */ new Map();
|
|
14684
|
+
canRestoreRun;
|
|
14414
14685
|
constructor(options) {
|
|
14686
|
+
if (options.canRestoreRun && !options.registryStore.compareAndSwap) {
|
|
14687
|
+
throw new Error("Run recovery requires RunRegistryStore.compareAndSwap");
|
|
14688
|
+
}
|
|
14415
14689
|
this.registryStore = options.registryStore;
|
|
14690
|
+
this.canRestoreRun = options.canRestoreRun;
|
|
14416
14691
|
this.auditPort = options.auditPort;
|
|
14417
14692
|
this.executor = options.executor;
|
|
14418
14693
|
this.runIdFactory = options.runIdFactory ?? generateRunId;
|
|
@@ -14460,6 +14735,23 @@ var DefaultRunSupervisor = class {
|
|
|
14460
14735
|
this.releaseRunAdmission(runId);
|
|
14461
14736
|
throw error;
|
|
14462
14737
|
}
|
|
14738
|
+
return this.attachRun(record, spec, controller);
|
|
14739
|
+
}
|
|
14740
|
+
async restoreRun(spec) {
|
|
14741
|
+
if (!this.registryStore.compareAndSwap) throw new Error("Run restoration requires atomic registry transitions");
|
|
14742
|
+
return this.withRunControlLock(spec.runId, async () => {
|
|
14743
|
+
if (this.handles.has(spec.runId)) throw new RunAlreadyRegisteredError(spec.runId);
|
|
14744
|
+
const record = await this.registryStore.load(spec.runId);
|
|
14745
|
+
if (!record) throw new RunNotFoundError(spec.runId);
|
|
14746
|
+
if (record.status !== "paused" && record.status !== "awaiting_user" || record.conversationId !== spec.conversationId || record.agentSpecId !== spec.agentSpec.id || record.parentRunId !== spec.parentRunId) {
|
|
14747
|
+
throw new RunInteractionConflictError(spec.runId, "restoration does not match persisted run");
|
|
14748
|
+
}
|
|
14749
|
+
this.acquireRunAdmission(spec.runId, spec.concurrencyKey);
|
|
14750
|
+
return this.attachRun(record, spec, new AbortController());
|
|
14751
|
+
});
|
|
14752
|
+
}
|
|
14753
|
+
attachRun(record, spec, controller) {
|
|
14754
|
+
const runId = record.runId;
|
|
14463
14755
|
try {
|
|
14464
14756
|
const handle = new DefaultRunHandle({
|
|
14465
14757
|
runRecord: record,
|
|
@@ -14557,11 +14849,36 @@ var DefaultRunSupervisor = class {
|
|
|
14557
14849
|
registryStore: this.registryStore,
|
|
14558
14850
|
reason,
|
|
14559
14851
|
now: this.now,
|
|
14560
|
-
notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId)
|
|
14852
|
+
notifyTerminal: (outcome) => this.notifyTerminalWaiters(outcome.runId),
|
|
14853
|
+
canRestoreRun: this.canRestoreRun
|
|
14561
14854
|
});
|
|
14562
14855
|
}
|
|
14563
|
-
async pause(
|
|
14564
|
-
|
|
14856
|
+
async pause(runId, reason) {
|
|
14857
|
+
await this.withRunControlLock(runId, () => this.getHandle(runId).pause(reason));
|
|
14858
|
+
}
|
|
14859
|
+
async resumePausedRun(input) {
|
|
14860
|
+
return this.withRunControlLock(input.runId, async () => {
|
|
14861
|
+
const handle = this.getHandle(input.runId);
|
|
14862
|
+
const record = await this.registryStore.load(input.runId);
|
|
14863
|
+
if (!record || record.status !== "paused" || record.pausedAt === void 0 || record.updatedAt !== input.expectedUpdatedAt) {
|
|
14864
|
+
throw new RunInteractionConflictError(input.runId, "run is not settled at the expected pause");
|
|
14865
|
+
}
|
|
14866
|
+
await persistRunTransition(this.registryStore, record, {
|
|
14867
|
+
...record,
|
|
14868
|
+
status: "running",
|
|
14869
|
+
updatedAt: this.now(),
|
|
14870
|
+
pausedAt: void 0,
|
|
14871
|
+
pauseReason: void 0,
|
|
14872
|
+
errorIfAny: void 0,
|
|
14873
|
+
metadata: { ...record.metadata, executionId: input.executionId }
|
|
14874
|
+
});
|
|
14875
|
+
const controller = new AbortController();
|
|
14876
|
+
handle.replaceExecutionAbortController(controller, input.executionId);
|
|
14877
|
+
handle.attachTransportEventBus(input.eventBus);
|
|
14878
|
+
this.controllers.set(input.runId, controller);
|
|
14879
|
+
this.attachAwaitingUserWatcher(input.runId, input.eventBus);
|
|
14880
|
+
return handle;
|
|
14881
|
+
});
|
|
14565
14882
|
}
|
|
14566
14883
|
async claimResume(runId, interaction, eventBus, parentSignal) {
|
|
14567
14884
|
return this.withRunControlLock(runId, async () => {
|
|
@@ -14596,7 +14913,7 @@ var DefaultRunSupervisor = class {
|
|
|
14596
14913
|
throw new RunNotFoundError(runId);
|
|
14597
14914
|
}
|
|
14598
14915
|
const claimId = generateRunResumeClaimId();
|
|
14599
|
-
await this.registryStore
|
|
14916
|
+
await persistRunTransition(this.registryStore, record, {
|
|
14600
14917
|
...record,
|
|
14601
14918
|
updatedAt: this.now(),
|
|
14602
14919
|
metadata: {
|
|
@@ -14684,7 +15001,7 @@ var DefaultRunSupervisor = class {
|
|
|
14684
15001
|
}
|
|
14685
15002
|
const awaitingUserWithoutClaim = { ...awaitingUser };
|
|
14686
15003
|
Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
|
|
14687
|
-
await this.registryStore
|
|
15004
|
+
await persistRunTransition(this.registryStore, record, {
|
|
14688
15005
|
...record,
|
|
14689
15006
|
status: "running",
|
|
14690
15007
|
updatedAt: this.now(),
|
|
@@ -14705,7 +15022,7 @@ var DefaultRunSupervisor = class {
|
|
|
14705
15022
|
});
|
|
14706
15023
|
const executionController = new AbortController();
|
|
14707
15024
|
forwardParentAbortSignal(executionController, parentSignal);
|
|
14708
|
-
handle.replaceExecutionAbortController(executionController);
|
|
15025
|
+
handle.replaceExecutionAbortController(executionController, execution?.executionId ?? (typeof record.metadata?.executionId === "string" ? record.metadata.executionId : void 0));
|
|
14709
15026
|
this.controllers.set(runId, executionController);
|
|
14710
15027
|
return handle;
|
|
14711
15028
|
});
|
|
@@ -14723,7 +15040,7 @@ var DefaultRunSupervisor = class {
|
|
|
14723
15040
|
}
|
|
14724
15041
|
const awaitingUserWithoutClaim = { ...awaitingUser };
|
|
14725
15042
|
Reflect.deleteProperty(awaitingUserWithoutClaim, "resumeClaim");
|
|
14726
|
-
await this.registryStore
|
|
15043
|
+
await persistRunTransition(this.registryStore, record, {
|
|
14727
15044
|
...record,
|
|
14728
15045
|
updatedAt: this.now(),
|
|
14729
15046
|
metadata: {
|