@capybara-hq/kernel 0.1.0-rc.116 → 0.1.0-rc.118

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 (79) hide show
  1. package/dist/admin/usage.service.d.ts +4 -2
  2. package/dist/admin/usage.service.js +35 -15
  3. package/dist/catalog/catalog-content.d.ts +11 -0
  4. package/dist/catalog/catalog-content.js +1 -0
  5. package/dist/catalog/component-scope.service.js +2 -1
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/org-catalog.service.d.ts +1 -0
  8. package/dist/catalog/org-catalog.service.js +44 -2
  9. package/dist/catalog/plugin-install.d.ts +1 -0
  10. package/dist/catalog/plugin-install.js +11 -1
  11. package/dist/catalog/schema-path.d.ts +4 -6
  12. package/dist/catalog/schema-path.js +48 -21
  13. package/dist/channels/outbound.d.ts +5 -0
  14. package/dist/channels/outbound.js +6 -1
  15. package/dist/channels/supervisor.js +3 -0
  16. package/dist/conversations/conversations.controller.d.ts +1 -1
  17. package/dist/conversations/conversations.controller.js +1 -1
  18. package/dist/conversations/conversations.service.d.ts +4 -2
  19. package/dist/conversations/conversations.service.js +17 -3
  20. package/dist/conversations/events.d.ts +10 -1
  21. package/dist/conversations/events.js +8 -1
  22. package/dist/db/kernel-schema.d.ts +15 -1
  23. package/dist/devices/devices.controller.d.ts +5 -0
  24. package/dist/devices/devices.controller.js +20 -2
  25. package/dist/devices/devices.service.d.ts +11 -1
  26. package/dist/devices/devices.service.js +20 -0
  27. package/dist/evals/plan.d.ts +3 -1
  28. package/dist/evals/plan.js +25 -5
  29. package/dist/evals/runs.service.js +3 -2
  30. package/dist/evals/trajectory.js +1 -0
  31. package/dist/files/blob-references.d.ts +8 -0
  32. package/dist/files/blob-references.js +19 -0
  33. package/dist/files/blob-sweep.job.js +5 -23
  34. package/dist/files/library-files.service.js +8 -4
  35. package/dist/models/cache-write-usage.d.ts +3 -0
  36. package/dist/models/cache-write-usage.js +26 -0
  37. package/dist/models/images.js +5 -1
  38. package/dist/models/prices.d.ts +8 -6
  39. package/dist/models/prices.js +28 -3
  40. package/dist/orgs/settings.controller.d.ts +4 -17
  41. package/dist/orgs/settings.controller.js +5 -9
  42. package/dist/orgs/settings.service.d.ts +12 -0
  43. package/dist/orgs/settings.service.js +24 -0
  44. package/dist/platform/exclusions.js +11 -0
  45. package/dist/platform/ops/admin.ops.js +2 -2
  46. package/dist/platform/ops/conversations.ops.js +1 -1
  47. package/dist/platform/ops/devices.ops.js +21 -0
  48. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  49. package/dist/platform/ops/org-settings.ops.js +10 -10
  50. package/dist/runtime/context/build.d.ts +2 -0
  51. package/dist/runtime/context/build.js +9 -1
  52. package/dist/runtime/usage-report.js +3 -0
  53. package/dist/sandbox/legacy-retirement.d.ts +15 -0
  54. package/dist/sandbox/legacy-retirement.js +243 -3
  55. package/dist/sandbox/permission-instance-writes.d.ts +4 -1
  56. package/dist/sandbox/permission-instance-writes.js +55 -1
  57. package/dist/sandbox/providers.d.ts +6 -1
  58. package/dist/sandbox/providers.js +15 -1
  59. package/dist/sandbox/sandbox.service.d.ts +19 -3
  60. package/dist/sandbox/sandbox.service.js +167 -9
  61. package/dist/tools/builtins/sandbox/common.d.ts +2 -7
  62. package/dist/tools/builtins/sandbox/common.js +14 -8
  63. package/dist/tools/connector-tools-jobs.d.ts +3 -2
  64. package/dist/tools/connectors.service.d.ts +3 -1
  65. package/dist/tools/connectors.service.js +64 -12
  66. package/dist/tools/drift.d.ts +1 -1
  67. package/dist/tools/drift.js +13 -13
  68. package/dist/tools/pipeline.d.ts +4 -0
  69. package/dist/tools/pipeline.js +55 -16
  70. package/dist/ui/admin-ui.controller.d.ts +5 -2
  71. package/dist/ui/admin-ui.controller.js +14 -1
  72. package/dist/ui/ui.schemas.d.ts +9 -0
  73. package/dist/ui/ui.schemas.js +2 -0
  74. package/dist/ui/views.d.ts +1 -1
  75. package/dist/ui/views.js +4 -5
  76. package/package.json +3 -3
  77. package/src/migrations/0202_connector_endpoint_changed_at.sql +1 -0
  78. package/src/migrations/0203_model_cache_write_pricing.sql +5 -0
  79. package/src/migrations/0204_device_instance_retirement_identities.sql +46 -0
@@ -67,17 +67,18 @@ import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
67
67
  import { effectiveSandboxLimits, readOrgSettings } from "../orgs/settings.service.js";
68
68
  import { isStorageError } from "../runtime/permission-context-errors.js";
69
69
  import { canonicalJson } from "../tools/canonical-json.js";
70
+ import { untilAborted } from "../until-aborted.js";
70
71
  import { attachmentsDir } from "./attachments-path.js";
