@andorra-labs/code 0.1.14 → 0.1.15

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 (107) hide show
  1. package/dist/src/acp-agent.d.ts +54 -0
  2. package/dist/src/acp-agent.js +991 -0
  3. package/dist/src/agent-execution.js +4 -0
  4. package/dist/src/agent-mcp-catalog.js +2 -0
  5. package/dist/src/agent-mcp.d.ts +2 -0
  6. package/dist/src/agent-mcp.js +84 -2
  7. package/dist/src/andorra/entry.js +21 -3
  8. package/dist/src/andorra/hosted.d.ts +3 -0
  9. package/dist/src/andorra/hosted.js +5 -1
  10. package/dist/src/andorra/notices.d.ts +10 -1
  11. package/dist/src/andorra/notices.js +25 -2
  12. package/dist/src/andorra/terminal.d.ts +2 -0
  13. package/dist/src/andorra/terminal.js +2 -2
  14. package/dist/src/app-server/protocol.d.ts +6 -2
  15. package/dist/src/app-server/protocol.js +1 -1
  16. package/dist/src/app-server/workspace.d.ts +1 -0
  17. package/dist/src/app-server/workspace.js +141 -10
  18. package/dist/src/app-server.d.ts +8 -0
  19. package/dist/src/app-server.js +87 -41
  20. package/dist/src/auth/AuthManager.js +4 -4
  21. package/dist/src/browser-bridge.d.ts +1 -0
  22. package/dist/src/browser-bridge.js +5 -2
  23. package/dist/src/browser-external-app.d.ts +27 -0
  24. package/dist/src/browser-external-app.js +60 -0
  25. package/dist/src/browser-panel-tool.d.ts +6 -0
  26. package/dist/src/browser-panel-tool.js +36 -0
  27. package/dist/src/browser-server.d.ts +5 -0
  28. package/dist/src/browser-server.js +27 -3
  29. package/dist/src/browser-view.d.ts +16 -0
  30. package/dist/src/browser-view.js +60 -2
  31. package/dist/src/bug-report.d.ts +81 -0
  32. package/dist/src/bug-report.js +235 -0
  33. package/dist/src/claude-provider.d.ts +2 -1
  34. package/dist/src/claude-provider.js +10 -8
  35. package/dist/src/cli-sign-in.d.ts +3 -1
  36. package/dist/src/cli-sign-in.js +4 -1
  37. package/dist/src/cli.js +164 -34
  38. package/dist/src/coding-tools.js +7 -7
  39. package/dist/src/command-screens.d.ts +9 -2
  40. package/dist/src/command-screens.js +161 -94
  41. package/dist/src/commands.d.ts +1 -1
  42. package/dist/src/commands.js +1 -0
  43. package/dist/src/completion-gates.d.ts +22 -0
  44. package/dist/src/completion-gates.js +11 -0
  45. package/dist/src/config.d.ts +5 -0
  46. package/dist/src/config.js +48 -0
  47. package/dist/src/google-provider.d.ts +31 -0
  48. package/dist/src/google-provider.js +153 -0
  49. package/dist/src/graph-health.js +1 -1
  50. package/dist/src/graph-manager-chat.js +6 -1
  51. package/dist/src/graph-sync.d.ts +1 -0
  52. package/dist/src/graph-sync.js +93 -34
  53. package/dist/src/graph-tool.d.ts +2 -0
  54. package/dist/src/graph-tool.js +2 -2
  55. package/dist/src/graph-ui/app.js +67 -8
  56. package/dist/src/graph-ui/edge-router.js +121 -53
  57. package/dist/src/graph-visibility.d.ts +31 -0
  58. package/dist/src/graph-visibility.js +102 -0
  59. package/dist/src/live-model.d.ts +24 -0
  60. package/dist/src/live-model.js +37 -0
  61. package/dist/src/managed-sign-in.d.ts +1 -0
  62. package/dist/src/managed-sign-in.js +13 -0
  63. package/dist/src/membership-errors.d.ts +2 -0
  64. package/dist/src/membership-errors.js +5 -1
  65. package/dist/src/membership.d.ts +3 -0
  66. package/dist/src/membership.js +19 -2
  67. package/dist/src/model-health-cache.js +1 -1
  68. package/dist/src/model-metadata.js +8 -1
  69. package/dist/src/paged-transcript.d.ts +2 -0
  70. package/dist/src/paged-transcript.js +16 -0
  71. package/dist/src/provider-connection.js +17 -0
  72. package/dist/src/provider-engine.d.ts +5 -0
  73. package/dist/src/provider-engine.js +3 -3
  74. package/dist/src/provider-import.js +3 -1
  75. package/dist/src/provider-settings.js +14 -2
  76. package/dist/src/providers.d.ts +16 -2
  77. package/dist/src/providers.js +36 -12
  78. package/dist/src/react-runtime.js +21 -5
  79. package/dist/src/read-document-tool.d.ts +2 -0
  80. package/dist/src/read-document-tool.js +6 -6
  81. package/dist/src/remote/engine-pool.js +26 -2
  82. package/dist/src/runtime-environment.d.ts +1 -0
  83. package/dist/src/runtime-environment.js +13 -0
  84. package/dist/src/save-lock.js +14 -7
  85. package/dist/src/session-title.d.ts +3 -0
  86. package/dist/src/session-title.js +5 -2
  87. package/dist/src/sign-in-detection.d.ts +1 -1
  88. package/dist/src/sign-in-detection.js +10 -3
  89. package/dist/src/sign-in-offer.js +1 -1
  90. package/dist/src/skill-commands.js +1 -1
  91. package/dist/src/skills/bundled/bug-report/SKILL.md +80 -0
  92. package/dist/src/skills/bundled/graph-manager/SKILL.md +9 -1
  93. package/dist/src/skills/bundled/graph-manager/errors.md +1 -0
  94. package/dist/src/skills/bundled/provenance.json +7 -2
  95. package/dist/src/skills/runtime-skills.js +1 -0
  96. package/dist/src/telemetry/uploader.d.ts +7 -1
  97. package/dist/src/telemetry/uploader.js +11 -2
  98. package/dist/src/terminal-links.d.ts +16 -0
  99. package/dist/src/terminal-links.js +113 -0
  100. package/dist/src/terminal-ui.d.ts +8 -1
  101. package/dist/src/terminal-ui.js +40 -14
  102. package/dist/src/tool-catalog.js +1 -1
  103. package/dist/src/trajectory.js +6 -1
  104. package/dist/src/transcript.d.ts +2 -0
  105. package/dist/src/transcript.js +2 -1
  106. package/dist/src/types.d.ts +2 -0
  107. package/package.json +2 -1
