@andorra-labs/code 0.1.18 → 0.1.19

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.
Files changed (277) hide show
  1. package/dist/src/account-jev-savings.d.ts +4 -0
  2. package/dist/src/account-jev-savings.js +92 -0
  3. package/dist/src/acp-agent.js +2 -2
  4. package/dist/src/agent-execution.js +347 -45
  5. package/dist/src/agent-mcp.js +7 -1
  6. package/dist/src/agent-modifiers.js +5 -7
  7. package/dist/src/analytics.d.ts +19 -1
  8. package/dist/src/analytics.js +9 -1
  9. package/dist/src/andorra/entry.js +15 -6
  10. package/dist/src/andorra/hosted.d.ts +8 -0
  11. package/dist/src/andorra/hosted.js +22 -3
  12. package/dist/src/andorra/streams.d.ts +49 -0
  13. package/dist/src/andorra/streams.js +98 -0
  14. package/dist/src/antigravity-acp.d.ts +28 -0
  15. package/dist/src/antigravity-acp.js +150 -0
  16. package/dist/src/antigravity-terminal.d.ts +2 -0
  17. package/dist/src/antigravity-terminal.js +214 -0
  18. package/dist/src/app-server/adaptive-routing-settings.d.ts +37 -0
  19. package/dist/src/app-server/adaptive-routing-settings.js +69 -0
  20. package/dist/src/app-server/artifact.d.ts +14 -0
  21. package/dist/src/app-server/artifact.js +46 -0
  22. package/dist/src/app-server/legal-protocol.d.ts +33 -0
  23. package/dist/src/app-server/legal-protocol.js +16 -0
  24. package/dist/src/app-server/protocol.d.ts +23 -3
  25. package/dist/src/app-server/protocol.js +3 -1
  26. package/dist/src/app-server/telemetry-protocol.d.ts +53 -0
  27. package/dist/src/app-server/telemetry-protocol.js +2 -0
  28. package/dist/src/app-server/telemetry.d.ts +38 -0
  29. package/dist/src/app-server/telemetry.js +163 -0
  30. package/dist/src/app-server/workspace.d.ts +3 -1
  31. package/dist/src/app-server/workspace.js +39 -8
  32. package/dist/src/app-server.d.ts +50 -25
  33. package/dist/src/app-server.js +1008 -400
  34. package/dist/src/auth/AuthManager.d.ts +11 -2
  35. package/dist/src/auth/AuthManager.js +56 -13
  36. package/dist/src/auth/index.d.ts +5 -1
  37. package/dist/src/auth/index.js +8 -1
  38. package/dist/src/auth/lifecycle.d.ts +13 -0
  39. package/dist/src/auth/lifecycle.js +109 -0
  40. package/dist/src/auth/store.d.ts +1 -0
  41. package/dist/src/auth/store.js +12 -0
  42. package/dist/src/auth/types.d.ts +12 -0
  43. package/dist/src/automation-runner.js +2 -0
  44. package/dist/src/automation-service.js +7 -2
  45. package/dist/src/benchmark-scores.d.ts +88 -0
  46. package/dist/src/benchmark-scores.js +302 -0
  47. package/dist/src/bridge/command.js +4 -1
  48. package/dist/src/bridge/control.js +2 -1
  49. package/dist/src/bridge/engines.d.ts +2 -0
  50. package/dist/src/bridge/engines.js +9 -0
  51. package/dist/src/bridge/host-ops.d.ts +2 -2
  52. package/dist/src/bridge/host-ops.js +4 -2
  53. package/dist/src/bridge/host.d.ts +2 -0
  54. package/dist/src/bridge/host.js +63 -12
  55. package/dist/src/bridge/protocol.d.ts +1 -0
  56. package/dist/src/bridge/protocol.js +1 -0
  57. package/dist/src/browser-panel-tool.d.ts +12 -0
  58. package/dist/src/browser-panel-tool.js +30 -3
  59. package/dist/src/browser-runner.js +53 -62
  60. package/dist/src/browser-server.js +10 -4
  61. package/dist/src/browser-session.d.ts +14 -0
  62. package/dist/src/browser-session.js +57 -12
  63. package/dist/src/browser-view.d.ts +40 -1
  64. package/dist/src/browser-view.js +163 -9
  65. package/dist/src/browser-window-style.d.ts +27 -0
  66. package/dist/src/browser-window-style.js +244 -0
  67. package/dist/src/claude-provider.d.ts +1 -0
  68. package/dist/src/claude-provider.js +77 -36
  69. package/dist/src/cli.js +235 -58
  70. package/dist/src/codex-provider.d.ts +1 -0
  71. package/dist/src/codex-provider.js +43 -7
  72. package/dist/src/coding-tools.d.ts +1 -0
  73. package/dist/src/coding-tools.js +19 -5
  74. package/dist/src/command-screens.d.ts +1 -1
  75. package/dist/src/command-screens.js +2 -2
  76. package/dist/src/commands.d.ts +8 -1
  77. package/dist/src/commands.js +67 -63
  78. package/dist/src/completion.js +5 -3
  79. package/dist/src/config.d.ts +14 -3
  80. package/dist/src/config.js +54 -16
  81. package/dist/src/context-budget.d.ts +11 -2
  82. package/dist/src/context-budget.js +23 -2
  83. package/dist/src/context-compaction.d.ts +10 -8
  84. package/dist/src/context-compaction.js +23 -24
  85. package/dist/src/deadline.js +1 -1
  86. package/dist/src/decision/DecisionManager.d.ts +5 -0
  87. package/dist/src/decision/DecisionManager.js +39 -2
  88. package/dist/src/decision/applyToolMenu.js +6 -2
  89. package/dist/src/decision/hostedPolicy.js +6 -4
  90. package/dist/src/decision/optimizationPolicy.d.ts +10 -0
  91. package/dist/src/decision/optimizationPolicy.js +23 -3
  92. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +2 -1
  93. package/dist/src/decision/providers/AndorraDecisionProvider.js +17 -7
  94. package/dist/src/decision/providers/index.js +1 -1
  95. package/dist/src/decision/toolFamilies.js +1 -1
  96. package/dist/src/decision/types.d.ts +2 -0
  97. package/dist/src/efficiency.d.ts +75 -1
  98. package/dist/src/efficiency.js +114 -3
  99. package/dist/src/extensions.d.ts +2 -0
  100. package/dist/src/extensions.js +30 -20
  101. package/dist/src/github-app/agent-writes.d.ts +1 -1
  102. package/dist/src/github-app/agent-writes.js +1 -1
  103. package/dist/src/github-app/event-source.d.ts +0 -5
  104. package/dist/src/github-app/event-source.js +1 -31
  105. package/dist/src/github-app/metrics.d.ts +2 -5
  106. package/dist/src/github-app/metrics.js +2 -14
  107. package/dist/src/github-app/review-loop.d.ts +5 -5
  108. package/dist/src/github-app/review-loop.js +1 -1
  109. package/dist/src/github-app/review-node.d.ts +2 -2
  110. package/dist/src/github-app/triggers.d.ts +3 -3
  111. package/dist/src/glob-search.d.ts +1 -0
  112. package/dist/src/glob-search.js +3 -0
  113. package/dist/src/google-provider.d.ts +5 -28
  114. package/dist/src/google-provider.js +6 -141
  115. package/dist/src/graph-editor-session.d.ts +1 -0
  116. package/dist/src/graph-editor-session.js +2 -0
  117. package/dist/src/graph-health.js +3 -1
  118. package/dist/src/graph-runner.js +19 -13
  119. package/dist/src/graph-selection.d.ts +3 -1
  120. package/dist/src/graph-selection.js +2 -2
  121. package/dist/src/graph-server.d.ts +8 -1
  122. package/dist/src/graph-server.js +45 -10
  123. package/dist/src/graph-sync.d.ts +2 -1
  124. package/dist/src/graph-sync.js +13 -0
  125. package/dist/src/graph-ui/app.js +19 -8
  126. package/dist/src/graph-ui/index.html +1 -1
  127. package/dist/src/graphs.d.ts +17 -1
  128. package/dist/src/graphs.js +51 -5
  129. package/dist/src/grok-provider.js +17 -14
  130. package/dist/src/hardened-runtime.js +7 -4
  131. package/dist/src/jev-savings.d.ts +4 -0
  132. package/dist/src/jev-savings.js +13 -0
  133. package/dist/src/legal/client.d.ts +25 -0
  134. package/dist/src/legal/client.js +47 -0
  135. package/dist/src/legal/command.d.ts +13 -0
  136. package/dist/src/legal/command.js +98 -0
  137. package/dist/src/legal/documents.d.ts +2 -0
  138. package/dist/src/legal/documents.js +14 -0
  139. package/dist/src/legal/gate.d.ts +13 -0
  140. package/dist/src/legal/gate.js +96 -0
  141. package/dist/src/legal/manifest.d.ts +21 -0
  142. package/dist/src/legal/manifest.js +23 -0
  143. package/dist/src/legal/receipt.d.ts +13 -0
  144. package/dist/src/legal/receipt.js +137 -0
  145. package/dist/src/legal/release.d.ts +27 -0
  146. package/dist/src/legal/release.js +28 -0
  147. package/dist/src/managed-sign-in.d.ts +0 -1
  148. package/dist/src/managed-sign-in.js +0 -13
  149. package/dist/src/membership.d.ts +27 -1
  150. package/dist/src/membership.js +139 -7
  151. package/dist/src/model-metadata.js +3 -7
  152. package/dist/src/model-pool.d.ts +99 -0
  153. package/dist/src/model-pool.js +136 -0
  154. package/dist/src/model-relay/local.js +5 -0
  155. package/dist/src/model-relay/remote.d.ts +2 -0
  156. package/dist/src/model-relay/remote.js +4 -0
  157. package/dist/src/model-tiers.d.ts +13 -1
  158. package/dist/src/model-tiers.js +28 -4
  159. package/dist/src/opencode-cli-provider.js +59 -56
  160. package/dist/src/opencode-provider.js +16 -13
  161. package/dist/src/permissions.d.ts +5 -0
  162. package/dist/src/permissions.js +7 -0
  163. package/dist/src/plan-pass.js +2 -1
  164. package/dist/src/pool-scores.d.ts +45 -0
  165. package/dist/src/pool-scores.js +40 -0
  166. package/dist/src/provider-connection.js +3 -17
  167. package/dist/src/provider-engine.js +42 -12
  168. package/dist/src/provider-request-error.d.ts +8 -0
  169. package/dist/src/provider-request-error.js +12 -0
  170. package/dist/src/provider-settings.d.ts +1 -1
  171. package/dist/src/provider-settings.js +36 -18
  172. package/dist/src/provider-turn-deadline.d.ts +39 -0
  173. package/dist/src/provider-turn-deadline.js +139 -0
  174. package/dist/src/providers.d.ts +3 -9
  175. package/dist/src/providers.js +181 -146
  176. package/dist/src/pull-request-merge.d.ts +1 -8
  177. package/dist/src/pull-request-merge.js +0 -4
  178. package/dist/src/pull-requests.d.ts +82 -66
  179. package/dist/src/pull-requests.js +266 -276
  180. package/dist/src/qa/runtime/ProcessManager.d.ts +5 -1
  181. package/dist/src/qa/runtime/ProcessManager.js +9 -3
  182. package/dist/src/react-runtime.js +147 -56
  183. package/dist/src/reasoning-probe-cloud.d.ts +10 -0
  184. package/dist/src/reasoning-probe-cloud.js +209 -0
  185. package/dist/src/remote/engine-pool.d.ts +3 -0
  186. package/dist/src/remote/engine-pool.js +85 -18
  187. package/dist/src/remote/recovery.d.ts +6 -0
  188. package/dist/src/remote/recovery.js +37 -0
  189. package/dist/src/run-records.d.ts +13 -3
  190. package/dist/src/run-records.js +59 -34
  191. package/dist/src/runtime.d.ts +18 -1
  192. package/dist/src/runtime.js +25 -7
  193. package/dist/src/session-summary.d.ts +8 -0
  194. package/dist/src/session-summary.js +34 -0
  195. package/dist/src/sessions.d.ts +8 -0
  196. package/dist/src/sessions.js +12 -3
  197. package/dist/src/shell.js +6 -0
  198. package/dist/src/side-panel.js +36 -2
  199. package/dist/src/sign-in-detection.d.ts +1 -1
  200. package/dist/src/sign-in-detection.js +4 -10
  201. package/dist/src/sign-in-offer.js +1 -1
  202. package/dist/src/skill-commands.js +1 -1
  203. package/dist/src/skills/bundled/graph-manager/SKILL.md +2 -2
  204. package/dist/src/skills/bundled/graph-manager/patterns.md +13 -19
  205. package/dist/src/skills/bundled/provenance.json +2 -2
  206. package/dist/src/subagent-run.js +50 -50
  207. package/dist/src/subscription-usage.d.ts +50 -0
  208. package/dist/src/subscription-usage.js +92 -0
  209. package/dist/src/task-checkout.d.ts +20 -4
  210. package/dist/src/task-checkout.js +78 -8
  211. package/dist/src/telemetry/access.d.ts +18 -0
  212. package/dist/src/telemetry/access.js +43 -0
  213. package/dist/src/telemetry/aggregate.d.ts +18 -2
  214. package/dist/src/telemetry/aggregate.js +22 -9
  215. package/dist/src/telemetry/capture-core.d.ts +33 -14
  216. package/dist/src/telemetry/capture-core.js +124 -25
  217. package/dist/src/telemetry/capture.d.ts +3 -2
  218. package/dist/src/telemetry/capture.js +21 -1
  219. package/dist/src/telemetry/decision-capture.js +4 -0
  220. package/dist/src/telemetry/emitter.d.ts +6 -7
  221. package/dist/src/telemetry/emitter.js +124 -29
  222. package/dist/src/telemetry/gate.d.ts +41 -2
  223. package/dist/src/telemetry/gate.js +89 -4
  224. package/dist/src/telemetry/home.d.ts +1 -0
  225. package/dist/src/telemetry/home.js +20 -0
  226. package/dist/src/telemetry/identity.d.ts +6 -3
  227. package/dist/src/telemetry/identity.js +19 -6
  228. package/dist/src/telemetry/lifecycle.d.ts +8 -0
  229. package/dist/src/telemetry/lifecycle.js +76 -0
  230. package/dist/src/telemetry/outbox.d.ts +13 -8
  231. package/dist/src/telemetry/outbox.js +68 -12
  232. package/dist/src/telemetry/permission-command.d.ts +38 -0
  233. package/dist/src/telemetry/permission-command.js +208 -0
  234. package/dist/src/telemetry/permission.d.ts +168 -0
  235. package/dist/src/telemetry/permission.js +662 -0
  236. package/dist/src/telemetry/record-installation.d.ts +1 -0
  237. package/dist/src/telemetry/record-installation.js +9 -0
  238. package/dist/src/telemetry/region-data.d.ts +12 -0
  239. package/dist/src/telemetry/region-data.js +1314 -0
  240. package/dist/src/telemetry/region.d.ts +34 -0
  241. package/dist/src/telemetry/region.js +87 -0
  242. package/dist/src/telemetry/run-privacy.d.ts +11 -0
  243. package/dist/src/telemetry/run-privacy.js +165 -0
  244. package/dist/src/telemetry/schema.d.ts +27 -6
  245. package/dist/src/telemetry/schema.js +109 -14
  246. package/dist/src/telemetry/state.d.ts +11 -7
  247. package/dist/src/telemetry/state.js +39 -6
  248. package/dist/src/telemetry/surface.d.ts +20 -3
  249. package/dist/src/telemetry/surface.js +71 -15
  250. package/dist/src/telemetry/uploader.d.ts +6 -11
  251. package/dist/src/telemetry/uploader.js +72 -46
  252. package/dist/src/telemetry/uploads.d.ts +5 -1
  253. package/dist/src/telemetry/uploads.js +25 -6
  254. package/dist/src/telemetry/version.d.ts +5 -0
  255. package/dist/src/telemetry/version.js +34 -0
  256. package/dist/src/telemetry/workspace.d.ts +4 -1
  257. package/dist/src/telemetry/workspace.js +18 -3
  258. package/dist/src/terminal-ui.d.ts +3 -0
  259. package/dist/src/terminal-ui.js +48 -6
  260. package/dist/src/thinking-level-detect.d.ts +3 -1
  261. package/dist/src/thinking-level-detect.js +8 -3
  262. package/dist/src/thinking-levels.d.ts +1 -1
  263. package/dist/src/thinking-levels.js +11 -4
  264. package/dist/src/timers.d.ts +2 -0
  265. package/dist/src/todos.d.ts +2 -1
  266. package/dist/src/todos.js +24 -4
  267. package/dist/src/tool-argument-coercion.d.ts +7 -0
  268. package/dist/src/tool-argument-coercion.js +49 -0
  269. package/dist/src/tool-catalog.d.ts +2 -2
  270. package/dist/src/tools.js +67 -22
  271. package/dist/src/transcript.js +2 -1
  272. package/dist/src/types.d.ts +14 -1
  273. package/dist/src/update.js +4 -0
  274. package/dist/src/usage-analytics.d.ts +7 -0
  275. package/dist/src/usage-analytics.js +85 -13
  276. package/dist/telemetry-consent-v1 +1 -0
  277. package/package.json +97 -96