71
72
  import { CloudPermissionSnapshots, } from "./cloud-permission-snapshot.js";
72
73
  import { DeviceReports } from "./device-reports.js";
73
74
  import { isKernelReadMethod, KernelReadInstanceNotRunning, KernelReadNotAdmitted, KernelReadUnsupported, } from "./kernel-read.js";
74
75
  import { SandboxLeases, SandboxLockLostError, sandboxBusy, } from "./leases.js";
75
- import { isKnownProvider, LegacyRetirementStore } from "./legacy-retirement.js";
76
+ import { isKnownProvider, LegacyRetirementStore, } from "./legacy-retirement.js";
76
77
  import { ManagedDeviceContextFailed } from "./managed-device-context.js";
77
78
  import { appliedLacksHost, appliedOf, appliedWider, installedWider, instanceLimitsJson, orgEffectiveHosts, providerLimits, readInstanceLimits, sameApplied, sameAppliedExact, sameAppliedExactly, } from "./modes.js";
78
79
  import { PermissionFacts } from "./permission-facts.js";
79
80
  import { reportOwed, supportOf } from "./permission-runtime-reports.js";
80
- import { DeviceProviders, isInProcessName, servesDialIn, } from "./providers.js";
81
+ import { DeviceProviders, isInProcessName, LOCAL_RETIREMENT_PROVIDER, localRetirementGeneration, RETIREMENT_GENERATION, servesDialIn, } from "./providers.js";
81
82
  import { isDeviceRequestNotSent } from "./request-not-sent.js";
82
83
  import { SandboxProviderUnreachableError } from "./unreachable.js";
83
84
  // Moved to leases.ts (phase C); re-exported for existing importers
@@ -88,6 +89,7 @@ const HOLDER_TTL_MARGIN_MS = 10 * 60_000;
88
89
  const PATH_LEASE_WAIT_MS = 30_000;
89
90
  /** Time limit of one provider call in maintenance (suspend, destroy). */
90
91
  const SWEEP_OP_TIMEOUT_MS = 120_000;
92
+ const RETIREMENT_CHECK_TIMEOUT_MS = 15_000;
91
93
  /** How long a cloud device's lifecycle reconcile waits before the sweep tries it again (B-12). */
92
94
  const RECONCILE_RETRY_SECONDS = 600;
93
95
  /**
@@ -292,7 +294,9 @@ export const retirementPending = () => new RetirementPendingError("device.unavai
292
294
  * will ever cover it (an incarnation replaced without a recorded confirmed destruction, or an
293
295
  * unknown one it cannot clear) (503, 8.5): the owner deletes the device and creates it again.
294
296
  */
295
- export const recreateRequired = () => new RetirementPendingError("device.recreate_required", "Background work started by an earlier version may still be running on an earlier instance of this device, and that instance can no longer be verified as destroyed. Delete this device and create it again.");
297
+ export const recreateRequired = (local = false) => new RetirementPendingError("device.recreate_required", local
298
+ ? "Earlier background work on the connected machine has not been confirmed stopped. If you own this device, open its device page and choose Check again."
299
+ : "Background work started by an earlier version may still be running on an earlier instance of this device, and that instance can no longer be verified as destroyed. Delete this device and create it again.", local ? [{ reason: "local_retirement" }] : undefined);
296
300
  const isRetirementPending = (err) => err instanceof RetirementPendingError;
297
301
  const abortReason = (signal) => signal.reason ?? new DOMException("This operation was aborted", "AbortError");
298
302
  function sleep(ms, signal) {
@@ -2362,6 +2366,106 @@ let SandboxService = class SandboxService {
2362
2366
  await lease.release();
2363
2367
  }
2364
2368
  }
