memeloop 0.2.4 → 0.2.5

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 (96) hide show
  1. package/dist/browser.d.cts +26 -21
  2. package/dist/browser.d.ts +26 -21
  3. package/dist/chunk-4OITUYFC.js +37 -0
  4. package/dist/chunk-4OITUYFC.js.map +1 -0
  5. package/dist/{chunk-HY3U3GLE.js → chunk-5EUJNLVW.js} +1 -1
  6. package/dist/chunk-5EUJNLVW.js.map +1 -0
  7. package/dist/{chunk-KXVZQLJL.js → chunk-645GZGNM.js} +3 -2
  8. package/dist/chunk-645GZGNM.js.map +1 -0
  9. package/dist/{chunk-EPHRIRAL.js → chunk-6OLAL5CW.js} +16 -1
  10. package/dist/chunk-6OLAL5CW.js.map +1 -0
  11. package/dist/{chunk-LGUGYRR4.js → chunk-HVLCOJWI.js} +11 -6
  12. package/dist/{chunk-LGUGYRR4.js.map → chunk-HVLCOJWI.js.map} +1 -1
  13. package/dist/{chunk-5VYZV33O.js → chunk-KTZDDC7M.js} +64 -79
  14. package/dist/chunk-KTZDDC7M.js.map +1 -0
  15. package/dist/{chunk-K5KZJNDP.js → chunk-ROPAEJIM.js} +2 -2
  16. package/dist/{chunk-XNSJRDCW.js → chunk-UB77WKAU.js} +202 -344
  17. package/dist/chunk-UB77WKAU.js.map +1 -0
  18. package/dist/{chunk-KV6TC5UJ.js → chunk-XIEXGFPY.js} +3 -3
  19. package/dist/conversation.d.cts +4 -3
  20. package/dist/conversation.d.ts +4 -3
  21. package/dist/device-network-portable.cjs +2 -1
  22. package/dist/device-network-portable.cjs.map +1 -1
  23. package/dist/device-network-portable.d.cts +9 -7
  24. package/dist/device-network-portable.d.ts +9 -7
  25. package/dist/device-network-portable.js +1 -1
  26. package/dist/device-network.cjs +17 -1
  27. package/dist/device-network.cjs.map +1 -1
  28. package/dist/device-network.d.cts +6 -5
  29. package/dist/device-network.d.ts +6 -5
  30. package/dist/device-network.js +2 -2
  31. package/dist/{fetchProvider-B_vva3b3.d.ts → fetchProvider-Do8Hf1BN.d.ts} +1 -1
  32. package/dist/{fetchProvider-Bz4CE3_R.d.cts → fetchProvider-tMo6gc6N.d.cts} +1 -1
  33. package/dist/index.cjs +336 -438
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.cts +20 -26
  36. package/dist/index.d.ts +20 -26
  37. package/dist/index.js +29 -46
  38. package/dist/index.js.map +1 -1
  39. package/dist/{interface-3C3eG8Hn.d.cts → interface-C54gkLA3.d.ts} +3 -110
  40. package/dist/{interface-3C3eG8Hn.d.ts → interface-CECFnbzR.d.cts} +3 -110
  41. package/dist/llm-providers.cjs.map +1 -1
  42. package/dist/llm-providers.d.cts +3 -2
  43. package/dist/llm-providers.d.ts +3 -2
  44. package/dist/llm-providers.js +1 -1
  45. package/dist/llm-providers.js.map +1 -1
  46. package/dist/loop-api.cjs +81 -82
  47. package/dist/loop-api.cjs.map +1 -1
  48. package/dist/loop-api.d.cts +8 -7
  49. package/dist/loop-api.d.ts +8 -7
  50. package/dist/loop-api.js +5 -5
  51. package/dist/mobile.cjs +10 -5
  52. package/dist/mobile.cjs.map +1 -1
  53. package/dist/mobile.d.cts +6 -5
  54. package/dist/mobile.d.ts +6 -5
  55. package/dist/mobile.js +3 -3
  56. package/dist/{orchestration-portable-DUoAjtD1.d.ts → orchestration-portable-CQRrnoEw.d.ts} +5 -4
  57. package/dist/{orchestration-portable-xJ7z-ctw.d.cts → orchestration-portable-D4KBEYQb.d.cts} +5 -4
  58. package/dist/orchestration-portable.cjs +201 -343
  59. package/dist/orchestration-portable.cjs.map +1 -1
  60. package/dist/orchestration-portable.d.cts +6 -5
  61. package/dist/orchestration-portable.d.ts +6 -5
  62. package/dist/orchestration-portable.js +1 -1
  63. package/dist/{pairingInvite-C12n-7Ak.d.cts → pairingInvite-BmCQ-bHt.d.cts} +3 -3
  64. package/dist/{pairingInvite-CPQkuhLQ.d.ts → pairingInvite-CsfsexXC.d.ts} +3 -3
  65. package/dist/{promptConcat-VLe5SEN4.d.cts → promptConcat-BqImJtVh.d.cts} +7 -4
  66. package/dist/{promptConcat-CUEIA_3T.d.ts → promptConcat-C5SEgESi.d.ts} +7 -4
  67. package/dist/{providerRegistry-CaFK_aUd.d.ts → providerRegistry-BGrwd7Zl.d.cts} +2 -2
  68. package/dist/{providerRegistry-BDGGs5gz.d.cts → providerRegistry-Bs2lJpj9.d.ts} +2 -2
  69. package/dist/{registry-DNSEVYug.d.cts → registry-CelnriUR.d.cts} +3 -3
  70. package/dist/{registry-yGnYHWhq.d.ts → registry-DVv_RVPZ.d.ts} +3 -3
  71. package/dist/{remoteClient-DwBCoHpc.d.ts → remoteClient-D1gPizds.d.ts} +1 -1
  72. package/dist/{remoteClient-DFIyCZEv.d.cts → remoteClient-DxCHC4_Z.d.cts} +1 -1
  73. package/dist/{runtime-6EELHWVB.js → runtime-SASMRN4I.js} +3 -3
  74. package/dist/{scriptDeploymentPipeline-B1q-UhrO.d.ts → scriptDeploymentPipeline-CdDLEDMS.d.cts} +10 -1
  75. package/dist/{scriptDeploymentPipeline-XJzQyYys.d.cts → scriptDeploymentPipeline-DU6sor6Y.d.ts} +10 -1
  76. package/dist/{syncCloudDevices-C8fCUhnX.d.ts → syncCloudDevices-3RmB41sA.d.cts} +6 -2
  77. package/dist/{syncCloudDevices-BFw_c1g5.d.cts → syncCloudDevices-CSLbMESm.d.ts} +6 -2
  78. package/dist/tools.cjs +63 -0
  79. package/dist/tools.cjs.map +1 -0
  80. package/dist/tools.d.cts +12 -0
  81. package/dist/tools.d.ts +12 -0
  82. package/dist/tools.js +7 -0
  83. package/dist/tools.js.map +1 -0
  84. package/dist/{types-CcFFIk8W.d.ts → types-C29NBZ2w.d.ts} +1 -1
  85. package/dist/types-CcoJ_fdH.d.cts +110 -0
  86. package/dist/types-CcoJ_fdH.d.ts +110 -0
  87. package/dist/{types-C8gnhG9M.d.cts → types-D1rAJy9l.d.cts} +1 -1
  88. package/package.json +6 -1
  89. package/dist/chunk-5VYZV33O.js.map +0 -1
  90. package/dist/chunk-EPHRIRAL.js.map +0 -1
  91. package/dist/chunk-HY3U3GLE.js.map +0 -1
  92. package/dist/chunk-KXVZQLJL.js.map +0 -1
  93. package/dist/chunk-XNSJRDCW.js.map +0 -1
  94. /package/dist/{chunk-K5KZJNDP.js.map → chunk-ROPAEJIM.js.map} +0 -0
  95. /package/dist/{chunk-KV6TC5UJ.js.map → chunk-XIEXGFPY.js.map} +0 -0
  96. /package/dist/{runtime-6EELHWVB.js.map → runtime-SASMRN4I.js.map} +0 -0
