@orion-agents/orion-code 0.4.3 → 0.4.4
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 +6 -0
- package/README.md +4 -4
- package/README.zh-CN.md +4 -4
- package/dist/acp/session-updates.d.ts +4 -3
- package/dist/acp/session-updates.js +23 -2
- package/dist/acp/sessions.js +19 -6
- package/dist/commands/core-command-handlers.js +10 -22
- package/dist/commands/diagnostic-command-handlers.js +48 -52
- package/dist/commands/registry.js +1 -1
- package/dist/commands/target-command.js +49 -6
- package/dist/commands/workflow-commands.js +2 -2
- package/dist/framework/loop-budget-contract.d.ts +1 -12
- package/dist/framework/loop-budget-contract.js +1 -7
- package/dist/framework/loop-progress.d.ts +3 -7
- package/dist/framework/loop-progress.js +7 -23
- package/dist/framework/query.d.ts +12 -24
- package/dist/framework/query.js +146 -287
- package/dist/harness/assembler.js +1 -1
- package/dist/harness/context-harness.d.ts +7 -1
- package/dist/harness/context-harness.js +68 -14
- package/dist/harness/index.d.ts +1 -1
- package/dist/harness/ledger.d.ts +1 -0
- package/dist/harness/ledger.js +12 -1
- package/dist/harness/progress-controller.js +57 -35
- package/dist/harness/state.js +1 -0
- package/dist/harness/stop-controller.d.ts +0 -5
- package/dist/harness/stop-controller.js +11 -31
- package/dist/harness/task-checklist.d.ts +1 -1
- package/dist/harness/task-checklist.js +2 -5
- package/dist/harness/types.d.ts +5 -0
- package/dist/print-ui/event-stream.d.ts +5 -0
- package/dist/print-ui/event-stream.js +22 -5
- package/dist/runtime/agent-loop.d.ts +2 -1
- package/dist/runtime/agent-loop.js +20 -17
- package/dist/runtime/agent-runtime-controller.d.ts +1 -1
- package/dist/runtime/agent-runtime-controller.js +21 -11
- package/dist/runtime/goal-lifecycle-v2.d.ts +6 -4
- package/dist/runtime/goal-lifecycle-v2.js +164 -56
- package/dist/runtime/goal-runtime-coordinator.d.ts +6 -3
- package/dist/runtime/goal-runtime-coordinator.js +90 -36
- package/dist/runtime/goals/presentation.js +3 -1
- package/dist/runtime/goals/types.d.ts +1 -3
- package/dist/runtime/goals/types.js +0 -3
- package/dist/runtime/loop-budget.d.ts +0 -7
- package/dist/runtime/loop-budget.js +8 -54
- package/dist/runtime/orion-runtime-v1.js +55 -14
- package/dist/runtime/product-orion-runtime.js +6 -11
- package/dist/runtime/rsi/evaluation.js +1 -7
- package/dist/runtime/step-snapshot.d.ts +3 -1
- package/dist/runtime/step-snapshot.js +11 -1
- package/dist/runtime/subagent-thread-runtime.js +27 -5
- package/dist/runtime/subagents/production.js +0 -4
- package/dist/runtime/task-context-recovery.js +9 -2
- package/dist/runtime/task-context-service.d.ts +5 -1
- package/dist/runtime/task-context-service.js +37 -8
- package/dist/runtime/thread-admission.d.ts +2 -0
- package/dist/runtime/thread-admission.js +9 -1
- package/dist/runtime/thread-runtime.d.ts +3 -0
- package/dist/runtime/thread-runtime.js +42 -3
- package/dist/runtime/thread-ui-adapter.js +1 -11
- package/dist/runtime/tool-gateway.d.ts +2 -0
- package/dist/runtime/tool-gateway.js +4 -0
- package/dist/runtime/tool-receipt-validator.js +4 -0
- package/dist/runtime/ui-events.d.ts +3 -1
- package/dist/runtime/ui-view-model.js +62 -59
- package/dist/runtime/workspace-verification.d.ts +7 -0
- package/dist/runtime/workspace-verification.js +83 -0
- package/dist/services/config.js +3 -7
- package/dist/services/global-config.d.ts +3 -11
- package/dist/services/global-config.js +36 -26
- package/dist/services/llm.d.ts +2 -0
- package/dist/services/llm.js +13 -0
- package/dist/services/provider-diagnostics.d.ts +1 -0
- package/dist/services/provider-diagnostics.js +8 -2
- package/dist/tools/core/edit-file.js +4 -2
- package/dist/tools/core/write-file.js +5 -3
- package/dist/tools/todo.d.ts +1 -1
- package/dist/tools/todo.js +17 -1
- package/dist/tui-ui/chrome-view-model.js +15 -6
- package/docs/cli-guide.md +53 -40
- package/docs/orion.example.yaml +4 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.PrintEventStreamV1 = void 0;
|
|
4
4
|
const tool_transcript_entry_1 = require("../runtime/tool-transcript-entry");
|
|
5
5
|
const turn_commit_1 = require("../runtime/turn-commit");
|
|
6
|
+
const redaction_1 = require("../services/redaction");
|
|
6
7
|
const EXIT_CODES = {
|
|
7
8
|
completed: 0,
|
|
8
9
|
failed: 1,
|
|
@@ -11,7 +12,9 @@ const EXIT_CODES = {
|
|
|
11
12
|
cancelled: 130,
|
|
12
13
|
};
|
|
13
14
|
function decisionOutcome(decision) {
|
|
14
|
-
const { status, reason, resumable } = decision;
|
|
15
|
+
const { status, disposition, reason, resumable, resources } = decision;
|
|
16
|
+
const llmRequests = resources.llmRequests?.used;
|
|
17
|
+
const toolCalls = resources.toolCalls?.used;
|
|
15
18
|
return {
|
|
16
19
|
status: status === 'stopped' ||
|
|
17
20
|
status === 'blocked' ||
|
|
@@ -19,7 +22,12 @@ function decisionOutcome(decision) {
|
|
|
19
22
|
? 'incomplete'
|
|
20
23
|
: status,
|
|
21
24
|
reasonCode: reason.code,
|
|
22
|
-
|
|
25
|
+
...(status === 'completed' ? {} : { reasonMessage: (0, redaction_1.redactTraceText)(reason.message) }),
|
|
26
|
+
resumable: resumable ??
|
|
27
|
+
(status === 'stopped' || (status === 'blocked' && disposition === 'resume_allowed')),
|
|
28
|
+
...(llmRequests === undefined || toolCalls === undefined
|
|
29
|
+
? {}
|
|
30
|
+
: { metrics: { llmRequests, toolCalls } }),
|
|
23
31
|
};
|
|
24
32
|
}
|
|
25
33
|
/** Versioned shell protocol. Internal receipts, tool arguments and reasoning stay in Runtime. */
|
|
@@ -74,7 +82,16 @@ class PrintEventStreamV1 {
|
|
|
74
82
|
? { status: 'failed', reasonCode: 'event_projection_failed', resumable: false }
|
|
75
83
|
: (this.terminalOutcome ?? fallback);
|
|
76
84
|
const exitCode = EXIT_CODES[outcome.status];
|
|
77
|
-
|
|
85
|
+
const committed = this.committedOutcome;
|
|
86
|
+
const metrics = committed?.metrics;
|
|
87
|
+
const reasonMessage = committed?.reasonCode === outcome.reasonCode ? committed.reasonMessage : undefined;
|
|
88
|
+
this.emit({
|
|
89
|
+
type: 'result',
|
|
90
|
+
...outcome,
|
|
91
|
+
...(metrics ? { metrics } : {}),
|
|
92
|
+
...(reasonMessage === undefined ? {} : { reasonMessage }),
|
|
93
|
+
exitCode,
|
|
94
|
+
});
|
|
78
95
|
this.exitCode = exitCode;
|
|
79
96
|
return exitCode;
|
|
80
97
|
}
|
|
@@ -127,9 +144,9 @@ class PrintEventStreamV1 {
|
|
|
127
144
|
};
|
|
128
145
|
return;
|
|
129
146
|
case 'turn.interrupted':
|
|
130
|
-
this.terminalOutcome = {
|
|
147
|
+
this.terminalOutcome = this.committedOutcome ?? {
|
|
131
148
|
status: 'cancelled',
|
|
132
|
-
reasonCode:
|
|
149
|
+
reasonCode: 'cancelled',
|
|
133
150
|
resumable: true,
|
|
134
151
|
};
|
|
135
152
|
return;
|
|
@@ -51,7 +51,8 @@ export interface AgentLoopOptionsV1 {
|
|
|
51
51
|
readonly streamCallbacks?: StreamCallbacks;
|
|
52
52
|
readonly loopBudget?: Partial<LoopBudget>;
|
|
53
53
|
readonly remainingGoalTokens?: QueryParams['remainingGoalTokens'];
|
|
54
|
-
readonly
|
|
54
|
+
readonly goalDeadlineAt?: QueryParams['goalDeadlineAt'];
|
|
55
|
+
readonly allowToolPressureCompaction?: boolean;
|
|
55
56
|
readonly enableTaskTodos?: boolean;
|
|
56
57
|
readonly resolveGoalTask?: () => {
|
|
57
58
|
readonly goalId: string;
|
|
@@ -137,7 +137,7 @@ class AgentLoopV1 {
|
|
|
137
137
|
threadId: context.threadId,
|
|
138
138
|
turnId: context.turnId,
|
|
139
139
|
requestIndex: stepInput.requestIndex,
|
|
140
|
-
input: context.input,
|
|
140
|
+
input: stepInput.input ?? context.input,
|
|
141
141
|
mode: context.mode,
|
|
142
142
|
messages: stepInput.messages,
|
|
143
143
|
taskContextRevision: this.options.taskContext.revision,
|
|
@@ -179,8 +179,17 @@ class AgentLoopV1 {
|
|
|
179
179
|
},
|
|
180
180
|
loopBudget: this.options.loopBudget,
|
|
181
181
|
remainingGoalTokens: this.options.remainingGoalTokens,
|
|
182
|
-
|
|
182
|
+
goalDeadlineAt: this.options.goalDeadlineAt,
|
|
183
|
+
allowToolPressureCompaction: this.options.allowToolPressureCompaction === true &&
|
|
183
184
|
(context.mode === 'build' || context.mode === 'auto'),
|
|
185
|
+
takePendingSteering: closeIfEmpty => {
|
|
186
|
+
const inputs = context.takePendingSteering?.(closeIfEmpty) ?? [];
|
|
187
|
+
for (const input of inputs) {
|
|
188
|
+
taskContextCompletion = undefined;
|
|
189
|
+
this.options.taskContext.observeUserInput(input, goal?.goalId);
|
|
190
|
+
}
|
|
191
|
+
return inputs;
|
|
192
|
+
},
|
|
184
193
|
onContextUsage: this.options.onContextUsage,
|
|
185
194
|
compactCoordinator: this.options.compactCoordinator,
|
|
186
195
|
})) {
|
|
@@ -189,29 +198,23 @@ class AgentLoopV1 {
|
|
|
189
198
|
finishReasoning();
|
|
190
199
|
completeAssistant(assistantContent);
|
|
191
200
|
activeStep = undefined;
|
|
201
|
+
taskContextCompletion = undefined;
|
|
192
202
|
break;
|
|
193
203
|
case 'assistant_tool_calls':
|
|
194
204
|
case 'message':
|
|
195
205
|
finishReasoning();
|
|
196
206
|
completeAssistant(event.content);
|
|
197
207
|
break;
|
|
198
|
-
case '
|
|
199
|
-
const content = event.
|
|
200
|
-
? 'Observed new tool evidence. Continuing the task.'
|
|
201
|
-
: 'No new tool evidence yet. Trying a different step before pausing.';
|
|
202
|
-
const item = context.startItem({ kind: 'reasoning', name: 'loop:progress-checkpoint' });
|
|
203
|
-
context.completeItem(item, { content, summary: content });
|
|
204
|
-
break;
|
|
205
|
-
}
|
|
206
|
-
case 'warning':
|
|
207
|
-
case 'strategy_exhausted': {
|
|
208
|
-
const content = event.type === 'warning' ? event.message : event.suggestion;
|
|
208
|
+
case 'warning': {
|
|
209
|
+
const content = event.message;
|
|
209
210
|
const item = context.startItem({ kind: 'reasoning', stepId: activeStep?.stepId });
|
|
210
211
|
context.completeItem(item, { content, summary: compactSummary(content) });
|
|
211
212
|
break;
|
|
212
213
|
}
|
|
213
214
|
case 'complete':
|
|
214
|
-
if (executionChecklist &&
|
|
215
|
+
if (executionChecklist &&
|
|
216
|
+
(event.stats?.finishReason === 'completion_gate' ||
|
|
217
|
+
event.stats?.stopDecision?.reason.code === 'task_step_blocked')) {
|
|
215
218
|
const item = context.startItem({ kind: 'message', role: 'system' });
|
|
216
219
|
context.completeItem(item, {
|
|
217
220
|
content: event.content,
|
|
@@ -260,10 +263,10 @@ class AgentLoopV1 {
|
|
|
260
263
|
? { status: 'interrupted', reason: abortReason(context.abortSignal) }
|
|
261
264
|
: { status: 'failed', error: 'AgentLoop ended without a terminal Query event' };
|
|
262
265
|
}
|
|
266
|
+
// The completion audit can precede the final visible answer or be bypassed
|
|
267
|
+
// by a terminal provider/tool outcome. Account for the entire committed turn.
|
|
268
|
+
this.options.taskContext.recordProgress(progressAtAdmission);
|
|
263
269
|
if (completeEvent.stats?.finishReason === 'budget_exceeded') {
|
|
264
|
-
// A completion gate may have run before the last tools, or not at all.
|
|
265
|
-
// Record progress for the whole turn without running another completion audit.
|
|
266
|
-
this.options.taskContext.recordProgress(progressAtAdmission);
|
|
267
270
|
taskContextCompletion = undefined;
|
|
268
271
|
}
|
|
269
272
|
const commitContent = {
|
|
@@ -79,6 +79,7 @@ export declare class AgentRuntimeController {
|
|
|
79
79
|
private readonly goalControlRuns;
|
|
80
80
|
private activeGoalRuntimeTransitions;
|
|
81
81
|
private goalRuntimeActive;
|
|
82
|
+
private goalEventRevision;
|
|
82
83
|
private settingsBoundarySynchronizations;
|
|
83
84
|
private reportedInvalidConfigRevision?;
|
|
84
85
|
private stopping;
|
|
@@ -157,7 +158,6 @@ export declare class AgentRuntimeController {
|
|
|
157
158
|
requestToolPermission(request: AgentRuntimeToolPermissionRequest): Promise<boolean>;
|
|
158
159
|
private startGoalControl;
|
|
159
160
|
private renderGoalControl;
|
|
160
|
-
private observeGoalControlResult;
|
|
161
161
|
private observeGoalRuntimeEvent;
|
|
162
162
|
private recordPermissionDecision;
|
|
163
163
|
private rejectPendingPermissions;
|
|
@@ -61,6 +61,7 @@ class AgentRuntimeController {
|
|
|
61
61
|
this.goalControlRuns = new Set();
|
|
62
62
|
this.activeGoalRuntimeTransitions = 0;
|
|
63
63
|
this.goalRuntimeActive = false;
|
|
64
|
+
this.goalEventRevision = 0;
|
|
64
65
|
this.settingsBoundarySynchronizations = 0;
|
|
65
66
|
this.stopping = false;
|
|
66
67
|
this.nextPermissionRequestId = 1;
|
|
@@ -1072,8 +1073,9 @@ class AgentRuntimeController {
|
|
|
1072
1073
|
return { type: 'command_handled' };
|
|
1073
1074
|
}
|
|
1074
1075
|
const startsGoal = goalControl.action === 'create' || goalControl.action === 'resume';
|
|
1076
|
+
const requiresIdle = startsGoal || goalControl.action === 'budget';
|
|
1075
1077
|
if ((this.hasActiveTurn() || this.goalControlRuns.size > 0 || this.goalRuntimeActive) &&
|
|
1076
|
-
|
|
1078
|
+
requiresIdle) {
|
|
1077
1079
|
const message = `/goal ${goalControl.action} is unavailable while Goal work is running; use /goal pause or /goal clear first.`;
|
|
1078
1080
|
this.emitStatus(message);
|
|
1079
1081
|
return { type: 'command_ignored' };
|
|
@@ -1090,9 +1092,10 @@ class AgentRuntimeController {
|
|
|
1090
1092
|
.then(async () => {
|
|
1091
1093
|
if (interruptedRun)
|
|
1092
1094
|
await interruptedRun.catch(() => undefined);
|
|
1093
|
-
if (
|
|
1095
|
+
if (requiresIdle && !(await this.synchronizeSettingsAtLogicalBoundary()))
|
|
1094
1096
|
return;
|
|
1095
1097
|
this.activeGoalRuntimeTransitions += 1;
|
|
1098
|
+
const goalEventRevision = this.goalEventRevision;
|
|
1096
1099
|
let result;
|
|
1097
1100
|
try {
|
|
1098
1101
|
result = await this.runner.controlGoal(goalControl);
|
|
@@ -1100,7 +1103,11 @@ class AgentRuntimeController {
|
|
|
1100
1103
|
finally {
|
|
1101
1104
|
this.activeGoalRuntimeTransitions -= 1;
|
|
1102
1105
|
}
|
|
1103
|
-
this.
|
|
1106
|
+
if (goalEventRevision === this.goalEventRevision &&
|
|
1107
|
+
result.accepted &&
|
|
1108
|
+
result.action !== 'status') {
|
|
1109
|
+
this.goalRuntimeActive = result.state?.status === 'active' || result.scheduleContinuation;
|
|
1110
|
+
}
|
|
1104
1111
|
this.renderGoalControl(result);
|
|
1105
1112
|
// Pause/clear must remain available while Goal work is active. Reconcile
|
|
1106
1113
|
// pending runtime-sensitive edits only after that work has stopped.
|
|
@@ -1128,17 +1135,13 @@ class AgentRuntimeController {
|
|
|
1128
1135
|
});
|
|
1129
1136
|
this.emitStatus(summary);
|
|
1130
1137
|
}
|
|
1131
|
-
observeGoalControlResult(result) {
|
|
1132
|
-
if (!result.accepted)
|
|
1133
|
-
return;
|
|
1134
|
-
this.goalRuntimeActive =
|
|
1135
|
-
(result.action === 'create' || result.action === 'resume') && result.scheduleContinuation;
|
|
1136
|
-
}
|
|
1137
1138
|
observeGoalRuntimeEvent(event) {
|
|
1138
1139
|
if (event.type === 'goal_updated') {
|
|
1140
|
+
this.goalEventRevision += 1;
|
|
1139
1141
|
this.goalRuntimeActive = event.goal.status === 'active';
|
|
1140
1142
|
}
|
|
1141
1143
|
else if (event.type === 'goal_cleared' || event.type === 'goal_completed') {
|
|
1144
|
+
this.goalEventRevision += 1;
|
|
1142
1145
|
this.goalRuntimeActive = false;
|
|
1143
1146
|
}
|
|
1144
1147
|
}
|
|
@@ -1225,8 +1228,12 @@ function formatGoalRuntimeStatus(result) {
|
|
|
1225
1228
|
const objective = state.objective.length > 80 ? `${state.objective.slice(0, 77)}...` : state.objective;
|
|
1226
1229
|
return [
|
|
1227
1230
|
result.message,
|
|
1228
|
-
`Goal: [${state.status}] ${objective}`,
|
|
1229
|
-
`Progress: ${state.continuationCount} turns · ${state.tokensUsed}/${state.budget.maxTokens} tokens · ${state.elapsedMs}/${state.budget.maxElapsedMs}ms`,
|
|
1231
|
+
`Goal: [${state.status}] ${objective} (${state.goalId})`,
|
|
1232
|
+
`Progress: ${state.continuationCount} turns · ${state.tokensUsed}/${state.budget.maxTokens ?? 'unlimited'} tokens · ${state.elapsedMs}/${state.budget.maxElapsedMs ?? 'unlimited'} ms`,
|
|
1233
|
+
...(state.lastStopDecision ? [state.lastStopDecision.reason.message] : []),
|
|
1234
|
+
...(state.lastStopDecision?.evidenceRefs?.length
|
|
1235
|
+
? [`Evidence: ${state.lastStopDecision.evidenceRefs.join(', ')}`]
|
|
1236
|
+
: []),
|
|
1230
1237
|
].join('\n');
|
|
1231
1238
|
}
|
|
1232
1239
|
function normalizeGoalRuntimeControl(control) {
|
|
@@ -1237,6 +1244,9 @@ function normalizeGoalRuntimeControl(control) {
|
|
|
1237
1244
|
...(control.budget ? { budget: control.budget } : {}),
|
|
1238
1245
|
};
|
|
1239
1246
|
}
|
|
1247
|
+
if (control.action === 'budget') {
|
|
1248
|
+
return { action: 'budget', budget: { ...control.budget } };
|
|
1249
|
+
}
|
|
1240
1250
|
return { action: control.action };
|
|
1241
1251
|
}
|
|
1242
1252
|
function commandIdentity(command, success) {
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { type StopDecision } from '../framework/stop-decision';
|
|
2
2
|
import type { TaskPlanStop } from '../harness/types';
|
|
3
3
|
import type { TaskContextCompletionDecisionV1 } from './task-context-service';
|
|
4
|
-
export type GoalLifecycleStatusV2 = 'active' | 'paused' | 'completed' | 'failed';
|
|
4
|
+
export type GoalLifecycleStatusV2 = 'active' | 'paused' | 'blocked' | 'usage_limited' | 'budget_limited' | 'completed' | 'failed';
|
|
5
5
|
export interface GoalLifecycleBudgetV2 {
|
|
6
|
-
readonly maxTokens
|
|
7
|
-
readonly maxElapsedMs
|
|
6
|
+
readonly maxTokens?: number;
|
|
7
|
+
readonly maxElapsedMs?: number;
|
|
8
8
|
}
|
|
9
9
|
export interface GoalLifecycleStateV2 {
|
|
10
10
|
readonly version: 2;
|
|
@@ -35,7 +35,6 @@ export interface GoalTurnObservationV2 {
|
|
|
35
35
|
readonly continuationMode?: 'agent' | 'manual';
|
|
36
36
|
/** Present only at a per-turn resource boundary; these refs must be verified by TaskContext. */
|
|
37
37
|
readonly checkpoint?: {
|
|
38
|
-
readonly unfinishedPlan: boolean;
|
|
39
38
|
readonly verificationRefs: readonly string[];
|
|
40
39
|
};
|
|
41
40
|
}
|
|
@@ -51,6 +50,7 @@ export interface GoalLifecycleOptionsV2 {
|
|
|
51
50
|
readonly clock?: () => number;
|
|
52
51
|
readonly state?: GoalLifecycleStateV2;
|
|
53
52
|
}
|
|
53
|
+
export declare function isGoalBudgetStopReason(code: string | undefined): boolean;
|
|
54
54
|
export declare function isTaskPlanStopDecision(decision: StopDecision | undefined): decision is StopDecision & {
|
|
55
55
|
reason: TaskPlanStop;
|
|
56
56
|
};
|
|
@@ -67,7 +67,9 @@ export declare class GoalLifecycleServiceV2 {
|
|
|
67
67
|
finalizeTurn(observation: GoalTurnObservationV2): GoalTurnResolutionV2;
|
|
68
68
|
pause(message?: string, reason?: string): GoalLifecycleStateV2;
|
|
69
69
|
resume(): GoalLifecycleStateV2;
|
|
70
|
+
updateBudget(update: GoalLifecycleBudgetV2, ceilings: GoalLifecycleBudgetV2): GoalLifecycleStateV2;
|
|
70
71
|
private transition;
|
|
71
72
|
}
|
|
72
73
|
export declare function assertGoalLifecycleStateV2(state: GoalLifecycleStateV2): void;
|
|
74
|
+
export declare function validateGoalBudget(budget: GoalLifecycleBudgetV2): void;
|
|
73
75
|
//# sourceMappingURL=goal-lifecycle-v2.d.ts.map
|
|
@@ -1,14 +1,21 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.GoalLifecycleServiceV2 = void 0;
|
|
4
|
+
exports.isGoalBudgetStopReason = isGoalBudgetStopReason;
|
|
4
5
|
exports.isTaskPlanStopDecision = isTaskPlanStopDecision;
|
|
5
6
|
exports.assertGoalLifecycleStateV2 = assertGoalLifecycleStateV2;
|
|
7
|
+
exports.validateGoalBudget = validateGoalBudget;
|
|
6
8
|
const crypto_1 = require("crypto");
|
|
7
9
|
const stop_decision_1 = require("../framework/stop-decision");
|
|
8
10
|
const canonical_1 = require("./protocol/canonical");
|
|
9
11
|
const runtime_protocol_v1_1 = require("./protocol/runtime-protocol-v1");
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
+
const GOAL_BUDGET_RESOURCES = [
|
|
13
|
+
{ key: 'maxTokens', used: 'tokensUsed', flag: '--max-tokens', unit: 'tokens' },
|
|
14
|
+
{ key: 'maxElapsedMs', used: 'elapsedMs', flag: '--max-elapsed-ms', unit: 'ms' },
|
|
15
|
+
];
|
|
16
|
+
function isGoalBudgetStopReason(code) {
|
|
17
|
+
return code === 'goal_budget' || code === 'goal_token_budget' || code === 'goal_time_budget';
|
|
18
|
+
}
|
|
12
19
|
function isTaskPlanStopDecision(decision) {
|
|
13
20
|
return (decision?.scope === 'request' &&
|
|
14
21
|
(decision.status === 'stopped' || decision.status === 'blocked') &&
|
|
@@ -24,11 +31,20 @@ class GoalLifecycleServiceV2 {
|
|
|
24
31
|
this.clock = options.clock ?? Date.now;
|
|
25
32
|
if (options.state) {
|
|
26
33
|
assertGoalLifecycleStateV2(options.state);
|
|
27
|
-
|
|
34
|
+
const restored = options.state;
|
|
35
|
+
const decision = restored.lastStopDecision;
|
|
36
|
+
this.stateValue =
|
|
37
|
+
restored.status === 'paused' && decision && isGoalBudgetStopReason(decision.reason.code)
|
|
38
|
+
? withDigest({
|
|
39
|
+
...withoutDigest(restored),
|
|
40
|
+
status: 'budget_limited',
|
|
41
|
+
lastStopDecision: goalBudgetDecision(restored, decision.reason.code),
|
|
42
|
+
})
|
|
43
|
+
: deepFreeze(structuredClone(restored));
|
|
28
44
|
return;
|
|
29
45
|
}
|
|
30
46
|
const objective = options.objective.trim();
|
|
31
|
-
|
|
47
|
+
validateGoalBudget(options.budget);
|
|
32
48
|
if (!objective)
|
|
33
49
|
throw new Error('Goal objective must not be empty');
|
|
34
50
|
const now = this.clock();
|
|
@@ -66,10 +82,20 @@ class GoalLifecycleServiceV2 {
|
|
|
66
82
|
const continuationCount = this.stateValue.continuationCount + 1;
|
|
67
83
|
const noProgressCount = observation.madeProgress ? 0 : this.stateValue.noProgressCount + 1;
|
|
68
84
|
const blockedCount = observation.blocked ? this.stateValue.blockedCount + 1 : 0;
|
|
85
|
+
const requestReason = observation.requestDecision?.reason;
|
|
86
|
+
const usage = { tokensUsed, elapsedMs, budget: this.stateValue.budget };
|
|
87
|
+
const exhausted = exhaustedGoalBudget(usage);
|
|
88
|
+
const budgetCode = isGoalBudgetStopReason(requestReason?.code)
|
|
89
|
+
? requestReason?.code
|
|
90
|
+
: exhausted?.key === 'maxTokens'
|
|
91
|
+
? 'goal_token_budget'
|
|
92
|
+
: exhausted
|
|
93
|
+
? 'goal_time_budget'
|
|
94
|
+
: undefined;
|
|
69
95
|
const resourceSnapshot = {
|
|
96
|
+
...observation.requestDecision?.resources,
|
|
70
97
|
turns: { used: continuationCount },
|
|
71
|
-
|
|
72
|
-
elapsedMs: { used: elapsedMs, limit: this.stateValue.budget.maxElapsedMs },
|
|
98
|
+
...goalResources(usage),
|
|
73
99
|
};
|
|
74
100
|
let status = 'active';
|
|
75
101
|
let decision;
|
|
@@ -84,21 +110,25 @@ class GoalLifecycleServiceV2 {
|
|
|
84
110
|
else if (observation.requestDecision?.status === 'failed' &&
|
|
85
111
|
(observation.requestDecision.disposition === 'resume_allowed' ||
|
|
86
112
|
isProviderFailure(observation.requestDecision))) {
|
|
87
|
-
|
|
88
|
-
|
|
113
|
+
const quota = observation.requestDecision.reason.code === 'provider_quota_or_credit_exhausted';
|
|
114
|
+
status = quota ? 'usage_limited' : 'paused';
|
|
115
|
+
decision = goalDecision('failed', 'pause_scope', quota || observation.requestDecision.disposition === 'resume_allowed'
|
|
89
116
|
? observation.requestDecision.reason.code
|
|
90
117
|
: 'provider_failure', observation.requestDecision.reason.message, resourceSnapshot);
|
|
91
118
|
}
|
|
92
|
-
else if (
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
decision = goalDecision('stopped', 'pause_scope', 'goal_budget', 'Goal budget reached. The saved budget cannot be reset by resume; inspect the receipts, then clear and explicitly create a new Goal with an appropriate budget.', resourceSnapshot);
|
|
119
|
+
else if (budgetCode) {
|
|
120
|
+
status = 'budget_limited';
|
|
121
|
+
decision = goalBudgetDecision(usage, budgetCode, resourceSnapshot);
|
|
96
122
|
}
|
|
97
123
|
else if (isTaskPlanStopDecision(observation.requestDecision)) {
|
|
98
124
|
const { code, message } = observation.requestDecision.reason;
|
|
99
|
-
status = 'paused';
|
|
125
|
+
status = code === 'task_step_blocked' ? 'blocked' : 'paused';
|
|
100
126
|
decision = goalDecision(code === 'task_step_blocked' ? 'blocked' : 'stopped', 'pause_scope', code, message, resourceSnapshot);
|
|
101
127
|
}
|
|
128
|
+
else if (observation.blocked) {
|
|
129
|
+
status = 'blocked';
|
|
130
|
+
decision = goalDecision('blocked', 'pause_scope', requestReason?.code ?? 'blocked', observation.blocked, resourceSnapshot);
|
|
131
|
+
}
|
|
102
132
|
else if (hasVerifiedGoalCompletion(observation.taskContextCompletion)) {
|
|
103
133
|
status = 'completed';
|
|
104
134
|
decision = (0, stop_decision_1.createStopDecision)({
|
|
@@ -122,30 +152,18 @@ class GoalLifecycleServiceV2 {
|
|
|
122
152
|
resources: resourceSnapshot,
|
|
123
153
|
});
|
|
124
154
|
}
|
|
125
|
-
else if (blockedCount >= MAX_BLOCKED_CONTINUATIONS) {
|
|
126
|
-
status = 'paused';
|
|
127
|
-
decision = goalDecision('blocked', 'pause_scope', 'blocked', observation.blocked ?? 'Goal remained blocked.', resourceSnapshot);
|
|
128
|
-
}
|
|
129
|
-
else if (noProgressCount >= MAX_NO_PROGRESS_TURNS) {
|
|
130
|
-
status = 'paused';
|
|
131
|
-
decision = goalDecision('stopped', 'pause_scope', 'no_progress', `Goal made no observable progress for ${MAX_NO_PROGRESS_TURNS} turns.`, resourceSnapshot);
|
|
132
|
-
}
|
|
133
155
|
else if (observation.continuationMode === 'manual') {
|
|
134
156
|
status = 'paused';
|
|
135
157
|
decision = goalDecision('stopped', 'pause_scope', 'goal_manual_continuation', 'Goal checkpoint saved. Manual continuation is enabled; use /goal resume for the next turn.', resourceSnapshot);
|
|
136
158
|
}
|
|
137
159
|
else if (observation.checkpoint) {
|
|
138
|
-
const verified = observation.checkpoint.unfinishedPlan && observation.checkpoint.verificationRefs.length > 0;
|
|
139
|
-
status = verified ? 'active' : 'paused';
|
|
140
160
|
decision = (0, stop_decision_1.createStopDecision)({
|
|
141
161
|
scope: 'goal',
|
|
142
162
|
status: 'stopped',
|
|
143
|
-
disposition:
|
|
163
|
+
disposition: 'resume_allowed',
|
|
144
164
|
reason: {
|
|
145
|
-
code:
|
|
146
|
-
message:
|
|
147
|
-
? 'Goal checkpoint saved with fresh successful verification and an unfinished plan; continuing automatically.'
|
|
148
|
-
: 'Goal checkpoint saved. Automatic continuation requires an unfinished plan and fresh successful verification from this turn; inspect the evidence, then use /goal resume.',
|
|
165
|
+
code: 'goal_checkpoint',
|
|
166
|
+
message: 'Goal checkpoint saved; continuing from the durable task state.',
|
|
149
167
|
},
|
|
150
168
|
evidence: observation.checkpoint.verificationRefs.map(ref => ({
|
|
151
169
|
kind: 'verification',
|
|
@@ -153,15 +171,9 @@ class GoalLifecycleServiceV2 {
|
|
|
153
171
|
detail: ref,
|
|
154
172
|
})),
|
|
155
173
|
evidenceRefs: [...observation.checkpoint.verificationRefs],
|
|
156
|
-
nextActions:
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
{
|
|
160
|
-
kind: 'resume',
|
|
161
|
-
label: 'Resume after inspecting the checkpoint.',
|
|
162
|
-
command: '/goal resume',
|
|
163
|
-
},
|
|
164
|
-
],
|
|
174
|
+
nextActions: [
|
|
175
|
+
{ kind: 'inspect', label: 'Inspect the durable checkpoint and ongoing Goal.' },
|
|
176
|
+
],
|
|
165
177
|
resources: resourceSnapshot,
|
|
166
178
|
});
|
|
167
179
|
}
|
|
@@ -193,11 +205,18 @@ class GoalLifecycleServiceV2 {
|
|
|
193
205
|
return this.transition('paused', reason, message);
|
|
194
206
|
}
|
|
195
207
|
resume() {
|
|
196
|
-
if (this.stateValue.status
|
|
208
|
+
if (!['paused', 'blocked', 'usage_limited'].includes(this.stateValue.status))
|
|
197
209
|
return this.state;
|
|
198
|
-
|
|
199
|
-
|
|
210
|
+
const exhausted = exhaustedGoalBudget(this.stateValue);
|
|
211
|
+
if (exhausted) {
|
|
212
|
+
this.stateValue = withDigest({
|
|
213
|
+
...withoutDigest(this.stateValue),
|
|
214
|
+
status: 'budget_limited',
|
|
215
|
+
lastStopDecision: goalBudgetDecision(this.stateValue),
|
|
216
|
+
updatedAt: Math.max(this.stateValue.updatedAt + 1, this.clock()),
|
|
217
|
+
});
|
|
200
218
|
return this.state;
|
|
219
|
+
}
|
|
201
220
|
const content = {
|
|
202
221
|
...withoutDigest(this.stateValue),
|
|
203
222
|
status: 'active',
|
|
@@ -210,11 +229,50 @@ class GoalLifecycleServiceV2 {
|
|
|
210
229
|
this.stateValue = withDigest(content);
|
|
211
230
|
return this.state;
|
|
212
231
|
}
|
|
232
|
+
updateBudget(update, ceilings) {
|
|
233
|
+
const state = this.stateValue;
|
|
234
|
+
if (!['paused', 'blocked', 'usage_limited', 'budget_limited'].includes(state.status)) {
|
|
235
|
+
throw new Error(`Goal budget cannot change while the Goal is ${state.status}.`);
|
|
236
|
+
}
|
|
237
|
+
validateGoalBudget(update);
|
|
238
|
+
if (update.maxTokens === undefined && update.maxElapsedMs === undefined) {
|
|
239
|
+
throw new Error('Specify a new total token or elapsed-time limit.');
|
|
240
|
+
}
|
|
241
|
+
for (const { key, used, flag, unit } of GOAL_BUDGET_RESOURCES) {
|
|
242
|
+
const next = update[key];
|
|
243
|
+
if (next === undefined)
|
|
244
|
+
continue;
|
|
245
|
+
const ceiling = ceilings[key];
|
|
246
|
+
if (ceiling !== undefined && next > ceiling) {
|
|
247
|
+
throw new Error(`${flag} exceeds the configured ceiling of ${ceiling} ${unit}.`);
|
|
248
|
+
}
|
|
249
|
+
if (next <= Math.max(state.budget[key] ?? 0, state[used])) {
|
|
250
|
+
throw new Error(`${flag} must exceed the saved limit and the ${state[used]} ${unit} already used.`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const budget = { ...state.budget, ...update };
|
|
254
|
+
const usage = { ...state, budget };
|
|
255
|
+
const exhausted = exhaustedGoalBudget(usage);
|
|
256
|
+
const status = state.status === 'budget_limited' && !exhausted ? 'paused' : state.status;
|
|
257
|
+
const resources = { turns: { used: state.continuationCount }, ...goalResources(usage) };
|
|
258
|
+
const decision = status === 'budget_limited'
|
|
259
|
+
? goalBudgetDecision(usage, undefined, resources)
|
|
260
|
+
: state.status === 'budget_limited'
|
|
261
|
+
? goalDecision('stopped', 'pause_scope', 'goal_budget_updated', 'Goal budget updated. Use /goal resume to continue from the saved checkpoint.', resources)
|
|
262
|
+
: state.lastStopDecision && (0, stop_decision_1.createStopDecision)({ ...state.lastStopDecision, resources });
|
|
263
|
+
this.stateValue = withDigest({
|
|
264
|
+
...withoutDigest(state),
|
|
265
|
+
budget,
|
|
266
|
+
status,
|
|
267
|
+
...(decision ? { lastStopDecision: decision } : {}),
|
|
268
|
+
updatedAt: Math.max(state.updatedAt + 1, this.clock()),
|
|
269
|
+
});
|
|
270
|
+
return this.state;
|
|
271
|
+
}
|
|
213
272
|
transition(status, code, message) {
|
|
214
273
|
const decision = goalDecision(status === 'failed' ? 'failed' : 'stopped', 'pause_scope', code, message, {
|
|
215
274
|
turns: { used: this.stateValue.continuationCount },
|
|
216
|
-
|
|
217
|
-
elapsedMs: { used: this.stateValue.elapsedMs, limit: this.stateValue.budget.maxElapsedMs },
|
|
275
|
+
...goalResources(this.stateValue),
|
|
218
276
|
});
|
|
219
277
|
this.stateValue = withDigest({
|
|
220
278
|
...withoutDigest(this.stateValue),
|
|
@@ -242,7 +300,7 @@ function assertGoalLifecycleStateV2(state) {
|
|
|
242
300
|
(0, canonical_1.digestRuntimeValue)(content) !== digest) {
|
|
243
301
|
throw new Error('GoalLifecycleStateV2 failed integrity validation');
|
|
244
302
|
}
|
|
245
|
-
|
|
303
|
+
validateGoalBudget(state.budget);
|
|
246
304
|
for (const value of [
|
|
247
305
|
state.generation,
|
|
248
306
|
state.continuationCount,
|
|
@@ -256,6 +314,58 @@ function assertGoalLifecycleStateV2(state) {
|
|
|
256
314
|
}
|
|
257
315
|
}
|
|
258
316
|
}
|
|
317
|
+
function exhaustedGoalBudget(usage) {
|
|
318
|
+
return GOAL_BUDGET_RESOURCES.find(({ key, used }) => {
|
|
319
|
+
const limit = usage.budget[key];
|
|
320
|
+
return limit !== undefined && usage[used] >= limit;
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
function goalResources({ budget, tokensUsed, elapsedMs }) {
|
|
324
|
+
return {
|
|
325
|
+
tokens: {
|
|
326
|
+
used: tokensUsed,
|
|
327
|
+
...(budget.maxTokens === undefined ? {} : { limit: budget.maxTokens }),
|
|
328
|
+
},
|
|
329
|
+
elapsedMs: {
|
|
330
|
+
used: elapsedMs,
|
|
331
|
+
...(budget.maxElapsedMs === undefined ? {} : { limit: budget.maxElapsedMs }),
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
function goalBudgetDecision(usage, code, resources = goalResources(usage)) {
|
|
336
|
+
const exhausted = GOAL_BUDGET_RESOURCES.filter(({ key, used }) => {
|
|
337
|
+
const limit = usage.budget[key];
|
|
338
|
+
return limit !== undefined && usage[used] >= limit;
|
|
339
|
+
});
|
|
340
|
+
const affected = exhausted.length
|
|
341
|
+
? exhausted
|
|
342
|
+
: GOAL_BUDGET_RESOURCES.filter(({ key }) => code === 'goal_token_budget' ? key === 'maxTokens' : key === 'maxElapsedMs');
|
|
343
|
+
const command = `/goal budget ${affected.map(({ flag }) => `${flag} <new-total>`).join(' ')}`;
|
|
344
|
+
const limits = affected
|
|
345
|
+
.map(({ key, used, unit }) => `${usage[used]}/${usage.budget[key] ?? 'unlimited'} ${unit}`)
|
|
346
|
+
.join(', ');
|
|
347
|
+
const message = `Goal budget reached (${limits}). Progress saved. Use ${command}, then /goal resume.`;
|
|
348
|
+
return (0, stop_decision_1.createStopDecision)({
|
|
349
|
+
scope: 'goal',
|
|
350
|
+
status: 'stopped',
|
|
351
|
+
disposition: 'pause_scope',
|
|
352
|
+
reason: {
|
|
353
|
+
code: code ?? (affected[0]?.key === 'maxTokens' ? 'goal_token_budget' : 'goal_time_budget'),
|
|
354
|
+
message,
|
|
355
|
+
},
|
|
356
|
+
evidence: [{ kind: 'resource_limit', source: 'goal-lifecycle-v2', detail: limits }],
|
|
357
|
+
nextActions: [
|
|
358
|
+
{
|
|
359
|
+
kind: 'inspect',
|
|
360
|
+
label: 'Inspect the saved Goal usage and checkpoint.',
|
|
361
|
+
command: '/goal status',
|
|
362
|
+
},
|
|
363
|
+
{ kind: 'raise_budget', label: 'Authorize a higher total, then resume.', command },
|
|
364
|
+
],
|
|
365
|
+
resumable: false,
|
|
366
|
+
resources,
|
|
367
|
+
});
|
|
368
|
+
}
|
|
259
369
|
function goalDecision(status, disposition, code, message, resources) {
|
|
260
370
|
return (0, stop_decision_1.createStopDecision)({
|
|
261
371
|
scope: 'goal',
|
|
@@ -263,14 +373,8 @@ function goalDecision(status, disposition, code, message, resources) {
|
|
|
263
373
|
disposition,
|
|
264
374
|
reason: { code, message },
|
|
265
375
|
evidence: [{ kind: 'runtime', source: 'goal-lifecycle-v2', detail: message }],
|
|
266
|
-
nextActions: code === '
|
|
267
|
-
? [
|
|
268
|
-
{ kind: 'inspect', label: 'Inspect the saved Goal usage and receipts.' },
|
|
269
|
-
{
|
|
270
|
-
kind: 'change_input',
|
|
271
|
-
label: 'Explicitly clear and create a new Goal after configuring its total budget.',
|
|
272
|
-
},
|
|
273
|
-
]
|
|
376
|
+
nextActions: code === 'persistence_error'
|
|
377
|
+
? [{ kind: 'inspect', label: 'Inspect the saved Goal state.' }]
|
|
274
378
|
: [
|
|
275
379
|
{ kind: 'inspect', label: 'Inspect the durable Goal state.' },
|
|
276
380
|
{
|
|
@@ -279,6 +383,7 @@ function goalDecision(status, disposition, code, message, resources) {
|
|
|
279
383
|
command: '/goal resume',
|
|
280
384
|
},
|
|
281
385
|
],
|
|
386
|
+
resumable: code !== 'persistence_error',
|
|
282
387
|
resources,
|
|
283
388
|
});
|
|
284
389
|
}
|
|
@@ -286,11 +391,14 @@ function isProviderFailure(decision) {
|
|
|
286
391
|
return (decision.evidence.some(item => item.kind === 'provider') ||
|
|
287
392
|
/provider|network|auth|rate.?limit/iu.test(decision.reason.code));
|
|
288
393
|
}
|
|
289
|
-
function
|
|
290
|
-
if (!
|
|
291
|
-
budget
|
|
292
|
-
|
|
293
|
-
|
|
394
|
+
function validateGoalBudget(budget) {
|
|
395
|
+
if (!budget ||
|
|
396
|
+
typeof budget !== 'object' ||
|
|
397
|
+
Array.isArray(budget) ||
|
|
398
|
+
GOAL_BUDGET_RESOURCES.some(({ key }) => {
|
|
399
|
+
const value = budget[key];
|
|
400
|
+
return value !== undefined && (!Number.isSafeInteger(value) || value <= 0);
|
|
401
|
+
})) {
|
|
294
402
|
throw new Error('Goal budget values must be positive safe integers');
|
|
295
403
|
}
|
|
296
404
|
}
|