car-runtime 0.62.0 → 0.63.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/agent-loop.js CHANGED
@@ -43,7 +43,7 @@ const FINISH_SCHEMA = {
43
43
  },
44
44
  };
45
45
 
46
- function buildProposal(modelUsed, toolCalls, toolTimeouts = {}, independent = false, continueOnFailure = false) {
46
+ function buildProposal(modelUsed, toolCalls, toolTimeouts = {}, 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.
@@ -54,8 +54,11 @@ function buildProposal(modelUsed, toolCalls, toolTimeouts = {}, independent = fa
54
54
  // it flows here as the action's per-call budget — without it the call is
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
+ // Every proposal carries an id: a real daemon refuses one without it
58
+ // ("active proposal raw submission requires an exact string id"), which
59
+ // is how runChatTurn's tools never ran (Parslee-ai/car#3847).
57
60
  return JSON.stringify({
58
- ...(independent ? { id: require('node:crypto').randomUUID() } : {}),
61
+ id: require('node:crypto').randomUUID(),
59
62
  source: modelUsed || 'model',
60
63
  actions: toolCalls.map((tc, i) => ({
61
64
  id: tc.id || `a${i}`,
@@ -153,6 +156,12 @@ function makeToolCallback(tools, toolTimeouts = {}, onFinish = null) {
153
156
  // same runtime talks to a blank daemon session, and remembering the old one's
154
157
  // registrations would leave the new session without its tools and policies.
155
158
  const RUNTIME_REGISTRATION = new WeakMap();
159
+ // The tools `registerAgentBasics()` adds. The daemon refuses to let
160
+ // `tools.register` shadow a tool already on the session, so a run that
161
+ // declares its own `write_file` or `edit_file` (the names the no-progress
162
+ // guard treats as mutating) must not register the built-ins first
163
+ // (Parslee-ai/car#3875).
164
+ const AGENT_BASICS = new Set(['read_file', 'write_file', 'edit_file', 'list_dir', 'find_files', 'grep_files', 'calculate']);
156
165
  const MAX_SETUP_ATTEMPTS = 3;
157
166
 
158
167
  // A runtime without `connectionEpoch` (a hand-built runtime-shaped object)
@@ -169,9 +178,13 @@ async function prepareRuntime(rt, toolSchemas, policies, terminalNames = new Set
169
178
  state = { epoch, basicsAttempted: false, tools: new Map(), policies: new Set() };
170
179
  RUNTIME_REGISTRATION.set(rt, state);
171
180
  }
172
- if (!state.basicsAttempted) {
181
+ const declaresBasic = toolSchemas.filter(schema => AGENT_BASICS.has(schema.name)).map(schema => schema.name);
182
+ if (declaresBasic.length && state.basicsRegistered) {
183
+ throw new Error(`this runtime already has CAR's built-in ${declaresBasic.join(', ')}; a run that declares its own must use a runtime that never registered the built-ins`);
184
+ }
185
+ if (!state.basicsAttempted && !declaresBasic.length) {
173
186
  state.basicsAttempted = true;
174
- try { await rt.registerAgentBasics(); } catch { /* unsupported on this daemon — fine */ }
187
+ try { await rt.registerAgentBasics(); state.basicsRegistered = true; } catch { /* unsupported on this daemon — fine */ }
175
188
  }
176
189
  for (const schema of toolSchemas) {
177
190
  const key = terminalNames.has(schema.name) ? JSON.stringify(schema) : schema.name;
@@ -200,9 +213,16 @@ async function closeRuntime(rt) {
200
213
  else if (typeof rt.disconnect === 'function') await rt.disconnect();
201
214
  }
202
215
 
216
+ // One daemon WebSocket frame is at most 16 MiB; the JSON-RPC envelope around
217
+ // a request takes a little of it. A request over this is refused before it is
218
+ // sent, so a transcript that grew past the frame (a resume near the limit plus
219
+ // the tool schemas, or a long run) never drops the connection mid-run
220
+ // (Parslee-ai/car#3873).
221
+ const MAX_REQUEST_BYTES = 16 * 1024 * 1024 - 64 * 1024;
222
+
203
223
  /** One request-shaped, cache-aware inference path for task and chat loops. */
204
224
  async function inferTurn(rt, { model, maxTokens, toolSchemas, messages, toolChoice = 'auto' }) {
205
- return JSON.parse(await rt.inferTrackedWithRequest(JSON.stringify({
225
+ const request = JSON.stringify({
206
226
  prompt: '',
207
227
  model: model ?? null,
208
228
  params: {
@@ -214,7 +234,12 @@ async function inferTurn(rt, { model, maxTokens, toolSchemas, messages, toolChoi
214
234
  tools: toolSchemas,
215
235
  messages,
216
236
  cache_control: true,
217
- })));
237
+ });
238
+ const bytes = Buffer.byteLength(request, 'utf8');
239
+ if (bytes > MAX_REQUEST_BYTES) {
240
+ throw new Error(`inference request is ${bytes} bytes; one daemon frame carries at most ${MAX_REQUEST_BYTES} bytes, so the transcript and tool schemas must be smaller`);
241
+ }
242
+ return JSON.parse(await rt.inferTrackedWithRequest(request));
218
243
  }
219
244
 
220
245
  /** Record one completed inference before any requested action executes. */
@@ -288,9 +313,20 @@ function stableValue(value) {
288
313
  if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(k => [k, stableValue(value[k])]));
289
314
  return value;
290
315
  }
316
+ // The daemon takes one WebSocket frame of at most 16 MiB (tokio-tungstenite's
317
+ // default), and every request of a resumed run carries the whole transcript.
318
+ // A larger resume dropped the connection mid-run (Parslee-ai/car#3873); it is
319
+ // refused up front instead, leaving 1 MiB for the rest of the request.
320
+ const MAX_RESUME_BYTES = 15 * 1024 * 1024;
321
+
291
322
  function resumeMessages(prior) {
292
323
  if (!Array.isArray(prior)) throw new Error('priorMessages must be a list');
293
- const copied = JSON.parse(JSON.stringify(prior));
324
+ const serialized = JSON.stringify(prior);
325
+ const bytes = Buffer.byteLength(serialized, 'utf8');
326
+ if (bytes > MAX_RESUME_BYTES) {
327
+ throw new Error(`priorMessages is ${bytes} bytes; a resume may carry at most ${MAX_RESUME_BYTES} bytes (15 MiB), because every request sends the whole transcript in one 16 MiB daemon frame`);
328
+ }
329
+ const copied = JSON.parse(serialized);
294
330
  // Keep one entry per call because provider IDs may repeat.
295
331
  const pending = [];
296
332
  for (const m of copied) {
@@ -455,7 +491,7 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
455
491
 
456
492
  const terminalCalls = calls.filter(c => terminalByName.has(c.name));
457
493
  const ordinaryCalls = calls.filter(c => !terminalByName.has(c.name));
458
- const proposal = buildProposal(tracked.model_used, calls, toolTimeouts, true, terminals.length > 0);
494
+ const proposal = buildProposal(tracked.model_used, calls, toolTimeouts, terminals.length > 0);
459
495
  const signature = calls.map(c => `${c.name}(${JSON.stringify(stableValue(c.arguments || {}))})`).sort().join('|');
460
496
  const observe = (results) => {
461
497
  if (config.noProgressGuard === false || outcome) return;
@@ -493,7 +529,7 @@ async function runAgentWithRuntime(rt, config, goal, { maxTurns } = {}) {
493
529
  try {
494
530
  const results = [];
495
531
  const executeChecked = async (group, callback) => {
496
- const groupProposal = terminals.length ? buildProposal(tracked.model_used, group, toolTimeouts, true, true) : proposal;
532
+ const groupProposal = terminals.length ? buildProposal(tracked.model_used, group, toolTimeouts, true) : proposal;
497
533
  const verified = terminals.length ? JSON.parse(await rt.verifyProposal(groupProposal)) : check;
498
534
  if (!verified.valid) return { results: group.map(c => ({ action_id: c.id, status: 'failed', error: `runtime rejected proposal: ${JSON.stringify(verified.issues)}` })) };
499
535
  return JSON.parse(await executeProposal(rt, groupProposal, callback));
@@ -653,58 +689,70 @@ async function runChatTurn(
653
689
  const toolsCalled = new Set();
654
690
  let terminal = null;
655
691
  let finalText = '';
656
- for (let turns = 0; turns < turnsCap; turns++) {
657
- metrics.turns = turns + 1;
658
- // Same cached request form as the one-shot loop. A chat thread grows for
659
- // the whole session, so it is the path that benefits most from the moving
660
- // conversation breakpoint.
661
- const tracked = await inferTurn(rt, {
662
- model: selectedModel ?? config.defaultModel ?? null,
663
- maxTokens: config.maxTokens ?? 4096,
664
- toolSchemas,
665
- messages,
666
- });
667
- const calls = tracked.tool_calls || [];
668
- calls.forEach((c, i) => { c.id = c.id || `a${i}`; });
669
- await recordModelTurn(
670
- rt, runId, turns + 1, tracked, selectedModel ?? config.defaultModel,
671
- );
672
- if (calls.length === 0) {
673
- finalText = tracked.text || '';
674
- messages.push({ role: 'assistant', content: finalText });
675
- terminal = 'done';
676
- break;
677
- }
678
- messages.push({ role: 'assistant', content: tracked.text || '', tool_calls: calls });
679
- const idToTool = Object.fromEntries(calls.map((c) => [c.id, c.name]));
680
- // Surface non-finish tool calls as progress so the host UI can show them.
681
- for (const c of calls) {
682
- if (c.name !== 'finish') await rt.chatEvent(sessionId, 'tool_call', c.name).catch(() => {});
683
- }
684
- const proposal = buildProposal(tracked.model_used, calls, toolTimeouts);
685
- const check = JSON.parse(await rt.verifyProposal(proposal));
686
- if (!check.valid) {
692
+ // Any throw after the run started (inference, verification, execution)
693
+ // completes the run as a failure once, then reaches the caller, so served
694
+ // chat still reports it and the trace is never left open (car#3873).
695
+ try {
696
+ for (let turns = 0; turns < turnsCap; turns++) {
697
+ metrics.turns = turns + 1;
698
+ // Same cached request form as the one-shot loop. A chat thread grows for
699
+ // the whole session, so it is the path that benefits most from the moving
700
+ // conversation breakpoint.
701
+ const tracked = await inferTurn(rt, {
702
+ model: selectedModel ?? config.defaultModel ?? null,
703
+ maxTokens: config.maxTokens ?? 4096,
704
+ toolSchemas,
705
+ messages,
706
+ });
707
+ const calls = tracked.tool_calls || [];
708
+ calls.forEach((c, i) => { c.id = c.id || `a${i}`; });
709
+ await recordModelTurn(
710
+ rt, runId, turns + 1, tracked, selectedModel ?? config.defaultModel,
711
+ );
712
+ if (calls.length === 0) {
713
+ finalText = tracked.text || '';
714
+ messages.push({ role: 'assistant', content: finalText });
715
+ terminal = 'done';
716
+ break;
717
+ }
718
+ messages.push({ role: 'assistant', content: tracked.text || '', tool_calls: calls });
719
+ const idToTool = Object.fromEntries(calls.map((c) => [c.id, c.name]));
720
+ // Surface non-finish tool calls as progress so the host UI can show them.
687
721
  for (const c of calls) {
688
- messages.push({ role: 'tool_result', tool_use_id: c.id,
689
- content: JSON.stringify({ error: `runtime rejected proposal: ${JSON.stringify(check.issues)}` }) });
722
+ if (c.name !== 'finish') await rt.chatEvent(sessionId, 'tool_call', c.name).catch(() => {});
690
723
  }
691
- continue;
724
+ const proposal = buildProposal(tracked.model_used, calls, toolTimeouts);
725
+ const check = JSON.parse(await rt.verifyProposal(proposal));
726
+ if (!check.valid) {
727
+ for (const c of calls) {
728
+ messages.push({ role: 'tool_result', tool_use_id: c.id,
729
+ content: JSON.stringify({ error: `runtime rejected proposal: ${JSON.stringify(check.issues)}` }) });
730
+ }
731
+ continue;
732
+ }
733
+ // Same callback the one-shot loop uses, so the declared per-action budget
734
+ // and the request_id/AbortController cancel wiring reach tools on the
735
+ // --serve path too.
736
+ let finishAnswer = null;
737
+ const result = JSON.parse(await executeProposal(rt, proposal,
738
+ makeToolCallback(tools, toolTimeouts, (a) => { finishAnswer = a; })));
739
+ for (const r of (result.results || [])) {
740
+ const ok = r.status === 'succeeded';
741
+ if (ok && idToTool[r.action_id]) toolsCalled.add(idToTool[r.action_id]);
742
+ messages.push({ role: 'tool_result', tool_use_id: r.action_id,
743
+ content: JSON.stringify(ok ? (r.output ?? {}) : { error: r.error }) });
744
+ metrics.tool_calls += 1;
745
+ if (ok) metrics.actions_succeeded += 1; else metrics.actions_failed += 1;
746
+ }
747
+ if (finishAnswer !== null) { finalText = finishAnswer; terminal = 'success'; break; }
692
748
  }
693
- // Same callback the one-shot loop uses, so the declared per-action budget
694
- // and the request_id/AbortController cancel wiring reach tools on the
695
- // --serve path too.
696
- let finishAnswer = null;
697
- const result = JSON.parse(await executeProposal(rt, proposal,
698
- makeToolCallback(tools, toolTimeouts, (a) => { finishAnswer = a; })));
699
- for (const r of (result.results || [])) {
700
- const ok = r.status === 'succeeded';
701
- if (ok && idToTool[r.action_id]) toolsCalled.add(idToTool[r.action_id]);
702
- messages.push({ role: 'tool_result', tool_use_id: r.action_id,
703
- content: JSON.stringify(ok ? (r.output ?? {}) : { error: r.error }) });
704
- metrics.tool_calls += 1;
705
- if (ok) metrics.actions_succeeded += 1; else metrics.actions_failed += 1;
749
+ } catch (e) {
750
+ if (runId !== null) {
751
+ const outcome = mkOutcome('failure', `chat turn failed: ${e?.message ?? e}`,
752
+ [{ kind: 'stop_reason', description: 'chat turn error', data: null }], metrics, toolsCalled);
753
+ try { await rt.runsComplete(JSON.stringify({ run_id: runId, outcome })); } catch { /* daemon lacks runs.* */ }
706
754
  }
707
- if (finishAnswer !== null) { finalText = finishAnswer; terminal = 'success'; break; }
755
+ throw e;
708
756
  }
709
757
  if (finalText) await rt.chatEvent(sessionId, 'token', finalText).catch(() => {});
710
758
  await rt.chatEvent(sessionId, 'done', finalText).catch(() => {});
@@ -457,6 +457,19 @@ const DAEMON_WRAPPER_ROWS = Object.freeze([
457
457
  },
458
458
  "role": "operator"
459
459
  },
460
+ {
461
+ "javascript": {
462
+ "generated": true,
463
+ "name": "agentPermissionsApplyStanding"
464
+ },
465
+ "method": "agent_permissions.apply_standing",
466
+ "owner": "CarRuntime",
467
+ "python": {
468
+ "generated": true,
469
+ "name": "agent_permissions_apply_standing"
470
+ },
471
+ "role": "operator"
472
+ },
460
473
  {
461
474
  "javascript": {
462
475
  "generated": true,
@@ -938,6 +951,19 @@ const DAEMON_WRAPPER_ROWS = Object.freeze([
938
951
  },
939
952
  "role": "operator"
940
953
  },
954
+ {
955
+ "javascript": {
956
+ "generated": true,
957
+ "name": "auditExport"
958
+ },
959
+ "method": "audit.export",
960
+ "owner": "HostClient",
961
+ "python": {
962
+ "generated": true,
963
+ "name": "audit_export"
964
+ },
965
+ "role": "host"
966
+ },
941
967
  {
942
968
  "javascript": {
943
969
  "generated": true,
@@ -3915,6 +3941,19 @@ const DAEMON_WRAPPER_ROWS = Object.freeze([
3915
3941
  },
3916
3942
  "role": "host"
3917
3943
  },
3944
+ {
3945
+ "javascript": {
3946
+ "generated": true,
3947
+ "name": "latticeOrgGrant"
3948
+ },
3949
+ "method": "lattice.org.grant",
3950
+ "owner": "HostClient",
3951
+ "python": {
3952
+ "generated": true,
3953
+ "name": "lattice_org_grant"
3954
+ },
3955
+ "role": "host"
3956
+ },
3918
3957
  {
3919
3958
  "javascript": {
3920
3959
  "generated": true,
package/docs/ASSISTANT.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Parslee Core — the `car do` assistant
2
2
 
3
- > Describes CAR **0.62.0**. Check yours with `car --version`; if it
3
+ > Describes CAR **0.63.0**. Check yours with `car --version`; if it
4
4
  > differs, prefer `car help <command>` on your own binary over this page.
5
5
 
6
6
  CAR ships with a general-purpose agent that works out of the box: no tools to
package/docs/CLI.md CHANGED
@@ -6,13 +6,13 @@
6
6
  > below; a new subcommand cannot ship without appearing here the next time
7
7
  > this script runs. To regenerate: `bash scripts/gen-cli-docs.sh`.
8
8
  >
9
- > 88 top-level commands, 190 nested subcommands
9
+ > 89 top-level commands, 191 nested subcommands
10
10
  > (one level deep) — counted from the live binary at generation time, not
11
11
  > typed by hand.
12
12
 
13
13
  ## Finding your way around
14
14
 
15
- `car` is one binary with 88 subcommands spanning several different jobs:
15
+ `car` is one binary with 89 subcommands spanning several different jobs:
16
16
  running the built-in agent, coding, local model management, OS integrations,
17
17
  and installing other people's agents on your machine. This map groups the
18
18
  commands people actually reach for; the full alphabetical reference with every
@@ -195,6 +195,7 @@ commands on a cadence via launchd / cron / schtasks).
195
195
  | [`car coder-overlays`](#car-coder-overlays) | Show the approved harness overlays — system-prompt and tool-description text applied through `evolution.run` — that every native coder session starts with, or clear them. Nothing removes an applied overlay on its own; `--clear` is how one is taken out of force. Reads the local coder state directory; no daemon needed |
196
196
  | [`car keys`](#car-keys) | Store cloud-provider API keys in CAR's secret store, so a native-app user never sets an environment variable (docs/proposals/native-secrets-no-env.md). Runtime reads process env first, then the secret store |
197
197
  | [`car heal`](#car-heal) | Inspect and operate the daemon's self-healing REPAIR loop: it reads a configured issue tracker, runs a coder session, gates the result on a multi-model panel, and opens a pull request. It never merges |
198
+ | [`car audit`](#car-audit) | Export the owner's record of what each agent did and who approved it |
198
199
  | [`car ledger`](#car-ledger) | Review and grade the owner's decision ledger |
199
200
  | [`car selfheal`](#car-selfheal) | Inspect and operate the daemon's deterministic self-healing detector |
200
201
  | [`car daemon`](#car-daemon) | Start the daemon server (delegates to car-server binary) |
@@ -1228,6 +1229,44 @@ Options:
1228
1229
  Print help (see a summary with '-h')
1229
1230
  ```
1230
1231
 
1232
+ ### car audit
1233
+
1234
+ ```text
1235
+ Export the owner's record of what each agent did and who approved it
1236
+
1237
+ Usage: car audit <COMMAND>
1238
+
1239
+ Commands:
1240
+ export Export what each agent did and what was approved, by whom and when, as one JSON document.
1241
+ Joins the per-client event journals, the permission approvals and rejections in approvals.jsonl,
1242
+ the host approvals with their resolvers, and the policy denials. Run content is redacted. States
1243
+ the earliest record it holds and each journal's hash chain status; it does not switch hash
1244
+ chaining on. Works with the daemon down
1245
+ help Print this message or the help of the given subcommand(s)
1246
+
1247
+ Options:
1248
+ -h, --help Print help
1249
+ ```
1250
+
1251
+ #### car audit export
1252
+
1253
+ ```text
1254
+ Export what each agent did and what was approved, by whom and when, as one JSON document. Joins the
1255
+ per-client event journals, the permission approvals and rejections in approvals.jsonl, the host
1256
+ approvals with their resolvers, and the policy denials. Run content is redacted. States the earliest
1257
+ record it holds and each journal's hash chain status; it does not switch hash chaining on. Works
1258
+ with the daemon down
1259
+
1260
+ Usage: car audit export [OPTIONS]
1261
+
1262
+ Options:
1263
+ --since <SINCE> Only records at or after this RFC 3339 time
1264
+ --until <UNTIL> Only records before this RFC 3339 time
1265
+ --agent <AGENT> Only records that name this agent
1266
+ --output <OUTPUT> Write the export to this new file (owner-only) instead of printing it
1267
+ -h, --help Print help
1268
+ ```
1269
+
1231
1270
  ### car ledger
1232
1271
 
1233
1272
  ```text
package/docs/MCP.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # CAR as an MCP server
2
2
 
3
- > Describes CAR **0.62.0**. Check yours with `car --version`; if it
3
+ > Describes CAR **0.63.0**. Check yours with `car --version`; if it
4
4
  > differs, prefer `car help <command>` on your own binary over this page.
5
5
 
6
6
  Wire CAR's graph memory, skill storage, static plan verification, and policy
package/ensure-native.js CHANGED
@@ -16,9 +16,25 @@ const fs = require('node:fs');
16
16
  const path = require('node:path');
17
17
  const { spawnSync } = require('node:child_process');
18
18
 
19
- function ensureNative(paths) {
20
- if (paths.every((p) => fs.existsSync(p))) return;
21
- if (process.env.CAR_RUNTIME_SKIP_DOWNLOAD === '1') return;
19
+ // How long a first use waits for another process's install before giving up.
20
+ const LOCK_WAIT_MS = 10 * 60 * 1000;
21
+ // A lock file still empty this long after it was made has lost its writer.
22
+ const EMPTY_LOCK_GRACE_MS = 10 * 1000;
23
+
24
+ function sleep(ms) {
25
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
26
+ }
27
+
28
+ function alive(pid) {
29
+ try {
30
+ process.kill(pid, 0);
31
+ return true;
32
+ } catch (e) {
33
+ return e.code === 'EPERM';
34
+ }
35
+ }
36
+
37
+ function runInstall() {
22
38
  const install = path.join(__dirname, 'install.js');
23
39
  const result = spawnSync(process.execPath, [install], {
24
40
  cwd: __dirname,
@@ -38,4 +54,114 @@ function ensureNative(paths) {
38
54
  }
39
55
  }
40
56
 
57
+ // How old a `.takeover` guard must be before a waiter treats it as left by a
58
+ // process that died mid-takeover.
59
+ const TAKEOVER_GRACE_MS = 30 * 1000;
60
+
61
+ // The same file: device, inode and birth time. An inode number can be reused at
62
+ // once for a new file; its birth time differs. Writes leave birth time alone.
63
+ const sameFile = (a, b) =>
64
+ a.dev === b.dev && a.ino === b.ino && a.birthtimeMs === b.birthtimeMs;
65
+
66
+ // Remove the abandoned lock `seen` (its stat when it was judged abandoned).
67
+ // Takeovers are serialized by an exclusive `.takeover` guard, and the lock path
68
+ // is unlinked only while it is still that same file (dev and inode, not
69
+ // content): a live lock made after the judgement is never touched, and no
70
+ // two waiters remove locks at once (car#4296).
71
+ function takeOver(lock, seen) {
72
+ const guard = `${lock}.takeover`;
73
+ let fd;
74
+ try {
75
+ fd = fs.openSync(guard, 'wx');
76
+ } catch (err) {
77
+ if (err.code !== 'EEXIST') throw err;
78
+ try {
79
+ if (Date.now() - fs.statSync(guard).mtimeMs > TAKEOVER_GRACE_MS) fs.unlinkSync(guard);
80
+ } catch (e) {
81
+ if (e.code !== 'ENOENT') throw e;
82
+ }
83
+ return; // another waiter is taking over; look again
84
+ }
85
+ try {
86
+ let current;
87
+ try {
88
+ current = fs.statSync(lock);
89
+ } catch (err) {
90
+ if (err.code === 'ENOENT') return;
91
+ throw err;
92
+ }
93
+ if (sameFile(current, seen)) fs.unlinkSync(lock);
94
+ } finally {
95
+ fs.closeSync(fd);
96
+ try {
97
+ fs.unlinkSync(guard);
98
+ } catch (_) {}
99
+ }
100
+ }
101
+
102
+ // Parallel first uses (worker pools, test runners) share one install
103
+ // (car#4296): the first takes `.install.lock` (created exclusively, holding its
104
+ // pid) and runs install.js; the others wait for the artifacts. A lock whose
105
+ // holder has exited is taken over. The lock only saves duplicate downloads:
106
+ // install.js writes each artifact to a file of its own and renames it into
107
+ // place, so even two installs at once leave only complete artifacts.
108
+ function ensureNative(paths) {
109
+ const present = () => paths.every((p) => fs.existsSync(p));
110
+ if (present()) return;
111
+ if (process.env.CAR_RUNTIME_SKIP_DOWNLOAD === '1') return;
112
+ const lock = path.join(__dirname, '.install.lock');
113
+ const deadline = Date.now() + LOCK_WAIT_MS;
114
+ for (;;) {
115
+ if (Date.now() > deadline) {
116
+ throw new Error(
117
+ `car-runtime: waited ${LOCK_WAIT_MS / 60000} minutes for another process ` +
118
+ `to fetch the native artifacts. Remove ${lock} if no install is running.`,
119
+ );
120
+ }
121
+ let fd;
122
+ try {
123
+ fd = fs.openSync(lock, 'wx');
124
+ } catch (e) {
125
+ if (e.code !== 'EEXIST') throw e;
126
+ if (present()) return;
127
+ let seen;
128
+ let content;
129
+ try {
130
+ seen = fs.statSync(lock);
131
+ content = fs.readFileSync(lock, 'utf8');
132
+ } catch (err) {
133
+ if (err.code === 'ENOENT') continue; // the holder just finished and removed it
134
+ throw err;
135
+ }
136
+ const holder = Number.parseInt(content, 10);
137
+ const age = Date.now() - seen.mtimeMs;
138
+ // A lock older than the whole wait is abandoned whatever its pid says: the
139
+ // operating system may have given a dead holder's pid to an unrelated
140
+ // process, which would otherwise look like a live install for ten minutes.
141
+ const abandoned =
142
+ age > LOCK_WAIT_MS ||
143
+ (Number.isInteger(holder) ? !alive(holder) : age > EMPTY_LOCK_GRACE_MS);
144
+ if (abandoned) {
145
+ takeOver(lock, seen);
146
+ continue;
147
+ }
148
+ sleep(200);
149
+ continue;
150
+ }
151
+ const mine = fs.fstatSync(fd);
152
+ try {
153
+ fs.writeSync(fd, String(process.pid));
154
+ // The holder before us may have finished between our check and our lock.
155
+ if (!present()) runInstall();
156
+ } finally {
157
+ fs.closeSync(fd);
158
+ // Remove the lock only while it is still this process's own file.
159
+ try {
160
+ if (sameFile(fs.statSync(lock), mine)) fs.unlinkSync(lock);
161
+ } catch (_) {}
162
+ }
163
+ return;
164
+ }
165
+ }
166
+
41
167
  module.exports = { ensureNative };
package/index.d.ts CHANGED
@@ -695,6 +695,9 @@ export class CarRuntime {
695
695
  /** Generated daemon wrapper for `agent/getAuthenticatedExtendedCard` (operator). */
696
696
  agentGetAuthenticatedExtendedCard(paramsJson: string): Promise<string>;
697
697
 
698
+ /** Generated daemon wrapper for `agent_permissions.apply_standing` (operator). */
699
+ agentPermissionsApplyStanding(paramsJson: string): Promise<string>;
700
+
698
701
  /** Generated daemon wrapper for `agent_permissions.evaluate` (operator). */
699
702
  agentPermissionsEvaluate(paramsJson: string): Promise<string>;
700
703
 
@@ -1812,9 +1815,15 @@ export class CarRuntime {
1812
1815
  * manifests, worker specs, `declagents.json`, `tasks/`, `messaging.json`)
1813
1816
  * by any spelling that resolves to one, and do
1814
1817
  * not create a new non-ASCII name in CAR's state, run, token or secrets
1815
- * folder. The user's own files stay reachable.
1818
+ * folder. The user's own files stay reachable. The tools run as the
1819
+ * daemon user, follow symlinks, and are admitted at the session's default
1820
+ * tier with no prompt. `root`, an absolute folder, keeps `write_file` and
1821
+ * `edit_file` inside it: a target that resolves outside it, through a
1822
+ * symlink or `..` included, is refused naming the root. With no root,
1823
+ * writes reach any path the daemon user can. `bindSandbox` /
1824
+ * `bindSubstrate` confine the tools further.
1816
1825
  */
1817
- registerAgentBasics(): Promise<void>;
1826
+ registerAgentBasics(root?: string | undefined | null): Promise<void>;
1818
1827
 
1819
1828
  /**
1820
1829
  * Start an agent run on the daemon (agent run tracing). Brackets the
@@ -2146,7 +2155,7 @@ export class CarRuntime {
2146
2155
  hostDevices(): Promise<string>;
2147
2156
  /** `host.notify` — emit a user-facing host notification. */
2148
2157
  hostNotify(requestJson: string): Promise<string>;
2149
- /** `host.request_approval` — request approval for a gated action. */
2158
+ /** `host.request_approval` — request approval; JSON accepts present and only_if_floor_clear. */
2150
2159
  hostRequestApproval(requestJson: string): Promise<string>;
2151
2160
  /** `host.resolve_approval` — resolve one pending host approval. */
2152
2161
  hostResolveApproval(requestJson: string): Promise<string>;
@@ -4372,6 +4381,9 @@ export class HostClient {
4372
4381
  /** Generated host wrapper for `assistant.identity.set`. */
4373
4382
  assistantIdentitySet(paramsJson: string): Promise<string>;
4374
4383
 
4384
+ /** Generated host wrapper for `audit.export`. */
4385
+ auditExport(paramsJson: string): Promise<string>;
4386
+
4375
4387
  /** Generated host wrapper for `auth.accounts`. */
4376
4388
  authAccounts(paramsJson: string): Promise<string>;
4377
4389
 
@@ -4537,6 +4549,9 @@ export class HostClient {
4537
4549
  /** Generated host wrapper for `lattice.org.attest`. */
4538
4550
  latticeOrgAttest(paramsJson: string): Promise<string>;
4539
4551
 
4552
+ /** Generated host wrapper for `lattice.org.grant`. */
4553
+ latticeOrgGrant(paramsJson: string): Promise<string>;
4554
+
4540
4555
  /** Generated host wrapper for `lattice.org.policy`. */
4541
4556
  latticeOrgPolicy(paramsJson: string): Promise<string>;
4542
4557
 
package/install.js CHANGED
@@ -19,6 +19,7 @@ const fs = require('node:fs');
19
19
  const path = require('node:path');
20
20
  const http = require('node:http');
21
21
  const https = require('node:https');
22
+ const crypto = require('node:crypto');
22
23
  const { pipeline } = require('node:stream/promises');
23
24
 
24
25
  // Platform → asset names read from the canonical assets.json registry.
@@ -71,45 +72,85 @@ function get(url) {
71
72
  });
72
73
  }
73
74
 
75
+ // Whether `pid` names a live process (EPERM: alive, owned by someone else).
76
+ function alive(pid) {
77
+ try {
78
+ process.kill(pid, 0);
79
+ return true;
80
+ } catch (e) {
81
+ return e.code === 'EPERM';
82
+ }
83
+ }
84
+
85
+ // Remove partial downloads of `destPath` that no running install owns: one
86
+ // named for a process that has exited, or any (including the old shared
87
+ // `<dest>.part` form) over an hour old. A running install's partial file is
88
+ // never touched (car#4296: two first uses at once each deleted the other's).
89
+ function removeStaleParts(destPath) {
90
+ const dir = path.dirname(destPath);
91
+ const base = path.basename(destPath);
92
+ let names;
93
+ try {
94
+ names = fs.readdirSync(dir);
95
+ } catch (_) {
96
+ return;
97
+ }
98
+ for (const name of names) {
99
+ const file = path.join(dir, name);
100
+ const owned = name.startsWith(`${base}.`) && /^\.(\d+)\.[0-9a-f]+\.part$/.exec(name.slice(base.length));
101
+ let stale = false;
102
+ if (owned || name === `${base}.part`) {
103
+ // Over an hour old is stale whoever it names: a pid can be reused by an
104
+ // unrelated live process. Younger, a file is stale once its process exited.
105
+ try {
106
+ stale = Date.now() - fs.statSync(file).mtimeMs > 60 * 60 * 1000;
107
+ } catch (_) {}
108
+ if (!stale && owned) stale = !alive(Number(owned[1]));
109
+ }
110
+ if (stale) {
111
+ try {
112
+ fs.unlinkSync(file);
113
+ } catch (_) {}
114
+ }
115
+ }
116
+ }
117
+
74
118
  async function downloadAsset(assetName, destPath, { executable = false } = {}) {
75
119
  if (fs.existsSync(destPath)) {
76
120
  return { skipped: true };
77
121
  }
78
- const tmp = `${destPath}.part`;
79
- // Clean stale .part files from a prior crashed install — without
80
- // this, fs.createWriteStream's default flag is 'w' which truncates
81
- // (fine for content) but a half-written file from a *previous*
82
- // process exit between writeStream end + rename leaves an orphan
83
- // .part on disk that nothing cleans up. Best-effort unlink.
84
- if (fs.existsSync(tmp)) {
85
- try {
86
- fs.unlinkSync(tmp);
87
- } catch (_) {
88
- // Non-fatal — pipeline will overwrite with 'w' mode regardless.
89
- }
90
- }
122
+ removeStaleParts(destPath);
123
+ // This process's own partial file. Concurrent installs (two first uses at
124
+ // once, car#4296) each write their own and rename it into place; the rename
125
+ // is atomic, so `destPath` only ever holds a complete, executable artifact.
126
+ const tmp = `${destPath}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.part`;
91
127
  const version = pkgVersion();
92
128
  const base = process.env.CAR_RUNTIME_DOWNLOAD_BASE;
93
129
  const url = base
94
130
  ? `${base}/${assetName}`
95
131
  : `https://github.com/Parslee-ai/car-releases/releases/download/v${version}/${assetName}`;
96
132
  console.log(`[car-runtime] downloading ${url}`);
97
- const res = await get(url);
98
- await pipeline(res, fs.createWriteStream(tmp));
99
- fs.renameSync(tmp, destPath);
100
- if (executable && process.platform !== 'win32') {
101
- // npm strips the execute bit from non-bin files. car-server is
102
- // exec'd by bin/car-server through child_process.spawn, which
103
- // needs the bit. chmod here so the bin shim doesn't have to
104
- // re-stat + chmod on first run.
105
- try {
106
- fs.chmodSync(destPath, 0o755);
107
- } catch (e) {
108
- console.warn(
109
- `[car-runtime] chmod +x on ${destPath} failed: ${e.message}. ` +
110
- `\`npx --package=car-runtime car-server\` may fail with EACCES.`
111
- );
133
+ try {
134
+ const res = await get(url);
135
+ await pipeline(res, fs.createWriteStream(tmp, { flags: 'wx' }));
136
+ if (executable && process.platform !== 'win32') {
137
+ // npm strips the execute bit from non-bin files. car-server is
138
+ // exec'd by bin/car-server through child_process.spawn, which
139
+ // needs the bit. Set it before the rename, so no process can
140
+ // find the binary in place without it; a failure leaves nothing
141
+ // in place, and the next first use downloads again.
142
+ try {
143
+ fs.chmodSync(tmp, 0o755);
144
+ } catch (e) {
145
+ throw new Error(`chmod +x on ${tmp} failed: ${e.message}`);
146
+ }
112
147
  }
148
+ fs.renameSync(tmp, destPath);
149
+ } catch (err) {
150
+ try {
151
+ fs.unlinkSync(tmp);
152
+ } catch (_) {}
153
+ throw err;
113
154
  }
114
155
  console.log(`[car-runtime] installed ${assetName}`);
115
156
  return { skipped: false };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "car-runtime",
3
- "version": "0.62.0",
3
+ "version": "0.63.0",
4
4
  "carProtocolVersion": 3,
5
5
  "description": "Common Agent Runtime — a deterministic execution layer for AI agents",
6
6
  "main": "index.js",