package/dist/index.cjs CHANGED
@@ -1567,12 +1567,13 @@ function createFleetRolloutController(_store, options) {
1567
1567
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
1568
1568
  async function reconcileRollout(request) {
1569
1569
  const rollout = request.resource;
1570
- const status = rollout.status ?? {};
1570
+ const previousStatus = rollout.status;
1571
+ const status = previousStatus?.observedGeneration !== void 0 && previousStatus.observedGeneration !== rollout.metadata.generation ? void 0 : previousStatus;
1571
1572
  const spec = rollout.spec;
1572
- if (status.phase === "Completed" || status.phase === "Failed" || status.phase === "RolledBack") {
1573
- return { ready: true };
1573
+ if (status?.phase === "Completed" || status?.phase === "Failed" || status?.phase === "RolledBack") {
1574
+ return status.observedGeneration === rollout.metadata.generation ? { ready: true } : { status, ready: true };
1574
1575
  }
1575
- if (!status.phase) {
1576
+ if (!status || status.phase === "Pending") {
1576
1577
  return {
1577
1578
  status: {
1578
1579
  ...status,
@@ -1907,6 +1908,7 @@ function createFleetRolloutController(_store, options) {
1907
1908
  if (result.status) {
1908
1909
  result.status = {
1909
1910
  ...result.status,
1911
+ observedGeneration: request.resource.metadata.generation,
1910
1912
  consumedBudget: sumEvidenceUsage(result.status.evidence)
1911
1913
  };
1912
1914
  }
@@ -3522,6 +3524,81 @@ var init_secretRedaction = __esm({
3522
3524
  }
3523
3525
  });
3524
3526
 
3527
+ // src/orchestration/drivers/driverState.ts
3528
+ function assertFencedDriverRequestEnvelope(request, options) {
3529
+ assertDriverRequestEnvelope(request, {
3530
+ now: options.now,
3531
+ requireRun: options.requireRun,
3532
+ requireFencing: true,
3533
+ requireCapability: true,
3534
+ expectedMethod: options.expectedMethod
3535
+ });
3536
+ if (options.actorKinds && !options.actorKinds.includes(request.actor.kind)) {
3537
+ throw new OrchestrationError({
3538
+ code: "FORBIDDEN",
3539
+ message: options.forbiddenMessage?.(request.actor.kind) ?? `actor kind '${request.actor.kind}' cannot call ${options.expectedMethod}`,
3540
+ retryable: false
3541
+ });
3542
+ }
3543
+ const epoch = request.fencingEpoch;
3544
+ const current = options.fences.get(request.resource.uid) ?? 0;
3545
+ if (epoch < current) {
3546
+ throw new OrchestrationError({
3547
+ code: "STALE_EPOCH",
3548
+ message: `stale ${options.fenceName} fencing epoch ${epoch}; current epoch is ${current}`,
3549
+ retryable: false
3550
+ });
3551
+ }
3552
+ options.fences.set(request.resource.uid, epoch);
3553
+ return epoch;
3554
+ }
3555
+ function driverOperationKey(request, operation) {
3556
+ return `${request.resource.uid}:${operation}:${request.idempotencyKey}`;
3557
+ }
3558
+ function findIdempotentDriverHandle(state, request, operation, driverName) {
3559
+ const key = driverOperationKey(request, operation);
3560
+ const handle = state.idempotency.get(key);
3561
+ if (handle === void 0) return void 0;
3562
+ if (state.idempotencyFingerprints.get(key) !== canonicalDriverValue(request.payload)) {
3563
+ throw new OrchestrationError({
3564
+ code: "CONFLICT",
3565
+ message: `${driverName} ${operation} idempotency key was reused with different input`,
3566
+ retryable: false
3567
+ });
3568
+ }
3569
+ return handle;
3570
+ }
3571
+ function rememberIdempotentDriverHandle(state, request, operation, handle) {
3572
+ const key = driverOperationKey(request, operation);
3573
+ state.idempotency.set(key, handle);
3574
+ state.idempotencyFingerprints.set(key, canonicalDriverValue(request.payload));
3575
+ }
3576
+ function getOwnedDriverValue(collection, handle, resourceUid, kind) {
3577
+ const value = collection.get(handle);
3578
+ if (!value) {
3579
+ throw new OrchestrationError({
3580
+ code: "NOT_FOUND",
3581
+ message: `${kind} handle '${handle}' was not found`,
3582
+ retryable: false
3583
+ });
3584
+ }
3585
+ if (value.resourceUid !== resourceUid) {
3586
+ throw new OrchestrationError({
3587
+ code: "FORBIDDEN",
3588
+ message: `${kind} handle '${handle}' belongs to another resource`,
3589
+ retryable: false
3590
+ });
3591
+ }
3592
+ return value;
3593
+ }
3594
+ var init_driverState = __esm({
3595
+ "src/orchestration/drivers/driverState.ts"() {
3596
+ "use strict";
3597
+ init_errors();
3598
+ init_driverRequest();
3599
+ }
3600
+ });
3601
+
3525
3602
  // src/orchestration/drivers/auditTelemetryManagement.ts
3526
3603
  function createFakeAuditTelemetryState() {
3527
3604
  return {
@@ -3535,16 +3612,8 @@ function createFakeAuditTelemetryState() {
3535
3612
  function invalid3(message) {
3536
3613
  throw new OrchestrationError({ code: "INVALID", message, retryable: false });
3537
3614
  }
3538
- function stable(value) {
3539
- if (value === void 0) return "undefined";
3540
- if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
3541
- if (value !== null && typeof value === "object") {
3542
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${stable(item)}`).join(",")}}`;
3543
- }
3544
- return JSON.stringify(value) ?? typeof value;
3545
- }
3546
3615
  async function digest(value) {
3547
- const bytes = new TextEncoder().encode(stable(value));
3616
+ const bytes = new TextEncoder().encode(canonicalDriverValue(value));
3548
3617
  const result = await globalThis.crypto.subtle.digest("SHA-256", bytes);
3549
3618
  return `sha256:${[...new Uint8Array(result)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
3550
3619
  }
@@ -3562,29 +3631,13 @@ function createFakeAuditTelemetryManagementDriver(options = {}) {
3562
3631
  const maxRecordsPerResource = options.maxRecordsPerResource ?? 1e4;
3563
3632
  const maxAttributes = options.maxAttributes ?? 16;
3564
3633
  function validate(request, expectedMethod, actorKinds) {
3565
- assertDriverRequestEnvelope(request, {
3634
+ assertFencedDriverRequestEnvelope(request, {
3566
3635
  now,
3567
- requireFencing: true,
3568
- requireCapability: true,
3569
- expectedMethod
3636
+ fences: state.fences,
3637
+ expectedMethod,
3638
+ fenceName: "audit",
3639
+ actorKinds
3570
3640
  });
3571
- if (!actorKinds.includes(request.actor.kind)) {
3572
- throw new OrchestrationError({
3573
- code: "FORBIDDEN",
3574
- message: `actor kind '${request.actor.kind}' cannot call ${expectedMethod}`,
3575
- retryable: false
3576
- });
3577
- }
3578
- const epoch = request.fencingEpoch;
3579
- const current = state.fences.get(request.resource.uid) ?? 0;
3580
- if (epoch < current) {
3581
- throw new OrchestrationError({
3582
- code: "STALE_EPOCH",
3583
- message: `stale audit fencing epoch ${epoch}; current epoch is ${current}`,
3584
- retryable: false
3585
- });
3586
- }
3587
- state.fences.set(request.resource.uid, epoch);
3588
3641
  }
3589
3642
  function common(request) {
3590
3643
  const policyDigest = requiredString2(request.payload, "policyDigest", 80);
@@ -3614,7 +3667,7 @@ function createFakeAuditTelemetryManagementDriver(options = {}) {
3614
3667
  }
3615
3668
  async function append(request, kind, data) {
3616
3669
  const idempotencyKey = `${request.resource.uid}:${request.method}:${request.idempotencyKey}`;
3617
- const fingerprint = stable(request.payload);
3670
+ const fingerprint = canonicalDriverValue(request.payload);
3618
3671
  let release;
3619
3672
  const previousAppend = state.appendTail;
3620
3673
  state.appendTail = new Promise((resolve) => {
@@ -3953,6 +4006,7 @@ var init_auditTelemetryManagement = __esm({
3953
4006
  init_errors();
3954
4007
  init_secretRedaction();
3955
4008
  init_driverRequest();
4009
+ init_driverState();
3956
4010
  SHA256 = /^sha256:[a-f0-9]{64}$/;
3957
4011
  FORBIDDEN_ATTRIBUTE = /(?:secret|token|password|credential|authorization|cookie|private[-_]?key)/i;
3958
4012
  }
@@ -6399,24 +6453,6 @@ function requiredString4(payload, field) {
6399
6453
  if (payload === null || typeof payload !== "object" || typeof payload[field] !== "string" || !payload[field]) invalid9(`identity payload '${field}' is required`);
6400
6454
  return payload[field];
6401
6455
  }
6402
- function owned(collection, handle, resourceUid, kind) {
6403
- const value = collection.get(handle);
6404
- if (!value) {
6405
- throw new OrchestrationError({
6406
- code: "NOT_FOUND",
6407
- message: `${kind} handle '${handle}' was not found`,
6408
- retryable: false
6409
- });
6410
- }
6411
- if (value.resourceUid !== resourceUid) {
6412
- throw new OrchestrationError({
6413
- code: "FORBIDDEN",
6414
- message: `${kind} handle '${handle}' belongs to another resource`,
6415
- retryable: false
6416
- });
6417
- }
6418
- return value;
6419
- }
6420
6456
  function createFakeIdentityAttestationManagementDriver(options = {}) {
6421
6457
  const state = options.state ?? createFakeIdentityAttestationState();
6422
6458
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
@@ -6433,29 +6469,13 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6433
6469
  `sha256:${"a".repeat(64)}`
6434
6470
  ];
6435
6471
  function validate(request, expectedMethod, actorKinds) {
6436
- assertDriverRequestEnvelope(request, {
6472
+ assertFencedDriverRequestEnvelope(request, {
6437
6473
  now,
6438
- requireFencing: true,
6439
- requireCapability: true,
6440
- expectedMethod
6474
+ fences: state.fences,
6475
+ expectedMethod,
6476
+ fenceName: "identity",
6477
+ actorKinds
6441
6478
  });
6442
- if (!actorKinds.includes(request.actor.kind)) {
6443
- throw new OrchestrationError({
6444
- code: "FORBIDDEN",
6445
- message: `actor kind '${request.actor.kind}' cannot call ${expectedMethod}`,
6446
- retryable: false
6447
- });
6448
- }
6449
- const fence = request.fencingEpoch;
6450
- const current = state.fences.get(request.resource.uid) ?? 0;
6451
- if (fence < current) {
6452
- throw new OrchestrationError({
6453
- code: "STALE_EPOCH",
6454
- message: `stale identity fencing epoch ${fence}; current epoch is ${current}`,
6455
- retryable: false
6456
- });
6457
- }
6458
- state.fences.set(request.resource.uid, fence);
6459
6479
  }
6460
6480
  function ttl(payload, field, maximum) {
6461
6481
  if (payload === null || typeof payload !== "object") {
@@ -6470,34 +6490,11 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6470
6490
  state.nextHandle += 1;
6471
6491
  return handle;
6472
6492
  }
6473
- function key(request, operation) {
6474
- return `${request.resource.uid}:${operation}:${request.idempotencyKey}`;
6475
- }
6476
- function stable6(value) {
6477
- if (value === void 0) return "undefined";
6478
- if (Array.isArray(value)) return `[${value.map(stable6).join(",")}]`;
6479
- if (value !== null && typeof value === "object") {
6480
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([name, item]) => `${JSON.stringify(name)}:${stable6(item)}`).join(",")}}`;
6481
- }
6482
- return JSON.stringify(value) ?? typeof value;
6483
- }
6484
6493
  function previous(request, operation) {
6485
- const idempotency = key(request, operation);
6486
- const handle = state.idempotency.get(idempotency);
6487
- if (!handle) return void 0;
6488
- if (state.idempotencyFingerprints.get(idempotency) !== stable6(request.payload)) {
6489
- throw new OrchestrationError({
6490
- code: "CONFLICT",
6491
- message: `identity ${operation} idempotency key was reused with different input`,
6492
- retryable: false
6493
- });
6494
- }
6495
- return handle;
6494
+ return findIdempotentDriverHandle(state, request, operation, "identity");
6496
6495
  }
6497
6496
  function remember(request, operation, handle) {
6498
- const idempotency = key(request, operation);
6499
- state.idempotency.set(idempotency, handle);
6500
- state.idempotencyFingerprints.set(idempotency, stable6(request.payload));
6497
+ rememberIdempotentDriverHandle(state, request, operation, handle);
6501
6498
  }
6502
6499
  function assertActiveIdentity(identity) {
6503
6500
  if (identity.revoked) {
@@ -6541,7 +6538,7 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6541
6538
  const ttlMs = ttl(request.payload, "ttlMs", maxSessionTtlMs);
6542
6539
  const existing = previous(request, "enroll");
6543
6540
  if (existing) {
6544
- return structuredClone(owned(
6541
+ return structuredClone(getOwnedDriverValue(
6545
6542
  state.enrollments,
6546
6543
  existing,
6547
6544
  request.resource.uid,
@@ -6565,7 +6562,7 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6565
6562
  },
6566
6563
  async challenge(request) {
6567
6564
  validate(request, "identity.challenge", ["controller", "admin"]);
6568
- const enrollment = owned(
6565
+ const enrollment = getOwnedDriverValue(
6569
6566
  state.enrollments,
6570
6567
  requiredString4(request.payload, "enrollmentHandle"),
6571
6568
  request.resource.uid,
@@ -6578,7 +6575,7 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6578
6575
  const ttlMs = ttl(request.payload, "ttlMs", maxChallengeTtlMs);
6579
6576
  const existing = previous(request, "challenge");
6580
6577
  if (existing) {
6581
- return structuredClone(owned(
6578
+ return structuredClone(getOwnedDriverValue(
6582
6579
  state.challenges,
6583
6580
  existing,
6584
6581
  request.resource.uid,
@@ -6608,13 +6605,13 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6608
6605
  },
6609
6606
  async attest(request) {
6610
6607
  validate(request, "identity.attest", ["controller", "verifier"]);
6611
- const challenge = owned(
6608
+ const challenge = getOwnedDriverValue(
6612
6609
  state.challenges,
6613
6610
  requiredString4(request.payload, "challengeHandle"),
6614
6611
  request.resource.uid,
6615
6612
  "challenge"
6616
6613
  );
6617
- const enrollment = owned(
6614
+ const enrollment = getOwnedDriverValue(
6618
6615
  state.enrollments,
6619
6616
  challenge.enrollmentHandle,
6620
6617
  request.resource.uid,
@@ -6650,7 +6647,7 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6650
6647
  }
6651
6648
  const existing = previous(request, "attest");
6652
6649
  if (existing) {
6653
- return structuredClone(owned(
6650
+ return structuredClone(getOwnedDriverValue(
6654
6651
  state.identities,
6655
6652
  existing,
6656
6653
  request.resource.uid,
@@ -6685,7 +6682,7 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6685
6682
  },
6686
6683
  async issueSession(request) {
6687
6684
  validate(request, "identity.issue-session", ["controller", "admin"]);
6688
- const identity = owned(
6685
+ const identity = getOwnedDriverValue(
6689
6686
  state.identities,
6690
6687
  requiredString4(request.payload, "identityHandle"),
6691
6688
  request.resource.uid,
@@ -6714,7 +6711,7 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6714
6711
  const ttlMs = ttl(request.payload, "ttlMs", maxSessionTtlMs);
6715
6712
  const existing = previous(request, "issue-session");
6716
6713
  if (existing) {
6717
- return structuredClone(owned(
6714
+ return structuredClone(getOwnedDriverValue(
6718
6715
  state.sessions,
6719
6716
  existing,
6720
6717
  request.resource.uid,
@@ -6738,7 +6735,7 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6738
6735
  },
6739
6736
  async rotate(request) {
6740
6737
  validate(request, "identity.rotate", ["controller", "admin"]);
6741
- const identity = owned(
6738
+ const identity = getOwnedDriverValue(
6742
6739
  state.identities,
6743
6740
  requiredString4(request.payload, "identityHandle"),
6744
6741
  request.resource.uid,
@@ -6755,7 +6752,7 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6755
6752
  );
6756
6753
  const existing = previous(request, "rotate");
6757
6754
  if (existing) {
6758
- return structuredClone(owned(
6755
+ return structuredClone(getOwnedDriverValue(
6759
6756
  state.identities,
6760
6757
  existing,
6761
6758
  request.resource.uid,
@@ -6783,7 +6780,7 @@ function createFakeIdentityAttestationManagementDriver(options = {}) {
6783
6780
  },
6784
6781
  async revoke(request) {
6785
6782
  validate(request, "identity.revoke", ["controller", "admin"]);
6786
- const identity = owned(
6783
+ const identity = getOwnedDriverValue(
6787
6784
  state.identities,
6788
6785
  requiredString4(request.payload, "identityHandle"),
6789
6786
  request.resource.uid,
@@ -7139,7 +7136,7 @@ var init_identityAttestationManagement = __esm({
7139
7136
  "src/orchestration/drivers/identityAttestationManagement.ts"() {
7140
7137
  "use strict";
7141
7138
  init_errors();
7142
- init_driverRequest();
7139
+ init_driverState();
7143
7140
  }
7144
7141
  });
7145
7142
 
@@ -8345,12 +8342,12 @@ function createManagedCredentialBrokerAdapter(broker, options) {
8345
8342
  retryable: false
8346
8343
  });
8347
8344
  }
8348
- const stable6 = options.stableHandleFor?.(request) ?? stableHandle();
8349
- if (!stable6 || stable6.length > 2048) {
8345
+ const stable = options.stableHandleFor?.(request) ?? stableHandle();
8346
+ if (!stable || stable.length > 2048) {
8350
8347
  invalid11("credential stable handle is empty or too long");
8351
8348
  }
8352
8349
  if (options.handleStore) {
8353
- const adopted = await options.handleStore.get(stable6);
8350
+ const adopted = await options.handleStore.get(stable);
8354
8351
  if (adopted) {
8355
8352
  const inspection = await broker.inspect(adopted.token);
8356
8353
  const exact = inspection.grantId === request.resource.uid && canonicalDriverValue(inspection.scope) === canonicalDriverValue({
@@ -8370,13 +8367,13 @@ function createManagedCredentialBrokerAdapter(broker, options) {
8370
8367
  });
8371
8368
  }
8372
8369
  const adoptedRecord = {
8373
- stableHandle: stable6,
8370
+ stableHandle: stable,
8374
8371
  token: adopted.token,
8375
8372
  resourceUid: request.resource.uid,
8376
8373
  targetDriver: request.payload.targetDriver
8377
8374
  };
8378
- records.set(stable6, adoptedRecord);
8379
- await rememberIdempotency(key, request, stable6);
8375
+ records.set(stable, adoptedRecord);
8376
+ await rememberIdempotency(key, request, stable);
8380
8377
  return managed(adoptedRecord, inspection);
8381
8378
  }
8382
8379
  }
@@ -8392,7 +8389,7 @@ function createManagedCredentialBrokerAdapter(broker, options) {
8392
8389
  grantId: request.resource.uid
8393
8390
  });
8394
8391
  const record2 = {
8395
- stableHandle: stable6,
8392
+ stableHandle: stable,
8396
8393
  token: issued.token,
8397
8394
  resourceUid: request.resource.uid,
8398
8395
  targetDriver: request.payload.targetDriver
@@ -9544,13 +9541,6 @@ function createFakeNetworkManagementState() {
9544
9541
  nextHandle: 1
9545
9542
  };
9546
9543
  }
9547
- function stable2(value) {
9548
- if (Array.isArray(value)) return `[${value.map(stable2).join(",")}]`;
9549
- if (value !== null && typeof value === "object") {
9550
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${stable2(item)}`).join(",")}}`;
9551
- }
9552
- return JSON.stringify(value) ?? typeof value;
9553
- }
9554
9544
  function invalid12(message) {
9555
9545
  throw new OrchestrationError({ code: "INVALID", message, retryable: false });
9556
9546
  }
@@ -9751,31 +9741,15 @@ function createFakeNetworkManagementDriver(options = {}) {
9751
9741
  ...options.capabilities
9752
9742
  };
9753
9743
  function validate(request, method) {
9754
- assertDriverRequestEnvelope(request, {
9744
+ return assertFencedDriverRequestEnvelope(request, {
9755
9745
  now,
9746
+ fences: state.fences,
9756
9747
  requireRun: true,
9757
- requireFencing: true,
9758
- requireCapability: true,
9759
- expectedMethod: method
9748
+ expectedMethod: method,
9749
+ fenceName: "network",
9750
+ actorKinds: ["controller", "admin"],
9751
+ forbiddenMessage: () => "network lifecycle requires a controller or admin actor"
9760
9752
  });
9761
- if (request.actor.kind !== "controller" && request.actor.kind !== "admin") {
9762
- throw new OrchestrationError({
9763
- code: "FORBIDDEN",
9764
- message: "network lifecycle requires a controller or admin actor",
9765
- retryable: false
9766
- });
9767
- }
9768
- const fence = request.fencingEpoch;
9769
- const current = state.fences.get(request.resource.uid) ?? 0;
9770
- if (fence < current) {
9771
- throw new OrchestrationError({
9772
- code: "STALE_EPOCH",
9773
- message: `stale network fencing epoch ${fence}; current epoch is ${current}`,
9774
- retryable: false
9775
- });
9776
- }
9777
- state.fences.set(request.resource.uid, fence);
9778
- return fence;
9779
9753
  }
9780
9754
  function nextHandle(prefix) {
9781
9755
  const handle = `${prefix}:${state.nextHandle}`;
@@ -9839,7 +9813,7 @@ function createFakeNetworkManagementDriver(options = {}) {
9839
9813
  }
9840
9814
  function idempotent(request, operation) {
9841
9815
  const key = `${request.resource.uid}:${operation}:${request.idempotencyKey}`;
9842
- const fingerprint = stable2(request.payload);
9816
+ const fingerprint = canonicalDriverValue(request.payload);
9843
9817
  const existing = state.idempotency.get(key);
9844
9818
  if (existing) {
9845
9819
  if (existing.fingerprint !== fingerprint) {
@@ -9856,7 +9830,7 @@ function createFakeNetworkManagementDriver(options = {}) {
9856
9830
  function remember(request, operation, resultHandle) {
9857
9831
  state.idempotency.set(
9858
9832
  `${request.resource.uid}:${operation}:${request.idempotencyKey}`,
9859
- { fingerprint: stable2(request.payload), resultHandle }
9833
+ { fingerprint: canonicalDriverValue(request.payload), resultHandle }
9860
9834
  );
9861
9835
  }
9862
9836
  return {
@@ -10151,6 +10125,7 @@ var init_networkManagement = __esm({
10151
10125
  "use strict";
10152
10126
  init_errors();
10153
10127
  init_driverRequest();
10128
+ init_driverState();
10154
10129
  ENFORCEMENT_RANK = {
10155
10130
  none: 0,
10156
10131
  process: 1,
@@ -10940,18 +10915,10 @@ function requiredString6(value, field, maximum = 256) {
10940
10915
  if (!result || result.length > maximum) invalid14(`tool payload '${field}' is invalid`);
10941
10916
  return result;
10942
10917
  }
10943
- function stable3(value) {
10944
- if (value === void 0) return "undefined";
10945
- if (Array.isArray(value)) return `[${value.map(stable3).join(",")}]`;
10946
- if (value !== null && typeof value === "object") {
10947
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${stable3(item)}`).join(",")}}`;
10948
- }
10949
- return JSON.stringify(value) ?? typeof value;
10950
- }
10951
10918
  async function digest3(value) {
10952
10919
  const result = await globalThis.crypto.subtle.digest(
10953
10920
  "SHA-256",
10954
- new TextEncoder().encode(stable3(value))
10921
+ new TextEncoder().encode(canonicalDriverValue(value))
10955
10922
  );
10956
10923
  return `sha256:${[...new Uint8Array(result)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
10957
10924
  }
@@ -11034,37 +11001,21 @@ function createFakeToolManagementDriver(options = {}) {
11034
11001
  if (!SHA2567.test(descriptor.schemaDigest) || descriptor.schemaDigest !== actualSchemaDigest || !descriptor.name || !descriptor.version || !descriptor.targets.length) invalid14(`tool catalog descriptor '${descriptor.name}' is invalid`);
11035
11002
  }
11036
11003
  return digest3(
11037
- tools.map(descriptorInput).sort((left, right) => stable3(left).localeCompare(stable3(right)))
11004
+ tools.map(descriptorInput).sort((left, right) => canonicalDriverValue(left).localeCompare(canonicalDriverValue(right)))
11038
11005
  );
11039
11006
  })();
11040
11007
  return catalogDigestPromise;
11041
11008
  }
11042
11009
  function validate(request, expectedMethod, actorKinds = ["controller"]) {
11043
- assertDriverRequestEnvelope(request, {
11010
+ assertFencedDriverRequestEnvelope(request, {
11044
11011
  now,
11045
- requireFencing: true,
11046
- requireCapability: true,
11047
- expectedMethod
11012
+ fences: state.fences,
11013
+ expectedMethod,
11014
+ fenceName: "tool",
11015
+ actorKinds
11048
11016
  });
11049
- if (!actorKinds.includes(request.actor.kind)) {
11050
- throw new OrchestrationError({
11051
- code: "FORBIDDEN",
11052
- message: `actor kind '${request.actor.kind}' cannot call ${expectedMethod}`,
11053
- retryable: false
11054
- });
11055
- }
11056
- const epoch = request.fencingEpoch;
11057
- const current = state.fences.get(request.resource.uid) ?? 0;
11058
- if (epoch < current) {
11059
- throw new OrchestrationError({
11060
- code: "STALE_EPOCH",
11061
- message: `stale tool fencing epoch ${epoch}; current epoch is ${current}`,
11062
- retryable: false
11063
- });
11064
- }
11065
- state.fences.set(request.resource.uid, epoch);
11066
11017
  }
11067
- function owned2(collection, handle, resourceUid, kind) {
11018
+ function owned(collection, handle, resourceUid, kind) {
11068
11019
  const value = collection.get(handle);
11069
11020
  if (!value) {
11070
11021
  throw new OrchestrationError({
@@ -11089,21 +11040,10 @@ function createFakeToolManagementDriver(options = {}) {
11089
11040
  return `${prefix}:${state.nextHandle++}`;
11090
11041
  }
11091
11042
  function idempotency(request, operation) {
11092
- const key = `${request.resource.uid}:${operation}:${request.idempotencyKey}`;
11093
- const previous = state.idempotency.get(key);
11094
- if (previous && state.idempotencyFingerprints.get(key) !== stable3(request.payload)) {
11095
- throw new OrchestrationError({
11096
- code: "CONFLICT",
11097
- message: `tool ${operation} idempotency key was reused with different input`,
11098
- retryable: false
11099
- });
11100
- }
11101
- return previous;
11043
+ return findIdempotentDriverHandle(state, request, operation, "tool");
11102
11044
  }
11103
11045
  function remember(request, operation, handle) {
11104
- const key = `${request.resource.uid}:${operation}:${request.idempotencyKey}`;
11105
- state.idempotency.set(key, handle);
11106
- state.idempotencyFingerprints.set(key, stable3(request.payload));
11046
+ rememberIdempotentDriverHandle(state, request, operation, handle);
11107
11047
  }
11108
11048
  async function* defaultExecutor(descriptor, target, arguments_) {
11109
11049
  yield JSON.stringify({ tool: descriptor.name, target, arguments: arguments_ });
@@ -11186,7 +11126,7 @@ function createFakeToolManagementDriver(options = {}) {
11186
11126
  if (request.payload.operationIdempotencyKey && !descriptor.supportsIdempotency) invalid14("tool does not support operation idempotency");
11187
11127
  const previous = idempotency(request, "prepare");
11188
11128
  if (previous) {
11189
- return structuredClone(owned2(
11129
+ return structuredClone(owned(
11190
11130
  state.preparations,
11191
11131
  previous,
11192
11132
  request.resource.uid,
@@ -11211,7 +11151,7 @@ function createFakeToolManagementDriver(options = {}) {
11211
11151
  },
11212
11152
  async authorize(request) {
11213
11153
  validate(request, "tool.authorize", ["controller", "admin"]);
11214
- const preparation = owned2(
11154
+ const preparation = owned(
11215
11155
  state.preparations,
11216
11156
  requiredString6(request.payload, "preparationHandle"),
11217
11157
  request.resource.uid,
@@ -11242,7 +11182,7 @@ function createFakeToolManagementDriver(options = {}) {
11242
11182
  }
11243
11183
  const previous = idempotency(request, "authorize");
11244
11184
  if (previous) {
11245
- return structuredClone(owned2(
11185
+ return structuredClone(owned(
11246
11186
  state.authorizations,
11247
11187
  previous,
11248
11188
  request.resource.uid,
@@ -11264,13 +11204,13 @@ function createFakeToolManagementDriver(options = {}) {
11264
11204
  },
11265
11205
  async *invoke(request, invokeOptions = {}) {
11266
11206
  validate(request, "tool.invoke");
11267
- const preparation = owned2(
11207
+ const preparation = owned(
11268
11208
  state.preparations,
11269
11209
  requiredString6(request.payload, "preparationHandle"),
11270
11210
  request.resource.uid,
11271
11211
  "tool preparation"
11272
11212
  );
11273
- const authorization = owned2(
11213
+ const authorization = owned(
11274
11214
  state.authorizations,
11275
11215
  requiredString6(request.payload, "authorizationHandle"),
11276
11216
  request.resource.uid,
@@ -11290,7 +11230,7 @@ function createFakeToolManagementDriver(options = {}) {
11290
11230
  }
11291
11231
  const previous = idempotency(request, "invoke");
11292
11232
  if (previous) {
11293
- const execution2 = owned2(
11233
+ const execution2 = owned(
11294
11234
  state.executions,
11295
11235
  previous,
11296
11236
  request.resource.uid,
@@ -11395,14 +11335,14 @@ function createFakeToolManagementDriver(options = {}) {
11395
11335
  },
11396
11336
  async reconcileUnknownEffect(request) {
11397
11337
  validate(request, "tool.reconcile-unknown", ["controller", "verifier", "admin"]);
11398
- const execution = owned2(
11338
+ const execution = owned(
11399
11339
  state.executions,
11400
11340
  requiredString6(request.payload, "executionHandle"),
11401
11341
  request.resource.uid,
11402
11342
  "tool execution"
11403
11343
  );
11404
11344
  if (execution.phase !== "Unknown") return structuredClone(execution);
11405
- const preparation = owned2(
11345
+ const preparation = owned(
11406
11346
  state.preparations,
11407
11347
  execution.preparationHandle,
11408
11348
  request.resource.uid,
@@ -11428,14 +11368,14 @@ function createFakeToolManagementDriver(options = {}) {
11428
11368
  },
11429
11369
  async collectEvidence(request) {
11430
11370
  validate(request, "tool.collect-evidence", ["controller", "verifier", "admin"]);
11431
- const execution = owned2(
11371
+ const execution = owned(
11432
11372
  state.executions,
11433
11373
  requiredString6(request.payload, "executionHandle"),
11434
11374
  request.resource.uid,
11435
11375
  "tool execution"
11436
11376
  );
11437
11377
  const descriptor = tool(
11438
- owned2(
11378
+ owned(
11439
11379
  state.preparations,
11440
11380
  execution.preparationHandle,
11441
11381
  request.resource.uid,
@@ -11445,7 +11385,7 @@ function createFakeToolManagementDriver(options = {}) {
11445
11385
  if (!descriptor?.supportsEvidence) invalid14("tool does not support evidence");
11446
11386
  const previous = idempotency(request, "evidence");
11447
11387
  if (previous) {
11448
- return structuredClone(owned2(
11388
+ return structuredClone(owned(
11449
11389
  state.evidence,
11450
11390
  previous,
11451
11391
  request.resource.uid,
@@ -11466,14 +11406,14 @@ function createFakeToolManagementDriver(options = {}) {
11466
11406
  },
11467
11407
  async cleanup(request) {
11468
11408
  validate(request, "tool.cleanup");
11469
- const preparation = owned2(
11409
+ const preparation = owned(
11470
11410
  state.preparations,
11471
11411
  requiredString6(request.payload, "preparationHandle"),
11472
11412
  request.resource.uid,
11473
11413
  "tool preparation"
11474
11414
  );
11475
11415
  if (request.payload.executionHandle) {
11476
- const execution = owned2(
11416
+ const execution = owned(
11477
11417
  state.executions,
11478
11418
  request.payload.executionHandle,
11479
11419
  request.resource.uid,
@@ -11632,7 +11572,7 @@ function createToolManagementConformanceSuite(options) {
11632
11572
  { executionHandle: first[0].executionHandle },
11633
11573
  "inspect-invoke"
11634
11574
  ));
11635
- if (!first.at(-1)?.final || stable3(first) !== stable3(replay) || execution?.phase !== "Completed") throw new Error("tool streaming or retry did not converge");
11575
+ if (!first.at(-1)?.final || canonicalDriverValue(first) !== canonicalDriverValue(replay) || execution?.phase !== "Completed") throw new Error("tool streaming or retry did not converge");
11636
11576
  }
11637
11577
  },
11638
11578
  {
@@ -11804,6 +11744,7 @@ var init_toolManagement = __esm({
11804
11744
  import__4 = require("ajv/dist/2020.js");
11805
11745
  init_errors();
11806
11746
  init_driverRequest();
11747
+ init_driverState();
11807
11748
  SHA2567 = /^sha256:[a-f0-9]{64}$/;
11808
11749
  }
11809
11750
  });
@@ -12470,7 +12411,7 @@ function createManagedWorkerIdentityAdapter(options) {
12470
12411
  fences.set(request.resource.uid, fence);
12471
12412
  return resource;
12472
12413
  }
12473
- function owned2(values, handle, resourceUid, kind) {
12414
+ function owned(values, handle, resourceUid, kind) {
12474
12415
  const value = values.get(handle);
12475
12416
  if (!value) {
12476
12417
  throw new OrchestrationError({
@@ -12540,7 +12481,7 @@ function createManagedWorkerIdentityAdapter(options) {
12540
12481
  "channelBinding",
12541
12482
  "ttlMs"
12542
12483
  ]);
12543
- const enrollment = owned2(
12484
+ const enrollment = owned(
12544
12485
  enrollments,
12545
12486
  requireBoundedString2(
12546
12487
  request.payload.enrollmentHandle,
@@ -12589,7 +12530,7 @@ function createManagedWorkerIdentityAdapter(options) {
12589
12530
  ["format", "evidenceDigest"],
12590
12531
  "attestation"
12591
12532
  );
12592
- const challenge = owned2(
12533
+ const challenge = owned(
12593
12534
  challenges,
12594
12535
  requireBoundedString2(
12595
12536
  request.payload.challengeHandle,
@@ -12647,7 +12588,7 @@ function createManagedWorkerIdentityAdapter(options) {
12647
12588
  "channelBinding",
12648
12589
  "ttlMs"
12649
12590
  ]);
12650
- const identity = owned2(
12591
+ const identity = owned(
12651
12592
  identities,
12652
12593
  requireBoundedString2(request.payload.identityHandle, "identityHandle"),
12653
12594
  resource.metadata.uid,
@@ -12712,7 +12653,7 @@ function createManagedWorkerIdentityAdapter(options) {
12712
12653
  "identityHandle",
12713
12654
  "reason"
12714
12655
  ]);
12715
- const identity = owned2(
12656
+ const identity = owned(
12716
12657
  identities,
12717
12658
  requireBoundedString2(request.payload.identityHandle, "identityHandle"),
12718
12659
  resource.metadata.uid,
@@ -13327,14 +13268,6 @@ function createFakeModelManagementState() {
13327
13268
  nextHandle: 1
13328
13269
  };
13329
13270
  }
13330
- function stable4(value) {
13331
- if (value === void 0) return "undefined";
13332
- if (Array.isArray(value)) return `[${value.map(stable4).join(",")}]`;
13333
- if (value !== null && typeof value === "object") {
13334
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${stable4(item)}`).join(",")}}`;
13335
- }
13336
- return JSON.stringify(value) ?? typeof value;
13337
- }
13338
13271
  function invalid17(message) {
13339
13272
  throw new OrchestrationError({ code: "INVALID", message, retryable: false });
13340
13273
  }
@@ -13393,31 +13326,15 @@ function createFakeModelManagementDriver(options = {}) {
13393
13326
  };
13394
13327
  const active = /* @__PURE__ */ new Map();
13395
13328
  function validate(request, method) {
13396
- assertDriverRequestEnvelope(request, {
13329
+ return assertFencedDriverRequestEnvelope(request, {
13397
13330
  now,
13331
+ fences: state.fences,
13398
13332
  requireRun: true,
13399
- requireFencing: true,
13400
- requireCapability: true,
13401
- expectedMethod: method
13333
+ expectedMethod: method,
13334
+ fenceName: "model",
13335
+ actorKinds: ["controller", "admin"],
13336
+ forbiddenMessage: () => "model provider access requires a controller or admin actor"
13402
13337
  });
13403
- if (request.actor.kind !== "controller" && request.actor.kind !== "admin") {
13404
- throw new OrchestrationError({
13405
- code: "FORBIDDEN",
13406
- message: "model provider access requires a controller or admin actor",
13407
- retryable: false
13408
- });
13409
- }
13410
- const fence = request.fencingEpoch;
13411
- const current = state.fences.get(request.resource.uid) ?? 0;
13412
- if (fence < current) {
13413
- throw new OrchestrationError({
13414
- code: "STALE_EPOCH",
13415
- message: `stale model fencing epoch ${fence}; current epoch is ${current}`,
13416
- retryable: false
13417
- });
13418
- }
13419
- state.fences.set(request.resource.uid, fence);
13420
- return fence;
13421
13338
  }
13422
13339
  function modelFor(payload) {
13423
13340
  assertOnlyFields2(
@@ -13544,7 +13461,7 @@ function createFakeModelManagementDriver(options = {}) {
13544
13461
  const fence = validate(request, "model.generate");
13545
13462
  const model = modelFor(request.payload);
13546
13463
  await authorize(request, model);
13547
- const inputFingerprint = stable4({
13464
+ const inputFingerprint = canonicalDriverValue({
13548
13465
  payload: request.payload,
13549
13466
  run: request.run,
13550
13467
  session: request.session,
@@ -13783,7 +13700,9 @@ function createModelManagementConformanceSuite(options) {
13783
13700
  );
13784
13701
  const first = await collect(driver, request);
13785
13702
  const second = await collect(driver, request);
13786
- if (stable4(first) !== stable4(second)) throw new Error("model generation did not replay");
13703
+ if (canonicalDriverValue(first) !== canonicalDriverValue(second)) {
13704
+ throw new Error("model generation did not replay");
13705
+ }
13787
13706
  if (first.at(-1)?.type !== "done") throw new Error("model stream did not complete");
13788
13707
  let driftRejected = false;
13789
13708
  try {
@@ -13899,6 +13818,7 @@ var init_modelManagement = __esm({
13899
13818
  "use strict";
13900
13819
  init_errors();
13901
13820
  init_driverRequest();
13821
+ init_driverState();
13902
13822
  init_modelProviderDriver();
13903
13823
  SHA2568 = /^sha256:[a-f0-9]{64}$/;
13904
13824
  }
@@ -13921,16 +13841,8 @@ function requiredString7(value, field) {
13921
13841
  if (value === null || typeof value !== "object" || typeof value[field] !== "string" || !value[field]) invalid18(`policy payload '${field}' is required`);
13922
13842
  return value[field];
13923
13843
  }
13924
- function stable5(value) {
13925
- if (value === void 0) return "undefined";
13926
- if (Array.isArray(value)) return `[${value.map(stable5).join(",")}]`;
13927
- if (value !== null && typeof value === "object") {
13928
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${stable5(item)}`).join(",")}}`;
13929
- }
13930
- return JSON.stringify(value) ?? typeof value;
13931
- }
13932
13844
  async function digest6(value) {
13933
- const bytes = new TextEncoder().encode(stable5(value));
13845
+ const bytes = new TextEncoder().encode(canonicalDriverValue(value));
13934
13846
  const result = await globalThis.crypto.subtle.digest("SHA-256", bytes);
13935
13847
  return `sha256:${[...new Uint8Array(result)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
13936
13848
  }
@@ -13951,34 +13863,18 @@ function createFakePolicyApprovalManagementDriver(options = {}) {
13951
13863
  ]
13952
13864
  );
13953
13865
  function validate(request, expectedMethod, actorKinds) {
13954
- assertDriverRequestEnvelope(request, {
13866
+ assertFencedDriverRequestEnvelope(request, {
13955
13867
  now,
13956
- requireFencing: true,
13957
- requireCapability: true,
13958
- expectedMethod
13868
+ fences: state.fences,
13869
+ expectedMethod,
13870
+ fenceName: "policy",
13871
+ actorKinds
13959
13872
  });
13960
- if (!actorKinds.includes(request.actor.kind)) {
13961
- throw new OrchestrationError({
13962
- code: "FORBIDDEN",
13963
- message: `actor kind '${request.actor.kind}' cannot call ${expectedMethod}`,
13964
- retryable: false
13965
- });
13966
- }
13967
- const epoch = request.fencingEpoch;
13968
- const current = state.fences.get(request.resource.uid) ?? 0;
13969
- if (epoch < current) {
13970
- throw new OrchestrationError({
13971
- code: "STALE_EPOCH",
13972
- message: `stale policy fencing epoch ${epoch}; current epoch is ${current}`,
13973
- retryable: false
13974
- });
13975
- }
13976
- state.fences.set(request.resource.uid, epoch);
13977
13873
  }
13978
13874
  function assertPolicyDigest(value) {
13979
13875
  if (!SHA2569.test(value)) invalid18("policyDigest must be a canonical sha256 digest");
13980
13876
  }
13981
- function owned2(handle, resourceUid) {
13877
+ function owned(handle, resourceUid) {
13982
13878
  const decision = state.decisions.get(handle);
13983
13879
  if (!decision) {
13984
13880
  throw new OrchestrationError({
@@ -13998,18 +13894,14 @@ function createFakePolicyApprovalManagementDriver(options = {}) {
13998
13894
  }
13999
13895
  async function decide(request, operation, kind, outcome, policyDigest, reasons, obligations = [], approval) {
14000
13896
  assertPolicyDigest(policyDigest);
14001
- const key = `${request.resource.uid}:${operation}:${request.idempotencyKey}`;
14002
- const fingerprint = stable5(request.payload);
14003
- const previousHandle = state.idempotency.get(key);
13897
+ const previousHandle = findIdempotentDriverHandle(
13898
+ state,
13899
+ request,
13900
+ operation,
13901
+ "policy"
13902
+ );
14004
13903
  if (previousHandle) {
14005
- if (state.idempotencyFingerprints.get(key) !== fingerprint) {
14006
- throw new OrchestrationError({
14007
- code: "CONFLICT",
14008
- message: `policy ${operation} idempotency key was reused with different input`,
14009
- retryable: false
14010
- });
14011
- }
14012
- return structuredClone(owned2(previousHandle, request.resource.uid));
13904
+ return structuredClone(owned(previousHandle, request.resource.uid));
14013
13905
  }
14014
13906
  const decision = {
14015
13907
  decisionHandle: `policy-decision:${state.nextHandle++}`,
@@ -14025,8 +13917,12 @@ function createFakePolicyApprovalManagementDriver(options = {}) {
14025
13917
  approval
14026
13918
  };
14027
13919
  state.decisions.set(decision.decisionHandle, decision);
14028
- state.idempotency.set(key, decision.decisionHandle);
14029
- state.idempotencyFingerprints.set(key, fingerprint);
13920
+ rememberIdempotentDriverHandle(
13921
+ state,
13922
+ request,
13923
+ operation,
13924
+ decision.decisionHandle
13925
+ );
14030
13926
  return structuredClone(decision);
14031
13927
  }
14032
13928
  return {
@@ -14099,7 +13995,7 @@ function createFakePolicyApprovalManagementDriver(options = {}) {
14099
13995
  }
14100
13996
  let approval;
14101
13997
  if (request.payload.approvalDecisionHandle) {
14102
- approval = owned2(request.payload.approvalDecisionHandle, request.resource.uid);
13998
+ approval = owned(request.payload.approvalDecisionHandle, request.resource.uid);
14103
13999
  }
14104
14000
  const needsApproval = effect !== "read";
14105
14001
  const approvalValid = !needsApproval || approval?.kind === "approval" && approval.outcome === "allow" && approval.policyDigest === policyDigest && approval.approval?.subjectDigest === operationDigest && Date.parse(approval.approval.expiresAt) > now().getTime();
@@ -14147,7 +14043,7 @@ function createFakePolicyApprovalManagementDriver(options = {}) {
14147
14043
  if (!["allow", "deny"].includes(request.payload.outcome)) {
14148
14044
  invalid18("approval outcome must be allow or deny");
14149
14045
  }
14150
- const decision = owned2(handle, request.resource.uid);
14046
+ const decision = owned(handle, request.resource.uid);
14151
14047
  if (decision.kind !== "approval") invalid18("decision is not an approval");
14152
14048
  if (decision.approval && Date.parse(decision.approval.expiresAt) <= now().getTime()) {
14153
14049
  decision.outcome = "deny";
@@ -14210,7 +14106,7 @@ function createFakePolicyApprovalManagementDriver(options = {}) {
14210
14106
  "verifier",
14211
14107
  "admin"
14212
14108
  ]);
14213
- const decision = owned2(
14109
+ const decision = owned(
14214
14110
  requiredString7(request.payload, "decisionHandle"),
14215
14111
  request.resource.uid
14216
14112
  );
@@ -14443,6 +14339,7 @@ var init_policyApprovalManagement = __esm({
14443
14339
  "use strict";
14444
14340
  init_errors();
14445
14341
  init_driverRequest();
14342
+ init_driverState();
14446
14343
  SHA2569 = /^sha256:[a-f0-9]{64}$/;
14447
14344
  TRUST_RANK3 = {
14448
14345
  quarantine: 0,
@@ -14461,6 +14358,7 @@ function createFakeStorageManagementState() {
14461
14358
  stages: /* @__PURE__ */ new Map(),
14462
14359
  publications: /* @__PURE__ */ new Map(),
14463
14360
  idempotency: /* @__PURE__ */ new Map(),
14361
+ idempotencyFingerprints: /* @__PURE__ */ new Map(),
14464
14362
  fences: /* @__PURE__ */ new Map(),
14465
14363
  nextHandle: 1
14466
14364
  };
@@ -14488,32 +14386,18 @@ function createFakeStorageManagementDriver(options = {}) {
14488
14386
  const state = options.state ?? createFakeStorageManagementState();
14489
14387
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
14490
14388
  function validate(request, expectedMethod) {
14491
- assertDriverRequestEnvelope(request, {
14389
+ return assertFencedDriverRequestEnvelope(request, {
14492
14390
  now,
14493
- requireFencing: true,
14494
- requireCapability: true,
14495
- expectedMethod
14391
+ fences: state.fences,
14392
+ expectedMethod,
14393
+ fenceName: "storage"
14496
14394
  });
14497
- const fence = request.fencingEpoch;
14498
- const current = state.fences.get(request.resource.uid) ?? 0;
14499
- if (fence < current) {
14500
- throw new OrchestrationError({
14501
- code: "STALE_EPOCH",
14502
- message: `stale storage fencing epoch ${fence}; current epoch is ${current}`,
14503
- retryable: false
14504
- });
14505
- }
14506
- state.fences.set(request.resource.uid, fence);
14507
- return fence;
14508
14395
  }
14509
14396
  function nextHandle(prefix) {
14510
14397
  const handle = `${prefix}:${state.nextHandle}`;
14511
14398
  state.nextHandle += 1;
14512
14399
  return handle;
14513
14400
  }
14514
- function operationKey2(request, operation) {
14515
- return `${request.resource.uid}:${operation}:${request.idempotencyKey}`;
14516
- }
14517
14401
  function getVolume(handle, resourceUid) {
14518
14402
  const record2 = state.volumes.get(handle);
14519
14403
  if (!record2 || record2.volume.phase === "Deleted") {
@@ -14532,27 +14416,8 @@ function createFakeStorageManagementDriver(options = {}) {
14532
14416
  }
14533
14417
  return record2;
14534
14418
  }
14535
- function owned2(collection, handle, resourceUid, kind) {
14536
- const value = collection.get(handle);
14537
- if (!value) {
14538
- throw new OrchestrationError({
14539
- code: "NOT_FOUND",
14540
- message: `${kind} handle '${handle}' was not found`,
14541
- retryable: false
14542
- });
14543
- }
14544
- if (value.resourceUid !== resourceUid) {
14545
- throw new OrchestrationError({
14546
- code: "FORBIDDEN",
14547
- message: `${kind} handle '${handle}' belongs to another resource`,
14548
- retryable: false
14549
- });
14550
- }
14551
- return value;
14552
- }
14553
14419
  function createVolume(request, capacityBytes, accessMode, replicaCount, operation) {
14554
- const key = operationKey2(request, operation);
14555
- const existing = state.idempotency.get(key);
14420
+ const existing = findIdempotentDriverHandle(state, request, operation, "storage");
14556
14421
  if (existing) return getVolume(existing, request.resource.uid).volume;
14557
14422
  const volume = {
14558
14423
  volumeHandle: nextHandle("volume"),
@@ -14563,7 +14428,7 @@ function createFakeStorageManagementDriver(options = {}) {
14563
14428
  phase: "Available"
14564
14429
  };
14565
14430
  state.volumes.set(volume.volumeHandle, { volume, desiredReplicas: replicaCount });
14566
- state.idempotency.set(key, volume.volumeHandle);
14431
+ rememberIdempotentDriverHandle(state, request, operation, volume.volumeHandle);
14567
14432
  return volume;
14568
14433
  }
14569
14434
  return {
@@ -14619,9 +14484,10 @@ function createFakeStorageManagementDriver(options = {}) {
14619
14484
  validate(request, "storage.snapshot");
14620
14485
  const volumeHandle = requiredString8(request.payload, "volumeHandle");
14621
14486
  getVolume(volumeHandle, request.resource.uid);
14622
- const key = operationKey2(request, "snapshot");
14623
- const existing = state.idempotency.get(key);
14624
- if (existing) return owned2(state.snapshots, existing, request.resource.uid, "snapshot");
14487
+ const existing = findIdempotentDriverHandle(state, request, "snapshot", "storage");
14488
+ if (existing) {
14489
+ return getOwnedDriverValue(state.snapshots, existing, request.resource.uid, "snapshot");
14490
+ }
14625
14491
  const snapshot = {
14626
14492
  snapshotHandle: nextHandle("snapshot"),
14627
14493
  volumeHandle,
@@ -14629,12 +14495,12 @@ function createFakeStorageManagementDriver(options = {}) {
14629
14495
  createdAt: now().toISOString()
14630
14496
  };
14631
14497
  state.snapshots.set(snapshot.snapshotHandle, snapshot);
14632
- state.idempotency.set(key, snapshot.snapshotHandle);
14498
+ rememberIdempotentDriverHandle(state, request, "snapshot", snapshot.snapshotHandle);
14633
14499
  return snapshot;
14634
14500
  },
14635
14501
  async restoreSnapshot(request) {
14636
14502
  validate(request, "storage.restore");
14637
- const snapshot = owned2(
14503
+ const snapshot = getOwnedDriverValue(
14638
14504
  state.snapshots,
14639
14505
  requiredString8(request.payload, "snapshotHandle"),
14640
14506
  request.resource.uid,
@@ -14697,9 +14563,10 @@ function createFakeStorageManagementDriver(options = {}) {
14697
14563
  validate(request, "storage.backup");
14698
14564
  const volumeHandle = requiredString8(request.payload, "volumeHandle");
14699
14565
  getVolume(volumeHandle, request.resource.uid);
14700
- const key = operationKey2(request, "backup");
14701
- const existing = state.idempotency.get(key);
14702
- if (existing) return owned2(state.backups, existing, request.resource.uid, "backup");
14566
+ const existing = findIdempotentDriverHandle(state, request, "backup", "storage");
14567
+ if (existing) {
14568
+ return getOwnedDriverValue(state.backups, existing, request.resource.uid, "backup");
14569
+ }
14703
14570
  const backup = {
14704
14571
  backupHandle: nextHandle("backup"),
14705
14572
  volumeHandle,
@@ -14707,7 +14574,7 @@ function createFakeStorageManagementDriver(options = {}) {
14707
14574
  createdAt: now().toISOString()
14708
14575
  };
14709
14576
  state.backups.set(backup.backupHandle, backup);
14710
- state.idempotency.set(key, backup.backupHandle);
14577
+ rememberIdempotentDriverHandle(state, request, "backup", backup.backupHandle);
14711
14578
  return backup;
14712
14579
  },
14713
14580
  async stage(request) {
@@ -14715,9 +14582,10 @@ function createFakeStorageManagementDriver(options = {}) {
14715
14582
  const volumeHandle = requiredString8(request.payload, "volumeHandle");
14716
14583
  getVolume(volumeHandle, request.resource.uid);
14717
14584
  const nodeId = requiredString8(request.payload, "nodeId");
14718
- const key = operationKey2(request, "stage");
14719
- const existing = state.idempotency.get(key);
14720
- if (existing) return owned2(state.stages, existing, request.resource.uid, "stage");
14585
+ const existing = findIdempotentDriverHandle(state, request, "stage", "storage");
14586
+ if (existing) {
14587
+ return getOwnedDriverValue(state.stages, existing, request.resource.uid, "stage");
14588
+ }
14721
14589
  const stage = {
14722
14590
  stageHandle: nextHandle("stage"),
14723
14591
  volumeHandle,
@@ -14725,12 +14593,12 @@ function createFakeStorageManagementDriver(options = {}) {
14725
14593
  nodeId
14726
14594
  };
14727
14595
  state.stages.set(stage.stageHandle, stage);
14728
- state.idempotency.set(key, stage.stageHandle);
14596
+ rememberIdempotentDriverHandle(state, request, "stage", stage.stageHandle);
14729
14597
  return stage;
14730
14598
  },
14731
14599
  async publish(request) {
14732
14600
  validate(request, "storage.publish");
14733
- const stage = owned2(
14601
+ const stage = getOwnedDriverValue(
14734
14602
  state.stages,
14735
14603
  requiredString8(request.payload, "stageHandle"),
14736
14604
  request.resource.uid,
@@ -14739,10 +14607,14 @@ function createFakeStorageManagementDriver(options = {}) {
14739
14607
  getVolume(stage.volumeHandle, request.resource.uid);
14740
14608
  const workloadUid = requiredString8(request.payload, "workloadUid");
14741
14609
  if (typeof request.payload.readOnly !== "boolean") invalid19("publish readOnly is required");
14742
- const key = operationKey2(request, "publish");
14743
- const existing = state.idempotency.get(key);
14610
+ const existing = findIdempotentDriverHandle(state, request, "publish", "storage");
14744
14611
  if (existing) {
14745
- return owned2(state.publications, existing, request.resource.uid, "publication");
14612
+ return getOwnedDriverValue(
14613
+ state.publications,
14614
+ existing,
14615
+ request.resource.uid,
14616
+ "publication"
14617
+ );
14746
14618
  }
14747
14619
  const publication = {
14748
14620
  publishHandle: nextHandle("publication"),
@@ -14752,7 +14624,7 @@ function createFakeStorageManagementDriver(options = {}) {
14752
14624
  readOnly: request.payload.readOnly
14753
14625
  };
14754
14626
  state.publications.set(publication.publishHandle, publication);
14755
- state.idempotency.set(key, publication.publishHandle);
14627
+ rememberIdempotentDriverHandle(state, request, "publish", publication.publishHandle);
14756
14628
  return publication;
14757
14629
  },
14758
14630
  async unpublish(request) {
@@ -14760,7 +14632,7 @@ function createFakeStorageManagementDriver(options = {}) {
14760
14632
  const handle = requiredString8(request.payload, "publishHandle");
14761
14633
  const publication = state.publications.get(handle);
14762
14634
  if (!publication) return;
14763
- owned2(state.publications, handle, request.resource.uid, "publication");
14635
+ getOwnedDriverValue(state.publications, handle, request.resource.uid, "publication");
14764
14636
  state.publications.delete(handle);
14765
14637
  },
14766
14638
  async unstage(request) {
@@ -14768,7 +14640,7 @@ function createFakeStorageManagementDriver(options = {}) {
14768
14640
  const handle = requiredString8(request.payload, "stageHandle");
14769
14641
  const stage = state.stages.get(handle);
14770
14642
  if (!stage) return;
14771
- owned2(state.stages, handle, request.resource.uid, "stage");
14643
+ getOwnedDriverValue(state.stages, handle, request.resource.uid, "stage");
14772
14644
  if ([...state.publications.values()].some(
14773
14645
  (publication) => publication.stageHandle === handle
14774
14646
  )) {
@@ -14782,13 +14654,13 @@ function createFakeStorageManagementDriver(options = {}) {
14782
14654
  },
14783
14655
  async getStats(request) {
14784
14656
  validate(request, "storage.stats");
14785
- const publication = owned2(
14657
+ const publication = getOwnedDriverValue(
14786
14658
  state.publications,
14787
14659
  requiredString8(request.payload, "publishHandle"),
14788
14660
  request.resource.uid,
14789
14661
  "publication"
14790
14662
  );
14791
- const stage = owned2(
14663
+ const stage = getOwnedDriverValue(
14792
14664
  state.stages,
14793
14665
  publication.stageHandle,
14794
14666
  request.resource.uid,
@@ -14990,7 +14862,7 @@ var init_storageManagement = __esm({
14990
14862
  "src/orchestration/drivers/storageManagement.ts"() {
14991
14863
  "use strict";
14992
14864
  init_errors();
14993
- init_driverRequest();
14865
+ init_driverState();
14994
14866
  }
14995
14867
  });
14996
14868
 
@@ -17773,6 +17645,9 @@ function resolveMaxIterations(context) {
17773
17645
  const configured = context.agentToolLoop?.maxIterations;
17774
17646
  return configured != null && configured > 0 ? configured : DEFAULT_MAX_ITERATIONS;
17775
17647
  }
17648
+ function resolveLocalNodeId(context, input) {
17649
+ return context.localNodeId?.trim() || input?.userMessage?.originNodeId?.trim() || "local";
17650
+ }
17776
17651
  function pluginToolCallSignature(calls) {
17777
17652
  return calls.map((call) => `${call.toolId}:${JSON.stringify(call.parameters)}`).join("|");
17778
17653
  }
@@ -17794,7 +17669,7 @@ async function blockRepeatedPluginToolCalls(context, input, state, calls, hookCo
17794
17669
  const toolMessage = createChatMessage({
17795
17670
  messageId: `${input.conversationId}:t:doom-loop:${state.iteration}:${Date.now().toString(36)}`,
17796
17671
  conversationId: input.conversationId,
17797
- originNodeId: "local",
17672
+ originNodeId: resolveLocalNodeId(context, input),
17798
17673
  lamportClock,
17799
17674
  role: "tool",
17800
17675
  parts: [{
@@ -17839,11 +17714,12 @@ async function startAgentToolLoopTurn(context, input, state) {
17839
17714
  input.conversationId
17840
17715
  );
17841
17716
  const hostUserMessage = input.userMessage;
17717
+ const localNodeId = resolveLocalNodeId(context, input);
17842
17718
  const userMessage = context.normalizeMessage?.({
17843
17719
  ...hostUserMessage,
17844
17720
  messageId: hostUserMessage?.messageId ?? `${input.conversationId}:${now.toString(36)}`,
17845
17721
  conversationId: input.conversationId,
17846
- originNodeId: hostUserMessage?.originNodeId ?? "local",
17722
+ originNodeId: hostUserMessage?.originNodeId ?? localNodeId,
17847
17723
  timestamp: hostUserMessage?.timestamp ?? now,
17848
17724
  lamportClock: hostUserMessage?.lamportClock ?? lamportClock,
17849
17725
  role: "user",
@@ -17852,7 +17728,7 @@ async function startAgentToolLoopTurn(context, input, state) {
17852
17728
  ...hostUserMessage,
17853
17729
  messageId: hostUserMessage?.messageId ?? `${input.conversationId}:${now.toString(36)}`,
17854
17730
  conversationId: input.conversationId,
17855
- originNodeId: hostUserMessage?.originNodeId ?? "local",
17731
+ originNodeId: hostUserMessage?.originNodeId ?? localNodeId,
17856
17732
  timestamp: hostUserMessage?.timestamp ?? now,
17857
17733
  lamportClock: hostUserMessage?.lamportClock ?? lamportClock,
17858
17734
  role: "user",
@@ -17963,10 +17839,11 @@ async function* runAgentToolLoopIteration(context, input, state) {
17963
17839
  context.storage,
17964
17840
  input.conversationId
17965
17841
  );
17842
+ const localNodeId = resolveLocalNodeId(context, input);
17966
17843
  const buildAssistantMessage = (content) => context.normalizeMessage?.({
17967
17844
  messageId: assistantMessageId,
17968
17845
  conversationId: input.conversationId,
17969
- originNodeId: "local",
17846
+ originNodeId: localNodeId,
17970
17847
  timestamp: Date.now(),
17971
17848
  lamportClock: assistantLamportClock,
17972
17849
  role: "assistant",
@@ -17974,7 +17851,7 @@ async function* runAgentToolLoopIteration(context, input, state) {
17974
17851
  }) ?? {
17975
17852
  messageId: assistantMessageId,
17976
17853
  conversationId: input.conversationId,
17977
- originNodeId: "local",
17854
+ originNodeId: localNodeId,
17978
17855
  timestamp: Date.now(),
17979
17856
  lamportClock: assistantLamportClock,
17980
17857
  role: "assistant",
@@ -18192,6 +18069,44 @@ var init_directRunner = __esm({
18192
18069
  }
18193
18070
  });
18194
18071
 
18072
+ // src/loopAPI/scriptRuntime.ts
18073
+ function messageStep(message) {
18074
+ return { type: "message", data: message };
18075
+ }
18076
+ function createScriptStepEmitter(emittedSteps, onEmit) {
18077
+ return (step) => {
18078
+ emittedSteps.push(step);
18079
+ onEmit?.(step);
18080
+ };
18081
+ }
18082
+ function isAsyncIterable3(value) {
18083
+ return Boolean(value && typeof value === "object" && Symbol.asyncIterator in value);
18084
+ }
18085
+ async function* drainEmittedSteps(steps) {
18086
+ while (steps.length > 0) {
18087
+ const step = steps.shift();
18088
+ if (step) yield step;
18089
+ }
18090
+ }
18091
+ async function* yieldScriptResult(result, emittedSteps) {
18092
+ yield* drainEmittedSteps(emittedSteps);
18093
+ if (isAsyncIterable3(result)) {
18094
+ yield* result;
18095
+ yield* drainEmittedSteps(emittedSteps);
18096
+ } else if (typeof result === "string") {
18097
+ yield messageStep(result);
18098
+ } else if (Array.isArray(result)) {
18099
+ yield* result;
18100
+ } else if (result) {
18101
+ yield result;
18102
+ }
18103
+ }
18104
+ var init_scriptRuntime2 = __esm({
18105
+ "src/loopAPI/scriptRuntime.ts"() {
18106
+ "use strict";
18107
+ }
18108
+ });
18109
+
18195
18110
  // src/loops/agent-tool-loop/builtinLoopSources.ts
18196
18111
  function getBuiltinAgentToolLoopSource(id) {
18197
18112
  return builtinAgentToolLoopSources[id];
@@ -18410,6 +18325,18 @@ var init_scriptValidation = __esm({
18410
18325
  });
18411
18326
 
18412
18327
  // src/loopAPI/scriptLoader.ts
18328
+ function createBuiltinAgentLoopScriptLoader(loaderOptions) {
18329
+ let builtinDigestsRegistered;
18330
+ return async (scriptReference, policy = {}) => {
18331
+ builtinDigestsRegistered ??= registerBuiltinScriptSources(loaderOptions.sources);
18332
+ await builtinDigestsRegistered;
18333
+ return loadAgentLoopScript(scriptReference, {
18334
+ ...policy,
18335
+ getBuiltinScriptSource: loaderOptions.getBuiltinScriptSource,
18336
+ scriptType: loaderOptions.scriptType
18337
+ });
18338
+ };
18339
+ }
18413
18340
  function isLoadedScriptFunction(value) {
18414
18341
  return typeof value === "function";
18415
18342
  }
@@ -18591,40 +18518,24 @@ var init_scriptLoader = __esm({
18591
18518
  });
18592
18519
 
18593
18520
  // src/loopAPI/agent-tool-loop/scriptLoader.ts
18594
- function ensureBuiltinDigestsRegistered() {
18595
- builtinDigestsRegistered ??= registerBuiltinScriptSources(builtinAgentToolLoopSources);
18596
- return builtinDigestsRegistered;
18597
- }
18598
18521
  async function loadAgentToolLoopScript(scriptReference, options = {}) {
18599
- await ensureBuiltinDigestsRegistered();
18600
- return loadAgentLoopScript(scriptReference, {
18601
- ...options,
18602
- getBuiltinScriptSource: getBuiltinAgentToolLoopSource,
18603
- scriptType: "AgentToolLoop script"
18604
- });
18522
+ return loadScript(scriptReference, options);
18605
18523
  }
18606
- var builtinDigestsRegistered;
18524
+ var loadScript;
18607
18525
  var init_scriptLoader2 = __esm({
18608
18526
  "src/loopAPI/agent-tool-loop/scriptLoader.ts"() {
18609
18527
  "use strict";
18610
18528
  init_builtinLoopSources2();
18611
18529
  init_scriptLoader();
18530
+ loadScript = createBuiltinAgentLoopScriptLoader({
18531
+ sources: builtinAgentToolLoopSources,
18532
+ getBuiltinScriptSource: getBuiltinAgentToolLoopSource,
18533
+ scriptType: "AgentToolLoop script"
18534
+ });
18612
18535
  }
18613
18536
  });
18614
18537
 
18615
18538
  // src/loopAPI/agent-tool-loop/scriptRunner.ts
18616
- function isAsyncIterable3(value) {
18617
- return Boolean(value && typeof value === "object" && Symbol.asyncIterator in value);
18618
- }
18619
- function messageStep(message) {
18620
- return { type: "message", data: message };
18621
- }
18622
- async function* drainEmittedSteps(steps) {
18623
- while (steps.length > 0) {
18624
- const step = steps.shift();
18625
- if (step) yield step;
18626
- }
18627
- }
18628
18539
  function asAgentToolLoopContext(rawContext) {
18629
18540
  return rawContext;
18630
18541
  }
@@ -18636,10 +18547,7 @@ async function resolveAgentToolLoopScript(context) {
18636
18547
  return loadAgentToolLoopScript(scriptReference, context.scriptPolicy);
18637
18548
  }
18638
18549
  function createAgentToolLoopScriptContext(input, context, emittedSteps) {
18639
- const emit = (step) => {
18640
- emittedSteps.push(step);
18641
- context.runtime?.emit?.(step);
18642
- };
18550
+ const emit = createScriptStepEmitter(emittedSteps, context.runtime?.emit);
18643
18551
  return {
18644
18552
  input,
18645
18553
  context,
@@ -18662,21 +18570,12 @@ function createAgentToolLoopScriptContext(input, context, emittedSteps) {
18662
18570
  async function* runAgentToolLoopScript(script, input, context) {
18663
18571
  const emittedSteps = [];
18664
18572
  const result = await script(createAgentToolLoopScriptContext(input, context, emittedSteps));
18665
- yield* drainEmittedSteps(emittedSteps);
18666
- if (isAsyncIterable3(result)) {
18667
- yield* result;
18668
- yield* drainEmittedSteps(emittedSteps);
18669
- } else if (typeof result === "string") {
18670
- yield messageStep(result);
18671
- } else if (Array.isArray(result)) {
18672
- yield* result;
18673
- } else if (result) {
18674
- yield result;
18675
- }
18573
+ yield* yieldScriptResult(result, emittedSteps);
18676
18574
  }
18677
18575
  var init_scriptRunner = __esm({
18678
18576
  "src/loopAPI/agent-tool-loop/scriptRunner.ts"() {
18679
18577
  "use strict";
18578
+ init_scriptRuntime2();
18680
18579
  init_scriptLoader2();
18681
18580
  init_turnPrimitives();
18682
18581
  }
@@ -23926,6 +23825,16 @@ function createWorkerProtocolGateway(options) {
23926
23825
  const rateLimit = options.maxRequestsPerMinute ?? DEFAULT_RATE_PER_MINUTE2;
23927
23826
  const maxResponseBytes = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
23928
23827
  const requestLog = /* @__PURE__ */ new Map();
23828
+ let nextRequestLogSweepAt = 0;
23829
+ function pruneInactiveRequestLogs(windowStart, receivedAtMs) {
23830
+ if (receivedAtMs < nextRequestLogSweepAt) return;
23831
+ for (const [sessionName, timestamps] of requestLog) {
23832
+ if (timestamps.length === 0 || timestamps[timestamps.length - 1] < windowStart) {
23833
+ requestLog.delete(sessionName);
23834
+ }
23835
+ }
23836
+ nextRequestLogSweepAt = receivedAtMs + 6e4;
23837
+ }
23929
23838
  async function audit(request, accepted, receivedAt, code) {
23930
23839
  try {
23931
23840
  await options.onAudit?.({
@@ -23984,6 +23893,7 @@ function createWorkerProtocolGateway(options) {
23984
23893
  throw protocolError("CONFLICT", "worker request sequence or nonce was already consumed");
23985
23894
  }
23986
23895
  const windowStart = received.getTime() - 6e4;
23896
+ pruneInactiveRequestLogs(windowStart, received.getTime());
23987
23897
  const log = (requestLog.get(session.name) ?? []).filter((time) => time >= windowStart);
23988
23898
  if (log.length >= rateLimit) {
23989
23899
  throw new OrchestrationError({
@@ -26165,34 +26075,24 @@ var init_orchestration2 = __esm({
26165
26075
  });
26166
26076
 
26167
26077
  // src/loopAPI/agent-agent-loop/scriptLoader.ts
26168
- function ensureBuiltinDigestsRegistered2() {
26169
- builtinDigestsRegistered2 ??= registerBuiltinScriptSources(builtinAgentAgentLoopSources);
26170
- return builtinDigestsRegistered2;
26171
- }
26172
26078
  async function loadAgentAgentLoopScript(scriptReference, options = {}) {
26173
- await ensureBuiltinDigestsRegistered2();
26174
- return loadAgentLoopScript(scriptReference, {
26175
- ...options,
26176
- getBuiltinScriptSource: getBuiltinAgentAgentLoopSource,
26177
- scriptType: "AgentAgentLoop script"
26178
- });
26079
+ return loadScript2(scriptReference, options);
26179
26080
  }
26180
- var builtinDigestsRegistered2;
26081
+ var loadScript2;
26181
26082
  var init_scriptLoader3 = __esm({
26182
26083
  "src/loopAPI/agent-agent-loop/scriptLoader.ts"() {
26183
26084
  "use strict";
26184
26085
  init_builtinLoopSources();
26185
26086
  init_scriptLoader();
26087
+ loadScript2 = createBuiltinAgentLoopScriptLoader({
26088
+ sources: builtinAgentAgentLoopSources,
26089
+ getBuiltinScriptSource: getBuiltinAgentAgentLoopSource,
26090
+ scriptType: "AgentAgentLoop script"
26091
+ });
26186
26092
  }
26187
26093
  });
26188
26094
 
26189
26095
  // src/loopAPI/agent-agent-loop/loop.ts
26190
- function isAsyncIterable4(value) {
26191
- return Boolean(value && typeof value === "object" && Symbol.asyncIterator in value);
26192
- }
26193
- function messageStep2(message) {
26194
- return { type: "message", data: message };
26195
- }
26196
26096
  function stepText(step) {
26197
26097
  if (step.type !== "message") return void 0;
26198
26098
  if (typeof step.data === "string") return step.data;
@@ -26246,10 +26146,7 @@ function createScriptArguments(input, context, emittedSteps) {
26246
26146
  if (key === "agents") return agentEntries;
26247
26147
  return readProfileAgentEntries(context.profile, key) ?? [];
26248
26148
  };
26249
- const emit = (step) => {
26250
- emittedSteps.push(step);
26251
- context.runtime?.emit?.(step);
26252
- };
26149
+ const emit = createScriptStepEmitter(emittedSteps, context.runtime?.emit);
26253
26150
  const log = (event, data) => {
26254
26151
  context.runtime?.log?.(event, data);
26255
26152
  };
@@ -26347,11 +26244,11 @@ function createScriptArguments(input, context, emittedSteps) {
26347
26244
  runParallel: (batchInput) => runBatch(batchInput, "parallel"),
26348
26245
  formatAgentResults,
26349
26246
  finishAgentResults: (result, options) => {
26350
- emit(messageStep2(formatAgentResults(result, options)));
26247
+ emit(messageStep(formatAgentResults(result, options)));
26351
26248
  },
26352
26249
  emit,
26353
26250
  finish: (message) => {
26354
- emit(typeof message === "string" ? messageStep2(message) : message);
26251
+ emit(typeof message === "string" ? messageStep(message) : message);
26355
26252
  },
26356
26253
  isCancelled,
26357
26254
  log,
@@ -26364,27 +26261,11 @@ function createScriptArguments(input, context, emittedSteps) {
26364
26261
  loadCheckpoint: context.runtime?.loadCheckpoint ?? (async () => void 0)
26365
26262
  };
26366
26263
  }
26367
- async function* drainEmittedSteps2(steps) {
26368
- while (steps.length > 0) {
26369
- const step = steps.shift();
26370
- if (step) yield step;
26371
- }
26372
- }
26373
26264
  async function* runScript(script, input, context) {
26374
26265
  const emittedSteps = [];
26375
26266
  const scriptArguments = createScriptArguments(input, context, emittedSteps);
26376
26267
  const result = await script(scriptArguments);
26377
- yield* drainEmittedSteps2(emittedSteps);
26378
- if (isAsyncIterable4(result)) {
26379
- yield* result;
26380
- yield* drainEmittedSteps2(emittedSteps);
26381
- } else if (typeof result === "string") {
26382
- yield messageStep2(result);
26383
- } else if (Array.isArray(result)) {
26384
- yield* result;
26385
- } else if (result) {
26386
- yield result;
26387
- }
26268
+ yield* yieldScriptResult(result, emittedSteps);
26388
26269
  }
26389
26270
  function asAgentAgentContext(context) {
26390
26271
  return context;
@@ -26447,6 +26328,7 @@ var init_loop2 = __esm({
26447
26328
  "src/loopAPI/agent-agent-loop/loop.ts"() {
26448
26329
  "use strict";
26449
26330
  init_orchestration2();
26331
+ init_scriptRuntime2();
26450
26332
  init_scriptLoader3();
26451
26333
  LOOP_ID = "agent-agent-loop";
26452
26334
  LOOP_NAME = "AgentAgent Loop";
@@ -27293,7 +27175,8 @@ var ChatSyncEngine = class {
27293
27175
  }
27294
27176
  }
27295
27177
  /**
27296
- * Anti-entropy:先 syncOnce,再对已知会话逐个向各 peer 拉取缺失消息(参考审查单「定期对账」)。
27178
+ * Anti-entropy 的定期对账入口。`syncOnce` 本身已经遍历全部已知会话,
27179
+ * 并在 metadata 对账后向各 peer 拉取缺失消息,因此这里无需第二次重复拉取。
27297
27180
  */
27298
27181
  async antiEntropyOnce() {
27299
27182
  await this.syncOnce();
@@ -30231,6 +30114,18 @@ function createPeerDriverRpcHandler(handlers) {
30231
30114
  }
30232
30115
 
30233
30116
  // src/device-network/syncCloudDevices.ts
30117
+ function warnAboutCloudKeyRotation(logger3, record2) {
30118
+ const message = "[device-network] Cloud directory rotated a cloud-account device public key";
30119
+ const details = {
30120
+ peerId: record2.peerId,
30121
+ accountId: record2.accountId
30122
+ };
30123
+ if (logger3) {
30124
+ logger3.warn(message, details);
30125
+ return;
30126
+ }
30127
+ console.warn(message, details);
30128
+ }
30234
30129
  async function syncCloudDevices(input) {
30235
30130
  const cloudDevices = await input.cloudClient.listDevices();
30236
30131
  const existingRecords = await input.trustStore.loadTrustedDevices();
@@ -30248,6 +30143,9 @@ async function syncCloudDevices(input) {
30248
30143
  for (const cloudDevice of activeCloudDevices) {
30249
30144
  const existing = existingByPeerId.get(cloudDevice.peerId);
30250
30145
  if (existing?.trustMode === "local-pairing") continue;
30146
+ if (existing?.trustMode === "cloud-account" && existing.publicKeyMultibase !== cloudDevice.publicKeyMultibase) {
30147
+ warnAboutCloudKeyRotation(input.logger, existing);
30148
+ }
30251
30149
  const record2 = {
30252
30150
  peerId: cloudDevice.peerId,
30253
30151
  publicKeyMultibase: cloudDevice.publicKeyMultibase,