@andorra-labs/code 0.1.8 → 0.1.9

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 (129) hide show
  1. package/THIRD_PARTY_NOTICES.md +2 -1
  2. package/dist/src/account-presentation.d.ts +11 -0
  3. package/dist/src/account-presentation.js +29 -2
  4. package/dist/src/agent-execution.js +37 -4
  5. package/dist/src/agent-mcp.d.ts +12 -0
  6. package/dist/src/agent-mcp.js +81 -2
  7. package/dist/src/app-server/protocol.d.ts +12 -0
  8. package/dist/src/app-server/reasoning.d.ts +0 -8
  9. package/dist/src/app-server/reasoning.js +15 -28
  10. package/dist/src/app-server.d.ts +7 -0
  11. package/dist/src/app-server.js +59 -11
  12. package/dist/src/auth/AuthManager.d.ts +15 -0
  13. package/dist/src/auth/AuthManager.js +66 -7
  14. package/dist/src/browser-runner.js +1 -2
  15. package/dist/src/browser-server.js +10 -2
  16. package/dist/src/browser-session.js +6 -2
  17. package/dist/src/browser-stealth.d.ts +29 -0
  18. package/dist/src/browser-stealth.js +166 -0
  19. package/dist/src/browser-ui/app.js +108 -13
  20. package/dist/src/browser-ui/icons/chevron-right.svg +8 -0
  21. package/dist/src/browser-ui/index.html +8 -8
  22. package/dist/src/browser-ui/style.css +199 -171
  23. package/dist/src/browser-ui/tokens.css +198 -0
  24. package/dist/src/browser-view.d.ts +57 -9
  25. package/dist/src/browser-view.js +187 -36
  26. package/dist/src/cli.js +21 -4
  27. package/dist/src/coding-tools.js +9 -5
  28. package/dist/src/command-screens.js +4 -4
  29. package/dist/src/commands.d.ts +1 -1
  30. package/dist/src/commands.js +2 -1
  31. package/dist/src/completion-gates.d.ts +35 -0
  32. package/dist/src/completion-gates.js +25 -0
  33. package/dist/src/completion.d.ts +6 -0
  34. package/dist/src/completion.js +36 -3
  35. package/dist/src/config.d.ts +1 -1
  36. package/dist/src/config.js +2 -2
  37. package/dist/src/context-budget.d.ts +11 -0
  38. package/dist/src/context-budget.js +13 -0
  39. package/dist/src/decision/DecisionEngine.d.ts +5 -1
  40. package/dist/src/decision/DecisionManager.d.ts +1 -0
  41. package/dist/src/decision/DecisionManager.js +14 -3
  42. package/dist/src/decision/FactContinuations.d.ts +6 -0
  43. package/dist/src/decision/FactContinuations.js +9 -1
  44. package/dist/src/decision/FactServiceGate.js +1 -1
  45. package/dist/src/decision/hostedSkills.d.ts +37 -0
  46. package/dist/src/decision/hostedSkills.js +64 -0
  47. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +10 -2
  48. package/dist/src/decision/providers/AndorraDecisionProvider.js +121 -10
  49. package/dist/src/default-graph.d.ts +11 -0
  50. package/dist/src/default-graph.js +20 -0
  51. package/dist/src/duration.d.ts +13 -2
  52. package/dist/src/duration.js +27 -3
  53. package/dist/src/graph-manager-chat.d.ts +302 -0
  54. package/dist/src/graph-manager-chat.js +940 -0
  55. package/dist/src/graph-runner.js +6 -0
  56. package/dist/src/graph-server.d.ts +9 -0
  57. package/dist/src/graph-server.js +167 -16
  58. package/dist/src/graph-studio-features.js +2 -2
  59. package/dist/src/graph-sync.js +5 -2
  60. package/dist/src/graph-ui/app.js +252 -71
  61. package/dist/src/graph-ui/controls.css +55 -32
  62. package/dist/src/graph-ui/controls.js +85 -9
  63. package/dist/src/graph-ui/edge-router.js +114 -13
  64. package/dist/src/graph-ui/embed.js +23 -8
  65. package/dist/src/graph-ui/index.html +3 -3
  66. package/dist/src/graph-ui/library.css +4 -10
  67. package/dist/src/graph-ui/manager-markdown.js +155 -0
  68. package/dist/src/graph-ui/manager-state.js +191 -0
  69. package/dist/src/graph-ui/manager.css +161 -0
  70. package/dist/src/graph-ui/manager.js +700 -0
  71. package/dist/src/graph-ui/studio-canvas.js +2 -0
  72. package/dist/src/graph-ui/studio.css +24 -23
  73. package/dist/src/graph-ui/studio.js +29 -8
  74. package/dist/src/graph-ui/style.css +125 -92
  75. package/dist/src/graph-ui/tokens.css +217 -151
  76. package/dist/src/graphs.d.ts +69 -1
  77. package/dist/src/graphs.js +160 -7
  78. package/dist/src/hardened-runtime.js +8 -2
  79. package/dist/src/membership-errors.d.ts +14 -0
  80. package/dist/src/membership-errors.js +24 -1
  81. package/dist/src/membership.d.ts +20 -0
  82. package/dist/src/membership.js +45 -16
  83. package/dist/src/palette.d.ts +25 -8
  84. package/dist/src/palette.js +26 -8
  85. package/dist/src/provider-engine.d.ts +4 -4
  86. package/dist/src/provider-engine.js +39 -22
  87. package/dist/src/providers.d.ts +24 -0
  88. package/dist/src/providers.js +47 -2
  89. package/dist/src/qa/guidance.d.ts +26 -0
  90. package/dist/src/qa/guidance.js +59 -0
  91. package/dist/src/qa/index.d.ts +1 -6
  92. package/dist/src/qa/index.js +1 -14
  93. package/dist/src/qa/runtime/ProcessManager.d.ts +20 -2
  94. package/dist/src/qa/runtime/ProcessManager.js +69 -13
  95. package/dist/src/react-runtime.d.ts +11 -0
  96. package/dist/src/react-runtime.js +190 -51
  97. package/dist/src/remote/engine-pool.js +4 -1
  98. package/dist/src/run-progress.d.ts +6 -0
  99. package/dist/src/run-progress.js +7 -0
  100. package/dist/src/runtime.d.ts +8 -0
  101. package/dist/src/session-skills.d.ts +75 -0
  102. package/dist/src/session-skills.js +151 -0
  103. package/dist/src/side-panel.d.ts +1 -1
  104. package/dist/src/side-panel.js +6 -12
  105. package/dist/src/skill-commands.js +1 -1
  106. package/dist/src/skills/bundled/control-browser/SKILL.md +9 -1
  107. package/dist/src/skills/bundled/graph-manager/SKILL.md +8 -0
  108. package/dist/src/skills/bundled/provenance.json +3 -3
  109. package/dist/src/skills/bundled/web-gui-tester/SKILL.md +1 -1
  110. package/dist/src/stall-recovery.d.ts +22 -0
  111. package/dist/src/stall-recovery.js +71 -0
  112. package/dist/src/subagent-run.js +1 -2
  113. package/dist/src/terminal-ui.d.ts +2 -2
  114. package/dist/src/terminal-ui.js +18 -13
  115. package/dist/src/transcript.js +9 -1
  116. package/dist/src/types.d.ts +18 -4
  117. package/dist/src/usage-analytics.d.ts +7 -0
  118. package/dist/src/usage-analytics.js +55 -15
  119. package/docs/concepts/README.md +1 -1
  120. package/docs/concepts/limits.md +9 -0
  121. package/docs/guides/desktop-app.md +1 -1
  122. package/docs/guides/graph-builder.md +16 -1
  123. package/docs/reference/slash-commands.md +2 -1
  124. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +203 -0
  125. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +79 -0
  126. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +182 -0
  127. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +156 -0
  128. package/package.json +1 -1
  129. package/tests/chat-side-panel-test-plan.md +1 -1
