@opencode/browse 0.0.17 → 0.0.18-dev.193

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 (39) hide show
  1. package/dist/{Runtime-tvxdkp60.mjs → Runtime-r9sev1rq.mjs} +1 -1
  2. package/dist/{cli-ktqhzcbw.mjs → cli-ekwkvvmm.mjs} +33 -29
  3. package/dist/cli.mjs +23 -13
  4. package/dist/{helpers-nsfj0mfw.mjs → helpers-3ycvp75a.mjs} +2 -1
  5. package/dist/{index-kmxtpxxk.mjs → index-xsb9s479.mjs} +2 -2
  6. package/dist/{legacy-runtime-fgpmhx47.mjs → legacy-runtime-v1sdjj5h.mjs} +8 -7
  7. package/dist/log-yek648ak.mjs +9 -0
  8. package/dist/{main-83z4fc6b.mjs → main-1qwrze1y.mjs} +2 -2
  9. package/dist/{main-gqr4pk9f.mjs → main-2p0v71q0.mjs} +39 -37
  10. package/dist/{main-hh16893t.mjs → main-3g7fdzbh.mjs} +28 -26
  11. package/dist/{main-n7w5a79r.mjs → main-55a4gpef.mjs} +59 -67
  12. package/dist/main-693wwz19.mjs +4 -0
  13. package/dist/main-91vhk5de.mjs +38 -0
  14. package/dist/{main-t9na9ekd.mjs → main-9t32k44b.mjs} +4 -3
  15. package/dist/{main-d1th6z2h.mjs → main-bv9nawja.mjs} +21 -225
  16. package/dist/main-cgnkhs2x.mjs +35 -0
  17. package/dist/{main-9fwqh5k7.mjs → main-esdgpebk.mjs} +3 -3
  18. package/dist/{main-z4c819pg.mjs → main-fg5awggs.mjs} +29 -27
  19. package/dist/{main-98dnkvn3.mjs → main-gt2gskrq.mjs} +2 -2
  20. package/dist/{main-mq9bc0zb.mjs → main-gw77et6v.mjs} +3 -3
  21. package/dist/{main-xzx6aepf.mjs → main-kcw411ep.mjs} +11 -42
  22. package/dist/{main-j4n6hkxm.mjs → main-nnfxg7re.mjs} +7 -7
  23. package/dist/{main-zrjcdksk.mjs → main-pcqtqhgv.mjs} +5 -3
  24. package/dist/{main-jtgan144.mjs → main-pxs5m0kb.mjs} +10 -8
  25. package/dist/main-qazf3bhk.mjs +223 -0
  26. package/dist/{main-k4ys0swh.mjs → main-sf7vaxb6.mjs} +1 -1
  27. package/dist/{main-5d9jn9px.mjs → main-stf180y1.mjs} +7 -5
  28. package/dist/{main-sx14bt3y.mjs → main-zedq93ez.mjs} +5 -3
  29. package/dist/{main-bbn1ah9d.mjs → main-zzggnpf4.mjs} +2 -2
  30. package/dist/{mcp-pxad1yrf.mjs → mcp-xfx04fxe.mjs} +125 -121
  31. package/dist/{migrate-haeckv81.mjs → migrate-4rewxqd7.mjs} +8 -7
  32. package/dist/{relay-53zb68pj.mjs → relay-me036e19.mjs} +562 -166
  33. package/dist/{remove-stored-secrets-036hkbd6.mjs → remove-stored-secrets-ymhge5va.mjs} +1 -1
  34. package/dist/{runtime-update-5jvb2g53.mjs → runtime-update-hd2cvy1c.mjs} +12 -10
  35. package/dist/{setup-5j4kxeyp.mjs → setup-0hmbzam5.mjs} +12 -11
  36. package/dist/{update-ssnpp5hp.mjs → update-vnkjbc0e.mjs} +3 -3
  37. package/dist/{version-yvaafhes.mjs → version-jn0h3rmc.mjs} +1 -1
  38. package/package.json +1 -1
  39. package/dist/main-ca2rymwh.mjs +0 -4
@@ -4,9 +4,10 @@ import {
4
4
  import {
5
5
  opencodeBrowserVersion2,
6
6
  opencodeBrowserBuildId2
7
- } from "./main-ca2rymwh.mjs";
7
+ } from "./main-693wwz19.mjs";
8
8
  import {
9
9
  extensionProtocolVersion,
10
+ extensionCapabilityTabRelease,
10
11
  minExtensionProtocolVersion,
11
12
  browserUnresponsive,
12
13
  browserReloading,
@@ -26,12 +27,14 @@ import {
26
27
  setStoredMode,
27
28
  autoUpdateStatus,
28
29
  createAutoUpdater
29
- } from "./main-t9na9ekd.mjs";
30
+ } from "./main-9t32k44b.mjs";
30
31
  import {
31
32
  isNodeError,
32
33
  isUnsupportedDirectorySyncError,
33
34
  ensurePrivateDirectorySync,
34
- writePrivateJsonFileSync,
35
+ writePrivateJsonFileSync
36
+ } from "./main-91vhk5de.mjs";
37
+ import {
35
38
  ExecuteRequest,
36
39
  SessionAdoptRequest,
37
40
  SessionNewRequest,
@@ -74,7 +77,7 @@ import {
74
77
  isRestrictedTarget2,
75
78
  isRestrictedUrl2,
76
79
  dataUrlDocument2
77
- } from "./main-xzx6aepf.mjs";
80
+ } from "./main-kcw411ep.mjs";
78
81
  import {
79
82
  context,
80
83
  pendingPairingCodeKeys,
@@ -92,16 +95,20 @@ import {
92
95
  pairingSessionKey,
93
96
  sessionProof,
94
97
  wrapToken
95
- } from "./main-98dnkvn3.mjs";
98
+ } from "./main-gt2gskrq.mjs";
99
+ import {
100
+ appendManagedRelayProcessLog2,
101
+ relayLog2
102
+ } from "./main-cgnkhs2x.mjs";
96
103
  import {
97
104
  defaultJournalBaseDir,
98
105
  makeJournalEntry,
99
106
  appendJournalEntry,
100
107
  startJournalRetention
101
- } from "./main-5d9jn9px.mjs";
108
+ } from "./main-stf180y1.mjs";
102
109
  import {
103
110
  createUpdateWatcher2
104
- } from "./main-mq9bc0zb.mjs";
111
+ } from "./main-gw77et6v.mjs";
105
112
  import {
106
113
  SettingsInputError,
107
114
  parseSettingChanges,
@@ -109,7 +116,15 @@ import {
109
116
  settingsToExtension,
110
117
  describeSettings,
111
118
  describeChanges
112
- } from "./main-gqr4pk9f.mjs";
119
+ } from "./main-2p0v71q0.mjs";
120
+ import {
121
+ map,
122
+ withDefault,
123
+ option,
124
+ String2,
125
+ Int,
126
+ Boolean2
127
+ } from "./main-55a4gpef.mjs";
113
128
  import {
114
129
  currentTimeMillis,
115
130
  makeUnsafe,
@@ -117,29 +132,19 @@ import {
117
132
  when,
118
133
  orElse,
119
134
  exhaustive
120
- } from "./main-jtgan144.mjs";
135
+ } from "./main-pxs5m0kb.mjs";
121
136
  import {
122
137
  installedDevExtension,
123
138
  syncDevExtension,
124
139
  relayHostname,
125
140
  isLocalPeer
126
- } from "./main-9fwqh5k7.mjs";
127
- import {
128
- map,
129
- withDefault,
130
- option,
131
- String2,
132
- Int,
133
- Boolean2,
134
- appendManagedRelayProcessLog,
135
- relayLog
136
- } from "./main-n7w5a79r.mjs";
141
+ } from "./main-esdgpebk.mjs";
137
142
  import {
138
143
  relayTokenQueryParam,
139
144
  relayToken,
140
145
  secretsEqual,
141
146
  ensurePrivateDirectory
142
- } from "./main-bbn1ah9d.mjs";
147
+ } from "./main-zzggnpf4.mjs";
143
148
  import {
144
149
  configuredRelayPort,
145
150
  relayPortPinned,
@@ -147,7 +152,7 @@ import {
147
152
  writeRelayState,
148
153
  removeRelayState,
149
154
  chooseRelayPort
150
- } from "./main-sx14bt3y.mjs";
155
+ } from "./main-zedq93ez.mjs";
151
156
  import {
152
157
  defaultRoots,
153
158
  configRoot2,
@@ -164,12 +169,12 @@ import {
164
169
  devExtension,
165
170
  storeUrl,
166
171
  installCommand
167
- } from "./main-83z4fc6b.mjs";
172
+ } from "./main-1qwrze1y.mjs";
168
173
  import {
169
174
  join,
170
175
  interrupt,
171
176
  makeUnsafe2
172
- } from "./main-hh16893t.mjs";
177
+ } from "./main-3g7fdzbh.mjs";
173
178
  import {
174
179
  taggedEnum,
175
180
  is2,
@@ -188,16 +193,8 @@ import {
188
193
  Int2,
189
194
  Defect,
190
195
  TaggedError2
191
- } from "./main-z4c819pg.mjs";
196
+ } from "./main-fg5awggs.mjs";
192
197
  import {
193
- isString,
194
- isNumber,
195
- isBoolean,
196
- isBigInt,
197
- isSymbol,
198
- isFunction,
199
- isObjectOrArray,
200
- isObject,
201
198
  isNone,
202
199
  isSome,
203
200
  getOrUndefined,
@@ -273,7 +270,17 @@ import {
273
270
  runSync,
274
271
  fnUntraced,
275
272
  fn
276
- } from "./main-d1th6z2h.mjs";
273
+ } from "./main-bv9nawja.mjs";
274
+ import {
275
+ isString,
276
+ isNumber,
277
+ isBoolean,
278
+ isBigInt,
279
+ isSymbol,
280
+ isFunction,
281
+ isObjectOrArray,
282
+ isObject
283
+ } from "./main-qazf3bhk.mjs";
277
284
 
278
285
  // src/relay.ts
279
286
  import crypto9 from "node:crypto";