@@ -7,6 +7,7 @@ import { decodeJwt } from 'jose';
7
7
  import { GraphConflictError, isReservedGraphId, reservedGraphId, restoreGraphRevision, validateGraph } from './graphs.js';
8
8
  import { acquireSaveLock, removeLockedFolder, SaveLockBusyError } from './save-lock.js';
9
9
  import { readGraphQuota } from './graph-quota.js';
10
+ import { requireLegalAcceptance, LegalAcceptanceRequired } from './legal/gate.js';
10
11
  const MAX_BYTES = 600 * 1024;
11
12
  const DELETION_MARKER = '.graph-deletion-pending.json';
12
13
  const digest = (raw) => createHash('sha256').update(raw).digest('hex');
@@ -34,6 +35,7 @@ const defaults = {
34
35
  subject: async () => (await getAuthStatus(AbortSignal.timeout(5000))).subject,
35
36
  baseUrl: getAuthConfiguration().apiBaseUrl,
36
37
  fetch: (...args) => globalThis.fetch(...args),
38
+ authorize: () => requireLegalAcceptance(),
37
39
  };
38
40
  async function entries(path) {
39
41
  try {
@@ -129,6 +131,7 @@ export class GraphSync {
129
131
  this.folder = join(directory, 'graph-cloud', subject);
130
132
  }
131
133
  async start() {
134
+ await this.deps.authorize?.();
132
135
  await mkdir(join(this.folder, 'snapshots'), { recursive: true });
133
136
  await mkdir(join(this.directory, 'graph-drafts'), { recursive: true });
134
137
  this.timer = setInterval(() => { void this.sync(); }, 30_000);
@@ -402,9 +405,16 @@ export class GraphSync {
402
405
  let generation;
403
406
  do {
404
407
  generation = this.generation;
408
+ await this.deps.authorize?.();
405
409
  await this.perform();
406
410
  } while (!this.stopped && generation !== this.generation);
407
411
  })().catch(error => {
412
+ if (error instanceof LegalAcceptanceRequired) {
413
+ clearInterval(this.timer);
414
+ this.timer = undefined;
415
+ this.status = { state: 'acceptance-required', detail: 'Cloud sync paused: review policies with andorra legal accept (or the desktop policy dialog), then reopen the editor. Local graphs remain saved.' };
416
+ return;
417
+ }
408
418
  this.status = error instanceof SyncPaused
409
419
  ? { state: 'pending', detail: 'Saved locally; cloud sync will resume automatically.' }
410
420
  : { state: 'offline', detail: 'Saved locally; cloud sync unavailable. Retrying automatically.' };
@@ -505,6 +515,7 @@ export class GraphSync {
505
515
  }
506
516
  async request(path, token, body) {
507
517
  this.checkBudget();
518
+ await this.deps.authorize?.();
508
519
  if (await this.deps.subject() !== this.subject)
509
520
  throw new Error('Account changed');
510
521
  const base = new URL(this.deps.baseUrl);
@@ -519,6 +530,8 @@ export class GraphSync {
519
530
  await response.body?.cancel();
520
531
  if (response.status === 401 || response.status === 403)
521
532
  this.accessDenied = true;
533
+ if (response.status === 428)
534
+ throw new LegalAcceptanceRequired();
522
535
  if (response.status === 422 && body !== undefined)
523
536
  throw new SnapshotRefused();
524
537
  throw new Error('Cloud sync failed');
@@ -75,6 +75,9 @@ function countedNodes(graph) { return Object.values(graph.nodes).filter(node =>
75
75
  function canCreateGraph() { return !freeTier() || state.plan.freeGraphId === undefined; }
76
76
  function freeGraphEditable(graph) { return !freeTier() || (graph.revision ? graph.id === state.plan.freeGraphId : canCreateGraph()); }
77
77
  const FREE_LOCKED_TIP = 'View only on the free tier. Duplicate it to make a copy you can change, or upgrade to Premium.';
78
+ // The bundled Andorra Agent is the one graph nobody can save: it can be explored and tried, and Duplicate makes an editable copy.
79
+ const presetReadOnly = graph => graph?.id === 'default';
80
+ const PRESET_READ_ONLY_TIP = 'Andorra Agent is read only. Duplicate it to make a copy you can change.';
78
81
  const FREE_DRAFT_LOCKED_TIP = 'This draft belongs to a view-only graph. Duplicate the graph to change it, or upgrade to Premium.';
79
82
  // Why a free account cannot copy this graph, or undefined when the copy would be its free graph.
80
83
  function freeCopyRefusal(graph) {
@@ -161,7 +164,9 @@ function refreshDirty() {
161
164
  state.dirty = !!state.graph && (state.savedKey == null || graphKey(state.graph) !== state.savedKey);
162
165
  if (!state.dirty && pendingDraft && pendingDraft.id === state.graph?.id) { pendingDraft = null; clearTimeout(draftTimer); }
163
166
  }
164
- function changed() { if (viewOnly() && state.viewOnlySource) { restoreViewOnly(); return; } scheduleValidation(); refreshDirty(); renderCanvas(); renderHeading(); renderValidation(); status(state.dirty ? 'Unsaved changes' : 'No unsaved changes'); syncImportRequirementsMarker(); queueDraft(); }
167
+ function changed() { if (viewOnly() && state.viewOnlySource) { restoreViewOnly(); return; } scheduleValidation(); refreshDirty(); renderCanvas(); renderHeading(); renderValidation(); status(state.dirty ? 'Unsaved changes' : 'No unsaved changes'); syncImportRequirementsMarker(); queueDraft();
168
+ // The first edit to the read-only preset says once why Save stays off, then lets the person keep trying things.
169
+ if (state.dirty && presetReadOnly(state.graph) && !state.readOnlyNoticed) { state.readOnlyNoticed = true; status(PRESET_READ_ONLY_TIP, 'notice'); } }
165
170
  function adoptServerStamps(saved) {
166
171
  for (const key of ['updatedAt', 'createdAt']) {
167
172
  if (saved.metadata?.[key] !== undefined) state.graph.metadata = { ...state.graph.metadata, [key]: saved.metadata[key] };
@@ -273,9 +278,10 @@ function applyProviderRegistry(value) {
273
278
  return true;
274
279
  }
275
280
  function isWritingRole(role) { return role?.capabilities?.filesystem === 'read-write' || role?.capabilities?.git === 'write'; }
281
+ function freeformWrites(node) { const caps = effectiveCaps(node); return node?.subagents?.freeform === 'write' && (caps.filesystem === 'read-write' || caps.git === 'write'); }
276
282
  function delegatesWriting(node) {
277
283
  return node?.type === 'agent' && node.agentRole === 'orchestrator' && node.subagents?.enabled === true && node.maxSubagents !== 0
278
- && (node.subagents.roles ?? []).some(isWritingRole);
284
+ && ((node.subagents.roles ?? []).some(isWritingRole) || freeformWrites(node));
279
285
  }
280
286
  function outcomes(node) {
281
287
  if (node.type === 'end') return [];
@@ -490,14 +496,18 @@ function renderHeading() {
490
496
  $('graph-title').textContent = state.graph?.name || 'Graph Editor';
491
497
  $('revision').textContent = state.graph ? (state.graph.revision ? `Version ${state.graph.revision}` : 'New graph') : '';
492
498
  $('save').disabled = state.saving || state.orderSaving || !state.graph || !state.dirty || state.graph.id === 'default';
493
- $('save').title = state.graph?.id === 'default' ? 'Duplicate the preset to save your customization' : '';
499
+ const readOnly = presetReadOnly(state.graph);
500
+ $('save').title = readOnly ? PRESET_READ_ONLY_TIP : '';
501
+ $('read-only-notice').hidden = !readOnly;
502
+ $('read-only-notice').title = readOnly ? PRESET_READ_ONLY_TIP : '';
494
503
  $('save-state').textContent = viewOnly() ? 'View only' : 'Saved';
495
504
  $('save-state').title = viewOnly() ? FREE_LOCKED_TIP : '';
496
505
  document.body?.classList?.toggle?.('view-only', viewOnly());
497
506
  // Save is the header's one primary and shows only while there is something to save; a clean graph says so quietly.
498
507
  const pending = !!state.graph && (state.dirty || state.saving);
499
508
  $('save').hidden = !pending;
500
- $('save-state').hidden = !state.graph || pending;
509
+ // The read-only preset has its own chip beside the title, so the muted Saved would only repeat it, untruthfully.
510
+ $('save-state').hidden = !state.graph || pending || readOnly;
501
511
  $('undo').disabled = !state.undo.length; $('redo').disabled = !state.redo.length;
502
512
  for (const id of ['duplicate', 'export', 'layout', 'fit']) $(id).disabled = !state.graph;
503
513
  $('duplicate').disabled = state.saving || state.orderSaving || !state.graph || !canCreateGraph();
@@ -1618,9 +1628,9 @@ function renderSubagents(parent, node) {
1618
1628
  const delegating = delegatesWriting(node);
1619
1629
  explain(check(parent,'Allow subagents',policy.enabled,value=>{set({enabled:value});pruneRoutes(node);}), delegating
1620
1630
  ? 'Writing roles of an Orchestrator run in their own Git worktree with a shell. The shell is not sandboxed and follows your permission mode. The Orchestrator reviews each change and lands the ones it accepts into your working folder; it never writes code itself.'
1621
- : 'Internal delegation returns observations to this Agent. Only this parent chooses its graph outcome. Active children finish or cancel before the parent can complete. Subagents of ordinary agents never receive the unsandboxed host shell. Read-only roles use filesystem tools and supported Git read operations.');
1631
+ : 'Internal delegation returns observations to this Agent. Only this parent chooses its graph outcome. Active children finish or cancel before the parent can complete. Subagents that share the working folder of this Agent never receive the host shell. With Separate Git worktree, a subagent whose tools include a command tool, or that this Agent gives one when it starts it, runs commands in its own worktree; that shell is not sandboxed and follows your permission mode. Read-only roles use filesystem tools and supported Git read operations.');
1622
1632
  if (!policy.enabled) return;
1623
- const requireWorktree = () => { if (node.agentRole === 'orchestrator' && (policy.roles || []).some(isWritingRole)) set({workspace:'worktree'}); };
1633
+ const requireWorktree = () => { if (node.agentRole === 'orchestrator' && ((policy.roles || []).some(isWritingRole) || freeformWrites(node))) set({workspace:'worktree'}); };
1624
1634
  for (const [key,label,fallback] of [['maxConcurrent','Max concurrent',3],['maxTotal','Max total per agent run',8],['maxDepth','Max nesting depth',1]]) field(parent,label,policy[key]??fallback,value=>set({[key]:value}),{type:'number',min:1,max:key==='maxDepth'?3:key==='maxConcurrent'?16:1000});
1625
1635
  choice(parent,'Model policy',policy.modelPolicy||'inherit',[{value:'inherit',label:'Inherit parent model'},{value:'specific',label:'Use specific model'},{value:'per-role',label:'Per-role model'}],value=>set({modelPolicy:value}));
1626
1636
  const childFallbackProvider = node.retry?.fallback && node.retry.maxAttempts > 1 ? node.retry.fallback.provider : '';
@@ -1628,6 +1638,7 @@ function renderSubagents(parent, node) {
1628
1638
  const workspace = choice(parent,'Workspace policy',policy.workspace||'shared-read-only',[{value:'shared-read-only',label:'Shared workspace, read only'},{value:'shared-write',label:'Shared workspace, write allowed'},{value:'worktree',label:'Separate Git worktree'}],value=>set({workspace:value}));
1629
1639
  if (delegating) { for (const option of workspace.options) option.disabled = option.value !== 'worktree'; explain(workspace, 'A writing role on an Orchestrator requires separate worktrees: each child edits its own copy, and the Orchestrator lands accepted changes into your working folder.'); }
1630
1640
  choice(parent,'Tool inheritance',policy.toolInheritance||'restricted',[{value:'restricted',label:'Restricted subset'},{value:'inherit',label:'Inherit parent allowlist'}],value=>set({toolInheritance:value}));
1641
+ explain(choice(parent,'Subagents without a role',policy.freeform||'off',[{value:'off',label:'Not allowed'},{value:'read-only',label:'Allowed, read only'},{value:'write',label:'Allowed, may write'}],value=>{set({freeform:value});requireWorktree();pruneRoutes(node);}), 'Lets this Agent start a general subagent for any task it writes, without naming a configured role. Read only: the subagent reads and searches. May write: it gets the same permissions as this Agent and needs a writing workspace policy; on an Orchestrator it works in its own Git worktree and each change is reviewed before it lands.');
1631
1642
  choice(parent,'Context',policy.context||'selected',[{value:'selected',label:'Selected context only'},{value:'task-only',label:'Task only'}],value=>set({context:value}));
1632
1643
  field(parent,'Wall time per child, seconds (blank = inherits the parent)',msToSeconds(policy.maxWallTimeMs),value=>{if(value===undefined)delete policy.maxWallTimeMs;else policy.maxWallTimeMs=secondsToMs(value);node.subagents=policy;},{type:'number',min:1,step:'any',optional:true,placeholder:'Inherits the parent'});
1633
1644
  const roles = disclosure(parent,'Configure roles',true);
@@ -1824,7 +1835,7 @@ function renderInspector() {
1824
1835
  const panels = inspectorTabs(parent, ['general', 'behavior', 'advanced']); const general = panels.general;
1825
1836
  field(general, 'Graph name', graph.name, value => { graph.name = value; renderList(); }, {maxLength:200});
1826
1837
  const meta = el('p', [graphIsFixed(graph) ? 'Preset' : '', graph.revision ? `Version ${graph.revision}` : 'Not saved yet'].filter(Boolean).join(' · '), 'graph-meta'); meta.title = `Graph ID: ${graph.id}`; general.append(meta);
1827
- if (graph.id === 'default') general.append(el('p', 'Duplicate this bundled preset to save your customization.', 'help'));
1838
+ if (presetReadOnly(graph)) general.append(el('p', PRESET_READ_ONLY_TIP, 'help'));
1828
1839
  const start = field(general,'Starting step',graph.nodes[graph.entry]?.name || '',()=>{}); start.disabled=true; explain(start,'The Orchestrator is optional. Deleting the starting step promotes its first remaining connected successor, or the first remaining step if none is connected.');
1829
1840
  field(general, 'Description', graph.metadata?.description, value => {graph.metadata={...graph.metadata,description:value};}, {multiline:true,maxLength:2000});
1830
1841
  const widgetGroup = disclosure(panels.behavior, 'Widgets', true);
@@ -1892,7 +1903,7 @@ function render() { renderHeading(); renderList(); renderLibrary(); renderCanvas
1892
1903
  async function openGraph(id, options = {}) {
1893
1904
  if (state.saving) { status('Wait for the current save before opening another graph.', 'notice'); return false; }
1894
1905
  if (state.dirty && !options.discard && !await askConfirm(DISCARD_QUESTION)) return false;
1895
- try { const opened = options.fetched === undefined ? await api(`/api/graphs/${encodeURIComponent(id)}`) : options.fetched; const locked = graphLocked(id); const capMoved = !locked && hasSubagentCap(opened); state.graph = dropLegacyTokenFields(opened); const migrated = !locked && state.graph.editorMigration === true; state.dirty = migrated || capMoved; delete state.graph.editorMigration; state.viewOnlySource = locked ? copy(state.graph) : null; markSaved(state.dirty ? null : state.graph); clearSelection(); state.undo = []; state.redo = []; state.pendingProviderNodes = null; render(); fit(); status(locked ? FREE_LOCKED_TIP : migrated ? 'This graph was updated to the current format. Save to keep it.' : capMoved ? 'Orchestrator Max subagents moved to Advanced > Subagents. Save to keep it.' : 'Graph loaded', locked || migrated || capMoved ? 'notice' : false); graphOpened(options.reason || 'open'); return true; } catch (error) { status(error.message, true); return false; }
1906
+ try { const opened = options.fetched === undefined ? await api(`/api/graphs/${encodeURIComponent(id)}`) : options.fetched; const locked = graphLocked(id); const capMoved = !locked && hasSubagentCap(opened); state.graph = dropLegacyTokenFields(opened); const migrated = !locked && state.graph.editorMigration === true; state.dirty = migrated || capMoved; delete state.graph.editorMigration; state.viewOnlySource = locked ? copy(state.graph) : null; state.readOnlyNoticed = false; markSaved(state.dirty ? null : state.graph); clearSelection(); state.undo = []; state.redo = []; state.pendingProviderNodes = null; render(); fit(); status(locked ? FREE_LOCKED_TIP : presetReadOnly(state.graph) ? PRESET_READ_ONLY_TIP : migrated ? 'This graph was updated to the current format. Save to keep it.' : capMoved ? 'Orchestrator Max subagents moved to Advanced > Subagents. Save to keep it.' : 'Graph loaded', locked || migrated || capMoved ? 'notice' : false); graphOpened(options.reason || 'open'); return true; } catch (error) { status(error.message, true); return false; }
1896
1907
  }
1897
1908
  function newId() { return `graph-${crypto.randomUUID()}`; }
1898
1909
  function newGraph(duplicate = false, discarded = false) {
@@ -3,5 +3,5 @@
3
3
  <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Graph Editor · Andorra Code</title><link rel="icon" type="image/png" href="/andorra-logo.png"><link rel="stylesheet" href="/tokens.css"><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/library.css"><link rel="stylesheet" href="/studio.css"><link rel="stylesheet" href="/controls.css"><link rel="stylesheet" href="/manager.css"><script src="/theme.js"></script></head>
4
4
  <body>
5
5
  <aside class="rail" id="library-rail"><div id="rail-resize" role="separator" aria-label="Resize library sidebar" aria-orientation="vertical" aria-controls="library-rail" tabindex="0"></div><div class="rail-caption" aria-hidden="true"></div><div class="rail-body" tabindex="0" aria-label="Graph and step library"><div class="section-label">Your graphs <button id="new-graph" aria-label="Create graph" title="Create graph" data-icon="plus"></button></div><div class="rail-search"><input id="search" type="search" placeholder="Find a graph" aria-label="Find a graph"></div><nav id="graphs" aria-label="Graphs" tabindex="0"></nav><div class="section-label library-label">Step library</div><div class="rail-search"><input id="node-search" type="search" placeholder="Search steps…" aria-label="Search steps"></div><nav id="node-library" aria-label="Step library"></nav><p class="hint">Drag a step onto the canvas, or select it and press Enter to add it. Connect each outcome to one or more destinations.</p></div><footer class="rail-footer">Your account <span id="sync-status" role="status">Saved locally; cloud sync pending</span></footer></aside>
6
- <main><header class="chrome"><div id="host-chrome" class="host-chrome" hidden></div><button id="toggle-library" class="icon-button" type="button" aria-expanded="true" aria-controls="library-rail" aria-label="Library" title="Show or hide the library" data-icon="panel-left"></button><div class="graph-heading"><strong id="graph-title">Graph Editor</strong><span id="revision">Loading graphs…</span><span id="host-notice" class="chip chip-accent" role="status" hidden></span></div><div class="chrome-actions" id="chrome-actions"><div class="manager-anchor" hidden><button id="graph-manager" class="btn-small studio-secondary" type="button" aria-label="Graph Manager" aria-expanded="false" aria-controls="manager-panel" title="Build or change this graph with Graph Manager" data-icon="bot" hidden><span>Graph Manager</span></button><div id="manager-tip" class="manager-tip" role="note" hidden><span>Let Graph Manager build this graph with you.</span><button id="manager-tip-close" type="button" class="icon-button" aria-label="Dismiss" title="Dismiss" data-icon="x"></button></div></div><div class="menu" id="more-wrap"><button id="more" class="icon-button" aria-haspopup="menu" aria-expanded="false" aria-controls="more-menu" aria-label="More actions" title="More actions" data-icon="more"></button><div id="more-menu" class="menu-list" role="menu" aria-label="More actions" hidden><button id="duplicate" type="button" role="menuitem" data-icon="copy">Duplicate</button><button id="export" type="button" role="menuitem" data-icon="download">Export JSON</button></div></div><button id="toggle-inspector" class="icon-button" aria-expanded="true" aria-label="Inspector" title="Show or hide the inspector" data-icon="panel-right"></button><span id="save-state" class="save-state" hidden>Saved</span><button id="save" class="primary btn-small" hidden>Save</button></div></header><div class="workspace"><section id="canvas" aria-label="Graph canvas"><div id="scene"><svg id="edges" aria-label="Graph connections"></svg><div id="nodes"></div></div><div id="empty"><div class="empty-state"><span class="empty-state-icon" data-icon="graph"></span><p class="empty-state-title">No graph open</p><p class="empty-state-line">Create a graph to get started.</p><div class="empty-state-action"><button id="empty-create" type="button" class="primary btn-small">Create Graph</button></div></div></div><div id="canvas-hint" class="canvas-hint" role="note"><span id="canvas-hint-text">Drag or scroll to pan · Pinch or Ctrl/Cmd+scroll to zoom</span><button id="canvas-hint-close" type="button" class="icon-button" aria-label="Dismiss canvas tips" title="Dismiss" data-icon="x"></button></div><div class="canvas-toolbar" role="toolbar" aria-label="Canvas controls"><button id="undo" aria-label="Undo" title="Undo (Ctrl/Cmd+Z)" data-icon="undo"></button><button id="redo" aria-label="Redo" title="Redo (Ctrl/Cmd+Y)" data-icon="redo"></button><span class="toolbar-divider" aria-hidden="true"></span><button id="zoom-out" aria-label="Zoom out" title="Zoom out" data-icon="zoom-out"></button><output id="zoom" aria-label="Zoom level">100%</output><button id="zoom-in" aria-label="Zoom in" title="Zoom in" data-icon="zoom-in"></button><button id="fit" aria-label="Fit graph" title="Fit graph" data-icon="fit"></button><button id="layout" aria-label="Arrange" title="Arrange steps" data-icon="arrange"></button></div></section><aside id="inspector"><div id="resize" role="separator" aria-label="Resize inspector" aria-orientation="vertical" tabindex="0"></div><header class="panel-header"><strong id="inspector-title">Graph settings</strong><button id="graph-settings" class="btn-small" title="Show the graph's own settings">Graph Settings</button></header><div id="inspector-body"></div></aside><aside id="manager-panel" aria-label="Graph Manager" hidden><div id="manager-resize" role="separator" aria-label="Resize Graph Manager" aria-orientation="vertical" tabindex="0"></div><header class="panel-header"><strong>Graph Manager</strong><span class="manager-header-actions"><button id="manager-new-chat" type="button" class="btn-small" title="Start a new conversation. The current one stays in your history.">New Chat</button><button id="manager-close" type="button" class="icon-button" aria-label="Close Graph Manager" title="Close" data-icon="x"></button></span></header><div class="manager-models" id="manager-models"></div><div id="manager-notices"></div><div id="manager-transcript" role="log" aria-label="Graph Manager conversation" tabindex="0"></div><footer class="manager-composer"><textarea id="manager-input" rows="3" placeholder="Ask Graph Manager to build or change this graph" aria-label="Message Graph Manager"></textarea><div class="manager-composer-actions"><span id="manager-run-state" role="status"></span><button id="manager-stop" type="button" class="btn-small" hidden>Stop</button><button id="manager-send" type="button" class="primary btn-small">Send</button></div></footer></aside></div><span id="status" class="visually-hidden" role="status" aria-live="polite">Connecting to your workspace…</span><div id="toasts" class="toasts" aria-live="off"></div></main>
6
+ <main><header class="chrome"><div id="host-chrome" class="host-chrome" hidden></div><button id="toggle-library" class="icon-button" type="button" aria-expanded="true" aria-controls="library-rail" aria-label="Library" title="Show or hide the library" data-icon="panel-left"></button><div class="graph-heading"><strong id="graph-title">Graph Editor</strong><span id="revision">Loading graphs…</span><span id="read-only-notice" class="chip" role="note" hidden>Read only</span><span id="host-notice" class="chip chip-accent" role="status" hidden></span></div><div class="chrome-actions" id="chrome-actions"><div class="manager-anchor" hidden><button id="graph-manager" class="btn-small studio-secondary" type="button" aria-label="Graph Manager" aria-expanded="false" aria-controls="manager-panel" title="Build or change this graph with Graph Manager" data-icon="bot" hidden><span>Graph Manager</span></button><div id="manager-tip" class="manager-tip" role="note" hidden><span>Let Graph Manager build this graph with you.</span><button id="manager-tip-close" type="button" class="icon-button" aria-label="Dismiss" title="Dismiss" data-icon="x"></button></div></div><div class="menu" id="more-wrap"><button id="more" class="icon-button" aria-haspopup="menu" aria-expanded="false" aria-controls="more-menu" aria-label="More actions" title="More actions" data-icon="more"></button><div id="more-menu" class="menu-list" role="menu" aria-label="More actions" hidden><button id="duplicate" type="button" role="menuitem" data-icon="copy">Duplicate</button><button id="export" type="button" role="menuitem" data-icon="download">Export JSON</button></div></div><button id="toggle-inspector" class="icon-button" aria-expanded="true" aria-label="Inspector" title="Show or hide the inspector" data-icon="panel-right"></button><span id="save-state" class="save-state" hidden>Saved</span><button id="save" class="primary btn-small" hidden>Save</button></div></header><div class="workspace"><section id="canvas" aria-label="Graph canvas"><div id="scene"><svg id="edges" aria-label="Graph connections"></svg><div id="nodes"></div></div><div id="empty"><div class="empty-state"><span class="empty-state-icon" data-icon="graph"></span><p class="empty-state-title">No graph open</p><p class="empty-state-line">Create a graph to get started.</p><div class="empty-state-action"><button id="empty-create" type="button" class="primary btn-small">Create Graph</button></div></div></div><div id="canvas-hint" class="canvas-hint" role="note"><span id="canvas-hint-text">Drag or scroll to pan · Pinch or Ctrl/Cmd+scroll to zoom</span><button id="canvas-hint-close" type="button" class="icon-button" aria-label="Dismiss canvas tips" title="Dismiss" data-icon="x"></button></div><div class="canvas-toolbar" role="toolbar" aria-label="Canvas controls"><button id="undo" aria-label="Undo" title="Undo (Ctrl/Cmd+Z)" data-icon="undo"></button><button id="redo" aria-label="Redo" title="Redo (Ctrl/Cmd+Y)" data-icon="redo"></button><span class="toolbar-divider" aria-hidden="true"></span><button id="zoom-out" aria-label="Zoom out" title="Zoom out" data-icon="zoom-out"></button><output id="zoom" aria-label="Zoom level">100%</output><button id="zoom-in" aria-label="Zoom in" title="Zoom in" data-icon="zoom-in"></button><button id="fit" aria-label="Fit graph" title="Fit graph" data-icon="fit"></button><button id="layout" aria-label="Arrange" title="Arrange steps" data-icon="arrange"></button></div></section><aside id="inspector"><div id="resize" role="separator" aria-label="Resize inspector" aria-orientation="vertical" tabindex="0"></div><header class="panel-header"><strong id="inspector-title">Graph settings</strong><button id="graph-settings" class="btn-small" title="Show the graph's own settings">Graph Settings</button></header><div id="inspector-body"></div></aside><aside id="manager-panel" aria-label="Graph Manager" hidden><div id="manager-resize" role="separator" aria-label="Resize Graph Manager" aria-orientation="vertical" tabindex="0"></div><header class="panel-header"><strong>Graph Manager</strong><span class="manager-header-actions"><button id="manager-new-chat" type="button" class="btn-small" title="Start a new conversation. The current one stays in your history.">New Chat</button><button id="manager-close" type="button" class="icon-button" aria-label="Close Graph Manager" title="Close" data-icon="x"></button></span></header><div class="manager-models" id="manager-models"></div><div id="manager-notices"></div><div id="manager-transcript" role="log" aria-label="Graph Manager conversation" tabindex="0"></div><footer class="manager-composer"><textarea id="manager-input" rows="3" placeholder="Ask Graph Manager to build or change this graph" aria-label="Message Graph Manager"></textarea><div class="manager-composer-actions"><span id="manager-run-state" role="status"></span><button id="manager-stop" type="button" class="btn-small" hidden>Stop</button><button id="manager-send" type="button" class="primary btn-small">Send</button></div></footer></aside></div><span id="status" class="visually-hidden" role="status" aria-live="polite">Connecting to your workspace…</span><div id="toasts" class="toasts" aria-live="off"></div></main>
7
7
  <script src="/compat.js" defer></script><script src="/icons.js" defer></script><script src="/controls.js" defer></script><script src="/skill-picker.js" defer></script><script src="/model-picker.js" defer></script><script src="/edge-router.js" defer></script><script src="/drafts.js" defer></script><script src="/app.js" defer></script><script src="/manager-markdown.js" defer></script><script src="/manager-state.js" defer></script><script src="/manager.js" defer></script><script src="/embed.js" defer></script><script src="/sidebar.js" defer></script><script src="/studio.js" defer></script><script src="/studio-canvas.js" defer></script></body></html>
@@ -68,6 +68,8 @@ export interface SubagentPolicy {
68
68
  context?: 'selected' | 'task-only';
69
69
  maxWallTimeMs?: number;
70
70
  roles?: SubagentRole[];
71
+ /** Lets the agent spawn a general subagent without naming a configured role: read-only, or with the node's own permissions. */
72
+ freeform?: 'off' | 'read-only' | 'write';
71
73
  }
72
74
  export type OutputSchema = JsonSchema;
73
75
  export interface AgentModifiers {
@@ -239,8 +241,22 @@ export declare function intakeCapabilities(node: {
239
241
  capabilities?: CapabilityPolicy;
240
242
  }): CapabilityPolicy;
241
243
  export declare const DELIVERED_OUTCOME = "delivered";
242
- export type CommandScope = boolean | 'delegated-worktree';
244
+ /**
245
+ * Who a tool set is being built for: `false` the node's own agent, `true` a child sharing its parent's folder,
246
+ * `'worktree'` a child running in its own Git worktree, and `'delegated-worktree'` a child of a delegating
247
+ * Orchestrator running in its own worktree. Only a child in a shared folder is refused command tools.
248
+ */
249
+ export type CommandScope = boolean | 'worktree' | 'delegated-worktree';
250
+ /** Tools that run commands on the host: the shells, native processes and the QA command tools. */
251
+ export declare function isCommandToolName(name: string): boolean;
243
252
  export declare function isWritingRole(role: SubagentRole): boolean;
253
+ /** Freeform subagents of this node may write: the setting is write and the node itself may write files or Git. */
254
+ export declare function freeformWrites(node: GraphNode): boolean;
255
+ /**
256
+ * The general role a spawn without a role runs as, or undefined when the node requires a configured role.
257
+ * The ceiling is the capability policy the child is measured against; read-only narrows it, write takes it whole.
258
+ */
259
+ export declare function freeformRole(policy: SubagentPolicy, ceiling: CapabilityPolicy): SubagentRole | undefined;
244
260
  export declare function delegatesWriting(node: GraphNode): boolean;
245
261
  export declare function permitsBuiltInTool(node: Pick<GraphNode, 'capabilities' | 'tools'>, name: string, child?: CommandScope): boolean;
246
262
  export declare function capabilitySubset(child: CapabilityPolicy, parent: CapabilityPolicy): boolean;
@@ -296,12 +296,39 @@ export function intakeCapabilities(node) {
296
296
  git: policy.git === 'none' ? 'none' : 'read', github: 'none', browser: policy.browser, deployment: 'none' };
297
297
  }
298
298
  export const DELIVERED_OUTCOME = 'delivered';
299
+ /** Tools that run commands on the host: the shells, native processes and the QA command tools. */
300
+ export function isCommandToolName(name) {
301
+ if (name === 'qa.browser_session')
302
+ return false;
303
+ return ['PowerShell', 'Bash', 'NativeExec', 'AsyncProcess', 'PowerShellFast'].includes(canonicalToolName(name)) || isQaToolName(name);
304
+ }
299
305
  export function isWritingRole(role) {
300
306
  return role.capabilities?.filesystem === 'read-write' || role.capabilities?.git === 'write';
301
307
  }
308
+ /** Freeform subagents of this node may write: the setting is write and the node itself may write files or Git. */
309
+ export function freeformWrites(node) {
310
+ const policy = effectiveCapabilities(node);
311
+ return node.subagents?.freeform === 'write' && (policy.filesystem === 'read-write' || policy.git === 'write');
312
+ }
313
+ /**
314
+ * The general role a spawn without a role runs as, or undefined when the node requires a configured role.
315
+ * The ceiling is the capability policy the child is measured against; read-only narrows it, write takes it whole.
316
+ */
317
+ export function freeformRole(policy, ceiling) {
318
+ const mode = policy.freeform ?? 'off';
319
+ if (mode === 'off')
320
+ return undefined;
321
+ const taken = new Set((policy.roles ?? []).map(role => role.id));
322
+ let id = 'general';
323
+ while (taken.has(id))
324
+ id += '-freeform';
325
+ return { id, name: 'General subagent', instruction: 'Complete the bounded task you are given, then report what you did and what you found.',
326
+ capabilities: mode === 'write' ? { ...ceiling } : { ...ceiling, filesystem: ceiling.filesystem === 'none' ? 'none' : 'read',
327
+ git: ceiling.git === 'none' ? 'none' : 'read', shell: 'disabled' } };
328
+ }
302
329
  export function delegatesWriting(node) {
303
330
  return node.type === 'agent' && node.agentRole === 'orchestrator' && node.subagents?.enabled === true && node.maxSubagents !== 0
304
- && (node.subagents.roles ?? []).some(isWritingRole);
331
+ && ((node.subagents.roles ?? []).some(isWritingRole) || freeformWrites(node));
305
332
  }
306
333
  const canRunCommands = (policy, child) => child !== true && policy.shell === 'allowed';
307
334
  export function permitsBuiltInTool(node, name, child = false) {
@@ -847,14 +874,14 @@ function validateGraphInternal(value, options = {}) {
847
874
  for (const key of Object.keys(s)) {
848
875
  if (key === 'maxTokensPerSubagent' || key === 'maxCombinedTokens')
849
876
  continue;
850
- if (!['enabled', 'maxConcurrent', 'maxTotal', 'maxDepth', 'modelPolicy', 'provider', 'model', 'workspace', 'toolInheritance', 'context', 'maxWallTimeMs', 'roles'].includes(key))
877
+ if (!['enabled', 'maxConcurrent', 'maxTotal', 'maxDepth', 'modelPolicy', 'provider', 'model', 'workspace', 'toolInheritance', 'context', 'maxWallTimeMs', 'roles', 'freeform'].includes(key))
851
878
  fail(`${label}: unsupported subagent setting ${key}; use a supported SubagentPolicy field`);
852
879
  }
853
880
  bounds(s.maxConcurrent, `${label} subagent concurrency`, 16);
854
881
  bounds(s.maxTotal, `${label} subagent maxTotal`, 1000);
855
882
  bounds(s.maxDepth, `${label} subagent maxDepth`, 3);
856
883
  bounds(s.maxWallTimeMs, `${label} maxWallTimeMs`);
857
- for (const [k, values] of Object.entries({ modelPolicy: ['inherit', 'specific', 'per-role'], workspace: ['shared-read-only', 'shared-write', 'worktree'], toolInheritance: ['restricted', 'inherit'], context: ['selected', 'task-only'] }))
884
+ for (const [k, values] of Object.entries({ modelPolicy: ['inherit', 'specific', 'per-role'], workspace: ['shared-read-only', 'shared-write', 'worktree'], toolInheritance: ['restricted', 'inherit'], context: ['selected', 'task-only'], freeform: ['off', 'read-only', 'write'] }))
858
885
  if (s[k] !== undefined && !values.includes(s[k]))
859
886
  fail(`${label}: invalid subagent ${k} ${JSON.stringify(s[k])}; use one of: ${values.join(', ')}`);
860
887
  subagentModelRef({ ...s, provider: s.provider ?? node.provider ?? options.defaultProvider }, `${label} subagent`, options);
@@ -900,16 +927,35 @@ function validateGraphInternal(value, options = {}) {
900
927
  fail(`${label}: role ${r.id} capability exceeds parent${node.agentRole === 'orchestrator' && !delegated ? ' intake read-only ceiling; reduce child permissions' : '; reduce child permissions or explicitly grant them to the parent'}`);
901
928
  if (r.tools?.some(t => !permitsBuiltInTool(delegated ? { capabilities: parent } : { ...node, capabilities: parent }, t)))
902
929
  fail(`${label}: role ${r.id} tools exceed effective parent capabilities; reduce its tools or explicitly grant parent permissions`);
903
- if (r.tools?.some(t => !permitsBuiltInTool({ capabilities: child }, t, delegated ? 'delegated-worktree' : true)))
904
- fail(`${label}: role ${r.id} tools exceed its child capabilities; remove unavailable tools${delegated ? '' : ' (subagents cannot use the host shell)'}`);
930
+ // A role in its own worktree may list command tools; one sharing its parent's folder may not.
931
+ const ownWorktree = s.workspace === 'worktree' && node.agentRole !== 'orchestrator';
932
+ const scope = delegated ? 'delegated-worktree' : ownWorktree ? 'worktree' : true;
933
+ if (r.tools?.some(t => !permitsBuiltInTool({ capabilities: child }, t, scope)))
934
+ fail(`${label}: role ${r.id} tools exceed its child capabilities; remove unavailable tools${scope === true ? ' (subagents in a shared folder cannot use the host shell; select Separate Git worktree to let them run commands)' : ''}`);
905
935
  const writes = child.filesystem === 'read-write' || child.git === 'write';
906
936
  if (spawningEnabled && s.workspace === 'worktree' && writes && parent.git !== 'write')
907
937
  fail(`${label}: writing worktree role ${r.id} requires parent Git write access; grant Git write or select a read-only role`);
938
+ // A role that lists command tools runs them in a worktree it creates, which needs the same Git write access.
939
+ if (spawningEnabled && ownWorktree && child.shell === 'allowed' && r.tools?.some(isCommandToolName) && parent.git !== 'write')
940
+ fail(`${label}: command-running worktree role ${r.id} requires parent Git write access to create its worktree; grant Git write or remove its command tools`);
908
941
  if (spawningEnabled && (s.workspace ?? 'shared-read-only') === 'shared-read-only' && writes)
909
942
  fail(`${label}: shared read-only subagents cannot write files or Git; reduce role permissions or set subagents.workspace to "shared-write" or "worktree"`);
910
943
  if (spawningEnabled && (s.workspace ?? 'shared-read-only') === 'shared-write' && (s.maxConcurrent ?? 3) > 1 && writes)
911
944
  fail(`${label}: concurrent writing subagents require separate worktrees; set subagents.workspace to "worktree" or subagents.maxConcurrent to 1`);
912
945
  }
946
+ if (spawningEnabled && freeformWrites(node)) {
947
+ const ws = s.workspace ?? 'shared-read-only', orchestrated = node.agentRole === 'orchestrator';
948
+ if (orchestrated && ws !== 'worktree')
949
+ fail(`${label}: freeform writing subagents on an Orchestrator require separate worktrees; set subagents.workspace to worktree (Separate Git worktree) or subagents.freeform to read-only`);
950
+ if (orchestrated && (node.completion?.mode === 'outcomes' ? node.completion.outcomes.includes(DELIVERED_OUTCOME) : node.completion?.outcome === DELIVERED_OUTCOME))
951
+ fail(`${label}: the outcome name ${DELIVERED_OUTCOME} is reserved for Orchestrator delegation; rename the completion outcome`);
952
+ if (ws === 'shared-read-only')
953
+ fail(`${label}: shared read-only subagents cannot write files or Git; set subagents.freeform to read-only or subagents.workspace to shared-write or worktree`);
954
+ if (ws === 'shared-write' && (s.maxConcurrent ?? 3) > 1)
955
+ fail(`${label}: concurrent writing subagents require separate worktrees; set subagents.workspace to worktree or subagents.maxConcurrent to 1`);
956
+ if (ws === 'worktree' && effectiveCapabilities(node).git !== 'write')
957
+ fail(`${label}: freeform writing subagents in worktrees require parent Git write access; grant Git write or set subagents.freeform to read-only`);
958
+ }
913
959
  if (spawningEnabled && (s.workspace ?? 'shared-read-only') === 'shared-write' && (s.maxConcurrent ?? 3) > 1 && !s.roles?.length)
914
960
  fail(`${label}: concurrent writing subagents require separate worktrees; set subagents.workspace to "worktree" or subagents.maxConcurrent to 1`);
915
961
  }
@@ -1,6 +1,7 @@
1
1
  import { join } from 'node:path';
2
2
  import { resolveCliExecutable } from './cli-executable.js';
3
3
  import { runBoundedCli } from './cli-process.js';
4
+ import { DEFAULT_WHOLE_RESPONSE_MS, withProviderTurnDeadline } from './provider-turn-deadline.js';
4
5
  import { allowanceInstruction, boundTextStep, parseStructuredStep, STRUCTURED_STEP_PROMPT, STRUCTURED_STEP_SCHEMA, structuredStepPrompt, TEXT_STEP_PROMPT } from './structured-step.js';
5
6
  export const GROK_BASE_URL = 'https://api.x.ai';
6
7
  export const GROK_EXECUTABLE = {
@@ -8,7 +9,6 @@ export const GROK_EXECUTABLE = {
8
9
  installMessage: 'Install the Grok CLI from x.ai, sign in, then retry the Grok provider.',
9
10
  };
10
11
  const SIGN_IN_MESSAGE = 'Sign in to Grok (grok login) on this machine, then retry the Grok provider.';
11
- const REQUEST_TIMEOUT_MS = 10 * 60_000;
12
12
  const CATALOG_TIMEOUT_MS = 30_000;
13
13
  export function grokEnvironment(source = process.env) {
14
14
  const env = Object.fromEntries(Object.entries(source).filter(([key]) => !/^(?:XAI_|GROK_API_KEY$|NODE_OPTIONS$)/i.test(key)));
@@ -143,19 +143,22 @@ export function createGrokAdapter(_config, dependencies = {}) {
143
143
  throw new Error('Invalid auxiliary output allowance.');
144
144
  if (auxiliary && request.tools.length)
145
145
  throw new Error('Grok cannot apply an auxiliary output allowance to tool-bearing requests.');
146
- const signal = AbortSignal.any([request.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
147
- const imageCount = request.messages.reduce((total, message) => total + (message.images?.length ?? 0), 0);
148
- const prompt = JSON.stringify({ ...JSON.parse(structuredStepPrompt(request)),
149
- ...(imageCount ? { omittedImages: `This provider cannot forward images; ${imageCount} image${imageCount === 1 ? ' was' : 's were'} omitted from the conversation.` } : {}) });
150
- request.onRequest?.();
151
- const { stdout } = await run(cwd => ['--prompt-file', join(cwd, 'prompt.json'), '--output-format', 'streaming-messages-json',
152
- '-m', request.model, ...ISOLATION_ARGS,
153
- ...(auxiliary ? ['--system-prompt-override', `${TEXT_STEP_PROMPT} ${allowanceInstruction(request.maxTokens)}`] : ['--json-schema', JSON.stringify(STRUCTURED_STEP_SCHEMA), '--system-prompt-override', STRUCTURED_STEP_PROMPT])], signal, { files: { 'prompt.json': prompt }, acceptedExitCodes: [0, 1] });
154
- signal.throwIfAborted();
155
- if (!auxiliary)
156
- return parseGrokResponse(stdout, request.tools);
157
- const text = parseGrokText(stdout);
158
- return boundTextStep(text, request.maxTokens, text.usage?.outputTokens);
146
+ return withProviderTurnDeadline(request.signal, async (deadline) => {
147
+ const { signal } = deadline;
148
+ const imageCount = request.messages.reduce((total, message) => total + (message.images?.length ?? 0), 0);
149
+ const prompt = JSON.stringify({ ...JSON.parse(structuredStepPrompt(request)),
150
+ ...(imageCount ? { omittedImages: `This provider cannot forward images; ${imageCount} image${imageCount === 1 ? ' was' : 's were'} omitted from the conversation.` } : {}) });
151
+ deadline.waitForResponse();
152
+ request.onRequest?.();
153
+ const { stdout } = await run(cwd => ['--prompt-file', join(cwd, 'prompt.json'), '--output-format', 'streaming-messages-json',
154
+ '-m', request.model, ...ISOLATION_ARGS,
155
+ ...(auxiliary ? ['--system-prompt-override', `${TEXT_STEP_PROMPT} ${allowanceInstruction(request.maxTokens)}`] : ['--json-schema', JSON.stringify(STRUCTURED_STEP_SCHEMA), '--system-prompt-override', STRUCTURED_STEP_PROMPT])], signal, { files: { 'prompt.json': prompt }, acceptedExitCodes: [0, 1] });
156
+ signal.throwIfAborted();
157
+ if (!auxiliary)
158
+ return parseGrokResponse(stdout, request.tools);
159
+ const text = parseGrokText(stdout);
160
+ return boundTextStep(text, request.maxTokens, text.usage?.outputTokens);
161
+ }, { responseMs: DEFAULT_WHOLE_RESPONSE_MS });
159
162
  },
160
163
  };
161
164
  }
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { resolveTelemetryCapture } from './telemetry/capture.js';
2
3
  import { readdir, stat } from 'node:fs/promises';
3
4
  import { join } from 'node:path';
4
5
  import { applyToolMenu } from './decision/applyToolMenu.js';
@@ -14,7 +15,7 @@ import { factTaskText } from './decision/facts.js';
14
15
  import { isVerificationCheck } from './decision/checks.js';
15
16
  import { FactContinuations, FACT_CONTINUATION_GUIDANCE, FINISH_SUMMARY_DESCRIPTION, PREPARE_FINISH, taskConstraints, localCheckResult, prepareFinishArguments, prepareFinishDescription } from './decision/FactContinuations.js';
16
17
  import { bypassGeneration } from './decision/ContinuationAdapter.js';
17
- import { bypassAccounting } from './context-budget.js';
18
+ import { JevOutputBaseline, bypassAccounting } from './context-budget.js';
18
19
  /** A continuation that holds only Andorra's router's `reasoning_details` for a Claude answer, and no signed blocks of its own. */
19
20
  function routerReasoningOnly(continuation) {
20
21
  return continuation.reasoningDetails !== undefined && !continuation.thinking?.length;
@@ -71,6 +72,7 @@ export async function workspaceListing(root) {
71
72
  }
72
73
  export class AndorraAgentEngine {
73
74
  async execute(options) {
75
+ options = { ...options, telemetry: resolveTelemetryCapture(options.telemetry) };
74
76
  const runId = options.runId ?? randomUUID();
75
77
  // Independent calls on the same first message: neither waits for the other.
76
78
  const [menu, kind] = await Promise.all([applyToolMenu({ ...options, runId }), applyTaskKind({ ...options, runId })]);
@@ -91,6 +93,7 @@ export class AndorraAgentEngine {
91
93
  let acceptedAutomatic;
92
94
  const bypassInput = new WeakMap();
93
95
  let liveProvider = options.provider, liveModel = options.model;
96
+ const jevOutputBaseline = new JevOutputBaseline();
94
97
  let task = options.decisionTask ?? options.task;
95
98
  let steered = false;
96
99
  let opaqueProtocol = ['anthropic', 'claude', 'codex'].includes(options.telemetryIdentity?.providerType ?? '');
@@ -272,7 +275,7 @@ export class AndorraAgentEngine {
272
275
  const outcome = batch.find(o => o.call.id === automatic.id);
273
276
  if (outcome?.executionSucceeded && !outcome.isError) {
274
277
  await emit('efficiency.prepared.executed', { kind: automatic.kind, succeeded: true });
275
- await emit('decision.turn_bypassed', { kind: automatic.kind, selection: 'fact_selected', evidenceSource: automatic.evidenceSource, accounting: 'observed_bypass_not_net_savings', ...bypassAccounting(bypassInput.get(automatic), liveProvider, liveModel) });
278
+ await emit('decision.turn_bypassed', { kind: automatic.kind, selection: 'fact_selected', evidenceSource: automatic.evidenceSource, accounting: 'observed_bypass_not_net_savings', ...bypassAccounting(bypassInput.get(automatic), liveProvider, liveModel, jevOutputBaseline.estimate(liveProvider, liveModel)) });
276
279
  }
277
280
  else
278
281
  await emit('efficiency.prepared.rejected', { kind: automatic.kind, reason: 'execution_not_confirmed' });
@@ -294,7 +297,7 @@ export class AndorraAgentEngine {
294
297
  });
295
298
  await emit('decision.ready', { style: 'facts', policy: 'call-bypass-v2', localEnabled, remoteFactsEnabled });
296
299
  const result = await new ReactEngine().execute({
297
- ...options, runId, todoStore,
300
+ ...options, runId, todoStore, jevOutputBaseline,
298
301
  decisionManager: undefined,
299
302
  tools: [...options.tools.filter(t => t.name !== PREPARE_FINISH), prepareFinish],
300
303
  recoverTools: options.recoverTools?.filter(t => t.name !== PREPARE_FINISH),
@@ -346,7 +349,7 @@ export class AndorraAgentEngine {
346
349
  },
347
350
  });
348
351
  if (result.status === 'succeeded' && acceptedAutomatic) {
349
- await emit('decision.turn_bypassed', { kind: 'complete', selection: 'fact_selected', evidenceSource: acceptedAutomatic.evidenceSource, accounting: 'observed_bypass_not_net_savings', ...bypassAccounting(bypassInput.get(acceptedAutomatic), liveProvider, liveModel) });
352
+ await emit('decision.turn_bypassed', { kind: 'complete', selection: 'fact_selected', evidenceSource: acceptedAutomatic.evidenceSource, accounting: 'observed_bypass_not_net_savings', ...bypassAccounting(bypassInput.get(acceptedAutomatic), liveProvider, liveModel, jevOutputBaseline.estimate(liveProvider, liveModel)) });
350
353
  }
351
354
  return result;
352
355
  }
@@ -0,0 +1,4 @@
1
+ export declare const JEV_SAVINGS_FIELDS: readonly ["directInputTokens", "directOutputTokens", "downstreamInputTokens"];
2
+ export type JevSavings = Record<typeof JEV_SAVINGS_FIELDS[number], number>;
3
+ export declare function readJevSavings(value: unknown): JevSavings | undefined;
4
+ export declare function emptyJevSavings(): JevSavings;
@@ -0,0 +1,13 @@
1
+ export const JEV_SAVINGS_FIELDS = ['directInputTokens', 'directOutputTokens', 'downstreamInputTokens'];
2
+ export function readJevSavings(value) {
3
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
4
+ return;
5
+ const counters = value;
6
+ if (!JEV_SAVINGS_FIELDS.every(field => typeof counters[field] === 'number'
7
+ && Number.isSafeInteger(counters[field]) && counters[field] >= 0))
8
+ return;
9
+ return Object.fromEntries(JEV_SAVINGS_FIELDS.map(field => [field, counters[field]]));
10
+ }
11
+ export function emptyJevSavings() {
12
+ return { directInputTokens: 0, directOutputTokens: 0, downstreamInputTokens: 0 };
13
+ }
@@ -0,0 +1,25 @@
1
+ import { type LegalAcceptancePayload } from './manifest.js';
2
+ import { type LegalReceipt } from './receipt.js';
3
+ import type { LegalActivation } from '../app-server/legal-protocol.js';
4
+ export interface LegalDependencies {
5
+ authStatus?: () => Promise<{
6
+ signedIn: boolean;
7
+ subject?: string;
8
+ }>;
9
+ credential?: () => Promise<{
10
+ token: string;
11
+ subject: string;
12
+ }>;
13
+ fetch?: typeof fetch;
14
+ apiBaseUrl?: string;
15
+ }
16
+ export declare const legalAuthStatus: (deps: LegalDependencies) => Promise<{
17
+ signedIn: boolean;
18
+ subject?: string;
19
+ }>;
20
+ export declare function legalClientVersion(): Promise<string>;
21
+ export declare function acceptanceRequest(subject: string, payload?: LegalAcceptancePayload, deps?: LegalDependencies): Promise<{
22
+ accepted: boolean;
23
+ receipt?: LegalReceipt;
24
+ activation: LegalActivation;
25
+ }>;
@@ -0,0 +1,47 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { getAuthState, getCredential, getAuthConfiguration } from '../auth/index.js';
3
+ import { LEGAL_MANIFEST } from './manifest.js';
4
+ import { receiptMatches } from './receipt.js';
5
+ export const legalAuthStatus = (deps) => (deps.authStatus ?? (async () => {
6
+ const state = await getAuthState();
7
+ if (state.state === 'unavailable')
8
+ throw new Error('Account credentials unavailable. Unlock the credential store and retry; this is not signed-out acceptance.');
9
+ return state.state === 'signed-in' ? { signedIn: true, subject: state.subject } : { signedIn: false };
10
+ }))();
11
+ export async function legalClientVersion() {
12
+ try {
13
+ return JSON.parse(await readFile(new URL('../../../package.json', import.meta.url), 'utf8')).version;
14
+ }
15
+ catch {
16
+ return 'unknown';
17
+ }
18
+ }
19
+ export async function acceptanceRequest(subject, payload, deps = {}) {
20
+ const credential = await (deps.credential ?? getCredential)();
21
+ if (credential.subject !== subject)
22
+ throw new Error('Account changed; review acceptance again.');
23
+ const response = await (deps.fetch ?? fetch)(`${deps.apiBaseUrl ?? getAuthConfiguration().apiBaseUrl}/legal/${payload ? 'acceptance' : 'status'}`, {
24
+ method: payload ? 'POST' : 'GET', headers: { Authorization: `Bearer ${credential.token}`, ...(payload ? { 'content-type': 'application/json' } : {}) },
25
+ ...(payload ? { body: JSON.stringify(payload) } : {}), signal: AbortSignal.timeout(10_000),
26
+ });
27
+ if (!response.ok) {
28
+ await response.body?.cancel();
29
+ throw new Error(`Account acceptance unavailable (${response.status}); hosted features remain blocked.`);
30
+ }
31
+ const text = await response.text();
32
+ if (text.length > 32768)
33
+ throw new Error('Invalid legal status response');
34
+ const result = JSON.parse(text);
35
+ if (result.subject !== subject || result.manifest?.releaseId !== LEGAL_MANIFEST.releaseId)
36
+ throw new Error('Legal documents changed; update this client and review again.');
37
+ const mode = result.mode === 'staged' || result.mode === 'enforced' ? result.mode : 'not-checked';
38
+ const activation = { stage: LEGAL_MANIFEST.stage, effectiveAt: LEGAL_MANIFEST.effectiveAt, mode, effective: mode !== 'not-checked' && typeof result.effective === 'boolean' ? result.effective : null };
39
+ if (result.accepted !== true) {
40
+ if (payload)
41
+ throw new Error('Account acceptance was not saved; hosted features remain blocked.');
42
+ return { accepted: false, activation };
43
+ }
44
+ if (!receiptMatches(result.receipt, subject))
45
+ throw new Error('Invalid authenticated acceptance response');
46
+ return { accepted: true, receipt: result.receipt, activation };
47
+ }
@@ -0,0 +1,13 @@
1
+ import type { LegalDependencies } from './client.js';
2
+ export declare const LEGAL_HELP = "Usage: andorra legal status | andorra legal view terms|privacy | andorra legal accept\nAcceptance is separate from telemetry permission. No unattended acceptance flag exists.";
3
+ export interface LegalChoiceIO {
4
+ interactive?: boolean;
5
+ ask?: (notice: string) => Promise<string | undefined>;
6
+ }
7
+ export declare function legalNotice(scope: string): string;
8
+ export declare function executeLegalCommand(args: readonly string[], home?: string, io?: LegalChoiceIO, deps?: LegalDependencies): Promise<{
9
+ code: number;
10
+ text: string;
11
+ }>;
12
+ /** Fresh TTY action only. Drain Node and OS type-ahead before arming; EOF/Escape/Ctrl+C never accept. */
13
+ export declare function terminalLegalChoice(): LegalChoiceIO;