2369
+ /** The owner's proof-only pass of the retirement gate, with no provider lifecycle mutation. */
2370
+ async checkLocalRetirement(owner, requested) {
2371
+ const { orgId, deviceId, accountId } = owner;
2372
+ if (!(await this.ownerLocalProvider(owner)))
2373
+ return "blocked";
2374
+ const lease = await this.leases.tryExclusive(deviceId, { unlessStreams: true });
2375
+ if (!lease)
2376
+ return "busy";
2377
+ const signal = AbortSignal.any([
2378
+ requested,
2379
+ lease.signal,
2380
+ AbortSignal.timeout(RETIREMENT_CHECK_TIMEOUT_MS),
2381
+ ]);
2382
+ try {
2383
+ const p = await this.ownerLocalProvider(owner);
2384
+ const attest = p?.impl.retirement;
2385
+ if (!p || !attest || signal.aborted)
2386
+ return "blocked";
2387
+ if (!(await this.retirement.hasUnresolved(deviceId)))
2388
+ return "clear";
2389
+ const row = await this.readRow(owner);
2390
+ if (!row?.handle ||
2391
+ row.handle.id !== deviceId ||
2392
+ row.provider !== p.plugin ||
2393
+ !row.had_instance ||
2394
+ (row.status !== "running" && row.status !== "suspended"))
2395
+ return "blocked";
2396
+ const currentGeneration = String(row.created_at.getTime());
2397
+ const currentProviderGeneration = localRetirementGeneration(p, row.handle, deviceId);
2398
+ if (!RETIREMENT_GENERATION.test(currentGeneration) || currentProviderGeneration === undefined)
2399
+ return "blocked";
2400
+ const machine = await this.db
2401
+ .selectFrom("device_machines")
2402
+ .select("id")
2403
+ .where("org_id", "=", orgId)
2404
+ .where("device_id", "=", deviceId)
2405
+ .where("account_id", "=", accountId)
2406
+ .where("revoked_at", "is", null)
2407
+ .executeTakeFirst();
2408
+ if (!machine || signal.aborted)
2409
+ return "blocked";
2410
+ const fence = { gen: row.generation };
2411
+ await this.fenced(lease, deviceId, fence, {});
2412
+ const check = {
2413
+ ...owner,
2414
+ machineId: machine.id,
2415
+ currentGeneration,
2416
+ fence: fence.gen,
2417
+ };
2418
+ for (const o of await this.retirement.quarantinedLocal(check)) {
2419
+ if (signal.aborted)
2420
+ break;
2421
+ const recorded = await this.retirement.destructionRecorded(deviceId, o.provider, o.instanceGeneration);
2422
+ const providerGeneration = recorded
2423
+ ? undefined
2424
+ : await this.retirement.localProviderGeneration(o);
2425
+ if (!recorded) {
2426
+ if (providerGeneration === undefined ||
2427
+ BigInt(providerGeneration) >= BigInt(currentProviderGeneration))
2428
+ continue;
2429
+ const confirmed = await untilAborted(Promise.resolve().then(() => attest.attestRetired(deviceId, providerGeneration, signal)), signal).catch(() => false);
2430
+ if (confirmed !== true)
2431
+ continue;
2432
+ }
2433
+ if (signal.aborted || !(await lease.renew()))
2434
+ break;
2435
+ if (!(await this.selection.isOnInOrg(orgId, p.plugin)))
2436
+ break;
2437
+ await this.retirement.resolveLocalProof(check, o, providerGeneration, signal);
2438
+ }
2439
+ return (await this.retirement.hasUnresolved(deviceId)) ? "blocked" : "clear";
2440
+ }
2441
+ catch (err) {
2442
+ if (signal.aborted || err instanceof SandboxLockLostError)
2443
+ return "blocked";
2444
+ throw err;
2445
+ }
2446
+ finally {
2447
+ await lease.release();
2448
+ }
2449
+ }
2450
+ async ownerLocalProvider(owner) {
2451
+ const row = await this.db
2452
+ .selectFrom("devices")
2453
+ .select("provider")
2454
+ .where("org_id", "=", owner.orgId)
2455
+ .where("id", "=", owner.deviceId)
2456
+ .where("owner_kind", "=", "personal")
2457
+ .where("owner_account_id", "=", owner.accountId)
2458
+ .where("deleted_at", "is", null)
2459
+ .executeTakeFirst();
2460
+ if (!row)
2461
+ throw deviceNotFound();
2462
+ if (row.provider !== LOCAL_RETIREMENT_PROVIDER)
2463
+ return undefined;
2464
+ const p = this.providers.forDevice(row.provider);
2465
+ return p && servesDialIn(p) && (await this.selection.isOnInOrg(owner.orgId, p.plugin))
2466
+ ? p
2467
+ : undefined;
2468
+ }
2365
2469
  /**
2366
2470
  * The worker's retirement of a device's old incarnations (8.5, `RetireLegacyTasksJob`): one try
2367
2471
  * at the exclusive lifecycle lease, then the same gate as every acquisition. `busy`: a holder
@@ -2957,7 +3061,9 @@ let SandboxService = class SandboxService {
2957
3061
  else if (still !== null && resumed !== undefined)
2958
3062
  resumed.resumed = true;
2959
3063
  if (pending)
2960
- throw failed ? retirementPending() : recreateRequired();
3064
+ throw failed
3065
+ ? retirementPending()
3066
+ : recreateRequired(now?.provider === LOCAL_RETIREMENT_PROVIDER);
2961
3067
  return now;
2962
3068
  }
2963
3069
  /**
@@ -3117,6 +3223,7 @@ let SandboxService = class SandboxService {
3117
3223
  const createdAt = row.created_at.getTime();
3118
3224
  const fsResets = row.fs_resets;
3119
3225
  if (handle && isInstance(row, gone) && row.status === "running") {
3226
+ await this.destroyGone(id, p, held, row, handle, fence, signal);
3120
3227
  const created = await this.createSettled(ctx, p, held, row, fence, signal, want);
3121
3228
  return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
3122
3229
  }
@@ -3198,6 +3305,7 @@ let SandboxService = class SandboxService {
3198
3305
  this.log.info("sandbox instance is gone at the provider; recreating", {
3199
3306
  deviceId: id,
3200
3307
  });
3308
+ await this.destroyGone(id, p, held, row, handle, fence, signal);
3201
3309
  }
3202
3310
  const created = await this.createSettled(ctx, p, held, row, fence, signal, want);
3203
3311
  // had_instance only ever becomes true: any earlier instance (even if a rebuild failed since)
@@ -3218,6 +3326,39 @@ let SandboxService = class SandboxService {
3218
3326
  throw err;
3219
3327
  }
3220
3328
  }
3329
+ /**
3330
+ * Under the exclusive lease, before the rebuild of an instance its provider answered gone
3331
+ * (`SandboxGoneError` during a use, or `resume` answering `gone`): the row's incarnation is
3332
+ * destroyed through its provider with this holder's fence token (a no-op where it is really
3333
+ * gone; on a provider whose `gone` means "never served again", such as a local machine whose
3334
+ * program restarted, it ends what the generation left) and that confirmed destruction is
3335
+ * recorded (8.5 evidence) before anything new is created. Its revoked starts and owed revokes
3336
+ * then settle against the record once a new incarnation runs, instead of quarantining the
3337
+ * device for an incarnation replaced without a recorded destruction. A destroy that fails fails
3338
+ * the use with nothing rebuilt: the row still names the gone incarnation, so the next use is
3339
+ * told gone again and retries (unavailable for now, never `device.recreate_required`).
3340
+ */
3341
+ async destroyGone(id, p, held, row, handle, fence, signal) {
3342
+ assertOwnRow(row, p);
3343
+ // still the holder (a fenced write), so the destroy's token is this holder's latest
3344
+ await this.fenced(held, id, fence, {});
3345
+ try {
3346
+ await p.impl.destroy(handle, signal, { token: fence.gen });
3347
+ }
3348
+ catch (err) {
3349
+ if (isStaleFenceError(err))
3350
+ throw await this.staleHolder(held, id, p.plugin, fence, "destroy", err);
3351
+ if (!signal.aborted)
3352
+ this.log.warn("cannot destroy the gone sandbox instance; it is rebuilt on a later use", {
3353
+ deviceId: id,
3354
+ err,
3355
+ });
3356
+ throw err;
3357
+ }
3358
+ if (!(await held.renew()))
3359
+ throw new SandboxLockLostError(id);
3360
+ await this.retirement.recordDestruction(id, p.plugin, String(row.created_at.getTime()));
3361
+ }
3221
3362
  /**
3222
3363
  * {@link create} from {@link ensure}, then, for a provider whose limits are fixed at its file
3223
3364
  * system (the new instance keeps the network its file system enforces, E2B), the installed
@@ -3252,6 +3393,11 @@ let SandboxService = class SandboxService {
3252
3393
  // instance has none yet (NULL): its first commit is no roots change (no consent reset, no
3253
3394
  // revoke)
3254
3395
  const committedRoots = row.permission_roots ?? (row.handle ? rootsOf(row.handle) : null);
3396
+ const previousGeneration = row.handle && row.had_instance && row.provider === p.plugin
3397
+ ? localRetirementGeneration(p, row.handle, id)
3398
+ : undefined;
3399
+ if (previousGeneration !== undefined)
3400
+ await runOutsideTransaction(() => this.instanceWrites.preserveRetirementIdentity(ctx.orgId, id, fence.gen, previousGeneration, held.signal));
3255
3401
  await this.fenced(held, id, fence, {
3256
3402
  org_id: ctx.orgId,
3257
3403
  provider: p.plugin,
@@ -3338,7 +3484,7 @@ let SandboxService = class SandboxService {
3338
3484
  running_since: sql `now()`,
3339
3485
  last_used_at: sql `now()`,
3340
3486
  ...(!atFileSystem && { instance_limits: record }),
3341
- }, held.signal, support));
3487
+ }, held.signal, support, localRetirementGeneration(p, handle, id)));
3342
3488
  fence.gen++;
3343
3489
  }
3344
3490
  catch (e) {
@@ -3446,12 +3592,17 @@ let SandboxService = class SandboxService {
3446
3592
  return null;
3447
3593
  }
3448
3594
  this.log.info("sandbox limits changed; recreating the instance on the kept files", facts);
3449
- // still the holder (a fenced write), so a holder whose lease ended meanwhile never destroys
3450
- // what a newer one uses; the destroy's token is then this holder's latest
3451
- await this.fenced(held, id, fence, {});
3452
- if (!gone) {
3595
+ // the provider answered gone: destroyed with confirmation and recorded before the rebuild
3596
+ if (gone)
3597
+ await this.destroyGone(id, p, held, row, handle, fence, signal);
3598
+ else {
3599
+ // still the holder (a fenced write), so a holder whose lease ended meanwhile never destroys
3600
+ // what a newer one uses; the destroy's token is then this holder's latest
3601
+ await this.fenced(held, id, fence, {});
3602
+ let destroyed = false;
3453
3603
  try {
3454
3604
  await p.impl.destroy(handle, signal, { token: fence.gen });
3605
+ destroyed = true;
3455
3606
  }
3456
3607
  catch (err) {
3457
3608
  if (isStaleFenceError(err))
@@ -3464,6 +3615,13 @@ let SandboxService = class SandboxService {
3464
3615
  err,
3465
3616
  });
3466
3617
  }
3618
+ // the provider's destroy resolved: confirmed destruction of exactly this incarnation (8.5
3619
+ // evidence, as in destroyRow), so its owed revokes settle once the new one runs
3620
+ if (destroyed) {
3621
+ if (!(await held.renew()))
3622
+ throw new SandboxLockLostError(id);
3623
+ await this.retirement.recordDestruction(id, p.plugin, String(row.created_at.getTime()));
3624
+ }
3467
3625
  }
3468
3626
  return await this.lifecycleStep("recreate", id, p, signal, () => this.create(ctx, p, held, row, fence, signal, want));
3469
3627
  }
@@ -254,13 +254,8 @@ export declare const PLATFORM_OUTSIDE_SANDBOX_OFF_TOOL_TEXT = "Running commands
254
254
  * The device does not allow running outside the sandbox (`device.outside_sandbox_not_allowed`).
255
255
  */