@@ -17,13 +17,15 @@ import { droppedCodexSlots, removeCodexAccount } from './codex-auth.js';
17
17
  import { testProviderConnection } from './provider-connection.js';
18
18
  import { CodexAccountAuth } from './codex-browser-auth.js';
19
19
  import { AnthropicConsoleAuth, droppedAnthropicAccounts } from './anthropic-console-auth.js';
20
- import { claudeSignIn, grokSignIn, OpenCodeSignIn } from './managed-sign-in.js';
20
+ import { claudeSignIn, googleSignIn, grokSignIn, OpenCodeSignIn } from './managed-sign-in.js';
21
21
  import { applySignInImports, detectSignIns, isDetectableSignInType } from './sign-in-detection.js';
22
22
  import { OPENCODE_BASE_URL, sharedOpenCodeServer } from './opencode-cli-provider.js';
23
+ import { GOOGLE_BASE_URL } from './google-provider.js';
23
24
  import { GROK_BASE_URL } from './grok-provider.js';
24
25
  import { anthropicAccountHome } from './anthropic-credentials.js';
25
26
  import { codexAccountHome } from './codex-rpc.js';
26
27
  import { configuredModelSnapshot, discoverModelMetadata, resolveModelContext } from './model-metadata.js';
28
+ import { liveModelTarget } from './live-model.js';
27
29
  import { graphLeavesNodesToSession, graphMcpServers, isDeletedGraph, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
28
30
  import { exportAgentDefinition, readAgentDefinition } from './agent-definitions.js';
29
31
  import { blockingHealthFailures, checkGraphModelHealth, formatGraphHealthFailure, resumeModelNodes } from './graph-health.js';
@@ -36,6 +38,7 @@ import { hostedDecisionPolicy } from './decision/hostedPolicy.js';
36
38
  import { createAccountPresentationReader, publishableMembership } from './account-presentation.js';
37
39
  import { getAuthStatus, login, logout, setAuthSignOutReporter } from './auth/index.js';
38
40
  import { configuredGraphSelection, currentGraphSubject, identityStillHolds } from './graph-selection.js';
41
+ import { announceGraphVisibilityChange, graphVisibilityFor, importGraphVisibility, onGraphVisibilityChange, relinkGraphVisibility, setGraphVisibility } from './graph-visibility.js';
39
42
  import { graphStorageAccess } from './graph-account.js';
40
43
  import { GraphAccessSync } from './graph-sync.js';
41
44
  import { canExtendLineage, displayHistory, lineagePoints, lineageThrough, SessionStore, projectIdentity, removeSessionSnapshot, savedSessionFields, sessionName, validSavedSession } from './sessions.js';
@@ -95,7 +98,7 @@ import { APP_SERVER_PROTOCOL_VERSION, APP_SERVER_CAPABILITIES, } from './app-ser
95
98
  import { RemotePeerError } from './remote/errors.js';
96
99
  import { fallbackProviderId, hasAndorraEntry, virtualAndorraEntry } from './andorra/entry.js';
97
100
  import { ANDORRA_CHANGED_MESSAGE, ANDORRA_UNAVAILABLE_MESSAGE } from './andorra/endpoint.js';
98
- import { ANDORRA_ANNOUNCEMENT } from './andorra/notices.js';
101
+ import { andorraAnnouncement } from './andorra/notices.js';
99
102
  import { ANDORRA_REMOVE_FAILED, recordAndorraRemoved, removingAndorraEntry } from './andorra/state.js';
100
103
  import { addAndorraEntry, saveAndorraAnswer } from './andorra/opt-in.js';
101
104
  import { HostedMonitor } from './andorra/monitor.js';
@@ -168,7 +171,7 @@ function providerAuthView(view, includeUrl) {
168
171
  return result;
169
172
  }
170
173
  const MANAGED_SIGN_IN_HOSTS = {
171
- claude: ['claude.com', 'claude.ai', 'anthropic.com'], grok: ['x.ai', 'grok.com'], opencode: undefined,
174
+ claude: ['claude.com', 'claude.ai', 'anthropic.com'], grok: ['x.ai', 'grok.com'], google: ['accounts.google.com'], opencode: undefined,
172
175
  };
173
176
  function managedAuthView(type, view, includeUrl) {
174
177
  if (!['signedOut', 'starting', 'waiting', 'signedIn', 'cancelled', 'error'].includes(view.state))
@@ -375,6 +378,8 @@ function providerView(provider, providers) {
375
378
  ...(provider.models === undefined ? {} : { models: [...provider.models] }),
376
379
  ...(provider.modelContextWindows === undefined ? {} : { modelContextWindows: { ...provider.modelContextWindows } }),
377
380
  ...(provider.type !== 'andorra' || provider.modelNames === undefined ? {} : { modelNames: { ...provider.modelNames } }),
381
+ ...(provider.type !== 'andorra' || provider.modelParameters === undefined ? {} : { modelParameters: { ...provider.modelParameters } }),
382
+ ...(provider.type !== 'andorra' || provider.freeModels === undefined ? {} : { freeModels: [...provider.freeModels] }),
378
383
  ...(provider.contextWindow === undefined ? {} : { contextWindow: provider.contextWindow }),
379
384
  ...(provider.reasoningEffort === undefined ? {} : { reasoningEffort: provider.reasoningEffort }),
380
385
  ...(provider.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: provider.requestTimeoutMs }),
@@ -521,6 +526,11 @@ export function mergeProviderSecrets(stored, incoming) {
521
526
  // The engine keeps an Andorra entry's display names from the router; a client never sets them.
522
527
  if (provider.type === 'andorra' && previousEntry?.type === 'andorra' && previousEntry.modelNames !== undefined)
523
528
  provider.modelNames = { ...previousEntry.modelNames };
529
+ // Likewise the sizes and the free list: they describe what the router serves, so only the router sets them.
530
+ if (provider.type === 'andorra' && previousEntry?.type === 'andorra' && previousEntry.modelParameters !== undefined)
531
+ provider.modelParameters = { ...previousEntry.modelParameters };
532
+ if (provider.type === 'andorra' && previousEntry?.type === 'andorra' && previousEntry.freeModels !== undefined)
533
+ provider.freeModels = [...previousEntry.freeModels];
524
534
  if (source.name === null)
525
535
  delete provider.name;
526
536
  else if (source.name === undefined) {
@@ -696,6 +706,7 @@ export class AppServer {
696
706
  anthropicAuth;
697
707
  claudeSignIn;
698
708
  grokSignIn;
709
+ googleSignIn;
699
710
  openCodeSignIn;
700
711
  signInProbes;
701
712
  detectedSignIns = new Map();
@@ -707,6 +718,8 @@ export class AppServer {
707
718
  reviewWaiters = new Map();
708
719
  reviewWaitsStarting = new Set();
709
720
  graphSync = new GraphAccessSync(undefined, undefined, () => this.emit('graphs.changed', {}));
721
+ // A visibility change made in this process, by a client or by the graph manager's tool in a run, reloads every client's list.
722
+ stopGraphVisibilityWatch = onGraphVisibilityChange(() => this.emit('graphs.changed', {}));
710
723
  terminals;
711
724
  backgroundTasks = new BackgroundTasks();
712
725
  stopBackgroundWatch = () => { };
@@ -773,6 +786,7 @@ export class AppServer {
773
786
  this.anthropicAuth = options.anthropicAuth ?? new AnthropicConsoleAuth();
774
787
  this.claudeSignIn = options.managedSignIn?.claude ?? claudeSignIn();
775
788
  this.grokSignIn = options.managedSignIn?.grok ?? grokSignIn();
789
+ this.googleSignIn = options.managedSignIn?.google ?? googleSignIn();
776
790
  this.openCodeSignIn = options.managedSignIn?.opencode ?? new OpenCodeSignIn();
777
791
  this.signInProbes = options.signInProbes;
778
792
  this.retireCodexAccount = options.removeCodexAccount ?? removeCodexAccount;
@@ -815,7 +829,7 @@ export class AppServer {
815
829
  hasEntry: async () => hasAndorraEntry(await loadConfig(this.directory)),
816
830
  onChange: () => { void this.hostedStatus().then(payload => { if (!this.closed)
817
831
  this.emit('andorra.status', payload); }, () => { }); },
818
- onAnnounce: ({ promotionId }) => this.emit('andorra.announce', { message: ANDORRA_ANNOUNCEMENT, promotionId }),
832
+ onAnnounce: ({ promotionId }) => this.emit('andorra.announce', { message: andorraAnnouncement(), promotionId }),
819
833
  onNotice: () => this.emit('andorra.notice', { message: ANDORRA_CHANGED_MESSAGE }),
820
834
  });
821
835
  this.timers.onDue = () => this.checkTimers();
@@ -1273,6 +1287,8 @@ export class AppServer {
1273
1287
  case 'graphs.list': return this.listGraphs(params);
1274
1288
  case 'graphs.get': return this.getGraph(params);
1275
1289
  case 'graphs.select': return this.selectGraph(params);
1290
+ case 'graphs.visibility.set': return this.setGraphVisibilityMethod(params);
1291
+ case 'graphs.visibility.import': return this.importGraphVisibilityMethod(params);
1276
1292
  case 'agents.export': return this.exportAgent(params);
1277
1293
  case 'editor.open': return this.openEditor();
1278
1294
  case 'editor.close': return this.closeEditor();
@@ -2093,9 +2109,9 @@ export class AppServer {
2093
2109
  async discoverModels(params) {
2094
2110
  let provider;
2095
2111
  if (params.providerType !== undefined) {
2096
- const catalogs = { claude: 'https://api.anthropic.com', 'opencode-go': 'https://opencode.ai/inference/go', grok: GROK_BASE_URL, opencode: OPENCODE_BASE_URL };
2112
+ const catalogs = { claude: 'https://api.anthropic.com', 'opencode-go': 'https://opencode.ai/inference/go', grok: GROK_BASE_URL, google: GOOGLE_BASE_URL, opencode: OPENCODE_BASE_URL };
2097
2113
  if (params.providerId !== undefined || typeof params.providerType !== 'string' || !Object.hasOwn(catalogs, params.providerType)) {
2098
- throw new AppServerError('invalid-params', 'providerType must be claude, grok, opencode or opencode-go, without providerId');
2114
+ throw new AppServerError('invalid-params', 'providerType must be claude, grok, google, opencode or opencode-go, without providerId');
2099
2115
  }
2100
2116
  const type = params.providerType;
2101
2117
  provider = { id: 'catalog', type, model: type === 'opencode' ? 'catalog/catalog' : 'catalog', baseUrl: catalogs[type] };
@@ -2118,7 +2134,7 @@ export class AppServer {
2118
2134
  async detectProviderSignIns(params) {
2119
2135
  const skip = params.skip;
2120
2136
  if (Object.keys(params).some(key => key !== 'skip') || (skip !== undefined && (!Array.isArray(skip) || skip.length > 8 || skip.some(type => !isDetectableSignInType(type))))) {
2121
- throw new AppServerError('invalid-params', 'Sign-in detection accepts only skip, a list of claude, codex, grok or opencode.');
2137
+ throw new AppServerError('invalid-params', 'Sign-in detection accepts only skip, a list of claude, codex, grok, opencode or google.');
2122
2138
  }
2123
2139
  const config = await loadConfig(this.directory);
2124
2140
  const { signIns } = await this.operation(60_000, signal => detectSignIns(config, signal, {
@@ -2169,10 +2185,10 @@ export class AppServer {
2169
2185
  return { config: view, added };
2170
2186
  }
2171
2187
  async providerAuth(action, params) {
2172
- if (params.providerType === 'claude' || params.providerType === 'grok' || params.providerType === 'opencode')
2188
+ if (params.providerType === 'claude' || params.providerType === 'grok' || params.providerType === 'google' || params.providerType === 'opencode')
2173
2189
  return this.managedProviderAuth(action, params);
2174
2190
  if (action === 'submit')
2175
- throw new AppServerError('invalid-params', 'Only Claude, Grok and OpenCode sign-ins accept a pasted code.');
2191
+ throw new AppServerError('invalid-params', 'Only Claude, Grok, Google and OpenCode sign-ins accept a pasted code.');
2176
2192
  if (params.providerType === 'anthropic')
2177
2193
  return this.anthropicProviderAuth(action, params);
2178
2194
  if (params.providerType !== 'codex' || Object.keys(params).some(key => !['providerType', 'attemptId', 'providerId'].includes(key))) {
@@ -2205,7 +2221,7 @@ export class AppServer {
2205
2221
  }
2206
2222
  async managedProviderAuth(action, params) {
2207
2223
  const type = params.providerType;
2208
- const product = type === 'claude' ? 'Claude' : type === 'grok' ? 'Grok' : 'OpenCode';
2224
+ const product = type === 'claude' ? 'Claude' : type === 'grok' ? 'Grok' : type === 'google' ? 'Google' : 'OpenCode';
2209
2225
  const allowed = ['providerType', 'attemptId', 'providerId', 'code', ...(type === 'opencode' ? ['signInProvider', 'signInMethod'] : [])];
2210
2226
  if (Object.keys(params).some(key => !allowed.includes(key))) {
2211
2227
  throw new AppServerError('invalid-params', `${product} sign-in accepts providerType, an optional attemptId and providerId${type === 'opencode' ? ', signInProvider and signInMethod' : ''}, and a code to submit.`);
@@ -2237,7 +2253,7 @@ export class AppServer {
2237
2253
  : await service.status(id);
2238
2254
  }
2239
2255
  else {
2240
- const service = type === 'claude' ? this.claudeSignIn : this.grokSignIn;
2256
+ const service = type === 'claude' ? this.claudeSignIn : type === 'google' ? this.googleSignIn : this.grokSignIn;
2241
2257
  view = action === 'start' ? await service.start(id)
2242
2258
  : action === 'cancel' ? await service.cancel(id)
2243
2259
  : action === 'submit' ? await service.submitCode(id, code)
@@ -3810,34 +3826,10 @@ export class AppServer {
3810
3826
  const current = liveRun?.modelSelection;
3811
3827
  if (!current)
3812
3828
  return undefined;
3813
- const [rootId, roleId] = (nodeId ?? '').split('/');
3814
- const fallback = roleId?.endsWith('#fallback') || rootId.endsWith('#fallback');
3815
- const own = liveRun?.modelGraph?.nodes[rootId.replace(/#fallback$/, '')];
3816
- const nodeOverride = current.nodeOverrides?.[rootId.replace(/#fallback$/, '')];
3817
- if (current.nodeOnly === true && nodeOverride === undefined && own?.provider === undefined)
3829
+ const target = liveModelTarget(current, liveRun?.modelGraph?.nodes, nodeId);
3830
+ if (target === undefined)
3818
3831
  return undefined;
3819
- const policy = own?.subagents;
3820
- const role = policy?.roles?.find(item => item.id === roleId?.replace(/#fallback$/, ''));
3821
- const parentProvider = nodeOverride?.provider ?? own?.provider ?? current.provider;
3822
- const parentModel = nodeOverride?.model ?? own?.model ?? (own?.provider === undefined ? current.model : undefined);
3823
- let targetProvider = parentProvider, targetModel = parentModel;
3824
- if (fallback && own?.retry?.fallback) {
3825
- targetProvider = own.retry.fallback.provider;
3826
- targetModel = own.retry.fallback.model;
3827
- }
3828
- const inheritedProvider = targetProvider, inheritedModel = targetModel;
3829
- if (roleId && policy?.modelPolicy === 'specific') {
3830
- targetProvider = policy.provider ?? inheritedProvider;
3831
- targetModel = policy.model;
3832
- }
3833
- else if (roleId && policy?.modelPolicy === 'per-role') {
3834
- targetProvider = role?.provider ?? inheritedProvider;
3835
- targetModel = role?.model ?? (targetProvider === inheritedProvider ? inheritedModel : undefined);
3836
- }
3837
- if (current.overrideAllNodes && nodeOverride === undefined) {
3838
- targetProvider = current.provider;
3839
- targetModel = current.model;
3840
- }
3832
+ const targetProvider = target.provider, targetModel = target.model;
3841
3833
  const effectiveModel = targetModel ?? current.config.providers.find(item => item.id === targetProvider)?.model;
3842
3834
  if (targetProvider === fallbackProvider && effectiveModel === fallbackModel)
3843
3835
  return undefined;
@@ -4730,9 +4722,56 @@ export class AppServer {
4730
4722
  const info = await stat(join(directory, 'graphs', graph.id, 'latest.json')).catch(() => undefined);
4731
4723
  graphs.push({ id: graph.id, name: graph.name, revision: graph.revision, preset: false, ...(info ? { updatedAt: info.mtime.toISOString() } : {}) });
4732
4724
  }
4733
- const configured = configuredGraphSelection(await loadConfig(this.directory), subject);
4725
+ const config = await loadConfig(this.directory);
4726
+ const configured = configuredGraphSelection(config, subject);
4734
4727
  const selected = saved.some(graph => graph.id === configured && isDeletedGraph(graph)) ? 'default' : configured;
4735
- return { graphs, selected, paid: membership.paid === true, ...(subject === undefined ? {} : { subject }) };
4728
+ return { graphs, selected, paid: membership.paid === true, ...(subject === undefined ? {} : { subject, visibility: graphVisibilityFor(config, subject) }) };
4729
+ }
4730
+ /** The caller names the account it read; a change made for an account that is no longer signed in is refused. */
4731
+ async visibilitySubject(params) {
4732
+ const subject = await currentGraphSubject();
4733
+ if (subject === undefined)
4734
+ throw new AppServerError('invalid-params', 'Sign in to Andorra Code to choose where a graph is listed.');
4735
+ if (params.subject !== subject)
4736
+ throw new AppServerError('busy', 'The account changed while project visibility was being saved. Choose it again.');
4737
+ return subject;
4738
+ }
4739
+ visibilityPaths(value, name) {
4740
+ if (!Array.isArray(value) || value.some(path => typeof path !== 'string' || !path || path.length > 4096 || path.includes('\0'))) {
4741
+ throw new AppServerError('invalid-params', `${name} must be a list of project paths`);
4742
+ }
4743
+ return value;
4744
+ }
4745
+ async setGraphVisibilityMethod(params) {
4746
+ const graphId = identifier(params.graphId, 'graphId');
4747
+ if (graphId === 'default')
4748
+ throw new AppServerError('invalid-params', 'The bundled Default graph is always listed in every project.');
4749
+ const projects = params.projects === null ? undefined : this.visibilityPaths(params.projects, 'projects');
4750
+ const subject = await this.visibilitySubject(params);
4751
+ try {
4752
+ return { subject, visibility: await setGraphVisibility(this.directory, subject, graphId, projects) };
4753
+ }
4754
+ catch (error) {
4755
+ throw new AppServerError('storage', message(error));
4756
+ }
4757
+ }
4758
+ async importGraphVisibilityMethod(params) {
4759
+ const raw = params.visibility;
4760
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
4761
+ throw new AppServerError('invalid-params', 'visibility must map graph ids to project paths');
4762
+ const entries = {};
4763
+ for (const [graphId, paths] of Object.entries(raw)) {
4764
+ if (!/^[\w-]{1,128}$/.test(graphId) || graphId === 'default')
4765
+ continue;
4766
+ entries[graphId] = this.visibilityPaths(paths, `visibility.${graphId}`);
4767
+ }
4768
+ const subject = await this.visibilitySubject(params);
4769
+ try {
4770
+ return { subject, visibility: await importGraphVisibility(this.directory, subject, entries) };
4771
+ }
4772
+ catch (error) {
4773
+ throw new AppServerError('storage', message(error));
4774
+ }
4736
4775
  }
4737
4776
  async exportAgent(params) {
4738
4777
  const id = identifier(params.id, 'id');
@@ -5445,7 +5484,10 @@ export class AppServer {
5445
5484
  .catch((error) => { throw new AppServerError('storage', message(error)); });
5446
5485
  const fromKey = workspacePermissionKey(from);
5447
5486
  const toKey = workspacePermissionKey(to);
5448
- await changeConfigFile(this.directory, config => {
5487
+ let visibilityMoved = false;
5488
+ await changeConfigFile(this.directory, current => {
5489
+ const config = relinkGraphVisibility(current, from, to, merged);
5490
+ visibilityMoved = config !== current;
5449
5491
  // A merged-away project takes its permission mode and per-project extension overrides with it: the surviving
5450
5492
  // folder keeps whatever it had. Only a rename carries them across, because there the destination is the same
5451
5493
  // project in a new place.
@@ -5457,6 +5499,8 @@ export class AppServer {
5457
5499
  }
5458
5500
  return rekeyProjectExtensions(config, fromKey, toKey, merged);
5459
5501
  }).catch((error) => { throw new AppServerError('storage', message(error)); });
5502
+ if (visibilityMoved)
5503
+ announceGraphVisibilityChange();
5460
5504
  if (merged) {
5461
5505
  const { removeProjectEntry, rememberProjectIdentity } = await import('./remote/pairing.js');
5462
5506
  await removeProjectEntry(from, this.directory)
@@ -6055,6 +6099,7 @@ export class AppServer {
6055
6099
  await this.anthropicAuth.close().catch(() => { });
6056
6100
  await this.claudeSignIn.close().catch(() => { });
6057
6101
  await this.grokSignIn.close().catch(() => { });
6102
+ await this.googleSignIn.close().catch(() => { });
6058
6103
  await this.openCodeSignIn.close().catch(() => { });
6059
6104
  await sharedOpenCodeServer().close().catch(() => { });
6060
6105
  if (this.automationCheck)
@@ -6091,6 +6136,7 @@ export class AppServer {
6091
6136
  await this.telemetrySettle;
6092
6137
  await drainTelemetry({ home: this.directory, surface: configuredSurface('desktop') });
6093
6138
  this.emitsStopped = true;
6139
+ this.stopGraphVisibilityWatch();
6094
6140
  this.terminals.shutdown();
6095
6141
  await Promise.race([
6096
6142
  this.browserViews.close(),
@@ -146,12 +146,12 @@ export class AuthManager {
146
146
  try {
147
147
  return await this.fetch(`${this.config.domain}${path}`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body, redirect: 'error', signal: signal ? AbortSignal.any([signal, deadline]) : deadline });
148
148
  }
149
- catch {
149
+ catch (error) {
150
150
  if (signal?.aborted)
151
151
  throw new AuthError('cancelled', 'Authentication cancelled.');
152
152
  if (deadline.aborted)
153
- throw new AuthError('network', 'The account service did not respond in time. Retry shortly.');
154
- throw new AuthError('network', 'The account service is unavailable. Retry shortly.');
153
+ throw new AuthError('network', 'The account service did not respond in time. Retry shortly.', { cause: error });
154
+ throw new AuthError('network', 'The account service is unavailable. Retry shortly.', { cause: error });
155
155
  }
156
156
  }
157
157
  async tokenResponse(body, signal) {
@@ -159,7 +159,7 @@ export class AuthManager {
159
159
  if (!response.ok) {
160
160
  if (response.status !== 400 && response.status !== 401) {
161
161
  await response.body?.cancel().catch(() => { });
162
- throw new AuthError('network', 'The account service is unavailable. Retry shortly.');
162
+ throw new AuthError('network', 'The account service is unavailable. Retry shortly.', { cause: Object.assign(new Error(`HTTP ${response.status}`), { code: `HTTP_${response.status}` }) });
163
163
  }
164
164
  let refusal;
165
165
  try {
@@ -31,6 +31,7 @@ export interface BrowserSession extends SavedSession {
31
31
  export declare function validBrowserSession(value: unknown): value is BrowserSession;
32
32
  export declare function browserReply(res: ServerResponse, status: number, value: unknown): void;
33
33
  export declare function browserBody(req: IncomingMessage): Promise<Record<string, unknown>>;
34
+ export declare function browserBearerMatches(req: IncomingMessage, token: string): boolean;
34
35
  export declare function browserAuthorized(req: IncomingMessage, token: string, origin: string): boolean;
35
36
  export interface BrowserBridgeActions {
36
37
  prompt(text: string): void | Promise<void>;
@@ -35,10 +35,13 @@ export async function browserBody(req) {
35
35
  throw new Error('Expected a JSON object');
36
36
  return value;
37
37
  }
38
- export function browserAuthorized(req, token, origin) {
38
+ export function browserBearerMatches(req, token) {
39
39
  const supplied = Buffer.from(req.headers.authorization || '');
40
40
  const expected = Buffer.from(`Bearer ${token}`);
41
- return req.headers.host === new URL(origin).host && (!req.headers.origin || req.headers.origin === origin) && supplied.length === expected.length && timingSafeEqual(supplied, expected);
41
+ return supplied.length === expected.length && timingSafeEqual(supplied, expected);
42
+ }
43
+ export function browserAuthorized(req, token, origin) {
44
+ return req.headers.host === new URL(origin).host && (!req.headers.origin || req.headers.origin === origin) && browserBearerMatches(req, token);
42
45
  }
43
46
  export async function createBrowserBridge(directory, snapshot, actions, cancellation) {
44
47
  const token = randomBytes(32).toString('hex');
@@ -0,0 +1,27 @@
1
+ /**
2
+ * A page that navigates to an app link (slack://, zoommtg://, ms-teams:// …) makes
3
+ * a headed Chromium raise its "Open <app>?" prompt. The prompt is part of the
4
+ * browser window, not the page, so the panel's screencast never shows it, and
5
+ * while it is up Chromium drops every click and key sent to that tab. The panel
6
+ * runs its window offscreen, so the tab looks frozen for no visible reason.
7
+ *
8
+ * Two layers deal with it. The guard below runs in every frame and cancels the
9
+ * navigations it can see (location changes, link clicks, window.open), so no
10
+ * prompt appears. Chromium offers no way to cancel the rest (an iframe whose src
11
+ * is an app link, a server redirect, a form post), so the panel watches for the
12
+ * request instead and tells the user and the agent how to clear the prompt.
13
+ */
14
+ /** The scheme of a URL that would be handed to another application, lower-cased and without the colon. */
15
+ export declare function externalAppScheme(url: unknown): string | undefined;
16
+ /**
17
+ * Runs in the page, in every frame, before the page's own scripts. It only adds a
18
+ * listener to the Navigation API; nothing on the page is patched or replaced.
19
+ */
20
+ export declare const EXTERNAL_APP_GUARD_SCRIPT: string;
21
+ export declare function guardExternalApps(context: any): Promise<void>;
22
+ export interface ExternalAppPrompt {
23
+ scheme: string;
24
+ at: number;
25
+ }
26
+ /** What the agent is told while a tab may be sitting behind the prompt. */
27
+ export declare function externalAppPromptNote(prompt: ExternalAppPrompt): string;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * A page that navigates to an app link (slack://, zoommtg://, ms-teams:// …) makes
3
+ * a headed Chromium raise its "Open <app>?" prompt. The prompt is part of the
4
+ * browser window, not the page, so the panel's screencast never shows it, and
5
+ * while it is up Chromium drops every click and key sent to that tab. The panel
6
+ * runs its window offscreen, so the tab looks frozen for no visible reason.
7
+ *
8
+ * Two layers deal with it. The guard below runs in every frame and cancels the
9
+ * navigations it can see (location changes, link clicks, window.open), so no
10
+ * prompt appears. Chromium offers no way to cancel the rest (an iframe whose src
11
+ * is an app link, a server redirect, a form post), so the panel watches for the
12
+ * request instead and tells the user and the agent how to clear the prompt.
13
+ */
14
+ /**
15
+ * Schemes the browser handles itself or opens without asking. mailto/news/snews
16
+ * are on Chromium's own never-prompt list, so they cannot freeze a tab.
17
+ */
18
+ const HANDLED_SCHEMES = [
19
+ 'http', 'https', 'ws', 'wss', 'about', 'blob', 'data', 'javascript', 'file', 'filesystem',
20
+ 'chrome', 'chrome-extension', 'chrome-untrusted', 'chrome-error', 'devtools', 'view-source',
21
+ 'mailto', 'news', 'snews',
22
+ ];
23
+ const HANDLED = new Set(HANDLED_SCHEMES);
24
+ /** The scheme of a URL that would be handed to another application, lower-cased and without the colon. */
25
+ export function externalAppScheme(url) {
26
+ if (typeof url !== 'string')
27
+ return undefined;
28
+ const match = /^\s*([a-z][a-z0-9+.-]*):/i.exec(url);
29
+ if (!match)
30
+ return undefined;
31
+ const scheme = match[1].toLowerCase();
32
+ // A one-letter scheme is a Windows drive path, which Chromium refuses outright.
33
+ return scheme.length < 2 || HANDLED.has(scheme) ? undefined : scheme.slice(0, 64);
34
+ }
35
+ /**
36
+ * Runs in the page, in every frame, before the page's own scripts. It only adds a
37
+ * listener to the Navigation API; nothing on the page is patched or replaced.
38
+ */
39
+ export const EXTERNAL_APP_GUARD_SCRIPT = `(() => {
40
+ try {
41
+ const nav = globalThis.navigation;
42
+ if (!nav || typeof nav.addEventListener !== 'function') return;
43
+ const handled = new Set(${JSON.stringify(HANDLED_SCHEMES)});
44
+ nav.addEventListener('navigate', event => {
45
+ try {
46
+ const match = /^\\s*([a-z][a-z0-9+.-]*):/i.exec(String(event.destination && event.destination.url));
47
+ if (!match) return;
48
+ const scheme = match[1].toLowerCase();
49
+ if (scheme.length > 1 && !handled.has(scheme) && event.cancelable) event.preventDefault();
50
+ } catch { /* A hostile page must not break the browser. */ }
51
+ });
52
+ } catch { /* The Navigation API is missing; the panel still reports the prompt. */ }
53
+ })()`;
54
+ export async function guardExternalApps(context) {
55
+ await Promise.resolve().then(() => context?.addInitScript?.(EXTERNAL_APP_GUARD_SCRIPT)).catch(() => { });
56
+ }
57
+ /** What the agent is told while a tab may be sitting behind the prompt. */
58
+ export function externalAppPromptNote(prompt) {
59
+ return `This tab asked to open a desktop app (${prompt.scheme}://). The browser may be showing an "Open app?" prompt that screenshots and snapshots cannot see; while it is up the tab ignores clicks and keys, and reloading does not clear it. Do not keep retrying. Ask the user to click "Show the browser window" in the Browser panel and press Cancel on the prompt, or close this tab and open the page in a new one.`;
60
+ }
@@ -13,6 +13,12 @@ export interface PanelArguments {
13
13
  deltaY?: number;
14
14
  }
15
15
  export declare function validatePanelArguments(args: Record<string, unknown>): PanelArguments;
16
+ /**
17
+ * Runs the operation, then says so when the tab may be sitting behind the
18
+ * browser's "Open app?" prompt. A snapshot or screenshot of such a tab looks
19
+ * normal and clicks on it appear to succeed, so without the warning the agent
20
+ * retries the same click with nothing to tell it why the page does not react.
21
+ */
16
22
  export declare function runPanelOperation(views: BrowserViewManager, sessionId: string, args: PanelArguments, signal: AbortSignal): Promise<{
17
23
  result: string;
18
24
  image?: ToolImage;
@@ -78,7 +78,43 @@ export function validatePanelArguments(args) {
78
78
  ...(args.deltaY === undefined ? {} : { deltaY: args.deltaY }),
79
79
  };
80
80
  }
81
+ /**
82
+ * Runs the operation, then says so when the tab may be sitting behind the
83
+ * browser's "Open app?" prompt. A snapshot or screenshot of such a tab looks
84
+ * normal and clicks on it appear to succeed, so without the warning the agent
85
+ * retries the same click with nothing to tell it why the page does not react.
86
+ */
81
87
  export async function runPanelOperation(views, sessionId, args, signal) {
88
+ const warning = () => {
89
+ try {
90
+ return views.appPromptNote?.(sessionId, args.tabId);
91
+ }
92
+ catch {
93
+ return undefined;
94
+ }
95
+ };
96
+ let answer;
97
+ try {
98
+ answer = await performPanelOperation(views, sessionId, args, signal);
99
+ }
100
+ catch (error) {
101
+ const note = signal.aborted ? undefined : warning();
102
+ if (note && error instanceof Error)
103
+ throw new Error(`${error.message} ${note}`, { cause: error });
104
+ throw error;
105
+ }
106
+ const note = warning();
107
+ if (!note)
108
+ return answer;
109
+ try {
110
+ const data = JSON.parse(answer.result);
111
+ if (data && typeof data === 'object' && !Array.isArray(data))
112
+ return { ...answer, result: JSON.stringify({ ...data, warning: note }) };
113
+ }
114
+ catch { /* A result that is not JSON is returned as it is. */ }
115
+ return answer;
116
+ }
117
+ async function performPanelOperation(views, sessionId, args, signal) {
82
118
  const { operation, url, tabId, selector } = args;
83
119
  if (operation === 'tabs')
84
120
  return { result: panelTabsResult(views, sessionId) };
@@ -22,4 +22,9 @@ export declare function startBrowserServer(options?: BrowserServerOptions): Prom
22
22
  url: string;
23
23
  close(): Promise<void>;
24
24
  }>;
25
+ export declare function loopbackRequestOrigin(host: string | undefined): string | undefined;
26
+ export declare function browserLaunch(url: string, environment?: NodeJS.ProcessEnv): {
27
+ text: string;
28
+ open: boolean;
29
+ };
25
30
  export declare function openBrowserUrl(url: string): void;
@@ -9,7 +9,7 @@ import { join, resolve } from 'node:path';
9
9
  import { configDirectory, loadConfig } from './config.js';
10
10
  import { SessionWriteFence, SessionStore, sessionName, writeSessionSnapshot, removeSessionSnapshot, savedSessionFields, carryRailOwnedFields, primaryDigest, projectIdentity, validSavedSession } from './sessions.js';
11
11
  import { acquireSessionMutationLock, SessionMutationLockHeldError, sessionHasOpenRun } from './run-records.js';
12
- import { createBrowserBridge, validBrowserSession, browserAuthorized, browserBody, browserReply, discoverBrowserSessions, assertBrowserSessionUnowned } from './browser-bridge.js';
12
+ import { createBrowserBridge, validBrowserSession, browserBearerMatches, browserBody, browserReply, discoverBrowserSessions, assertBrowserSessionUnowned } from './browser-bridge.js';
13
13
  import { readSessionTrajectory } from './app-server/workspace.js';
14
14
  import { runBrowserTask } from './browser-runner.js';
15
15
  import { configuredSurface, reportSessionStarted } from './telemetry/surface.js';
@@ -659,7 +659,8 @@ export async function startBrowserServer(options = {}) {
659
659
  const server = createServer(async (req, res) => {
660
660
  try {
661
661
  const path = new URL(req.url || '/', origin).pathname;
662
- if (!req.headers.host || req.headers.host !== new URL(origin).host || req.headers.origin && req.headers.origin !== origin) {
662
+ const requestOrigin = loopbackRequestOrigin(req.headers.host);
663
+ if (!requestOrigin || req.headers.origin && req.headers.origin !== requestOrigin) {
663
664
  browserReply(res, 403, { error: 'Invalid origin' });
664
665
  return;
665
666
  }
@@ -674,7 +675,7 @@ export async function startBrowserServer(options = {}) {
674
675
  res.end(content);
675
676
  return;
676
677
  }
677
- if (!browserAuthorized(req, token, origin)) {
678
+ if (!browserBearerMatches(req, token)) {
678
679
  browserReply(res, 401, { error: 'Reopen using /browser.' });
679
680
  return;
680
681
  }
@@ -987,6 +988,29 @@ export async function startBrowserServer(options = {}) {
987
988
  throw failure.reason;
988
989
  } };
989
990
  }
991
+ // The origin a request addressed, when its Host header names this machine's loopback interface.
992
+ // A forwarded port (ssh -L, an editor's port forwarding) arrives as localhost or under another
993
+ // port, so neither the spelling nor the port is compared with the bound address. Refusing every
994
+ // other name is what stops DNS rebinding: a page on a hostile name that resolves here still sends
995
+ // its own name as Host.
996
+ export function loopbackRequestOrigin(host) {
997
+ if (!host || !/^(?:127\.0\.0\.1|localhost|\[::1\])(?::\d{1,5})?$/i.test(host))
998
+ return undefined;
999
+ return `http://${host.toLowerCase()}`;
1000
+ }
1001
+ // What /browser prints, and whether to launch a browser on this machine. Over SSH a browser
1002
+ // opened here is on the wrong computer, so the text explains how to reach the server instead.
1003
+ export function browserLaunch(url, environment = process.env) {
1004
+ if (!(environment.SSH_CONNECTION || environment.SSH_CLIENT || environment.SSH_TTY))
1005
+ return { text: `Andorra Browser: ${url}`, open: true };
1006
+ const port = new URL(url).port;
1007
+ return { open: false, text: [
1008
+ `Andorra Browser: ${url}`,
1009
+ 'This is an SSH session, so no browser was opened on this machine. The server listens only on this machine, so forward its port from your own computer, then open the address above there:',
1010
+ ` ssh -N -L ${port}:127.0.0.1:${port} <this host>`,
1011
+ 'The same address works with localhost in place of 127.0.0.1, and with a different local port if you forward to one.',
1012
+ ].join('\n') };
1013
+ }
990
1014
  export function openBrowserUrl(url) {
991
1015
  const command = process.platform === 'win32' ? 'rundll32.exe' : process.platform === 'darwin' ? 'open' : 'xdg-open';
992
1016
  execFile(command, process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url], { windowsHide: true, timeout: 10000 }, error => { if (error)
@@ -1,3 +1,4 @@
1
+ import { type ExternalAppPrompt } from './browser-external-app.js';
1
2
  import type { ImportedCookie } from './firefox-cookies.js';
2
3
  import type { ExtensionStatus } from './browser-extensions.js';
3
4
  export type BrowserViewChannel = 'chromium' | 'msedge' | 'chrome';
@@ -12,6 +13,7 @@ export interface BrowserViewTab {
12
13
  url: string;
13
14
  title: string;
14
15
  loading: boolean;
16
+ appPrompt?: ExternalAppPrompt;
15
17
  }
16
18
  export declare const VIEW_TAB_LIMIT = 6;
17
19
  export declare const VIEW_SESSION_LIMIT = 4;
@@ -161,6 +163,20 @@ export declare class BrowserViewManager {
161
163
  private browserCdpFor;
162
164
  showWindow(sessionId: string): Promise<void>;
163
165
  hideWindow(sessionId: string): Promise<void>;
166
+ /**
167
+ * Whether the native window holding this tab is on the user's screen right now.
168
+ * Sessions of one project share a window, so one session can hide what another
169
+ * showed; the window's own bounds are the only record that stays true.
170
+ */
171
+ private windowOnScreen;
172
+ /**
173
+ * An app link got past the in-page guard. With the window on screen the user can
174
+ * see the browser's prompt; otherwise the tab is flagged so the panel and the
175
+ * agent are told why it stopped responding.
176
+ */
177
+ private flagAppPrompt;
178
+ /** What to tell the agent when a tab may be stuck behind the browser's "Open app?" prompt. */
179
+ appPromptNote(sessionId: string, tabId?: string): string | undefined;
164
180
  private moveWindow;
165
181
  restartForExtensions(force?: boolean): Promise<{
166
182
  restarted: number;