@@ -312,9 +319,13 @@ class ExtensionRpc {
312
319
  protocolVersion;
313
320
  protocolCompatible;
314
321
  protocolLegacy;
322
+ capabilities = new Set;
315
323
  constructor(timeouts = {}) {
316
324
  this.timeouts = timeouts;
317
325
  }
326
+ supports(capability) {
327
+ return this.capabilities.has(capability);
328
+ }
318
329
  get connected() {
319
330
  return this.socket?.readyState === WebSocket.OPEN && this.ready && !this.unresponsive && this.protocolCompatible !== false;
320
331
  }
@@ -332,12 +343,19 @@ class ExtensionRpc {
332
343
  this.socket?.close(4001, "Extension replaced");
333
344
  this.resetConnectionState(socket);
334
345
  }
335
- markHandshake(version, reportedProtocolVersion) {
346
+ markHandshake(version, reportedProtocolVersion, reportedCapabilities) {
336
347
  const protocol = extensionProtocolCompatibility(reportedProtocolVersion);
337
348
  this.version = version;
338
349
  this.protocolVersion = protocol.version;
339
350
  this.protocolCompatible = protocol.compatible;
340
351
  this.protocolLegacy = protocol.legacy;
352
+ this.capabilities.clear();
353
+ if (Array.isArray(reportedCapabilities)) {
354
+ for (const capability of reportedCapabilities) {
355
+ if (typeof capability === "string" && capability.length <= 64)
356
+ this.capabilities.add(capability);
357
+ }
358
+ }
341
359
  return protocol;
342
360
  }
343
361
  markReady() {
@@ -363,6 +381,7 @@ class ExtensionRpc {
363
381
  this.protocolVersion = undefined;
364
382
  this.protocolCompatible = undefined;
365
383
  this.protocolLegacy = undefined;
384
+ this.capabilities.clear();
366
385
  }
367
386
  close() {
368
387
  this.cancelLivenessProbe();
@@ -7419,6 +7438,8 @@ async function withRestoredViewports(options) {
7419
7438
  }
7420
7439
 
7421
7440
  // src/execute/default-page.ts
7441
+ var defaultTargetResolveMaxAttempts = 3;
7442
+
7422
7443
  class DefaultPageHost {
7423
7444
  page;
7424
7445
  defaultPageTargetId;
@@ -7437,6 +7458,7 @@ class DefaultPageHost {
7437
7458
  actionTimeoutMs = defaultActionTimeoutMs;
7438
7459
  actionTimeoutPages = new Set;
7439
7460
  actionTimeoutGuardedPage;
7461
+ defaultTargetResolveAttempts = 0;
7440
7462
  boundPageListeners;
7441
7463
  onDefaultTargetChangeOption;
7442
7464
  pageHealthCheckTimeoutMsOption;
@@ -7544,13 +7566,15 @@ class DefaultPageHost {
7544
7566
  this.defaultPageTargetId = targetId;
7545
7567
  this.ownsPage = ownsPage;
7546
7568
  this.pendingTargetRebind = undefined;
7569
+ this.defaultTargetResolveAttempts = 0;
7547
7570
  this.pageReleasedByDebuggingBar = false;
7548
7571
  this.recordNonBlankUrl(safePageUrl(page));
7549
7572
  const close = () => {
7550
7573
  if (this.page !== page)
7551
7574
  return;
7552
- if (targetId !== undefined && !this.pageCrashed)
7553
- this.closedDefaultPage = { targetId, ownsPage: this.ownsPage };
7575
+ const currentTargetId = this.defaultPageTargetId;
7576
+ if (currentTargetId !== undefined && !this.pageCrashed)
7577
+ this.closedDefaultPage = { targetId: currentTargetId, ownsPage: this.ownsPage };
7554
7578
  if (this.lastKnownNonBlankUrl) {
7555
7579
  this.recreatedFromClosedUrl = this.lastKnownNonBlankUrl;
7556
7580
  }
@@ -7589,6 +7613,20 @@ class DefaultPageHost {
7589
7613
  this.clearBoundPageListeners();
7590
7614
  this.clearSnapshotRefs();
7591
7615
  }
7616
+ async identifyBoundDefaultPage() {
7617
+ const page = this.page;
7618
+ if (!page || page.isClosed() || this.defaultPageTargetId !== undefined)
7619
+ return;
7620
+ if (this.defaultTargetResolveAttempts >= defaultTargetResolveMaxAttempts)
7621
+ return;
7622
+ this.defaultTargetResolveAttempts += 1;
7623
+ const targetId = await resolvePageTargetId(page);
7624
+ if (!targetId || this.page !== page || page.isClosed() || this.defaultPageTargetId !== undefined)
7625
+ return;
7626
+ this.defaultPageTargetId = targetId;
7627
+ this.defaultTargetResolveAttempts = 0;
7628
+ this.notifyDefaultTargetChange();
7629
+ }
7592
7630
  async getSessionPage({ context, targetSelection }) {
7593
7631
  const selection = targetSelection ?? {};
7594
7632
  if (hasExplicitTargetSelection(selection)) {
@@ -7598,6 +7636,7 @@ class DefaultPageHost {
7598
7636
  }
7599
7637
  return selected;
7600
7638
  }
7639
+ await this.identifyBoundDefaultPage();
7601
7640
  if (!this.page && this.defaultPageTargetId) {
7602
7641
  const targetId = this.defaultPageTargetId;
7603
7642
  const rebind = this.pendingTargetRebind;
@@ -10446,7 +10485,7 @@ function tunePatchright({ server }) {
10446
10485
  const page = server?.Page?.prototype;
10447
10486
  const mainFrame = page?.mainFrame;
10448
10487
  if (!page || typeof mainFrame !== "function") {
10449
- relayLog("patchright.tuning", { applied: false, reason: "server.Page.mainFrame not found" });
10488
+ relayLog2("patchright.tuning", { applied: false, reason: "server.Page.mainFrame not found" });
10450
10489
  return;
10451
10490
  }
10452
10491
  page.mainFrame = function() {
@@ -10455,7 +10494,7 @@ function tunePatchright({ server }) {
10455
10494
  const frames = Object.getPrototypeOf(frame);
10456
10495
  const selectors = Object.getPrototypeOf(frame.selectors);
10457
10496
  if (typeof selectors._hasClosedShadowRoots !== "function" || typeof frames.queryCount !== "function" || typeof frames.querySelectorAll !== "function") {
10458
- relayLog("patchright.tuning", { applied: false, reason: "Frame or FrameSelectors internals changed" });
10497
+ relayLog2("patchright.tuning", { applied: false, reason: "Frame or FrameSelectors internals changed" });
10459
10498
  return frame;
10460
10499
  }
10461
10500
  selectors._hasClosedShadowRoots = async () => false;
@@ -11350,6 +11389,12 @@ class RelayShutdown {
11350
11389
  constructor(options) {
11351
11390
  this.options = options;
11352
11391
  }
11392
+ log(event, fields = {}) {
11393
+ try {
11394
+ const log = this.options.log ?? relayLog2;
11395
+ log(event, fields);
11396
+ } catch {}
11397
+ }
11353
11398
  get accepting() {
11354
11399
  return State.$is("Running")(this.state);
11355
11400
  }
@@ -11370,6 +11415,7 @@ class RelayShutdown {
11370
11415
  close() {
11371
11416
  const control = this;
11372
11417
  return gen(function* () {
11418
+ control.log("relay.shutdown.close", { requests: control.requests });
11373
11419
  control.state = State.Closing();
11374
11420
  yield* control.drainAndSettle();
11375
11421
  });
@@ -11396,6 +11442,11 @@ class RelayShutdown {
11396
11442
  request(request) {
11397
11443
  const control = this;
11398
11444
  return uninterruptibleMask2((restore) => gen(function* () {
11445
+ control.log("relay.shutdown.requested", {
11446
+ requestId: request.requestId,
11447
+ client: request.client.kind,
11448
+ force: request.force === true
11449
+ });
11399
11450
  if (request.instanceId !== control.options.instanceId) {
11400
11451
  return yield* new RelayShutdownError({ reason: "instance-changed", message: "Relay shutdown does not match the active managed instance" });
11401
11452
  }
@@ -11439,6 +11490,7 @@ class RelayShutdown {
11439
11490
  if (busy)
11440
11491
  return yield* control.busyError(busy);
11441
11492
  control.state = State.Stopping();
11493
+ control.log("relay.shutdown.stopping", { requestId: request.requestId });
11442
11494
  control.options.stop();
11443
11495
  }).pipe(onExit((exit) => {
11444
11496
  if (isSuccess2(exit) || !State.$is("Draining")(control.state))
@@ -11574,8 +11626,20 @@ function createdSummary(session, created, hooks) {
11574
11626
  ...created ? { created: true } : {}
11575
11627
  };
11576
11628
  }
11577
- function persistedSession(session) {
11629
+ function persistedSession(session, hooks) {
11578
11630
  const target = session.target;
11631
+ const targets = new Map;
11632
+ if (target?.owner === "relay")
11633
+ targets.set(target.id, { id: target.id, owner: "relay" });
11634
+ for (const held of session.targets ?? []) {
11635
+ if (held.owner === "relay")
11636
+ targets.set(held.id, { id: held.id, owner: "relay" });
11637
+ }
11638
+ for (const id of hooks?.relayTargetIdsForSession?.(session.id) ?? []) {
11639
+ if (!targets.has(id))
11640
+ targets.set(id, { id, owner: "relay" });
11641
+ }
11642
+ const ownedTargets = Array.from(targets.values());
11579
11643
  return {
11580
11644
  id: session.id,
11581
11645
  createdAt: session.createdAt,
@@ -11585,6 +11649,7 @@ function persistedSession(session) {
11585
11649
  ...session.keepVisible ? { keepVisible: true } : {},
11586
11650
  ...session.browser ? { browser: session.browser.id, ...session.browser.key ? { browserKey: session.browser.key } : {} } : {},
11587
11651
  ...target ? { target } : {},
11652
+ ...ownedTargets.length > 0 ? { targets: ownedTargets } : {},
11588
11653
  ...session.clientPid === undefined ? {} : { clientPid: session.clientPid }
11589
11654
  };
11590
11655
  }
@@ -11682,7 +11747,7 @@ class SessionAdmission {
11682
11747
  }));
11683
11748
  }
11684
11749
  persistedSessions() {
11685
- return Array.from(this.sessions.values(), (session) => persistedSession(session));
11750
+ return Array.from(this.sessions.values(), (session) => persistedSession(session, this.hooks));
11686
11751
  }
11687
11752
  schedulePersistence() {
11688
11753
  const hook = this.hooks.onSessionsChanged;
@@ -11800,7 +11865,21 @@ function adoptTargetForSession(context, options) {
11800
11865
  yield* context.closeRelayTarget(previousTarget.id);
11801
11866
  previousRelayClosed = true;
11802
11867
  }
11868
+ for (const other of context.sessions.values()) {
11869
+ if (other.id === session.id)
11870
+ continue;
11871
+ if (other.target?.owner === "relay" && other.target.id === options.targetId) {
11872
+ context.clearSessionDefaultTarget(other, options.targetId, { reason: "adopted" });
11873
+ }
11874
+ }
11803
11875
  session.target = { id: options.targetId, owner: "user" };
11876
+ if (session.targets) {
11877
+ const held = session.targets.filter((target) => target.id !== options.targetId && target.id !== previousTargetId);
11878
+ if (held.length > 0)
11879
+ session.targets = held;
11880
+ else
11881
+ delete session.targets;
11882
+ }
11804
11883
  session.updatedAt = new Date().toISOString();
11805
11884
  yield* context.admission.commitPersistence();
11806
11885
  if (adoptionCancelled()) {
@@ -11886,6 +11965,8 @@ function sessionRelayTargetIds(hooks, session) {
11886
11965
  ids.add(session.target.id);
11887
11966
  else if (session.target)
11888
11967
  ids.delete(session.target.id);
11968
+ for (const target of session.targets ?? [])
11969
+ ids.add(target.id);
11889
11970
  return ids;
11890
11971
  }
11891
11972
  function withLifecycleTimeout(hooks, effect, label) {
@@ -12067,6 +12148,7 @@ class OpenCodeBrowserSessions {
12067
12148
  closeOpenCodeBrowserSessionSettled: (session) => this.closeOpenCodeBrowserSessionSettled(session),
12068
12149
  closeRelayTarget: (targetId) => this.closeRelayTarget(targetId),
12069
12150
  releaseSessionTargetOwnership: (session) => this.releaseSessionTargetOwnership(session),
12151
+ clearSessionDefaultTarget: (session, targetId, options) => this.clearSessionDefaultTarget(session, targetId, options),
12070
12152
  notifyTargetOwnershipChange: (change) => this.notifyTargetOwnershipChange(change)
12071
12153
  };
12072
12154
  this.executionContext = {
@@ -12092,19 +12174,39 @@ class OpenCodeBrowserSessions {
12092
12174
  this.admission.assertAdmission();
12093
12175
  if (this.sessions.size > 0)
12094
12176
  throw new Error("Cannot restore sessions after session management has started");
12095
- const ids = new Set;
12096
- const targetOwners = new Set;
12177
+ const sessionIds = new Set;
12178
+ const accepted = [];
12097
12179
  for (const entry of entries) {
12098
- if (ids.has(entry.id))
12099
- throw new Error(`Duplicate persisted session: ${entry.id}`);
12100
- ids.add(entry.id);
12101
- if (entry.target && targetOwners.has(entry.target.id)) {
12102
- throw new Error(`Duplicate persisted target owner: ${entry.target.id}`);
12180
+ if (sessionIds.has(entry.id)) {
12181
+ this.warnRestore(`duplicate session ${entry.id}; later entry dropped`);
12182
+ continue;
12183
+ }
12184
+ sessionIds.add(entry.id);
12185
+ accepted.push(entry);
12186
+ }
12187
+ const targetOwners = new Map;
12188
+ for (const entry of accepted) {
12189
+ const target = this.acceptRestoredTarget(entry, entry.target, targetOwners);
12190
+ const targets = [];
12191
+ const seen = new Set(target ? [target.id] : []);
12192
+ for (const candidate of entry.targets ?? []) {
12193
+ if (candidate.owner !== "relay") {
12194
+ this.warnRestore(`session ${entry.id} held a non-relay target ${candidate.id}; target dropped`);
12195
+ continue;
12196
+ }
12197
+ if (seen.has(candidate.id)) {
12198
+ this.warnRestore(`session ${entry.id} lists target ${candidate.id} twice; duplicate dropped`);
12199
+ continue;
12200
+ }
12201
+ const owner = targetOwners.get(candidate.id);
12202
+ if (owner !== undefined && owner !== entry.id) {
12203
+ this.warnRestore(`session ${entry.id} claims target ${candidate.id} of session ${owner}; target dropped`);
12204
+ continue;
12205
+ }
12206
+ targetOwners.set(candidate.id, entry.id);
12207
+ seen.add(candidate.id);
12208
+ targets.push(candidate);
12103
12209
  }
12104
- if (entry.target)
12105
- targetOwners.add(entry.target.id);
12106
- }
12107
- for (const entry of entries) {
12108
12210
  const session = this.createOpenCodeBrowserSession(entry.id, entry.readOnly, {
12109
12211
  createdAt: entry.createdAt,
12110
12212
  updatedAt: entry.updatedAt
@@ -12115,22 +12217,139 @@ class OpenCodeBrowserSessions {
12115
12217
  session.keepVisible = true;
12116
12218
  if (entry.browser)
12117
12219
  session.browser = { id: entry.browser, ...entry.browserKey ? { key: entry.browserKey } : {} };
12118
- if (entry.target)
12119
- session.target = entry.target;
12220
+ if (target)
12221
+ session.target = target;
12222
+ if (targets.length > 0)
12223
+ session.targets = targets;
12120
12224
  if (entry.clientPid !== undefined)
12121
12225
  session.clientPid = entry.clientPid;
12122
- session.sandbox.restore(entry.target);
12226
+ session.sandbox.restore(target);
12123
12227
  this.sessions.set(entry.id, session);
12124
12228
  }
12125
12229
  }
12126
- persistedTargetOwner(targetId) {
12230
+ acceptRestoredTarget(entry, target, targetOwners) {
12231
+ if (!target)
12232
+ return;
12233
+ const owner = targetOwners.get(target.id);
12234
+ if (owner !== undefined && owner !== entry.id) {
12235
+ this.warnRestore(`session ${entry.id} claims target ${target.id} of session ${owner}; target dropped`);
12236
+ return;
12237
+ }
12238
+ targetOwners.set(target.id, entry.id);
12239
+ return target;
12240
+ }
12241
+ warnRestore(message) {
12242
+ try {
12243
+ if (this.hooks.onRestoreWarning)
12244
+ return this.hooks.onRestoreWarning(message);
12245
+ } catch {}
12246
+ console.error(`browse session restore: ${message}`);
12247
+ }
12248
+ persistedTargetOwner(targetId, options = {}) {
12127
12249
  for (const session of this.sessions.values()) {
12250
+ if (options.browserKey !== undefined && session.browser?.key !== undefined && session.browser.key !== options.browserKey)
12251
+ continue;
12128
12252
  const target = session.target;
12129
- if (target?.id === targetId)
12253
+ if (target?.id === targetId && (options.includeHeldTargets !== false || target.owner === "user" || options.legacy === true)) {
12130
12254
  return { sessionId: session.id, owner: target.owner };
12255
+ }
12256
+ if (options.includeHeldTargets === false)
12257
+ continue;
12258
+ const held = session.targets?.find((candidate) => candidate.id === targetId);
12259
+ if (held)
12260
+ return { sessionId: session.id, owner: held.owner };
12131
12261
  }
12132
12262
  return;
12133
12263
  }
12264
+ noteTargetHeld(targetId, sessionId) {
12265
+ const session = this.sessions.get(sessionId);
12266
+ if (!session)
12267
+ return;
12268
+ const targets = session.targets ?? [];
12269
+ if (targets.some((target) => target.id === targetId && target.owner === "relay"))
12270
+ return;
12271
+ session.targets = [...targets, { id: targetId, owner: "relay" }];
12272
+ this.admission.schedulePersistence();
12273
+ }
12274
+ clearSessionDefaultTarget(session, targetId, options = {}) {
12275
+ if (session.target?.id !== targetId)
12276
+ return false;
12277
+ session.sandbox.markTargetDetached(targetId, { releasedByUser: options.releasedByUser === true });
12278
+ this.notifyTargetCleared(session.id, targetId, options.reason ?? "released");
12279
+ this.updateTarget(session, undefined);
12280
+ return true;
12281
+ }
12282
+ forgetTargetHeld(targetId, options = {}) {
12283
+ let changed = false;
12284
+ for (const session of this.sessions.values()) {
12285
+ let sessionChanged = false;
12286
+ if (session.target?.owner === "relay" && session.target.id === targetId) {
12287
+ this.clearSessionDefaultTarget(session, targetId, options);
12288
+ sessionChanged = true;
12289
+ }
12290
+ if (session.targets?.some((target) => target.id === targetId)) {
12291
+ const kept = session.targets.filter((target) => target.id !== targetId);
12292
+ if (kept.length > 0)
12293
+ session.targets = kept;
12294
+ else
12295
+ delete session.targets;
12296
+ sessionChanged = true;
12297
+ }
12298
+ changed ||= sessionChanged;
12299
+ }
12300
+ if (changed)
12301
+ this.admission.schedulePersistence();
12302
+ return changed;
12303
+ }
12304
+ pruneHeldTargets(options) {
12305
+ const removed = new Set;
12306
+ let changed = false;
12307
+ for (const session of this.sessions.values()) {
12308
+ if (session.browser?.key === undefined) {
12309
+ if (!options.includeUnknownBrowser)
12310
+ continue;
12311
+ } else if (session.browser.key !== options.browserKey) {
12312
+ continue;
12313
+ }
12314
+ if (session.target && !options.liveTargetIds.has(session.target.id)) {
12315
+ removed.add(session.target.id);
12316
+ this.clearSessionDefaultTarget(session, session.target.id, { reason: "pruned" });
12317
+ changed = true;
12318
+ }
12319
+ if (session.targets === undefined)
12320
+ continue;
12321
+ const kept = [];
12322
+ const seen = new Set;
12323
+ for (const target of session.targets) {
12324
+ if (!options.liveTargetIds.has(target.id) || seen.has(target.id)) {
12325
+ removed.add(target.id);
12326
+ changed = true;
12327
+ continue;
12328
+ }
12329
+ seen.add(target.id);
12330
+ kept.push(target);
12331
+ }
12332
+ if (kept.length > 0)
12333
+ session.targets = kept;
12334
+ else
12335
+ delete session.targets;
12336
+ }
12337
+ if (changed)
12338
+ this.admission.schedulePersistence();
12339
+ return [...removed];
12340
+ }
12341
+ tombstoneHeldTargets(session) {
12342
+ const targetIds = new Set((session.targets ?? []).map((target) => target.id));
12343
+ if (session.target?.owner === "relay")
12344
+ targetIds.add(session.target.id);
12345
+ if (targetIds.size === 0)
12346
+ return;
12347
+ try {
12348
+ this.hooks.onTombstoneRelayTargets?.(session.id, [...targetIds], session.browser?.key);
12349
+ } catch (error) {
12350
+ console.error("Session tombstone hook failed", error);
12351
+ }
12352
+ }
12134
12353
  updateTarget(session, target) {
12135
12354
  if (this.sessions.get(session.id) !== session)
12136
12355
  return;
@@ -12312,14 +12531,20 @@ class OpenCodeBrowserSessions {
12312
12531
  return this.collectSessionIds((session) => session.sandbox.markTargetProtectedUi(targetId, protectedUi));
12313
12532
  }
12314
12533
  markTargetDetached(targetId, options = {}) {
12534
+ const reason = options.reason ?? (options.releasedByUser === true ? "released-by-user" : "detached");
12315
12535
  return this.collectSessionIds((session) => {
12316
12536
  const detached = session.sandbox.markTargetDetached(targetId, options);
12317
12537
  if (session.target?.id === targetId && session.target.owner === "user") {
12318
12538
  this.notifyTargetOwnershipChange(this.targetOwnership.releaseTargetOwnership(targetId, session.id));
12319
12539
  }
12320
12540
  if (session.target?.id === targetId) {
12541
+ this.notifyTargetCleared(session.id, targetId, reason);
12321
12542
  this.updateTarget(session, undefined);
12322
12543
  }
12544
+ if (session.targets?.some((target) => target.id === targetId)) {
12545
+ session.targets = session.targets.filter((target) => target.id !== targetId);
12546
+ this.admission.schedulePersistence();
12547
+ }
12323
12548
  return detached;
12324
12549
  });
12325
12550
  }
@@ -12327,9 +12552,27 @@ class OpenCodeBrowserSessions {
12327
12552
  return this.collectSessionIds((session) => {
12328
12553
  if (session.target?.id === previousTargetId)
12329
12554
  this.updateTarget(session, { ...session.target, id: targetId });
12555
+ if (session.targets?.some((target) => target.id === previousTargetId)) {
12556
+ const seen = new Set;
12557
+ session.targets = session.targets.flatMap((target) => {
12558
+ const id = target.id === previousTargetId ? targetId : target.id;
12559
+ if (seen.has(id))
12560
+ return [];
12561
+ seen.add(id);
12562
+ return [{ ...target, id }];
12563
+ });
12564
+ this.admission.schedulePersistence();
12565
+ }
12330
12566
  return session.sandbox.markTargetReplaced(previousTargetId, targetId);
12331
12567
  });
12332
12568
  }
12569
+ notifyTargetCleared(sessionId, targetId, reason) {
12570
+ try {
12571
+ this.hooks.onTargetCleared?.(sessionId, targetId, reason);
12572
+ } catch (error) {
12573
+ console.error("Session target cleared hook failed", error);
12574
+ }
12575
+ }
12333
12576
  delete(id) {
12334
12577
  const manager = this;
12335
12578
  return this.admission.withAdmission(id, gen(function* () {
@@ -12347,6 +12590,7 @@ class OpenCodeBrowserSessions {
12347
12590
  yield* manager.admission.commitPersistence(() => sync2(() => {
12348
12591
  manager.sessions.set(id, session);
12349
12592
  }));
12593
+ manager.tombstoneHeldTargets(session);
12350
12594
  yield* manager.releaseSessionTargetOwnership(session);
12351
12595
  yield* manager.closeOpenCodeBrowserSession(session);
12352
12596
  yield* sync2(() => {
@@ -12512,6 +12756,8 @@ class OpenCodeBrowserSessions {
12512
12756
  const targetIds = sessionRelayTargetIds(manager.hooks, session);
12513
12757
  if (session.target)
12514
12758
  targetIds.add(session.target.id);
12759
+ for (const held of session.targets ?? [])
12760
+ targetIds.add(held.id);
12515
12761
  if (Array.from(targetIds).some((id) => options.isTargetBusy?.(id)))
12516
12762
  continue;
12517
12763
  const done = yield* manager.delete(session.id).pipe(map6((result) => result.deleted), orElseSucceed(() => false));
@@ -12631,6 +12877,7 @@ class OpenCodeBrowserSessions {
12631
12877
  for (const id of ids)
12632
12878
  this.notifyTargetOwnershipChange(this.targetOwnership.releaseTargetOwnership(id, session.id));
12633
12879
  delete session.target;
12880
+ delete session.targets;
12634
12881
  return void_3;
12635
12882
  }
12636
12883
  closeSessionRelayTargets(session) {
@@ -14280,7 +14527,7 @@ async function travel(tabId, tab, to, params, send, root) {
14280
14527
  }
14281
14528
  tab.arrivedAt = Date.now();
14282
14529
  if (path.length)
14283
- relayLog("input.move", { tabId, type: params.type, from: `${Math.round(from.x)},${Math.round(from.y)}`, to: `${Math.round(to.x)},${Math.round(to.y)}`, points: path.length, ms: tab.arrivedAt - started });
14530
+ relayLog2("input.move", { tabId, type: params.type, from: `${Math.round(from.x)},${Math.round(from.y)}`, to: `${Math.round(to.x)},${Math.round(to.y)}`, points: path.length, ms: tab.arrivedAt - started });
14284
14531
  }
14285
14532
  async function viewportSize(send) {
14286
14533
  const metrics = await send("Page.getLayoutMetrics", {}).catch(() => {
@@ -14337,7 +14584,7 @@ async function scrollToward(tabId, tab, params, send) {
14337
14584
  break;
14338
14585
  await sleep3(random(90, 240));
14339
14586
  }
14340
- relayLog("input.scroll", { tabId, distance: Math.round(first.offset), scrolled: Math.round(first.offset - at.offset), wheel: Math.round(wheel), ms: Date.now() - started });
14587
+ relayLog2("input.scroll", { tabId, distance: Math.round(first.offset), scrolled: Math.round(first.offset - at.offset), wheel: Math.round(wheel), ms: Date.now() - started });
14341
14588
  }
14342
14589
  function glide(dx, dy) {
14343
14590
  const distance = Math.hypot(dx, dy);
@@ -14863,7 +15110,7 @@ var navigateTopFrameToDataUrl = fnUntraced(function* (options) {
14863
15110
  return navigated;
14864
15111
  }
14865
15112
  yield* sendDebuggerCommand({ tabId, method: "Page.setDocumentContent", params: { frameId, html } });
14866
- relayLog("navigate.data", { tabId, chars: html.length });
15113
+ relayLog2("navigate.data", { tabId, chars: html.length });
14867
15114
  return { frameId: getString2(navigated, "frameId") ?? frameId, loaderId };
14868
15115
  }).pipe(ensuring(sync2(() => {
14869
15116
  blankNavigationWaiters.delete(tabId);
@@ -14912,7 +15159,7 @@ function handleRelayProcessFault(kind, cause, detail, options = {}) {
14912
15159
  const since = benignRejections.count - benignRejections.logged;
14913
15160
  benignRejections.lastLogAt = now;
14914
15161
  benignRejections.logged = benignRejections.count;
14915
- relayLog("process.benignRejections", { count: since, total: benignRejections.count, example: safeErrorMessage(cause).slice(0, 160) });
15162
+ relayLog2("process.benignRejections", { count: since, total: benignRejections.count, example: safeErrorMessage(cause).slice(0, 160) });
14916
15163
  }
14917
15164
  return;
14918
15165
  }
@@ -14954,7 +15201,7 @@ function logProcessFault(kind, cause, detail, disposition) {
14954
15201
  ${safeErrorStack(cause) ?? safeErrorMessage(cause)}`;
14955
15202
  console.error(message);
14956
15203
  if (process.env.OPENCODE_BROWSER_MANAGED_RELAY === "1")
14957
- appendManagedRelayProcessLog(message);
15204
+ appendManagedRelayProcessLog2(message);
14958
15205
  if (debugEnvironmentEnabled(process.env.OPENCODE_BROWSER_DEBUG)) {
14959
15206
  console.error(`[browse relay] ${kind} detail`, detail);
14960
15207
  }
@@ -14972,7 +15219,7 @@ var installRelayProcessGuard = acquireRelease(sync2(() => {
14972
15219
  };
14973
15220
  const onUnhandledRejection = (reason, promise) => {
14974
15221
  if (handleExecuteRealmRejection(promise, reason)) {
14975
- relayLog("process.executeRejection");
15222
+ relayLog2("process.executeRejection");
14976
15223
  return;
14977
15224
  }
14978
15225
  handleRelayProcessFault("unhandledRejection", reason, {});
@@ -15069,7 +15316,7 @@ function createCdpDispatcher(options) {
15069
15316
  const nudges = gen(function* () {
15070
15317
  for (const delayMs of [600, 1000, 1500, 2000, 3000, 5000, 8000]) {
15071
15318
  yield* sleep(delayMs);
15072
- relayLog("screenshot.nudge", { tabId: command.tabId, afterMs: delayMs });
15319
+ relayLog2("screenshot.nudge", { tabId: command.tabId, afterMs: delayMs });
15073
15320
  yield* forkDetach(sendDebuggerCommand({
15074
15321
  tabId: command.tabId,
15075
15322
  method: "Page.captureScreenshot",
@@ -15201,7 +15448,7 @@ function createCdpDispatcher(options) {
15201
15448
  }
15202
15449
  if (target.owner === "user") {
15203
15450
  yield* detachTab(target.tabId);
15204
- relayLog("target.released", { tabId: target.tabId, reason: "Target.closeTarget on a user tab" });
15451
+ relayLog2("target.released", { tabId: target.tabId, reason: "Target.closeTarget on a user tab" });
15205
15452
  return { success: true, released: true, message: "This tab belongs to the user, so it was released to them instead of closed." };
15206
15453
  }
15207
15454
  yield* closeTargetByTargetId(targetId);
@@ -15485,14 +15732,15 @@ function createExtensionEventHandler(options) {
15485
15732
  if (opener.owner === "user" && !sessions.isExecuting(sessionId))
15486
15733
  return;
15487
15734
  const autoAttachParams = Array.from(cdpClients).filter((client) => cdpClients.sessionId(client) === sessionId).map((client) => cdpClients.autoAttachParams(client)).find((params) => params !== undefined);
15488
- relayLog("tab.opened", { tabId, openerTabId, session: sessionId });
15735
+ relayLog2("tab.opened", { tabId, openerTabId, session: sessionId });
15489
15736
  announceTab(tabId);
15490
15737
  const attach = () => runPromise(rootLifecycle.attach({
15491
15738
  tabId,
15492
15739
  owner: "relay",
15493
15740
  opencodeBrowserSessionId: sessionId,
15494
15741
  openerTargetId: opener.targetInfo.targetId,
15495
- ...autoAttachParams ? { autoAttachParams } : {}
15742
+ ...autoAttachParams ? { autoAttachParams } : {},
15743
+ deferHeldTarget: true
15496
15744
  }));
15497
15745
  const attachWithRetry = async () => {
15498
15746
  await Promise.allSettled(Array.from(openedPageReleases.get(openerTabId) ?? []));
@@ -15503,7 +15751,7 @@ function createExtensionEventHandler(options) {
15503
15751
  const message = error instanceof Error ? error.message : String(error);
15504
15752
  if (!/already attached|another debugger/i.test(message) || registry.routingRootTarget(tabId) || !registry.tabTargets.has(openerTabId))
15505
15753
  throw error;
15506
- relayLog("tab.opened.retry", { tabId, delayMs, error: message });
15754
+ relayLog2("tab.opened.retry", { tabId, delayMs, error: message });
15507
15755
  await new Promise((resolve) => setTimeout(resolve, delayMs));
15508
15756
  }
15509
15757
  }
@@ -15511,10 +15759,13 @@ function createExtensionEventHandler(options) {
15511
15759
  };
15512
15760
  attachWithRetry().then(() => {
15513
15761
  const popup = registry.tabTargets.get(tabId);
15514
- if (popup)
15515
- navigationGuard.popupAttached(popup);
15762
+ if (!popup)
15763
+ return;
15764
+ const allowed = navigationGuard.popupAttached(popup);
15765
+ if (allowed && popup.opencodeBrowserSessionId)
15766
+ sessions.noteTargetHeld(popup.targetInfo.targetId, popup.opencodeBrowserSessionId);
15516
15767
  }).catch((error) => {
15517
- relayLog("tab.opened.error", { tabId, error: error instanceof Error ? error.message : String(error) });
15768
+ relayLog2("tab.opened.error", { tabId, error: error instanceof Error ? error.message : String(error) });
15518
15769
  });
15519
15770
  }
15520
15771
  return function handleExtensionMessage(link, raw) {
@@ -15552,37 +15803,58 @@ function createExtensionEventHandler(options) {
15552
15803
  return;
15553
15804
  const failed = settled ? [] : rootLifecycle.failedTabIds(generation);
15554
15805
  if (failed.length > 0) {
15555
- relayLog("extension.inventory.dropped", { tabIds: failed.join(","), generation });
15806
+ relayLog2("extension.inventory.dropped", { tabIds: failed.join(","), generation });
15556
15807
  for (const tabId of failed) {
15557
- detachTargetState(tabId);
15808
+ detachTargetState(tabId, { reason: "inventory-dropped" });
15558
15809
  sendExtensionBestEffort({ method: "debugger.detach", params: { tabId } });
15559
15810
  }
15560
15811
  }
15561
15812
  if (settled || failed.length > 0) {
15562
15813
  for (const target of registry.listRootTargets()) {
15563
15814
  if (mine(target.tabId) && !announcedRootTabIds.has(target.tabId))
15564
- detachTargetState(target.tabId);
15815
+ detachTargetState(target.tabId, { reason: "inventory-missing" });
15565
15816
  }
15566
15817
  for (const [targetId, known] of ownersAcrossReconnect) {
15567
- if (known.browser !== link.key)
15818
+ if (known.browser !== link.key && known.browser !== "")
15568
15819
  continue;
15569
- if (known.owner !== "relay" || known.sessionId === undefined || sessions.sessions.has(known.sessionId))
15820
+ if (known.owner !== "relay" || known.sessionId === undefined)
15821
+ continue;
15822
+ if (known.deleted !== true && sessions.sessions.has(known.sessionId))
15570
15823
  continue;
15571
15824
  const target = registry.targetsByTargetId.get(targetId);
15572
- if (!target || target.opencodeBrowserSessionId !== undefined)
15825
+ if (!target || known.deleted !== true && target.opencodeBrowserSessionId !== undefined)
15573
15826
  continue;
15574
- relayLog("extension.inventory.orphan", { tabId: target.tabId, session: known.sessionId });
15827
+ relayLog2("extension.inventory.orphan", { tabId: target.tabId, session: known.sessionId, reason: "session deleted" });
15575
15828
  sendExtensionBestEffort({ method: "tabs.remove", params: { tabId: target.tabId } });
15576
- detachTargetState(target.tabId, { updateExtension: false });
15829
+ detachTargetState(target.tabId, { updateExtension: false, reason: "session-deleted" });
15830
+ ownersAcrossReconnect.delete(targetId);
15831
+ }
15832
+ if (settled) {
15833
+ for (const [targetId, known] of ownersAcrossReconnect) {
15834
+ if (known.browser === "")
15835
+ ownersAcrossReconnect.delete(targetId);
15836
+ }
15577
15837
  }
15578
15838
  for (const target of registry.listRootTargets()) {
15579
15839
  if (!announcedAgentTabIds.has(target.tabId) || target.owner !== "user" || target.opencodeBrowserSessionId !== undefined)
15580
15840
  continue;
15581
- if (ownersAcrossReconnect.get(target.targetInfo.targetId)?.owner === "user")
15841
+ const known = ownersAcrossReconnect.get(target.targetInfo.targetId);
15842
+ if (known?.owner === "user")
15582
15843
  continue;
15583
- relayLog("extension.inventory.orphan", { tabId: target.tabId, reason: "agent tab without a session" });
15584
- sendExtensionBestEffort({ method: "tabs.remove", params: { tabId: target.tabId } });
15585
- detachTargetState(target.tabId, { updateExtension: false });
15844
+ if (!link.rpc.supports(extensionCapabilityTabRelease)) {
15845
+ relayLog2("extension.inventory.orphan", {
15846
+ tabId: target.tabId,
15847
+ reason: `${known ? "relay-owned tab without a session" : "agent tab without a session"} (extension has no release support)`
15848
+ });
15849
+ sendExtensionBestEffort({ method: "tabs.remove", params: { tabId: target.tabId } });
15850
+ detachTargetState(target.tabId, { updateExtension: false, reason: "session-deleted" });
15851
+ continue;
15852
+ }
15853
+ relayLog2("extension.inventory.released", { tabId: target.tabId, reason: known ? "relay-owned tab without a session" : "agent tab without a session" });
15854
+ sendExtensionBestEffort({ method: "debugger.detach", params: { tabId: target.tabId, release: true } });
15855
+ sendExtensionBestEffort({ method: "pageStatus.clear", params: { tabId: target.tabId } });
15856
+ sendExtensionBestEffort({ method: "action.setAttached", params: { tabId: target.tabId, attached: false } });
15857
+ detachTargetState(target.tabId, { updateExtension: false, reason: "released" });
15586
15858
  }
15587
15859
  announcedAgentTabIds.clear();
15588
15860
  for (const [targetId, known] of ownersAcrossReconnect)
@@ -15596,6 +15868,16 @@ function createExtensionEventHandler(options) {
15596
15868
  if (mine(target.tabId))
15597
15869
  refreshTabGrouping(target.tabId);
15598
15870
  browsersChanged();
15871
+ if (settled && link.rpc.supports(extensionCapabilityTabRelease)) {
15872
+ const liveTargetIds = new Set(registry.listRootTargets().filter((target) => mine(target.tabId)).map((target) => target.targetInfo.targetId));
15873
+ const pruned = sessions.pruneHeldTargets({
15874
+ browserKey: link.key,
15875
+ liveTargetIds,
15876
+ includeUnknownBrowser: browsers.list().length === 1 && browsers.knownBrowser(undefined) !== undefined
15877
+ });
15878
+ if (pruned.length > 0)
15879
+ relayLog2("extension.inventory.pruned", { browser: link.id, targets: pruned.length });
15880
+ }
15599
15881
  if (!sweptBrowsers.has(link.key)) {
15600
15882
  sweptBrowsers.add(link.key);
15601
15883
  runPromise(sessions.sweepOrphanedRelayTargets());
@@ -15609,9 +15891,10 @@ function createExtensionEventHandler(options) {
15609
15891
  if (extensionMethod === "debugger.attached") {
15610
15892
  if (eventTabId) {
15611
15893
  announcedRootTabIds.add(eventTabId);
15612
- if (message.params?.agent === true)
15894
+ const announcedAgent = message.params?.agent === true;
15895
+ if (announcedAgent)
15613
15896
  announcedAgentTabIds.add(eventTabId);
15614
- rootLifecycle.queue({ tabId: eventTabId, attachIfMissing: true, verificationRetries: 0, errorMessage: "Debugger re-announce failed", generation });
15897
+ rootLifecycle.queue({ tabId: eventTabId, attachIfMissing: true, verificationRetries: 0, errorMessage: "Debugger re-announce failed", generation, announcedAgent });
15615
15898
  }
15616
15899
  return;
15617
15900
  }
@@ -15654,7 +15937,7 @@ function createExtensionEventHandler(options) {
15654
15937
  if (eventTabId) {
15655
15938
  const renewed = message.params?.reattached === true;
15656
15939
  if (renewed)
15657
- relayLog("debugger.renewed", { tabId: eventTabId });
15940
+ relayLog2("debugger.renewed", { tabId: eventTabId });
15658
15941
  rootLifecycle.queue({
15659
15942
  tabId: eventTabId,
15660
15943
  attachIfMissing: false,
@@ -15668,12 +15951,12 @@ function createExtensionEventHandler(options) {
15668
15951
  if (reason === "canceled_by_user") {
15669
15952
  if (eventTabId) {
15670
15953
  handleDebuggingBarCancel(eventTabId);
15671
- detachTargetState(eventTabId, { releasedByUser: true });
15954
+ detachTargetState(eventTabId, { releasedByUser: true, reason: "released-by-user" });
15672
15955
  }
15673
15956
  return;
15674
15957
  }
15675
15958
  if (eventTabId)
15676
- detachTargetState(eventTabId);
15959
+ detachTargetState(eventTabId, { reason: "debugger-detached" });
15677
15960
  return;
15678
15961
  }
15679
15962
  if (extensionMethod === "tabs.opened") {
@@ -15684,7 +15967,7 @@ function createExtensionEventHandler(options) {
15684
15967
  }
15685
15968
  if (extensionMethod === "tabs.removed") {
15686
15969
  if (eventTabId)
15687
- detachTargetState(eventTabId);
15970
+ detachTargetState(eventTabId, { reason: "tab-closed" });
15688
15971
  return;
15689
15972
  }
15690
15973
  if (extensionMethod !== "debugger.event" || !eventTabId) {
@@ -15934,7 +16217,7 @@ class ExtensionHandshake {
15934
16217
  for (const link of links)
15935
16218
  link.socket.close(4006, "Pairing revoked: run `pair` and enter the code to pair again");
15936
16219
  if (links.length)
15937
- relayLog("extension.revoked", { browser: links.map((link) => link.id).join(", ") });
16220
+ relayLog2("extension.revoked", { browser: links.map((link) => link.id).join(", ") });
15938
16221
  return links.length > 0;
15939
16222
  }
15940
16223
  reloadOutdatedDevExtension(link) {
@@ -15944,7 +16227,7 @@ class ExtensionHandshake {
15944
16227
  if (link.build === folderBuild || this.devExtensionReloadedFor === folderBuild)
15945
16228
  return;
15946
16229
  this.devExtensionReloadedFor = folderBuild;
15947
- relayLog("extension.dev_reload", { browser: link.id, from: link.build, to: folderBuild });
16230
+ relayLog2("extension.dev_reload", { browser: link.id, from: link.build, to: folderBuild });
15948
16231
  this.options.sendExtensionBestEffort({ method: "runtime.reload" }, link);
15949
16232
  }
15950
16233
  resolveSessionBrowser(requested, session) {
@@ -16026,7 +16309,7 @@ class ExtensionHandshake {
16026
16309
  const handshakeTimer = setTimeout(() => {
16027
16310
  if (handshaken)
16028
16311
  return;
16029
- relayLog("extension.rejected", { reason: "handshake timeout", ms: preAuthHandshakeTimeoutMs });
16312
+ relayLog2("extension.rejected", { reason: "handshake timeout", ms: preAuthHandshakeTimeoutMs });
16030
16313
  socket.close(1008, "Handshake timed out");
16031
16314
  }, preAuthHandshakeTimeoutMs);
16032
16315
  handshakeTimer.unref();
@@ -16042,7 +16325,7 @@ class ExtensionHandshake {
16042
16325
  if (!handshaken) {
16043
16326
  const bytes = rawDataByteLength(data);
16044
16327
  if (bytes > maxPreAuthMessageBytes) {
16045
- relayLog("extension.rejected", { reason: "message too large before pairing", bytes });
16328
+ relayLog2("extension.rejected", { reason: "message too large before pairing", bytes });
16046
16329
  socket.close(1009, "Message too large before pairing");
16047
16330
  return;
16048
16331
  }
@@ -16091,7 +16374,7 @@ class ExtensionHandshake {
16091
16374
  const proof = message.method === "auth.response" ? getString2(message.params, "proof") : undefined;
16092
16375
  if (challenge.expected === undefined || !secretsEqual(challenge.expected, proof)) {
16093
16376
  this.pairingRefused();
16094
- relayLog("extension.rejected", { reason: "pairing failed", mode: challenge.mode, profile: getString2(getObject2(challenge.hello.params), "profileName") });
16377
+ relayLog2("extension.rejected", { reason: "pairing failed", mode: challenge.mode, profile: getString2(getObject2(challenge.hello.params), "profileName") });
16095
16378
  socket.close(4006, "Pairing failed: this browser isn't paired with this relay");
16096
16379
  return;
16097
16380
  }
@@ -16129,12 +16412,12 @@ class ExtensionHandshake {
16129
16412
  }
16130
16413
  });
16131
16414
  socket.on("error", (error) => {
16132
- relayLog("extension.error", { error: error.message, code: error.code });
16415
+ relayLog2("extension.error", { error: error.message, code: error.code });
16133
16416
  });
16134
16417
  socket.on("close", (code, reason) => {
16135
16418
  clearTimeout(handshakeTimer);
16136
16419
  const gone = browsers.disconnect(socket);
16137
- relayLog("extension.close", { code, reason: reason.toString() || undefined, browser: gone?.id, current: gone !== undefined });
16420
+ relayLog2("extension.close", { code, reason: reason.toString() || undefined, browser: gone?.id, current: gone !== undefined });
16138
16421
  if (gone) {
16139
16422
  this.options.clearLiveExtensionState(gone.key, "Extension disconnected");
16140
16423
  this.options.browsersChanged();
@@ -16156,7 +16439,7 @@ class ExtensionHandshake {
16156
16439
  const extensionNonce = getString2(pairing, "nonce");
16157
16440
  if (extensionNonce === undefined) {
16158
16441
  this.pairingRefused();
16159
- relayLog("extension.rejected", { reason: "no pairing (extension too old)", version: getString2(params, "version") });
16442
+ relayLog2("extension.rejected", { reason: "no pairing (extension too old)", version: getString2(params, "version") });
16160
16443
  if (!this.legacyExtensionReloaded && origin === stableUnpackedExtensionOrigin2) {
16161
16444
  this.legacyExtensionReloaded = true;
16162
16445
  socket.send(JSON.stringify({ id: 0, method: "runtime.reload" }));
@@ -16177,7 +16460,7 @@ class ExtensionHandshake {
16177
16460
  }
16178
16461
  const refuse = (reason, text) => {
16179
16462
  this.pairingRefused();
16180
- relayLog("extension.rejected", { reason, mode, profile: getString2(params, "profileName") });
16463
+ relayLog2("extension.rejected", { reason, mode, profile: getString2(params, "profileName") });
16181
16464
  socket.close(4006, text);
16182
16465
  return;
16183
16466
  };
@@ -16213,7 +16496,7 @@ class ExtensionHandshake {
16213
16496
  return refuse("shared code retired", "The old pairing code is no longer accepted: run `pair` and enter the new code");
16214
16497
  const session = pairingSessionKey(legacy, exchange.secret, transcript);
16215
16498
  const token = newBrowserToken();
16216
- relayLog("extension.pairing", { mode });
16499
+ relayLog2("extension.pairing", { mode });
16217
16500
  socket.send(JSON.stringify({
16218
16501
  method: "auth.challenge",
16219
16502
  params: { nonce: relayNonce, ecdh: exchange.publicKey, proof: sessionProof(session, "relay"), wrapped: wrapToken(session, token), protocol }
@@ -16228,13 +16511,13 @@ class ExtensionHandshake {
16228
16511
  if (!match) {
16229
16512
  this.pairingRefused();
16230
16513
  const exhausted = recordPairingFailure();
16231
- relayLog("extension.rejected", { reason: "wrong pairing code", exhausted, profile: getString2(getObject2(challenge.hello.params), "profileName") });
16514
+ relayLog2("extension.rejected", { reason: "wrong pairing code", exhausted, profile: getString2(getObject2(challenge.hello.params), "profileName") });
16232
16515
  socket.close(4006, exhausted ? "Too many wrong codes: run `pair` for a new one" : "Pairing failed: that code is wrong, used or expired");
16233
16516
  return;
16234
16517
  }
16235
16518
  const receipt = consumePairingCode(match.codeKey);
16236
16519
  const token = issueBrowserToken(challenge.key, undefined, Date.now(), undefined, receipt);
16237
- relayLog("extension.paired", { profile: getString2(getObject2(challenge.hello.params), "profileName") });
16520
+ relayLog2("extension.paired", { profile: getString2(getObject2(challenge.hello.params), "profileName") });
16238
16521
  socket.send(JSON.stringify({ method: "auth.token", params: { proof: sessionProof(match.session, "relay"), wrapped: wrapToken(match.session, token) } }));
16239
16522
  challenge.expected = pairingProof(token, "extension", this.options.port, challenge.extensionNonce, challenge.relayNonce);
16240
16523
  }
@@ -16251,7 +16534,7 @@ class ExtensionHandshake {
16251
16534
  replaced.socket.close(4001, "Extension replaced");
16252
16535
  this.options.clearLiveExtensionState(replaced.key, "Extension replaced");
16253
16536
  }
16254
- link.rpc.markHandshake(getString2(message.params, "version"), message.params?.protocolVersion);
16537
+ link.rpc.markHandshake(getString2(message.params, "version"), message.params?.protocolVersion, message.params?.capabilities);
16255
16538
  link.build = getString2(message.params, "build");
16256
16539
  link.origin = origin;
16257
16540
  link.local = local;
@@ -16261,7 +16544,7 @@ class ExtensionHandshake {
16261
16544
  this.reloadOutdatedDevExtension(link);
16262
16545
  }, 2000).unref();
16263
16546
  }
16264
- relayLog("extension.connected", {
16547
+ relayLog2("extension.connected", {
16265
16548
  browser: link.id,
16266
16549
  name: link.name,
16267
16550
  version: getString2(message.params, "version"),
@@ -16372,7 +16655,7 @@ function createRelayHousekeeping(options) {
16372
16655
  return busy.length ? { reason: "recordings", detail: busy.slice(0, 5).join(", ") + (busy.length > 5 ? ` and ${busy.length - 5} more` : "") } : undefined;
16373
16656
  },
16374
16657
  release: gen(function* () {
16375
- relayLog("relay.restart.force", {});
16658
+ relayLog2("relay.restart.force", {});
16376
16659
  for (const capture of sessions.activeNetworkCaptures())
16377
16660
  yield* sessions.networkEnd(capture.sessionId, "the relay was restarted with --force");
16378
16661
  yield* promise(() => recordingRelay.cleanupAll().catch(() => {}));
@@ -16403,7 +16686,7 @@ function createRelayHousekeeping(options) {
16403
16686
  const id = session.id;
16404
16687
  runPromise(gen(function* () {
16405
16688
  if (yield* sessions.networkEnd(id, `its client (process ${pid}) exited`))
16406
- relayLog("session.capture.ended", { session: id, reason: "client gone", pid });
16689
+ relayLog2("session.capture.ended", { session: id, reason: "client gone", pid });
16407
16690
  if (!isMcpSession(id) || sessions.isExecuting(id) || sessions.hasPendingWork(id))
16408
16691
  return;
16409
16692
  const tabs = registry.listRootTargets().filter((target) => target.opencodeBrowserSessionId === id).map((target) => target.tabId);
@@ -16411,7 +16694,7 @@ function createRelayHousekeeping(options) {
16411
16694
  return;
16412
16695
  if (activeHandoffTabs.has(id))
16413
16696
  return;
16414
- relayLog("session.collected", { session: id, reason: "client gone", pid, tabs: tabs.length });
16697
+ relayLog2("session.collected", { session: id, reason: "client gone", pid, tabs: tabs.length });
16415
16698
  clientGoneSince.delete(id);
16416
16699
  yield* sessions.delete(id);
16417
16700
  }).pipe(ignore)).catch(() => {});
@@ -16535,9 +16818,9 @@ function createRelaySettingsSync(options) {
16535
16818
  const autoUpdate = params?.autoUpdate;
16536
16819
  if (typeof autoUpdate === "string" && autoUpdateModes.includes(autoUpdate)) {
16537
16820
  setStoredMode(autoUpdate);
16538
- relayLog("autoupdate.mode", { mode: autoUpdate });
16821
+ relayLog2("autoupdate.mode", { mode: autoUpdate });
16539
16822
  }
16540
- relayLog("extension.settings", { browser: link.id, humanInput: humanInputEnabled(link.humanInput) ? "on" : "off" });
16823
+ relayLog2("extension.settings", { browser: link.id, humanInput: humanInputEnabled(link.humanInput) ? "on" : "off" });
16541
16824
  if (link.rpc.connected)
16542
16825
  sendRelaySettings();
16543
16826
  else
@@ -16567,7 +16850,7 @@ function createRelaySettingsSync(options) {
16567
16850
  const after = withRelaySettings(Object.keys(extensionChanges).length ? yield* extensionSettings("settings.set", extensionChanges) : fromExtension ?? before);
16568
16851
  if (writable.autoUpdate !== undefined)
16569
16852
  sendRelaySettings();
16570
- relayLog("settings.set", { changes: Object.keys(writable).join(",") || undefined, overridden: Object.keys(requested).filter((key) => (key in overrides)).join(",") || undefined });
16853
+ relayLog2("settings.set", { changes: Object.keys(writable).join(",") || undefined, overridden: Object.keys(requested).filter((key) => (key in overrides)).join(",") || undefined });
16571
16854
  return describeChanges({ before, after, requested, overrides });
16572
16855
  })
16573
16856
  };
@@ -16793,14 +17076,14 @@ function createTabPresentation(options) {
16793
17076
  sessionExecuting: sessionId !== undefined && sessions.isExecuting(sessionId)
16794
17077
  });
16795
17078
  if (action === "complete-handoff" && pending) {
16796
- relayLog("handoff.completed", { tabId, from: "toolbar" });
17079
+ relayLog2("handoff.completed", { tabId, from: "toolbar" });
16797
17080
  if (handoffs.complete({ id: pending.id, tabId, targetId: target.targetInfo.targetId, targetSessionId: target.sessionId })) {
16798
17081
  refreshPageStatus(tabId);
16799
17082
  }
16800
17083
  return;
16801
17084
  }
16802
17085
  if (action === "stop-execution" && sessionId) {
16803
- relayLog("execute.stopped", { tabId, session: sessionId, from: "toolbar" });
17086
+ relayLog2("execute.stopped", { tabId, session: sessionId, from: "toolbar" });
16804
17087
  sessions.stopExecution(sessionId, `The user took tab ${tabId} back (browse toolbar button) while this script ran, so it was stopped. Don't use that tab again unless the user lends it back; ask the user how to continue.`);
16805
17088
  }
16806
17089
  }
@@ -16815,7 +17098,7 @@ function createTabPresentation(options) {
16815
17098
  return;
16816
17099
  const sessionId = pageStatusSessionId(target) ?? activeHandoffSessionIdForTab(tabId);
16817
17100
  if (sessionId && sessions.isExecuting(sessionId)) {
16818
- relayLog("execute.stopped", { tabId, session: sessionId, from: "debugging-bar" });
17101
+ relayLog2("execute.stopped", { tabId, session: sessionId, from: "debugging-bar" });
16819
17102
  sessions.stopExecution(sessionId, debuggingBarDismissedStop, "debugging-bar-cancel");
16820
17103
  }
16821
17104
  }
@@ -16910,13 +17193,13 @@ function createRelayTransportServers(deps) {
16910
17193
  const pathname = (request.url ?? "").split("?")[0];
16911
17194
  if (isSilentProbePath(pathname))
16912
17195
  return;
16913
- relayLog("http", { method: request.method, path: pathname, status: response.statusCode, ms: Math.round(performance.now() - started) });
17196
+ relayLog2("http", { method: request.method, path: pathname, status: response.statusCode, ms: Math.round(performance.now() - started) });
16914
17197
  });
16915
17198
  relayRequestHandler(request, response);
16916
17199
  });
16917
17200
  httpServer.requestTimeout = 0;
16918
17201
  httpServer.timeout = 0;
16919
- httpServer.on("error", (error) => relayLog("http.error", { error: error.message, code: error.code }));
17202
+ httpServer.on("error", (error) => relayLog2("http.error", { error: error.message, code: error.code }));
16920
17203
  const websocketServer = new WebSocketServer({ noServer: true, maxPayload: 256 * 1024 * 1024 });
16921
17204
  httpServer.on("upgrade", (request, socket, head) => {
16922
17205
  if (!isReady()) {
@@ -16992,7 +17275,7 @@ function createRelayTransportServers(deps) {
16992
17275
  });
16993
17276
  });
16994
17277
  socket.on("error", (error) => {
16995
- relayLog("client.error", { session: cdpClients.sessionId(socket), error: error.message, code: error.code });
17278
+ relayLog2("client.error", { session: cdpClients.sessionId(socket), error: error.message, code: error.code });
16996
17279
  });
16997
17280
  socket.on("close", () => {
16998
17281
  debugLog?.(`client- ${cdpClients.sessionId(socket) ?? "raw"} total=${cdpClients.size - 1}`);
@@ -17072,6 +17355,7 @@ class RootTargetLifecycle {
17072
17355
  if (existing) {
17073
17356
  existing.pending = true;
17074
17357
  existing.attachIfMissing ||= options.attachIfMissing;
17358
+ existing.reclaimHeldTargets ||= options.announcedAgent === true;
17075
17359
  existing.renewed ||= options.renewed === true;
17076
17360
  existing.verificationRetries = Math.max(existing.verificationRetries, options.verificationRetries);
17077
17361
  return;
@@ -17081,6 +17365,7 @@ class RootTargetLifecycle {
17081
17365
  generation,
17082
17366
  done: makeUnsafe2(),
17083
17367
  attachIfMissing: options.attachIfMissing,
17368
+ reclaimHeldTargets: options.announcedAgent === true,
17084
17369
  renewed: options.renewed === true,
17085
17370
  pending: false,
17086
17371
  verificationRetries: options.verificationRetries
@@ -17090,6 +17375,8 @@ class RootTargetLifecycle {
17090
17375
  worker.pending = false;
17091
17376
  const mayAttach = worker.attachIfMissing;
17092
17377
  worker.attachIfMissing = false;
17378
+ const reclaimHeldTargets = worker.reclaimHeldTargets;
17379
+ worker.reclaimHeldTargets = false;
17093
17380
  const renewed = worker.renewed;
17094
17381
  worker.renewed = false;
17095
17382
  yield* suspend2(() => {
@@ -17105,9 +17392,10 @@ class RootTargetLifecycle {
17105
17392
  ...root.opencodeBrowserSessionId ? { opencodeBrowserSessionId: root.opencodeBrowserSessionId } : {}
17106
17393
  }).pipe(asVoid2);
17107
17394
  }
17108
- if (lifecycle.options.registry.routingRootTarget(options.tabId))
17109
- return lifecycle.reconcileUnlocked(transition);
17110
- return mayAttach ? lifecycle.attachUnlocked(transition, { tabId: options.tabId, owner: "user", alreadyAttached: true }).pipe(asVoid2) : void_3;
17395
+ if (lifecycle.options.registry.routingRootTarget(options.tabId)) {
17396
+ return lifecycle.reconcileUnlocked(transition, !lifecycle.options.extension.supportsTargetRelease(options.tabId));
17397
+ }
17398
+ return mayAttach ? lifecycle.attachUnlocked(transition, { tabId: options.tabId, owner: "user", alreadyAttached: true, reclaimHeldTargets }).pipe(asVoid2) : void_3;
17111
17399
  }, lifecycle.options.inventoryCommandTimeoutMs ?? DEFAULT_INVENTORY_COMMAND_TIMEOUT_MS);
17112
17400
  }).pipe(tapError((error) => sync2(() => lifecycle.options.reportError(options.errorMessage, error))), retry({
17113
17401
  times: 2,
@@ -17224,19 +17512,39 @@ class RootTargetLifecycle {
17224
17512
  if (!reportedTargetInfo)
17225
17513
  return yield* fail6(new Error("Target.getTargetInfo did not return targetInfo"));
17226
17514
  const targetInfo = options.openerTargetId && !reportedTargetInfo.openerId ? { ...reportedTargetInfo, openerId: options.openerTargetId } : reportedTargetInfo;
17227
- const restored = options.opencodeBrowserSessionId ? undefined : this.options.sessions.persistedTargetOwner(targetInfo.targetId);
17228
- const opencodeBrowserSessionId = options.opencodeBrowserSessionId ?? restored?.sessionId;
17515
+ let publishedTargetInfo = targetInfo;
17516
+ const supportsTargetRelease = this.options.extension.supportsTargetRelease(tabId);
17517
+ const legacyOwnership = !supportsTargetRelease;
17518
+ const browserKey = legacyOwnership ? undefined : this.options.browserKeyForTab?.(tabId);
17519
+ const restored = options.opencodeBrowserSessionId || options.restoreOwnership === false ? undefined : this.options.sessions.persistedTargetOwner(targetInfo.targetId, {
17520
+ includeHeldTargets: !legacyOwnership && options.reclaimHeldTargets === true,
17521
+ ...legacyOwnership ? { legacy: true } : {},
17522
+ ...browserKey ? { browserKey } : {}
17523
+ });
17524
+ let owner = restored?.owner ?? options.owner;
17525
+ let opencodeBrowserSessionId = options.opencodeBrowserSessionId ?? restored?.sessionId;
17526
+ if (owner === "relay" && opencodeBrowserSessionId && !options.opencodeBrowserSessionId && this.options.authorizeRestoredTarget && !this.options.authorizeRestoredTarget({
17527
+ tabId,
17528
+ targetId: targetInfo.targetId,
17529
+ url: targetInfo.url,
17530
+ owner,
17531
+ sessionId: opencodeBrowserSessionId
17532
+ })) {
17533
+ owner = "user";
17534
+ opencodeBrowserSessionId = undefined;
17535
+ publishedTargetInfo = { ...targetInfo, url: "about:blank", title: "" };
17536
+ }
17229
17537
  const target = this.options.registry.stageRootTarget({
17230
17538
  tabId,
17231
17539
  sessionId: `bc-tab-${this.nextSessionId++}`,
17232
- targetInfo,
17233
- owner: restored?.owner ?? options.owner,
17540
+ targetInfo: publishedTargetInfo,
17541
+ owner,
17234
17542
  ...opencodeBrowserSessionId ? { opencodeBrowserSessionId } : {}
17235
17543
  });
17236
17544
  transition.staged = target;
17237
- return yield* this.finish(transition, target, options.autoAttachParams);
17545
+ return yield* this.finish(transition, target, options.autoAttachParams, options.deferHeldTarget === true, legacyOwnership, options.restoreOwnership === false);
17238
17546
  });
17239
- reconcileUnlocked = fnUntraced(function* (transition) {
17547
+ reconcileUnlocked = fnUntraced(function* (transition, legacyOwnership = false) {
17240
17548
  const { registry } = this.options;
17241
17549
  const expected = registry.tabTargets.get(transition.tabId);
17242
17550
  const staged = registry.stagedRootTarget(transition.tabId);
@@ -17249,7 +17557,7 @@ class RootTargetLifecycle {
17249
17557
  return yield* fail6(new Error(staged ? "Unable to verify staged root target" : "Unable to verify committed root target"));
17250
17558
  }
17251
17559
  if (staged?.targetInfo.targetId === targetInfo.targetId) {
17252
- yield* this.finish(transition, staged);
17560
+ yield* this.finish(transition, staged, undefined, false, legacyOwnership);
17253
17561
  return;
17254
17562
  }
17255
17563
  if (!staged && expected?.targetInfo.targetId === targetInfo.targetId)
@@ -17264,7 +17572,7 @@ class RootTargetLifecycle {
17264
17572
  ...owner.opencodeBrowserSessionId ? { opencodeBrowserSessionId: owner.opencodeBrowserSessionId } : {}
17265
17573
  });
17266
17574
  });
17267
- finish = fnUntraced(function* (transition, target, autoAttachParams) {
17575
+ finish = fnUntraced(function* (transition, target, autoAttachParams, deferHeldTarget = false, legacyOwnership = false, releasedByUser = false) {
17268
17576
  const { registry, handoffs, sessions, clients, presentation } = this.options;
17269
17577
  yield* this.command(transition, "Target.setAutoAttach", autoAttachParams ?? { autoAttach: true, waitForDebuggerOnStart: false, flatten: true });
17270
17578
  const result = yield* this.command(transition, "Target.getTargetInfo");
@@ -17288,6 +17596,16 @@ class RootTargetLifecycle {
17288
17596
  clients.detachTab(target.tabId);
17289
17597
  presentation.replaced(change);
17290
17598
  }
17599
+ if (!deferHeldTarget) {
17600
+ if (change.target.owner === "relay" && change.target.opencodeBrowserSessionId) {
17601
+ sessions.noteTargetHeld(change.target.targetInfo.targetId, change.target.opencodeBrowserSessionId);
17602
+ } else if (!legacyOwnership) {
17603
+ sessions.forgetTargetHeld(change.target.targetInfo.targetId, {
17604
+ releasedByUser,
17605
+ reason: releasedByUser ? "released-by-user" : "released"
17606
+ });
17607
+ }
17608
+ }
17291
17609
  presentation.committed(change.target);
17292
17610
  presentation.announceRoot(change.target);
17293
17611
  for (const child of registry.childTargets.values()) {
@@ -17305,6 +17623,14 @@ import fs12 from "node:fs/promises";
17305
17623
  import os5 from "node:os";
17306
17624
  import path9 from "node:path";
17307
17625
  import crypto8 from "node:crypto";
17626
+ var PersistedTarget = Struct({
17627
+ id: String3,
17628
+ owner: Literals(["relay", "user"])
17629
+ });
17630
+ var PersistedRelayTarget = Struct({
17631
+ id: String3,
17632
+ owner: Literal("relay")
17633
+ });
17308
17634
  var PersistedSession = Struct({
17309
17635
  id: String3,
17310
17636
  createdAt: String3,
@@ -17314,16 +17640,37 @@ var PersistedSession = Struct({
17314
17640
  keepVisible: optionalKey(Boolean3),
17315
17641
  browser: optionalKey(String3),
17316
17642
  browserKey: optionalKey(String3),
17317
- target: optionalKey(Struct({
17318
- id: String3,
17319
- owner: Literals(["relay", "user"])
17320
- })),
17643
+ target: optionalKey(PersistedTarget),
17644
+ targets: optionalKey(ArraySchema(PersistedRelayTarget)),
17321
17645
  clientPid: optionalKey(Int2)
17322
17646
  });
17323
17647
  var Catalog = Struct({
17324
17648
  version: Literal(1),
17325
17649
  sessions: ArraySchema(PersistedSession)
17326
17650
  });
17651
+ function relayOwnedCatalog(input) {
17652
+ if (input === null || typeof input !== "object" || Array.isArray(input))
17653
+ return { value: input, dropped: 0 };
17654
+ const catalog = input;
17655
+ if (!Array.isArray(catalog.sessions))
17656
+ return { value: input, dropped: 0 };
17657
+ let dropped = 0;
17658
+ const sessions = catalog.sessions.map((session) => {
17659
+ if (session === null || typeof session !== "object" || Array.isArray(session))
17660
+ return session;
17661
+ const entry = session;
17662
+ if (!Array.isArray(entry.targets))
17663
+ return session;
17664
+ const targets = entry.targets.filter((target) => {
17665
+ const keep = target !== null && typeof target === "object" && !Array.isArray(target) && target.owner === "relay";
17666
+ if (!keep)
17667
+ dropped++;
17668
+ return keep;
17669
+ });
17670
+ return { ...entry, targets };
17671
+ });
17672
+ return { value: { ...catalog, sessions }, dropped };
17673
+ }
17327
17674
  function defaultSessionCatalogPath(port, home = os5.homedir()) {
17328
17675
  return path9.join(dataRoot(home), "relays", String(port), "sessions.json");
17329
17676
  }
@@ -17343,10 +17690,14 @@ class SessionCatalog {
17343
17690
  throw new Error(`Could not read browse session catalog at ${this.filePath}`, { cause: error });
17344
17691
  }
17345
17692
  try {
17346
- const sessions = decodeUnknownSync(Catalog)(JSON.parse(text)).sessions;
17693
+ const sanitized = relayOwnedCatalog(JSON.parse(text));
17694
+ const sessions = decodeUnknownSync(Catalog)(sanitized.value).sessions;
17347
17695
  const invalid = sessions.find((session) => !isValidSessionId2(session.id));
17348
17696
  if (invalid)
17349
17697
  throw new Error(`Invalid persisted session id: ${invalid.id}`);
17698
+ if (sanitized.dropped > 0) {
17699
+ console.error(`Browse session catalog at ${this.filePath} held ${sanitized.dropped} non-relay target(s); dropped them`);
17700
+ }
17350
17701
  return sessions;
17351
17702
  } catch (error) {
17352
17703
  const detail = error instanceof Error && error.message ? `: ${error.message}` : "";
@@ -17455,9 +17806,9 @@ class SessionNavigationGuard {
17455
17806
  }
17456
17807
  popupAttached(target) {
17457
17808
  if (!this.enforced(target))
17458
- return;
17809
+ return true;
17459
17810
  this.freshPopups.add(target.tabId);
17460
- this.observeCommittedUrl(target, target.targetInfo.url);
17811
+ return this.observeCommittedUrl(target, target.targetInfo.url);
17461
17812
  }
17462
17813
  createdTabNavigated(target) {
17463
17814
  if (!this.enforced(target))
@@ -17720,7 +18071,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17720
18071
  method: "Emulation.setFocusEmulationEnabled",
17721
18072
  params: { enabled }
17722
18073
  }));
17723
- const browsersChanged = () => relayLog("browsers", { connected: browsers.list().map((link) => `${link.id}${link.rpc.connected ? "" : " (starting)"}`).join(", ") || "none" });
18074
+ const browsersChanged = () => relayLog2("browsers", { connected: browsers.list().map((link) => `${link.id}${link.rpc.connected ? "" : " (starting)"}`).join(", ") || "none" });
17724
18075
  const announceTab = (tabId) => browsers.browserTab(tabId)?.link.announcedRootTabIds.add(tabId);
17725
18076
  const presentation = createTabPresentation({
17726
18077
  registry,
@@ -17864,11 +18215,18 @@ var makeRelay = fnUntraced(function* (options = {}) {
17864
18215
  return appendJournalEntry({ baseDir: journalBaseDir, entry });
17865
18216
  },
17866
18217
  onTargetOwnershipChange: (change) => reconcileTargetOwnership(change),
18218
+ onTargetCleared: (sessionId, targetId, reason) => relayLog2("session.target.cleared", { session: sessionId, target: targetId, reason }),
18219
+ onRestoreWarning: (detail) => relayLog2("session.restore.dropped", { detail }),
18220
+ onTombstoneRelayTargets: (sessionId, targetIds, browserKey) => {
18221
+ for (const targetId of targetIds) {
18222
+ ownersAcrossReconnect.set(targetId, { browser: browserKey ?? "", owner: "relay", sessionId, deleted: true });
18223
+ }
18224
+ },
17867
18225
  onReleaseRelayTarget: (targetId) => releaseRelayTarget(targetId),
17868
18226
  getTargets: () => registry.listRootTargets(),
17869
18227
  relayTargetIdsForSession: (sessionId) => [
17870
18228
  ...registry.listRootTargets().filter((target) => target.owner === "relay" && target.opencodeBrowserSessionId === sessionId).map((target) => target.targetInfo.targetId),
17871
- ...Array.from(ownersAcrossReconnect).filter(([targetId, known]) => known.owner === "relay" && known.sessionId === sessionId && !registry.targetsByTargetId.has(targetId)).map(([targetId]) => targetId)
18229
+ ...Array.from(ownersAcrossReconnect).filter(([targetId, known]) => known.deleted !== true && known.owner === "relay" && known.sessionId === sessionId && !registry.targetsByTargetId.has(targetId)).map(([targetId]) => targetId)
17872
18230
  ],
17873
18231
  onCancelSessionHandoff: (sessionId) => handoffs.cancelForSession(sessionId) !== undefined,
17874
18232
  pendingHandoff: (sessionId) => {
@@ -17893,30 +18251,54 @@ var makeRelay = fnUntraced(function* (options = {}) {
17893
18251
  const target = registry.tabTargets.get(tabId);
17894
18252
  if (target?.owner === "user")
17895
18253
  return;
17896
- relayLog("allowlist.close", { tabId, registered: target !== undefined });
18254
+ relayLog2("allowlist.close", { tabId, registered: target !== undefined });
17897
18255
  yield* sendToExtension({ method: "tabs.remove", params: { tabId } });
17898
18256
  if (target)
17899
- detachTargetState(tabId);
18257
+ detachTargetState(tabId, { reason: "navigation-blocked" });
17900
18258
  })),
17901
- log: (event, details) => relayLog(event, details)
18259
+ log: (event, details) => relayLog2(event, details)
17902
18260
  });
17903
- const ownerAcrossReconnect = (targetId) => {
18261
+ const ownerAcrossReconnect = (targetId, includeRelayOwnership, browserKey) => {
17904
18262
  const known = ownersAcrossReconnect.get(targetId);
17905
- return known?.sessionId !== undefined && sessions.sessions.has(known.sessionId) ? { sessionId: known.sessionId, owner: known.owner } : undefined;
18263
+ if (!known || known.deleted === true)
18264
+ return;
18265
+ if (browserKey !== undefined && known.browser !== "" && known.browser !== browserKey)
18266
+ return;
18267
+ if (!includeRelayOwnership && known.owner !== "user")
18268
+ return;
18269
+ return known.sessionId !== undefined && sessions.sessions.has(known.sessionId) ? { sessionId: known.sessionId, owner: known.owner } : undefined;
17906
18270
  };
17907
18271
  const attachTimeoutMs = yield* Int("OPENCODE_BROWSER_ATTACH_TIMEOUT_MS").pipe(withDefault(1e4));
17908
18272
  const rootLifecycle = yield* RootTargetLifecycle.make({
17909
18273
  registry,
17910
18274
  sessions: {
17911
- persistedTargetOwner: (targetId) => sessions.persistedTargetOwner(targetId) ?? ownerAcrossReconnect(targetId),
17912
- markTargetReplaced: (previousTargetId, targetId) => sessions.markTargetReplaced(previousTargetId, targetId)
18275
+ persistedTargetOwner: (targetId, restoreOptions) => sessions.persistedTargetOwner(targetId, restoreOptions) ?? ownerAcrossReconnect(targetId, restoreOptions?.legacy === true || restoreOptions?.includeHeldTargets !== false, restoreOptions?.browserKey),
18276
+ markTargetReplaced: (previousTargetId, targetId) => sessions.markTargetReplaced(previousTargetId, targetId),
18277
+ noteTargetHeld: (targetId, sessionId) => sessions.noteTargetHeld(targetId, sessionId),
18278
+ forgetTargetHeld: (targetId) => sessions.forgetTargetHeld(targetId)
18279
+ },
18280
+ browserKeyForTab: (tabId) => browsers.ownerKey(tabId),
18281
+ authorizeRestoredTarget: ({ tabId, targetId, url, owner, sessionId }) => {
18282
+ const allowed = navigationGuard.createdTabNavigated({
18283
+ tabId,
18284
+ opencodeBrowserSessionId: sessionId,
18285
+ owner,
18286
+ targetInfo: { targetId, url }
18287
+ });
18288
+ if (!allowed) {
18289
+ relayLog2("allowlist.reclaim-refused", { tabId, session: sessionId });
18290
+ sessions.markTargetDetached(targetId, { reason: "allowlist-reclaim" });
18291
+ sessions.forgetTargetHeld(targetId);
18292
+ }
18293
+ return allowed;
17913
18294
  },
17914
18295
  handoffs,
17915
18296
  clients: cdpClients,
17916
18297
  extension: {
17917
18298
  generation: (tabId) => browsers.generationOf(tabId),
17918
18299
  isCurrentGeneration: (generation) => browsers.isCurrentGeneration(generation),
17919
- send: (command) => sendToExtension(command)
18300
+ send: (command) => sendToExtension(command),
18301
+ supportsTargetRelease: (tabId) => browsers.browserTab(tabId)?.link.rpc.supports(extensionCapabilityTabRelease) ?? false
17920
18302
  },
17921
18303
  presentation: {
17922
18304
  replaced: recordRootReplacement,
@@ -17949,7 +18331,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17949
18331
  }
17950
18332
  const detachTab = fnUntraced(function* (tabId) {
17951
18333
  yield* sendToExtension({ method: "debugger.detach", params: { tabId } });
17952
- detachTargetState(tabId);
18334
+ detachTargetState(tabId, { reason: "relay-detached" });
17953
18335
  yield* ignore(sendToExtension({ method: "action.setAttached", params: { tabId, attached: false } }));
17954
18336
  });
17955
18337
  const housekeeping = createRelayHousekeeping({
@@ -18003,7 +18385,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
18003
18385
  if (registry.tabTargets.has(tabId))
18004
18386
  return yield* detachTab(tabId);
18005
18387
  announceTab(tabId);
18006
- yield* rootLifecycle.attach({ tabId, owner: "user" });
18388
+ yield* rootLifecycle.attach({ tabId, owner: "user", restoreOwnership: false });
18007
18389
  });
18008
18390
  const sessionBrowser = (sessionId) => suspend2(() => {
18009
18391
  const session = sessionId && sessions.sessions.get(sessionId);
@@ -18026,33 +18408,41 @@ var makeRelay = fnUntraced(function* (options = {}) {
18026
18408
  tabId,
18027
18409
  owner: "relay",
18028
18410
  ...createOptions.opencodeBrowserSessionId ? { opencodeBrowserSessionId: createOptions.opencodeBrowserSessionId } : {},
18029
- ...createOptions.autoAttachParams ? { autoAttachParams: createOptions.autoAttachParams } : {}
18411
+ ...createOptions.autoAttachParams ? { autoAttachParams: createOptions.autoAttachParams } : {},
18412
+ deferHeldTarget: true
18030
18413
  }).pipe(tapError((error) => sync2(() => {
18031
- relayLog("create.attach-failed", { tabId, error: error instanceof Error ? error.message : String(error) });
18414
+ relayLog2("create.attach-failed", { tabId, error: error instanceof Error ? error.message : String(error) });
18032
18415
  sendExtensionBestEffort({ method: "tabs.remove", params: { tabId } });
18033
- detachTargetState(tabId);
18416
+ detachTargetState(tabId, { reason: "attach-failed" });
18034
18417
  })));
18035
18418
  const requested = createTargetUrl2({ url: createOptions.url });
18419
+ let heldAllowed = true;
18420
+ const finishCreatedTarget = (created) => {
18421
+ if (heldAllowed && createOptions.opencodeBrowserSessionId)
18422
+ sessions.noteTargetHeld(created.targetInfo.targetId, createOptions.opencodeBrowserSessionId);
18423
+ return created;
18424
+ };
18036
18425
  if (requested !== "about:blank") {
18037
18426
  const data = /^data:/i.test(requested.trim());
18038
18427
  const navigation = yield* (data ? navigateTopFrameToDataUrl({ tabId, params: { url: requested }, mainFrameIdsByTab, blankNavigationWaiters, registry, sendDebuggerCommand }) : sendDebuggerCommand({ tabId, method: "Page.navigate", params: { url: requested } })).pipe(catch_((error) => sync2(() => {
18039
- relayLog("create.navigate-failed", { tabId, error: error instanceof Error ? error.message : String(error) });
18428
+ relayLog2("create.navigate-failed", { tabId, error: error instanceof Error ? error.message : String(error) });
18040
18429
  return;
18041
18430
  })));
18042
18431
  const errorText = getString2(navigation, "errorText");
18043
18432
  if (errorText)
18044
- relayLog("create.navigate-failed", { tabId, errorText });
18433
+ relayLog2("create.navigate-failed", { tabId, errorText });
18045
18434
  else if (data && navigation === undefined)
18046
- relayLog("create.data-skipped", { tabId });
18435
+ relayLog2("create.data-skipped", { tabId });
18047
18436
  const current = yield* sendDebuggerCommand({ tabId, method: "Target.getTargetInfo", params: {} }).pipe(orElseSucceed(() => ({})));
18048
18437
  const targetInfo = getTargetInfo2(current.targetInfo);
18049
- if (targetInfo && !isRestrictedTarget2(targetInfo) && navigationGuard.createdTabNavigated({ ...target, targetInfo })) {
18438
+ heldAllowed = !targetInfo || isRestrictedTarget2(targetInfo) || navigationGuard.createdTabNavigated({ ...target, targetInfo });
18439
+ if (targetInfo && !isRestrictedTarget2(targetInfo) && heldAllowed) {
18050
18440
  const updated = registry.updateConnectedTargetInfo({ tabId, targetInfo });
18051
18441
  if (updated?.kind === "root")
18052
- return updated.target;
18442
+ return finishCreatedTarget(updated.target);
18053
18443
  }
18054
18444
  }
18055
- return target;
18445
+ return finishCreatedTarget(target);
18056
18446
  });
18057
18447
  const closeTargetByTargetId = fnUntraced(function* (targetId) {
18058
18448
  const target = registry.targetsByTargetId.get(targetId);
@@ -18061,7 +18451,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
18061
18451
  if (target.owner === "user")
18062
18452
  return yield* detachTab(target.tabId);
18063
18453
  yield* sendToExtension({ method: "tabs.remove", params: { tabId: target.tabId } }).pipe(catchIf(isMissingTabError, () => void_3));
18064
- detachTargetState(target.tabId);
18454
+ detachTargetState(target.tabId, { reason: "target-closed" });
18065
18455
  });
18066
18456
  function clearTabRuntimeState(tabId) {
18067
18457
  tabActivity.forget(tabId);
@@ -18089,8 +18479,12 @@ var makeRelay = fnUntraced(function* (options = {}) {
18089
18479
  const detached = registry.detachRootTargetState(tabId);
18090
18480
  if (detached) {
18091
18481
  presentation.cancelTargetHandoffs(detached.target, "target-detached");
18092
- if (!detachOptions.preserveSessionTarget)
18093
- sessions.markTargetDetached(detached.target.targetInfo.targetId, { releasedByUser: detachOptions.releasedByUser === true });
18482
+ if (!detachOptions.preserveSessionTarget) {
18483
+ sessions.markTargetDetached(detached.target.targetInfo.targetId, {
18484
+ releasedByUser: detachOptions.releasedByUser === true,
18485
+ ...detachOptions.reason === undefined ? {} : { reason: detachOptions.reason }
18486
+ });
18487
+ }
18094
18488
  contextDebugLog?.(`target-detached kind=root ${targetDiagnosticIdentity(registry, detached.target)}`);
18095
18489
  }
18096
18490
  cdpClients.detachTab(tabId, { destroyed: true });
@@ -18099,8 +18493,8 @@ var makeRelay = fnUntraced(function* (options = {}) {
18099
18493
  function forgetMissingTab(tabId, method) {
18100
18494
  if (!registry.routingRootTarget(tabId))
18101
18495
  return;
18102
- relayLog("target.gone", { tabId, method });
18103
- detachTargetState(tabId);
18496
+ relayLog2("target.gone", { tabId, method });
18497
+ detachTargetState(tabId, { reason: "target-missing" });
18104
18498
  const owner = browsers.browserTab(tabId);
18105
18499
  owner?.link.rpc.rejectDebuggerCommandsForTab(owner.tabId, new Error(`Target closed: tab ${tabId} no longer exists`));
18106
18500
  }
@@ -18243,11 +18637,12 @@ var makeRelay = fnUntraced(function* (options = {}) {
18243
18637
  debugLog
18244
18638
  });
18245
18639
  const cleanup = fnUntraced(function* () {
18640
+ relayLog2("relay.shutdown.start", { managed, sessions: sessions.sessions.size, pid: process.pid });
18246
18641
  stopTimers();
18247
18642
  autoUpdater?.stop();
18248
18643
  yield* shutdownControl.close().pipe(ignore);
18249
18644
  yield* sessions.closeAll({
18250
- onStalled: (sessions) => relayLog("relay.shutdown.stalled", {
18645
+ onStalled: (sessions) => relayLog2("relay.shutdown.stalled", {
18251
18646
  sessions: sessions.length > 0 ? sessions.map(({ sessionId, pending }) => `${sessionId} (${pending})`).join(", ") : "none",
18252
18647
  waitedMs: defaultShutdownTimeoutMs
18253
18648
  })
@@ -18267,6 +18662,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
18267
18662
  link.rpc.close();
18268
18663
  yield* closeWebSocketServer2(websocketServer).pipe(logCloseError2("Failed to close websocket server"));
18269
18664
  yield* closeHttpServer2(httpServer).pipe(logCloseError2("Failed to close http server"), ensuring(sync2(() => removeRelayState(browserId, stateRoot(), configuredPort))));
18665
+ relayLog2("relay.shutdown.closed", { managed, pid: process.pid });
18270
18666
  });
18271
18667
  const close = cleanup();
18272
18668
  yield* catch_(gen(function* () {
@@ -18275,14 +18671,14 @@ var makeRelay = fnUntraced(function* (options = {}) {
18275
18671
  try: () => writeRelayState({ port, configuredPort, pid: process.pid, instanceId: browserId, startedAt }),
18276
18672
  catch: (cause) => new Error("Write the relay port file", { cause })
18277
18673
  }).pipe(catch_((error) => {
18278
- relayLog("relay.state.write_failed", { port, configuredPort, error: error.message });
18674
+ relayLog2("relay.state.write_failed", { port, configuredPort, error: error.message });
18279
18675
  return port === configuredPort ? void_3 : fail6(error);
18280
18676
  }));
18281
18677
  yield* try_2({
18282
18678
  try: () => writeLastRelayPort(port, stateRoot(), configuredPort),
18283
18679
  catch: (cause) => new Error("Write the last relay port", { cause })
18284
18680
  }).pipe(catch_((error) => {
18285
- relayLog("relay.last_port.write_failed", { port, configuredPort, error: error.message });
18681
+ relayLog2("relay.last_port.write_failed", { port, configuredPort, error: error.message });
18286
18682
  return void_3;
18287
18683
  }));
18288
18684
  yield* sync2(() => pruneStaleExecuteFilesDirectories());
@@ -18326,7 +18722,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
18326
18722
  autoUpdater = createAutoUpdater({
18327
18723
  runtime,
18328
18724
  isIdle: browserIdle,
18329
- log: relayLog,
18725
+ log: relayLog2,
18330
18726
  onChange: () => settingsSync.sendRelaySettings()
18331
18727
  });
18332
18728
  autoUpdater.start();
@@ -18335,13 +18731,13 @@ var makeRelay = fnUntraced(function* (options = {}) {
18335
18731
  if (dev && installedDevExtension()) {
18336
18732
  syncDevExtension(dev, { port }).then((result) => {
18337
18733
  if (result === "updated")
18338
- relayLog("extension.dev_updated", { file: dev.file });
18734
+ relayLog2("extension.dev_updated", { file: dev.file });
18339
18735
  for (const link of browsers.list())
18340
18736
  if (link.local)
18341
18737
  handshake.reloadOutdatedDevExtension(link);
18342
- }, (error) => relayLog("extension.dev_update_failed", { error: error.message }));
18738
+ }, (error) => relayLog2("extension.dev_update_failed", { error: error.message }));
18343
18739
  }
18344
- relayLog("relay.ready", {
18740
+ relayLog2("relay.ready", {
18345
18741
  url: endpointUrl,
18346
18742
  version: opencodeBrowserVersion2,
18347
18743
  build: opencodeBrowserBuildId2,