256
256
  export declare const OUTSIDE_SANDBOX_CEILING_TOOL_TEXT = "This device does not allow running commands outside the sandbox, so nothing ran. Run the command inside the sandbox, or ask the device's owner whether its provider can allow it.";
257
- /**
258
- * The legacy retirement gate's refusals (`RetirementPendingError`, permission runtime cutover
259
- * 8.5): the device's earlier instance may still run background work an earlier version started.
260
- * Each says what clears it; the generic `device.unavailable` text would name an inactive provider.
261
- */
262
- export declare const RETIREMENT_PENDING_TOOL_TEXT = "This device is unavailable: background work started by an earlier version may still run on its previous instance, which has not been confirmed destroyed yet, so nothing ran. Retry later (a cloud device becomes usable once its provider confirms the old instance destroyed), continue without the device, or ask the user to start a new conversation on another device.";
263
- export declare const RETIREMENT_RECREATE_TOOL_TEXT = "Background work started by an earlier version may still be running on an earlier instance of this device, which can no longer be verified as destroyed, so nothing ran. Ask the device's owner to delete the device and create it again, or ask the user to start a new conversation on another device.";
257
+ export declare const RETIREMENT_PENDING_TOOL_TEXT = "This device is unavailable: background work started by an earlier version may still run on its previous instance, which has not been confirmed destroyed yet, so nothing ran. Retry later (a cloud device becomes usable once its provider confirms the old instance destroyed), continue without the device, or ask the user to start a new conversation on another device. Attachments and artifacts of this conversation can still be read without the device: if Read is available to you, Read with file_id.";
258
+ export declare const RETIREMENT_RECREATE_TOOL_TEXT = "Background work started by an earlier version may still be running on an earlier instance of this device, which can no longer be verified as destroyed, so nothing ran. Ask the device's owner to delete the device and create it again, or ask the user to start a new conversation on another device. Attachments and artifacts of this conversation can still be read without the device: if Read is available to you, Read with file_id.";
264
259
  /**
265
260
  * A managed operation outside the admitted scope (`SandboxScopeDeniedError`): fixed text, never
266
261
  * the refusal's own message (a provider may write it).
@@ -276,13 +276,19 @@ export const OUTSIDE_SANDBOX_CEILING_TOOL_TEXT = "This device does not allow run
276
276
  * 8.5): the device's earlier instance may still run background work an earlier version started.
277
277
  * Each says what clears it; the generic `device.unavailable` text would name an inactive provider.
278
278
  */
