@andorra-labs/code 0.1.11 → 0.1.13

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 (614) hide show
  1. package/README.md +8 -2
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/dist/src/account-presentation.d.ts +1 -37
  4. package/dist/src/account-presentation.js +2 -42
  5. package/dist/src/activity.d.ts +0 -25
  6. package/dist/src/activity.js +1 -23
  7. package/dist/src/agent-definitions.d.ts +0 -26
  8. package/dist/src/agent-definitions.js +0 -43
  9. package/dist/src/agent-execution.d.ts +0 -2
  10. package/dist/src/agent-execution.js +59 -414
  11. package/dist/src/agent-mcp-catalog.d.ts +0 -8
  12. package/dist/src/agent-mcp-catalog.js +0 -2
  13. package/dist/src/agent-mcp.d.ts +0 -56
  14. package/dist/src/agent-mcp.js +14 -153
  15. package/dist/src/agent-modifiers.d.ts +0 -1
  16. package/dist/src/agent-modifiers.js +25 -68
  17. package/dist/src/analytics.d.ts +0 -66
  18. package/dist/src/analytics.js +0 -45
  19. package/dist/src/anthropic-console-auth.d.ts +0 -24
  20. package/dist/src/anthropic-console-auth.js +0 -37
  21. package/dist/src/anthropic-credentials.d.ts +0 -25
  22. package/dist/src/anthropic-credentials.js +0 -28
  23. package/dist/src/app-server/protocol.d.ts +19 -244
  24. package/dist/src/app-server/protocol.js +1 -132
  25. package/dist/src/app-server/reasoning.d.ts +0 -31
  26. package/dist/src/app-server/reasoning.js +0 -54
  27. package/dist/src/app-server/terminal.d.ts +0 -36
  28. package/dist/src/app-server/terminal.js +3 -39
  29. package/dist/src/app-server/workspace.d.ts +0 -167
  30. package/dist/src/app-server/workspace.js +4 -406
  31. package/dist/src/app-server.d.ts +33 -918
  32. package/dist/src/app-server.js +608 -2984
  33. package/dist/src/artifacts.d.ts +0 -10
  34. package/dist/src/artifacts.js +1 -11
  35. package/dist/src/attachments.d.ts +4 -98
  36. package/dist/src/attachments.js +10 -130
  37. package/dist/src/auth/AuthManager.d.ts +0 -93
  38. package/dist/src/auth/AuthManager.js +3 -165
  39. package/dist/src/auth/callback-page.d.ts +0 -1
  40. package/dist/src/auth/callback-page.js +0 -4
  41. package/dist/src/auth/callback.d.ts +0 -25
  42. package/dist/src/auth/callback.js +1 -29
  43. package/dist/src/auth/deployment.d.ts +0 -16
  44. package/dist/src/auth/deployment.js +0 -16
  45. package/dist/src/auth/index.d.ts +0 -11
  46. package/dist/src/auth/index.js +0 -11
  47. package/dist/src/auth/lock.d.ts +0 -1
  48. package/dist/src/auth/lock.js +0 -1
  49. package/dist/src/auth/store.d.ts +7 -108
  50. package/dist/src/auth/store.js +21 -129
  51. package/dist/src/auth/types.d.ts +0 -8
  52. package/dist/src/auth-commands.d.ts +0 -5
  53. package/dist/src/auth-commands.js +0 -1
  54. package/dist/src/automation-runner.d.ts +0 -9
  55. package/dist/src/automation-runner.js +0 -11
  56. package/dist/src/automation-service.d.ts +0 -10
  57. package/dist/src/automation-service.js +3 -17
  58. package/dist/src/automation-tool.js +0 -5
  59. package/dist/src/automation-worker-shutdown.d.ts +0 -1
  60. package/dist/src/automation-worker-shutdown.js +0 -3
  61. package/dist/src/automations.d.ts +23 -2
  62. package/dist/src/automations.js +91 -12
  63. package/dist/src/background-tasks.d.ts +0 -23
  64. package/dist/src/background-tasks.js +0 -11
  65. package/dist/src/boot-trace.d.ts +0 -13
  66. package/dist/src/boot-trace.js +1 -14
  67. package/dist/src/browser-activity.js +0 -2
  68. package/dist/src/browser-bridge.d.ts +0 -2
  69. package/dist/src/browser-bridge.js +0 -27
  70. package/dist/src/browser-captcha-tool.d.ts +0 -13
  71. package/dist/src/browser-captcha-tool.js +3 -35
  72. package/dist/src/browser-extensions-tool.d.ts +24 -0
  73. package/dist/src/browser-extensions-tool.js +137 -0
  74. package/dist/src/browser-extensions.d.ts +127 -0
  75. package/dist/src/browser-extensions.js +729 -0
  76. package/dist/src/browser-observation.d.ts +0 -15
  77. package/dist/src/browser-observation.js +1 -22
  78. package/dist/src/browser-panel-tool.d.ts +10 -25
  79. package/dist/src/browser-panel-tool.js +64 -60
  80. package/dist/src/browser-runner.d.ts +0 -1
  81. package/dist/src/browser-runner.js +7 -46
  82. package/dist/src/browser-server.d.ts +0 -6
  83. package/dist/src/browser-server.js +6 -229
  84. package/dist/src/browser-session.d.ts +0 -25
  85. package/dist/src/browser-session.js +1 -71
  86. package/dist/src/browser-stealth.d.ts +0 -12
  87. package/dist/src/browser-stealth.js +0 -36
  88. package/dist/src/browser-ui/app.js +7 -174
  89. package/dist/src/browser-ui/style.css +0 -68
  90. package/dist/src/browser-ui/tokens.css +11 -93
  91. package/dist/src/browser-view.d.ts +52 -290
  92. package/dist/src/browser-view.js +354 -567
  93. package/dist/src/capabilities.d.ts +0 -8
  94. package/dist/src/capabilities.js +0 -29
  95. package/dist/src/capsolver.d.ts +0 -13
  96. package/dist/src/capsolver.js +0 -15
  97. package/dist/src/clarification-ui.d.ts +0 -7
  98. package/dist/src/clarification-ui.js +0 -8
  99. package/dist/src/claude-executable.d.ts +0 -1
  100. package/dist/src/claude-executable.js +1 -2
  101. package/dist/src/claude-provider.d.ts +6 -19
  102. package/dist/src/claude-provider.js +166 -61
  103. package/dist/src/cli-executable.d.ts +0 -16
  104. package/dist/src/cli-executable.js +0 -7
  105. package/dist/src/cli-process.d.ts +0 -26
  106. package/dist/src/cli-process.js +0 -18
  107. package/dist/src/cli-sign-in.d.ts +0 -20
  108. package/dist/src/cli-sign-in.js +1 -17
  109. package/dist/src/cli.d.ts +3 -56
  110. package/dist/src/cli.js +193 -702
  111. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +4 -59
  112. package/dist/src/code-intelligence/CodeIntelligenceManager.js +27 -100
  113. package/dist/src/code-intelligence/ContextLedger.d.ts +0 -4
  114. package/dist/src/code-intelligence/ContextLedger.js +0 -10
  115. package/dist/src/code-intelligence/ContextRouter.d.ts +0 -6
  116. package/dist/src/code-intelligence/ContextRouter.js +0 -8
  117. package/dist/src/code-intelligence/codegraph/CodeGraphProjectSession.d.ts +0 -2
  118. package/dist/src/code-intelligence/codegraph/CodeGraphProjectSession.js +5 -12
  119. package/dist/src/code-intelligence/codegraph/CodeGraphProvider.d.ts +0 -6
  120. package/dist/src/code-intelligence/codegraph/CodeGraphProvider.js +0 -6
  121. package/dist/src/code-intelligence/codegraph/CodeGraphSyncBarrier.d.ts +0 -5
  122. package/dist/src/code-intelligence/codegraph/CodeGraphSyncBarrier.js +1 -17
  123. package/dist/src/code-intelligence/codegraph/repoExploreTool.d.ts +0 -5
  124. package/dist/src/code-intelligence/codegraph/repoExploreTool.js +0 -5
  125. package/dist/src/code-intelligence/repository.d.ts +0 -9
  126. package/dist/src/code-intelligence/repository.js +1 -11
  127. package/dist/src/code-intelligence/types.d.ts +0 -8
  128. package/dist/src/codex-auth.d.ts +0 -44
  129. package/dist/src/codex-auth.js +0 -45
  130. package/dist/src/codex-browser-auth.d.ts +0 -13
  131. package/dist/src/codex-browser-auth.js +3 -20
  132. package/dist/src/codex-errors.js +0 -2
  133. package/dist/src/codex-executable.d.ts +0 -2
  134. package/dist/src/codex-executable.js +1 -7
  135. package/dist/src/codex-provider.d.ts +0 -13
  136. package/dist/src/codex-provider.js +1 -26
  137. package/dist/src/codex-rpc.d.ts +0 -10
  138. package/dist/src/codex-rpc.js +0 -12
  139. package/dist/src/coding-tools.d.ts +6 -27
  140. package/dist/src/coding-tools.js +193 -205
  141. package/dist/src/command-metrics.d.ts +0 -4
  142. package/dist/src/command-output-tap.d.ts +0 -11
  143. package/dist/src/command-output-tap.js +0 -3
  144. package/dist/src/command-screens.d.ts +24 -0
  145. package/dist/src/command-screens.js +132 -100
  146. package/dist/src/commands.d.ts +6 -63
  147. package/dist/src/commands.js +20 -100
  148. package/dist/src/completion-gates.d.ts +0 -47
  149. package/dist/src/completion-gates.js +0 -14
  150. package/dist/src/completion.d.ts +2 -58
  151. package/dist/src/completion.js +90 -186
  152. package/dist/src/config.d.ts +12 -116
  153. package/dist/src/config.js +41 -171
  154. package/dist/src/context-budget.d.ts +0 -22
  155. package/dist/src/context-budget.js +0 -44
  156. package/dist/src/context-compaction.d.ts +29 -6
  157. package/dist/src/context-compaction.js +94 -25
  158. package/dist/src/context-selection.d.ts +0 -24
  159. package/dist/src/context-selection.js +0 -34
  160. package/dist/src/dashboard-view.d.ts +0 -2
  161. package/dist/src/dashboard-view.js +0 -35
  162. package/dist/src/dashboard.d.ts +0 -2
  163. package/dist/src/dashboard.js +0 -9
  164. package/dist/src/deadline.d.ts +0 -45
  165. package/dist/src/deadline.js +0 -54
  166. package/dist/src/decision/ContinuationAdapter.d.ts +0 -5
  167. package/dist/src/decision/ContinuationAdapter.js +0 -5
  168. package/dist/src/decision/DecisionEngine.d.ts +0 -4
  169. package/dist/src/decision/DecisionManager.d.ts +0 -1
  170. package/dist/src/decision/DecisionManager.js +2 -7
  171. package/dist/src/decision/DecisionPolicy.d.ts +0 -1
  172. package/dist/src/decision/DecisionPolicy.js +0 -1
  173. package/dist/src/decision/FactContinuations.d.ts +11 -43
  174. package/dist/src/decision/FactContinuations.js +126 -95
  175. package/dist/src/decision/FactServiceGate.d.ts +0 -1
  176. package/dist/src/decision/FactServiceGate.js +0 -4
  177. package/dist/src/decision/PreparedSteps.d.ts +0 -15
  178. package/dist/src/decision/PreparedSteps.js +1 -11
  179. package/dist/src/decision/applyToolMenu.d.ts +0 -1
  180. package/dist/src/decision/applyToolMenu.js +1 -5
  181. package/dist/src/decision/checks.d.ts +15 -28
  182. package/dist/src/decision/checks.js +118 -49
  183. package/dist/src/decision/facts.d.ts +0 -16
  184. package/dist/src/decision/facts.js +0 -30
  185. package/dist/src/decision/guidancePolicy.js +0 -1
  186. package/dist/src/decision/hostedPolicy.d.ts +0 -6
  187. package/dist/src/decision/hostedPolicy.js +0 -7
  188. package/dist/src/decision/hostedSkills.d.ts +0 -19
  189. package/dist/src/decision/hostedSkills.js +0 -19
  190. package/dist/src/decision/optimizationPolicy.d.ts +0 -3
  191. package/dist/src/decision/optimizationPolicy.js +1 -4
  192. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +0 -7
  193. package/dist/src/decision/providers/AndorraDecisionProvider.js +4 -27
  194. package/dist/src/decision/providers/HttpDecisionProvider.d.ts +0 -2
  195. package/dist/src/decision/providers/HttpDecisionProvider.js +0 -6
  196. package/dist/src/decision/routeTools.d.ts +0 -8
  197. package/dist/src/decision/routeTools.js +1 -8
  198. package/dist/src/decision/toolFamilies.d.ts +0 -1
  199. package/dist/src/decision/toolFamilies.js +0 -1
  200. package/dist/src/decision/toolMenu.d.ts +0 -3
  201. package/dist/src/decision/toolMenu.js +0 -4
  202. package/dist/src/decision/types.d.ts +0 -6
  203. package/dist/src/default-graph.d.ts +0 -9
  204. package/dist/src/default-graph.js +0 -9
  205. package/dist/src/delegation-changes.d.ts +0 -56
  206. package/dist/src/delegation-changes.js +15 -124
  207. package/dist/src/diff-preview.d.ts +1 -1
  208. package/dist/src/diff-preview.js +4 -12
  209. package/dist/src/duration.d.ts +0 -50
  210. package/dist/src/duration.js +0 -50
  211. package/dist/src/efficiency.d.ts +0 -39
  212. package/dist/src/efficiency.js +0 -16
  213. package/dist/src/engine/protocol.d.ts +0 -2
  214. package/dist/src/engine/protocol.js +0 -2
  215. package/dist/src/engine-streams.d.ts +13 -0
  216. package/dist/src/engine-streams.js +16 -0
  217. package/dist/src/extensions.d.ts +3 -2
  218. package/dist/src/extensions.js +76 -37
  219. package/dist/src/favicons.d.ts +0 -26
  220. package/dist/src/favicons.js +0 -34
  221. package/dist/src/file-diff.d.ts +2 -58
  222. package/dist/src/file-diff.js +0 -32
  223. package/dist/src/file-read-key.d.ts +1 -0
  224. package/dist/src/file-read-key.js +5 -0
  225. package/dist/src/file-read-state.d.ts +0 -1
  226. package/dist/src/file-read-state.js +0 -4
  227. package/dist/src/firefox-cookies.d.ts +0 -34
  228. package/dist/src/firefox-cookies.js +1 -55
  229. package/dist/src/git-identity-audit.d.ts +27 -0
  230. package/dist/src/git-identity-audit.js +286 -0
  231. package/dist/src/git-identity-guard.d.ts +4 -0
  232. package/dist/src/git-identity-guard.js +998 -0
  233. package/dist/src/git-identity-hold.d.ts +12 -0
  234. package/dist/src/git-identity-hold.js +81 -0
  235. package/dist/src/git-summary.d.ts +0 -58
  236. package/dist/src/git-summary.js +2 -212
  237. package/dist/src/goal-completion-verification.d.ts +2 -2
  238. package/dist/src/goal-completion-verification.js +3 -6
  239. package/dist/src/graph-account.d.ts +0 -21
  240. package/dist/src/graph-account.js +0 -17
  241. package/dist/src/graph-editor-session.d.ts +0 -1
  242. package/dist/src/graph-editor-session.js +1 -3
  243. package/dist/src/graph-health.d.ts +7 -49
  244. package/dist/src/graph-health.js +35 -46
  245. package/dist/src/graph-manager-chat.d.ts +27 -128
  246. package/dist/src/graph-manager-chat.js +36 -166
  247. package/dist/src/graph-provider-portability.d.ts +1 -21
  248. package/dist/src/graph-provider-portability.js +6 -45
  249. package/dist/src/graph-quota.d.ts +0 -33
  250. package/dist/src/graph-quota.js +1 -44
  251. package/dist/src/graph-runner.d.ts +0 -1
  252. package/dist/src/graph-runner.js +47 -387
  253. package/dist/src/graph-selection.d.ts +0 -14
  254. package/dist/src/graph-selection.js +0 -14
  255. package/dist/src/graph-server.d.ts +3 -11
  256. package/dist/src/graph-server.js +70 -111
  257. package/dist/src/graph-studio-features.d.ts +0 -5
  258. package/dist/src/graph-studio-features.js +2 -42
  259. package/dist/src/graph-sync.d.ts +0 -78
  260. package/dist/src/graph-sync.js +5 -201
  261. package/dist/src/graph-tool.d.ts +0 -18
  262. package/dist/src/graph-tool.js +0 -27
  263. package/dist/src/graph-ui/app.js +229 -498
  264. package/dist/src/graph-ui/compat.js +0 -7
  265. package/dist/src/graph-ui/controls.css +47 -43
  266. package/dist/src/graph-ui/controls.js +0 -88
  267. package/dist/src/graph-ui/drafts.js +0 -12
  268. package/dist/src/graph-ui/edge-router.js +0 -62
  269. package/dist/src/graph-ui/embed.js +0 -59
  270. package/dist/src/graph-ui/icons.js +2 -7
  271. package/dist/src/graph-ui/index.html +2 -2
  272. package/dist/src/graph-ui/library.css +0 -5
  273. package/dist/src/graph-ui/manager-markdown.js +0 -11
  274. package/dist/src/graph-ui/manager-state.js +110 -49
  275. package/dist/src/graph-ui/manager.css +2 -20
  276. package/dist/src/graph-ui/manager.js +251 -166
  277. package/dist/src/graph-ui/model-picker.js +250 -0
  278. package/dist/src/graph-ui/provider-glyphs/alibaba-cloud.png +0 -0
  279. package/dist/src/graph-ui/provider-glyphs/anthropic.png +0 -0
  280. package/dist/src/graph-ui/provider-glyphs/aws-bedrock.png +0 -0
  281. package/dist/src/graph-ui/provider-glyphs/claude.png +0 -0
  282. package/dist/src/graph-ui/provider-glyphs/deepseek.png +0 -0
  283. package/dist/src/graph-ui/provider-glyphs/fireworks.png +0 -0
  284. package/dist/src/graph-ui/provider-glyphs/kimi.png +0 -0
  285. package/dist/src/graph-ui/provider-glyphs/minimax.png +0 -0
  286. package/dist/src/graph-ui/provider-glyphs/openai.png +0 -0
  287. package/dist/src/graph-ui/provider-glyphs/opencode.png +0 -0
  288. package/dist/src/graph-ui/provider-glyphs/openrouter.png +0 -0
  289. package/dist/src/graph-ui/provider-glyphs/xai.png +0 -0
  290. package/dist/src/graph-ui/provider-glyphs/xiaomi-mimo.png +0 -0
  291. package/dist/src/graph-ui/provider-glyphs/zai.png +0 -0
  292. package/dist/src/graph-ui/sidebar.js +2 -3
  293. package/dist/src/graph-ui/skill-picker.js +373 -39
  294. package/dist/src/graph-ui/studio-canvas.js +3 -38
  295. package/dist/src/graph-ui/studio.css +0 -18
  296. package/dist/src/graph-ui/studio.js +3 -71
  297. package/dist/src/graph-ui/style.css +11 -134
  298. package/dist/src/graph-ui/theme.js +1 -26
  299. package/dist/src/graph-ui/tokens.css +15 -114
  300. package/dist/src/graphs.d.ts +7 -156
  301. package/dist/src/graphs.js +72 -273
  302. package/dist/src/grep-regex-worker.js +0 -2
  303. package/dist/src/grep-regex.d.ts +1 -5
  304. package/dist/src/grep-regex.js +6 -8
  305. package/dist/src/grok-provider.d.ts +0 -17
  306. package/dist/src/grok-provider.js +1 -26
  307. package/dist/src/handoffs.d.ts +0 -11
  308. package/dist/src/handoffs.js +0 -13
  309. package/dist/src/hardened-runtime.d.ts +0 -10
  310. package/dist/src/hardened-runtime.js +8 -46
  311. package/dist/src/harness-home.d.ts +21 -0
  312. package/dist/src/harness-home.js +87 -0
  313. package/dist/src/host-process-guard.d.ts +0 -50
  314. package/dist/src/host-process-guard.js +0 -641
  315. package/dist/src/limits.d.ts +0 -64
  316. package/dist/src/limits.js +0 -62
  317. package/dist/src/managed-sign-in.d.ts +0 -12
  318. package/dist/src/managed-sign-in.js +0 -16
  319. package/dist/src/markdown.d.ts +0 -28
  320. package/dist/src/markdown.js +1 -175
  321. package/dist/src/mcp.d.ts +21 -82
  322. package/dist/src/mcp.js +228 -237
  323. package/dist/src/membership-errors.d.ts +0 -14
  324. package/dist/src/membership-errors.js +0 -13
  325. package/dist/src/membership.d.ts +2 -60
  326. package/dist/src/membership.js +0 -85
  327. package/dist/src/memory/LocalToolMemory.d.ts +0 -1
  328. package/dist/src/memory/LocalToolMemory.js +2 -7
  329. package/dist/src/memory/MemoryDistiller.js +0 -15
  330. package/dist/src/memory/MemoryManager.d.ts +0 -3
  331. package/dist/src/memory/MemoryManager.js +6 -18
  332. package/dist/src/memory/MemoryPolicy.d.ts +0 -2
  333. package/dist/src/memory/MemoryPolicy.js +0 -2
  334. package/dist/src/memory/MemoryProvider.d.ts +0 -6
  335. package/dist/src/memory/MemoryRetriever.js +0 -7
  336. package/dist/src/memory/PermissionMemoryProvider.d.ts +0 -1
  337. package/dist/src/memory/PermissionMemoryProvider.js +0 -1
  338. package/dist/src/memory/ProjectMemory.d.ts +42 -0
  339. package/dist/src/memory/ProjectMemory.js +285 -0
  340. package/dist/src/memory/ToolFailureLessons.d.ts +0 -3
  341. package/dist/src/memory/ToolFailureLessons.js +0 -6
  342. package/dist/src/memory/index.d.ts +1 -0
  343. package/dist/src/memory/index.js +1 -0
  344. package/dist/src/memory/providers/NoOpMemoryProvider.d.ts +0 -1
  345. package/dist/src/memory/providers/NoOpMemoryProvider.js +0 -1
  346. package/dist/src/memory/redaction.d.ts +0 -5
  347. package/dist/src/memory/redaction.js +0 -11
  348. package/dist/src/memory/repository.d.ts +0 -6
  349. package/dist/src/memory/repository.js +2 -12
  350. package/dist/src/memory/types.d.ts +0 -1
  351. package/dist/src/model-health-cache.d.ts +0 -38
  352. package/dist/src/model-health-cache.js +1 -49
  353. package/dist/src/model-metadata.d.ts +0 -18
  354. package/dist/src/model-metadata.js +2 -42
  355. package/dist/src/model-override.d.ts +0 -36
  356. package/dist/src/model-override.js +0 -43
  357. package/dist/src/model-tiers.d.ts +0 -13
  358. package/dist/src/model-tiers.js +0 -23
  359. package/dist/src/opencode-catalog.d.ts +0 -2
  360. package/dist/src/opencode-catalog.js +0 -11
  361. package/dist/src/opencode-cli-provider.d.ts +0 -35
  362. package/dist/src/opencode-cli-provider.js +1 -44
  363. package/dist/src/opencode-provider.d.ts +0 -2
  364. package/dist/src/opencode-provider.js +6 -22
  365. package/dist/src/package-name.d.ts +1 -0
  366. package/dist/src/package-name.js +1 -0
  367. package/dist/src/paged-transcript.d.ts +0 -11
  368. package/dist/src/paged-transcript.js +2 -20
  369. package/dist/src/palette.d.ts +0 -63
  370. package/dist/src/palette.js +0 -63
  371. package/dist/src/permissions.d.ts +0 -15
  372. package/dist/src/permissions.js +0 -17
  373. package/dist/src/powershell-pool.d.ts +0 -9
  374. package/dist/src/powershell-pool.js +3 -26
  375. package/dist/src/process-warnings.d.ts +4 -0
  376. package/dist/src/process-warnings.js +103 -0
  377. package/dist/src/profile.d.ts +0 -43
  378. package/dist/src/profile.js +0 -43
  379. package/dist/src/project-reservation.d.ts +11 -0
  380. package/dist/src/project-reservation.js +143 -0
  381. package/dist/src/provider-connection.d.ts +0 -18
  382. package/dist/src/provider-connection.js +0 -39
  383. package/dist/src/provider-engine.d.ts +0 -21
  384. package/dist/src/provider-engine.js +3 -98
  385. package/dist/src/provider-import.d.ts +0 -49
  386. package/dist/src/provider-import.js +0 -60
  387. package/dist/src/provider-keys.d.ts +1 -36
  388. package/dist/src/provider-keys.js +5 -48
  389. package/dist/src/provider-settings.d.ts +0 -2
  390. package/dist/src/provider-settings.js +0 -32
  391. package/dist/src/providers.d.ts +0 -217
  392. package/dist/src/providers.js +0 -315
  393. package/dist/src/pull-requests.d.ts +0 -173
  394. package/dist/src/pull-requests.js +5 -195
  395. package/dist/src/qa/browser/PlaywrightRunner.d.ts +0 -7
  396. package/dist/src/qa/browser/PlaywrightRunner.js +2 -16
  397. package/dist/src/qa/command-policy.d.ts +0 -23
  398. package/dist/src/qa/command-policy.js +0 -30
  399. package/dist/src/qa/guidance.d.ts +0 -21
  400. package/dist/src/qa/guidance.js +0 -20
  401. package/dist/src/qa/profile/ProjectInspector.d.ts +0 -4
  402. package/dist/src/qa/profile/ProjectInspector.js +0 -6
  403. package/dist/src/qa/profile/QaConfigLoader.d.ts +0 -7
  404. package/dist/src/qa/profile/QaConfigLoader.js +0 -6
  405. package/dist/src/qa/profile/QaProfile.d.ts +0 -7
  406. package/dist/src/qa/profile/QaProfile.js +0 -7
  407. package/dist/src/qa/profile/yaml.d.ts +0 -9
  408. package/dist/src/qa/profile/yaml.js +0 -13
  409. package/dist/src/qa/qa-authorize.d.ts +0 -19
  410. package/dist/src/qa/qa-authorize.js +4 -11
  411. package/dist/src/qa/runtime/ProcessManager.d.ts +0 -31
  412. package/dist/src/qa/runtime/ProcessManager.js +4 -41
  413. package/dist/src/qa/runtime/PtyManager.d.ts +0 -4
  414. package/dist/src/qa/runtime/PtyManager.js +2 -7
  415. package/dist/src/qa/runtime/changes.d.ts +0 -11
  416. package/dist/src/qa/runtime/changes.js +1 -3
  417. package/dist/src/qa/tools.d.ts +0 -10
  418. package/dist/src/qa/tools.js +0 -12
  419. package/dist/src/qa/types.d.ts +0 -13
  420. package/dist/src/react-runtime.d.ts +2 -21
  421. package/dist/src/react-runtime.js +106 -418
  422. package/dist/src/read-document-doc.d.ts +0 -6
  423. package/dist/src/read-document-doc.js +0 -55
  424. package/dist/src/read-document-docx.d.ts +0 -16
  425. package/dist/src/read-document-docx.js +2 -69
  426. package/dist/src/read-document-text.d.ts +0 -17
  427. package/dist/src/read-document-text.js +0 -22
  428. package/dist/src/read-document-tool.d.ts +0 -31
  429. package/dist/src/read-document-tool.js +0 -30
  430. package/dist/src/read-document.d.ts +0 -49
  431. package/dist/src/read-document.js +1 -67
  432. package/dist/src/read-image.d.ts +0 -32
  433. package/dist/src/read-image.js +0 -33
  434. package/dist/src/remote/cert.d.ts +1 -19
  435. package/dist/src/remote/cert.js +2 -51
  436. package/dist/src/remote/client.d.ts +0 -70
  437. package/dist/src/remote/client.js +2 -117
  438. package/dist/src/remote/command.js +0 -17
  439. package/dist/src/remote/engine-pool.d.ts +0 -152
  440. package/dist/src/remote/engine-pool.js +17 -335
  441. package/dist/src/remote/errors.d.ts +0 -15
  442. package/dist/src/remote/errors.js +0 -7
  443. package/dist/src/remote/network.d.ts +0 -26
  444. package/dist/src/remote/network.js +1 -34
  445. package/dist/src/remote/pairing.d.ts +16 -51
  446. package/dist/src/remote/pairing.js +50 -57
  447. package/dist/src/remote/pem.d.ts +2 -0
  448. package/dist/src/remote/pem.js +7 -0
  449. package/dist/src/remote/roots.d.ts +0 -20
  450. package/dist/src/remote/roots.js +0 -8
  451. package/dist/src/remote/serve.d.ts +0 -47
  452. package/dist/src/remote/serve.js +0 -30
  453. package/dist/src/remote/server.d.ts +0 -14
  454. package/dist/src/remote/server.js +1 -79
  455. package/dist/src/remote/types.d.ts +1 -32
  456. package/dist/src/remote/types.js +0 -10
  457. package/dist/src/run-control.d.ts +0 -7
  458. package/dist/src/run-control.js +0 -7
  459. package/dist/src/run-progress.d.ts +0 -170
  460. package/dist/src/run-progress.js +0 -285
  461. package/dist/src/run-records.d.ts +0 -443
  462. package/dist/src/run-records.js +44 -678
  463. package/dist/src/run-temp.d.ts +12 -0
  464. package/dist/src/run-temp.js +50 -0
  465. package/dist/src/runtime.d.ts +11 -227
  466. package/dist/src/runtime.js +0 -127
  467. package/dist/src/sandbox-child.js +0 -1
  468. package/dist/src/save-lock.d.ts +0 -12
  469. package/dist/src/save-lock.js +0 -28
  470. package/dist/src/screen-selection.d.ts +0 -23
  471. package/dist/src/screen-selection.js +0 -22
  472. package/dist/src/secret-redaction.d.ts +0 -12
  473. package/dist/src/secret-redaction.js +0 -45
  474. package/dist/src/session-changes.d.ts +4 -80
  475. package/dist/src/session-changes.js +25 -130
  476. package/dist/src/session-goal.d.ts +129 -0
  477. package/dist/src/session-goal.js +230 -0
  478. package/dist/src/session-monitor.d.ts +1 -10
  479. package/dist/src/session-monitor.js +2 -39
  480. package/dist/src/session-reaper.d.ts +0 -15
  481. package/dist/src/session-reaper.js +0 -14
  482. package/dist/src/session-skills.d.ts +15 -44
  483. package/dist/src/session-skills.js +75 -60
  484. package/dist/src/session-summary.d.ts +0 -26
  485. package/dist/src/session-summary.js +0 -32
  486. package/dist/src/session-title.d.ts +0 -1
  487. package/dist/src/session-title.js +0 -2
  488. package/dist/src/sessions.d.ts +2 -120
  489. package/dist/src/sessions.js +9 -178
  490. package/dist/src/shell.d.ts +3 -20
  491. package/dist/src/shell.js +8 -72
  492. package/dist/src/side-panel.d.ts +5 -99
  493. package/dist/src/side-panel.js +76 -133
  494. package/dist/src/sign-in-detection.d.ts +43 -0
  495. package/dist/src/sign-in-detection.js +154 -0
  496. package/dist/src/sign-in-offer.d.ts +17 -0
  497. package/dist/src/sign-in-offer.js +103 -0
  498. package/dist/src/skill-commands.d.ts +0 -1
  499. package/dist/src/skill-commands.js +1 -4
  500. package/dist/src/skills/bundled/control-browser/SKILL.md +1 -1
  501. package/dist/src/skills/bundled/graph-manager/SKILL.md +22 -4
  502. package/dist/src/skills/bundled/provenance.json +2 -2
  503. package/dist/src/skills/invocable-skills.d.ts +0 -18
  504. package/dist/src/skills/invocable-skills.js +0 -17
  505. package/dist/src/skills/project-skills.d.ts +0 -1
  506. package/dist/src/skills/project-skills.js +0 -3
  507. package/dist/src/skills/prompt-skills.js +0 -14
  508. package/dist/src/skills/runtime-skills.d.ts +1 -8
  509. package/dist/src/skills/runtime-skills.js +8 -32
  510. package/dist/src/stall-recovery.d.ts +0 -25
  511. package/dist/src/stall-recovery.js +0 -38
  512. package/dist/src/stray-files.d.ts +5 -0
  513. package/dist/src/stray-files.js +65 -0
  514. package/dist/src/structured-step.d.ts +0 -22
  515. package/dist/src/structured-step.js +0 -22
  516. package/dist/src/subagent-run.d.ts +0 -163
  517. package/dist/src/subagent-run.js +10 -374
  518. package/dist/src/subagent-tree.d.ts +32 -0
  519. package/dist/src/subagent-tree.js +128 -0
  520. package/dist/src/telemetry/aggregate.d.ts +0 -37
  521. package/dist/src/telemetry/aggregate.js +0 -40
  522. package/dist/src/telemetry/capture-core.d.ts +0 -87
  523. package/dist/src/telemetry/capture-core.js +0 -67
  524. package/dist/src/telemetry/capture.d.ts +0 -1
  525. package/dist/src/telemetry/capture.js +0 -3
  526. package/dist/src/telemetry/classify.d.ts +0 -58
  527. package/dist/src/telemetry/classify.js +0 -60
  528. package/dist/src/telemetry/decision-capture.d.ts +0 -1
  529. package/dist/src/telemetry/emitter.d.ts +0 -30
  530. package/dist/src/telemetry/emitter.js +1 -62
  531. package/dist/src/telemetry/gate.d.ts +0 -29
  532. package/dist/src/telemetry/gate.js +0 -22
  533. package/dist/src/telemetry/identity.d.ts +0 -13
  534. package/dist/src/telemetry/identity.js +0 -29
  535. package/dist/src/telemetry/outbox.d.ts +0 -64
  536. package/dist/src/telemetry/outbox.js +1 -108
  537. package/dist/src/telemetry/schema.d.ts +1 -49
  538. package/dist/src/telemetry/schema.js +1 -82
  539. package/dist/src/telemetry/state.d.ts +0 -53
  540. package/dist/src/telemetry/state.js +0 -64
  541. package/dist/src/telemetry/surface.d.ts +0 -31
  542. package/dist/src/telemetry/surface.js +1 -39
  543. package/dist/src/telemetry/uploader.d.ts +0 -11
  544. package/dist/src/telemetry/uploader.js +0 -46
  545. package/dist/src/telemetry/uploads.d.ts +0 -11
  546. package/dist/src/telemetry/uploads.js +0 -11
  547. package/dist/src/telemetry/version.d.ts +0 -4
  548. package/dist/src/telemetry/version.js +0 -14
  549. package/dist/src/telemetry/workspace.d.ts +0 -7
  550. package/dist/src/telemetry/workspace.js +1 -22
  551. package/dist/src/terminal-ui.d.ts +15 -524
  552. package/dist/src/terminal-ui.js +80 -876
  553. package/dist/src/test-edit-guard.d.ts +74 -0
  554. package/dist/src/test-edit-guard.js +269 -0
  555. package/dist/src/text.d.ts +0 -1
  556. package/dist/src/text.js +0 -1
  557. package/dist/src/time-limit.d.ts +0 -36
  558. package/dist/src/time-limit.js +0 -37
  559. package/dist/src/timers.d.ts +0 -161
  560. package/dist/src/timers.js +0 -126
  561. package/dist/src/todos.d.ts +0 -1
  562. package/dist/src/todos.js +0 -3
  563. package/dist/src/token-rate.d.ts +0 -94
  564. package/dist/src/token-rate.js +0 -154
  565. package/dist/src/tool-activity.d.ts +0 -6
  566. package/dist/src/tool-activity.js +1 -8
  567. package/dist/src/tool-availability.d.ts +0 -13
  568. package/dist/src/tool-availability.js +1 -14
  569. package/dist/src/tool-call-clock.d.ts +1 -4
  570. package/dist/src/tool-call-clock.js +0 -13
  571. package/dist/src/tool-catalog.d.ts +0 -11
  572. package/dist/src/tool-catalog.js +0 -23
  573. package/dist/src/tool-dependencies.d.ts +0 -5
  574. package/dist/src/tool-dependencies.js +0 -4
  575. package/dist/src/tool-diff-stats.d.ts +0 -23
  576. package/dist/src/tool-diff-stats.js +0 -49
  577. package/dist/src/tool-errors.d.ts +9 -7
  578. package/dist/src/tool-errors.js +13 -6
  579. package/dist/src/tool-failure-tracker.d.ts +3 -11
  580. package/dist/src/tool-failure-tracker.js +19 -27
  581. package/dist/src/tool-names.d.ts +0 -16
  582. package/dist/src/tool-names.js +0 -12
  583. package/dist/src/tool-profile.d.ts +6 -0
  584. package/dist/src/tool-profile.js +23 -0
  585. package/dist/src/tool-result-filter.d.ts +0 -19
  586. package/dist/src/tool-result-filter.js +1 -66
  587. package/dist/src/tool-schema-compatibility.d.ts +1 -2
  588. package/dist/src/tool-schema-compatibility.js +2 -7
  589. package/dist/src/tools.d.ts +0 -4
  590. package/dist/src/tools.js +11 -114
  591. package/dist/src/trajectory.d.ts +0 -13
  592. package/dist/src/trajectory.js +23 -79
  593. package/dist/src/transcript.d.ts +1 -37
  594. package/dist/src/transcript.js +11 -61
  595. package/dist/src/types.d.ts +2 -167
  596. package/dist/src/untracked-file-removal.d.ts +3 -0
  597. package/dist/src/untracked-file-removal.js +105 -0
  598. package/dist/src/update-check.d.ts +0 -14
  599. package/dist/src/update-check.js +2 -16
  600. package/dist/src/update.d.ts +4 -29
  601. package/dist/src/update.js +20 -98
  602. package/dist/src/usage-analytics.d.ts +17 -17
  603. package/dist/src/usage-analytics.js +168 -209
  604. package/dist/src/web-search.d.ts +0 -23
  605. package/dist/src/web-search.js +1 -27
  606. package/dist/src/widgets.d.ts +0 -25
  607. package/dist/src/widgets.js +0 -24
  608. package/dist/src/workspace-facts.d.ts +0 -12
  609. package/dist/src/workspace-facts.js +1 -18
  610. package/dist/src/workspace-git-metadata.d.ts +4 -5
  611. package/dist/src/workspace-git-metadata.js +37 -9
  612. package/dist/src/workspace-instructions.d.ts +3 -15
  613. package/dist/src/workspace-instructions.js +7 -20
  614. package/package.json +2 -2
