@capybara-hq/kernel 0.1.0-rc.117 → 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 (61) 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/component-scope.service.js +2 -1
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/catalog/plugin-install.d.ts +1 -0
  6. package/dist/catalog/plugin-install.js +11 -1
  7. package/dist/conversations/conversations.controller.d.ts +1 -1
  8. package/dist/conversations/conversations.controller.js +1 -1
  9. package/dist/conversations/conversations.service.d.ts +4 -2
  10. package/dist/conversations/conversations.service.js +17 -3
  11. package/dist/conversations/events.d.ts +9 -1
  12. package/dist/conversations/events.js +2 -0
  13. package/dist/db/kernel-schema.d.ts +15 -1
  14. package/dist/devices/devices.controller.d.ts +5 -0
  15. package/dist/devices/devices.controller.js +20 -2
  16. package/dist/devices/devices.service.d.ts +3 -1
  17. package/dist/devices/devices.service.js +4 -0
  18. package/dist/evals/plan.d.ts +3 -1
  19. package/dist/evals/plan.js +25 -5
  20. package/dist/evals/runs.service.js +3 -2
  21. package/dist/evals/trajectory.js +1 -0
  22. package/dist/files/blob-references.d.ts +8 -0
  23. package/dist/files/blob-references.js +19 -0
  24. package/dist/files/blob-sweep.job.js +5 -23
  25. package/dist/files/library-files.service.js +8 -4
  26. package/dist/models/cache-write-usage.d.ts +3 -0
  27. package/dist/models/cache-write-usage.js +26 -0
  28. package/dist/models/images.js +5 -1
  29. package/dist/models/prices.d.ts +8 -6
  30. package/dist/models/prices.js +28 -3
  31. package/dist/orgs/settings.controller.d.ts +4 -17
  32. package/dist/orgs/settings.controller.js +5 -9
  33. package/dist/orgs/settings.service.d.ts +12 -0
  34. package/dist/orgs/settings.service.js +24 -0
  35. package/dist/platform/exclusions.js +6 -0
  36. package/dist/platform/ops/admin.ops.js +2 -2
  37. package/dist/platform/ops/conversations.ops.js +1 -1
  38. package/dist/platform/ops/devices.ops.js +7 -0
  39. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  40. package/dist/platform/ops/org-settings.ops.js +10 -10
  41. package/dist/runtime/context/build.d.ts +2 -0
  42. package/dist/runtime/context/build.js +9 -1
  43. package/dist/runtime/usage-report.js +3 -0
  44. package/dist/sandbox/legacy-retirement.d.ts +15 -0
  45. package/dist/sandbox/legacy-retirement.js +243 -3
  46. package/dist/sandbox/permission-instance-writes.d.ts +4 -1
  47. package/dist/sandbox/permission-instance-writes.js +55 -1
  48. package/dist/sandbox/providers.d.ts +6 -1
  49. package/dist/sandbox/providers.js +15 -1
  50. package/dist/sandbox/sandbox.service.d.ts +6 -3
  51. package/dist/sandbox/sandbox.service.js +116 -5
  52. package/dist/tools/builtins/sandbox/common.js +10 -6
  53. package/dist/tools/connector-tools-jobs.d.ts +3 -2
  54. package/dist/tools/connectors.service.d.ts +3 -1
  55. package/dist/tools/connectors.service.js +64 -12
  56. package/dist/tools/drift.d.ts +1 -1
  57. package/dist/tools/drift.js +13 -13
  58. package/package.json +2 -2
  59. package/src/migrations/0202_connector_endpoint_changed_at.sql +1 -0
  60. package/src/migrations/0203_model_cache_write_pricing.sql +5 -0
  61. 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
  /**
@@ -3287,6 +3393,11 @@ let SandboxService = class SandboxService {
3287
3393
  // instance has none yet (NULL): its first commit is no roots change (no consent reset, no
3288
3394
  // revoke)
3289
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));
3290
3401
  await this.fenced(held, id, fence, {
3291
3402
  org_id: ctx.orgId,
3292
3403
  provider: p.plugin,
@@ -3373,7 +3484,7 @@ let SandboxService = class SandboxService {
3373
3484
  running_since: sql `now()`,
3374
3485
  last_used_at: sql `now()`,
3375
3486
  ...(!atFileSystem && { instance_limits: record }),
3376
- }, held.signal, support));
3487
+ }, held.signal, support, localRetirementGeneration(p, handle, id)));
3377
3488
  fence.gen++;
3378
3489
  }
3379
3490
  catch (e) {
@@ -280,11 +280,15 @@ export const OUTSIDE_SANDBOX_CEILING_TOOL_TEXT = "This device does not allow run
280
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
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
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
- /** The model-facing text of a retirement refusal's code (`device.unavailable` for any other). */
284
- function retirementToolText(code) {
285
- if (code === "device.recreate_required")
286
- return RETIREMENT_RECREATE_TOOL_TEXT;
287
- return RETIREMENT_PENDING_TOOL_TEXT;
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;
288
292
  }