279
- export const RETIREMENT_PENDING_TOOL_TEXT = "This device is unavailable: background work started by an earlier version may still run on its previous instance, which has not been confirmed destroyed yet, so nothing ran. Retry later (a cloud device becomes usable once its provider confirms the old instance destroyed), continue without the device, or ask the user to start a new conversation on another device.";
280
- export const RETIREMENT_RECREATE_TOOL_TEXT = "Background work started by an earlier version may still be running on an earlier instance of this device, which can no longer be verified as destroyed, so nothing ran. Ask the device's owner to delete the device and create it again, or ask the user to start a new conversation on another device.";
281
- /** The model-facing text of a retirement refusal's code (`device.unavailable` for any other). */
282
- function retirementToolText(code) {
283
- if (code === "device.recreate_required")
284
- return RETIREMENT_RECREATE_TOOL_TEXT;
285
- return RETIREMENT_PENDING_TOOL_TEXT;
279
+ /** What still works without the device: attachments and artifacts are read from file storage. */
280
+ const READ_BY_ID_HINT = "Attachments and artifacts of this conversation can still be read without the device: if Read is available to you, Read with file_id.";
281
+ export const RETIREMENT_PENDING_TOOL_TEXT = `This device is unavailable: background work started by an earlier version may still run on its previous instance, which has not been confirmed destroyed yet, so nothing ran. Retry later (a cloud device becomes usable once its provider confirms the old instance destroyed), continue without the device, or ask the user to start a new conversation on another device. ${READ_BY_ID_HINT}`;
282
+ export const RETIREMENT_RECREATE_TOOL_TEXT = `Background work started by an earlier version may still be running on an earlier instance of this device, which can no longer be verified as destroyed, so nothing ran. Ask the device's owner to delete the device and create it again, or ask the user to start a new conversation on another device. ${READ_BY_ID_HINT}`;
283
+ const RETIREMENT_LOCAL_TOOL_TEXT = `Earlier background work on this device's connected machine has not been confirmed stopped, so nothing ran. Ask the device's owner to open the device page and choose Check again, or use another device. ${READ_BY_ID_HINT}`;
284
+ /** The model-facing text of a retirement refusal. */
285
+ function retirementToolText(error) {
286
+ if (error.code !== "device.recreate_required")
287
+ return RETIREMENT_PENDING_TOOL_TEXT;
288
+ const reason = error.details?.[0]?.reason;
289
+ if (reason === "local_retirement")
290
+ return RETIREMENT_LOCAL_TOOL_TEXT;
291
+ return RETIREMENT_RECREATE_TOOL_TEXT;
286
292
  }
287
293
  /**
288
294
  * A managed operation outside the admitted scope (`SandboxScopeDeniedError`): fixed text, never
@@ -413,7 +419,7 @@ export function mapSandboxError(e, log) {
413
419
  return new ToolError(SANDBOX_CONNECTION_DROPPED_TEXT, { kind: "unavailable" });
414
420
  }
415
421
  if (e instanceof RetirementPendingError) {
416
- return new ToolError(retirementToolText(e.code));
422
+ return new ToolError(retirementToolText(e));
417
423
  }
418
424
  if (e instanceof ApiError) {
419
425
  if (e.code === "sandbox.busy")
@@ -9,10 +9,11 @@ export declare const CONNECTOR_TOOLS_JOB = "connector-tools-list";
9
9
  * What owed the listing: the connector was `created` ready, it turned ready when an org admin
10
10
  * saved its missing input (`configured`), a member saved the first credential of a personal
11
11
  * connector with no tool list yet (`connected`), an org admin changed an editable endpoint
12
- * field of a ready template connector (`endpoint_changed`), or a platform update cleared the
12
+ * field of a ready template connector (`endpoint_changed`), a ready template connector with
13
+ * a stale list was enabled (`reactivated`), or a platform update cleared the
13
14
  * credentials of a template connector whose new auth leaves it ready (`template_updated`).
14
15
  */
15
- export type ConnectorToolsTrigger = "created" | "configured" | "connected" | "endpoint_changed" | "template_updated";
16
+ export type ConnectorToolsTrigger = "created" | "configured" | "connected" | "endpoint_changed" | "reactivated" | "template_updated";
16
17
  /** Data of a {@link CONNECTOR_TOOLS_JOB}; `accountId` is the member whose credential lists. */
17
18
  export interface ConnectorToolsJobData {
18
19
  orgId: string;
@@ -503,6 +503,8 @@ export declare class ConnectorsService {
503
503
  * runs in its transaction.
504
504
  */
505
505
  disableWithPluginIn(orgId: string, connectorId: string, itemId: string): Promise<void>;
506
+ /** Owe a listing before changing the row's status and legacy last-update timestamp. */
507
+ private oweStaleEndpointList;
506
508
  /**
507
509
  * Re-enables a connector the given plugin's switch-off disabled
508
510
  * ({@link disableWithPluginIn}) when the plugin is switched back on and its install takes the
@@ -564,7 +566,7 @@ export declare class ConnectorsService {
564
566
  listToolsForJob(data: ConnectorToolsJobData): Promise<"listed" | "skipped">;
565
567
  /**
566
568
  * The org-locked write of {@link listToolsForJob}; false (nothing written) when the org or the
567
- * connector is gone, disabled or `needs_config` by now.
569
+ * connector is gone, disabled, `needs_config`, or the endpoint changed.
568
570
  */
569
571
  private storeListedIn;
570
572
  /**
@@ -29,6 +29,7 @@ import { OutboxService } from "../infra/outbox/outbox.service.js";
29
29
  import { OrgLock } from "../orgs/org-lock.js";
30
30
  import { firstOrgOwner } from "../orgs/org-owner.js";
31
31
  import { UUID_RE } from "../ui/registry.js";
32
+ import { canonicalJson } from "./canonical-json.js";
32
33
  import { connectorSetup, connectorSetups } from "./connector-setup.js";
33
34
  import { CONNECTOR_TOOLS_JOB, CONNECTOR_TOOLS_QUEUE, connectorToolsJobId, } from "./connector-tools-jobs.js";
34
35
  import { CredentialMissing, Credentials, isOAuth, } from "./credentials.js";
@@ -530,6 +531,7 @@ let ConnectorsService = class ConnectorsService {
530
531
  name,
531
532
  connector: input.connector,
532
533
  endpoint: JSON.stringify(endpoint),
534
+ endpoint_changed_at: sql `now()`,
533
535
  auth: JSON.stringify(auth),
534
536
  git_hosts: input.git !== undefined ? JSON.stringify(input.git.hosts) : null,
535
537
  description: ownDescription(input.description),
@@ -659,6 +661,8 @@ let ConnectorsService = class ConnectorsService {
659
661
  .updateTable("connectors")
660
662
  .set({
661
663
  endpoint: JSON.stringify(p.endpoint),
664
+ endpoint_changed_at: sql `case when endpoint is distinct from ${JSON.stringify(p.endpoint)}::jsonb
665
+ then clock_timestamp() else endpoint_changed_at end`,
662
666
  auth: JSON.stringify(input.auth),
663
667
  git_hosts: input.git !== undefined ? JSON.stringify(input.git.hosts) : null,
664
668
  // "use for git" needs org ownership and git hosts: a template that drops either clears it
@@ -1190,6 +1194,9 @@ let ConnectorsService = class ConnectorsService {
1190
1194
  throw new ApiError("validation_failed", "Request validation failed", problems);
1191
1195
  }
1192
1196
  const ep = patch.endpoint !== undefined ? await this.endpointChange(t, app, patch.endpoint) : undefined;
1197
+ if (patch.status === "active" && app.status === "disabled" && ep === undefined) {
1198
+ await this.oweStaleEndpointList(orgId, app);
1199
+ }
1193
1200
  const gitChanged = patch.useForGit !== undefined && patch.useForGit !== app.use_for_git;
1194
1201
  const description = patch.description !== undefined ? ownDescription(patch.description) : undefined;
1195
1202
  const descriptionChanged = description !== undefined && description !== app.description;
@@ -1210,7 +1217,10 @@ let ConnectorsService = class ConnectorsService {
1210
1217
  }),
1211
1218
  ...(gitChanged && { use_for_git: patch.useForGit === true }),
1212
1219
  ...(descriptionChanged && { description }),
1213
- ...(ep !== undefined && { endpoint: JSON.stringify(ep.endpoint) }),
1220
+ ...(ep !== undefined && {
1221
+ endpoint: JSON.stringify(ep.endpoint),
1222
+ endpoint_changed_at: sql `clock_timestamp()`,
1223
+ }),
1214
1224
  updated_at: sql `now()`,
1215
1225
  })
1216
1226
  .where("id", "=", connectorId)
@@ -1411,6 +1421,27 @@ let ConnectorsService = class ConnectorsService {
1411
1421
  .where("deleted_at", "is", null)
1412
1422
  .execute();
1413
1423
  }
1424
+ /** Owe a listing before changing the row's status and legacy last-update timestamp. */
1425
+ async oweStaleEndpointList(orgId, app) {
1426
+ const auth = app.auth;
1427
+ if (app.platform_template_id === null ||
1428
+ (auth.type !== "none" && auth.ownership === "personal")) {
1429
+ return;
1430
+ }
1431
+ const stale = await this.db
1432
+ .selectFrom("connectors")
1433
+ .select("id")
1434
+ .where("org_id", "=", orgId)
1435
+ .where("id", "=", app.id)
1436
+ .where((eb) => eb.or([
1437
+ eb("tools_synced_at", "is", null),
1438
+ eb("tools_synced_at", "<", sql `coalesce(endpoint_changed_at, updated_at)`),
1439
+ ]))
1440
+ .executeTakeFirst();
1441
+ if (stale && (await this.setupOf(orgId, app)) === "ready") {
1442
+ await this.oweToolList(orgId, app.id, "reactivated");
1443
+ }
1444
+ }
1414
1445
  /**
1415
1446
  * Re-enables a connector the given plugin's switch-off disabled
1416
1447
  * ({@link disableWithPluginIn}) when the plugin is switched back on and its install takes the
@@ -1418,17 +1449,27 @@ let ConnectorsService = class ConnectorsService {
1418
1449
  * or one another state left disabled stays disabled. Returns whether it switched it on.
1419
1450
  */
1420
1451
  async enableIfPluginDisabledIn(orgId, connectorId, itemId) {
1421
- const r = await this.db
1422
- .updateTable("connectors")
1423
- .set({ status: "active", disabled_by_plugin_id: null, updated_at: sql `now()` })
1452
+ await this.orgLock.lock(orgId);
1453
+ const app = await this.db
1454
+ .selectFrom("connectors")
1455
+ .select(["id", "auth", "platform_template_id"])
1424
1456
  .where("id", "=", connectorId)
1425
1457
  .where("org_id", "=", orgId)
1426
1458
  .where("deleted_at", "is", null)
1427
1459
  .where("status", "=", "disabled")
1428
1460
  .where("disabled_by_plugin_id", "=", itemId)
1429
- .returning("id")
1461
+ .forUpdate()
1430
1462
  .executeTakeFirst();
1431
- return r !== undefined;
1463
+ if (!app)
1464
+ return false;
1465
+ await this.oweStaleEndpointList(orgId, app);
1466
+ await this.db
1467
+ .updateTable("connectors")
1468
+ .set({ status: "active", disabled_by_plugin_id: null, updated_at: sql `now()` })
1469
+ .where("id", "=", connectorId)
1470
+ .where("org_id", "=", orgId)
1471
+ .execute();
1472
+ return true;
1432
1473
  }
1433
1474
  /**
1434
1475
  * Disables or enables a connector on the platform's behalf (a super admin who need not be a
@@ -1441,6 +1482,9 @@ let ConnectorsService = class ConnectorsService {
1441
1482
  const orgId = await this.liveOrgOf(connectorId);
1442
1483
  await this.orgLock.lock(orgId);
1443
1484
  const app = await this.row(t, orgId, connectorId, true);
1485
+ if (status === "active" && app.status === "disabled") {
1486
+ await this.oweStaleEndpointList(orgId, app);
1487
+ }
1444
1488
  await t
1445
1489
  .updateTable("connectors")
1446
1490
  // The platform's explicit choice replaces a plugin switch-off's: a later plugin switch-on
@@ -1525,13 +1569,17 @@ let ConnectorsService = class ConnectorsService {
1525
1569
  const auth = app.auth;
1526
1570
  const { specs, resources } = await this.drift.listTools(orgId, app.connector, app.endpoint, () => this.credentials.injection(orgId, connectorId, auth, actorAccountId), { connectorId }, (last) => this.credentials.onUnauthorized(orgId, connectorId, auth, actorAccountId, last));
1527
1571
  const { rows, issues } = snapshot(app.slug, specs, resources);
1528
- return this.refreshIn(orgId, connectorId, actorAccountId, actorTokenId, opts, rows, issues);
1572
+ return this.refreshIn(orgId, connectorId, actorAccountId, actorTokenId, opts, app.endpoint, rows, issues);
1529
1573
  }
1530
1574
  /** The org-locked compare-and-write of {@link refresh} (the tool list was fetched before). */
1531
- async refreshIn(orgId, connectorId, actorAccountId, actorTokenId, opts, rows, issues) {
1575
+ async refreshIn(orgId, connectorId, actorAccountId, actorTokenId, opts, listedEndpoint, rows, issues) {
1532
1576
  const t = this.db;
1533
1577
  await this.orgLock.lockAndAuthorize(orgId, actorAccountId, opts.trigger === "first_connect" ? "connectors.use" : "connectors.manage");
1534
- const changes = await this.drift.apply(await this.row(t, orgId, connectorId, true), rows);
1578
+ const app = await this.row(t, orgId, connectorId, true);
1579
+ if (canonicalJson(app.endpoint) !== canonicalJson(listedEndpoint)) {
1580
+ throw new ApiError("conflict", "The connector endpoint changed during the refresh. Retry the refresh.");
1581
+ }
1582
+ const changes = await this.drift.apply(app, rows);
1535
1583
  await audit(t, {
1536
1584
  actorAccountId,
1537
1585
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -1588,13 +1636,15 @@ let ConnectorsService = class ConnectorsService {
1588
1636
  throw e;
1589
1637
  }
1590
1638
  const { rows } = snapshot(app.slug, listed.specs, listed.resources);
1591
- return (await this.storeListedIn(orgId, connectorId, rows, accountId)) ? "listed" : "skipped";
1639
+ return (await this.storeListedIn(orgId, connectorId, app.endpoint, rows, accountId))
1640
+ ? "listed"
1641
+ : "skipped";
1592
1642
  }
1593
1643
  /**
1594
1644
  * The org-locked write of {@link listToolsForJob}; false (nothing written) when the org or the
1595
- * connector is gone, disabled or `needs_config` by now.
1645
+ * connector is gone, disabled, `needs_config`, or the endpoint changed.
1596
1646
  */
1597
- async storeListedIn(orgId, connectorId, rows, accountId) {
1647
+ async storeListedIn(orgId, connectorId, listedEndpoint, rows, accountId) {
1598
1648
  const t = this.db;
1599
1649
  if (!(await this.orgLock.tryLock(orgId)))
1600
1650
  return false;
@@ -1609,6 +1659,8 @@ let ConnectorsService = class ConnectorsService {
1609
1659
  // switched off or lost its input since the listing: write nothing (a later save owes a job)
1610
1660
  if (locked?.status !== "active")
1611
1661
  return false;
1662
+ if (canonicalJson(locked.endpoint) !== canonicalJson(listedEndpoint))
1663
+ return false;
1612
1664
  if ((await this.setupOf(orgId, locked)) !== "ready")
1613
1665
  return false;
1614
1666
  const changes = await this.drift.apply(locked, rows);
@@ -25,7 +25,7 @@ export type DriftCheckResult = {
25
25
  changes: DriftChanges;
26
26
  } | {
27
27
  status: "skipped";
28
- reason: "not_found" | "inactive" | "no_connector" | "no_credential" | "connect_failed";
28
+ reason: "not_found" | "inactive" | "endpoint_changed" | "no_connector" | "no_credential" | "connect_failed";
29
29
  };
30
30
  type ToolSource = "connector" | "resources";
31
31
  /** 快照中被停用 / 跳过的工具及英文原因。 */
@@ -495,17 +495,14 @@ let ToolDrift = class ToolDrift {
495
495
  return { status: "skipped", reason };
496
496
  }
497
497
  const { rows } = snapshot(app.slug, listed.specs, listed.resources);
498
- const changes = await this.applyChecked(orgId, connectorId, trigger, rows);
499
- if (!changes)
500
- return { status: "skipped", reason: "inactive" };
501
- return { status: "checked", changes };
498
+ return this.applyChecked(orgId, connectorId, trigger, app.endpoint, rows);
502
499
  }
503
500
  /** The locked compare-and-write of {@link check}, audited when something changed. */
504
- async applyChecked(orgId, connectorId, trigger, rows) {
501
+ async applyChecked(orgId, connectorId, trigger, listedEndpoint, rows) {
505
502
  const t = this.db.db;
506
503
  const locked = await t
507
504
  .selectFrom("connectors")
508
- .select(["id", "tools_synced_at", "template_tool_policies"])
505
+ .select(["id", "endpoint", "tools_synced_at", "template_tool_policies"])
509
506
  .where("id", "=", connectorId)
510
507
  .where("org_id", "=", orgId)
511
508
  .where("deleted_at", "is", null)
@@ -513,22 +510,25 @@ let ToolDrift = class ToolDrift {
513
510
  .forUpdate()
514
511
  .executeTakeFirst();
515
512
  if (!locked)
516
- return null;
517
- const c = await this.apply(locked, rows);
518
- if (c.added.length + c.changed.length + c.removed.length > 0) {
513
+ return { status: "skipped", reason: "inactive" };
514
+ if (canonicalJson(locked.endpoint) !== canonicalJson(listedEndpoint)) {
515
+ return { status: "skipped", reason: "endpoint_changed" };
516
+ }
517
+ const changes = await this.apply(locked, rows);
518
+ if (changes.added.length + changes.changed.length + changes.removed.length > 0) {
519
519
  await audit(t, {
520
520
  orgId,
521
521
  action: "connector.tools_drifted",
522
522
  target: connectorId,
523
523
  detail: {
524
- added: c.added.length,
525
- changed: c.changed.length,
526
- removed: c.removed.length,
524
+ added: changes.added.length,
525
+ changed: changes.changed.length,
526
+ removed: changes.removed.length,
527
527
  trigger,
528
528
  },
529
529
  });
530
530
  }
531
- return c;
531
+ return { status: "checked", changes };
532
532
  }
533
533
  /**
534
534
  * 连接器在会话中报告工具清单变了:投递一次该连接器的检查(jobId 按分钟桶去重)。投递失败只记日志。
@@ -740,6 +740,10 @@ export declare class ToolPipeline {
740
740
  private networkBlocked;
741
741
  /** The call's live loopback port grant (null: none, ended, or no grants service). */
742
742
  private loopbackGrantOf;
743
+ /**
744
+ * The attempt that recorded a ready-grant loopback rerun for this call, or null when none did.
745
+ */
746
+ private readyLoopbackRerunOf;
743
747
  /**
744
748
  * A device service's loopback refusal (browser loopback port grants): the port of the person's
745
749
  * own device a service of an extension declaring `permissions.deviceAccess.loopbackPorts` was