car-runtime 0.60.0 → 0.61.0-nightly.20261105
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/README.md +135 -0
- package/agent-loop.d.ts +4 -0
- package/agent-loop.js +159 -21
- package/index.d.ts +27 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -180,6 +180,141 @@ online: https://github.com/Parslee-ai/car-releases
|
|
|
180
180
|
- `CAR_RUNTIME_DOWNLOAD_BASE=<url>` — override the download origin (e.g.
|
|
181
181
|
internal mirror). Binary filename is appended.
|
|
182
182
|
|
|
183
|
+
## Long-running packaged task loops
|
|
184
|
+
|
|
185
|
+
`openai-codex/gpt-6.1-sol:high` and `openai-codex/gpt-6.1-sol:medium`
|
|
186
|
+
run on CAR's ChatGPT subscription sign-in (`car auth login --provider openai-codex`),
|
|
187
|
+
without an OpenAI API key. Both catalog rows have a 500,000-token context window;
|
|
188
|
+
the suffix selects high or medium reasoning effort.
|
|
189
|
+
|
|
190
|
+
`runAgent` (Node) / `run_agent` (Python) supports these task-only settings:
|
|
191
|
+
|
|
192
|
+
| Node | Python | Meaning |
|
|
193
|
+
| --- | --- | --- |
|
|
194
|
+
| `terminalTools` | `terminal_tools` | Array of tool schemas (`name`, `description`, `parameters`) plus a host `validate(arguments)` function. Exactly `true`/`True` accepts; all other results refuse. Nonempty strings give the reason; empty strings/other values use a default. Async validators are awaited; exceptions use their message, or the default if empty. |
|
|
195
|
+
| `requireTerminal` | `require_terminal` | Require a terminal call even with the default `finish` tool. Defaults off; declared terminal tools imply it. One text-only turn receives a reminder; a second ends as `no_terminal`. |
|
|
196
|
+
| `noProgressGuard` | `no_progress_guard` | Defaults on. Set false for intentional polling. Cumulative repeated signatures earn one nudge at repeat 3 and stop at repeat 6 as `stalled`; eight turns without mutation earn the same single nudge. A new successful mutating signature resets the guard. |
|
|
197
|
+
| `priorMessages` | `prior_messages` | Resume a JSON transcript. Prior system messages are removed in favor of the current identity. Unanswered calls are closed with an explanatory tool result without executing them. The new goal follows the prior messages. The guard starts fresh. |
|
|
198
|
+
| `maxTurns` | `max_turns` | Task default 8. Node: **0** or `Infinity` removes the cap. Python: **0** or `float('inf')` removes the cap. A positive finite cap ends as `timeout` when reached. |
|
|
199
|
+
| `maxTokens` | `max_tokens` | Defaults to **4096**, also for chat turns. |
|
|
200
|
+
|
|
201
|
+
Declared terminal tools replace `finish` in both the offered schemas and the
|
|
202
|
+
system instruction. A refusal becomes a tool result for the model to repair.
|
|
203
|
+
Two terminal calls in one turn are both refused. Ordinary tools execute first;
|
|
204
|
+
a terminal call alongside them is accepted only when all succeeded. In runs with terminal tools, independent ordinary tools continue after a sibling fails so terminal eligibility can be evaluated. Without terminal tools, the runtime's normal abort behavior stops the rest of the turn. A successful ending returns
|
|
205
|
+
`status: "success"` and `terminal_tool: {name, arguments}`.
|
|
206
|
+
|
|
207
|
+
Every returned task outcome includes `transcript`, an ordered JSON message array
|
|
208
|
+
with assistant tool calls and their results. Store it and pass it as prior
|
|
209
|
+
messages on the next invocation, including across Node and Python. Transcript
|
|
210
|
+
and `run_id` are return metadata added after `runs.complete`; the daemon run
|
|
211
|
+
record does not contain the transcript. Terminal identity is also in outcome
|
|
212
|
+
evidence. `stalled` and `no_terminal` are real daemon outcome statuses and both
|
|
213
|
+
cause the task CLI's `main` to exit with code **1**, like `failure`. Other endings remain
|
|
214
|
+
`done`, `timeout`, `success`, `partial_success`, and `give_up`.
|
|
215
|
+
|
|
216
|
+
A successful tool whose schema declares `mutating: true`, or whose name is
|
|
217
|
+
`write_file` or `edit_file`, resets the guard only for a new signature. Failed
|
|
218
|
+
mutations and identical writes do not reset it. Distinct read calls never hit
|
|
219
|
+
the repeat stop. With no custom terminal tools, the legacy `finish` and `done`
|
|
220
|
+
paths remain. Chat retains its existing finish behavior and has no guard.
|
|
221
|
+
|
|
222
|
+
### Terminal tools: complete runnable configurations
|
|
223
|
+
|
|
224
|
+
Use the released package entry shown here (Node: save as an `.mjs` file; Python: save as `.py`). A daemon must be available.
|
|
225
|
+
|
|
226
|
+
```javascript
|
|
227
|
+
import { runAgent } from 'car-runtime/agent-loop';
|
|
228
|
+
const validate = args => args.reason.trim() ? true : 'Give a concrete reason.';
|
|
229
|
+
const terminalTools = ['retry_commit', 'request_recut', 'hand_off'].map(name => ({
|
|
230
|
+
name, description: 'End this investigation.',
|
|
231
|
+
parameters: { type: 'object', properties: { reason: { type: 'string' } }, required: ['reason'] },
|
|
232
|
+
validate,
|
|
233
|
+
}));
|
|
234
|
+
const outcome = await runAgent({ agentName: 'incident-owner', identity: 'Investigate; end with a terminal tool.',
|
|
235
|
+
terminalTools, maxTokens: 4096, maxTurns: 0, noProgressGuard: true }, 'Investigate the failing check.');
|
|
236
|
+
console.log(JSON.stringify(outcome));
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
```python
|
|
240
|
+
from car_runtime.agent_loop import run_agent
|
|
241
|
+
|
|
242
|
+
def validate(args):
|
|
243
|
+
return True if args['reason'].strip() else 'Give a concrete reason.'
|
|
244
|
+
|
|
245
|
+
terminal_tools = [dict(name=name, description='End this investigation.',
|
|
246
|
+
parameters={'type': 'object', 'properties': {'reason': {'type': 'string'}}, 'required': ['reason']},
|
|
247
|
+
validate=validate) for name in ['retry_commit', 'request_recut', 'hand_off']]
|
|
248
|
+
outcome = run_agent(dict(agent_name='incident-owner', identity='Investigate; end with a terminal tool.',
|
|
249
|
+
terminal_tools=terminal_tools, max_tokens=4096, max_turns=0, no_progress_guard=True),
|
|
250
|
+
'Investigate the failing check.')
|
|
251
|
+
print(outcome)
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
The runtime checks the declared argument schema before invoking the host validator.
|
|
255
|
+
The validator receives only the decoded argument object. Exactly `true` (`True` in Python)
|
|
256
|
+
accepts; every other result refuses. A string supplies the refusal reason; an empty string
|
|
257
|
+
or other value uses a default reason. Async validators are awaited. A thrown error's
|
|
258
|
+
message is the refusal reason (the default if empty). A validator which never returns hangs the run, just as
|
|
259
|
+
a hung tool does; supply your own bounded validator when it performs I/O.
|
|
260
|
+
|
|
261
|
+
Terminal tools replace `finish`; declaring `finish` beside them, duplicate names, malformed
|
|
262
|
+
prior messages, or a negative/NaN cap is an error before `runs.start`. With no terminal
|
|
263
|
+
tools, `requireTerminal` (`require_terminal`) makes the built-in `finish` the required
|
|
264
|
+
terminal. Without that option, a text answer still ends as `done`.
|
|
265
|
+
|
|
266
|
+
`terminal_tool: {name, arguments}` appears only on `success`. `main` exits with code **1** for `failure`, `stalled`, and `no_terminal`, and **0** for other returned statuses (`success`, `partial_success`, `give_up`, `timeout`, `done`).
|
|
267
|
+
The no-progress guard counts a repeat whenever a whole turn's sorted tool-name/argument
|
|
268
|
+
signature has occurred earlier since the last reset, not only on consecutive turns.
|
|
269
|
+
The third repeat nudges and the sixth stops; eight turns without a new successful
|
|
270
|
+
state-changing signature only nudges. Python schemas support `mutating: True`, matching
|
|
271
|
+
Node's `mutating: true`; `write_file` and `edit_file` are also state-changing. Failed
|
|
272
|
+
calls do not reset the guard. `noProgressGuard: false` / `no_progress_guard=False`
|
|
273
|
+
disables it for one run.
|
|
274
|
+
|
|
275
|
+
For task runs, the per-call `maxTurns` option / Python `max_turns` argument overrides the
|
|
276
|
+
config value when non-null. Null or omission uses the config; a null/omitted config
|
|
277
|
+
uses 8. Zero or positive infinity lifts the task cap. Chat retains its existing cap
|
|
278
|
+
semantics. `maxTokens` / `max_tokens` defaults to 4096.
|
|
279
|
+
|
|
280
|
+
Resume with `priorMessages` / `prior_messages`, a JSON list of messages shaped as:
|
|
281
|
+
`{role: "user" | "assistant" | "system", content: "text"}`; assistant messages may carry
|
|
282
|
+
`tool_calls: [{id: "call-id", name: "tool-name", arguments: {...}}]`. A tool result is
|
|
283
|
+
`{role: "tool_result", tool_use_id: "call-id", content: "JSON text"}`. `tool_calls` cannot
|
|
284
|
+
be null, and each call needs its id and an `arguments` JSON object. Absent
|
|
285
|
+
`arguments`, null, arrays, and strings are refused before `runs.start`. Node validates
|
|
286
|
+
the JSON round trip, so values that serialize to strings are also refused. Old system
|
|
287
|
+
messages are replaced by the current one. Do not trim a transcript ending on a terminal call: answered calls are retained;
|
|
288
|
+
unanswered calls are closed with an explanatory tool result without rerunning handlers.
|
|
289
|
+
Every ending returns `transcript`; it is never sent to `runs.complete`.
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
Task cap lifting (`0` or positive infinity) applies to `runAgent` / `run_agent`.
|
|
294
|
+
In chat, `maxTurns: 0` / `max_turns=0` performs zero model turns; it does not
|
|
295
|
+
remove the chat budget. Python chat rejects infinity before `runs.start`.
|
|
296
|
+
A refused task configuration throws an Error in Node or raises ValueError in
|
|
297
|
+
Python, rather than returning an outcome. A terminal name cannot collide with
|
|
298
|
+
an ordinary tool name. Node keeps main's missing-identity and numeric-string
|
|
299
|
+
cap behavior.
|
|
300
|
+
|
|
301
|
+
Python async validators are awaited with `asyncio.run` when no event loop is
|
|
302
|
+
running on the callback thread. If that thread already has an event loop, a
|
|
303
|
+
separate thread runs and awaits the coroutine; the synchronous caller waits
|
|
304
|
+
for its result. A validator that never returns therefore still hangs its run.
|
|
305
|
+
The validator receives a deep copy: mutations cannot rewrite the transcript or
|
|
306
|
+
the arguments checked and recorded by CAR. The daemon's full parameter check
|
|
307
|
+
runs before dispatch to that validator, including enum, nested, array and
|
|
308
|
+
additional-property constraints. Schema refusals count as failed tool calls.
|
|
309
|
+
Each task run restores its declared terminal schemas, including A/B/A reuse.
|
|
310
|
+
|
|
311
|
+
The initial occurrence is not a repeat: for one identical signature, the third
|
|
312
|
+
repeat is its fourth occurrence and the sixth repeat is its seventh occurrence.
|
|
313
|
+
Repeats of any previously seen whole-turn signature accumulate between resets;
|
|
314
|
+
for example A, B, A, B, A reaches the third repeat on turn five.
|
|
315
|
+
A typed success also includes an evidence entry shaped as
|
|
316
|
+
`{kind: "tool_result", description: "terminal_name", data: { /* original arguments */ }}`.
|
|
317
|
+
|
|
183
318
|
## License
|
|
184
319
|
|
|
185
320
|
Free for any use including commercial; free to redistribute unmodified.
|
package/agent-loop.d.ts
CHANGED
|
@@ -9,6 +9,9 @@ import type {
|
|
|
9
9
|
CarRuntime,
|
|
10
10
|
} from './index';
|
|
11
11
|
|
|
12
|
+
/** Supports terminalTools, requireTerminal, noProgressGuard, priorMessages; maxTurns 0 or Infinity removes the task cap. Returns transcript on every ending.
|
|
13
|
+
* Prior tool calls must include arguments as a JSON object after JSON serialization; absent or non-object arguments are refused before runs.start.
|
|
14
|
+
*/
|
|
12
15
|
export function runAgent(
|
|
13
16
|
config: AgentLoopConfig,
|
|
14
17
|
goal: string,
|
|
@@ -43,6 +46,7 @@ export function runChatTurn(
|
|
|
43
46
|
|
|
44
47
|
export function serveChat(config: AgentLoopConfig): Promise<CarRuntime>;
|
|
45
48
|
|
|
49
|
+
/** Task CLI exits 1 for failure, stalled, or no_terminal; 0 for other returned statuses; 2 when --task is missing. */
|
|
46
50
|
export function main(config: AgentLoopConfig): Promise<void>;
|
|
47
51
|
|
|
48
52
|
declare const agentLoop: {
|
package/agent-loop.js
CHANGED
|
@@ -43,7 +43,7 @@ const FINISH_SCHEMA = {
|
|
|
43
43
|
},
|
|
44
44
|
};
|
|
45
45
|
|
|
46
|
-
function buildProposal(modelUsed, toolCalls, toolTimeouts = {}) {
|
|
46
|
+
function buildProposal(modelUsed, toolCalls, toolTimeouts = {}, independent = false, continueOnFailure = false) {
|
|
47
47
|
// Glue between the inference IR (ToolCall {id,name,arguments}) and the
|
|
48
48
|
// action IR (Action {id,type,tool,parameters,timeout_ms}). The only IR
|
|
49
49
|
// plumbing you owe.
|
|
@@ -55,6 +55,7 @@ function buildProposal(modelUsed, toolCalls, toolTimeouts = {}) {
|
|
|
55
55
|
// reaped at the default. Omitted (undefined) when the schema sets none,
|
|
56
56
|
// so the action falls back to the daemon default.
|
|
57
57
|
return JSON.stringify({
|
|
58
|
+
...(independent ? { id: require('node:crypto').randomUUID() } : {}),
|
|
58
59
|
source: modelUsed || 'model',
|
|
59
60
|
actions: toolCalls.map((tc, i) => ({
|
|
60
61
|
id: tc.id || `a${i}`,
|
|
@@ -62,6 +63,7 @@ function buildProposal(modelUsed, toolCalls, toolTimeouts = {}) {
|
|
|
62
63
|
tool: tc.name,
|
|
63
64
|
parameters: tc.arguments || {},
|
|
64
65
|
dependencies: [],
|
|
66
|
+
...(continueOnFailure ? { failure_behavior: 'skip' } : {}),
|
|
65
67
|
timeout_ms: toolTimeouts[tc.name],
|
|
66
68
|
})),
|
|
67
69
|
});
|
|
@@ -159,12 +161,12 @@ async function connectionEpoch(rt) {
|
|
|
159
161
|
return typeof rt.connectionEpoch === 'function' ? rt.connectionEpoch() : 0;
|
|
160
162
|
}
|
|
161
163
|
|
|
162
|
-
async function prepareRuntime(rt, toolSchemas, policies) {
|
|
164
|
+
async function prepareRuntime(rt, toolSchemas, policies, terminalNames = new Set()) {
|
|
163
165
|
for (let attempt = 0; attempt < MAX_SETUP_ATTEMPTS; attempt++) {
|
|
164
166
|
const epoch = await connectionEpoch(rt);
|
|
165
167
|
let state = RUNTIME_REGISTRATION.get(rt);
|
|
166
168
|
if (!state || state.epoch !== epoch) {
|
|
167
|
-
state = { epoch, basicsAttempted: false, tools: new
|
|
169
|
+
state = { epoch, basicsAttempted: false, tools: new Map(), policies: new Set() };
|
|
168
170
|
RUNTIME_REGISTRATION.set(rt, state);
|
|
169
171
|
}
|
|
170
172
|
if (!state.basicsAttempted) {
|
|
@@ -172,9 +174,13 @@ async function prepareRuntime(rt, toolSchemas, policies) {
|
|
|
172
174
|
try { await rt.registerAgentBasics(); } catch { /* unsupported on this daemon — fine */ }
|
|
173
175
|
}
|
|
174
176
|
for (const schema of toolSchemas) {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
177
|
+
const key = terminalNames.has(schema.name) ? JSON.stringify(schema) : schema.name;
|
|
178
|
+
if (!terminalNames.has(schema.name) && state.tools.get(schema.name) === key) continue;
|
|
179
|
+
if (terminalNames.has(schema.name)) {
|
|
180
|
+
if (typeof rt.registerToolSchema !== 'function') throw new Error('terminal tools require registerToolSchema');
|
|
181
|
+
await rt.registerToolSchema(JSON.stringify({ name: schema.name, description: schema.description || '', parameters: schema.parameters ?? {}, returns: null, idempotent: false, cache_ttl_secs: null, rate_limit: null }));
|
|
182
|
+
} else await rt.registerTool(schema.name);
|
|
183
|
+
state.tools.set(schema.name, key);
|
|
178
184
|
}
|
|
179
185
|
for (const policy of policies || []) {
|
|
180
186
|
const fingerprint = JSON.stringify(policy);
|
|
@@ -236,8 +242,8 @@ async function recordModelTurn(rt, runId, turnIndex, tracked, fallbackModel) {
|
|
|
236
242
|
/**
|
|
237
243
|
* Run the agent once toward `goal`. Returns an AgentOutcome-shaped object:
|
|
238
244
|
* { status, summary, evidence[], metrics{}, tools_called[], run_id }
|
|
239
|
-
* `status` is one of the
|
|
240
|
-
* done|give_up|timeout|failure). AgentOutcome is caller-built — CAR does not
|
|
245
|
+
* `status` is one of the OutcomeStatus values (success|partial_success|
|
|
246
|
+
* done|give_up|timeout|failure|stalled|no_terminal). AgentOutcome is caller-built — CAR does not
|
|
241
247
|
* return it; we assemble it from what the loop observed.
|
|
242
248
|
*
|
|
243
249
|
* Run-trace lifecycle: each `runAgent` invocation is one run. Before the first
|
|
@@ -257,11 +263,82 @@ async function runAgent(config, goal, options = {}) {
|
|
|
257
263
|
}
|
|
258
264
|
}
|
|
259
265
|
|
|
266
|
+
const NO_PROGRESS_NUDGE = 'You have repeated the same action several times without changing anything or making progress. Stop re-reading and either take a concrete action (write or edit a file, run a command) or, if the task is genuinely complete, finish now with your summary.';
|
|
267
|
+
class NoProgressGuard {
|
|
268
|
+
constructor() { this.seen = new Set(); this.repeats = 0; this.turns = 0; this.nudged = false; }
|
|
269
|
+
observe(sig, mutated) {
|
|
270
|
+
const fresh = !this.seen.has(sig);
|
|
271
|
+
this.seen.add(sig);
|
|
272
|
+
if (mutated && fresh) {
|
|
273
|
+
this.seen = new Set([sig]); this.repeats = 0; this.turns = 0; this.nudged = false;
|
|
274
|
+
return 'progress';
|
|
275
|
+
}
|
|
276
|
+
this.turns++;
|
|
277
|
+
if (!fresh) {
|
|
278
|
+
this.repeats++;
|
|
279
|
+
if (this.repeats >= 6) return 'break';
|
|
280
|
+
if (this.repeats >= 3 && !this.nudged) { this.nudged = true; return 'nudge'; }
|
|
281
|
+
}
|
|
282
|
+
if (this.turns >= 8 && !this.nudged) { this.nudged = true; return 'nudge'; }
|
|
283
|
+
return 'continue';
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function stableValue(value) {
|
|
287
|
+
if (Array.isArray(value)) return value.map(stableValue);
|
|
288
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(k => [k, stableValue(value[k])]));
|
|
289
|
+
return value;
|
|
290
|
+
}
|
|
291
|
+
function resumeMessages(prior) {
|
|
292
|
+
if (!Array.isArray(prior)) throw new Error('priorMessages must be a list');
|
|
293
|
+
const copied = JSON.parse(JSON.stringify(prior));
|
|
294
|
+
const pending = new Set();
|
|
295
|
+
for (const m of copied) {
|
|
296
|
+
if (!m || !['system', 'user', 'assistant', 'tool_result'].includes(m.role)) throw new Error('priorMessages message requires a valid role');
|
|
297
|
+
if (typeof m.content !== 'string') throw new Error('priorMessages message requires content');
|
|
298
|
+
if (m.role === 'tool_result') {
|
|
299
|
+
if (!pending.delete(m.tool_use_id)) throw new Error('orphan tool result');
|
|
300
|
+
} else {
|
|
301
|
+
pending.clear();
|
|
302
|
+
}
|
|
303
|
+
if ('tool_calls' in m && (!Array.isArray(m.tool_calls) || m.tool_calls.some(c => !c || typeof c.id !== 'string' || !c.id || typeof c.name !== 'string'))) throw new Error('priorMessages tool_calls must be a list with call ids and names');
|
|
304
|
+
for (const c of m.tool_calls || []) {
|
|
305
|
+
if (!c.arguments || typeof c.arguments !== 'object' || Array.isArray(c.arguments)) throw new Error('priorMessages tool call arguments must be an object');
|
|
306
|
+
pending.add(c.id);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
const messages = copied.filter(m => m.role !== 'system');
|
|
310
|
+
// Close at the original turn boundary, including when later user turns exist.
|
|
311
|
+
for (let i = 0; i < messages.length; i++) {
|
|
312
|
+
const calls = messages[i].tool_calls || [];
|
|
313
|
+
let end = i + 1;
|
|
314
|
+
while (end < messages.length && messages[end].role === 'tool_result') end++;
|
|
315
|
+
const answered = new Set(messages.slice(i + 1, end).map(m => m.tool_use_id));
|
|
316
|
+
const missing = calls.filter(c => !answered.has(c.id)).map(c => ({ role: 'tool_result', tool_use_id: c.id, content: JSON.stringify({ error: 'Unanswered tool call closed on resume; tool was not re-run.' }) }));
|
|
317
|
+
messages.splice(end, 0, ...missing);
|
|
318
|
+
i = end + missing.length - 1;
|
|
319
|
+
}
|
|
320
|
+
return messages;
|
|
321
|
+
}
|
|
322
|
+
|
|
260
323
|
async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
261
324
|
const { executeProposal } = runtimeApi();
|
|
262
325
|
const turnsCap = maxTurns ?? config.maxTurns ?? 8;
|
|
263
|
-
|
|
264
|
-
const
|
|
326
|
+
if (Number.isNaN(turnsCap) || turnsCap < 0) throw new Error('maxTurns must be nonnegative or infinity');
|
|
327
|
+
const prior = resumeMessages(config.priorMessages ?? []);
|
|
328
|
+
const terminals = config.terminalTools || [];
|
|
329
|
+
const declared = [...(config.toolSchemas || []), ...terminals];
|
|
330
|
+
if (declared.some(t => !t || typeof t.name !== 'string' || !t.name)) throw new Error('tool requires a name');
|
|
331
|
+
const names = declared.map(t => t.name);
|
|
332
|
+
if (new Set(names).size !== names.length) throw new Error('duplicate tool names');
|
|
333
|
+
if (terminals.some(t => Object.hasOwn(config.tools || {}, t.name))) throw new Error('duplicate tool and terminal names');
|
|
334
|
+
if (terminals.length && (names.includes('finish') || Object.hasOwn(config.tools || {}, 'finish'))) throw new Error('finish cannot be declared beside terminal tools');
|
|
335
|
+
for (const t of terminals) if (!t || typeof t.name !== 'string' || !t.name || typeof t.validate !== 'function') throw new Error('terminal tool requires a validator');
|
|
336
|
+
const terminalByName = new Map(terminals.map(t => [t.name, t]));
|
|
337
|
+
const toolSchemas = [...(config.toolSchemas || []), ...(terminals.length ? terminals.map(({ validate, ...schema }) => schema) : [FINISH_SCHEMA])];
|
|
338
|
+
const tools = { ...(terminals.length ? {} : { finish: ({ answer }) => ({ answer }) }), ...(config.tools || {}) };
|
|
339
|
+
const guard = new NoProgressGuard();
|
|
340
|
+
const mutating = new Set(['write_file', 'edit_file', ...toolSchemas.filter(s => s.mutating).map(s => s.name)]);
|
|
341
|
+
let reminded = false;
|
|
265
342
|
// Per-tool execution budget (Parslee-ai/car#259): a tool schema may set
|
|
266
343
|
// `timeoutMs` (e.g. a CLI driver that runs for 180s); it flows onto each
|
|
267
344
|
// action so the daemon honors it instead of reaping at the default.
|
|
@@ -271,7 +348,7 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
|
271
348
|
|
|
272
349
|
// Tools and declarative policies live on the daemon connection. Register
|
|
273
350
|
// each exact entry once when the caller reuses a runtime across runs.
|
|
274
|
-
await prepareRuntime(rt, toolSchemas, config.policies);
|
|
351
|
+
await prepareRuntime(rt, toolSchemas, config.policies, new Set(terminals.map(t => t.name)));
|
|
275
352
|
|
|
276
353
|
// Run-trace bracket (open). Tell the daemon a run is starting so CarHost can
|
|
277
354
|
// trace it: prompt -> CLI outcome -> verifier verdict -> AgentOutcome. The
|
|
@@ -307,8 +384,12 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
|
307
384
|
const isLocalModel = typeof config.defaultModel === 'string'
|
|
308
385
|
&& /^(mlx|qwen)\//.test(config.defaultModel);
|
|
309
386
|
const noThink = isLocalModel ? '\n\n/no_think' : '';
|
|
387
|
+
const endingInstruction = terminals.length
|
|
388
|
+
? 'End the run by calling exactly one declared terminal tool. Do not narrate; act via tools.'
|
|
389
|
+
: 'When the task is complete or you cannot proceed, call the `finish` tool with a concise answer. Do not narrate; act via tools.';
|
|
310
390
|
const messages = [
|
|
311
|
-
{ role: 'system', content: `${config.identity}\n\
|
|
391
|
+
{ role: 'system', content: `${config.identity}\n\n${endingInstruction}${noThink}` },
|
|
392
|
+
...prior,
|
|
312
393
|
{ role: 'user', content: goal },
|
|
313
394
|
];
|
|
314
395
|
|
|
@@ -318,7 +399,7 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
|
318
399
|
let turns = 0;
|
|
319
400
|
|
|
320
401
|
while (outcome === null) {
|
|
321
|
-
if (++turns > turnsCap) {
|
|
402
|
+
if (++turns > turnsCap && turnsCap !== 0) {
|
|
322
403
|
outcome = mkOutcome('timeout', `hit ${turnsCap}-turn cap without finishing`,
|
|
323
404
|
[{ kind: 'stop_reason', description: 'max turns', data: { turnsCap } }], metrics, toolsCalled);
|
|
324
405
|
break;
|
|
@@ -330,7 +411,7 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
|
330
411
|
try {
|
|
331
412
|
tracked = await inferTurn(rt, {
|
|
332
413
|
model: config.defaultModel ?? null,
|
|
333
|
-
maxTokens: config.maxTokens ??
|
|
414
|
+
maxTokens: config.maxTokens ?? 4096,
|
|
334
415
|
toolSchemas,
|
|
335
416
|
messages,
|
|
336
417
|
});
|
|
@@ -343,9 +424,19 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
|
343
424
|
const calls = tracked.tool_calls || [];
|
|
344
425
|
// Normalize ids before tracing so the recorded decision carries the same
|
|
345
426
|
// ids proposal execution and subsequent tool_results use.
|
|
346
|
-
calls.forEach((c, i) => { c.id = c.id || `a${i}`; });
|
|
427
|
+
calls.forEach((c, i) => { c.id = c.id || `a${i}`; if (!Object.hasOwn(c, 'arguments')) c.arguments = {}; });
|
|
347
428
|
await recordModelTurn(rt, runId, turns, tracked, config.defaultModel);
|
|
348
429
|
if (calls.length === 0) {
|
|
430
|
+
if (tracked.text) messages.push({ role: 'assistant', content: tracked.text });
|
|
431
|
+
if (terminals.length || config.requireTerminal) {
|
|
432
|
+
if (!reminded) {
|
|
433
|
+
reminded = true;
|
|
434
|
+
messages.push({ role: 'user', content: 'A terminal tool call is required. Call a terminal tool to end this run.' });
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
outcome = mkOutcome('no_terminal', 'Stopped: no terminal tool was called after the reminder.', [], metrics, toolsCalled);
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
349
440
|
// Model answered in prose with no tool call — treat as a neutral Done.
|
|
350
441
|
outcome = mkOutcome('done', tracked.text || 'no further actions',
|
|
351
442
|
[{ kind: 'self_assessment', description: tracked.text || '', data: null }], metrics, toolsCalled);
|
|
@@ -354,7 +445,16 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
|
354
445
|
messages.push({ role: 'assistant', content: tracked.text || '', tool_calls: calls });
|
|
355
446
|
const idToTool = Object.fromEntries(calls.map((c) => [c.id, c.name]));
|
|
356
447
|
|
|
357
|
-
const
|
|
448
|
+
const terminalCalls = calls.filter(c => terminalByName.has(c.name));
|
|
449
|
+
const ordinaryCalls = calls.filter(c => !terminalByName.has(c.name));
|
|
450
|
+
const proposal = buildProposal(tracked.model_used, calls, toolTimeouts, true, terminals.length > 0);
|
|
451
|
+
const signature = calls.map(c => `${c.name}(${JSON.stringify(stableValue(c.arguments || {}))})`).sort().join('|');
|
|
452
|
+
const observe = (results) => {
|
|
453
|
+
if (config.noProgressGuard === false || outcome) return;
|
|
454
|
+
const step = guard.observe(signature, results.some(r => r.status === 'succeeded' && mutating.has(idToTool[r.action_id])));
|
|
455
|
+
if (step === 'break') outcome = mkOutcome('stalled', `Stopped: repeated the same action ${guard.repeats} times without changing anything — no progress was being made.`, [], metrics, toolsCalled);
|
|
456
|
+
if (step === 'nudge') messages.push({ role: 'user', content: NO_PROGRESS_NUDGE });
|
|
457
|
+
};
|
|
358
458
|
|
|
359
459
|
// 2. VERIFY — static gate. Never execute an unverified proposal.
|
|
360
460
|
let check;
|
|
@@ -372,6 +472,9 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
|
372
472
|
messages.push({ role: 'tool_result', tool_use_id: c.id,
|
|
373
473
|
content: JSON.stringify({ error: `runtime rejected proposal: ${JSON.stringify(check.issues)}` }) });
|
|
374
474
|
}
|
|
475
|
+
metrics.tool_calls += calls.length;
|
|
476
|
+
metrics.actions_failed += calls.length;
|
|
477
|
+
observe([]);
|
|
375
478
|
continue;
|
|
376
479
|
}
|
|
377
480
|
|
|
@@ -380,8 +483,40 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
|
380
483
|
let finishAnswer = null;
|
|
381
484
|
let result;
|
|
382
485
|
try {
|
|
383
|
-
|
|
384
|
-
|
|
486
|
+
const results = [];
|
|
487
|
+
const executeChecked = async (group, callback) => {
|
|
488
|
+
const groupProposal = terminals.length ? buildProposal(tracked.model_used, group, toolTimeouts, true, true) : proposal;
|
|
489
|
+
const verified = terminals.length ? JSON.parse(await rt.verifyProposal(groupProposal)) : check;
|
|
490
|
+
if (!verified.valid) return { results: group.map(c => ({ action_id: c.id, status: 'failed', error: `runtime rejected proposal: ${JSON.stringify(verified.issues)}` })) };
|
|
491
|
+
return JSON.parse(await executeProposal(rt, groupProposal, callback));
|
|
492
|
+
};
|
|
493
|
+
if (ordinaryCalls.length) {
|
|
494
|
+
const ordinary = await executeChecked(ordinaryCalls,
|
|
495
|
+
makeToolCallback(tools, toolTimeouts, (a) => { finishAnswer = a; }));
|
|
496
|
+
results.push(...(ordinary.results || []));
|
|
497
|
+
}
|
|
498
|
+
for (const c of terminalCalls) {
|
|
499
|
+
let refusal = terminalCalls.length !== 1 ? 'Exactly one terminal call is allowed per turn.'
|
|
500
|
+
: ordinaryCalls.some(call => !results.some(r => r.action_id === call.id && r.status === 'succeeded')) ? 'Terminal call refused: another tool failed.' : null;
|
|
501
|
+
if (refusal !== null) results.push({ action_id: c.id, status: 'failed', error: refusal });
|
|
502
|
+
else {
|
|
503
|
+
const originalArgs = JSON.parse(JSON.stringify(c.arguments || {}));
|
|
504
|
+
const accepted = await executeChecked([c], makeToolCallback({ [c.name]: async () => {
|
|
505
|
+
// Execution's full JSON Schema check runs before this callback.
|
|
506
|
+
let verdict;
|
|
507
|
+
try { verdict = await terminalByName.get(c.name).validate(JSON.parse(JSON.stringify(originalArgs))); }
|
|
508
|
+
catch (e) { throw new Error((typeof e?.message === 'string' ? e.message : String(e)) || 'Terminal validator refused the call.'); }
|
|
509
|
+
if (verdict !== true) throw new Error(typeof verdict === 'string' && verdict ? verdict : 'Terminal validator refused the call.');
|
|
510
|
+
return originalArgs;
|
|
511
|
+
} }, toolTimeouts));
|
|
512
|
+
results.push(...(accepted.results || []));
|
|
513
|
+
if ((accepted.results || []).some(r => r.action_id === c.id && r.status === 'succeeded')) {
|
|
514
|
+
outcome = mkOutcome('success', `Accepted terminal tool: ${c.name}`, [{ kind: 'tool_result', description: c.name, data: c.arguments || {} }], metrics, toolsCalled);
|
|
515
|
+
outcome.terminal_tool = { name: c.name, arguments: c.arguments || {} };
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
result = { results };
|
|
385
520
|
} catch (e) {
|
|
386
521
|
outcome = mkOutcome('failure', `execution failed: ${e.message || e}`,
|
|
387
522
|
[{ kind: 'stop_reason', description: 'executeProposal error', data: null }], metrics, toolsCalled);
|
|
@@ -402,13 +537,15 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
|
402
537
|
}
|
|
403
538
|
|
|
404
539
|
// 5. Terminal? finish() succeeded -> success.
|
|
405
|
-
if (finishAnswer !== null) {
|
|
540
|
+
if (!terminals.length && finishAnswer !== null) {
|
|
406
541
|
outcome = mkOutcome('success', finishAnswer,
|
|
407
542
|
[{ kind: 'tool_result', description: 'finish called', data: { answer: finishAnswer } }], metrics, toolsCalled);
|
|
408
543
|
}
|
|
544
|
+
observe(result.results || []);
|
|
409
545
|
// else: loop for the next proposal.
|
|
410
546
|
}
|
|
411
547
|
|
|
548
|
+
outcome.tools_called = [...toolsCalled].sort();
|
|
412
549
|
// Run-trace bracket (close). Report the terminal AgentOutcome to the daemon so
|
|
413
550
|
// CarHost shows the run's final status and stops streaming it. Await the ack
|
|
414
551
|
// before returning (the connection may close right after) so a healthy run is
|
|
@@ -425,6 +562,7 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
|
|
|
425
562
|
// AgentOutcome. Add it only after runs.complete so the wire shape stays
|
|
426
563
|
// unchanged. Null reports an older daemon or unacknowledged runs.start.
|
|
427
564
|
outcome.run_id = runId;
|
|
565
|
+
outcome.transcript = JSON.parse(JSON.stringify(messages));
|
|
428
566
|
return outcome;
|
|
429
567
|
}
|
|
430
568
|
|
|
@@ -514,7 +652,7 @@ async function runChatTurn(
|
|
|
514
652
|
// conversation breakpoint.
|
|
515
653
|
const tracked = await inferTurn(rt, {
|
|
516
654
|
model: selectedModel ?? config.defaultModel ?? null,
|
|
517
|
-
maxTokens: config.maxTokens ??
|
|
655
|
+
maxTokens: config.maxTokens ?? 4096,
|
|
518
656
|
toolSchemas,
|
|
519
657
|
messages,
|
|
520
658
|
});
|
|
@@ -710,7 +848,7 @@ async function main(config) {
|
|
|
710
848
|
} else {
|
|
711
849
|
console.log(`${outcome.status} — ${outcome.summary}`);
|
|
712
850
|
}
|
|
713
|
-
process.exit(
|
|
851
|
+
process.exit(['failure', 'stalled', 'no_terminal'].includes(outcome.status) ? 1 : 0);
|
|
714
852
|
}
|
|
715
853
|
|
|
716
854
|
module.exports = { main, runAgent, runChatTurn, serveChat };
|
package/index.d.ts
CHANGED
|
@@ -38,6 +38,8 @@ export interface AgentToolSchema {
|
|
|
38
38
|
description: string;
|
|
39
39
|
parameters: Record<string, unknown>;
|
|
40
40
|
timeoutMs?: number;
|
|
41
|
+
/** Successful new signatures count as state changes for the task guard. */
|
|
42
|
+
mutating?: boolean;
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
export interface AgentToolContext {
|
|
@@ -50,8 +52,9 @@ export type AgentTool = (
|
|
|
50
52
|
context: AgentToolContext,
|
|
51
53
|
) => unknown | Promise<unknown>;
|
|
52
54
|
|
|
55
|
+
/** stalled: repeated actions without progress; no_terminal: second text-only turn when a terminal is required. Both are unsuccessful endings. */
|
|
53
56
|
export type AgentOutcomeStatus =
|
|
54
|
-
| 'success' | 'partial_success' | 'done' | 'give_up' | 'timeout' | 'failure';
|
|
57
|
+
| 'success' | 'partial_success' | 'done' | 'give_up' | 'timeout' | 'failure' | 'stalled' | 'no_terminal';
|
|
55
58
|
|
|
56
59
|
export interface AgentOutcome {
|
|
57
60
|
/** Durable trace key, or null when runs.start was unavailable/unacknowledged. */
|
|
@@ -67,6 +70,15 @@ export interface AgentOutcome {
|
|
|
67
70
|
};
|
|
68
71
|
tools_called: string[];
|
|
69
72
|
timestamp: string;
|
|
73
|
+
transcript: AgentMessage[];
|
|
74
|
+
terminal_tool?: { name: string; arguments: Record<string, unknown> };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export type AgentMessage = Record<string, unknown> & { role: string };
|
|
78
|
+
export interface AgentTerminalTool extends AgentToolSchema {
|
|
79
|
+
/** A refused terminal call returns to the model as a tool result so it can repair the call.
|
|
80
|
+
* Runtime validates the schema first. Exactly true accepts; all other results refuse. Empty strings use a default reason; throws use the error message (default if empty). */
|
|
81
|
+
validate(args: Record<string, unknown>): boolean | string | Promise<boolean | string>;
|
|
70
82
|
}
|
|
71
83
|
|
|
72
84
|
/** Declarative input consumed by `car-runtime/agent-loop`. */
|
|
@@ -74,12 +86,23 @@ export interface AgentLoopConfig {
|
|
|
74
86
|
agentId?: string;
|
|
75
87
|
agentName: string;
|
|
76
88
|
identity: string;
|
|
77
|
-
toolSchemas?: AgentToolSchema[];
|
|
89
|
+
toolSchemas?: AgentToolSchema[] | null;
|
|
78
90
|
tools?: Record<string, AgentTool>;
|
|
79
91
|
policies?: Array<[string, string, string?, string?, string?, string?]>;
|
|
80
92
|
defaultModel?: string | null;
|
|
93
|
+
/** Output budget; defaults to 4096 for task and chat turns. */
|
|
81
94
|
maxTokens?: number;
|
|
82
|
-
|
|
95
|
+
/** Task default 8; null uses the default, 0 or Infinity removes the task cap. Chat retains its existing cap semantics. */
|
|
96
|
+
maxTurns?: number | null;
|
|
97
|
+
/** Task-only validated endings; replace finish and imply requireTerminal when nonempty. */
|
|
98
|
+
terminalTools?: AgentTerminalTool[] | null;
|
|
99
|
+
/** Task-only; defaults false. One text-only turn gets a reminder; the second ends as no_terminal. */
|
|
100
|
+
requireTerminal?: boolean;
|
|
101
|
+
/** Task-only; defaults true. Repeat 3 nudges, repeat 6 stalls; 8 turns without mutation only nudges. False disables it. */
|
|
102
|
+
noProgressGuard?: boolean;
|
|
103
|
+
/** Old system messages are replaced; unanswered calls are closed without rerunning them; the guard starts fresh.
|
|
104
|
+
* Prior tool calls must include arguments as a JSON object; absent or non-object arguments are refused before runs.start, after JSON serialization. */
|
|
105
|
+
priorMessages?: AgentMessage[];
|
|
83
106
|
targetOutcome?: string;
|
|
84
107
|
standingGoal?: string | null;
|
|
85
108
|
intervalSecs?: number;
|
|
@@ -88,7 +111,7 @@ export interface AgentLoopConfig {
|
|
|
88
111
|
}
|
|
89
112
|
|
|
90
113
|
export interface AgentLoopOptions {
|
|
91
|
-
maxTurns?: number;
|
|
114
|
+
maxTurns?: number | null;
|
|
92
115
|
}
|
|
93
116
|
|
|
94
117
|
export interface AgentChatTurnOptions {
|