@@ -21,7 +21,7 @@ import { GROK_BASE_URL } from './grok-provider.js';
21
21
  import { anthropicAccountHome } from './anthropic-credentials.js';
22
22
  import { codexAccountHome } from './codex-rpc.js';
23
23
  import { configuredModelSnapshot, discoverModelMetadata, resolveModelContext } from './model-metadata.js';
24
- import { graphLeavesNodesToSession, isDeletedGraph, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
24
+ import { graphLeavesNodesToSession, graphMcpServers, isDeletedGraph, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
25
25
  import { exportAgentDefinition, readAgentDefinition } from './agent-definitions.js';
26
26
  import { blockingHealthFailures, checkGraphModelHealth, formatGraphHealthFailure, resumeModelNodes } from './graph-health.js';
27
27
  import { bindPortableGraphProviders, GraphProviderUnavailableError } from './graph-provider-portability.js';
@@ -61,10 +61,11 @@ import { readFavicon } from './favicons.js';
61
61
  import { attachmentReferenceBlock, loadResolvedImages, parsePendingAttachments, pruneAttachments, readSpooledImage, readSpooledText, resolveAttachments, attachmentReadRoots } from './attachments.js';
62
62
  import { extensionSnapshot, listBundles, installBundle, removeBundle, removeBundleTransactional, setBundleEnabled, listSkillResources, readSkillResource, writeSkillResource, resolveSkillInvocation } from './extensions.js';
63
63
  import { isBuiltinSlashCommand } from './skill-commands.js';
64
+ import { copySessionSkill, readSessionSkill, removeSessionSkill, setSessionSkillPaused, skillForRun } from './session-skills.js';
64
65
  import { connectMcpServers, mcpCatalogStore } from './mcp.js';
65
66
  import { loadWorkspaceInstructions } from './workspace-instructions.js';
66
67
  import { DAY_MS, planAutoArchive } from './session-reaper.js';
67
- import { QA_SYSTEM_GUIDANCE, disposeAllQaProcesses, disposeAllQaPtys, onBackgroundChange } from './qa/index.js';
68
+ import { disposeAllQaProcesses, disposeAllQaPtys, onBackgroundChange } from './qa/index.js';
68
69
  import { BackgroundTasks } from './background-tasks.js';
69
70
  import { disposePooledPowerShell } from './powershell-pool.js';
70
71
  import { TodoStore } from './todos.js';
@@ -1377,6 +1378,8 @@ export class AppServer {
1377
1378
  case 'sessions.pullRequest.dismiss':
1378
1379
  await this.dismissPullRequest(identifier(params.id, 'id'));
1379
1380
  return {};
1381
+ case 'sessions.skill.get': return { skill: (await readSessionSkill(this.directory, identifier(params.id, 'id'))) ?? null };
1382
+ case 'sessions.skill.update': return { skill: (await this.updateSessionSkill(identifier(params.id, 'id'), params)) ?? null };
1380
1383
  case 'timers.list': return this.listTimers();
1381
1384
  case 'run.start': return this.startRun(params);
1382
1385
  case 'workspace.warm': return this.warmWorkspace(params);
@@ -1471,7 +1474,7 @@ export class AppServer {
1471
1474
  if (params.mode !== undefined && params.mode !== 'desktop' && params.mode !== 'mobile')
1472
1475
  throw new AppServerError('invalid-params', 'mode must be desktop or mobile');
1473
1476
  await this.browserViews.configureStream(sessionId, {
1474
- enabled: params.enabled, viewportWidth: params.viewportWidth, viewportHeight: params.viewportHeight, quality: params.quality, mode: params.mode,
1477
+ enabled: params.enabled, viewportWidth: params.viewportWidth, viewportHeight: params.viewportHeight, quality: params.quality, mode: params.mode, scale: params.scale,
1475
1478
  });
1476
1479
  return { ok: true };
1477
1480
  }
@@ -2460,6 +2463,11 @@ export class AppServer {
2460
2463
  ...(access.dailyDecisionLimit === undefined ? {} : { dailyDecisionLimit: access.dailyDecisionLimit }),
2461
2464
  ...(access.dailyDecisionUsed === undefined ? {} : { dailyDecisionUsed: access.dailyDecisionUsed }),
2462
2465
  ...(access.decisionsSinceRollout === undefined ? {} : { decisionsSinceRollout: access.decisionsSinceRollout }),
2466
+ ...(access.fairUse === undefined ? {} : { fairUse: access.fairUse }),
2467
+ ...(access.windowDays === undefined ? {} : { windowDays: access.windowDays }),
2468
+ ...(access.windowDecisionLimit === undefined ? {} : { windowDecisionLimit: access.windowDecisionLimit }),
2469
+ ...(access.windowDecisionUsed === undefined ? {} : { windowDecisionUsed: access.windowDecisionUsed }),
2470
+ ...(access.windowDecisionResetsAt === undefined ? {} : { windowDecisionResetsAt: access.windowDecisionResetsAt }),
2463
2471
  ...(access.billingUrl === undefined ? {} : { billingUrl: access.billingUrl }),
2464
2472
  };
2465
2473
  return { account };
@@ -2816,6 +2824,7 @@ export class AppServer {
2816
2824
  await this.browserViews.release(id, 'That session was deleted.');
2817
2825
  // Its pull request stops being watched with it: an Auto-fix wake has no conversation left to land in.
2818
2826
  await removePullRequest(this.directory, id).catch(() => { });
2827
+ await removeSessionSkill(this.directory, id).catch(() => { });
2819
2828
  this.emit('session.removed', { id });
2820
2829
  return { removed: true };
2821
2830
  });
@@ -3459,6 +3468,8 @@ export class AppServer {
3459
3468
  record = { ...forked, id: randomUUID(), parentId: existing.id,
3460
3469
  ancestors: lineageThrough(existing.ancestors, existing.id), inheritedUsage: { ...existing.usage },
3461
3470
  inheritedTurns: existing.history.length, lineage: lineagePoints(existing, existing.usage, existing.history.length) };
3471
+ // The fork continues the parent's conversation, so it keeps following the skill the parent was.
3472
+ await copySessionSkill(this.directory, existing.id, record.id).catch(error => this.log('warn', `Could not carry the session's active skill to its continuation: ${message(error)}`));
3462
3473
  }
3463
3474
  record = { ...record, workspace: root, projectId: record.projectId ?? projectIdentity(root), updatedAt: new Date().toISOString() };
3464
3475
  const controller = new AbortController();
@@ -4240,7 +4251,13 @@ export class AppServer {
4240
4251
  // dispatched, so the naming request waits for a signal this run publishes.
4241
4252
  if (params.sessionId === undefined)
4242
4253
  this.titleSessionFromPrompt(record, task, provider, modelId, runId);
4243
- const runTask = this.executeRun({ runId, startedAt, telemetryRunId, ...(accountSubject ? { accountSubject } : {}), task, selection, providerId: provider.id, modelId, root, permissions: effective, liveSteers, ...(internal?.inheritedPermissions === undefined ? {} : { boundPermissions: internal.inheritedPermissions }), ...(effort === undefined ? {} : { reasoningEffort: effort }), ...(overrideAllNodes ? { overrideAllNodes: true } : {}), ...(modelPinned ? { modelPinned: true } : {}), ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }), ...(panelRelay ? { panelBrowserRelay: true } : {}), ...(entryHistory ? { entryHistory: true } : {}), ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(automationContext === undefined ? {} : { automationContext }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(wake === undefined ? {} : { wake }), ...(directionNode === undefined ? {} : { directionNode }), ...(armedCarried.length === 0 ? {} : { carriedDirections: armedCarried, pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }), ...wakeProvenance(entry.wake, entry.node) })) }), ownDirectionId: `${runId}#own`, ...(seedExclusions.length === 0 ? {} : { armedRunIds: seedExclusions }), ...(openingAttachments === undefined ? {} : { openingAttachments }), record, controller, ...(attachments === undefined ? {} : { attachments }), ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }), ...(resumeFrom === undefined ? {} : { resumeFrom }), lineage, ...(lineageArtifacts === undefined ? {} : { lineageArtifacts }), ...(resumedGraph === undefined ? {} : { prepared: resumedGraph }) })
4254
+ // The text that may invoke a skill is a message the user just sent: a new run's task, or the
4255
+ // direction sent with a resume. A resume otherwise replays the stopped attempt's own task, or
4256
+ // recovers its own direction, or delivers a wake — none of which is a new invocation, and reading
4257
+ // one as such would rewrite the session's skill and undo a pause or removal made since the stop.
4258
+ const invocationText = internal?.resumedFrom === undefined ? task
4259
+ : internal.recoveredDirection === true || internal.wake !== undefined ? undefined : internal.direction;
4260
+ const runTask = this.executeRun({ runId, startedAt, telemetryRunId, ...(accountSubject ? { accountSubject } : {}), ...(invocationText === undefined ? {} : { invocationText }), task, selection, providerId: provider.id, modelId, root, permissions: effective, liveSteers, ...(internal?.inheritedPermissions === undefined ? {} : { boundPermissions: internal.inheritedPermissions }), ...(effort === undefined ? {} : { reasoningEffort: effort }), ...(overrideAllNodes ? { overrideAllNodes: true } : {}), ...(modelPinned ? { modelPinned: true } : {}), ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }), ...(panelRelay ? { panelBrowserRelay: true } : {}), ...(entryHistory ? { entryHistory: true } : {}), ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(automationContext === undefined ? {} : { automationContext }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(wake === undefined ? {} : { wake }), ...(directionNode === undefined ? {} : { directionNode }), ...(armedCarried.length === 0 ? {} : { carriedDirections: armedCarried, pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }), ...wakeProvenance(entry.wake, entry.node) })) }), ownDirectionId: `${runId}#own`, ...(seedExclusions.length === 0 ? {} : { armedRunIds: seedExclusions }), ...(openingAttachments === undefined ? {} : { openingAttachments }), record, controller, ...(attachments === undefined ? {} : { attachments }), ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }), ...(resumeFrom === undefined ? {} : { resumeFrom }), lineage, ...(lineageArtifacts === undefined ? {} : { lineageArtifacts }), ...(resumedGraph === undefined ? {} : { prepared: resumedGraph }) })
4244
4261
  .catch(error => this.log('error', `Run ${runId} failed: ${message(error)}`));