@@ -1,24 +1,14 @@
1
- /* Browser-only graph editor. No dependencies or remote assets. */
2
1
  'use strict';
3
2
  const $ = id => document.getElementById(id);
4
- // SVG attributes cannot use CSS custom properties, so a token's value is read from :root.
5
- // `getComputedStyle` is feature-detected because this module is also loaded into harnesses that
6
- // provide a partial DOM.
7
3
  const themeColor = (token, fallback) => {
8
4
  try {
9
5
  if (typeof getComputedStyle === 'function') {
10
6
  const value = getComputedStyle(document.documentElement).getPropertyValue(token).trim();
11
7
  if (value) return value;
12
8
  }
13
- } catch { /* A partial DOM falls through to the literal below. */ }
9
+ } catch { }
14
10
  return fallback;
15
11
  };
16
- // The connection colours, read once per paint. Every connection is the same neutral line, whatever
17
- // its outcome: an outcome is not a failure, and colouring "blocked" or "pass" made a resting graph
18
- // read as a status board. The one red on the canvas is a run route into a node that failed
19
- // (studio.css). The outcome's pill is outlined in the hairline with muted ink; the halo is the
20
- // canvas ground, so a crossing stays legible. Each fallback is the dark token's own value
21
- // (desktop/src/styles/tokens.css), for a page that has not loaded the stylesheet.
22
12
  const connectionPalette = () => ({
23
13
  line: themeColor('--text-3', 'rgba(245,245,245,.60)'),
24
14
  active: themeColor('--accent', '#ececec'),
@@ -27,24 +17,19 @@ const connectionPalette = () => ({
27
17
  pillEdge: themeColor('--border', 'rgba(245,245,245,.08)'),
28
18
  pillInk: themeColor('--text-2', 'rgba(245,245,245,.74)'),
29
19
  });
30
- /** The connection's stroke at rest and while it is traced (hovered, focused or selected). */
31
20
  const EDGE_WIDTH = '1.5', EDGE_ACTIVE_WIDTH = '2';
32
21
  const fragmentToken = new URLSearchParams(location.hash.slice(1)).get('token');
33
22
  const token = fragmentToken || sessionStorage.getItem('andorra-graph-token');
34
23
  if (fragmentToken) sessionStorage.setItem('andorra-graph-token', fragmentToken);
35
24
  history.replaceState(null, '', location.pathname + location.search);
36
- const state = { graphs: [], providers: [], tools: [], definitions: [], libraryExpanded: {}, selectedEdge: null, selectedIds: [], routePick: null, bulkOutcome: null, disclosures: {}, validationErrors: [], validationTimer: null, graph: null, selected: null, dirty: false, saving: false, undo: [], redo: [], zoom: 1, x: 60, y: 120, pendingProviderNodes: null };
25
+ const state = { graphs: [], providers: [], tools: [], definitions: [], libraryExpanded: {}, selectedEdge: null, selectedIds: [], routePick: null, bulkOutcome: null, disclosures: {}, validationErrors: [], validationTimer: null, graph: null, selected: null, dirty: false, saving: false, orderSaving: false, undo: [], redo: [], zoom: 1, x: 60, y: 120, pendingProviderNodes: null };
37
26
  const copy = value => JSON.parse(JSON.stringify(value));
38
27
  const el = (tag, text, className) => { const item = document.createElement(tag); if (text !== undefined) item.textContent = text; if (className) item.className = className; return item; };
39
- // The studio's questions are the app's own dialogs (controls.js). A page without that layer — the
40
- // test harness — answers through the platform's, so the code path is the same either way.
41
28
  function askConfirm(options) {
42
29
  const controls = globalThis.AndorraControls;
43
30
  if (typeof controls?.confirm === 'function') return controls.confirm(options);
44
31
  return Promise.resolve(confirm([options.title, options.message].filter(Boolean).join('\n\n')));
45
32
  }
46
- // Menus and dialogs leave the way they came (controls.js). A page without that layer — the test
47
- // harness — removes or closes them at once.
48
33
  function leaveLayer(layer, done) {
49
34
  const controls = globalThis.AndorraControls;
50
35
  if (typeof controls?.leave === 'function') return controls.leave(layer, done);
@@ -56,28 +41,19 @@ function closeDialog(dialog) {
56
41
  }
57
42
  const DISCARD_QUESTION = { title: 'Discard unsaved changes?', message: 'Edits to this graph since its last version are lost. Recoverable drafts stay in draft history.', confirmLabel: 'Discard', tone: 'danger' };
58
43
  function status(message, error = false) { $('status').textContent = message; $('status').parentElement.classList.toggle('error', error); }
59
- // The free tier keeps one custom graph of up to three nodes (Done does not count) and leaves the
60
- // Orchestrator to Premium. The server enforces the same rules on save; these keep the editor honest
61
- // about them before the user builds something it cannot save.
62
44
  const FREE_CREATE_TIP = 'Free tier includes 1 custom graph. Upgrade to Premium for more graphs.';
63
45
  const FREE_ORCHESTRATOR_TIP = 'The Orchestrator is a Premium feature. Free tier graphs can use the other agents.';
64
46
  function freeTier() { return state.plan?.paid === false; }
65
47
  function freeNodeTip() { return `Free tier graphs can have up to ${state.plan.nodeLimit} steps, not counting Done. Upgrade to Premium for larger graphs.`; }
66
48
  function countedNodes(graph) { return Object.values(graph.nodes).filter(node => node.type !== 'end').length; }
67
49
  function canCreateGraph() { return !freeTier() || state.graphs.filter(graph => graph.id !== 'default').length < state.plan.customGraphLimit; }
68
- /** Whether a free account may save this graph: its kept graph, or a new one while it has none. */
69
50
  function freeGraphEditable(graph) { return !freeTier() || (graph.revision ? graph.id === (state.plan.freeGraphId ?? state.graphs.find(item => item.id !== 'default')?.id) : canCreateGraph()); }
70
51
  const FREE_LOCKED_TIP = 'On the free tier only your first custom graph is available. Upgrade to Premium to open this graph.';
71
- /**
72
- * Whether a free account's saved workflow is outside its allowance: neither the preset nor the one it
73
- * keeps. The server refuses to run or save it, so the list shows it locked and the editor never opens it.
74
- */
75
52
  function graphLocked(id) {
76
53
  if (!freeTier() || id === 'default') return false;
77
54
  const graph = state.graphs.find(item => item.id === id);
78
55
  return Boolean(graph?.revision) && !freeGraphEditable(graph);
79
56
  }
80
- /** Why adding these nodes would leave the free allowance, or undefined. */
81
57
  function freeNodeRefusal(added) {
82
58
  if (!freeTier() || !state.graph) return undefined;
83
59
  if (added.some(node => node?.agentRole === 'orchestrator')) return FREE_ORCHESTRATOR_TIP;
@@ -89,19 +65,12 @@ async function api(path, body, options = {}) {
89
65
  const data = await response.json();
90
66
  if (!response.ok) {
91
67
  const message = typeof data.error === 'string' ? data.error : JSON.stringify(data.error || data);
92
- // A graph the engine refused is explained in the editor's words, naming the step it is about.
93
68
  const graph = body?.graph && typeof body.graph === 'object' ? body.graph : body?.nodes ? body : state.graph;
94
69
  const plain = plainGraphError(message, graph);
95
70
  throw Object.assign(new Error(plain.message), plain.nodeId ? { nodeId: plain.nodeId } : {});
96
71
  }
97
72
  return data;
98
73
  }
99
- // The engine's validation says "Invalid graph: node fixer: required outcome fail has no route; connect
100
- // its output port": its own identifiers and words (node, entry, edge, limits.maxNodeVisits), meant for
101
- // the CLI and the agents that read them. The editor says the same thing in the words its own controls
102
- // use (ADR 0022 D13: a step, a connection, the starting step, Maximum visits per step) and names the
103
- // step by its name. The messages the editor's controls can produce are written out; any other keeps
104
- // the engine's sentence with those words swapped. Engine text that is not a validation passes through.
105
74
  function plainGraphError(message, graph) {
106
75
  const match = /^Invalid graph: ([\s\S]*)$/.exec(String(message));
107
76
  if (!match) return { message: String(message), nodeId: null };
@@ -117,7 +86,6 @@ function plainGraphError(message, graph) {
117
86
  const detail = match[1];
118
87
  let found;
119
88
  if (/^all nodes must be reachable from the entry/.test(detail)) {
120
- // Which steps no connection reaches from the starting step: the engine does not say, the editor can.
121
89
  const reached = new Set(), queue = graph?.entry && nodes[graph.entry] ? [graph.entry] : [];
122
90
  while (queue.length) { const id = queue.shift(); if (reached.has(id)) continue; reached.add(id); for (const edge of graph?.edges || []) if (edge?.source === id && nodes[edge.target]) queue.push(edge.target); }
123
91
  const lost = Object.keys(nodes).filter(id => !reached.has(id));
@@ -134,16 +102,12 @@ function plainGraphError(message, graph) {
134
102
  if ((found = /^edge \S+: nonexistent outcome (\S+)/.exec(detail))) return { message: `A connection starts from the outcome “${found[1]}”, which its step no longer has. Remove it or pick another outcome.`, nodeId: null };
135
103
  if (/^duplicate edge /.test(detail)) return { message: 'Two connections join the same outcome to the same step. Remove one of them.', nodeId: null };
136
104
  if ((found = /^Join (\S+) needs an incoming branch$/.exec(detail))) return { message: `${name(found[1])}: connect at least one step into this Join.`, nodeId: found[1] };
137
- // A message about one step: "node <id>: …", "node <id> must …", or "Join <id>: …", "Agent <id>: …".
138
105
  if ((found = /^(?:node|Join|Condition|Loop|Agent) (\S+?)(:\s*| )([\s\S]*)$/.exec(detail)) && nodes[found[1]]) {
139
106
  return { message: `${name(found[1])}: ${sentence(words(found[3]))}`, nodeId: found[1] };
140
107
  }
141
108
  return { message: sentence(words(detail)), nodeId: null };
142
109
  }
143
110
  function checkpoint() { state.undo.push(copy(state.graph)); if (state.undo.length > 80) state.undo.shift(); state.redo = []; }
144
- // The comparison form of a graph: keys sorted at every depth, so an edit that is undone by hand
145
- // (a field cleared and typed back) compares equal even when its key moved in the object, and
146
- // without the draft-only provider marker, which is editor state rather than graph content.
147
111
  function graphKey(graph) {
148
112
  const sorted = value => Array.isArray(value) ? value.map(sorted)
149
113
  : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, sorted(value[key])]))
@@ -151,20 +115,12 @@ function graphKey(graph) {
151
115
  const { pendingProviderNodes, ...content } = graph;
152
116
  return JSON.stringify(sorted(content));
153
117
  }
154
- // Remember the open graph as the saved state. `null` marks a graph with no saved form to return to
155
- // (new, duplicated, recovered from a draft, migrated, or replaced by an import), which stays
156
- // unsaved until it is saved.
157
118
  function markSaved(graph) { state.savedKey = graph ? graphKey(graph) : null; }
158
- // Unsaved means the open graph differs from the saved state, not that some edit happened: edits
159
- // that are undone, or reverted by hand, leave nothing to save. Back at the saved state, an
160
- // autosave still waiting would record an edit that no longer exists, so it is cancelled.
161
119
  function refreshDirty() {
162
120
  state.dirty = !!state.graph && (state.savedKey == null || graphKey(state.graph) !== state.savedKey);
163
121
  if (!state.dirty && pendingDraft && pendingDraft.id === state.graph?.id) { pendingDraft = null; clearTimeout(draftTimer); }
164
122
  }
165
123
  function changed() { scheduleValidation(); refreshDirty(); renderCanvas(); renderHeading(); renderValidation(); status(state.dirty ? 'Unsaved changes' : 'No unsaved changes'); syncImportRequirementsMarker(); queueDraft(); }
166
- // The save stamps metadata only the server writes; edits kept across a save take those stamps, so
167
- // reverting the kept edits returns the graph to exactly the version just saved.
168
124
  function adoptServerStamps(saved) {
169
125
  for (const key of ['updatedAt', 'createdAt']) {
170
126
  if (saved.metadata?.[key] !== undefined) state.graph.metadata = { ...state.graph.metadata, [key]: saved.metadata[key] };
@@ -172,18 +128,12 @@ function adoptServerStamps(saved) {
172
128
  }
173
129
  }
174
130
  let draftTimer, pendingDraft, draftWrite;
175
- // How long editing must pause before a draft is written. Every draft is a snapshot the account
176
- // keeps, so a pause shorter than this would store one per keystroke burst.
177
131
  const DRAFT_PAUSE_MS = 2000;
178
132
  function flushDraft(leaving = false) {
179
133
  clearTimeout(draftTimer);
180
134
  const graph = pendingDraft; pendingDraft = null;
181
135
  if (graph) return draftWrite = api('/api/drafts', graph, leaving ? { keepalive: true } : {}).then(refreshDrafts).catch(error => status('Draft not saved: ' + error.message, true));
182
136
  }
183
- // Whether the open graph holds edits a draft should keep. A graph that is still exactly what New
184
- // or Duplicate made holds nothing to recover, so it gets no draft until an edit makes it differ.
185
- // Without this every New graph left a draft behind, from the autosave and from the embedded
186
- // editor's flush on leaving alike.
187
137
  function hasDraftableEdits() {
188
138
  if (!state.graph || !state.dirty) return false;
189
139
  if (state.untouched) {
@@ -203,18 +153,11 @@ function queueDraft() {
203
153
  async function refreshDrafts() {
204
154
  state.drafts = await api('/api/drafts'); renderList();
205
155
  }
206
- // The pending-provider set is session memory; the id array mirrored onto the graph object is
207
- // what survives an autosave, because queueDraft serializes the graph verbatim. Only the draft
208
- // round-trip carries the mirror (every saved-artifact reader strips it through
209
- // dropLegacyTokenFields), so a recovered imported draft can rebuild the requirement set.
210
156
  function syncImportRequirementsMarker() {
211
157
  if (!state.graph) return;
212
158
  if (state.pendingProviderNodes?.size) state.graph.pendingProviderNodes = [...state.pendingProviderNodes];
213
159
  else if (Array.isArray(state.graph.pendingProviderNodes)) delete state.graph.pendingProviderNodes;
214
160
  }
215
- // A recovered draft rebuilds its requirement set from the mirror, keeping only ids whose node
216
- // still exists as an unassigned agent, so requirements can neither vanish nor outlive their
217
- // nodes, and the mirror on the draft converges to what is actually still owed.
218
161
  function restoreImportRequirements(graph) {
219
162
  if (!graph || !Array.isArray(graph.pendingProviderNodes)) return null;
220
163
  const owed = new Set();
@@ -225,7 +168,6 @@ function restoreImportRequirements(graph) {
225
168
  if (owed.size) graph.pendingProviderNodes = [...owed]; else delete graph.pendingProviderNodes;
226
169
  return owed.size ? owed : null;
227
170
  }
228
- /** Open a draft snapshot; `graphId` names the saved workflow it belongs to, refused when that one is locked. */
229
171
  async function openDraft(snapshot, graphId) {
230
172
  if (graphLocked(graphId)) { status(FREE_LOCKED_TIP, true); return; }
231
173
  if (state.dirty && !await askConfirm({ title: 'Open the saved draft?', message: 'Current edits are retained in draft history.', confirmLabel: 'Open Draft' })) return;
@@ -233,14 +175,6 @@ async function openDraft(snapshot, graphId) {
233
175
  catch (error) { status(error.message, true); }
234
176
  }
235
177
  function mutate(action, inspector = false) { if (!state.graph) return; checkpoint(); action(); changed(); if (inspector) renderInspector(); }
236
- /**
237
- * Fold an Orchestrator's legacy `maxSubagents` cap into its subagent policy, the same way
238
- * migrateGraphToOrchestrator does in src/graphs.ts. The editor no longer shows that field: it
239
- * duplicated "Max total per node run" and silently lowered or disabled the Subagents settings.
240
- * The runtime still honours the field, so a saved value must not stay hidden; folding it keeps
241
- * the run identical (the runtime uses the smaller of the two) and makes Advanced the only place
242
- * the limits live. Zero turns subagents off; a node without a policy has nothing to cap.
243
- */
244
178
  function foldSubagentCap(node) {
245
179
  if (!node || typeof node !== 'object' || node.maxSubagents === undefined) return node;
246
180
  const cap = node.maxSubagents; const policy = node.subagents;
@@ -263,17 +197,6 @@ function foldGraphSubagentCaps(graph) {
263
197
  for (const node of Object.values(graph?.nodes || {})) foldSubagentCap(node);
264
198
  return graph;
265
199
  }
266
- /**
267
- * Drop settings the runtime no longer defines. `maxTokens` and the subagent token pair were
268
- * removed with the cumulative token ceiling; the server still accepts them so old graphs keep
269
- * loading, but hiding their controls alone would not remove them from a saved revision because
270
- * the editor serializes the whole graph. Removing them here makes the next save authoritative.
271
- * An Orchestrator's hidden `maxSubagents` cap is folded into its policy for the same reason.
272
- * The import-requirements marker (`pendingProviderNodes`) is stripped here too: it is editor
273
- * state riding on draft snapshots, not graph content, so it never reaches a saved revision, an
274
- * export or a reopened saved graph. Only the draft round-trip keeps it (queueDraft and
275
- * openDraft bypass this), which is what lets a recovery restore the requirements.
276
- */
277
200
  function dropLegacyTokenFields(graph) {
278
201
  if (!graph || typeof graph !== 'object') return graph;
279
202
  if (graph.limits && typeof graph.limits === 'object') delete graph.limits.maxTokens;
@@ -296,22 +219,10 @@ function applyProviderRegistry(value) {
296
219
  state.defaultProvider = nextDefault;
297
220
  state.providers = nextProviders;
298
221
  state.modelContextRequests = new Map();
299
- // A changed registry can move the default provider or the endpoint's catalog, so discovered
300
- // suggestions must not survive it; the next inspector render rediscovers against live config.
301
222
  state.providerModelRequests = new Map();
302
- // The same reasoning applies to the record-on-commit dedupe: a model that was recorded under
303
- // the previous registry may have been removed from the provider's configured list since, and
304
- // a stale entry would suppress the re-POST that makes such a selection runnable again.
305
- // Models that are still configured skip re-recording via the `known` set, not this one.
223
+ state.providerModelCatalogs = new Map();
306
224
  state.providerModelRecords = new Set();
307
- // And to the unmet-fallback explanations: each asserts what a fallback provider does not serve,
308
- // a claim only the previous registry's catalogs justified. The next commit re-derives one.
309
225
  state.providerModelWarnings = new Map();
310
- // A discovery request started before this change is detached from the cleared caches: when it
311
- // resolves it advertises the PREVIOUS endpoint's catalog, and applying it would record those
312
- // model names into the new endpoint's configuration — binding checks the configured list, so an
313
- // unsupported model would pass binding and fail only at inference. Callbacks capture this
314
- // generation and discard themselves when it no longer matches.
315
226
  state.providerRegistryGeneration = (state.providerRegistryGeneration || 0) + 1;
316
227
  if (state.graph) {
317
228
  document.activeElement?.blur?.();
@@ -320,9 +231,6 @@ function applyProviderRegistry(value) {
320
231
  }
321
232
  return true;
322
233
  }
323
- // Browser copies of isWritingRole and delegatesWriting in src/graphs.ts. The server decides which
324
- // ports a node has and whether it delegates; these must agree with it exactly, or the canvas
325
- // shows a port the server does not know, or hides one it offers.
326
234
  function isWritingRole(role) { return role?.capabilities?.filesystem === 'read-write' || role?.capabilities?.git === 'write'; }
327
235
  function delegatesWriting(node) {
328
236
  return node?.type === 'agent' && node.agentRole === 'orchestrator' && node.subagents?.enabled === true && node.maxSubagents !== 0
@@ -337,14 +245,11 @@ function outcomes(node) {
337
245
  if (node.type === 'approval') return ['approved', 'rejected'];
338
246
  if (node.completion?.mode === 'outcomes') return node.completion.outcomes;
339
247
  const outcome = node.completion?.outcome ?? 'completed';
340
- // Mirrors nodeOutcomes: a delegating Orchestrator also ends as delivered once it has landed
341
- // accepted changes. The server accepts delivered without an edge, so the port needs no route.
248
+ // An Action's command that exits non-zero takes the optional failed port; unrouted, it stops the run.
249
+ if (node.type === 'action') return [outcome, 'failed'];
342
250
  return delegatesWriting(node) ? [outcome, 'delivered'] : [outcome];
343
251
  }
344
252
  function edgeOutcome(edge) { return edge.outcome || 'completed'; }
345
- // Drops this node's connections whose outcome it no longer has. Called inside the mutate that
346
- // changed its outcomes, so undo restores the routes together with the setting. An edge left on a
347
- // vanished port is refused by the server and is drawn as if it left the first port.
348
253
  function pruneRoutes(node) { state.graph.edges = state.graph.edges.filter(edge => edge.source !== node.id || outcomes(node).includes(edgeOutcome(edge))); }
349
254
  function selectedNodes() { return (state.selectedIds.length ? state.selectedIds : state.selected ? [state.selected] : []).map(id => state.graph?.nodes[id]).filter(Boolean); }
350
255
  function selectionType(node) { return `${node.type}:${node.agentRole || 'regular'}`; }
@@ -392,8 +297,6 @@ function renderBulkInspector(parent, nodes) {
392
297
  for(const node of nodes) for(const edge of state.graph.edges.filter(edge=>edge.source===node.id&&edgeOutcome(edge)===state.bulkOutcome)) {const edit=el('button',`${node.name} → ${state.graph.nodes[edge.target]?.name} (${Object.keys(edge.inputMapping||{}).length} mappings)`,'graph-row');edit.onclick=()=>{clearSelection();state.selectedEdge=edge;renderCanvas();renderInspector();};connections.append(edit);}
393
298
  }
394
299
  function cancelRoutePick() { state.routePick=null;renderCanvas();renderInspector();status('Destination selection cancelled. No connections changed.'); }
395
- /** One validation problem: the message shown to the reader, and the node it blames. Errors that
396
- * carry their node id directly survive duplicate display names; graph-level ones name none. */
397
300
  function issues() {
398
301
  const graph = state.graph; if (!graph) return [];
399
302
  const result = [], nodes = Object.values(graph.nodes);
@@ -425,11 +328,7 @@ function issues() {
425
328
  if (node.name.length > 200) blame(`${node.id}: Keep the step name to 200 characters or fewer.`);
426
329
  if (node.position !== undefined && (!Number.isFinite(node.position?.x) || !Number.isFinite(node.position?.y) || Math.abs(node.position.x) > 100000 || Math.abs(node.position.y) > 100000)) blame(`${node.name}: Set finite X and Y coordinates between -100000 and 100000.`);
427
330
  if (node.type === 'agent') {
428
- // An imported graph must not drift onto the machine default provider unnoticed: nodes
429
- // that arrived without a usable provider stay pinned to this list until one is chosen.
430
331
  if (state.pendingProviderNodes?.has(node.id) && !node.provider) blame(`${node.name}: choose a model profile for this imported step before saving.`);
431
- // Missing provider profiles remain editable; the inspector labels them unavailable.
432
- // Run-time preflight, not graph storage, enforces local provider availability.
433
332
  for (const key of ['instruction', 'systemPrompt']) if (node[key] !== undefined && (typeof node[key] !== 'string' || node[key].length > 100000)) blame(`${node.name}: Keep ${key} to 100000 characters or fewer.`);
434
333
  if (node.limits?.maxIterations !== undefined && (!Number.isSafeInteger(node.limits.maxIterations) || node.limits.maxIterations < 0 || node.limits.maxIterations > 1000)) blame(`${node.name}: Set an integer iteration limit from 1 to 1000, or 0 for unlimited.`);
435
334
  if (node.prompt !== undefined && (typeof node.prompt !== 'string' || node.prompt.length > 100000)) blame(`${node.name}: Keep the system prompt to 100000 characters or fewer.`);
@@ -448,19 +347,14 @@ function scheduleValidation() {
448
347
  catch (error) { if (JSON.stringify(state.graph) === snapshot) { state.validated = true; state.validationErrors = [error.nodeId ? { message: error.message, nodeId: error.nodeId } : error.message]; renderValidation(); renderCanvas(); } }
449
348
  }, 350);
450
349
  }
451
- // The workflow on the canvas, kept for this tab in session storage, so a reload of the editor — the
452
- // desktop's Reload Editor, or the browser's — opens it again rather than the first in the list. An
453
- // unsaved one is reopened from the draft the reload kept of it.
454
350
  const OPEN_KEY = 'andorra-graph-open';
455
351
  let rememberedOpen;
456
352
  function rememberOpenGraph() {
457
- // Before boot has opened anything there is nothing to remember, and the last value must survive
458
- // until boot has read it.
459
353
  if (!state.graph) return;
460
354
  const value = JSON.stringify({ id: state.graph.id, unsaved: !!state.dirty });
461
355
  if (value === rememberedOpen) return;
462
356
  rememberedOpen = value;
463
- try { sessionStorage.setItem(OPEN_KEY, value); } catch { /* Storage is unavailable; boot opens the first workflow. */ }
357
+ try { sessionStorage.setItem(OPEN_KEY, value); } catch { }
464
358
  }
465
359
  function rememberedGraph() {
466
360
  try {
@@ -468,9 +362,6 @@ function rememberedGraph() {
468
362
  return value && typeof value.id === 'string' ? { id: value.id, unsaved: value.unsaved === true } : null;
469
363
  } catch { return null; }
470
364
  }
471
- // Reopen what the tab had open before it reloaded: the newest draft of it when it held unsaved work
472
- // (the reload kept that work as a draft first), else its saved version. False when there is nothing
473
- // to reopen, and boot opens the first workflow as before.
474
365
  async function reopenRemembered() {
475
366
  const remembered = rememberedGraph();
476
367
  if (!remembered || graphLocked(remembered.id)) return false;
@@ -480,7 +371,7 @@ async function reopenRemembered() {
480
371
  state.drafts = await api('/api/drafts');
481
372
  const draft = state.drafts.find(item => item.graphId === remembered.id);
482
373
  if (draft) { await openDraft(draft.snapshot, draft.graphId); return state.graph?.id === remembered.id; }
483
- } catch { /* Fall back to the saved version. */ }
374
+ } catch { }
484
375
  }
485
376
  return saved && await openGraph(remembered.id);
486
377
  }
@@ -488,49 +379,105 @@ function renderHeading() {
488
379
  rememberOpenGraph();
489
380
  $('graph-title').textContent = state.graph?.name || 'Graph Editor';
490
381
  $('revision').textContent = state.graph ? `${state.graph.revision ? `Version ${state.graph.revision}` : 'New graph'}${state.dirty ? ' · Unsaved' : ''}` : '';
491
- $('save').disabled = state.saving || !state.graph || !state.dirty || state.graph.id === 'default';
382
+ $('save').disabled = state.saving || state.orderSaving || !state.graph || !state.dirty || state.graph.id === 'default';
492
383
  $('save').title = state.graph?.id === 'default' ? 'Duplicate the preset to save your customization' : '';
493
384
  $('undo').disabled = !state.undo.length; $('redo').disabled = !state.redo.length;
494
385
  for (const id of ['duplicate', 'export', 'layout', 'fit']) $(id).disabled = !state.graph;
495
- $('duplicate').disabled = state.saving || !state.graph || !canCreateGraph();
386
+ $('duplicate').disabled = state.saving || state.orderSaving || !state.graph || !canCreateGraph();
496
387
  renderLibrary();
497
388
  window.AndorraStudio?.heading?.();
498
389
  globalThis.AndorraManager?.heading?.();
499
390
  }
500
- // How the open graph arrived ('new', 'duplicate', 'import' or 'open'). Graph Manager's first-run tip
501
- // belongs to New graph alone, and the reason is kept for a panel script that loads after the graph.
502
391
  function graphOpened(reason) { state.openReason = reason; globalThis.AndorraManager?.graphOpened(reason); }
392
+ const graphIsFixed = graph => graph.id === 'default' || graph.preset === true;
393
+ let graphDrag = null;
394
+ let graphDropHint = null;
395
+ function clearGraphDropHint() { if (!graphDropHint) return; graphDropHint.row.classList.remove('graph-drop-above'); graphDropHint.row.classList.remove('graph-drop-below'); graphDropHint = null; }
396
+ function showGraphDropHint(row, below) { if (graphDropHint?.row === row && graphDropHint.below === below) return; clearGraphDropHint(); row.classList.add(below ? 'graph-drop-below' : 'graph-drop-above'); graphDropHint = { row, below }; }
397
+ function graphDropBelow(row, event) {
398
+ const bounds = row.getBoundingClientRect?.();
399
+ return bounds ? Number.isFinite(event.clientY) && event.clientY > bounds.top + bounds.height / 2 : false;
400
+ }
401
+ async function persistGraphOrder() {
402
+ const order = state.graphs.filter(graph => !graphIsFixed(graph)).map(graph => graph.id);
403
+ await api('/api/graph-order', { order }, { method: 'PUT' });
404
+ }
405
+ async function reorderGraph(sourceId, targetId, below) {
406
+ if (state.saving || state.orderSaving || sourceId === targetId) return;
407
+ const previous = state.graphs;
408
+ const from = previous.findIndex(item => item.id === sourceId);
409
+ if (from < 0 || graphIsFixed(previous[from])) return;
410
+ if (!previous.some(item => item.id === targetId)) return;
411
+ const list = [...previous];
412
+ const [moved] = list.splice(from, 1);
413
+ const at = list.findIndex(item => item.id === targetId);
414
+ if (at < 0) return;
415
+ const position = below ? at + 1 : at;
416
+ if (position === from) return;
417
+ list.splice(Math.max(leadFixedCount(list), position), 0, moved);
418
+ state.graphs = list;
419
+ state.orderSaving = true;
420
+ renderList();
421
+ try { await persistGraphOrder(); status('Graph order saved'); }
422
+ catch (error) {
423
+ if (state.graphs === list) { state.graphs = previous; renderList(); }
424
+ status('Graph order not saved: ' + error.message, true);
425
+ }
426
+ finally { state.orderSaving = false; renderList(); renderHeading(); }
427
+ }
428
+ function leadFixedCount(list) { let count = 0; for (const item of list) { if (!graphIsFixed(item)) break; count++; } return count; }
503
429
  function renderList() {
504
- $('new-graph').disabled = state.saving || !canCreateGraph();
430
+ $('new-graph').disabled = state.saving || state.orderSaving || !canCreateGraph();
505
431
  $('new-graph').title = canCreateGraph() ? 'Create graph' : FREE_CREATE_TIP;
506
- $('duplicate').disabled = state.saving || !state.graph || !canCreateGraph();
432
+ $('duplicate').disabled = state.saving || state.orderSaving || !state.graph || !canCreateGraph();
507
433
  $('duplicate').title = canCreateGraph() ? '' : FREE_CREATE_TIP;
508
- $('empty-create').disabled = state.saving || !canCreateGraph();
434
+ $('empty-create').disabled = state.saving || state.orderSaving || !canCreateGraph();
509
435
  $('empty-create').title = canCreateGraph() ? '' : FREE_CREATE_TIP;
510
436
  $('graphs').replaceChildren();
511
437
  const query = $('search').value.toLowerCase();
512
438
  const listed = state.graphs.filter(graph => graph.name.toLowerCase().includes(query));
439
+ const canReorder = !query && !state.saving && !state.orderSaving;
513
440
  for (const graph of listed) {
514
441
  const locked = graphLocked(graph.id);
515
442
  const button = el('button', undefined, `graph-row${state.graph?.id === graph.id ? ' active' : ''}${locked ? ' locked' : ''}`);
516
443
  button.disabled = state.saving;
517
444
  const tag = el('small', graph.id === 'default' ? 'Preset' : `v${graph.revision}`);
518
445
  button.append(el('span', graph.name), tag);
519
- // A locked row stays focusable so its tooltip and context menu (Export, Delete) still reach it;
520
- // aria-disabled says it cannot be opened, and a click explains why instead.
521
446
  if (locked) {
522
447
  button.setAttribute('aria-disabled', 'true');
523
448
  button.title = FREE_LOCKED_TIP;
524
449
  const glyph = globalThis.AndorraIcons?.icon?.('lock', 12);
525
450
  if (glyph) tag.prepend(glyph);
526
451
  }
452
+ const fixed = graphIsFixed(graph);
453
+ if (canReorder && !fixed && !locked) {
454
+ button.draggable = true;
455
+ button.title = 'Drag to reorder saved graphs';
456
+ button.ondragstart = event => {
457
+ if (state.saving || state.orderSaving || $('search').value) { event.preventDefault?.(); return; }
458
+ graphDrag = graph.id;
459
+ button.classList?.add('graph-dragging');
460
+ if (event.dataTransfer) { event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.setData('text/plain', graph.id); }
461
+ };
462
+ button.ondragend = () => { if (graphDrag === graph.id) graphDrag = null; button.classList?.remove('graph-dragging'); clearGraphDropHint(); };
463
+ button.ondragover = event => {
464
+ if (!graphDrag || graphDrag === graph.id || state.saving || state.orderSaving) return;
465
+ event.preventDefault?.();
466
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'move';
467
+ showGraphDropHint(button, graphDropBelow(button, event));
468
+ };
469
+ button.ondrop = event => {
470
+ const source = graphDrag;
471
+ graphDrag = null; clearGraphDropHint();
472
+ event.preventDefault?.();
473
+ if (!source || source === graph.id || state.saving || state.orderSaving) return;
474
+ void reorderGraph(source, graph.id, graphDropBelow(button, event));
475
+ };
476
+ }
527
477
  button.onclick = () => openGraph(graph.id);
528
478
  button.oncontextmenu = event => { event.preventDefault(); showGraphMenu(graph, event.clientX, event.clientY); };
529
479
  $('graphs').append(button);
530
480
  }
531
- // Drafts sit under their own heading, below the saved graphs. By default only the ones still
532
- // holding unsaved work are listed (the newest per graph, and not one a later revision
533
- // overtook); the history toggle lists every snapshot.
534
481
  const matching = (state.drafts || []).filter(draft => draft.name.toLowerCase().includes($('search').value.toLowerCase()));
535
482
  const latest = () => { const seen = new Set(); return matching.filter(draft => !seen.has(draft.graphId) && seen.add(draft.graphId)); };
536
483
  const current = globalThis.AndorraDrafts ? globalThis.AndorraDrafts.currentDrafts(matching, state.graphs) : latest();
@@ -558,7 +505,6 @@ function renderList() {
558
505
  $('graphs').append(button);
559
506
  }
560
507
  if (state.showDraftHistory || matching.length > current.length) {
561
- // A disclosure, as the desktop's Disclosure is: the chevron turns, the words stay (D13).
562
508
  const history = el('button', undefined, 'graph-drafts-toggle');
563
509
  history.type = 'button';
564
510
  history.setAttribute('aria-expanded', String(Boolean(state.showDraftHistory)));
@@ -567,11 +513,8 @@ function renderList() {
567
513
  history.append(el('span', state.showDraftHistory ? 'Draft history' : `Draft history (${matching.length})`));
568
514
  history.onclick = () => { state.showDraftHistory = !state.showDraftHistory; renderList(); }; $('graphs').append(history);
569
515
  }
570
- // A filter that matches nothing says so, in the EmptyState's anatomy, rather than leaving a gap.
571
516
  if (query && !listed.length && !matching.length) $('graphs').append(emptyState('search', 'No graphs match', 'Try another name, or clear the filter.'));
572
517
  }
573
- // The desktop's EmptyState (components/ui.tsx): a 16px mark, a 13/500 title, a 12px muted line and at
574
- // most one button. In the rail's lists it is the compact kind.
575
518
  function emptyState(icon, title, line, action) {
576
519
  const box = el('div', undefined, 'empty-state empty-state-compact');
577
520
  box.setAttribute('role', 'status');
@@ -582,8 +525,6 @@ function emptyState(icon, title, line, action) {
582
525
  if (action) { const row = el('div', undefined, 'empty-state-action'); row.append(action); box.append(row); }
583
526
  return box;
584
527
  }
585
- // Clearing takes a graph's drafts off the list; saved graphs and their revisions are untouched.
586
- // The open graph's edits are not lost: its next autosave is a new draft.
587
528
  async function clearDrafts(drafts, all = false) {
588
529
  const graphIds = [...new Set(drafts.map(draft => draft.graphId))];
589
530
  if (!graphIds.length) return;
@@ -592,21 +533,16 @@ async function clearDrafts(drafts, all = false) {
592
533
  try { state.drafts = await api('/api/drafts/clear', { graphIds }); if (!state.drafts.length) state.showDraftHistory = false; renderList(); status(one ? 'Draft cleared' : 'Drafts cleared'); }
593
534
  catch (error) { status('Drafts not cleared: ' + error.message, true); }
594
535
  }
595
- // Right-click actions for a saved graph row, and the Plus button's New/Import choices. The menu
596
- // floats at the pointer as a body-level overlay, so a list re-render cannot tear it down
597
- // mid-choice; a pointerdown outside it or Escape closes it.
598
536
  let closeGraphMenuHandlers;
599
537
  function closeGraphMenu() { closeGraphMenuHandlers?.(); }
600
538
  function showMenuAt(x, y, ariaLabel, items) {
601
539
  closeGraphMenu();
602
- // A harness without a body cannot host the overlay; the click then simply does nothing.
603
540
  if (!document.body?.append) return;
604
541
  const menu = el('div', undefined, 'menu-list graph-context');
605
542
  menu.id = 'graph-context-menu';
606
543
  menu.setAttribute('role', 'menu'); menu.setAttribute('aria-label', ariaLabel);
607
544
  const buttons = [];
608
545
  for (const item of items) {
609
- // A destructive item is a neutral row below a divider (C7); its confirmation names the loss.
610
546
  if (item.danger && buttons.length) { const rule = el('hr'); rule.setAttribute('role', 'separator'); menu.append(rule); }
611
547
  const button = el('button', item.label);
612
548
  button.type = 'button'; button.setAttribute('role', 'menuitem');
@@ -617,7 +553,6 @@ function showMenuAt(x, y, ariaLabel, items) {
617
553
  }
618
554
  window.AndorraIcons?.hydrate?.(menu);
619
555
  document.body.append(menu);
620
- // A menu near a window edge must not clip an item out of reach.
621
556
  const width = menu.offsetWidth || 210, height = menu.offsetHeight || 40;
622
557
  menu.style.left = `${Math.max(0, Math.min(x, (window.innerWidth || x + width + 8) - width - 8))}px`;
623
558
  menu.style.top = `${Math.max(0, Math.min(y, (window.innerHeight || y + height + 8) - height - 8))}px`;
@@ -625,15 +560,11 @@ function showMenuAt(x, y, ariaLabel, items) {
625
560
  const close = (restoreFocus = false) => {
626
561
  closeGraphMenuHandlers = undefined;
627
562
  window.removeEventListener?.('pointerdown', outside, true);
628
- // The menu leaves the way it came (controls.js); a menu opened at once is a new element.
629
563
  menu.removeAttribute?.('id'); menu.setAttribute('aria-hidden', 'true');
630
564
  leaveLayer(menu, () => menu.remove());
631
565
  if (restoreFocus) invoker?.focus?.();
632
566
  };
633
567
  const outside = event => { if (!menu.contains(event.target)) close(); };
634
- // The toolbar overflow's menu-button pattern: the opening takes focus, arrows move between
635
- // items, Escape and Tab close it and hand focus back to where it was, so focus never falls to the
636
- // page as the menu leaves.
637
568
  menu.onkeydown = event => {
638
569
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
639
570
  event.preventDefault();
@@ -648,12 +579,9 @@ function showMenuAt(x, y, ariaLabel, items) {
648
579
  }
649
580
  function showGraphMenu(graph, x, y) {
650
581
  const items = [
651
- // A locked workflow cannot seed a copy: the copy would be a second custom workflow.
652
582
  ...(graphLocked(graph.id) ? [] : [{ label: 'Duplicate', icon: 'copy', run: () => duplicateGraph(graph) }]),
653
583
  { label: 'Export JSON', icon: 'download', run: () => { exportGraph(graph).catch(error => status(error.message, true)); } },
654
584
  ];
655
- // The preset is bundled with the CLI: it has no storage to remove, and hiding it would only
656
- // last until the next launch, so deletion is offered for saved graphs alone.
657
585
  if (graph.id !== 'default') items.push({ label: 'Delete', icon: 'trash', danger: true, run: () => { deleteGraph(graph).catch(error => status(error.message, true)); } });
658
586
  showMenuAt(x, y, `${graph.name} actions`, items);
659
587
  }
@@ -663,9 +591,6 @@ function showNewGraphMenu(x, y) {
663
591
  { label: 'Import Graph', icon: 'upload', run: () => { if (window.AndorraStudio?.openImport) window.AndorraStudio.openImport(); else status('The import dialog is still loading. Try again in a moment.', true); } },
664
592
  ]);
665
593
  }
666
- // The saved revision a row names is what a friend receives: the open draft's unsaved edits are
667
- // not part of it. In the desktop host the graph id alone crosses the frame and the host writes
668
- // the file itself; a plain browser downloads the fetched revision directly.
669
594
  async function exportGraph(graph) {
670
595
  if (window.AndorraEmbed?.hostChrome?.() && window.AndorraEmbed.exportGraph) { window.AndorraEmbed.exportGraph(graph.id); return; }
671
596
  if (state.saving) { status('Wait for the current save before exporting a graph.'); return; }
@@ -682,40 +607,32 @@ function downloadJson(value, stem) {
682
607
  setTimeout(() => URL.revokeObjectURL(url), 1000);
683
608
  }
684
609
  async function duplicateGraph(source) {
685
- if (state.saving) { status('Wait for the current save before duplicating a graph.'); return; }
610
+ if (state.saving || state.orderSaving) { status('Wait for the current save before duplicating a graph.'); return; }
686
611
  state.saving = true; renderHeading(); renderList();
687
612
  let created;
613
+ let orderSaveError;
688
614
  try {
689
615
  const saved = dropLegacyTokenFields(await api(`/api/graphs/${encodeURIComponent(source.id)}`));
690
- // validateGraph caps names at 200 characters, so a near-limit source name must make room
691
- // for the suffix or the save would be rejected with no way to rename the invisible copy.
692
616
  const suffix = ' (Copy)', base = saved.name || 'Untitled graph';
693
617
  const name = base.length + suffix.length > 200 ? base.slice(0, 200 - suffix.length).trimEnd() + suffix : base + suffix;
694
618
  const duplicate = { ...saved, id: newId(), name, revision: 0 };
695
619
  const stored = await api('/api/graphs', duplicate);
696
620
  created = { id: stored.id, name: stored.name };
697
- // The rail lists graphs in the server's id order; slot the copy into that order.
698
621
  const summary = { id: stored.id, name: stored.name, revision: stored.revision };
699
- const index = state.graphs.findIndex(item => item.id !== 'default' && item.id > stored.id);
700
- if (index < 0) state.graphs.push(summary); else state.graphs.splice(index, 0, summary);
622
+ state.graphs.push(summary);
623
+ try { await persistGraphOrder(); } catch (orderError) { orderSaveError = orderError; }
701
624
  } catch (error) { status(error.message, true); }
702
625
  state.saving = false; renderHeading(); renderList();
703
626
  if (!created) return;
627
+ if (orderSaveError) status('Graph order not saved: ' + orderSaveError.message, true);
704
628
  if (state.dirty) { status(`Created "${created.name}". Open it from the list to rename it.`); return; }
705
629
  await openGraph(created.id, { reason: 'duplicate' });
706
630
  if (state.graph?.id === created.id) status(`Duplicated "${source.name}". Rename it in Graph settings.`);
707
631
  }
708
- // Deleting removes the graph, its revisions and its draft history from this machine, and for a
709
- // signed-in account the cloud copies stop restoring it. The confirm names that loss: there is no undo.
710
632
  async function deleteGraph(graph) {
711
- if (state.saving) { status('Wait for the current save before deleting a graph.'); return; }
633
+ if (state.saving || state.orderSaving) { status('Wait for the current save before deleting a graph.'); return; }
712
634
  if (!await askConfirm({ title: `Delete “${graph.name}”?`, message: 'Its versions and drafts are removed from this machine.', confirmLabel: 'Delete', tone: 'danger' })) return;
713
635
  state.saving = true; renderHeading(); renderList();
714
- // The confirm accepted the loss of unsaved edits of the deleted graph, so no draft of it may
715
- // outlive it: stop its queued write, and let an in-flight one land before the deletion's
716
- // cleanup rather than racing the removal it must not survive. A queued draft of the open
717
- // graph is not part of this deletion: flush it before the request, so the autosave of the
718
- // graph the user kept is neither discarded nor left writing during the rail refresh.
719
636
  if (!pendingDraft || pendingDraft.id === graph.id) { pendingDraft = null; clearTimeout(draftTimer); }
720
637
  else void flushDraft();
721
638
  await draftWrite?.catch(() => {});
@@ -724,49 +641,33 @@ async function deleteGraph(graph) {
724
641
  await api(`/api/graphs/${encodeURIComponent(graph.id)}`, undefined, { method: 'DELETE' });
725
642
  deleted = true;
726
643
  state.graphs = state.graphs.filter(item => item.id !== graph.id);
727
- // The free allowance pinned this graph: a stale kept id would mark a replacement read-only
728
- // through issues(), so the plan's pointer steps aside the way a reload would recompute it.
729
644
  if (state.plan?.freeGraphId === graph.id) delete state.plan.freeGraphId;
730
645
  await refreshDrafts().catch(() => {});
731
646
  } catch (error) {
732
647
  status(error.message, true);
733
- // The deletion cancelled the open graph's queued autosave. When the same graph survives the
734
- // failed request and nothing re-queued a draft while it ran, queue one again: otherwise the
735
- // edits the confirm was about to discard stay out of draft history until the next edit.
736
648
  if (state.graph?.id === graph.id && state.dirty && !pendingDraft) queueDraft();
737
649
  }
738
650
  state.saving = false; renderHeading(); renderList();
739
651
  if (!deleted) return;
740
652
  if (state.graph?.id === graph.id) {
741
- // The open graph is gone: a later save would recreate it, so fall back to the preset. The
742
- // delete already confirmed the loss of unsaved edits, so skip the second confirmation.
743
653
  state.dirty = false; pendingDraft = null; clearTimeout(draftTimer);
744
654
  await openGraph('default');
745
655
  }
746
656
  if (state.graph?.id !== graph.id) status(`Deleted "${graph.name}".`);
747
657
  }
748
658
  function position(node, index) { return node.position || { x: index * 290, y: 0 }; }
749
- // The snap lattice, in canvas units: a dragged card lands on it when Snap to grid is on, and the
750
- // canvas draws one dot on each of its points.
751
659
  const GRID_STEP = 20;
752
- // Below this many screen pixels between dots the grid doubles its step, so at a low zoom it stays a
753
- // grid rather than a haze; every dot drawn is still a snap point.
754
660
  const GRID_MIN_PX = 10;
755
661
  function transform() {
756
662
  $('scene').style.transform = `translate(${state.x}px,${state.y}px) scale(${state.zoom})`;
757
- // The dot grid lives in canvas space, so it moves and scales with the cards. A dot is drawn at the
758
- // centre of its tile, so the tile starts half a step before the lattice point it marks.
759
663
  let step = GRID_STEP * state.zoom;
760
664
  while (step < GRID_MIN_PX) step *= 2;
761
665
  const canvas = $('canvas');
762
666
  if (canvas?.style) { canvas.style.backgroundSize = `${step}px ${step}px`; canvas.style.backgroundPosition = `${state.x - step / 2}px ${state.y - step / 2}px`; }
763
667
  $('zoom').textContent = `${Math.round(state.zoom * 100)}%`; window.AndorraStudio?.viewport?.();
764
668
  }
765
- // Pan and pinch arrive many times a frame; the view is written once per frame.
766
669
  let transformFrame = 0;
767
670
  function requestTransform() { transformFrame ||= nextFrame(() => { transformFrame = 0; transform(); }); }
768
- // The canvas tips show until the reader dismisses them once. The choice is a per-browser
769
- // convenience, so unavailable storage simply shows the tips again next time.
770
671
  const HINT_KEY = 'andorra-graph-canvas-hint-dismissed';
771
672
  function canvasHintDismissed() {
772
673
  if (state.canvasHintDismissed) return true;
@@ -775,10 +676,9 @@ function canvasHintDismissed() {
775
676
  function dismissCanvasHint() {
776
677
  if (canvasHintDismissed()) return;
777
678
  state.canvasHintDismissed = true;
778
- try { localStorage.setItem(HINT_KEY, '1'); } catch { /* The tips still hide for this session. */ }
679
+ try { localStorage.setItem(HINT_KEY, '1'); } catch { }
779
680
  if (!state.routePick && $('canvas-hint')) $('canvas-hint').hidden = true;
780
681
  }
781
- // The model a card names: its own override, else the model its provider profile runs.
782
682
  function nodeModelLabel(node) {
783
683
  if (node.model) return node.model;
784
684
  const providerId = node.provider || state.defaultProvider;
@@ -808,7 +708,6 @@ function renderCanvas() {
808
708
  nodes.forEach((node, index) => {
809
709
  const p = positions.get(node.id), button = el('div', undefined, `node ${node.type}${selectedNodes().some(item=>item.id===node.id) ? ' selected' : ''}${errorIds.has(node.id) ? ' node-error' : ''}${state.routePick && !state.routePick.sources.includes(node.id) && node.agentRole !== 'orchestrator' ? ' route-target' : ''}`);
810
710
  button.tabIndex = 0; button.setAttribute('data-node-id',node.id); button.setAttribute('role', 'button'); button.style.left = `${p.x}px`; button.style.top = `${p.y}px`; button.setAttribute('aria-label', `${node.name}, ${node.agentRole === 'orchestrator' ? 'orchestrator' : node.type}${node.id === state.graph.entry ? ', entry' : ''}`);
811
- // The kind is the card's stripe and icon; the subtitle names what the node runs.
812
711
  const title = el('div', undefined, 'node-title'), glyph = nodeIconElement(node);
813
712
  if (glyph) title.append(glyph);
814
713
  title.append(el('b', node.name || 'Untitled'));
@@ -821,9 +720,6 @@ function renderCanvas() {
821
720
  button.onclick = event => selectNode(node,event);
822
721
  button.onpointerdown = event => {
823
722
  if (event.button !== 0) return; event.stopPropagation(); if(event.ctrlKey || event.metaKey || state.routePick) return; state.suppressClick=null; const start = { x: event.clientX, y: event.clientY }, origin = position(node, index); let moved = false;
824
- // A drag moves this one card and re-routes only its own connections, once per frame
825
- // (dragFrame). The full paint — every route, validation, the status line, the draft — runs
826
- // once, on release; before, every pointer move rebuilt the whole canvas.
827
723
  let boxes = null, latest = null, frame = 0;
828
724
  const paint = () => { frame = 0; if (!latest) return; node.position = latest; dragFrame(node, boxes); };
829
725
  const move = e => {
@@ -843,16 +739,10 @@ function renderCanvas() {
843
739
  $('nodes').append(button);
844
740
  }); transform(); renderEdges(); window.AndorraStudio?.canvas?.();
845
741
  }
846
- // One animation frame, or at once where there are no frames (a harness without a renderer).
847
742
  const nextFrame = callback => (typeof requestAnimationFrame === 'function' ? requestAnimationFrame(callback) : (callback(), 0));
848
743
  const cancelFrame = frame => { if (frame && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frame); };
849
- // Every connection's route, computed together in edge-list order (AndorraEdgeRouter.routeEdges) and
850
- // kept until the cards or the connections change. The corner points are kept as well, so a drag can
851
- // re-route the connections it moves while keeping them off the others.
852
744
  let routedKey = '', routedPaths = [], routedPoints = [];
853
- // The drawn parts of each connection, by its index in the edge list: what a drag frame updates.
854
745
  let drawnEdges = [];
855
- /** Each card's box in canvas units and the centre of each of its outcome ports, measured once. */
856
746
  function measureBoxes() {
857
747
  const boxes = new Map(), elements = new Map(Array.from($('nodes').children).map(item => [item.getAttribute('data-node-id'), item]));
858
748
  Object.values(state.graph.nodes).forEach((node, index) => {
@@ -863,23 +753,15 @@ function measureBoxes() {
863
753
  });
864
754
  return boxes;
865
755
  }
866
- /** Where a connection leaves its source's outcome port and where it enters its target. */
867
756
  function routeInput(edge, boxes) {
868
757
  const from = boxes.get(edge.source), to = boxes.get(edge.target); if (!from || !to) return null;
869
758
  const source = from.ports[Math.max(0, outcomes(state.graph.nodes[edge.source]).indexOf(edgeOutcome(edge)))];
870
759
  return source ? { source, target: { x: to.x, y: to.y + 48 } } : null;
871
760
  }
872
- // Elbows are drawn rounded; a router without the helper keeps its square corners.
873
761
  const drawnRoute = points => points && { d: (AndorraEdgeRouter.roundedPath || AndorraEdgeRouter.path)(points), label: AndorraEdgeRouter.labelPoint?.(points) };
874
- /**
875
- * One frame of a node drag. The card moves by its transform alone, and only the connections that
876
- * touch it are routed again — each kept off the routes the last full paint laid out — and written
877
- * into the paths already drawn. No element is created or removed.
878
- */
879
762
  function dragFrame(node, boxes) {
880
763
  const element = Array.from($('nodes').children).find(item => item.getAttribute('data-node-id') === node.id), box = boxes?.get(node.id), p = node.position;
881
764
  if (!element || !box) return;
882
- // Measured from where the card was last painted, so a repaint mid-drag cannot double the offset.
883
765
  element.style.transform = `translate(${p.x - parseFloat(element.style.left)}px, ${p.y - parseFloat(element.style.top)}px)`;
884
766
  box.x = p.x; box.y = p.y; box.ports = box.offsets.map(offset => ({ x: p.x + box.width, y: p.y + offset }));
885
767
  const edges = state.graph.edges, moving = edges.map((edge, index) => (edge.source === node.id || edge.target === node.id ? index : -1)).filter(index => index >= 0);
@@ -896,7 +778,6 @@ function dragFrame(node, boxes) {
896
778
  }
897
779
  window.AndorraStudio?.dragged?.();
898
780
  }
899
- /** Put an outcome pill on its route's label point. */
900
781
  function placePill(pill, at) {
901
782
  pill.rect.setAttribute('x', String(Math.round(at.x - pill.width / 2))); pill.rect.setAttribute('y', String(at.y - PILL_HEIGHT / 2));
902
783
  pill.text.setAttribute('x', String(Math.round(at.x))); pill.text.setAttribute('y', String(at.y + 4));
@@ -909,8 +790,6 @@ function renderEdges() {
909
790
  const defs=svg('defs'); $('edges').append(defs);
910
791
  const boxes=measureBoxes();
911
792
  const rectangles=[...boxes.values()], rendered=[], pills=[], palette=connectionPalette();
912
- // Routes are laid out in the edge list's order, never the drawing order below, so selecting a
913
- // connection does not move any line. Each route keeps clear of those laid out before it.
914
793
  const routeInputs=state.graph.edges.map(edge=>routeInput(edge,boxes));
915
794
  const routesKey=JSON.stringify([[...boxes].map(([id,box])=>[id,box.x,box.y,box.width,box.height,box.ports]),routeInputs]);
916
795
  if(routesKey!==routedKey){
@@ -919,8 +798,6 @@ function renderEdges() {
919
798
  routedPaths=routedPoints.map(drawnRoute);
920
799
  }
921
800
  const caption=svg('text'); caption.setAttribute('class','edge-caption'); caption.style.pointerEvents='none';
922
- // A traced connection (hovered, focused or selected) is drawn in the accent ink, a little heavier,
923
- // and the others step back; nothing else about a connection changes its colour.
924
801
  const emphasize = active => {
925
802
  for (const item of rendered) {
926
803
  const on=item.edge===active;
@@ -940,7 +817,6 @@ function renderEdges() {
940
817
  caption.textContent=item?`${edgeOutcome(item.edge)} → ${state.graph.nodes[item.edge.target].name}`:'';
941
818
  if(item){caption.setAttribute('x',String(item.from.x));caption.setAttribute('y',String(item.from.y-14));caption.setAttribute('fill',palette.active);}
942
819
  };
943
- // Draw a selected connection last so crossings cannot obscure its direction.
944
820
  const ordered=state.graph.edges.map((edge,index)=>({edge,index})).sort((a,b)=>Number(a.edge===state.selectedEdge)-Number(b.edge===state.selectedEdge));
945
821
  ordered.forEach(({edge,index})=>{
946
822
  const from=boxes.get(edge.source),route=routedPaths[index];if(!from||!route)return;
@@ -954,14 +830,12 @@ function renderEdges() {
954
830
  hit.setAttribute('d',d);hit.setAttribute('stroke','transparent');hit.setAttribute('stroke-width','14');hit.setAttribute('fill','none');hit.style.pointerEvents='stroke';hit.style.cursor='pointer';hit.setAttribute('tabindex','0');hit.setAttribute('role','button');hit.setAttribute('aria-label',`Edit connection from ${state.graph.nodes[edge.source].name}, ${edgeOutcome(edge)}, to ${state.graph.nodes[edge.target].name}`);
955
831
  hit.onclick=event=>{event.stopPropagation();clearSelection();state.selectedEdge=edge;renderInspector();renderCanvas();showInspector();};
956
832
  hit.onkeydown=event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();hit.onclick(event);}};
957
- // The connection's hint is the app's tooltip (an SVG title would be the platform's).
958
833
  hit.setAttribute('data-tip',`${state.graph.nodes[edge.source].name}: ${outcome} → ${state.graph.nodes[edge.target].name}`);
959
834
  hit.onpointerenter=hit.onfocus=()=>emphasize(edge);
960
835
  hit.onpointerleave=hit.onblur=()=>emphasize(state.selectedEdge);
961
836
  const entry={edge,path,halo,arrow,from,pill:null};rendered.push(entry);
962
837
  drawnEdges[index]={path,halo,hit,pill:null};
963
838
  $('edges').append(halo,path,hit);
964
- // The outcome rides its line as a pill. A node's only, default outcome needs no name.
965
839
  const single=outcomes(state.graph.nodes[edge.source]).length===1&&outcome==='completed';
966
840
  if(route.label&&!single)pills.push({entry,index,outcome,at:route.label});
967
841
  });
@@ -977,7 +851,6 @@ function renderEdges() {
977
851
  entry.pill=group;drawnEdges[index].pill=pill;drawnPills.push({pill,at});
978
852
  }
979
853
  $('edges').append(pillLayer,caption);
980
- // A pill fits its word as the face sets it; the estimate stands in where nothing is rendered.
981
854
  for(const {pill,at} of drawnPills){
982
855
  const measured=typeof pill.text.getComputedTextLength==='function'?pill.text.getComputedTextLength():0;
983
856
  if(measured>0)pill.width=Math.max(28,Math.ceil(measured+16));
@@ -997,7 +870,6 @@ function removeNodes(ids) {
997
870
  graph.edges = graph.edges.filter(edge => !ids.has(edge.source) && !ids.has(edge.target));
998
871
  if (graph.metadata?.studioLayoutGroupsV1) { for (const group of graph.metadata.studioLayoutGroupsV1) group.nodeIds = group.nodeIds.filter(id => !ids.has(id)); graph.metadata.studioLayoutGroupsV1 = graph.metadata.studioLayoutGroupsV1.filter(group => group.nodeIds.length); }
999
872
  graph.entry = nextEntry;
1000
- // Explicitly preserve an edited graph without intake when it is reopened.
1001
873
  graph.schemaVersion = 3;
1002
874
  clearSelection();
1003
875
  }, true);
@@ -1014,7 +886,7 @@ function field(parent, label, value, onChange, options = {}) {
1014
886
  const input = el(options.multiline ? 'textarea' : options.options ? 'select' : 'input');
1015
887
  if (options.options) for (const option of options.options) { const item = el('option', option.label); item.value = option.value; input.append(item); }
1016
888
  if (options.type) input.type = options.type;
1017
- if (options.type === 'number') input.step = '1';
889
+ if (options.type === 'number') input.step = options.step ?? '1';
1018
890
  if (options.min !== undefined) input.min = options.min; if (options.max !== undefined) input.max = options.max;
1019
891
  if (options.maxLength !== undefined) input.maxLength = options.maxLength;
1020
892
  if (options.placeholder !== undefined) input.placeholder = options.placeholder;
@@ -1023,9 +895,6 @@ function field(parent, label, value, onChange, options = {}) {
1023
895
  wrapper.append(input); parent.append(wrapper); return input;
1024
896
  }
1025
897
  function section(parent, title) { const item = el('section', undefined, 'section'); item.append(el('h3', title)); parent.append(item); return item; }
1026
- // Normalize one validation error for display. Client issues carry the node id directly, so two
1027
- // agents sharing a display name cannot misattribute an aura or a click-to-focus; a server
1028
- // message names its node by the `node <id>:` label or `${node.name}:` and is matched the old way.
1029
898
  function errorEntry(error) {
1030
899
  if (typeof error === 'string') {
1031
900
  return { message: error, nodeId: Object.values(state.graph?.nodes || {}).find(node => error.includes('node ' + node.id) || error.includes(node.name + ':'))?.id ?? null };
@@ -1044,9 +913,6 @@ function renderValidation() {
1044
913
  }
1045
914
  function disclosure(parent, title, open = false) { const item = el('details', undefined, 'section disclosure'); const key = `${state.selectedEdge?.id || state.selected || 'graph'}:${title}`; item.open = state.disclosures[key] ?? open; item.ontoggle = () => {state.disclosures[key] = item.open;}; item.append(el('summary', title)); const body = el('div'); item.append(body); parent.append(item); return body; }
1046
915
  function check(parent, label, value, update) { const wrapper = el('label', undefined, 'tool-label'), input = el('input'); input.type = 'checkbox'; input.checked = value; input.onchange = () => mutate(() => update(input.checked), true); wrapper.append(input, el('span', label)); parent.append(wrapper); return input; }
1047
- // A "?" beside a label keeps a long explanation one hover, focus or tap away (ADR 0022). The text
1048
- // stays in the document as the trigger's accessible description. `target` is a field's input, its
1049
- // label, or a heading; anything else receives the explanation as an ordinary paragraph.
1050
916
  let infoTipSeq = 0;
1051
917
  const tipHost = item => !!item && (item.className === 'field' || item.className === 'field prompt-field' || item.className === 'tool-label' || item.tagName === 'h3' || item.tagName === 'H3');
1052
918
  function explain(target, text) {
@@ -1057,15 +923,11 @@ function explain(target, text) {
1057
923
  body.id = id; body.setAttribute('role', 'tooltip');
1058
924
  trigger.type = 'button'; trigger.setAttribute('aria-label', 'More information'); trigger.setAttribute('aria-describedby', id);
1059
925
  const glyph = globalThis.AndorraIcons?.icon?.('help', 14); if (glyph) trigger.append(glyph); else trigger.textContent = '?';
1060
- // The trigger sits inside a label, so its click must not reach the label's control.
1061
926
  trigger.onclick = event => { event?.preventDefault?.(); event?.stopPropagation?.(); tip.classList.toggle('open'); };
1062
927
  trigger.onkeydown = event => { if (event.key === 'Escape') { tip.classList.remove('open'); trigger.blur?.(); } };
1063
928
  trigger.onblur = () => tip.classList.remove('open');
1064
929
  tip.append(trigger, body); host.append(tip);
1065
930
  }
1066
- // The inspector's node settings are split into tabs. Every panel is rendered, so a field keeps its
1067
- // place in the document and the validity check before saving can still reach it; only the chosen
1068
- // panel is shown. The choice is kept across selections, so moving between nodes stays on a tab.
1069
931
  const INSPECTOR_TABS = { general: 'General', model: 'Model', behavior: 'Behavior', advanced: 'Advanced' };
1070
932
  let inspectorTabControls = [];
1071
933
  function selectInspectorTab(id, focus = false) {
@@ -1077,7 +939,6 @@ function selectInspectorTab(id, focus = false) {
1077
939
  if (active && focus) item.tab.focus?.();
1078
940
  }
1079
941
  }
1080
- // Shows the panel holding a control, used before a control in a hidden panel reports a problem.
1081
942
  function revealInspectorControl(control) {
1082
943
  for (const item of inspectorTabControls) if (item.panel.contains?.(control)) { selectInspectorTab(item.id); return; }
1083
944
  }
@@ -1100,18 +961,16 @@ function inspectorTabs(parent, ids) {
1100
961
  bar.append(tab); panels[id] = panel; inspectorTabControls.push({ id, tab, panel });
1101
962
  }
1102
963
  for (const id of ids) parent.append(panels[id]);
1103
- // Selecting is an inspection, not a choice: only a click on a tab changes the remembered tab.
1104
964
  const remembered = state.inspectorTab;
1105
965
  selectInspectorTab(active);
1106
966
  if (remembered !== undefined && !ids.includes(remembered)) state.inspectorTab = remembered;
1107
967
  return panels;
1108
968
  }
1109
- // The prompt grows with its text up to a ceiling, and a button opens it full screen.
1110
969
  function promptField(parent, label, value, onChange, options = {}) {
1111
970
  const input = field(parent, label, value, onChange, { multiline: true, maxLength: 100000, ...options });
1112
971
  const wrapper = input.parentElement; wrapper.className = 'field prompt-field';
1113
972
  const isFullscreen = () => !!wrapper.classList.contains?.('fullscreen');
1114
- const grow = () => { try { if (!isFullscreen() && input.scrollHeight) { input.style.height = 'auto'; input.style.height = `${input.scrollHeight + 2}px`; } } catch { /* A partial DOM has no layout. */ } };
973
+ const grow = () => { try { if (!isFullscreen() && input.scrollHeight) { input.style.height = 'auto'; input.style.height = `${input.scrollHeight + 2}px`; } } catch { } };
1115
974
  input.addEventListener?.('input', grow);
1116
975
  const expand = el('button', undefined, 'icon-button btn-small prompt-expand'); expand.type = 'button';
1117
976
  let backdrop;
@@ -1131,18 +990,14 @@ function promptField(parent, label, value, onChange, options = {}) {
1131
990
  setTimeout(grow, 0);
1132
991
  return input;
1133
992
  }
1134
- // Typing `/` in a prompt opens this machine's skills (skill-picker.js); a `/name` none of them
1135
- // answers to is a warning under the field, never a validation error.
1136
993
  function skillPrompt(input) {
1137
994
  globalThis.AndorraSkillPicker?.attach?.(input, { load: () => api('/api/skills') });
1138
995
  return input;
1139
996
  }
1140
- // A provider the graph names but this machine does not configure is a warning, not a model name.
1141
997
  function providerWarning(parent, providerId) {
1142
998
  const chip = el('p', undefined, 'chip chip-warning provider-warning'); chip.setAttribute('role', 'status');
1143
999
  const glyph = globalThis.AndorraIcons?.icon?.('warning', 14); if (glyph) chip.append(glyph);
1144
1000
  chip.append(el('span', `${providerId} unavailable`));
1145
- // The desktop app can open its provider settings; a browser-launched studio has no such route.
1146
1001
  if (typeof window.AndorraEmbed?.openProviderSettings === 'function' && window.AndorraEmbed.hostChrome?.()) {
1147
1002
  const configure = el('button', 'Configure', 'link-button'); configure.type = 'button';
1148
1003
  configure.title = 'Open provider settings in the desktop app'; configure.onclick = () => window.AndorraEmbed.openProviderSettings();
@@ -1151,8 +1006,53 @@ function providerWarning(parent, providerId) {
1151
1006
  parent.append(chip);
1152
1007
  }
1153
1008
  function choice(parent, label, value, values, update, refresh = true) { return field(parent, label, value, update, { options: values.map(v => typeof v === 'string' ? {value: v, label: v.replaceAll('-', ' ')} : v), refresh }); }
1154
- function jsonField(parent, label, value, update) {
1155
- const wrapper = el('label', undefined, 'field'); wrapper.append(el('span', label)); const input = el('textarea'); input.className = 'mono'; input.value = value === undefined ? '' : JSON.stringify(value, null, 2); input.onchange = () => { try { const parsed = input.value.trim() ? JSON.parse(input.value) : undefined; input.setCustomValidity(''); mutate(() => update(parsed)); } catch { input.setCustomValidity('Enter valid JSON or clear this field.'); input.reportValidity(); } }; wrapper.append(input); parent.append(wrapper);
1009
+ const msToSeconds = ms => ms === undefined ? undefined : ms / 1000;
1010
+ const secondsToMs = seconds => seconds === undefined ? undefined : Math.round(seconds * 1000);
1011
+ // The saved graph keeps wallTimeMs; the editor shows and takes seconds.
1012
+ const RUN_LIMITS_JSON = {
1013
+ label: 'Run limits',
1014
+ keys: [
1015
+ { key: 'maxNodeVisits', description: 'Most times one step may run. 0 is unlimited.' },
1016
+ { key: 'maxConcurrency', description: 'Most steps running at once, 1 to 32.' },
1017
+ { key: 'maxToolCalls', description: 'Most tool calls across the whole run.' },
1018
+ { key: 'wallTimeSeconds', description: 'Longest the run may take, in seconds. 0 is unlimited.' },
1019
+ ],
1020
+ offer: context => context.depth <= 1,
1021
+ show(limits) {
1022
+ if (!limits || typeof limits !== 'object' || limits.wallTimeMs === undefined) return limits;
1023
+ return Object.fromEntries(Object.entries(limits).map(([key, value]) => key === 'wallTimeMs' ? ['wallTimeSeconds', value / 1000] : [key, value]));
1024
+ },
1025
+ read(limits) {
1026
+ if (!limits || typeof limits !== 'object' || Array.isArray(limits) || !Object.hasOwn(limits, 'wallTimeSeconds')) return limits;
1027
+ if (Object.hasOwn(limits, 'wallTimeMs')) throw new Error('Set wallTimeSeconds or wallTimeMs, not both.');
1028
+ const seconds = limits.wallTimeSeconds;
1029
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds < 0) throw new Error('wallTimeSeconds must be a number of seconds, 0 or more.');
1030
+ return Object.fromEntries(Object.entries(limits).map(([key, value]) => key === 'wallTimeSeconds' ? ['wallTimeMs', secondsToMs(value)] : [key, value]));
1031
+ },
1032
+ };
1033
+ const SCHEMA_JSON = {
1034
+ label: 'Schema keywords',
1035
+ keys: [
1036
+ { key: 'type', description: 'object, array, string, number, integer, boolean or null.' },
1037
+ { key: 'properties', description: 'The fields of an object, each with its own schema.' },
1038
+ { key: 'required', description: 'Names of the fields that must be present.' },
1039
+ { key: 'items', description: 'The schema every array entry follows.' },
1040
+ { key: 'additionalProperties', description: 'false refuses fields that properties does not name.' },
1041
+ { key: 'format', description: 'A format a string must follow.' },
1042
+ ],
1043
+ // Inside "properties" the keys are the author's own field names.
1044
+ offer: context => context.parentKey !== 'properties',
1045
+ };
1046
+ function jsonField(parent, label, value, update, options = {}) {
1047
+ const shown = options.show ? options.show(value) : value;
1048
+ const wrapper = el('label', undefined, 'field'); wrapper.append(el('span', label)); const input = el('textarea'); input.className = 'mono'; input.value = shown === undefined ? '' : JSON.stringify(shown, null, 2);
1049
+ input.onchange = () => {
1050
+ try { let parsed = input.value.trim() ? JSON.parse(input.value) : undefined; if (options.read) parsed = options.read(parsed); input.setCustomValidity(''); mutate(() => update(parsed)); }
1051
+ catch (error) { input.setCustomValidity(error instanceof SyntaxError ? 'Enter valid JSON or clear this field.' : error.message); input.reportValidity(); }
1052
+ };
1053
+ wrapper.append(input); parent.append(wrapper);
1054
+ if (options.keys) globalThis.AndorraSkillPicker?.attachKeys?.(input, options);
1055
+ return input;
1156
1056
  }
1157
1057
  const CAPABILITIES = { filesystem: ['none', 'read', 'read-write'], shell: ['disabled', 'read-only', 'allowed'], git: ['none', 'read', 'write'], github: ['none', 'read', 'pull-request', 'review'], browser: ['disabled', 'playwright'], deployment: ['none', 'allowed'] };
1158
1058
  function capabilities(parent, policy, update, ceiling) {
@@ -1162,42 +1062,84 @@ function capabilities(parent, policy, update, ceiling) {
1162
1062
  }
1163
1063
  }
1164
1064
  let modelSuggestionSeq = 0;
1165
- function modelFields(parent, target, update, parentModel, inheritedProvider, fallbackProvider) {
1166
- // The provider dropdown lists every configured provider by name; the Model dropdown under it
1167
- // lists every model the chosen provider serves. Labelling each provider with its one active
1168
- // model made the provider list read as the whole model list.
1169
- const providers = state.providers.map(p => ({value: idFor(p), label: titleFor(p)}));
1170
- if (target.provider && !providers.some(p => p.value === target.provider)) providers.push({value: target.provider, label: target.provider + ' (unavailable)'});
1171
- const defaultProviderLabel = inheritedProvider ? `Same as parent agent (${inheritedProvider})` : state.defaultProvider ? `Use configured default (${state.defaultProvider})` : 'Use configured default';
1172
- choice(parent, 'Provider', target.provider || '', [{value:'', label: defaultProviderLabel}, ...providers], value => update({ ...target, provider: value || undefined, model: undefined }));
1173
- if (target.provider && !state.providers.some(p => idFor(p) === target.provider)) providerWarning(parent, target.provider);
1174
- // A providerless subagent child inherits the parent node's provider at execution
1175
- // (bindPortableGraphProviders adds its model to the parent's requirements), so the suggestions
1176
- // shown here and the recording that makes a discovered pick runnable must resolve against that
1177
- // inherited provider, not the machine default, or the selection lands on the wrong provider.
1065
+ function modelPickerButton(spec) {
1066
+ const button = el('button', undefined, 'model-picker-trigger'); button.type = 'button';
1067
+ button.setAttribute('aria-haspopup', 'dialog'); button.setAttribute('aria-expanded', 'false');
1068
+ button.modelPicker = spec;
1069
+ button.redraw = () => {
1070
+ const { model, provider, entry, note } = spec.current();
1071
+ button.replaceChildren();
1072
+ const mark = globalThis.AndorraModelPicker?.mark?.(entry);
1073
+ if (mark) button.append(mark);
1074
+ button.append(el('span', model, 'model-picker-trigger-name'));
1075
+ if (note) button.append(el('span', note, 'model-picker-trigger-note'));
1076
+ if (provider) button.append(el('span', provider, 'model-picker-trigger-provider'));
1077
+ const chevron = el('span', undefined, 'model-picker-trigger-chevron'); const glyph = globalThis.AndorraIcons?.icon?.('chevron-down', 14); if (glyph) chevron.append(glyph);
1078
+ button.append(chevron);
1079
+ button.setAttribute('aria-label', `${spec.ariaLabel}: ${model}${note ? ` (${note})` : ''}${provider ? `, ${provider}` : ''}`);
1080
+ button.title = [model + (note ? ` (${note})` : ''), provider].filter(Boolean).join(' · ');
1081
+ };
1082
+ button.redraw();
1083
+ button.onclick = () => globalThis.AndorraModelPicker?.toggle(button);
1084
+ return button;
1085
+ }
1086
+ function discoverProviderModels(providerId) {
1087
+ state.providerModelRequests ||= new Map();
1088
+ state.providerModelCatalogs ||= new Map();
1089
+ const registryGeneration = state.providerRegistryGeneration || 0;
1090
+ if (!state.providerModelRequests.has(providerId)) state.providerModelRequests.set(providerId, api(`/api/provider-models?provider=${encodeURIComponent(providerId)}`).catch(() => ({ models: [] })));
1091
+ return state.providerModelRequests.get(providerId).then(data => {
1092
+ if ((state.providerRegistryGeneration || 0) !== registryGeneration) return data;
1093
+ state.providerModelCatalogs.set(providerId, (data.models || []).map(name => name?.trim()).filter(Boolean));
1094
+ return data;
1095
+ });
1096
+ }
1097
+ function modelFields(parent, target, update, parentModel, inheritedProvider, fallbackProvider, options = {}) {
1178
1098
  const listingProvider = target.provider || inheritedProvider || state.defaultProvider || '';
1179
1099
  const provider = state.providers.find(p => idFor(p) === listingProvider);
1180
1100
  const activeName = provider?.model?.trim() || '';
1181
- // Every model the resolved provider serves: its configured models first, then whatever its
1182
- // endpoint lists once discovery answers (filled in by addModelOption below). Picking one commits
1183
- // through the custom-name field so a discovered pick is recorded exactly as a typed one is.
1184
- const picker = field(parent, 'Model', '', () => {}, { options: [] });
1185
- const pickerModels = [];
1186
1101
  const inheritedModel = parentModel?.trim() || activeName;
1187
- const renderPicker = () => {
1188
- picker.replaceChildren();
1189
- const rows = [{ value: '', label: inheritedModel ? `${parentModel ? 'Same as parent' : 'Provider default'} (${inheritedModel})` : 'Provider default' },
1190
- ...pickerModels.map(name => ({ value: name, label: name === activeName ? `${name} (active)` : name }))];
1191
- for (const row of rows) { const option = el('option', row.label); option.value = row.value; picker.append(option); }
1192
- picker.value = target.model?.trim() || '';
1193
- // Discovery can answer while the list is open; the branded panel copies the options when it
1194
- // opens, so redraw it or the newly served models stay out of reach until it is reopened.
1195
- window.AndorraControls?.refreshSelect?.(picker);
1196
- };
1197
- renderPicker();
1198
- // Surface portability without rewriting the synced revision or local credentials. The alias must
1199
- // satisfy every reference to the original provider graph-wide (bindPortableGraphProviders groups
1200
- // them), so the hint mirrors that grouping instead of promising an alias execution would refuse.
1102
+ const effectiveProvider = target.provider || listingProvider;
1103
+ const entryFor = id => { const p = state.providers.find(item => idFor(item) === id); return p ? { id, label: titleFor(p), type: p.type, baseUrl: p.baseUrl } : id ? { id, label: `${id} (unavailable)` } : undefined; };
1104
+ const configuredOn = id => { const p = state.providers.find(item => idFor(item) === id); return [p?.model, ...(p?.models || [])].map(name => name?.trim()).filter(Boolean); };
1105
+ const pickerModels = [];
1106
+ const defaultLabel = options.defaultLabel || (inheritedProvider || parentModel ? 'Same as parent agent' : 'Use configured default');
1107
+ const clearedProvider = inheritedProvider || state.defaultProvider || '';
1108
+ const clearedModel = parentModel?.trim() || state.providers.find(p => idFor(p) === clearedProvider)?.model?.trim() || '';
1109
+ const defaultHint = options.defaultLabel ? '' : [clearedProvider ? entryFor(clearedProvider)?.label : '', clearedModel].filter(Boolean).join(' · ');
1110
+ const pickerButton = modelPickerButton({
1111
+ ariaLabel: 'Model',
1112
+ current: () => {
1113
+ const pinned = target.model?.trim();
1114
+ const entry = entryFor(effectiveProvider);
1115
+ if (!pinned && !target.provider && options.defaultLabel) return { model: options.defaultLabel, provider: '', entry: undefined };
1116
+ return { model: pinned || inheritedModel || 'Provider default', note: pinned || !inheritedModel ? '' : 'default', provider: entry?.label || '', entry };
1117
+ },
1118
+ groups: () => {
1119
+ const ids = state.providers.map(idFor);
1120
+ if (target.provider && !ids.includes(target.provider)) ids.push(target.provider);
1121
+ return ids.map(id => {
1122
+ const active = state.providers.find(item => idFor(item) === id)?.model?.trim() || '';
1123
+ const names = [...configuredOn(id), ...(state.providerModelCatalogs?.get(id) || [])];
1124
+ if (id === effectiveProvider) names.push(...pickerModels);
1125
+ return { provider: entryFor(id), models: [...new Set(names)].map(model => ({ model, note: model === active ? 'active' : '' })) };
1126
+ });
1127
+ },
1128
+ selected: () => target.model?.trim() ? { provider: effectiveProvider, model: target.model.trim() } : null,
1129
+ defaultRow: () => options.noDefault ? undefined : ({ label: defaultLabel, hint: defaultHint, selected: !target.provider && !target.model?.trim() }),
1130
+ pickDefault: () => mutate(() => update({ ...target, provider: undefined, model: undefined }), true),
1131
+ pick: ({ provider: chosenProvider, model: chosenModel }) => {
1132
+ if (chosenProvider === effectiveProvider && !(options.requireProvider && !target.provider)) { model.value = chosenModel; model.onchange(); return; }
1133
+ mutate(() => update({ ...target, provider: chosenProvider, model: chosenModel }), true);
1134
+ if (!configuredOn(chosenProvider).includes(chosenModel) && state.providerModelCatalogs?.get(chosenProvider)?.includes(chosenModel)) recordWith(chosenProvider, chosenModel);
1135
+ },
1136
+ onOpen: () => {
1137
+ for (const p of state.providers) discoverProviderModels(idFor(p)).then(() => globalThis.AndorraModelPicker?.refresh?.(pickerButton));
1138
+ },
1139
+ });
1140
+ const pickerField = el('div', undefined, 'field model-picker-field'); pickerField.append(el('span', 'Model'), pickerButton); parent.append(pickerField);
1141
+ const renderPicker = () => { pickerButton.redraw(); globalThis.AndorraModelPicker?.refresh?.(pickerButton); };
1142
+ if (target.provider && !state.providers.some(p => idFor(p) === target.provider)) providerWarning(parent, target.provider);
1201
1143
  if (target.provider) {
1202
1144
  const originalId = target.provider;
1203
1145
  const recorded = state.graph?.metadata?.graphProviderProfilesV1?.[originalId];
@@ -1206,7 +1148,7 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1206
1148
  const note = (reference, parentProvider) => {
1207
1149
  if (reference.provider !== originalId) return;
1208
1150
  if (reference.model) { explicit.add(reference.model); return; }
1209
- if (parentProvider === originalId) return; // Same-provider child without a model inherits the parent at execution.
1151
+ if (parentProvider === originalId) return;
1210
1152
  groupInheritsRecorded = true;
1211
1153
  };
1212
1154
  for (const node of Object.values(state.graph?.nodes || {})) {
@@ -1230,18 +1172,11 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1230
1172
  else if (policy.modelPolicy === 'per-role') for (const role of policy.roles || []) note(role, node.provider);
1231
1173
  }
1232
1174
  const explicitModels = [...explicit];
1233
- // The live-model hint describes the inspected selection, not the whole provider group: another
1234
- // reference being unpinned must not claim this one has no override.
1235
1175
  const followsProvider = target.model === undefined && parentModel === undefined;
1236
1176
  const requiredModels = groupInheritsRecorded && recorded?.model ? [...explicitModels, recorded.model] : explicitModels;
1237
1177
  const offers = (p, models) => models.every(model => [p.model, ...(p.models || [])].includes(model));
1238
- // A same-ID local provider is authoritative; its current model is what an unpinned reference
1239
- // uses, so the recorded model is only an alias requirement. This mirrors
1240
- // bindPortableGraphProviders, which execution calls before every run.
1241
1178
  const exact = state.providers.find(p => idFor(p) === originalId && (!recorded?.type || p.type === recorded.type) && offers(p, explicitModels));
1242
1179
  if (!exact) {
1243
- // A local provider that owns the original ID blocks aliasing even when it cannot satisfy
1244
- // the graph, so the editor must not promise a Codex profile execution will refuse.
1245
1180
  const claimedProvider = state.providers.find(p => idFor(p) === originalId);
1246
1181
  const claimed = claimedProvider !== undefined;
1247
1182
  const typeMismatch = claimed && !!recorded?.type && claimedProvider.type !== recorded.type;
@@ -1263,8 +1198,6 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1263
1198
  }
1264
1199
  const info = el('p', 'Context window: detecting from model…', 'help model-context'); parent.append(info);
1265
1200
  const key = JSON.stringify([target.provider || '', target.model || '', provider?.model || '']);
1266
- // Capture the registry generation before any discovery request starts: a callback resolving
1267
- // after a registry change describes the previous endpoint and must discard itself.
1268
1201
  const registryGeneration = state.providerRegistryGeneration || 0;
1269
1202
  state.modelContextRequests ||= new Map();
1270
1203
  if (!state.modelContextRequests.has(key)) state.modelContextRequests.set(key, api(`/api/model-context?provider=${encodeURIComponent(target.provider || '')}&model=${encodeURIComponent(target.model || '')}`).catch(() => ({contextWindow:null})));
@@ -1274,37 +1207,21 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1274
1207
  });
1275
1208
  const override = disclosure(parent, 'Custom model name');
1276
1209
  const model = field(override, 'Custom model name (optional)', target.model, value => update({...target, model: value.trim() || undefined}), {maxLength:500,refresh:true}); model.placeholder = provider?.model || 'Configured profile model';
1277
- // The override stays free-text so a graph can name a model this machine has never seen, but the
1278
- // provider's catalog is offered alongside it: the configured models first, then everything the
1279
- // endpoint itself lists, so a provider that serves several models is selectable here rather than
1280
- // only the active one. Discovery is per provider, requested once, and failures simply leave the
1281
- // configured suggestions in place.
1282
1210
  const datalist = el('datalist'); datalist.id = `provider-models-${++modelSuggestionSeq}`; model.setAttribute('list', datalist.id); override.append(datalist);
1283
1211
  const displayed = new Set();
1284
- // Recording candidates are ONLY names discovery listed. Everything shown in the datalist lives in
1285
- // `displayed` (dedupe for <option> elements), but committing a displayed name must not authorize
1286
- // recording it: the configured models are already configured (skipped via `known`), and the node's
1287
- // own free-text override is precisely the speculative name this machine must not endorse into the
1288
- // provider configuration just because the graph happened to contain it.
1289
1212
  const offered = new Set();
1290
1213
  const addModelOption = (name, label) => {
1291
1214
  const value = name?.trim();
1292
1215
  if (!value || displayed.has(value)) return;
1293
1216
  displayed.add(value);
1294
1217
  const option = el('option'); option.value = value; if (label) option.label = label; datalist.append(option);
1295
- // The picker is rebuilt once per batch by the caller: rebuilding per model is quadratic for a
1296
- // large catalog, and an open panel would be redrawn and re-measured for every entry.
1297
1218
  pickerModels.push(value);
1298
1219
  return true;
1299
1220
  };
1300
1221
  for (const name of [activeName, ...(provider?.models || [])]) addModelOption(name, name?.trim() === activeName && name ? '(active)' : undefined);
1301
1222
  if (target.model) addModelOption(target.model, target.model.trim() === activeName ? '(active)' : undefined);
1302
1223
  renderPicker();
1303
- // Keyed by the resolved provider: a node using the configured default must follow that default's
1304
- // identity, not share a blank key that survives a default switch.
1305
- state.providerModelRequests ||= new Map();
1306
- if (!state.providerModelRequests.has(listingProvider)) state.providerModelRequests.set(listingProvider, api(`/api/provider-models?provider=${encodeURIComponent(listingProvider)}`).catch(() => ({ models: [] })));
1307
- state.providerModelRequests.get(listingProvider).then(data => {
1224
+ discoverProviderModels(listingProvider).then(data => {
1308
1225
  if ((state.providerRegistryGeneration || 0) !== registryGeneration) return;
1309
1226
  let added = false;
1310
1227
  for (const name of data.models || []) {
@@ -1314,23 +1231,8 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1314
1231
  }
1315
1232
  if (added) renderPicker();
1316
1233
  });
1317
- // Committing one of the discovered suggestions records it with the provider, the way /model does:
1318
- // execution validates a node's explicit model against the provider's configured models, so an
1319
- // unrecorded discovered pick would save a graph that refuses to run. Eligibility keys on the
1320
- // discovered catalog, not the displayed options, so a stored free-text override the provider never
1321
- // listed stays untouched even when recommitted, keeping speculative model names out of this
1322
- // machine's configuration.
1323
1234
  const known = new Set([activeName, ...(provider?.models || []).map(name => name?.trim() || '')].filter(Boolean));
1324
1235
  const committed = model.onchange;
1325
- // A providerless subagent child executes on the inherited provider OR on the parent node's
1326
- // enabled retry fallback (bindPortableGraphProviders adds every providerless child model to the
1327
- // fallback provider's requirements when retry.maxAttempts > 1), so a discovered pick must be
1328
- // recorded on every provider the child can run on. But recording must not endorse a model the
1329
- // fallback does not actually serve: binding checks each provider's CONFIGURED list, and recording
1330
- // rewrites exactly that list, so a primary-only name POSTed blindly to the fallback would turn
1331
- // the save-time GraphProviderUnavailableError into a failure deferred to a retry executing the
1332
- // child. Verify against the fallback's own catalog before recording there, and explain an unmet
1333
- // requirement instead of configuring an unsupported model.
1334
1236
  const fallbackTarget = !target.provider && fallbackProvider && fallbackProvider !== listingProvider ? fallbackProvider : '';
1335
1237
  let fallbackCheck = null;
1336
1238
  const recordWith = (recordProvider, value) => {
@@ -1340,10 +1242,6 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1340
1242
  state.providerModelRecords.add(key);
1341
1243
  api('/api/provider-models', { provider: recordProvider, model: value }).catch(() => state.providerModelRecords.delete(key));
1342
1244
  };
1343
- // The commit path re-renders the whole inspector (the field's refresh), so a note appended to
1344
- // this closure's `override` would land on detached DOM. Persist the unmet requirement in state:
1345
- // every re-rendered modelFields draws it from the map on its initial pass, and a decision that
1346
- // the fallback does serve the model removes it the same way.
1347
1245
  const warningKey = (value) => JSON.stringify([fallbackTarget, value]);
1348
1246
  const setWarning = (value, text) => {
1349
1247
  state.providerModelWarnings ||= new Map();
@@ -1352,10 +1250,6 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1352
1250
  else if (had) { state.providerModelWarnings.delete(warningKey(value)); renderInspector(); }
1353
1251
  };
1354
1252
  const applyCommit = (value) => {
1355
- // Eligibility is per provider, not per commit: the model being configured on the primary
1356
- // (live registry updates can add it there after an earlier commit) must not suppress the
1357
- // fallback leg — the fallback's own catalog decides whether it runs. Same on the fallback
1358
- // side: already-configured names need no POST, verified or not.
1359
1253
  if (!known.has(value)) recordWith(listingProvider, value);
1360
1254
  if (!fallbackCheck) return;
1361
1255
  if (fallbackCheck.configured.has(value) || fallbackCheck.offered.has(value)) {
@@ -1366,8 +1260,6 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1366
1260
  fallbackCheck.pending = null;
1367
1261
  setWarning(value, `The retry fallback "${fallbackTarget}" does not serve ${value}. The model was recorded on "${listingProvider}" only; a retry that runs this child on the fallback will be refused until the model is offered there.`);
1368
1262
  } else {
1369
- // The fallback's catalog is still loading: withhold the endorsement until it answers rather
1370
- // than recording an unverified name into that provider's configuration.
1371
1263
  fallbackCheck.pending = value;
1372
1264
  }
1373
1265
  };
@@ -1377,31 +1269,16 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1377
1269
  const configuredFallback = state.providers.find(p => idFor(p) === fallbackTarget);
1378
1270
  fallbackCheck = { offered: new Set(), configured: new Set([configuredFallback?.model?.trim() || '', ...(configuredFallback?.models || []).map(name => name?.trim() || '')].filter(Boolean)), loaded: false, pending: null };
1379
1271
  state.providerModelRequests.get(fallbackTarget).then(data => {
1380
- // A catalog resolving after a registry change came from the previous endpoint: recording its
1381
- // names into the new endpoint's configuration, or running a withheld commit against it,
1382
- // would endorse models the new endpoint may not serve. Discard it; the re-render started by
1383
- // applyProviderRegistry discovers against the live registry.
1384
1272
  if ((state.providerRegistryGeneration || 0) !== registryGeneration) return;
1385
1273
  for (const name of data.models || []) { const value = name?.trim(); if (value) fallbackCheck.offered.add(value); }
1386
1274
  fallbackCheck.loaded = true;
1387
- // A commit made before the catalog arrived is decided now: recorded if served, explained if not.
1388
1275
  if (fallbackCheck.pending !== null) applyCommit(fallbackCheck.pending);
1389
1276
  });
1390
- // Draw a pending explanation recorded against this field's current model value.
1391
1277
  const initialWarning = state.providerModelWarnings?.get(warningKey(target.model?.trim() || ''));
1392
1278
  if (initialWarning) override.append(el('p', initialWarning, 'help'));
1393
1279
  }
1394
- picker.onchange = () => { model.value = picker.value; model.onchange(); };
1395
1280
  model.onchange = () => {
1396
1281
  committed?.();
1397
- // Recording eligibility keys on whether the model still needs recording, not on whether the
1398
- // commit changed the graph value: a commit whose POST failed transiently must stay retryable
1399
- // by recomitting the same suggestion (the failed attempt already wrote the model into the
1400
- // graph, and a value-unchanged early-return would strand the node against execution's
1401
- // provider/model validation). The per-provider skips live inside applyCommit — `known` for
1402
- // the primary, the fallback's configured set for the child's other home — so a model that
1403
- // became configured on one provider cannot silence reconciliation on the other. Already-
1404
- // recorded ones skip via the dedupe set, which the failed POST removed.
1405
1282
  const value = model.value.trim();
1406
1283
  if (!value || !offered.has(value)) return;
1407
1284
  applyCommit(value);
@@ -1417,8 +1294,6 @@ function renderCompletion(parent, node) {
1417
1294
  graph.edges = graph.edges.filter(edge => edge.source !== node.id || outcomes(node).includes(edgeOutcome(edge)));
1418
1295
  });
1419
1296
  explain(behavior, 'Outcome names are short phrases such as DONE, PASS, FAILED TESTING or BLOCKED. Describe when the agent should choose each one; for a single outcome, describe when the work is considered achieved, for example "This is considered DONE when xyz is finished". The agent evaluates these written criteria using its evidence; they are not automatic checks. Connect outcomes to destinations under Connections.');
1420
- // The server refuses written criteria on a delegating Orchestrator, so the option is withheld
1421
- // rather than offered and then rejected on save.
1422
1297
  if (delegatesWriting(node) && node.completion?.mode !== 'outcomes') { for (const option of behavior.options) option.disabled = option.value === 'outcomes'; parent.append(el('p', 'An Orchestrator with a writing role keeps a single outcome: it completes by passing work on, or delivers landed changes through its delivered port.', 'help')); }
1423
1298
  if (node.completion?.mode === 'outcomes') {
1424
1299
  parent.append(el('p', 'Criteria are optional; blank rows use the agent prompt. Removing or renaming an outcome removes its old routes. Undo restores routes and criteria.', 'help'));
@@ -1515,11 +1390,6 @@ function renderEdgeInspector(parent, edge) {
1515
1390
  const remove = el('button', 'Remove Connection', 'danger'); remove.onclick = () => mutate(() => { state.graph.edges = state.graph.edges.filter(e => e !== edge); state.selectedEdge = null; }, true); parent.append(remove);
1516
1391
  }
1517
1392
  function effectiveCaps(node = {}) { return node.capabilities || {filesystem:'read-write',shell:'allowed',git:'write',github:'none',browser:'playwright',deployment:'none'}; }
1518
- // Browser copy of src/tool-names.ts. The server treats these spellings as aliases of the canonical
1519
- // tools it exposes, so every comparison on tool names here resolves them first: a name that
1520
- // skips this step cannot match a canonical allowlist, and the editor then silently drops
1521
- // allowed tools. 'shell' is deliberately absent: it is platform-resolved server-side and kept
1522
- // as its own family token below rather than pinned to a spelling this page cannot know.
1523
1393
  const TOOL_ALIASES = {
1524
1394
  read_file: 'Read', read: 'Read',
1525
1395
  write_file: 'Write', write: 'Write',
@@ -1529,18 +1399,11 @@ const TOOL_ALIASES = {
1529
1399
  bash: 'Bash', powershell: 'PowerShell',
1530
1400
  };
1531
1401
  const SHELL_TOOLS = ['Bash', 'PowerShell', 'shell'];
1532
- // Display spelling round-trips back into role.tools, so it must stay one-to-one.
1533
1402
  function displayToolName(name) { return TOOL_ALIASES[name] || name; }
1534
- // Permission comparison spelling: folds the whole shell family onto one token so the server's
1535
- // platform-dependent resolution of 'shell' cannot change which tools the editor offers.
1536
1403
  function canonicalToolName(name) { const d = displayToolName(name); return SHELL_TOOLS.includes(d) ? 'shell' : d; }
1537
- // Browser copy of permitsBuiltInTool in src/graphs.ts for a delegated worktree child, the one
1538
- // kind of subagent that runs commands. The server validates a writing role's tools with that rule,
1539
- // so a tool offered here that it refuses could be ticked and then fail validation.
1540
1404
  const QA_TOOL_NAMES = ['qa.terminal', 'qa.browser'];
1541
1405
  function delegatedRolePermits(caps, name) {
1542
1406
  const display = displayToolName(name);
1543
- // Mirrors canRunCommands in src/graphs.ts: the shell setting alone grants commands.
1544
1407
  const commands = caps.shell === 'allowed';
1545
1408
  if (name === 'qa.browser_session' || name === 'browser.solve_captcha' || name === 'web_search') return caps.browser === 'playwright';
1546
1409
  if (['Read', 'Glob', 'Grep', 'repo_explore', 'read_skill_resource'].includes(display)) return caps.filesystem !== 'none';
@@ -1551,10 +1414,6 @@ function delegatedRolePermits(caps, name) {
1551
1414
  return name === 'read_artifact' || name === 'write_artifact';
1552
1415
  }
1553
1416
  function roleToolOptions(node, role, policy) {
1554
- // A writing role of an Orchestrator is a delegated one. The runtime builds its tools from the
1555
- // node's capabilities, for a child that works in its own worktree with a shell, and ignores both
1556
- // the node's tool list (the Orchestrator's read-only intake kit) and the tool-inheritance
1557
- // setting. So do the tools offered here; a role with no list of its own gets all of them.
1558
1417
  if (delegatesWriting(node) && isWritingRole(role)) {
1559
1418
  const ceiling = effectiveCaps(node), own = role.capabilities || ceiling;
1560
1419
  const available = state.tools.map(t => displayToolName(typeof t === 'string' ? t : t.name || t.id)).filter((name, index, array) => array.indexOf(name) === index)
@@ -1564,7 +1423,7 @@ function roleToolOptions(node, role, policy) {
1564
1423
  const parent = effectiveCaps(node);
1565
1424
  const child = role.capabilities || {...parent,...((policy.workspace || 'shared-read-only') === 'shared-read-only' ? {filesystem:parent.filesystem === 'none' ? 'none' : 'read',git:parent.git === 'none' ? 'none' : 'read',shell:'disabled'} : {})};
1566
1425
  const canonical = canonicalToolName;
1567
- const permits = (caps, name) => name === 'qa.browser_session' ? caps.browser === 'playwright' : ['Read','Glob','Grep','repo_explore','read_skill_resource'].includes(canonical(name)) ? caps.filesystem !== 'none' : ['Write','Edit'].includes(canonical(name)) ? caps.filesystem === 'read-write' : canonical(name) === 'shell' ? false /* an ordinary subagent never runs commands (validateGraph refuses it) */ : name === 'git_read' ? caps.git !== 'none' : ['read_artifact','write_artifact'].includes(name);
1426
+ const permits = (caps, name) => name === 'qa.browser_session' ? caps.browser === 'playwright' : ['Read','Glob','Grep','repo_explore','read_skill_resource'].includes(canonical(name)) ? caps.filesystem !== 'none' : ['Write','Edit'].includes(canonical(name)) ? caps.filesystem === 'read-write' : canonical(name) === 'shell' ? false : name === 'git_read' ? caps.git !== 'none' : ['read_artifact','write_artifact'].includes(name);
1568
1427
  const configured = node.tools?.map(displayToolName);
1569
1428
  const available = (configured || state.tools.map(t=>displayToolName(typeof t === 'string' ? t : t.name || t.id))).filter((name,index,array)=>array.indexOf(name)===index).filter(name=>permits(parent,name)&&permits(child,name));
1570
1429
  const defaults = policy.toolInheritance === 'inherit' ? available : available.filter(name=>['Read','Glob','Grep','git_read','qa.browser_session','read_skill_resource'].includes(canonical(name)));
@@ -1572,40 +1431,27 @@ function roleToolOptions(node, role, policy) {
1572
1431
  }
1573
1432
  function renderSubagents(parent, node) {
1574
1433
  const policy = node.subagents || {enabled:false}; const set = patch => {Object.assign(policy,patch);node.subagents=policy;};
1575
- // The server rule that adds the delivered port (delegatesWriting) also decides this text: once
1576
- // a role on an Orchestrator may write, its children run commands in their own worktrees.
1577
1434
  const delegating = delegatesWriting(node);
1578
1435
  explain(check(parent,'Allow subagents',policy.enabled,value=>{set({enabled:value});pruneRoutes(node);}), delegating
1579
1436
  ? '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.'
1580
1437
  : '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.');
1581
1438
  if (!policy.enabled) return;
1582
- // The server refuses writing roles on an Orchestrator outside separate worktrees, so the
1583
- // editor moves the policy there as soon as a role may write.
1584
1439
  const requireWorktree = () => { if (node.agentRole === 'orchestrator' && (policy.roles || []).some(isWritingRole)) set({workspace:'worktree'}); };
1585
1440
  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});
1586
1441
  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}));
1587
- // Mirrors bindPortableGraphProviders: enabled retry attempts may spawn providerless children on
1588
- // the fallback provider, so a discovered child pick must be recorded there as well.
1589
1442
  const childFallbackProvider = node.retry?.fallback && node.retry.maxAttempts > 1 ? node.retry.fallback.provider : '';
1590
- if(policy.modelPolicy==='specific') modelFields(parent,policy,value=>set({provider:value.provider,model:value.model}),undefined,node.provider,childFallbackProvider);
1443
+ if(policy.modelPolicy==='specific') modelFields(parent,policy,value=>set({provider:value.provider,model:value.model}),undefined,node.provider,childFallbackProvider,{requireProvider:true,noDefault:true});
1591
1444
  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}));
1592
1445
  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.'); }
1593
1446
  choice(parent,'Tool inheritance',policy.toolInheritance||'restricted',[{value:'restricted',label:'Restricted subset'},{value:'inherit',label:'Inherit parent allowlist'}],value=>set({toolInheritance:value}));
1594
1447
  choice(parent,'Context',policy.context||'selected',[{value:'selected',label:'Selected context only'},{value:'task-only',label:'Task only'}],value=>set({context:value}));
1595
- // The runtime no longer invents a child deadline, so this field must not display one: blank
1596
- // means the child inherits the parent's bounds, and a shown fallback would claim a two-minute
1597
- // ceiling that is not configured.
1598
- field(parent,'Wall time per child, ms (blank = inherits the parent)',policy.maxWallTimeMs,value=>{if(value===undefined)delete policy.maxWallTimeMs;else policy.maxWallTimeMs=value;node.subagents=policy;},{type:'number',min:1,optional:true,placeholder:'Inherits the parent'});
1448
+ 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'});
1599
1449
  const roles = disclosure(parent,'Configure roles',true);
1600
1450
  roles.append(el('p','Roles can only narrow parent capabilities. Concurrent writing roles require separate worktrees.', 'help'));
1601
1451
  for(const role of policy.roles||[]) {
1602
1452
  const body=disclosure(roles,role.name||'New role',true);
1603
1453
  field(body,'Role ID',role.id,value=>{role.id=value;}); field(body,'Name',role.name,value=>{role.name=value;});field(body,'Instruction',role.instruction,value=>{role.instruction=value;},{multiline:true,maxLength:100000});
1604
- if(policy.modelPolicy==='per-role')modelFields(body,role,value=>{role.provider=value.provider;role.model=value.model;},// A per-role child with no provider of its own runs on the parent's provider and inherits the
1605
- // parent's model there (agent-execution resolves `role.model ?? model`), so its default row must
1606
- // name that model, not the provider's active one.
1607
- // Both sides are compared as execution resolves them: an unset parent provider is the machine
1608
- // default, so a role naming that default explicitly still inherits the parent's model.
1454
+ if(policy.modelPolicy==='per-role')modelFields(body,role,value=>{role.provider=value.provider;role.model=value.model;},
1609
1455
  (role.provider||node.provider||state.defaultProvider)===(node.provider||state.defaultProvider)?node.model:undefined,node.provider,childFallbackProvider);
1610
1456
  capabilities(disclosure(body,'Role capabilities'),role.capabilities||effectiveCaps(node),value=>{role.capabilities=value;requireWorktree();pruneRoutes(node);},effectiveCaps(node));
1611
1457
  const allowedTools=disclosure(body,'Role tools'); const toolOptions=roleToolOptions(node,role,policy);
@@ -1613,7 +1459,7 @@ function renderSubagents(parent, node) {
1613
1459
  const available=toolOptions.available.includes(name);
1614
1460
  check(allowedTools,available?name:`${name} (unavailable — remove to repair)`,toolOptions.selected.includes(name),enabled=>{role.tools=enabled?[...new Set([...toolOptions.selected,name])]:toolOptions.selected.filter(t=>t!==name);if(!toolOptions.delegated)policy.toolInheritance='restricted';});
1615
1461
  }
1616
- const contracts=disclosure(body,'Role contracts');jsonField(contracts,'Input schema',role.inputSchema,value=>{role.inputSchema=value;});jsonField(contracts,'Output schema',role.outputSchema,value=>{role.outputSchema=value;});
1462
+ const contracts=disclosure(body,'Role contracts');jsonField(contracts,'Input schema',role.inputSchema,value=>{role.inputSchema=value;},SCHEMA_JSON);jsonField(contracts,'Output schema',role.outputSchema,value=>{role.outputSchema=value;},SCHEMA_JSON);
1617
1463
  const remove=el('button','Remove Role');remove.onclick=()=>mutate(()=>{set({roles:policy.roles.filter(r=>r!==role)});pruneRoutes(node);},true);body.append(remove);
1618
1464
  }
1619
1465
  const add=el('button','Add Role');add.onclick=()=>mutate(()=>{set({roles:[...(policy.roles||[]),{id:`role-${crypto.randomUUID().slice(0,8)}`,name:'Repository Researcher',instruction:'Research the bounded task and return findings.',capabilities:{...effectiveCaps(node),filesystem:effectiveCaps(node).filesystem==='none'?'none':'read',shell:effectiveCaps(node).shell==='disabled'?'disabled':'read-only',git:effectiveCaps(node).git==='none'?'none':'read'}}]});requireWorktree();},true);roles.append(add);
@@ -1704,7 +1550,6 @@ function retryLimitHelp(parent, graph) {
1704
1550
  box.append(fix, clock); parent.append(box);
1705
1551
  }
1706
1552
  function renderInspector() {
1707
- // A redraw replaces a full-screen prompt editor, so its backdrop goes with it.
1708
1553
  document.body?.classList?.remove?.('prompt-fullscreen'); for (const backdrop of document.querySelectorAll?.('.prompt-backdrop') ?? []) backdrop.remove();
1709
1554
  const parent = $('inspector-body'); parent.replaceChildren(); const graph = state.graph; if (!graph) { parent.append(el('p', 'Create a graph or choose a preset.', 'help')); return; }
1710
1555
  if (state.selectedEdge && !graph.edges.includes(state.selectedEdge)) state.selectedEdge = null;
@@ -1738,9 +1583,8 @@ function renderInspector() {
1738
1583
  } else widgetGroup.append(el('p','Widget limit reached (5).','help'));
1739
1584
  const visits = field(panels.behavior, 'Maximum visits per step', graph.limits?.maxNodeVisits ?? 0, value => {graph.limits={...graph.limits}; if(value===undefined || value===0) delete graph.limits.maxNodeVisits; else graph.limits.maxNodeVisits=value;}, {type:'number',optional:true,min:0,max:100,refresh:true});
1740
1585
  explain(visits,'0 means unlimited, which is the default. A return connection repeats a step, so a graph with one needs a ceiling: a visit limit, or a wall clock. An agent Loop modifier has its own try limit.');
1741
- // Per-graph desktop settings render here; a browser-launched studio has no host bridge and skips them.
1742
1586
  window.AndorraEmbed?.inspector?.(general);
1743
- const advanced = panels.advanced; jsonField(advanced, 'Run limits', graph.limits, value => {graph.limits=value;}); jsonField(advanced,'Run input schema',graph.inputSchema,value=>{graph.inputSchema=value;}); jsonField(advanced,'Run state schema',graph.stateSchema,value=>{graph.stateSchema=value;});
1587
+ const advanced = panels.advanced; jsonField(advanced, 'Run limits', graph.limits, value => {graph.limits=value;}, RUN_LIMITS_JSON); jsonField(advanced,'Run input schema',graph.inputSchema,value=>{graph.inputSchema=value;},SCHEMA_JSON); jsonField(advanced,'Run state schema',graph.stateSchema,value=>{graph.stateSchema=value;},SCHEMA_JSON);
1744
1588
  } else {
1745
1589
  const panels = inspectorTabs(parent, node.type === 'agent' ? ['general', 'model', 'behavior', 'advanced'] : outcomes(node).length ? ['general', 'behavior', 'advanced'] : ['general', 'advanced']);
1746
1590
  const general = panels.general; field(general, 'Name', node.name, value => {node.name=value;}, {maxLength:200});
@@ -1763,17 +1607,10 @@ function renderInspector() {
1763
1607
  renderSubagents(disclosure(advanced,'Subagents'),node);
1764
1608
  const limits = disclosure(advanced,'Execution limits');
1765
1609
  for (const [key,label,defaultValue] of [['maxContextChars','Context characters',120000],['maxCompletionRepairs','Completion repair tries',2]]) field(limits,label,node.limits?.[key] ?? defaultValue,value=>{node.limits={...node.limits,[key]:value}; delete node.limits.maxTokens;},{type:'number',min:key==='maxCompletionRepairs'?0:1});
1766
- // Iterations and wall time default to blank, and blank means unlimited. The editor must
1767
- // not invent a bound the author never chose: a task that legitimately runs for hours
1768
- // should not be cut short, and a person answering a question is never on the clock.
1769
- // Clearing the field removes the limit rather than writing a zero, which the runtime
1770
- // accepts as the same thing but which reads to a human as "no time at all".
1771
1610
  field(limits,'Iterations (blank = unlimited)',node.limits?.maxIterations ?? node.maxIterations,value=>{node.limits={...node.limits,maxIterations:value}; delete node.limits.maxTokens; if(value===undefined){delete node.limits.maxIterations; delete node.maxIterations;} else node.maxIterations=value;},{type:'number',min:0,max:1000,optional:true,placeholder:'Unlimited'});
1772
- field(limits,'Wall time, milliseconds (blank = unlimited)',node.limits?.wallTimeMs,value=>{node.limits={...node.limits,wallTimeMs:value}; delete node.limits.maxTokens; if(value===undefined)delete node.limits.wallTimeMs;},{type:'number',min:0,optional:true,placeholder:'Unlimited'});
1773
- // Tool calls default to blank, and blank means unlimited: an absent limit is only
1774
- // written when the field is cleared, so a node keeps its ceiling once one is set.
1611
+ field(limits,'Wall time, seconds (blank = unlimited)',msToSeconds(node.limits?.wallTimeMs),value=>{node.limits={...node.limits,wallTimeMs:secondsToMs(value)}; delete node.limits.maxTokens; if(value===undefined)delete node.limits.wallTimeMs;},{type:'number',min:0,step:'any',optional:true,placeholder:'Unlimited'});
1775
1612
  field(limits,'Tool calls (blank = unlimited)',node.limits?.maxToolCalls,value=>{node.limits={...node.limits,maxToolCalls:value}; if(value===undefined)delete node.limits.maxToolCalls;},{type:'number',min:0,optional:true,placeholder:'Unlimited'});
1776
- skillPrompt(field(advanced,'System prompt',node.systemPrompt ?? node.prompt,value=>{node.systemPrompt=value; delete node.prompt;},{multiline:true,maxLength:100000})); jsonField(advanced,'Input schema (JSON Schema)',node.inputSchema,value=>{node.inputSchema=value;}); jsonField(advanced,'Output schema (JSON Schema)',node.outputSchema,value=>{node.outputSchema=value;}); field(advanced,'Retries',node.retry?.maxAttempts??1,value=>{node.retry={...node.retry,maxAttempts:value};},{type:'number',min:1}); const fallback=disclosure(advanced,'Fallback model'); modelFields(fallback,node.retry?.fallback||{},value=>{node.retry={maxAttempts:1,...node.retry,fallback:value.provider?{provider:value.provider,model:value.model}:undefined};});
1613
+ skillPrompt(field(advanced,'System prompt',node.systemPrompt ?? node.prompt,value=>{node.systemPrompt=value; delete node.prompt;},{multiline:true,maxLength:100000})); jsonField(advanced,'Input schema (JSON Schema)',node.inputSchema,value=>{node.inputSchema=value;},SCHEMA_JSON); jsonField(advanced,'Output schema (JSON Schema)',node.outputSchema,value=>{node.outputSchema=value;},SCHEMA_JSON); field(advanced,'Retries',node.retry?.maxAttempts??1,value=>{node.retry={...node.retry,maxAttempts:value};},{type:'number',min:1}); const fallback=disclosure(advanced,'Fallback model'); modelFields(fallback,node.retry?.fallback||{},value=>{node.retry={maxAttempts:1,...node.retry,fallback:value.provider?{provider:value.provider,model:value.model}:undefined};},undefined,undefined,undefined,{requireProvider:true,defaultLabel:'No fallback model'});
1777
1614
  field(advanced,'Executor','react-basic',()=>{}).disabled=true;
1778
1615
  const tools = disclosure(advanced,'Tool allowlist');
1779
1616
  for (const name of [...new Set([...state.tools.map(t=>typeof t==='string'?t:t.name||t.id),...(node.tools||[])])]) check(tools,name,node.tools===undefined||node.tools.includes(name),enabled=>{const all=state.tools.map(t=>typeof t==='string'?t:t.name||t.id); node.tools=enabled?[...new Set([...(node.tools??all),name])]:(node.tools??all).filter(t=>t!==name);});
@@ -1787,25 +1624,19 @@ function renderInspector() {
1787
1624
  window.AndorraStudio?.inspector?.(parent, node);
1788
1625
  }
1789
1626
  function render() { renderHeading(); renderList(); renderLibrary(); renderCanvas(); renderInspector(); scheduleValidation(); queueDraft(); }
1790
- // `options.discard` skips the question about unsaved edits: Graph Manager passes it once it has
1791
- // established that loading loses nothing, or the user has asked for the load. Resolves to whether
1792
- // the graph was opened.
1793
1627
  async function openGraph(id, options = {}) {
1794
1628
  if (state.saving) { status('Wait for the current save before opening another graph.'); return false; }
1795
1629
  if (graphLocked(id)) { status(FREE_LOCKED_TIP, true); return false; }
1796
1630
  if (state.dirty && !options.discard && !await askConfirm(DISCARD_QUESTION)) return false;
1797
- // A caller that already holds the graph (`options.fetched`) is applied without a request, so nothing can change the canvas between its own checks and this replacement.
1798
1631
  try { const opened = options.fetched === undefined ? await api(`/api/graphs/${encodeURIComponent(id)}`) : options.fetched; const capMoved = hasSubagentCap(opened); state.graph = dropLegacyTokenFields(opened); const migrated = state.graph.editorMigration === true; state.dirty = migrated || capMoved; delete state.graph.editorMigration; markSaved(state.dirty ? null : state.graph); clearSelection(); state.undo = []; state.redo = []; state.pendingProviderNodes = null; render(); fit(); status(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'); graphOpened(options.reason || 'open'); return true; } catch (error) { status(error.message, true); return false; }
1799
1632
  }
1800
1633
  function newId() { return `graph-${crypto.randomUUID()}`; }
1801
1634
  function newGraph(duplicate = false, discarded = false) {
1802
1635
  if (state.saving) { status('Wait for the current save before creating another graph.'); return; }
1803
1636
  if (!canCreateGraph()) { status(FREE_CREATE_TIP, true); return; }
1804
- // Unsaved edits are asked about first; a clean graph is replaced at once.
1805
1637
  if (state.dirty && !discarded) { void askConfirm(DISCARD_QUESTION).then(discard => { if (discard) newGraph(duplicate, true); }); return; }
1806
1638
  if (duplicate) state.graph={...copy(state.graph),id:newId(),name:`${state.graph.name} copy`,revision:0};
1807
1639
  else if (freeTier()) {
1808
- // A free graph starts from the Software Engineer alone: the Orchestrator is a Premium node.
1809
1640
  const engineerPreset=state.definitions.find(definition=>definition.id==='software-engineer')?.node;
1810
1641
  if(!engineerPreset){status('Starting presets are unavailable. Reload the Graph Editor and try again.',true);return;}
1811
1642
  state.graph={schemaVersion:3,id:newId(),name:'Untitled graph',revision:0,entry:'engineer',nodes:{engineer:{...copy(engineerPreset),id:'engineer',position:{x:0,y:0}},done:{id:'done',name:'Done',type:'end',position:{x:320,y:0}}},edges:[{id:'engineer-done',source:'engineer',target:'done',outcome:'completed'}]};
@@ -1820,15 +1651,12 @@ function newGraph(duplicate = false, discarded = false) {
1820
1651
  for(const key of ['taskInstruction','requirements','acceptanceCriteria','designConsiderations','codebaseFindings']) inputMapping[key]=`$source.output.${key}`;
1821
1652
  state.graph={schemaVersion:3,id:newId(),name:'Untitled graph',revision:0,entry:'orchestrator',nodes:{orchestrator,engineer,done:{id:'done',name:'Done',type:'end',position:{x:640,y:0}}},edges:[{id:'orchestrator-engineer',source:'orchestrator',target:'engineer',outcome:'completed',inputMapping},{id:'engineer-done',source:'engineer',target:'done',outcome:'completed'}]};
1822
1653
  }
1823
- // A duplicate copies the open graph, providerless nodes included, so its unmet provider
1824
- // requirements travel with it; an unrelated new graph starts without any.
1825
1654
  markSaved(null); state.dirty = true; clearSelection(); state.undo = []; state.redo = [];
1826
1655
  state.untouched = JSON.stringify(state.graph);
1827
1656
  state.pendingProviderNodes = duplicate ? new Set(state.pendingProviderNodes ?? []) : null;
1828
1657
  render(); fit(); status('New graph · Customize your agent, then save');
1829
1658
  graphOpened(duplicate ? 'duplicate' : 'new');
1830
1659
  }
1831
- // The settings a new Agent starts from, whether it is dropped on the canvas or added to the list.
1832
1660
  function blankAgentSettings() {
1833
1661
  return { executor: 'react-basic', instruction: '', contextPolicy: {history: false, predecessors: 'none'}, completion: { mode: 'single', outcome: 'completed' }, subagents: { enabled: false } };
1834
1662
  }
@@ -1839,8 +1667,6 @@ function addNode(type, definition, dropPosition) {
1839
1667
  const refusal = freeNodeRefusal([{ type, agentRole: definition?.agentRole }]);
1840
1668
  if (refusal) { status(refusal, true); return; }
1841
1669
  if (definition?.agentRole === 'orchestrator') {
1842
- // Compare canonically: saved variants may carry either the retired spellings or the
1843
- // canonical tool names, and the server canonicalizes tool lists on validation.
1844
1670
  const researchTools = (definition.tools ?? []).map(canonicalToolName);
1845
1671
  const canResearch = definition.capabilities?.filesystem !== 'none' &&
1846
1672
  (definition.tools === undefined || ['Read','Glob','Grep','repo_explore'].some(tool => researchTools.includes(tool)));
@@ -1848,10 +1674,7 @@ function addNode(type, definition, dropPosition) {
1848
1674
  status('Cannot apply this saved Orchestrator: enable filesystem read access and at least one research tool (Read, Glob, Grep, or repo_explore), then save it again. Choose another saved Orchestrator to continue.', true);
1849
1675
  return;
1850
1676
  }
1851
- // Saved definitions can predate intake's required research and clarification.
1852
- // Normalize a copy for both insertion and replacement, preserving unlimited ceilings.
1853
1677
  definition = copy(definition);
1854
- // Completion guarantees these declared fields even in older optional schemas.
1855
1678
  if (definition.outputSchema?.properties) {
1856
1679
  const runtimeFields = ['originalTask','taskInstruction','requirements','acceptanceCriteria','designConsiderations','codebaseFindings'];
1857
1680
  definition.outputSchema.required = [...new Set([...(definition.outputSchema.required || []), ...runtimeFields.filter(key => Object.hasOwn(definition.outputSchema.properties, key))])];
@@ -1880,13 +1703,9 @@ function addNode(type, definition, dropPosition) {
1880
1703
  const id = `${type}-${crypto.randomUUID().slice(0, 8)}`;
1881
1704
  if (!dropPosition) { dropPosition = {x:(120-state.x)/state.zoom,y:(180-state.y)/state.zoom}; for (let attempts=0; attempts<100 && Object.values(state.graph.nodes).some((node,index)=>{const p=position(node,index);return Math.abs(p.x-dropPosition.x)<45 && Math.abs(p.y-dropPosition.y)<45;});attempts++) {dropPosition.x+=48;dropPosition.y+=48;} }
1882
1705
  state.graph.schemaVersion = 3;
1883
- // A new Agent starts with no iteration ceiling, matching the runtime default. Seeding it
1884
- // with 40 would silently reinstate the legacy limit the runtime no longer applies.
1885
1706
  state.graph.nodes[id] = { ...(definition ? copy(definition) : type === 'agent' ? blankAgentSettings() : {}), id, type, ...(type==='join'?{join:{mode:'all'}}:type==='loop'?{loop:{maxIterations:3}}:type==='condition'?{condition:{source:state.graph.entry,path:'result',equals:true}}:{}), name: definition?.name || (type === 'agent' ? 'New Agent' : type.charAt(0).toUpperCase() + type.slice(1)), position: dropPosition || { x: (120 - state.x) / state.zoom, y: (180 - state.y) / state.zoom } };
1886
1707
  if (definition?.agentRole === 'orchestrator') {
1887
1708
  const previousEntry = state.graph.entry;
1888
- // Keep the direct-start graph's tool budget available after intake uses its
1889
- // required research and clarification calls. An absent ceiling stays unlimited.
1890
1709
  if (state.graph.limits?.maxToolCalls !== undefined) state.graph.limits.maxToolCalls = Math.min(1_000_000_000, state.graph.limits.maxToolCalls + 2);
1891
1710
  const outcome = outcomes(state.graph.nodes[id])[0];
1892
1711
  const bootstrap = state.graph.nodes[previousEntry]?.type === 'join' && state.graph.edges.some(edge => edge.target === previousEntry);
@@ -1899,7 +1718,6 @@ function addNode(type, definition, dropPosition) {
1899
1718
  const target = targetNode.inputSchema?.properties?.[key];
1900
1719
  if (!target) return targetNode.inputSchema?.additionalProperties !== false;
1901
1720
  const sourceSchema = key === 'originalTask' ? state.graph.inputSchema : state.graph.nodes[id].outputSchema;
1902
- // Intake owns these output types even when a saved variant omits its schema.
1903
1721
  const runtimeSource = key === 'originalTask' || key === 'taskInstruction' ? {type:'string'} : {type:'array',items:{type:'string'}};
1904
1722
  const declaredSource = sourceSchema?.properties?.[key === 'originalTask' ? 'task' : key];
1905
1723
  const source = declaredSource?.type === 'array' && !declaredSource.items && runtimeSource.type === 'array'
@@ -1924,8 +1742,6 @@ function libraryDialog(title, fields, submit, submitLabel = 'Save') {
1924
1742
  form.onsubmit = async event => { event.preventDefault(); save.disabled = true; try { await submit(); closeDialog(dialog); } catch (failure) { error.textContent = failure.message; } finally { save.disabled = false; } };
1925
1743
  dialog.onclose = () => dialog.remove(); dialog.append(form); document.body.append(dialog); dialog.showModal(); fields[0]?.[1].focus();
1926
1744
  }
1927
- // The browser's `required` accepts whitespace, so a name that only trims to nothing is
1928
- // refused here instead of being sent as a request that can only fail.
1929
1745
  function requireAgentName(input) {
1930
1746
  const value = input.value.trim();
1931
1747
  if (!value) throw new Error('Enter an Agent name.');
@@ -1939,9 +1755,6 @@ function saveAgentVariant(node) {
1939
1755
  await writeDefinition({schemaVersion:2, id, name:agentName, description:'', revision:0, node:{...snapshot,name:agentName}}, 'Saved to library');
1940
1756
  });
1941
1757
  }
1942
- // Truncation counts the field's own unit (UTF-16 code units) but must not cut between the two
1943
- // halves of an astral character: a split pair still passes the length check while showing as a
1944
- // replacement character. Walk whole code points and stop before the budget is exceeded.
1945
1758
  function truncateToUnits(value, limit) {
1946
1759
  let kept = '';
1947
1760
  for (const character of value) {
@@ -1950,10 +1763,7 @@ function truncateToUnits(value, limit) {
1950
1763
  }
1951
1764
  return kept;
1952
1765
  }
1953
- // A saved Agent is never edited in place, so copying always writes a new definition.
1954
1766
  function copyAgent(definition) {
1955
- // The suffix must not push a long source name past the field's own limit, which would
1956
- // prefill an invalid default the browser then refuses to submit.
1957
1767
  const suffix = ' copy', source = definition.name.trim(), id = `definition-${crypto.randomUUID()}`;
1958
1768
  const name = el('input'); name.value = `${truncateToUnits(source, 200 - suffix.length)}${suffix}`; name.required = true; name.maxLength = 200;
1959
1769
  libraryDialog(`Clone ${definition.name}`, [['Agent name', name]], async () => {
@@ -1961,9 +1771,6 @@ function copyAgent(definition) {
1961
1771
  await writeDefinition({schemaVersion:2, id, name:agentName, description:definition.description || '', revision:0, node:{...copy(definition.node),name:agentName}}, `Agent ${agentName} created`);
1962
1772
  });
1963
1773
  }
1964
- // Add agent appends a new Agent to the list from a name, an optional description and its
1965
- // instructions; the rest of its settings start as a blank canvas Agent's do. Deeper settings are
1966
- // edited on the canvas and kept with Save Agent variant.
1967
1774
  function addAgent() {
1968
1775
  const name = el('input'); name.required = true; name.maxLength = 200;
1969
1776
  const description = el('input'); description.maxLength = 2000;
@@ -1975,13 +1782,8 @@ function addAgent() {
1975
1782
  }, 'Add Agent');
1976
1783
  skillPrompt(instruction);
1977
1784
  }
1978
- // The server's 512 KiB limit applies to the import request, not the file: Share pretty-prints its
1979
- // file, so a file over that limit can still make a request under it. The request is measured
1980
- // exactly; files far beyond anything that could fit are refused before they are read.
1981
1785
  const AGENT_REQUEST_LIMIT = 512 * 1024;
1982
1786
  const AGENT_FILE_LIMIT = 4 * AGENT_REQUEST_LIMIT;
1983
- // Import accepts only a file made by Share. The server checks the format marker and version and
1984
- // validates the Agent like any saved one, so this dialog only reads the file.
1985
1787
  function importAgent() {
1986
1788
  const file = el('input'); file.type = 'file'; file.accept = '.json,application/json';
1987
1789
  const id = `definition-${crypto.randomUUID()}`;
@@ -1996,8 +1798,6 @@ function importAgent() {
1996
1798
  await importDefinition(id, parsed);
1997
1799
  }, 'Import');
1998
1800
  }
1999
- // Like writeDefinition, a committed import whose response was lost is confirmed from the store by
2000
- // the id this dialog minted, so a retry never adds the Agent twice.
2001
1801
  async function importDefinition(id, file) {
2002
1802
  let stored;
2003
1803
  try { stored = await api('/api/definitions/import', { id, file }); }
@@ -2012,28 +1812,22 @@ async function importDefinition(id, file) {
2012
1812
  try { await readDefinitions(); renderLibrary(); status(saved); }
2013
1813
  catch (error) { status(`${saved}, but the library did not refresh: ${error.message}`, true); }
2014
1814
  }
2015
- // Share writes the Agent's export file. In the desktop host only the id crosses the frame and the
2016
- // host writes the file to Downloads; a plain browser downloads it directly.
2017
1815
  async function shareAgent(definition) {
2018
1816
  if (window.AndorraEmbed?.hostChrome?.() && window.AndorraEmbed.exportAgent) { await window.AndorraEmbed.exportAgent(definition.id); return; }
2019
1817
  downloadJson(await api(`/api/definitions/${encodeURIComponent(definition.id)}/export`), exportFileName(definition));
2020
1818
  status(`Agent ${definition.name} shared as a JSON file`);
2021
1819
  }
2022
- // Built-in Agents have no Delete. Graphs that already use a deleted Agent keep their own copy.
2023
1820
  async function deleteAgent(definition) {
2024
1821
  if (definition.preset) return;
2025
1822
  if (!await askConfirm({ title: `Delete the Agent “${definition.name}”?`, message: 'Graphs that already use it keep their own copy. This cannot be undone.', confirmLabel: 'Delete', tone: 'danger' })) return;
2026
1823
  try { await api(`/api/definitions/${encodeURIComponent(definition.id)}`, undefined, { method: 'DELETE' }); }
2027
1824
  catch (error) {
2028
- // A lost response can still have deleted it, so the refreshed list decides what is reported.
2029
1825
  const remaining = (await readDefinitions().catch(() => undefined))?.some(item => item.id === definition.id);
2030
1826
  if (remaining !== false) { if (remaining) renderLibrary(); status(error.message, true); return; }
2031
1827
  }
2032
1828
  try { await readDefinitions(); renderLibrary(); status(`Agent ${definition.name} deleted`); }
2033
1829
  catch (error) { status(`Agent ${definition.name} deleted, but the library did not refresh: ${error.message}`, true); }
2034
1830
  }
2035
- // The same menu opens from a right-click (or the keyboard's context-menu key) on the row and from
2036
- // the row's More actions button.
2037
1831
  function showAgentMenu(definition, use, x, y) {
2038
1832
  showMenuAt(x, y, `${definition.name} actions`, [
2039
1833
  { label: 'Use', icon: 'plus', run: use },
@@ -2045,16 +1839,9 @@ function showAgentMenu(definition, use, x, y) {
2045
1839
  async function readDefinitions() {
2046
1840
  const data = await api('/api/bootstrap'); state.definitions = foldDefinitionCaps(data.definitions); return state.definitions;
2047
1841
  }
2048
- // The id is fixed for the dialog's lifetime and a committed write is confirmed from the store
2049
- // before any failure is reported: a dropped response or a failed refresh must not turn the
2050
- // author's second Save into a duplicate Agent. A refresh failure after a committed write is
2051
- // reported instead of rethrown, because the Agent is saved either way.
2052
1842
  async function writeDefinition(payload, saved) {
2053
1843
  try { await api('/api/definitions', payload); }
2054
1844
  catch (error) {
2055
- // A lost response can still have committed the write, so confirm it from the store. The
2056
- // confirmation must be the record the author asked for: a form edited after that commit is a
2057
- // different Agent, and reporting it as created would hide that the stored name differs.
2058
1845
  const existing = (await readDefinitions().catch(() => undefined))?.find(definition => definition.id === payload.id);
2059
1846
  if (!existing) throw error;
2060
1847
  if (existing.name !== payload.name) throw new Error(`This Agent is already saved as "${existing.name}". Reload the library to see it, then copy again for a different name.`);
@@ -2068,11 +1855,7 @@ function renderLibrary() {
2068
1855
  const query = $('node-search').value.toLowerCase();
2069
1856
  const definitionItem = d => ({name:d.name,type:'agent',description:d.preset ? 'Editable Agent preset' : `Saved agent · version ${d.revision}`,node:d.node,definition:d});
2070
1857
  const addItem = (parent, item) => {
2071
- // A library item drags onto the canvas; a click, Enter or Space adds it, so the library stays
2072
- // usable without a pointer. The type icon is placed first by the stylesheet's grid.
2073
1858
  const row = el('div', undefined, 'library-row'), button = el('button', undefined, 'library-item'); button.append(el('b', item.name), el('span', item.description));
2074
- // Add agent and Import agent manage the list itself: a click opens their dialog, and they are
2075
- // neither draggable nor given the Agent menu.
2076
1859
  if (item.action) {
2077
1860
  const actionGlyph = globalThis.AndorraIcons?.icon?.(item.icon);
2078
1861
  if (actionGlyph) button.append(actionGlyph);
@@ -2085,21 +1868,15 @@ function renderLibrary() {
2085
1868
  button.setAttribute('data-node-type', item.type);
2086
1869
  button.title = `Drag onto the canvas, or press Enter to add ${item.name}`;
2087
1870
  const cannotAdd = !state.graph || (Object.keys(state.graph.nodes).length >= nodeLimit(state.graph, item.node) && !(item.node?.agentRole === 'orchestrator' && Object.values(state.graph.nodes).some(node => node.agentRole === 'orchestrator')));
2088
- // A free-tier refusal leaves the item clickable, so a click explains the limit rather than doing nothing.
2089
1871
  const freeRefusal = freeNodeRefusal([{ type: item.type, agentRole: item.node?.agentRole }]);
2090
1872
  if (freeRefusal) button.title = freeRefusal;
2091
1873
  button.disabled = cannotAdd && !item.definition; button.draggable = !button.disabled && !freeRefusal;
2092
1874
  button.onclick = () => { if (cannotAdd) { status(state.graph ? 'Graph step limit reached.' : 'Open a graph to add this Agent.', true); return; } addNode(item.type, item.node); };
2093
1875
  button.ondragstart = event => { event.dataTransfer.setData('application/andorra-node', JSON.stringify({name:item.name,type:item.type,node:item.node})); event.dataTransfer.effectAllowed = 'copy'; };
2094
1876
  row.append(button);
2095
- // An Agent's actions are secondary, so they open from a right-click on the row (which the
2096
- // keyboard's context-menu key and Shift+F10 also raise) or from a quiet icon that shows on the
2097
- // row's hover or focus rather than a pill on every row.
2098
1877
  if (item.definition) {
2099
1878
  const openMenu = (x, y) => showAgentMenu(item.definition, () => button.onclick(), x, y);
2100
1879
  row.oncontextmenu = event => { event.preventDefault(); openMenu(event.clientX, event.clientY); };
2101
- // Not every host raises a contextmenu event for the keyboard's own menu keys, so they open
2102
- // the menu directly beneath the focused row; preventing the default avoids a second opening.
2103
1880
  button.onkeydown = event => {
2104
1881
  if (event.key !== 'ContextMenu' && !(event.shiftKey && event.key === 'F10')) return;
2105
1882
  event.preventDefault();
@@ -2135,15 +1912,11 @@ function renderLibrary() {
2135
1912
  section(container,'flow','Flow',[{name:'Human approval',type:'approval',description:'Pause for a decision'},{name:'End',type:'end',description:'Finish this graph path'}]);
2136
1913
  if (query && !container.children.length) container.append(emptyState('search', 'No steps match', 'Try another name, or clear the search.'));
2137
1914
  }
2138
- // Fit, Arrange and the zoom buttons ease the view to where it is going, over --dur-3 on an ease-in-out
2139
- // with no overshoot, so the eye can follow the cards. A gesture (pan, pinch, wheel) stops the ease and
2140
- // takes over at once. Reduced motion, and a page that draws no frames, jump straight there.
2141
1915
  let viewAnimation = 0, viewTarget = null;
2142
1916
  function stopViewAnimation() { cancelFrame(viewAnimation); viewAnimation = 0; viewTarget = null; }
2143
1917
  const easeInOut = t => (t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
2144
1918
  function viewDuration() { return Math.min(240, parseFloat(themeColor('--dur-3', '200ms')) || 200); }
2145
1919
  function reducedMotion() { try { return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; } catch { return false; } }
2146
- /** Ease the view to `target` ({x, y, zoom}); with an `anchor`, that screen point stays still. */
2147
1920
  function animateView(target, anchor) {
2148
1921
  stopViewAnimation();
2149
1922
  if (reducedMotion() || typeof requestAnimationFrame !== 'function' || typeof performance === 'undefined') { Object.assign(state, target); transform(); return; }
@@ -2151,7 +1924,6 @@ function animateView(target, anchor) {
2151
1924
  viewTarget = target;
2152
1925
  const step = now => {
2153
1926
  const t = Math.min(1, Math.max(0, (now - begin) / duration)), k = easeInOut(t);
2154
- // The zoom moves geometrically, so each frame scales by the same ratio.
2155
1927
  state.zoom = from.zoom * Math.pow(target.zoom / from.zoom, k);
2156
1928
  if (anchor) { state.x = anchor.x - (anchor.x - from.x) * state.zoom / from.zoom; state.y = anchor.y - (anchor.y - from.y) * state.zoom / from.zoom; }
2157
1929
  else { state.x = from.x + (target.x - from.x) * k; state.y = from.y + (target.y - from.y) * k; }
@@ -2169,9 +1941,7 @@ function fit(animate = false) {
2169
1941
  stopViewAnimation(); Object.assign(state, target); transform();
2170
1942
  }
2171
1943
  const ZOOM_MIN = .2, ZOOM_MAX = 2;
2172
- /** Zoom at once about a screen point: the pinch and Ctrl/Cmd+wheel gesture. */
2173
1944
  function zoom(factor, x = $('canvas').clientWidth / 2, y = $('canvas').clientHeight / 2) { stopViewAnimation(); const next = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, state.zoom * factor)); state.x = x - (x - state.x) * next / state.zoom; state.y = y - (y - state.y) * next / state.zoom; state.zoom = next; requestTransform(); }
2174
- /** The zoom buttons: ease about the canvas centre. A press during an ease builds on where it was going. */
2175
1945
  function zoomBy(factor) {
2176
1946
  const x = $('canvas').clientWidth / 2, y = $('canvas').clientHeight / 2, base = viewTarget ?? state;
2177
1947
  const next = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, base.zoom * factor));
@@ -2179,23 +1949,16 @@ function zoomBy(factor) {
2179
1949
  if (viewTarget) { animateView(target); return; }
2180
1950
  animateView(target, { x, y });
2181
1951
  }
2182
- // A keyboard-activated click carries no pointer coordinates, so the menu falls back to the
2183
- // window corner rather than refusing to open.
2184
1952
  $('new-graph').onclick = event => showNewGraphMenu(event?.clientX ?? 0, event?.clientY ?? 0); $('empty-create').onclick = () => newGraph(); $('duplicate').onclick = () => newGraph(true); $('search').oninput = renderList;
2185
1953
  $('node-search').oninput = renderLibrary;
2186
1954
  $('graph-settings').onclick = () => { clearSelection(); renderCanvas(); renderInspector(); };
2187
1955
  $('toggle-inspector').onclick = () => { const hidden = $('inspector').classList.toggle('hidden'); $('toggle-inspector').setAttribute('aria-expanded', String(!hidden)); };
2188
1956
  $('undo').onclick = () => { if (!state.undo.length) return; state.redo.push(copy(state.graph)); state.graph = state.undo.pop(); clearSelection(); refreshDirty(); render(); status(state.dirty ? 'Change undone' : 'Change undone · No unsaved changes'); };
2189
1957
  $('redo').onclick = () => { if (!state.redo.length) return; state.undo.push(copy(state.graph)); state.graph = state.redo.pop(); clearSelection(); refreshDirty(); render(); status('Change restored'); };
2190
- // A refused Save briefly pulses the outlined nodes, so the eye finds the cards it must fix
2191
- // before the run can be saved. No re-render happens on that early return, so the class lives.
2192
1958
  function pulseErrorNodes() {
2193
1959
  for (const element of document.querySelectorAll?.('.node.node-error') ?? []) element.classList.add('node-error-pulse');
2194
1960
  setTimeout(() => { for (const element of document.querySelectorAll?.('.node.node-error-pulse') ?? []) element.classList.remove('node-error-pulse'); }, 1300);
2195
1961
  }
2196
- // After a successful save, a requirement is retired only if its node is gone or now has a
2197
- // provider: edits made while the save was in flight (a providerless clipboard paste) keep
2198
- // theirs, since the submitted snapshot never covered them.
2199
1962
  function retireSatisfiedProviderRequirements() {
2200
1963
  if (!state.pendingProviderNodes?.size) return;
2201
1964
  const stillOwed = new Set();
@@ -2207,13 +1970,13 @@ function retireSatisfiedProviderRequirements() {
2207
1970
  syncImportRequirementsMarker();
2208
1971
  }
2209
1972
  $('save').onclick = async () => {
2210
- if (state.saving) return;
1973
+ if (state.saving || state.orderSaving) return;
2211
1974
  const invalid = document.querySelector('textarea:invalid, input:invalid'); if (invalid) { revealInspectorControl(invalid); invalid.reportValidity(); return; } const errors = issues(); if (errors.length) { status(errors[0].message, true); pulseErrorNodes(); return; }
2212
1975
  state.saving = true; renderHeading(); renderList();
1976
+ let orderFailed = false;
2213
1977
  try { const submitted = dropLegacyTokenFields(copy(state.graph)); const graph = await api('/api/graphs', submitted); if (state.graph.id === submitted.id) {
2214
- // The draft marker is editor state, not graph content, so a difference in it alone is not an edit.
2215
1978
  const liveView = { ...state.graph }; delete liveView.pendingProviderNodes;
2216
- const edited = JSON.stringify(liveView) !== JSON.stringify(submitted); markSaved(graph); if (edited) { state.graph.revision = graph.revision; adoptServerStamps(graph); state.undo = []; state.redo = []; refreshDirty(); } else { state.graph = graph; state.dirty = false; state.undo = []; state.redo = []; } retireSatisfiedProviderRequirements(); } const index = state.graphs.findIndex(g => g.id === graph.id); const summary = { id: graph.id, name: graph.name, revision: graph.revision }; if (index >= 0) state.graphs[index] = summary; else state.graphs.push(summary); render(); status(`Saved version ${graph.revision}${state.dirty ? ' · You have newer unsaved changes' : ''}`); } catch (error) { status(error.message, true); } finally { state.saving = false; renderHeading(); renderList(); }
1979
+ const edited = JSON.stringify(liveView) !== JSON.stringify(submitted); markSaved(graph); if (edited) { state.graph.revision = graph.revision; adoptServerStamps(graph); state.undo = []; state.redo = []; refreshDirty(); } else { state.graph = graph; state.dirty = false; state.undo = []; state.redo = []; } retireSatisfiedProviderRequirements(); } const index = state.graphs.findIndex(g => g.id === graph.id); const summary = { id: graph.id, name: graph.name, revision: graph.revision }; if (index >= 0) state.graphs[index] = summary; else { state.graphs.push(summary); try { await persistGraphOrder(); } catch { orderFailed = true; } } render(); status(`Saved version ${graph.revision}${state.dirty ? ' · You have newer unsaved changes' : ''}${orderFailed ? ' · Graph order not saved' : ''}`); } catch (error) { status(error.message, true); } finally { state.saving = false; renderHeading(); renderList(); }
2217
1980
  };
2218
1981
  $('canvas-hint-close').onclick = dismissCanvasHint;
2219
1982
  $('fit').onclick = () => fit(true); $('zoom-in').onclick = () => zoomBy(1.2); $('zoom-out').onclick = () => zoomBy(1 / 1.2);
@@ -2222,9 +1985,6 @@ $('layout').onclick = () => mutate(() => {
2222
1985
  while (queue.length) { const id = queue.shift(); for (const edge of state.graph.edges.filter(e => e.source === id)) if (!levels.has(edge.target)) { levels.set(edge.target, levels.get(id) + 1); queue.push(edge.target); } }
2223
1986
  const rows = new Map(); for (const node of Object.values(state.graph.nodes)) { const level = levels.get(node.id) ?? 0, row = rows.get(level) || 0; node.position = { x: level * 300, y: row * 220 }; rows.set(level, row + 1); } fit(true);
2224
1987
  }, true);
2225
- // Two-finger scroll pans, as on every canvas a trackpad drives; a pinch (which the browser reports as
2226
- // a wheel with Ctrl held) or Ctrl/Cmd with a mouse wheel zooms about the pointer. A mouse wheel with
2227
- // Shift pans sideways. Only the floating controls keep the wheel to themselves.
2228
1988
  const WHEEL_LINE_PX = 16, WHEEL_ZOOM_CAP = 50, WHEEL_ZOOM_RATE = 150;
2229
1989
  $('canvas').addEventListener('wheel', event => {
2230
1990
  if (event.target.closest('.canvas-toolbar, .canvas-hint, #studio-minimap')) return;
@@ -2250,8 +2010,6 @@ $('canvas').ondrop = event => {
2250
2010
  try {const item=JSON.parse(raw);if(!item || typeof item.type!=='string')return;const bounds=$('canvas').getBoundingClientRect();addNode(item.type,item.node,{x:Math.round((event.clientX-bounds.left-state.x)/state.zoom),y:Math.round((event.clientY-bounds.top-state.y)/state.zoom)});} catch(error){status('This library item could not be added: '+error.message,true);}
2251
2011
  return;
2252
2012
  }
2253
- // An OS file dropped onto the canvas imports as a new graph (the desktop host hands drops
2254
- // over through its own frame channel, so this path only serves a browser-opened studio).
2255
2013
  const file = Array.from(event.dataTransfer?.files || []).find(item => /\.json$/i.test(item.name) || item.type === 'application/json');
2256
2014
  if (file) { event.preventDefault(); void window.AndorraStudio?.importGraphFile?.(file)?.catch(error => status(error.message, true)); }
2257
2015
  };
@@ -2259,37 +2017,27 @@ $('canvas').onpointerdown = event => { if (event.button !== 0 || event.target.cl
2259
2017
  $('resize').onpointerdown = event => { $('resize').setPointerCapture(event.pointerId); $('resize').onpointermove = e => { document.documentElement.style.setProperty('--panel', `${Math.max(360, Math.min(720, innerWidth - e.clientX))}px`); }; $('resize').onpointerup = () => { $('resize').onpointermove = null; }; };
2260
2018
  $('resize').onkeydown = event => { if (!['ArrowLeft', 'ArrowRight'].includes(event.key)) return; event.preventDefault(); const width = $('inspector').getBoundingClientRect().width + (event.key === 'ArrowLeft' ? 20 : -20); document.documentElement.style.setProperty('--panel', `${Math.max(360, Math.min(720, width))}px`); };
2261
2019
  $('export').onclick = () => { if (!state.graph) return; downloadGraph(state.graph); };
2262
- // A change of appearance repaints the connections, whose colours are read from the tokens.
2263
2020
  if (typeof document.addEventListener === 'function') {
2264
2021
  document.addEventListener('andorra:themechange', () => { if (state.graph) renderCanvas(); });
2265
2022
  }
2266
- // A draft still waiting out its pause is written as the page goes, so closing the tab right after
2267
- // an edit does not lose it.
2268
2023
  window.addEventListener('pagehide', () => { void flushDraft(true); });
2269
2024
  window.addEventListener('beforeunload', event => { document.activeElement?.blur(); if (state.dirty) { event.preventDefault(); event.returnValue = ''; } });
2270
2025
  window.addEventListener('keydown', event => { if(event.key==='Delete' && !document.querySelector('dialog[open]') && !event.target?.closest('input, textarea, select, [contenteditable]:not([contenteditable=\"false\"])') && !event.isComposing) {event.preventDefault();deleteSelection();return;} if(event.key==='Escape' && state.routePick){event.preventDefault();cancelRoutePick();return;} if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { event.preventDefault(); document.activeElement?.blur(); if (!$('save').disabled) $('save').click(); } });
2271
2026
  async function refreshCloudState() {
2272
2027
  if (!token) return;
2028
+ const orderSavingDuringSync = state.orderSaving;
2273
2029
  try {
2274
2030
  const sync = await api('/api/sync');
2275
2031
  if ($('sync-status')) $('sync-status').textContent = sync.detail;
2276
2032
  await refreshDrafts();
2277
- const data = await api('/api/bootstrap'); state.plan = data.plan; state.graphs = data.graphs; applyProviderRegistry(data); renderList();
2033
+ const data = await api('/api/bootstrap'); state.plan = data.plan; applyProviderRegistry(data);
2034
+ if (!state.orderSaving && !orderSavingDuringSync) { state.graphs = data.graphs; }
2035
+ renderList();
2278
2036
  } catch (error) { if ($('sync-status')) $('sync-status').textContent = 'Cloud sync unavailable: ' + error.message; }
2279
2037
  setTimeout(refreshCloudState, 10000);
2280
2038
  }
2281
- // First sync check after one second; subsequent status/list refreshes remain periodic.
2282
2039
  if (token) setTimeout(refreshCloudState, 1000);
2283
2040
 
2284
- /* CLI run activity: this tab mirrors the live run state of the CLI sharing this installation.
2285
- A spinner favicon turns while the CLI works; an exclamation favicon, a title prefix, and a
2286
- system notification (a Windows toast) fire when the CLI waits on the user. Every browser
2287
- entry point is feature-detected because this module also loads into partial-DOM harnesses.
2288
- The idle favicon is the published Andorra Labs logo; the two busy states are status markers
2289
- rather than the brand, so they keep their own artwork, drawn in the theme's neutral inks when they
2290
- are set: both stand on the neutral accent's tile, with the turning ring or the wait's mark in the
2291
- ink that sits on it, so either reads on a light or a dark tab strip. The chrome keeps no amber
2292
- (P-LNT-16). Each fallback is the dark token's own value, for a page without the stylesheet. */
2293
2041
  const baseTitle = document.title || 'Graph Editor · Andorra Code';
2294
2042
  const faviconHref = svg => 'data:image/svg+xml,' + encodeURIComponent(svg);
2295
2043
  const FAVICONS = {
@@ -2308,33 +2056,25 @@ function setFavicon(activity) {
2308
2056
  const href = (FAVICONS[activity] || FAVICONS.idle)();
2309
2057
  link.setAttribute('type', href.startsWith('data:') ? 'image/svg+xml' : 'image/png');
2310
2058
  link.setAttribute('href', href);
2311
- } catch { /* A partial DOM cannot host a favicon. */ }
2059
+ } catch { }
2312
2060
  }
2313
2061
  let lastActivityKey;
2314
2062
  function applyActivity(value) {
2315
2063
  if (!value) return;
2316
- // Feature-detected: the run-activity block is exercised in partial-DOM harnesses where the
2317
- // provider registry lives outside the evaluated slice.
2318
2064
  if (typeof applyProviderRegistry === 'function') applyProviderRegistry(value);
2319
2065
  if (!Object.hasOwn(FAVICONS, value.state)) return;
2320
2066
  setFavicon(value.state);
2321
- // One phrase for a run waiting on the person, the desktop's (P-ATN-07): "Needs your input".
2322
2067
  document.title = value.state === 'running' ? `Running · ${baseTitle}` : value.state === 'awaiting-input' ? `Needs your input · ${baseTitle}` : baseTitle;
2323
2068
  const activityKey = JSON.stringify([value.state, value.runId, value.updatedAt, value.kind, value.detail]);
2324
- // Native-app notifications are requested by the top-level Tauri window. Browsers
2325
- // deny permission requests from cross-origin iframes, so relay only safe status.
2326
2069
  window.AndorraEmbed?.activity?.(value);
2327
2070
  if ((!window.parent || window.parent === window) && value.state === 'awaiting-input' &&
2328
2071
  lastActivityKey !== activityKey && typeof Notification === 'function' && Notification.permission === 'granted') {
2329
- // The desktop's own notice for the same state (desktop/src/engine/taskNotifications.ts).
2330
- try { new Notification('Needs your input', { body: value.detail || 'A graph run is waiting for your answer in its terminal.', tag: 'andorra-activity' }); } catch { /* The favicon and title still changed. */ }
2072
+ try { new Notification('Needs your input', { body: value.detail || 'A graph run is waiting for your answer in its terminal.', tag: 'andorra-activity' }); } catch { }
2331
2073
  }
2332
2074
  lastActivityKey = activityKey;
2333
2075
  }
2334
- // Browsers want a user gesture before showing the permission prompt, so ask on the first click
2335
- // or keypress; until then the favicon and title carry the state without notifications.
2336
2076
  function requestActivityNotifications() {
2337
- try { if (typeof Notification === 'function' && Notification.permission === 'default') void Notification.requestPermission(); } catch { /* Denied or unsupported. */ }
2077
+ try { if (typeof Notification === 'function' && Notification.permission === 'default') void Notification.requestPermission(); } catch { }
2338
2078
  window.removeEventListener('pointerdown', requestActivityNotifications);
2339
2079
  window.removeEventListener('keydown', requestActivityNotifications);
2340
2080
  }
@@ -2345,36 +2085,27 @@ function watchActivity() {
2345
2085
  applyActivity(await api('/api/activity'));
2346
2086
  pollFailures = 0;
2347
2087
  } catch {
2348
- // A dead server must not leave the fallback path claiming a run forever: after the same
2349
- // 20-second grace the stream path uses (four failed five-second polls), clear to idle
2350
- // and keep polling quietly in case a server comes back.
2351
2088
  if (++pollFailures === 4) applyActivity({ state: 'idle' });
2352
2089
  }
2353
2090
  setTimeout(poll, 5000);
2354
2091
  };
2355
- // Prefer a server-sent event stream: background tabs throttle timers, and a throttled poll
2356
- // could report an input request minutes late. EventSource cannot send the Authorization
2357
- // header, so the stream accepts the session token in the query string.
2358
2092
  if (typeof EventSource !== 'function' || !token) { setTimeout(poll, 1000); return; }
2359
2093
  let source;
2360
2094
  try { source = new EventSource(`/api/activity/stream?token=${encodeURIComponent(token)}`); }
2361
2095
  catch { setTimeout(poll, 1000); return; }
2362
- // The CLI that hosts this tab's server can exit mid-run, and a dead stream must not leave the
2363
- // tab claiming a run forever. EventSource retries silently, so only clear the state after the
2364
- // retries have had a real grace period; polling then takes over if a server ever returns.
2365
2096
  let staleTimer;
2366
2097
  source.onmessage = event => {
2367
2098
  clearTimeout(staleTimer);
2368
2099
  staleTimer = undefined;
2369
- try { applyActivity(JSON.parse(event.data)); } catch { /* Ignore a malformed frame. */ }
2100
+ try { applyActivity(JSON.parse(event.data)); } catch { }
2370
2101
  };
2371
2102
  source.onerror = () => {
2372
2103
  if (staleTimer !== undefined) return;
2373
- staleTimer = setTimeout(() => { try { source.close(); } catch { /* Already closed. */ } applyActivity({ state: 'idle' }); poll(); }, 20000);
2104
+ staleTimer = setTimeout(() => { try { source.close(); } catch { } applyActivity({ state: 'idle' }); poll(); }, 20000);
2374
2105
  };
2375
2106
  }
2376
2107
  setFavicon('idle');
2377
2108
  if (token) watchActivity();
2378
- try { if ((!window.parent || window.parent === window) && typeof Notification === 'function' && Notification.permission === 'default') { window.addEventListener('pointerdown', requestActivityNotifications); window.addEventListener('keydown', requestActivityNotifications); } } catch { /* Partial DOM. */ }
2109
+ try { if ((!window.parent || window.parent === window) && typeof Notification === 'function' && Notification.permission === 'default') { window.addEventListener('pointerdown', requestActivityNotifications); window.addEventListener('keydown', requestActivityNotifications); } } catch { }
2379
2110
 
2380
- (async () => { renderHeading(); if (!token) { status('The sign-in token is missing. Open this app with the andorra graph command.', true); return; } try { const data = await api('/api/bootstrap'); state.plan = data.plan; state.graphs = data.graphs; applyProviderRegistry(data); state.tools = data.tools || []; state.definitions = foldDefinitionCaps(data.definitions); renderLibrary(); renderList(); const wantsNew = new URLSearchParams(location.search).get('new') === '1'; if (wantsNew && canCreateGraph()) newGraph(); else if (!wantsNew && await reopenRemembered()) { /* The graph this tab had open before it reloaded. */ } else if (state.graphs.length) { await openGraph((freeTier() && state.plan.freeGraphId) || state.graphs[0].id); if (wantsNew) status(FREE_CREATE_TIP, true); } else { render(); status('Create your first graph'); } window.AndorraEmbed?.ready?.(); if (data.graphMigrationErrors?.length) status('Some saved graphs could not be opened: ' + data.graphMigrationErrors.map(item => item.name + ' (' + item.id + '): ' + item.error).join('; ') + '. Their saved versions are unchanged.', true); } catch (error) { status(error.message, true); } })();
2111
+ (async () => { renderHeading(); if (!token) { status('The sign-in token is missing. Open this app with the andorra graph command.', true); return; } try { const data = await api('/api/bootstrap'); state.plan = data.plan; state.graphs = data.graphs; applyProviderRegistry(data); state.tools = data.tools || []; state.definitions = foldDefinitionCaps(data.definitions); renderLibrary(); renderList(); const wantsNew = new URLSearchParams(location.search).get('new') === '1'; if (wantsNew && canCreateGraph()) newGraph(); else if (!wantsNew && await reopenRemembered()) { } else if (state.graphs.length) { await openGraph((freeTier() && state.plan.freeGraphId) || state.graphs[0].id); if (wantsNew) status(FREE_CREATE_TIP, true); } else { render(); status('Create your first graph'); } window.AndorraEmbed?.ready?.(); if (data.graphMigrationErrors?.length) status('Some saved graphs could not be opened: ' + data.graphMigrationErrors.map(item => item.name + ' (' + item.id + '): ' + item.error).join('; ') + '. Their saved versions are unchanged.', true); } catch (error) { status(error.message, true); } })();