@saturn-universe/runtime 0.0.0-stage → 0.1.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/LICENSE +661 -0
- package/dist/agent-loop.d.ts +48 -0
- package/dist/agent-loop.js +1072 -0
- package/dist/command-dependencies.d.ts +14 -0
- package/dist/command-dependencies.js +1 -0
- package/dist/command-handler.d.ts +10 -0
- package/dist/command-handler.js +269 -0
- package/dist/compaction.d.ts +81 -0
- package/dist/compaction.js +444 -0
- package/dist/completion-policy.d.ts +30 -0
- package/dist/completion-policy.js +502 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +8 -0
- package/dist/journal.d.ts +28 -0
- package/dist/journal.js +473 -0
- package/dist/recovery.d.ts +19 -0
- package/dist/recovery.js +103 -0
- package/dist/run-loop.d.ts +49 -0
- package/dist/run-loop.js +739 -0
- package/dist/search-loop.d.ts +57 -0
- package/dist/search-loop.js +905 -0
- package/dist/team-loop.d.ts +46 -0
- package/dist/team-loop.js +936 -0
- package/package.json +15 -3
- package/README.md +0 -3
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
import { isLimited, settledModelTokens } from '@saturn-universe/core';
|
|
2
|
+
const writeToolNames = new Set(['edit_file', 'write_file', 'apply_patch']);
|
|
3
|
+
const verificationToolNames = new Set([
|
|
4
|
+
'shell',
|
|
5
|
+
'run_process',
|
|
6
|
+
'run_readonly_command',
|
|
7
|
+
'read_process',
|
|
8
|
+
'sandbox_target_logs',
|
|
9
|
+
]);
|
|
10
|
+
const activeExecutionToolNames = new Set([
|
|
11
|
+
'edit_file',
|
|
12
|
+
'write_file',
|
|
13
|
+
'apply_patch',
|
|
14
|
+
'shell',
|
|
15
|
+
'run_process',
|
|
16
|
+
'start_process',
|
|
17
|
+
'write_process',
|
|
18
|
+
'sandbox_target_up',
|
|
19
|
+
'sandbox_target_down',
|
|
20
|
+
]);
|
|
21
|
+
export function createContinuationCompletionPolicy(options = {}) {
|
|
22
|
+
const defaultMaxTurns = options.defaultMaxTurns ?? 5;
|
|
23
|
+
const now = options.now ?? (() => Date.now());
|
|
24
|
+
const semanticJudge = options.semanticJudge;
|
|
25
|
+
const semanticJudgeMinToolCalls = options.semanticJudgeMinToolCalls ?? 4;
|
|
26
|
+
return {
|
|
27
|
+
async decide(state, result, context) {
|
|
28
|
+
if (state.status === 'cancelling')
|
|
29
|
+
return 'cancel';
|
|
30
|
+
if (result.status === 'paused')
|
|
31
|
+
return 'pause';
|
|
32
|
+
if (result.status === 'interrupted' && result.reason === 'cancelled')
|
|
33
|
+
return 'cancel';
|
|
34
|
+
if (result.status !== 'completed')
|
|
35
|
+
return 'fail';
|
|
36
|
+
if (state.status !== 'running' || !context?.surface)
|
|
37
|
+
return 'complete';
|
|
38
|
+
if (context.config.continuation?.enabled === false)
|
|
39
|
+
return 'complete';
|
|
40
|
+
const maxTurns = context.config.continuation?.maxTurns ?? context.maxContinuationTurns ?? defaultMaxTurns;
|
|
41
|
+
if (maxTurns <= 0 || context.continuationTurnsUsed >= maxTurns)
|
|
42
|
+
return 'complete';
|
|
43
|
+
if (!hasSufficientBudget(state, context, now()))
|
|
44
|
+
return 'complete';
|
|
45
|
+
const { turnOrder, callsByTurn, assistantTextByTurn, latestTodos, initialUserGoal } = analyzeRunSurface(context.surface, context.runId);
|
|
46
|
+
const turnCalls = callsByTurn.get(context.turnId) ?? [];
|
|
47
|
+
const runCalls = turnOrder.flatMap((turnId) => callsByTurn.get(turnId) ?? []);
|
|
48
|
+
const finalAssistantText = assistantTextByTurn.get(context.turnId) ?? '';
|
|
49
|
+
if (hasExternalBlocker(finalAssistantText, turnCalls, runCalls)) {
|
|
50
|
+
return 'complete';
|
|
51
|
+
}
|
|
52
|
+
const stagnant = isStagnantContinuation(context.continuationTurnsUsed, turnOrder, callsByTurn);
|
|
53
|
+
const search = context.config.search;
|
|
54
|
+
const triggers = search?.triggers ?? ['stagnation', 'consecutive_failures'];
|
|
55
|
+
const canSearch = search?.mode === 'selective' && !context.searchesUsed && initialUserGoal.length > 0;
|
|
56
|
+
if (canSearch) {
|
|
57
|
+
// Successful reads between verification attempts do not resolve a verification failure.
|
|
58
|
+
const checks = runCalls.filter((call) => call.verificationObserved);
|
|
59
|
+
const failures = turnCalls.some((call) => call.failed) &&
|
|
60
|
+
((checks.length >= 2 && checks.slice(-2).every((call) => call.failed)) ||
|
|
61
|
+
(runCalls.length >= 2 && runCalls.slice(-2).every((call) => call.failed)));
|
|
62
|
+
const trigger = failures && triggers.includes('consecutive_failures')
|
|
63
|
+
? 'consecutive_failures'
|
|
64
|
+
: stagnant && triggers.includes('stagnation')
|
|
65
|
+
? 'stagnation'
|
|
66
|
+
: undefined;
|
|
67
|
+
if (trigger) {
|
|
68
|
+
return {
|
|
69
|
+
kind: 'branch',
|
|
70
|
+
trigger,
|
|
71
|
+
reason: trigger === 'stagnation'
|
|
72
|
+
? 'The last continuation made no progress.'
|
|
73
|
+
: 'Recent tool checks failed repeatedly.',
|
|
74
|
+
goal: initialUserGoal,
|
|
75
|
+
input: 'Revisit the unresolved user goal. Use the existing evidence to choose a different approach and verify it with a concrete check.',
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (stagnant) {
|
|
80
|
+
return 'complete';
|
|
81
|
+
}
|
|
82
|
+
const canVerify = hasVerificationToolsAvailable(context);
|
|
83
|
+
// Case B1: current turn wrote files without running a verification/execution tool afterward.
|
|
84
|
+
const lastTurnWriteIndex = findLastIndex(turnCalls, (call) => writeToolNames.has(call.toolName) && call.status === 'success');
|
|
85
|
+
if (lastTurnWriteIndex !== -1 && canVerify && !hasVerificationAfter(turnCalls, lastTurnWriteIndex)) {
|
|
86
|
+
const editedPaths = collectTargets(turnCalls.slice(0, lastTurnWriteIndex + 1));
|
|
87
|
+
return {
|
|
88
|
+
kind: 'continue',
|
|
89
|
+
reason: 'unverified_edits',
|
|
90
|
+
input: buildUnverifiedEditsPrompt(editedPaths),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
const canSearchOnUnresolvedGoal = canSearch && triggers.includes('stagnation') && context.continuationTurnsUsed >= 1;
|
|
94
|
+
const continueUnresolved = (reason, input) => canSearchOnUnresolvedGoal
|
|
95
|
+
? { kind: 'branch', trigger: 'stagnation', reason, goal: initialUserGoal, input }
|
|
96
|
+
: { kind: 'continue', reason, input };
|
|
97
|
+
// Case C1: todo_write checklist still has untouched pending items (or unfinished items with bailout phrasing).
|
|
98
|
+
const incompleteTodos = latestTodos.filter((todo) => todo.status === 'pending' || todo.status === 'in_progress');
|
|
99
|
+
const hasPendingTodos = latestTodos.some((todo) => todo.status === 'pending');
|
|
100
|
+
const partialGoalSurrender = matchesPartialGoalSurrender(finalAssistantText);
|
|
101
|
+
const prematureBailout = matchesPrematureBailout(finalAssistantText);
|
|
102
|
+
if (incompleteTodos.length > 0 && (hasPendingTodos || prematureBailout || partialGoalSurrender)) {
|
|
103
|
+
return continueUnresolved('incomplete_todos', buildIncompleteTodosPrompt(incompleteTodos, context.continuationTurnsUsed));
|
|
104
|
+
}
|
|
105
|
+
// Case C2: self-cancelled todo items without a tool-verified external blocker.
|
|
106
|
+
const cancelledTodos = latestTodos.filter((todo) => todo.status === 'cancelled');
|
|
107
|
+
const hadTaskWork = runCalls.length > 0;
|
|
108
|
+
if (hadTaskWork && cancelledTodos.length > 0) {
|
|
109
|
+
return continueUnresolved('incomplete_todos', buildCancelledTodosPrompt(cancelledTodos, context.continuationTurnsUsed));
|
|
110
|
+
}
|
|
111
|
+
// Case A: fast-path detection of partial-goal surrender or premature bail-out.
|
|
112
|
+
if (hadTaskWork && partialGoalSurrender) {
|
|
113
|
+
return continueUnresolved('premature_bailout', buildPartialGoalSurrenderPrompt(context.continuationTurnsUsed));
|
|
114
|
+
}
|
|
115
|
+
if (hadTaskWork && prematureBailout) {
|
|
116
|
+
const readonlyOnly = !runCalls.some((call) => activeExecutionToolNames.has(call.toolName));
|
|
117
|
+
return continueUnresolved('premature_bailout', buildPrematureBailoutPrompt(readonlyOnly, context.continuationTurnsUsed));
|
|
118
|
+
}
|
|
119
|
+
// Case D: semantic LLM completion judge as the final stop-gate for substantive multi-step runs.
|
|
120
|
+
const substantiveTask = runCalls.length >= semanticJudgeMinToolCalls &&
|
|
121
|
+
runCalls.some((call) => activeExecutionToolNames.has(call.toolName));
|
|
122
|
+
if (semanticJudge && substantiveTask && initialUserGoal.trim() && finalAssistantText.trim()) {
|
|
123
|
+
try {
|
|
124
|
+
const verdict = await semanticJudge({
|
|
125
|
+
runId: context.runId,
|
|
126
|
+
agentSessionId: context.agentSessionId,
|
|
127
|
+
turnId: context.turnId,
|
|
128
|
+
config: context.config,
|
|
129
|
+
userGoal: initialUserGoal,
|
|
130
|
+
finalAssistantText,
|
|
131
|
+
todos: latestTodos,
|
|
132
|
+
toolSummary: summarizeRunCalls(runCalls),
|
|
133
|
+
continuationTurnsUsed: context.continuationTurnsUsed,
|
|
134
|
+
});
|
|
135
|
+
if (verdict && !verdict.goalAchieved && !verdict.isGenuineExternalBlocker) {
|
|
136
|
+
return continueUnresolved('premature_bailout', buildSemanticJudgePrompt(verdict, context.continuationTurnsUsed));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// Fail open if the lightweight semantic judge errors or times out.
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return 'complete';
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function hasSufficientBudget(state, context, nowMs) {
|
|
148
|
+
const limits = context.config.limits;
|
|
149
|
+
if (isLimited(limits.maxTotalTokens)) {
|
|
150
|
+
const usedTokens = settledModelTokens(state) + state.reservedTokens;
|
|
151
|
+
const remainingTokens = limits.maxTotalTokens - usedTokens;
|
|
152
|
+
if (remainingTokens / limits.maxTotalTokens < 0.2)
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
if (isLimited(limits.maxSteps) && (limits.maxSteps - state.stepsStarted) / limits.maxSteps < 0.2)
|
|
156
|
+
return false;
|
|
157
|
+
if (isLimited(limits.maxModelAttempts) &&
|
|
158
|
+
(limits.maxModelAttempts - state.modelAttempts) / limits.maxModelAttempts < 0.2)
|
|
159
|
+
return false;
|
|
160
|
+
if (state.deadlineAt && isLimited(limits.wallTimeMs)) {
|
|
161
|
+
const remainingMs = Date.parse(state.deadlineAt) - nowMs;
|
|
162
|
+
if (!Number.isFinite(remainingMs) || remainingMs / limits.wallTimeMs < 0.2)
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
function analyzeRunSurface(surface, runId) {
|
|
168
|
+
const turnOrder = [];
|
|
169
|
+
const itemsByTurn = new Map();
|
|
170
|
+
for (const item of surface.items) {
|
|
171
|
+
if (!item.active || item.message.runId !== runId)
|
|
172
|
+
continue;
|
|
173
|
+
const list = itemsByTurn.get(item.message.turnId);
|
|
174
|
+
if (list)
|
|
175
|
+
list.push(item);
|
|
176
|
+
else {
|
|
177
|
+
turnOrder.push(item.message.turnId);
|
|
178
|
+
itemsByTurn.set(item.message.turnId, [item]);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const callsByTurn = new Map();
|
|
182
|
+
const assistantTextByTurn = new Map();
|
|
183
|
+
let latestTodos = [];
|
|
184
|
+
let initialUserGoal = '';
|
|
185
|
+
for (const turnId of turnOrder) {
|
|
186
|
+
const items = itemsByTurn.get(turnId) ?? [];
|
|
187
|
+
const calls = [];
|
|
188
|
+
const callIndexById = new Map();
|
|
189
|
+
let lastText = '';
|
|
190
|
+
for (const item of items) {
|
|
191
|
+
const msg = item.message;
|
|
192
|
+
if (msg.role === 'user') {
|
|
193
|
+
if (!initialUserGoal) {
|
|
194
|
+
const text = renderText(msg.content).trim();
|
|
195
|
+
if (text)
|
|
196
|
+
initialUserGoal = text;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
else if (msg.role === 'assistant') {
|
|
200
|
+
for (const call of msg.toolCalls) {
|
|
201
|
+
const target = extractTarget(call.arguments);
|
|
202
|
+
const todos = call.toolName === 'todo_write' ? extractTodosFromArgs(call.arguments) : undefined;
|
|
203
|
+
callIndexById.set(call.id, calls.length);
|
|
204
|
+
calls.push({
|
|
205
|
+
toolName: call.toolName,
|
|
206
|
+
arguments: call.arguments,
|
|
207
|
+
status: 'pending',
|
|
208
|
+
failed: false,
|
|
209
|
+
verificationObserved: false,
|
|
210
|
+
...(target ? { target } : {}),
|
|
211
|
+
...(todos ? { todos } : {}),
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
const text = renderText(msg.content).trim();
|
|
215
|
+
if (text)
|
|
216
|
+
lastText = text;
|
|
217
|
+
}
|
|
218
|
+
else if (msg.role === 'tool') {
|
|
219
|
+
const index = callIndexById.get(msg.result.toolCallId);
|
|
220
|
+
if (index !== undefined) {
|
|
221
|
+
const prev = calls[index];
|
|
222
|
+
const outcome = msg.result.outcome;
|
|
223
|
+
const data = outcome.status === 'success' &&
|
|
224
|
+
outcome.data &&
|
|
225
|
+
typeof outcome.data === 'object' &&
|
|
226
|
+
!Array.isArray(outcome.data)
|
|
227
|
+
? outcome.data
|
|
228
|
+
: undefined;
|
|
229
|
+
const processRead = prev.toolName === 'read_process';
|
|
230
|
+
const exitedProcess = processRead && data?.status === 'exited';
|
|
231
|
+
const exitCode = processRead ? data?.exit_code : data?.exitCode;
|
|
232
|
+
const failed = outcome.status === 'error' ||
|
|
233
|
+
(verificationToolNames.has(prev.toolName) &&
|
|
234
|
+
(!processRead || exitedProcess) &&
|
|
235
|
+
typeof exitCode === 'number' &&
|
|
236
|
+
exitCode !== 0);
|
|
237
|
+
const verificationObserved = verificationToolNames.has(prev.toolName) &&
|
|
238
|
+
(processRead
|
|
239
|
+
? outcome.status === 'success' && exitedProcess && typeof exitCode === 'number'
|
|
240
|
+
: outcome.status !== 'denied');
|
|
241
|
+
const errorCode = outcome.status === 'success' ? undefined : outcome.error.code;
|
|
242
|
+
const outcomeText = outcome.status === 'success'
|
|
243
|
+
? renderText(outcome.content)
|
|
244
|
+
: `${outcome.error.code}: ${outcome.error.message}`;
|
|
245
|
+
const todosFromOutcome = prev.toolName === 'todo_write' && outcome.status === 'success'
|
|
246
|
+
? (extractTodosFromData(data) ?? prev.todos)
|
|
247
|
+
: undefined;
|
|
248
|
+
if (todosFromOutcome !== undefined) {
|
|
249
|
+
latestTodos = todosFromOutcome;
|
|
250
|
+
}
|
|
251
|
+
calls[index] = {
|
|
252
|
+
...prev,
|
|
253
|
+
status: outcome.status,
|
|
254
|
+
failed,
|
|
255
|
+
verificationObserved,
|
|
256
|
+
outcomeText,
|
|
257
|
+
...(errorCode ? { errorCode } : {}),
|
|
258
|
+
...(todosFromOutcome ? { todos: todosFromOutcome } : {}),
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
callsByTurn.set(turnId, calls);
|
|
264
|
+
assistantTextByTurn.set(turnId, lastText);
|
|
265
|
+
}
|
|
266
|
+
return { turnOrder, callsByTurn, assistantTextByTurn, latestTodos, initialUserGoal };
|
|
267
|
+
}
|
|
268
|
+
function isStagnantContinuation(continuationTurnsUsed, turnOrder, callsByTurn) {
|
|
269
|
+
if (continuationTurnsUsed < 1 || !turnOrder.length)
|
|
270
|
+
return false;
|
|
271
|
+
const currentTurnId = turnOrder.at(-1);
|
|
272
|
+
const currentCalls = callsByTurn.get(currentTurnId) ?? [];
|
|
273
|
+
if (currentCalls.length === 0)
|
|
274
|
+
return true;
|
|
275
|
+
if (continuationTurnsUsed >= 2 && turnOrder.length >= 2) {
|
|
276
|
+
const prevTurnId = turnOrder.at(-2);
|
|
277
|
+
const prevCalls = callsByTurn.get(prevTurnId) ?? [];
|
|
278
|
+
const currentSig = toolSignature(currentCalls);
|
|
279
|
+
const prevSig = toolSignature(prevCalls);
|
|
280
|
+
if (currentSig === prevSig)
|
|
281
|
+
return true;
|
|
282
|
+
const currentSuccesses = currentCalls.filter((c) => c.status === 'success').length;
|
|
283
|
+
const prevSuccesses = prevCalls.filter((c) => c.status === 'success').length;
|
|
284
|
+
if (currentSuccesses === 0 && prevSuccesses === 0)
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
return false;
|
|
288
|
+
}
|
|
289
|
+
function toolSignature(calls) {
|
|
290
|
+
return calls.map((c) => `${c.toolName}:${c.status}:${JSON.stringify(c.arguments)}`).join('|');
|
|
291
|
+
}
|
|
292
|
+
function hasVerificationToolsAvailable(context) {
|
|
293
|
+
const allowed = context.config.contextExtensions?.mode?.allowedTools;
|
|
294
|
+
const snapshot = context.config.toolSnapshot?.definitions;
|
|
295
|
+
if (allowed && snapshot) {
|
|
296
|
+
const allowedSet = new Set(allowed);
|
|
297
|
+
return snapshot.some((def) => allowedSet.has(def.name) && verificationToolNames.has(def.name));
|
|
298
|
+
}
|
|
299
|
+
if (snapshot)
|
|
300
|
+
return snapshot.some((def) => verificationToolNames.has(def.name));
|
|
301
|
+
if (allowed)
|
|
302
|
+
return allowed.some((name) => verificationToolNames.has(name));
|
|
303
|
+
return true;
|
|
304
|
+
}
|
|
305
|
+
function hasVerificationAfter(calls, afterIndex) {
|
|
306
|
+
for (let i = afterIndex + 1; i < calls.length; i++) {
|
|
307
|
+
const call = calls[i];
|
|
308
|
+
if (call.verificationObserved)
|
|
309
|
+
return true;
|
|
310
|
+
}
|
|
311
|
+
return false;
|
|
312
|
+
}
|
|
313
|
+
const externalBlockerPattern = /(permission denied|access denied|approval denied|user denied|missing credentials?|no credentials?|api[_ ]?key|unauthorized|\b401\b|\b403\b|\b451\b|AUTH_REQUIRED|authentication required|SANDBOX_DISK_LIMIT_EXCEEDED|SANDBOX_UNAVAILABLE|SANDBOX_CONTAINER_LIMIT_EXCEEDED|PLATFORM_AUTH_FAILED|unreachable|connection refused|ECONNREFUSED|ENOTFOUND|权限不足|没有权限|未获批准|拒绝访问|缺少凭据|缺少凭证|缺少密钥|未配置密钥|认证失败|无法连接|网络不可达|基础设施故障|沙箱.*(?:不可恢复|未重建|已终止))/i;
|
|
314
|
+
const externalBlockerErrorCodes = new Set([
|
|
315
|
+
'SANDBOX_DISK_LIMIT_EXCEEDED',
|
|
316
|
+
'SANDBOX_UNAVAILABLE',
|
|
317
|
+
'SANDBOX_CONTAINER_LIMIT_EXCEEDED',
|
|
318
|
+
'PLATFORM_AUTH_FAILED',
|
|
319
|
+
]);
|
|
320
|
+
const structuredBlockerOutcomePattern = /("code"\s*:\s*"(?:AUTH_REQUIRED|UNAVAILABLE|FORBIDDEN|UNAUTHORIZED|PLATFORM_AUTH_FAILED|SANDBOX_DISK_LIMIT_EXCEEDED|SANDBOX_UNAVAILABLE)"|authentication required|SANDBOX_DISK_LIMIT_EXCEEDED|SANDBOX_UNAVAILABLE|HTTP\s*(?:401|403|451))/i;
|
|
321
|
+
const localValidationErrorCodes = new Set([
|
|
322
|
+
'WORKSPACE_PATH_INVALID',
|
|
323
|
+
'INVALID_ARGUMENTS',
|
|
324
|
+
'TOOL_UNAVAILABLE',
|
|
325
|
+
'INVALID_TEAM_CONFIG',
|
|
326
|
+
]);
|
|
327
|
+
function isPermissionDeniedCall(call) {
|
|
328
|
+
return call.status === 'denied' && !localValidationErrorCodes.has(call.errorCode ?? '');
|
|
329
|
+
}
|
|
330
|
+
function hasExternalBlocker(text, turnCalls, runCalls) {
|
|
331
|
+
if (turnCalls.some(isPermissionDeniedCall)) {
|
|
332
|
+
if (/(denied|approval|permission|拒绝|未批准|审批|权限)/i.test(text))
|
|
333
|
+
return true;
|
|
334
|
+
}
|
|
335
|
+
if (runCalls.some((call) => call.errorCode && externalBlockerErrorCodes.has(call.errorCode)) &&
|
|
336
|
+
externalBlockerPattern.test(text)) {
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
339
|
+
if (runCalls.some((call) => call.outcomeText !== undefined && structuredBlockerOutcomePattern.test(call.outcomeText)) &&
|
|
340
|
+
externalBlockerPattern.test(text)) {
|
|
341
|
+
return true;
|
|
342
|
+
}
|
|
343
|
+
const observedFailure = runCalls.some((call) => isPermissionDeniedCall(call) || call.failed);
|
|
344
|
+
if (!observedFailure)
|
|
345
|
+
return false;
|
|
346
|
+
if (runCalls.some((call) => (isPermissionDeniedCall(call) || call.failed) &&
|
|
347
|
+
call.outcomeText !== undefined &&
|
|
348
|
+
externalBlockerPattern.test(call.outcomeText))) {
|
|
349
|
+
return true;
|
|
350
|
+
}
|
|
351
|
+
return externalBlockerPattern.test(text);
|
|
352
|
+
}
|
|
353
|
+
function matchesPartialGoalSurrender(text) {
|
|
354
|
+
if (!text.trim())
|
|
355
|
+
return false;
|
|
356
|
+
return /(没有确认可实现|不足以证明|现有证据不足|现有实验没有证明|未能(?:实现|完成|建立|打通|达成|获得|拿到|取得|构造|找到|验证).{0,16}(?:代码执行|控制流|任意写|利用链|shell|flag|漏洞利用|完整)|(?:仅|只)(?:完成|实现|验证|确认).{0,14}(?:信息泄露|泄露|部分|初步)|而不是.{0,8}(?:代码执行|控制流|获取|shell|flag|完整利用)|不是完整.{0,8}(?:利用|脚本|方案|解决)|仅(?:是|为).{0,8}(?:漏洞验证|诊断|验证)脚本|无法稳定(?:获得|实现|控制|利用)|(?:尚未|没有|未)(?:实现|完成|建立|打通|达成|获得|拿到|取得|构造出?).{0,14}(?:代码执行|控制流劫持|控制流|任意地址写|利用链|shell|RCE|flag)|不能(?:把这题|据此)?(?:称为已解|声称获得)|本地验证到此为止|\bnot\s+code\s+execution\b|\bonly\s+confirms?\s+information\s+disclosure\b|\binsufficient\s+evidence\s+to\s+prove\b|\b(?:could\s+not|did\s+not|unable\s+to|failed\s+to)\s+(?:achieve|complete|establish|confirm|obtain|get)\s+(?:code\s+execution|rce|a?\s*shell|arbitrary\s+write|control[- ]flow|exploit\s+chain|the\s+flag)\b|\binstead\s+of\s+(?:code\s+execution|rce|a?\s*shell|capturing\s+the\s+flag)\b|\bnot\s+a\s+(?:full|complete)\s+exploit\b|\bpartial\s+(?:solution|exploit|result)\s+only\b)/i.test(text);
|
|
357
|
+
}
|
|
358
|
+
function matchesPrematureBailout(text) {
|
|
359
|
+
if (!text.trim())
|
|
360
|
+
return false;
|
|
361
|
+
return /(还需要(?:继续)?(?:确定|确认|检查|调查|分析|排查|验证|查看|定位|测试|补充|完成)|(?:目前|现在|我)?还不能(?:给出|确定|确认|完成|下结论|验证)|尚未(?:完成|建立|打通|验证|确认|检查|测试|实现|修复)|还未(?:完成|建立|验证|确认|检查|测试)|(?:暂时)?无法(?:确定|确认|完成|给出|验证|取得|继续)|仅凭(?:目前|当前|本地)|要继续完成|需要提供|请提供|补充.{0,12}(?:源码|源代码|代码|地址|端口)|拿到.{0,12}(?:后|再).{0,12}(?:继续|分析|验证)|需要进一步(?:调查|分析|检查|确认|验证|排查|测试)|下一步(?:需要|可以|将|是)|(?:\bneed|\bneeds|\bhave)\s+to\s+(?:further\s+)?(?:investigate|check|verify|inspect|confirm|determine|test|complete|finish)\b|\b(?:haven't|have\s+not|not\s+yet)\s+(?:verified|checked|tested|completed|finished|confirmed|established|investigated)\b|\bnext\s+steps?\s+(?:would\s+be|are|include)\b|\b(?:cannot|can't|unable\s+to)\s+(?:determine|confirm|conclude|complete|verify|exploit|solve)\b|\bto\s+be\s+(?:verified|confirmed|checked|completed)\b|\bstill\s+(?:need|needs)\s+to\s+(?:check|verify|investigate|test|complete)\b|\bplease\s+provide\b|\bonce\s+you\s+provide\b|\bwith\s+only\s+the\s+(?:current|local)\b)/i.test(text);
|
|
362
|
+
}
|
|
363
|
+
function pivotProtocolHint(continuationTurnsUsed) {
|
|
364
|
+
if (continuationTurnsUsed < 1)
|
|
365
|
+
return [];
|
|
366
|
+
return [
|
|
367
|
+
'Pivot protocol: explicitly list which hypothesis/path failed so far, formulate 2 genuinely different technical approaches (do NOT repeat the same command or diagnostic script), pick the highest-leverage alternative, and dynamically test it right away.',
|
|
368
|
+
];
|
|
369
|
+
}
|
|
370
|
+
function buildUnverifiedEditsPrompt(editedPaths) {
|
|
371
|
+
const targets = editedPaths.length ? editedPaths.join(', ') : 'workspace files';
|
|
372
|
+
return [
|
|
373
|
+
`You modified ${targets} in the previous turn without observing verification afterward (shell, run_process, run_readonly_command, or read_process for an exited process).`,
|
|
374
|
+
'Run the relevant tests, build, or read-only checks to empirically verify your changes and report the observed output.',
|
|
375
|
+
'If a verification process is already running, use read_process to observe its exit; do not start a duplicate process.',
|
|
376
|
+
'If verification is blocked by an external environment limitation, demonstrate the exact blocker.',
|
|
377
|
+
].join('\n');
|
|
378
|
+
}
|
|
379
|
+
function buildIncompleteTodosPrompt(todos, continuationTurnsUsed) {
|
|
380
|
+
const summary = todos.map((todo) => `- [${todo.status}] ${todo.id}: ${todo.content}`).join('\n');
|
|
381
|
+
return [
|
|
382
|
+
'Your todo_write checklist still has unfinished items while local tools and budget remain available:',
|
|
383
|
+
summary,
|
|
384
|
+
'Continue working autonomously to complete the remaining items (write and execute scripts/exploits/fixes locally and verify empirically), then update todo_write before giving your final answer.',
|
|
385
|
+
...pivotProtocolHint(continuationTurnsUsed),
|
|
386
|
+
].join('\n');
|
|
387
|
+
}
|
|
388
|
+
function buildCancelledTodosPrompt(cancelledTodos, continuationTurnsUsed) {
|
|
389
|
+
const summary = cancelledTodos.map((todo) => `- [cancelled] ${todo.id}: ${todo.content}`).join('\n');
|
|
390
|
+
return [
|
|
391
|
+
'You marked core todo_write item(s) as cancelled without a concrete, tool-verified external blocker:',
|
|
392
|
+
summary,
|
|
393
|
+
'Self-cancelling unfinished user objectives is not permitted while local workspace files, debugging/execution tools, and budget remain available.',
|
|
394
|
+
'Restore the unfinished item(s) to in_progress in todo_write and continue working autonomously using the available tools (e.g., gdb dynamic memory/pointer-chain inspection, iterative script/code development, end-to-end empirical testing) until the original goal is genuinely achieved and verified.',
|
|
395
|
+
...pivotProtocolHint(continuationTurnsUsed),
|
|
396
|
+
].join('\n');
|
|
397
|
+
}
|
|
398
|
+
function buildPartialGoalSurrenderPrompt(continuationTurnsUsed) {
|
|
399
|
+
return [
|
|
400
|
+
'Your previous response settled for a partial result (such as information disclosure only) or concluded that full exploitation/completion was not confirmed while local tools and budget remain available.',
|
|
401
|
+
'Do NOT downgrade the user goal, self-cancel or rewrite todo_write items to mark partial progress as completed, or give up based on static analysis alone.',
|
|
402
|
+
'Continue using the available tools to perform deep dynamic debugging and iterative exploitation/implementation locally: use gdb (-batch or start_process) to inspect live registers, stack frames, saved rbp/pointer chains, loop counters, and binary/libc memory layout; test concrete primitives (e.g., partial %hhn/%hn overwrites via existing stack pointer chains, loop-counter extension, ROP/one_gadget with local libc.so.6, or alternative execution paths); and iterate on your script until you empirically prove full end-to-end completion (or exhaust dynamic attempts with concrete failed debugging evidence).',
|
|
403
|
+
...pivotProtocolHint(continuationTurnsUsed),
|
|
404
|
+
].join('\n');
|
|
405
|
+
}
|
|
406
|
+
function buildPrematureBailoutPrompt(readonlyOnly, continuationTurnsUsed) {
|
|
407
|
+
return [
|
|
408
|
+
'Your previous response stopped at partial analysis or deferred work to the user while local workspace files, tools, and budget are still available.',
|
|
409
|
+
...(readonlyOnly
|
|
410
|
+
? [
|
|
411
|
+
'You have only performed read-only reconnaissance so far. Do NOT ask the user for remote host:port or source code when local binaries, Dockerfiles, or scripts exist in the workspace.',
|
|
412
|
+
'Continue using the available tools: read any truncated tool output with read_tool_result, finish reverse-engineering/analysis, write a concrete local solution or exploit script (e.g., solve.py) with write_file, and verify it end-to-end against the local target using shell, run_process (python3/gdb/bash/stdin), or start_process.',
|
|
413
|
+
]
|
|
414
|
+
: [
|
|
415
|
+
'Do NOT ask the user for optional remote endpoints or source code when you can solve and empirically verify against the local binary or service.',
|
|
416
|
+
'Continue using the available tools to implement and verify a complete working solution locally, or produce concrete failed tool output proving an unresolvable external blocker.',
|
|
417
|
+
]),
|
|
418
|
+
...pivotProtocolHint(continuationTurnsUsed),
|
|
419
|
+
].join('\n');
|
|
420
|
+
}
|
|
421
|
+
function buildSemanticJudgePrompt(verdict, continuationTurnsUsed) {
|
|
422
|
+
const missing = verdict.missingCriteria.length
|
|
423
|
+
? ['Missing completion criteria:', ...verdict.missingCriteria.map((item) => `- ${item}`)].join('\n')
|
|
424
|
+
: 'The original user objective has not yet been fully achieved and empirically verified.';
|
|
425
|
+
return [
|
|
426
|
+
'Completion verification detected that your previous response stopped before achieving the full user objective while local tools and budget remain available.',
|
|
427
|
+
missing,
|
|
428
|
+
...(verdict.nextConcreteAction.trim()
|
|
429
|
+
? [`Recommended next concrete action: ${verdict.nextConcreteAction.trim()}`]
|
|
430
|
+
: []),
|
|
431
|
+
'Do NOT downgrade the goal or settle for a partial diagnostic. Continue autonomously with the available tools to implement and empirically verify the complete solution.',
|
|
432
|
+
...pivotProtocolHint(continuationTurnsUsed),
|
|
433
|
+
].join('\n');
|
|
434
|
+
}
|
|
435
|
+
function summarizeRunCalls(calls) {
|
|
436
|
+
const recent = calls.slice(-24);
|
|
437
|
+
return recent
|
|
438
|
+
.map((call, idx) => {
|
|
439
|
+
const target = call.target ? ` target=${call.target}` : '';
|
|
440
|
+
const err = call.errorCode ? ` error=${call.errorCode}` : '';
|
|
441
|
+
const failed = call.failed ? ' [failed]' : '';
|
|
442
|
+
return `${idx + 1}. ${call.toolName}${target} status=${call.status}${failed}${err}`;
|
|
443
|
+
})
|
|
444
|
+
.join('\n');
|
|
445
|
+
}
|
|
446
|
+
function extractTodosFromArgs(args) {
|
|
447
|
+
if (args.kind !== 'json' ||
|
|
448
|
+
args.value === null ||
|
|
449
|
+
typeof args.value !== 'object' ||
|
|
450
|
+
Array.isArray(args.value))
|
|
451
|
+
return undefined;
|
|
452
|
+
return parseTodoArray(args.value.todos);
|
|
453
|
+
}
|
|
454
|
+
function extractTodosFromData(data) {
|
|
455
|
+
if (!data || data.kind !== 'todo_write')
|
|
456
|
+
return undefined;
|
|
457
|
+
return parseTodoArray(data.todos);
|
|
458
|
+
}
|
|
459
|
+
function parseTodoArray(value) {
|
|
460
|
+
if (!Array.isArray(value))
|
|
461
|
+
return undefined;
|
|
462
|
+
const todos = [];
|
|
463
|
+
for (const item of value) {
|
|
464
|
+
if (!item || typeof item !== 'object' || Array.isArray(item))
|
|
465
|
+
continue;
|
|
466
|
+
const record = item;
|
|
467
|
+
if (typeof record.id === 'string' &&
|
|
468
|
+
typeof record.content === 'string' &&
|
|
469
|
+
typeof record.status === 'string') {
|
|
470
|
+
todos.push({ id: record.id, content: record.content, status: record.status });
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
return todos;
|
|
474
|
+
}
|
|
475
|
+
function collectTargets(calls) {
|
|
476
|
+
const seen = new Set();
|
|
477
|
+
for (const call of calls) {
|
|
478
|
+
if (writeToolNames.has(call.toolName) && call.status === 'success' && call.target) {
|
|
479
|
+
seen.add(call.target);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return [...seen];
|
|
483
|
+
}
|
|
484
|
+
function extractTarget(args) {
|
|
485
|
+
if (args.kind !== 'json' ||
|
|
486
|
+
args.value === null ||
|
|
487
|
+
typeof args.value !== 'object' ||
|
|
488
|
+
Array.isArray(args.value))
|
|
489
|
+
return undefined;
|
|
490
|
+
const pathVal = args.value.path;
|
|
491
|
+
return typeof pathVal === 'string' && pathVal.trim() ? pathVal.trim() : undefined;
|
|
492
|
+
}
|
|
493
|
+
function renderText(parts) {
|
|
494
|
+
return parts.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('\n');
|
|
495
|
+
}
|
|
496
|
+
function findLastIndex(items, predicate) {
|
|
497
|
+
for (let i = items.length - 1; i >= 0; i--) {
|
|
498
|
+
if (predicate(items[i]))
|
|
499
|
+
return i;
|
|
500
|
+
}
|
|
501
|
+
return -1;
|
|
502
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { createRuntimeJournal } from './journal.js';
|
|
2
|
+
export type { AdmissionState } from '@saturn-universe/core';
|
|
3
|
+
export type { CommandDependencies } from './command-dependencies.js';
|
|
4
|
+
export { createAgentLoop, type LiveAgentUpdate } from './agent-loop.js';
|
|
5
|
+
export { createRunLoop, defaultCompletionPolicy } from './run-loop.js';
|
|
6
|
+
export { createContinuationCompletionPolicy, type ContinuationCompletionPolicyOptions, type SemanticCompletionJudge, type SemanticCompletionJudgeInput, type SemanticCompletionVerdict, } from './completion-policy.js';
|
|
7
|
+
export { driveSelectiveSearch, extractExploreHypothesesCall, formatSearchResultMessage, type ExploreHypothesesPayload, type SearchBranchReport, type SearchDependencies, type SearchExecutionRequest, type SearchExecutionResult, } from './search-loop.js';
|
|
8
|
+
export { recoverRuntime } from './recovery.js';
|
|
9
|
+
export { autoCompactSurface, compactSurface, generateCompactionSummary, preparePreflightSummaryPlan, resolveAutoCompactionOptions, serializeItemsForSummary, type AutoCompactionOptions, type AutoCompactionOutcome, type PreflightSummaryPlan, } from './compaction.js';
|
|
10
|
+
export { createCommandHandler } from './command-handler.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createRuntimeJournal } from './journal.js';
|
|
2
|
+
export { createAgentLoop } from './agent-loop.js';
|
|
3
|
+
export { createRunLoop, defaultCompletionPolicy } from './run-loop.js';
|
|
4
|
+
export { createContinuationCompletionPolicy, } from './completion-policy.js';
|
|
5
|
+
export { driveSelectiveSearch, extractExploreHypothesesCall, formatSearchResultMessage, } from './search-loop.js';
|
|
6
|
+
export { recoverRuntime } from './recovery.js';
|
|
7
|
+
export { autoCompactSurface, compactSurface, generateCompactionSummary, preparePreflightSummaryPlan, resolveAutoCompactionOptions, serializeItemsForSummary, } from './compaction.js';
|
|
8
|
+
export { createCommandHandler } from './command-handler.js';
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { RuntimeJournal, EventIntent, EventId, RuntimeStateReader, RuntimeEvent, JournalReader } from '@saturn-universe/core';
|
|
2
|
+
import type { CommandDependencies } from './command-dependencies.js';
|
|
3
|
+
type JournalEvent = EventIntent | RuntimeEvent;
|
|
4
|
+
type JournalDependencies = CommandDependencies & {
|
|
5
|
+
stateReader: RuntimeStateReader;
|
|
6
|
+
reader: CommandDependencies['reader'] & JournalReader;
|
|
7
|
+
};
|
|
8
|
+
interface CausalFact {
|
|
9
|
+
readonly id: EventId;
|
|
10
|
+
readonly type: JournalEvent['type'];
|
|
11
|
+
readonly runId: string | undefined;
|
|
12
|
+
readonly turnId: string | undefined;
|
|
13
|
+
readonly stepId: string | undefined;
|
|
14
|
+
readonly callId: string | undefined;
|
|
15
|
+
readonly attemptId: string | undefined;
|
|
16
|
+
readonly requestId: string | undefined;
|
|
17
|
+
readonly approvalId: string | undefined;
|
|
18
|
+
readonly messageId: string | undefined;
|
|
19
|
+
readonly correlationId: string;
|
|
20
|
+
}
|
|
21
|
+
export declare class CausationIndex {
|
|
22
|
+
readonly facts: Map<string, CausalFact>;
|
|
23
|
+
through: import("@saturn-universe/core").EventPosition;
|
|
24
|
+
terminal: boolean;
|
|
25
|
+
add(event: RuntimeEvent): void;
|
|
26
|
+
}
|
|
27
|
+
export declare function createRuntimeJournal(d: JournalDependencies): RuntimeJournal;
|
|
28
|
+
export {};
|