289
293
  /**
290
294
  * A managed operation outside the admitted scope (`SandboxScopeDeniedError`): fixed text, never
@@ -415,7 +419,7 @@ export function mapSandboxError(e, log) {
415
419
  return new ToolError(SANDBOX_CONNECTION_DROPPED_TEXT, { kind: "unavailable" });
416
420
  }
417
421
  if (e instanceof RetirementPendingError) {
418
- return new ToolError(retirementToolText(e.code));
422
+ return new ToolError(retirementToolText(e));
419
423
  }
420
424
  if (e instanceof ApiError) {
421
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 按分钟桶去重)。投递失败只记日志。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.117",
3
+ "version": "0.1.0-rc.118",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  "yaml": "^2.9.1",
67
67
  "yauzl": "3.4.0",
68
68
  "zod": "^4.6.7",
69
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.92"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.93"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -0,0 +1 @@
1
+ ALTER TABLE connectors ADD COLUMN IF NOT EXISTS endpoint_changed_at timestamptz;
@@ -0,0 +1,5 @@
1
+ ALTER TABLE model_prices ADD COLUMN IF NOT EXISTS cache_write_per_mtok_by_ttl jsonb NOT NULL
2
+ DEFAULT '{}'::jsonb CHECK (jsonb_typeof(cache_write_per_mtok_by_ttl) = 'object');
3
+
4
+ ALTER TABLE model_usage ADD COLUMN IF NOT EXISTS cache_write_by_ttl jsonb
5
+ CHECK (cache_write_by_ttl IS NULL OR jsonb_typeof(cache_write_by_ttl) = 'array');
@@ -0,0 +1,46 @@
1
+ -- Keep the exact local provider generation separately from the kernel's incarnation timestamp.
2
+ CREATE TABLE IF NOT EXISTS device_instance_retirement_identities (
3
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
4
+ device_id text NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
5
+ provider text NOT NULL,
6
+ instance_generation text NOT NULL CHECK (instance_generation ~ '^[1-9][0-9]{0,15}$'),
7
+ provider_generation text NOT NULL CHECK (provider_generation ~ '^[1-9][0-9]{0,15}$'),
8
+ -- Kept separately from unconditional provider destruction evidence.
9
+ attested_at timestamptz,
10
+ PRIMARY KEY (org_id, device_id, provider, instance_generation),
11
+ UNIQUE (org_id, device_id, provider, provider_generation)
12
+ );
13
+
14
+ DROP POLICY IF EXISTS org_scope ON device_instance_retirement_identities;
15
+ CREATE POLICY org_scope ON device_instance_retirement_identities
16
+ USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
17
+
18
+ -- Older workers also add members. Reopen a proof-based resolution atomically with any addition,
19
+ -- so the existing finisher can never inherit authority for a member the check did not validate.
20
+ CREATE OR REPLACE FUNCTION reopen_local_retirement_proof() RETURNS trigger
21
+ LANGUAGE plpgsql SET search_path FROM CURRENT AS $$
22
+ BEGIN
23
+ UPDATE device_retirement_obligations AS o
24
+ SET state = 'quarantined', resolution = NULL, resolved_at = NULL,
25
+ reason = 'a retirement member has yet to be covered by checked machine evidence'
26
+ WHERE o.id = NEW.obligation_id
27
+ AND o.provider = 'device-local'
28
+ AND o.state = 'resolved'
29
+ AND o.resolution = 'provider-destroyed'
30
+ AND EXISTS (
31
+ SELECT 1 FROM device_instance_retirement_identities AS i
32
+ WHERE i.org_id = o.org_id AND i.device_id = o.device_id AND i.provider = o.provider
33
+ AND i.instance_generation = o.instance_generation AND i.attested_at IS NOT NULL
34
+ )
35
+ AND NOT EXISTS (
36
+ SELECT 1 FROM device_instance_destructions AS d
37
+ WHERE d.device_id = o.device_id AND d.provider = o.provider
38
+ AND d.instance_generation = o.instance_generation
39
+ );
40
+ RETURN NEW;
41
+ END
42
+ $$;
43
+
44
+ CREATE OR REPLACE TRIGGER device_retirement_proof_new_member
45
+ AFTER INSERT ON device_retirement_members
46
+ FOR EACH ROW EXECUTE FUNCTION reopen_local_retirement_proof();