4245
4262
  // The finally sits outside the awaited chain so the settle can name the exact promise this
4246
4263
  // attempt owns: the finalizer now releases the live-run slot before the terminal events, so a
@@ -4787,11 +4804,19 @@ export class AppServer {
4787
4804
  // may have a different window.
4788
4805
  contextWindow = snapshot.contextWindow;
4789
4806
  this.emit('run.context', { runId, provider: provider.id, model: snapshot.model, ...(snapshot.contextWindow === undefined ? {} : { contextWindow: snapshot.contextWindow }), ...(snapshot.reasoningEffort === undefined ? {} : { reasoningEffort: snapshot.reasoningEffort }) });
4790
- const invocationInput = direction ?? task;
4807
+ const invocationInput = input.invocationText;
4791
4808
  bootMark('run.exec.model-context.resolved');
4792
- const invocation = isBuiltinSlashCommand(invocationInput) ? undefined : await resolveSkillInvocation(invocationInput, config, signal, this.directory);
4809
+ const invocation = invocationInput === undefined || isBuiltinSlashCommand(invocationInput) ? undefined : await resolveSkillInvocation(invocationInput, config, signal, this.directory);
4810
+ // A slash invocation becomes the session's skill, and a later message without one inherits it
4811
+ // (see `src/session-skills.ts`): the skill's requirements apply to the whole conversation, not
4812
+ // only to the message that named it.
4813
+ const runSkill = await skillForRun({ invocation, home: this.directory, sessionId: input.record.id, config, signal });
4814
+ if (runSkill.recorded)
4815
+ this.emitSessionSkill(input.record.id, runSkill.recorded);
4816
+ if (runSkill.notice)
4817
+ this.emit('log', { level: 'warn', message: runSkill.notice });
4793
4818
  bootMark('run.exec.skill-invocation.resolved');
4794
- const extension = await extensionSnapshot(config, signal, this.directory, invocation?.id);
4819
+ const extension = await extensionSnapshot(config, signal, this.directory, runSkill.skill?.id);
4795
4820
  for (const notice of extension.notices)
4796
4821
  this.emit('log', { level: 'info', message: notice });
4797
4822
  bootMark('run.exec.extensions.loaded');
@@ -4872,8 +4897,9 @@ export class AppServer {
4872
4897
  // process starts beside the first model request rather than in front of it: starting a stdio
4873
4898
  // server and listing its tools is seconds of work the first node does not need the result of
4874
4899
  // until a model calls one of those tools, and that call waits for the connection.
4875
- const connecting = Object.keys(extension.servers).length
4876
- ? connectMcpServers(extension.servers, { ...toolContext, signal: setupSignal, userSignal: setupSignal }, detail => this.emit('log', { level: 'info', message: detail }), setupSignal, { catalogs: mcpCatalogStore(this.directory) })
4900
+ const servers = graphMcpServers(graph.id, extension.servers);
4901
+ const connecting = Object.keys(servers).length
4902
+ ? connectMcpServers(servers, { ...toolContext, signal: setupSignal, userSignal: setupSignal }, detail => this.emit('log', { level: 'info', message: detail }), setupSignal, { catalogs: mcpCatalogStore(this.directory) })
4877
4903
  : Promise.resolve(undefined);
4878
4904
  try {
4879
4905
  mcp = await Promise.race([connecting, healthGate.then(() => connecting)]);
@@ -4913,8 +4939,8 @@ export class AppServer {
4913
4939
  // CLI builds its toolset without an app-server and never sees it.
4914
4940
  tools: [...createTools(), createBrowserPanelTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined),
4915
4941
  createBrowserIncognitoTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined), ...extension.tools, ...(mcp?.tools ?? [])], installedSkillClaims: extension.claimsSkillName, history: contextSeed,
4916
- ...(invocation ? { inheritedSkills: [invocation.id], skillInvocationInstruction: invocation.task } : {}),
4917
- instructions: `${await loadWorkspaceInstructions(root, signal, config.systemPromptOverride)}\n${QA_SYSTEM_GUIDANCE}${extension.instructions}`,
4942
+ ...(runSkill.skill ? { inheritedSkills: [runSkill.skill.id], skillInvocationInstruction: runSkill.skill.instruction } : {}),
4943
+ instructions: `${await loadWorkspaceInstructions(root, signal, config.systemPromptOverride)}${extension.instructions}`,
4918
4944
  codeIntel, todoStore: new TodoStore(), ...(commandMemory ? { commandMemory } : {}),
4919
4945
  limits: resolveConfiguredLimits(config),
4920
4946
  ...hostedDecisionPolicy(membership, config.jevEnabled !== false, config.decisions),
@@ -7206,6 +7232,28 @@ export class AppServer {
7206
7232
  }
7207
7233
  return { sessions: [...owners].map(sessionId => ({ sessionId, timers: this.timersFor(sessionId) })) };
7208
7234
  }
7235
+ /** Tell every window the session's active skill changed; `null` means it has none now. */
7236
+ emitSessionSkill(sessionId, skill) {
7237
+ this.emit('session.skill.updated', { sessionId, skill });
7238
+ }
7239
+ /**
7240
+ * Pause, resume or remove the session's skill. It takes effect from the session's next message: a
7241
+ * run already working read the skill when it started.
7242
+ */
7243
+ async updateSessionSkill(sessionId, params) {
7244
+ if (params.remove === true) {
7245
+ await removeSessionSkill(this.directory, sessionId);
7246
+ this.emitSessionSkill(sessionId, null);
7247
+ return undefined;
7248
+ }
7249
+ if (typeof params.paused !== 'boolean')
7250
+ throw new AppServerError('invalid-params', 'paused must be a boolean, or remove must be true');
7251
+ const skill = await setSessionSkillPaused(this.directory, sessionId, params.paused);
7252
+ if (!skill)
7253
+ throw new AppServerError('not-found', 'This session has no active skill.');
7254
+ this.emitSessionSkill(sessionId, skill);
7255
+ return skill;
7256
+ }
7209
7257
  /** Say what a session is waiting on. An empty list is a real answer: it is what ends a wait. */
7210
7258
  emitPullRequest(sessionId, pullRequest) {
7211
7259
  this.emit('session.pullRequest.updated', { sessionId, pullRequest: pullRequestForClients(pullRequest) });
@@ -38,6 +38,12 @@ export declare class AuthManager {
38
38
  private readonly store;
39
39
  private readonly fetch;
40
40
  private readonly keys;
41
+ /**
42
+ * A rotated session this process holds but could not save, and the stored refresh token it
43
+ * replaced. The server already retired that stored token, so until a save lands this copy is the
44
+ * only live credential (see `rotate`).
45
+ */
46
+ private unsaved?;
41
47
  constructor(options: {
42
48
  config: AuthConfiguration;
43
49
  store?: CredentialStore;
@@ -98,6 +104,15 @@ export declare class AuthManager {
98
104
  * for what they *observe* (`getAccessToken` checks the signal once the exchange has landed).
99
105
  */
100
106
  private rotate;
107
+ /**
108
+ * The envelope to work from: the store's, or the rotated session this process could not save.
109
+ *
110
+ * The kept session stands in only while the store still holds the exact token it replaced, under
111
+ * the same login generation. Anything else means another process signed in, signed out or saved
112
+ * its own rotation, and the store is the newer answer. A store left unreadable by a failed save
113
+ * cannot say either way, so the kept session is used until a save repairs it.
114
+ */
115
+ private current;
101
116
  /**
102
117
  * Request one rotation, repeating a lost response once inside the server's retry grace.
103
118
  *
@@ -146,6 +146,12 @@ export class AuthManager {
146
146
  store;
147
147
  fetch;
148
148
  keys;
149
+ /**
150
+ * A rotated session this process holds but could not save, and the stored refresh token it
151
+ * replaced. The server already retired that stored token, so until a save lands this copy is the
152
+ * only live credential (see `rotate`).
153
+ */
154
+ unsaved;
149
155
  constructor(options) {
150
156
  this.options = options;
151
157
  validateAuthConfiguration(options.config);
@@ -293,7 +299,7 @@ export class AuthManager {
293
299
  const code = await receiveAuthorizationCode({ url: url.toString(), state, redirectUri: this.config.redirectUri, signal, openBrowser: this.options.openBrowser ?? openBrowser, onMessage: options.onMessage,
294
300
  readCallback: options.readCallback, onManual: extendDeadline, browserUnavailable, copyAddress: options.copyAddress,
295
301
  // A competing login must own the callback port before superseding this generation.
296
- onReady: () => this.locked(async () => { const current = await abortable(this.read(), signal); signal.throwIfAborted(); await this.store.write(JSON.stringify({ ...current, generation })); }, signal),
302
+ onReady: () => this.locked(async () => { const current = await this.current(signal); signal.throwIfAborted(); await this.store.write(JSON.stringify({ ...current, generation })); }, signal),
297
303
  });
298
304
  const tokens = await this.tokenResponse(new URLSearchParams({ grant_type: 'authorization_code', client_id: this.config.clientId, redirect_uri: this.config.redirectUri, code, code_verifier: verifier }), signal).catch((error) => {
299
305
  // A refused code is not an expired session: it expired (codes are short-lived, and a pasted
@@ -307,7 +313,7 @@ export class AuthManager {
307
313
  try {
308
314
  session = await this.session(tokens, nonce, undefined, signal);
309
315
  await this.locked(async () => {
310
- const current = await abortable(this.read(), signal);
316
+ const current = await this.current(signal);
311
317
  if (current.generation !== generation)
312
318
  throw new AuthError('superseded', 'This login was superseded by another login or logout.');
313
319
  signal.throwIfAborted();
@@ -353,7 +359,7 @@ export class AuthManager {
353
359
  const tokens = await this.locked(async () => {
354
360
  let token;
355
361
  try {
356
- token = (await abortable(this.read(), signal)).session?.refreshToken;
362
+ token = (await this.current(signal)).session?.refreshToken;
357
363
  }
358
364
  catch (error) {
359
365
  if (!(error instanceof AuthError) || error.code !== 'storage')
@@ -375,6 +381,7 @@ export class AuthManager {
375
381
  if (signal?.aborted)
376
382
  throw new AuthError('cancelled', 'Authentication cancelled.');
377
383
  await this.store.clear(JSON.stringify({ version: 1, generation: randomUUID() }));
384
+ this.unsaved = undefined;
378
385
  const own = [...new Set([token, previous].filter((value) => Boolean(value)))];
379
386
  if (!options.everywhere)
380
387
  return { own };
@@ -448,13 +455,63 @@ export class AuthManager {
448
455
  // between the token response and this write would otherwise restart on the dead token,
449
456
  // fail its next refresh, and wipe the only credential it had. Verification still runs
450
457
  // before anything is returned from this call.
458
+ //
459
+ // A save that fails here (a full disk, a locked credential store) must not lose the rotated
460
+ // token either: the store still holds the one the server just retired, and refreshing with it
461
+ // again works only inside the server's 60-second grace. After that the server refuses it and the
462
+ // session is wiped as revoked. The rotated session is kept in memory instead, used by every later
463
+ // call in this process, and saved again until a save lands (see `current`).
464
+ // The refresh token the store holds right now: what a kept session is matched against later.
465
+ let stored = this.unsaved?.replaces ?? session.refreshToken;
466
+ const persist = async (rotated) => {
467
+ try {
468
+ await this.store.write(JSON.stringify({ ...current, session: rotated }));
469
+ this.unsaved = undefined;
470
+ stored = rotated.refreshToken;
471
+ }
472
+ catch {
473
+ this.unsaved = { generation: current.generation, replaces: stored, session: rotated };
474
+ }
475
+ };
451
476
  const interim = interimSession(tokens, session);
452
477
  if (interim)
453
- await this.store.write(JSON.stringify({ ...current, session: interim }));
478
+ await persist(interim);
454
479
  const next = await this.session(tokens, session.nonce, session);
455
- await this.store.write(JSON.stringify({ ...current, session: next }));
480
+ await persist(next);
456
481
  return next;
457
482
  }
483
+ /**
484
+ * The envelope to work from: the store's, or the rotated session this process could not save.
485
+ *
486
+ * The kept session stands in only while the store still holds the exact token it replaced, under
487
+ * the same login generation. Anything else means another process signed in, signed out or saved
488
+ * its own rotation, and the store is the newer answer. A store left unreadable by a failed save
489
+ * cannot say either way, so the kept session is used until a save repairs it.
490
+ */
491
+ async current(signal) {
492
+ let stored;
493
+ try {
494
+ stored = await abortable(this.read(), signal);
495
+ }
496
+ catch (error) {
497
+ if (!this.unsaved || !(error instanceof AuthError && error.code === 'storage'))
498
+ throw error;
499
+ }
500
+ const pending = this.unsaved;
501
+ if (!pending)
502
+ return stored;
503
+ if (stored && (stored.generation !== pending.generation || stored.session?.refreshToken !== pending.replaces)) {
504
+ this.unsaved = undefined;
505
+ return stored;
506
+ }
507
+ const recovered = { version: 1, generation: pending.generation, session: pending.session };
508
+ try {
509
+ await this.store.write(JSON.stringify(recovered));
510
+ this.unsaved = undefined;
511
+ }
512
+ catch { /* Still unsaved: the next call tries again, and this one uses the live token meanwhile. */ }
513
+ return recovered;
514
+ }
458
515
  /**
459
516
  * Request one rotation, repeating a lost response once inside the server's retry grace.
460
517
  *
@@ -491,6 +548,8 @@ export class AuthManager {
491
548
  */
492
549
  async clearRejectedCredential(rejection) {
493
550
  let failure;
551
+ // The token was refused, so a rotated copy of it this process kept is no longer worth saving.
552
+ this.unsaved = undefined;
494
553
  try {
495
554
  await this.store.clear(JSON.stringify({ version: 1, generation: randomUUID() }));
496
555
  }
@@ -526,7 +585,7 @@ export class AuthManager {
526
585
  * subject against the token it is about to use.
527
586
  */
528
587
  async tokenAndSubject(signal) {
529
- const current = await abortable(this.read(), signal);
588
+ const current = await this.current(signal);
530
589
  const session = current.session;
531
590
  if (!session || session.refreshExpiresAt <= Date.now())
532
591
  throw new AuthError('login_required', 'Sign in to your Andorra account first with andorra login.');
@@ -558,6 +617,6 @@ export class AuthManager {
558
617
  return this.locked(() => this.tokenAndSubject(signal), signal);
559
618
  }
560
619
  async status(signal) {
561
- return this.locked(async () => { const session = (await abortable(this.read(), signal)).session; return session && session.refreshExpiresAt > Date.now() ? { signedIn: true, subject: session.subject, expiresAt: session.expiresAt } : { signedIn: false }; }, signal);
620
+ return this.locked(async () => { const session = (await this.current(signal)).session; return session && session.refreshExpiresAt > Date.now() ? { signedIn: true, subject: session.subject, expiresAt: session.expiresAt } : { signedIn: false }; }, signal);
562
621
  }
563
622
  }
@@ -16,7 +16,6 @@ import { refreshModelContext, resolveModelContext } from './model-metadata.js';
16
16
  import { runGraph } from './runtime.js';
17
17
  import { createTools } from './tools.js';
18
18
  import { loadWorkspaceInstructions } from './workspace-instructions.js';
19
- import { QA_SYSTEM_GUIDANCE } from './qa/index.js';
20
19
  import { extensionSnapshot } from './extensions.js';
21
20
  import { connectMcpServers } from './mcp.js';
22
21
  import { hostedDecisionPolicy } from './decision/hostedPolicy.js';
@@ -253,7 +252,7 @@ export async function runBrowserTask(session, task, control, options = {}) {
253
252
  const result = await runGraph(graph, {
254
253
  task, runId, provider: selected.id, model: refreshed.model, adapter: adapters(refreshed), contextWindow: refreshed.contextWindow,
255
254
  tools: [...createTools(), ...snapshot.tools, ...mcp.tools], history: (session.contextHistory ?? session.history).slice(-6),
256
- instructions: `${workspaceGuidance}\n${QA_SYSTEM_GUIDANCE}${snapshot.instructions}`,
255
+ instructions: `${workspaceGuidance}${snapshot.instructions}`,
257
256
  context, codeIntel, commandMemory, todoStore: new TodoStore(),
258
257
  ...hostedDecisionPolicy(membership, config.jevEnabled !== false, config.decisions), limits: resolveConfiguredLimits(config),
259
258
  getSteeringMessages: async () => control.steering().map(content => ({ role: 'user', content })),
@@ -829,8 +829,16 @@ export async function startBrowserServer(options = {}) {
829
829
  browserReply(res, 403, { error: 'Invalid origin' });
830
830
  return;
831
831
  }
832
- const assets = { '/': ['index.html', 'text/html'], '/app.js': ['app.js', 'text/javascript'], '/style.css': ['style.css', 'text/css'], '/andorra-logo.png': ['andorra-logo.png', 'image/png'] };
833
- if (req.method === 'GET' && assets[path]) {
832
+ // `/tokens.css` is the desktop client's own token file, which build-assets.mjs copies into the
833
+ // build beside this page, so the workspace and the desktop draw from one source. The page
834
+ // renders the desktop's face too: the build ships one copy of the Geist files (the graph
835
+ // editor's, under graph-ui/fonts), and they are served here from this origin, the only one the
836
+ // page's CSP admits.
837
+ const assets = { '/': ['index.html', 'text/html'], '/app.js': ['app.js', 'text/javascript'], '/style.css': ['style.css', 'text/css'], '/tokens.css': ['tokens.css', 'text/css'], '/icons/chevron-right.svg': ['icons/chevron-right.svg', 'image/svg+xml'], '/andorra-logo.png': ['andorra-logo.png', 'image/png'],
838
+ '/fonts/geist-sans-latin-400-normal.woff2': ['../graph-ui/fonts/geist-sans-latin-400-normal.woff2', 'font/woff2'],
839
+ '/fonts/geist-sans-latin-500-normal.woff2': ['../graph-ui/fonts/geist-sans-latin-500-normal.woff2', 'font/woff2'],
840
+ '/fonts/geist-mono-latin-400-normal.woff2': ['../graph-ui/fonts/geist-mono-latin-400-normal.woff2', 'font/woff2'] };
841
+ if (req.method === 'GET' && Object.hasOwn(assets, path)) {
834
842
  const [file, type] = assets[path];
835
843
  const content = await readFile(new URL(`./browser-ui/${file}`, import.meta.url));
836
844
  res.writeHead(200, { 'Content-Type': type.startsWith('text/') || type === 'text/javascript' ? `${type}; charset=utf-8` : type, 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'", 'X-Content-Type-Options': 'nosniff' });
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { setTimeout as delay } from 'node:timers/promises';
3
3
  import { observePage, observationResult } from './browser-observation.js';
4
+ import { hardenContext, stealthContextOptions, stealthLaunchArgs } from './browser-stealth.js';
4
5
  const sessions = new Map();
5
6
  export const IMAGE_LIMIT = 512 * 1024;
6
7
  export const PENDING_IMAGE_LIMIT = 10;
@@ -152,7 +153,7 @@ async function launch(signal) {
152
153
  for (const channel of [undefined, 'msedge', 'chrome']) {
153
154
  signal.throwIfAborted();
154
155
  try {
155
- const pending = chromium.launch({ headless: true, ...(channel ? { channel } : {}), timeout: 15_000 });
156
+ const pending = chromium.launch({ headless: true, args: stealthLaunchArgs(), ...(channel ? { channel } : {}), timeout: 15_000 });
156
157
  return await new Promise((resolve, reject) => {
157
158
  const abort = () => {
158
159
  signal.removeEventListener('abort', abort);
@@ -392,11 +393,14 @@ export function createBrowserSessionTool(authorize) {
392
393
  context.signal.throwIfAborted();
393
394
  // Browser.newPage owns a single-page context which rejects new tabs.
394
395
  // An explicit context keeps every tab in this isolated session profile.
395
- const pending = browser.newContext({ viewport: { width: 1280, height: 800 }, acceptDownloads: false }).then((isolated) => {
396
+ const pending = browser.newContext({ viewport: { width: 1280, height: 800 }, acceptDownloads: false, ...stealthContextOptions() }).then(async (isolated) => {
396
397
  if (closing || context.signal.aborted) {
397
398
  void Promise.resolve().then(() => isolated.close()).catch(() => { });
398
399
  throw new Error('Browser closed while creating context');
399
400
  }
401
+ // Every tab of this session is a page of this context, so the
402
+ // identity is set once here instead of per page.
403
+ await hardenContext(isolated);
400
404
  return isolated.newPage();
401
405
  });
402
406
  const page = await new Promise((resolve, reject) => {
@@ -0,0 +1,29 @@
1
+ export declare const STEALTH_LOCALE = "en-US";
2
+ export declare const STEALTH_ACCEPT_LANGUAGE = "en-US,en;q=0.9";
3
+ /** A normal desktop Chrome user agent: no HeadlessChrome, no Electron, no Playwright. */
4
+ export declare function stealthUserAgent(platform?: NodeJS.Platform): string;
5
+ /** Chromium args that switch off the blink "automated" feature: the strongest webdriver removal. */
6
+ export declare function stealthLaunchArgs(): string[];
7
+ /** Context options that give every page of a context the desktop identity. */
8
+ export declare function stealthContextOptions(platform?: NodeJS.Platform): {
9
+ userAgent: string;
10
+ locale: string;
11
+ };
12
+ /** The CDP `Emulation.setUserAgentOverride` payload for the panel's desktop mode: UA, language and platform from one profile. */
13
+ export declare function desktopUaOverride(platform?: NodeJS.Platform): {
14
+ userAgent: string;
15
+ acceptLanguage: string;
16
+ platform: string;
17
+ };
18
+ /** The init script text: the page script with one hardware config baked in. */
19
+ export declare function stealthInitScript(hardware?: {
20
+ cores?: number;
21
+ }): string;
22
+ /**
23
+ * Add the stealth init script to a browser context, once per context.
24
+ *
25
+ * Every page the context later creates runs it: tabs a session opened and
26
+ * popups the browser opened alike. A context without the API (a test fake)
27
+ * is left as it is.
28
+ */
29
+ export declare function hardenContext(context: any): Promise<void>;
@@ -0,0 +1,166 @@
1
+ import { cpus } from 'node:os';
2
+ /**
3
+ * The browser identity the integrated browsers present to websites.
4
+ *
5
+ * A Playwright-launched Chromium ships automation markers a Cloudflare-class
6
+ * challenge scores and fails: a `HeadlessChrome` user agent, `navigator.webdriver`
7
+ * true, an empty plugin list, SwiftShader WebGL. A failed score keeps the
8
+ * challenge looping no matter how often the checkbox is clicked. This module
9
+ * builds the single identity both the panel browser and the agent's isolated
10
+ * browser present, so the two cannot drift apart.
11
+ *
12
+ * Everything here agrees with one profile per platform: the user agent's OS
13
+ * token, `navigator.platform`, the CDP override's platform and the WebGL
14
+ * renderer all name the same machine shape. The profile follows the engine's
15
+ * own OS, because a real browser on this machine would report that platform.
16
+ */
17
+ /** One Chrome release, matching the mobile UA the panel already presents. */
18
+ const STEALTH_UA_VERSION = '140.0.0.0';
19
+ export const STEALTH_LOCALE = 'en-US';
20
+ export const STEALTH_ACCEPT_LANGUAGE = 'en-US,en;q=0.9';
21
+ const OS_PROFILES = {
22
+ win32: {
23
+ uaPlatform: 'Windows NT 10.0; Win64; x64',
24
+ cdpPlatform: 'Win32',
25
+ webglRenderer: 'ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002503) Direct3D11 (1992.0.0) vs_5_0 ps_5_0, D3D11)',
26
+ },
27
+ darwin: {
28
+ uaPlatform: 'Macintosh; Intel Mac OS X 10_15_7',
29
+ cdpPlatform: 'MacIntel',
30
+ webglRenderer: 'ANGLE (Apple, ANGLE Metal Renderer: Apple M2, Unspecified Version)',
31
+ },
32
+ linux: {
33
+ uaPlatform: 'X11; Linux x86_64',
34
+ cdpPlatform: 'Linux x86_64',
35
+ webglRenderer: 'ANGLE (Intel, Mesa Intel(R) UHD Graphics (CML GT2), OpenGL 4.6)',
36
+ },
37
+ };
38
+ const osProfile = (platform = process.platform) => OS_PROFILES[platform === 'darwin' ? 'darwin' : platform === 'win32' ? 'win32' : 'linux'];
39
+ /** A normal desktop Chrome user agent: no HeadlessChrome, no Electron, no Playwright. */
40
+ export function stealthUserAgent(platform = process.platform) {
41
+ return `Mozilla/5.0 (${osProfile(platform).uaPlatform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${STEALTH_UA_VERSION} Safari/537.36`;
42
+ }
43
+ /** Chromium args that switch off the blink "automated" feature: the strongest webdriver removal. */
44
+ export function stealthLaunchArgs() {
45
+ return ['--disable-blink-features=AutomationControlled'];
46
+ }
47
+ /** Context options that give every page of a context the desktop identity. */
48
+ export function stealthContextOptions(platform = process.platform) {
49
+ return { userAgent: stealthUserAgent(platform), locale: STEALTH_LOCALE };
50
+ }
51
+ /** The CDP `Emulation.setUserAgentOverride` payload for the panel's desktop mode: UA, language and platform from one profile. */
52
+ export function desktopUaOverride(platform = process.platform) {
53
+ const profile = osProfile(platform);
54
+ return { userAgent: stealthUserAgent(platform), acceptLanguage: STEALTH_ACCEPT_LANGUAGE, platform: profile.cdpPlatform };
55
+ }
56
+ const clampCores = (cores) => Math.min(Math.max(cores || 8, 2), 16);
57
+ /**
58
+ * The page script every page of a hardened context runs before its own scripts.
59
+ *
60
+ * Self-contained: Playwright serializes it, so it may not reference module scope.
61
+ * Values that the effective user agent implies are derived from that UA at page
62
+ * time, so the same script stays consistent under the panel's desktop and mobile
63
+ * overrides instead of hardcoding one platform and fighting the other.
64
+ */
65
+ const PAGE_SCRIPT = `(cfg => {
66
+ try {
67
+ const define = (target, name, value) => {
68
+ try { Object.defineProperty(target, name, { get: () => value, configurable: true }); } catch { /* A frozen navigator keeps its own value. */ }
69
+ };
70
+ const defineGetter = (target, name, get) => {
71
+ try { Object.defineProperty(target, name, { get, configurable: true }); } catch { /* A frozen navigator keeps its own value. */ }
72
+ };
73
+ if ('webdriver' in navigator) define(navigator, 'webdriver', false);
74
+ const platformFor = (ua) => /Windows/.test(ua) ? 'Win32'
75
+ : /Android/.test(ua) ? 'Linux armv8l'
76
+ : /Macintosh|Mac OS/.test(ua) ? 'MacIntel' : 'Linux x86_64';
77
+ // The platform is derived per read, not captured: the panel flips a live
78
+ // tab between desktop and mobile emulation by overriding the user agent
79
+ // without a reload, and a value frozen at document creation would pair a
80
+ // desktop UA with an Android platform on the switched tab.
81
+ defineGetter(navigator, 'platform', () => platformFor(navigator.userAgent));
82
+ define(navigator, 'hardwareConcurrency', cfg.cores);
83
+ define(navigator, 'deviceMemory', cfg.deviceMemory);
84
+ // maxTouchPoints is left alone: an own getter here would pin the value the
85
+ // panel's touch emulation (Emulation.setTouchEmulationEnabled) changes on a
86
+ // live tab, and headless desktop already reports the same 0 a real one does.
87
+ define(navigator, 'languages', Object.freeze(['en-US', 'en']));
88
+ // An empty plugin list is an automation tell; real Chrome always ships the
89
+ // PDF set. The replacement answers the PluginArray API pages call — item,
90
+ // namedItem, indexed plugins that themselves expose their MIME types —
91
+ // because a bare array of bare objects is a stronger fingerprint than none.
92
+ const pluginNames = ['PDF Viewer', 'Chrome PDF Viewer', 'Chromium PDF Viewer', 'Microsoft Edge PDF Viewer', 'WebKit built-in PDF'];
93
+ const makePlugin = (name) => {
94
+ const plugin = {
95
+ name, description: 'Portable Document Format', filename: 'internal-pdf-viewer', length: 1,
96
+ item(index) { return index === 0 ? this[0] : null; },
97
+ namedItem(type) { return this[0] && this[0].type === type ? this[0] : null; },
98
+ [Symbol.toStringTag]: 'Plugin',
99
+ };
100
+ plugin[0] = {
101
+ type: 'application/pdf', suffixes: 'pdf', description: 'Portable Document Format', enabledPlugin: plugin,
102
+ [Symbol.toStringTag]: 'MimeType',
103
+ };
104
+ return plugin;
105
+ };
106
+ const entries = pluginNames.map(makePlugin);
107
+ const pluginArray = {
108
+ length: entries.length,
109
+ item(index) { return index >= 0 && index < entries.length ? entries[index] : null; },
110
+ namedItem(name) { return entries.find((entry) => entry.name === name) || null; },
111
+ refresh() {},
112
+ [Symbol.toStringTag]: 'PluginArray',
113
+ };
114
+ // Indexed and named access: Chromium's collections answer both, plugins by
115
+ // name and MIME types by type string.
116
+ entries.forEach((entry, index) => { pluginArray[index] = entry; pluginArray[entry.name] = entry; });
117
+ pluginArray[Symbol.iterator] = [][Symbol.iterator];
118
+ define(navigator, 'plugins', pluginArray);
119
+ // Chrome pairs the five plugins with two PDF MIME types whose enabledPlugin
120
+ // points back at the first entry; leaving the headless emptiness beside a
121
+ // five-entry plugin list would be its own inconsistency.
122
+ const mimeType = (type) => ({ type, suffixes: 'pdf', description: 'Portable Document Format', enabledPlugin: entries[0], [Symbol.toStringTag]: 'MimeType' });
123
+ const mimeEntries = [mimeType('application/pdf'), mimeType('text/pdf')];
124
+ const mimeTypes = {
125
+ length: mimeEntries.length,
126
+ item(index) { return index >= 0 && index < mimeEntries.length ? mimeEntries[index] : null; },
127
+ namedItem(type) { return mimeEntries.find((entry) => entry.type === type) || null; },
128
+ [Symbol.toStringTag]: 'MimeTypeArray',
129
+ };
130
+ mimeEntries.forEach((entry, index) => { mimeTypes[index] = entry; mimeTypes[entry.type] = entry; });
131
+ mimeTypes[Symbol.iterator] = [][Symbol.iterator];
132
+ define(navigator, 'mimeTypes', mimeTypes);
133
+ for (const proto of [window.WebGLRenderingContext && window.WebGLRenderingContext.prototype, window.WebGL2RenderingContext && window.WebGL2RenderingContext.prototype]) {
134
+ if (!proto) continue;
135
+ const original = proto.getParameter;
136
+ proto.getParameter = function (parameter) {
137
+ if (parameter === 37445) return 'Google Inc.';
138
+ if (parameter === 37446) return cfg.renderer;
139
+ return original.call(this, parameter);
140
+ };
141
+ }
142
+ // window.chrome exists on a real page, but its runtime is absent without an
143
+ // extension context. A stub that answers sendMessage and connect without
144
+ // responses or ports turns a clean feature check into a hang or a throw.
145
+ if (!window.chrome) window.chrome = {};
146
+ } catch { /* A hostile page must not break the browser. */ }
147
+ })`;
148
+ /** The init script text: the page script with one hardware config baked in. */
149
+ export function stealthInitScript(hardware) {
150
+ const config = {
151
+ cores: clampCores(hardware?.cores ?? cpus().length),
152
+ deviceMemory: 8,
153
+ renderer: osProfile().webglRenderer,
154
+ };
155
+ return `${PAGE_SCRIPT}(${JSON.stringify(config)})`;
156
+ }
157
+ /**
158
+ * Add the stealth init script to a browser context, once per context.
159
+ *
160
+ * Every page the context later creates runs it: tabs a session opened and
161
+ * popups the browser opened alike. A context without the API (a test fake)
162
+ * is left as it is.
163
+ */
164
+ export async function hardenContext(context) {
165
+ await Promise.resolve().then(() => context?.addInitScript?.(stealthInitScript())).catch(() => { });
166
+ }