@robota-sdk/agent-cli 3.0.0-beta.99 → 3.0.1
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.
- package/CHANGELOG.md +2181 -8
- package/dist/node/bin.js +22 -22
- package/dist/node/cli-core-Cus9ebuT.js +2920 -0
- package/dist/node/desktop-host.js +1 -1
- package/dist/node/headless.js +2 -2
- package/dist/node/host.d.ts +1 -1
- package/dist/node/host.js +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.js +2 -2
- package/dist/node/index.js.map +1 -1
- package/dist/node/node-BsDZQcvi.js +67 -0
- package/dist/node/node-Ct446qHg.js +15 -0
- package/dist/node/node-Ct446qHg.js.map +1 -0
- package/dist/node/node-DdB-oeq6.js +100 -0
- package/dist/node/node-DdB-oeq6.js.map +1 -0
- package/dist/node/node-PhNl8kvo.js +15 -0
- package/dist/node/node-gdZ0H7su.js +100 -0
- package/dist/node/node-oHeP4vDn.js +67 -0
- package/dist/node/node-oHeP4vDn.js.map +1 -0
- package/dist/node/product-host-C-IQQ6ph.js +2954 -0
- package/dist/node/product-host-C-IQQ6ph.js.map +1 -0
- package/dist/node/{product-host-DYR8lHfh.d.ts → product-host-SaMRTzxB.d.ts} +3 -3
- package/dist/node/{product-host-DYR8lHfh.d.ts.map → product-host-SaMRTzxB.d.ts.map} +1 -1
- package/dist/node/src-B9UMvThT-C1A4E6i9.js +2 -0
- package/dist/node/src-B9UMvThT-C1A4E6i9.js.map +1 -0
- package/dist/node/src-B9UMvThT-fOIUDLqp.js +2 -0
- package/dist/node/src-BzaNFPZx-Cn-T7595.js +2 -0
- package/dist/node/src-BzaNFPZx-Cn-T7595.js.map +1 -0
- package/dist/node/src-BzaNFPZx-Df7aFS3N.js +2 -0
- package/dist/node/src-DwAfU-9z-B8gxThPt.js +2 -0
- package/dist/node/{node-BIcfIxK2.js → src-DwAfU-9z-DU29KIpt.js} +2 -2
- package/dist/node/src-DwAfU-9z-DU29KIpt.js.map +1 -0
- package/dist/node/src-UPsd6jNY-B387swGC.js +2 -0
- package/dist/node/src-UPsd6jNY-DPPw_--T.js +2 -0
- package/dist/node/src-UPsd6jNY-DPPw_--T.js.map +1 -0
- package/package.json +43 -43
- package/dist/node/cli-core-CrauPvKn.js +0 -2920
- package/dist/node/node-BIcfIxK2.js.map +0 -1
- package/dist/node/node-BRvqhy29.js +0 -165
- package/dist/node/node-BRvqhy29.js.map +0 -1
- package/dist/node/node-BTKWbzr0.js +0 -15
- package/dist/node/node-BZfTvzcV.js +0 -15
- package/dist/node/node-BZfTvzcV.js.map +0 -1
- package/dist/node/node-CI_NCC-t.js +0 -2
- package/dist/node/node-zABT8WBL.js +0 -165
- package/dist/node/product-host-DmP4TgQl.js +0 -2954
- package/dist/node/product-host-DmP4TgQl.js.map +0 -1
package/dist/node/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["organizationCanonical","identifier","record","identifier","identifier","parsePublicHttpsUrl","createAccessTokenVerifier","createBearerResourceServer","bearerCredential"],"sources":["../../../agent-organization/dist/node/index.js","../../../agent-organization-host/dist/node/index.js","../../src/hosted/hosted-organization-control.ts","../../src/hosted/e2b-organization-inventory.ts","../../src/hosted/hosted-organization-gateway.ts","../../src/hosted/hosted-organization-payloads.ts","../../src/hosted/hosted-organization-model.ts","../../src/hosted/hosted-organization-token-counter.ts","../../src/hosted/hosted-filesystem-checkpoint.ts","../../src/hosted/e2b-worker-provisioning.ts","../../src/hosted/desktop/authorization.ts","../../src/hosted/desktop/authority-store.ts","../../src/hosted/desktop/worker-port.ts","../../src/hosted/desktop/gateway.ts"],"sourcesContent":["//#region src/error.ts\nvar OrganizationSchemaError = class extends Error {\n\treason = \"invalid-schema\";\n\tconstructor() {\n\t\tsuper(\"Invalid organization schema\");\n\t}\n};\n//#endregion\n//#region src/canonical.ts\nfunction validString(value) {\n\tfor (const character of value) {\n\t\tconst point = character.codePointAt(0);\n\t\tif (point >= 55296 && point <= 57343) throw new OrganizationSchemaError();\n\t}\n}\n/** Canonical JSON for a bounded, safe-integer subset; no float coercion. */\nfunction organizationCanonical(value) {\n\tconst visiting = /* @__PURE__ */ new Set();\n\tlet nodes = 0;\n\tfunction encode(item, depth) {\n\t\tif (++nodes > 4096 || depth > 32) throw new OrganizationSchemaError();\n\t\tif (item === null || typeof item === \"boolean\") return JSON.stringify(item);\n\t\tif (typeof item === \"string\") {\n\t\t\tvalidString(item);\n\t\t\treturn JSON.stringify(item);\n\t\t}\n\t\tif (typeof item === \"number\") {\n\t\t\tif (!Number.isSafeInteger(item) || Object.is(item, -0)) throw new OrganizationSchemaError();\n\t\t\treturn JSON.stringify(item);\n\t\t}\n\t\tif (typeof item !== \"object\" || visiting.has(item)) throw new OrganizationSchemaError();\n\t\tvisiting.add(item);\n\t\ttry {\n\t\t\tif (Array.isArray(item)) {\n\t\t\t\tif (Reflect.ownKeys(item).length !== item.length + 1) throw new OrganizationSchemaError();\n\t\t\t\treturn `[${Array.from({ length: item.length }, (_, index) => {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(item, String(index));\n\t\t\t\t\tif (descriptor === void 0 || !(\"value\" in descriptor)) throw new OrganizationSchemaError();\n\t\t\t\t\treturn encode(descriptor.value, depth + 1);\n\t\t\t\t}).join(\",\")}]`;\n\t\t\t}\n\t\t\tif (Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null) throw new OrganizationSchemaError();\n\t\t\tconst keys = Reflect.ownKeys(item);\n\t\t\tif (keys.some((key) => typeof key !== \"string\")) throw new OrganizationSchemaError();\n\t\t\treturn `{${keys.sort().map((key) => {\n\t\t\t\tvalidString(key);\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(item, key);\n\t\t\t\tif (!descriptor.enumerable || !(\"value\" in descriptor)) throw new OrganizationSchemaError();\n\t\t\t\treturn `${JSON.stringify(key)}:${encode(descriptor.value, depth + 1)}`;\n\t\t\t}).join(\",\")}}`;\n\t\t} finally {\n\t\t\tvisiting.delete(item);\n\t\t}\n\t}\n\tconst encoded = encode(value, 0);\n\tif (new TextEncoder().encode(encoded).byteLength > 64 * 1024) throw new OrganizationSchemaError();\n\treturn encoded;\n}\n//#endregion\n//#region src/validation.ts\nfunction exactRecord(value, keys) {\n\torganizationCanonical(value);\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new OrganizationSchemaError();\n\tconst record = value;\n\tif (Object.keys(record).length !== keys.length || keys.some((key) => !Object.hasOwn(record, key))) throw new OrganizationSchemaError();\n\treturn record;\n}\nfunction nonnegativeInteger(value, minimum = 0) {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || Object.is(value, -0) || value < minimum) throw new OrganizationSchemaError();\n\treturn value;\n}\nfunction organizationUnits(value) {\n\tconst data = exactRecord(value, [\n\t\t\"tokens\",\n\t\t\"timeMs\",\n\t\t\"costMicros\"\n\t]);\n\treturn Object.freeze({\n\t\ttokens: nonnegativeInteger(data.tokens),\n\t\ttimeMs: nonnegativeInteger(data.timeMs),\n\t\tcostMicros: nonnegativeInteger(data.costMicros)\n\t});\n}\nfunction organizationBudget(value) {\n\tconst data = exactRecord(value, [\n\t\t\"tokens\",\n\t\t\"timeMs\",\n\t\t\"costMicros\",\n\t\t\"concurrency\"\n\t]);\n\treturn Object.freeze({\n\t\ttokens: nonnegativeInteger(data.tokens),\n\t\ttimeMs: nonnegativeInteger(data.timeMs),\n\t\tcostMicros: nonnegativeInteger(data.costMicros),\n\t\tconcurrency: nonnegativeInteger(data.concurrency, 1)\n\t});\n}\n//#endregion\nexport { OrganizationSchemaError, organizationBudget, organizationCanonical, organizationUnits };\n\n//# sourceMappingURL=index.js.map","import { createRequire } from \"node:module\";\nimport { createHash, createPublicKey, randomUUID, verify } from \"node:crypto\";\nimport { OrganizationSchemaError, organizationBudget, organizationCanonical as organizationCanonical$1, organizationUnits } from \"@robota-sdk/agent-organization\";\nimport { execFileSync } from \"node:child_process\";\nimport { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, join } from \"node:path\";\nimport { performance } from \"node:perf_hooks\";\n//#region src/types.ts\nvar OrganizationRefused = class extends Error {\n\treason;\n\tconstructor(reason) {\n\t\tsuper(`Organization operation refused: ${reason}`);\n\t\tthis.reason = reason;\n\t}\n};\n//#endregion\n//#region src/canonical.ts\nfunction organizationCanonical(value) {\n\ttry {\n\t\treturn organizationCanonical$1(value);\n\t} catch (error) {\n\t\tif (error instanceof OrganizationSchemaError) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthrow error;\n\t}\n}\nfunction organizationSigningBytes(domain, claims) {\n\tif (![\n\t\t\"workload\",\n\t\t\"request\",\n\t\t\"approval\"\n\t].includes(domain)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Buffer.from(organizationCanonical([`robota/organization-${domain}/v1`, claims]), \"utf8\");\n}\nfunction organizationOperationDigest(request) {\n\treturn createHash(\"sha256\").update(organizationCanonical([\n\t\t\"robota/organization-operation/v1\",\n\t\trequest.grantId,\n\t\trequest.tenant,\n\t\trequest.task,\n\t\trequest.actor,\n\t\trequest.audience,\n\t\trequest.epoch,\n\t\trequest.operation\n\t]), \"utf8\").digest(\"hex\");\n}\n//#endregion\n//#region src/verification.ts\nfunction record(value, keys) {\n\torganizationCanonical(value);\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new OrganizationRefused(\"invalid-schema\");\n\tconst data = value;\n\tif (Object.keys(data).length !== keys.length || keys.some((key) => !Object.hasOwn(data, key))) throw new OrganizationRefused(\"invalid-schema\");\n\treturn data;\n}\nfunction identifier(value) {\n\tif (typeof value !== \"string\" || value.length < 1 || value.length > 256 || [...value].some((character) => {\n\t\tconst point = character.codePointAt(0);\n\t\treturn point < 32 || point === 127 || point >= 55296 && point <= 57343;\n\t})) throw new OrganizationRefused(\"invalid-schema\");\n\treturn value;\n}\nfunction integer(value, minimum = 0) {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || Object.is(value, -0) || value < minimum) throw new OrganizationRefused(\"invalid-schema\");\n\treturn value;\n}\nfunction units(value) {\n\ttry {\n\t\treturn organizationUnits(value);\n\t} catch (error) {\n\t\tif (error instanceof OrganizationSchemaError) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthrow error;\n\t}\n}\nfunction receipt(value) {\n\tconst data = record(value, [\"value\", \"usage\"]);\n\treturn Object.freeze({\n\t\tvalue: immutableJson(JSON.parse(organizationCanonical(data.value))),\n\t\tusage: units(data.usage)\n\t});\n}\nfunction budget(value) {\n\ttry {\n\t\treturn organizationBudget(value);\n\t} catch (error) {\n\t\tif (error instanceof OrganizationSchemaError) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthrow error;\n\t}\n}\nfunction publicKey(value) {\n\tif (typeof value !== \"string\" || value.length > 4096 || !value.startsWith(\"-----BEGIN PUBLIC KEY-----\")) throw new OrganizationRefused(\"invalid-schema\");\n\ttry {\n\t\tconst key = createPublicKey(value);\n\t\tif (key.asymmetricKeyType !== \"ed25519\") throw new Error(\"wrong type\");\n\t\treturn key;\n\t} catch {\n\t\tthrow new OrganizationRefused(\"invalid-proof\");\n\t}\n}\nfunction strings(value) {\n\tif (!Array.isArray(value) || value.length < 1 || value.length > 64) throw new OrganizationRefused(\"invalid-schema\");\n\tconst output = value.map(identifier);\n\tif (new Set(output).size !== output.length) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Object.freeze(output);\n}\nfunction immutableJson(value) {\n\tif (value !== null && typeof value === \"object\") {\n\t\tfor (const child of Object.values(value)) immutableJson(child);\n\t\tObject.freeze(value);\n\t}\n\treturn value;\n}\nfunction validity(data) {\n\tif (data.version !== 1 || integer(data.expiresAt, 1) <= integer(data.notBefore)) throw new OrganizationRefused(\"invalid-schema\");\n\tinteger(data.epoch, 1);\n}\nfunction grantClaims(value) {\n\tconst data = record(value, [\n\t\t\"version\",\n\t\t\"id\",\n\t\t\"tenant\",\n\t\t\"task\",\n\t\t\"actor\",\n\t\t\"role\",\n\t\t\"audience\",\n\t\t\"parent\",\n\t\t\"epoch\",\n\t\t\"notBefore\",\n\t\t\"expiresAt\",\n\t\t\"publicKey\",\n\t\t\"scopes\",\n\t\t\"budget\"\n\t]);\n\tvalidity(data);\n\tpublicKey(data.publicKey);\n\tif (!Array.isArray(data.scopes) || data.scopes.length < 1 || data.scopes.length > 64) throw new OrganizationRefused(\"invalid-schema\");\n\tconst scopes = data.scopes.map((value) => {\n\t\tconst scope = record(value, [\"resource\", \"operations\"]);\n\t\treturn Object.freeze({\n\t\t\tresource: identifier(scope.resource),\n\t\t\toperations: strings(scope.operations)\n\t\t});\n\t});\n\tif (new Set(scopes.map((scope) => scope.resource)).size !== scopes.length) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Object.freeze({\n\t\tversion: 1,\n\t\tid: identifier(data.id),\n\t\ttenant: identifier(data.tenant),\n\t\ttask: identifier(data.task),\n\t\tactor: identifier(data.actor),\n\t\trole: identifier(data.role),\n\t\taudience: identifier(data.audience),\n\t\tparent: data.parent === null ? null : identifier(data.parent),\n\t\tepoch: integer(data.epoch, 1),\n\t\tnotBefore: integer(data.notBefore),\n\t\texpiresAt: integer(data.expiresAt, 1),\n\t\tpublicKey: data.publicKey,\n\t\tscopes: Object.freeze(scopes),\n\t\tbudget: budget(data.budget)\n\t});\n}\nfunction requestClaims(value) {\n\tconst data = record(value, [\n\t\t\"version\",\n\t\t\"grantId\",\n\t\t\"tenant\",\n\t\t\"task\",\n\t\t\"actor\",\n\t\t\"audience\",\n\t\t\"epoch\",\n\t\t\"nonce\",\n\t\t\"notBefore\",\n\t\t\"expiresAt\",\n\t\t\"operation\"\n\t]);\n\tvalidity(data);\n\tconst operation = record(data.operation, [\n\t\t\"idempotencyKey\",\n\t\t\"resource\",\n\t\t\"operation\",\n\t\t\"environment\",\n\t\t\"parameters\"\n\t]);\n\treturn Object.freeze({\n\t\tversion: 1,\n\t\tgrantId: identifier(data.grantId),\n\t\ttenant: identifier(data.tenant),\n\t\ttask: identifier(data.task),\n\t\tactor: identifier(data.actor),\n\t\taudience: identifier(data.audience),\n\t\tepoch: integer(data.epoch, 1),\n\t\tnonce: identifier(data.nonce),\n\t\tnotBefore: integer(data.notBefore),\n\t\texpiresAt: integer(data.expiresAt, 1),\n\t\toperation: Object.freeze({\n\t\t\tidempotencyKey: identifier(operation.idempotencyKey),\n\t\t\tresource: identifier(operation.resource),\n\t\t\toperation: identifier(operation.operation),\n\t\t\tenvironment: identifier(operation.environment),\n\t\t\tparameters: immutableJson(JSON.parse(organizationCanonical(operation.parameters)))\n\t\t})\n\t});\n}\nfunction approvalClaims(value) {\n\tconst data = record(value, [\n\t\t\"version\",\n\t\t\"id\",\n\t\t\"tenant\",\n\t\t\"task\",\n\t\t\"actor\",\n\t\t\"audience\",\n\t\t\"epoch\",\n\t\t\"environment\",\n\t\t\"operationDigest\",\n\t\t\"notBefore\",\n\t\t\"expiresAt\"\n\t]);\n\tvalidity(data);\n\tif (typeof data.operationDigest !== \"string\" || !/^[a-f0-9]{64}$/.test(data.operationDigest)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Object.freeze({\n\t\tversion: 1,\n\t\tid: identifier(data.id),\n\t\ttenant: identifier(data.tenant),\n\t\ttask: identifier(data.task),\n\t\tactor: identifier(data.actor),\n\t\taudience: identifier(data.audience),\n\t\tepoch: integer(data.epoch, 1),\n\t\tenvironment: identifier(data.environment),\n\t\toperationDigest: data.operationDigest,\n\t\tnotBefore: integer(data.notBefore),\n\t\texpiresAt: integer(data.expiresAt, 1)\n\t});\n}\nfunction verifyEnvelope(domain, envelope, key) {\n\tconst data = record(envelope, [\"claims\", \"signature\"]);\n\tif (typeof data.signature !== \"string\" || !/^[A-Za-z0-9_-]{86}$/.test(data.signature)) throw new OrganizationRefused(\"invalid-proof\");\n\tconst signature = Buffer.from(data.signature, \"base64url\");\n\tif (signature.length !== 64 || signature.toString(\"base64url\") !== data.signature || !verify(null, organizationSigningBytes(domain, data.claims), key, signature)) throw new OrganizationRefused(\"invalid-proof\");\n}\nfunction currentTime(claims, now, maxTtlMs) {\n\tinteger(now);\n\tif (claims.expiresAt - claims.notBefore > maxTtlMs || now < claims.notBefore || now >= claims.expiresAt) throw new OrganizationRefused(\"expired\");\n}\n//#endregion\n//#region src/audit.ts\n/** A trusted sink may report this only when its expected-head CAS made no append. Other failures are ambiguous. */\nvar OrganizationAuditAppendConflict = class extends Error {\n\tconstructor() {\n\t\tsuper(\"Organization audit append conflict\");\n\t}\n};\nconst HASH = /^[0-9a-f]{64}$/;\nconst PHASES = [\n\t\"dispatch\",\n\t\"complete\",\n\t\"refused\",\n\t\"unknown\"\n];\nfunction digest$1(value) {\n\treturn createHash(\"sha256\").update(organizationCanonical(value), \"utf8\").digest(\"hex\");\n}\nfunction hash(value) {\n\tif (typeof value !== \"string\" || !HASH.test(value)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn value;\n}\nfunction head(value, stream) {\n\tconst data = record(value, [\n\t\t\"version\",\n\t\t\"stream\",\n\t\t\"sequence\",\n\t\t\"hash\"\n\t]);\n\tif (data.version !== 1 || data.stream !== stream) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Object.freeze({\n\t\tversion: 1,\n\t\tstream,\n\t\tsequence: integer(data.sequence),\n\t\thash: hash(data.hash)\n\t});\n}\nfunction event(value) {\n\tconst data = record(value, [\n\t\t\"phase\",\n\t\t\"operationDigest\",\n\t\t\"tenantDigest\",\n\t\t\"taskDigest\",\n\t\t\"actorDigest\",\n\t\t\"grantDigest\",\n\t\t\"epoch\"\n\t]);\n\tif (typeof data.phase !== \"string\" || !PHASES.includes(data.phase)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Object.freeze({\n\t\tphase: data.phase,\n\t\toperationDigest: hash(data.operationDigest),\n\t\ttenantDigest: hash(data.tenantDigest),\n\t\ttaskDigest: hash(data.taskDigest),\n\t\tactorDigest: hash(data.actorDigest),\n\t\tgrantDigest: hash(data.grantDigest),\n\t\tepoch: integer(data.epoch, 1)\n\t});\n}\nfunction organizationAuditEvent(value, phase) {\n\tif (!PHASES.includes(phase)) throw new OrganizationRefused(\"invalid-schema\");\n\tconst request = requestClaims(value);\n\tconst pseudonym = (kind, parts) => digest$1([\n\t\t\"robota/organization-audit-identity/v1\",\n\t\tkind,\n\t\tparts\n\t]);\n\treturn Object.freeze({\n\t\tphase,\n\t\toperationDigest: organizationOperationDigest(request),\n\t\ttenantDigest: pseudonym(\"tenant\", [request.tenant]),\n\t\ttaskDigest: pseudonym(\"task\", [request.tenant, request.task]),\n\t\tactorDigest: pseudonym(\"actor\", [request.tenant, request.actor]),\n\t\tgrantDigest: pseudonym(\"grant\", [request.grantId]),\n\t\tepoch: request.epoch\n\t});\n}\nfunction organizationAuditGenesis(stream) {\n\tidentifier(stream);\n\treturn Object.freeze({\n\t\tversion: 1,\n\t\tstream,\n\t\tsequence: 0,\n\t\thash: digest$1([\"robota/organization-audit-genesis/v1\", stream])\n\t});\n}\nfunction organizationAuditHash(stream, sequence, previous, value) {\n\treturn digest$1([\n\t\t\"robota/organization-audit-entry/v1\",\n\t\tidentifier(stream),\n\t\tinteger(sequence, 1),\n\t\thash(previous),\n\t\tevent(value)\n\t]);\n}\n/** Public signing bytes for an external audit owner; this package never accepts its private key. */\nfunction organizationAuditSigningBytes(value) {\n\treturn Buffer.from(organizationCanonical([\"robota/organization-audit-checkpoint/v1\", head(value, identifier(value.stream))]), \"utf8\");\n}\nfunction checkpoint(value, stream, key) {\n\tconst data = record(value, [\"claims\", \"signature\"]);\n\tconst claims = head(data.claims, stream);\n\tif (typeof data.signature !== \"string\" || !/^[A-Za-z0-9_-]{86}$/.test(data.signature)) throw new OrganizationRefused(\"invalid-proof\");\n\tconst signature = Buffer.from(data.signature, \"base64url\");\n\tif (signature.length !== 64 || signature.toString(\"base64url\") !== data.signature || !verify(null, organizationAuditSigningBytes(claims), key, signature)) throw new OrganizationRefused(\"invalid-proof\");\n\tif (claims.sequence === 0 && claims.hash !== organizationAuditGenesis(stream).hash) throw new OrganizationRefused(\"invalid-proof\");\n\treturn Object.freeze({\n\t\tclaims,\n\t\tsignature: data.signature\n\t});\n}\nfunction entry(value, previous) {\n\tconst data = record(value, [\n\t\t\"stream\",\n\t\t\"sequence\",\n\t\t\"previous\",\n\t\t\"event\",\n\t\t\"hash\"\n\t]);\n\tconst safeEvent = event(data.event);\n\tif (data.stream !== previous.stream || data.sequence !== previous.sequence + 1 || data.previous !== previous.hash) throw new OrganizationRefused(\"invalid-proof\");\n\tconst computed = organizationAuditHash(previous.stream, integer(data.sequence, 1), previous.hash, safeEvent);\n\tif (data.hash !== computed) throw new OrganizationRefused(\"invalid-proof\");\n\treturn Object.freeze({\n\t\tstream: previous.stream,\n\t\tsequence: data.sequence,\n\t\tprevious: previous.hash,\n\t\tevent: safeEvent,\n\t\thash: computed\n\t});\n}\nfunction same(a, b) {\n\treturn a.stream === b.stream && a.sequence === b.sequence && a.hash === b.hash;\n}\nfunction page(value, start, key) {\n\tconst data = record(value, [\"entries\", \"head\"]);\n\tif (!Array.isArray(data.entries) || data.entries.length > 128) throw new OrganizationRefused(\"invalid-schema\");\n\tconst last = checkpoint(data.head, start.stream, key);\n\tlet current = start;\n\tfor (const item of data.entries) {\n\t\tconst next = entry(item, current);\n\t\tcurrent = {\n\t\t\tversion: 1,\n\t\t\tstream: next.stream,\n\t\t\tsequence: next.sequence,\n\t\t\thash: next.hash\n\t\t};\n\t}\n\tif (!same(current, last.claims)) throw new OrganizationRefused(\"invalid-proof\");\n\treturn last;\n}\n/** Verify a bounded continuation against pinned signed checkpoints, without trusting a mutable local head. */\nfunction verifyOrganizationAudit(entries, start, end, pinnedKey, pinnedStream) {\n\tconst key = publicKey(pinnedKey);\n\tconst first = checkpoint(start, identifier(pinnedStream), key);\n\treturn page({\n\t\tentries,\n\t\thead: end\n\t}, first.claims, key).claims;\n}\nfunction pause(milliseconds, signal) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst cleanup = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t};\n\t\tconst abort = () => {\n\t\t\tcleanup();\n\t\t\treject(new OrganizationRefused(\"policy-unavailable\"));\n\t\t};\n\t\tconst timer = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t}, milliseconds);\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\tif (signal.aborted) abort();\n\t});\n}\nfunction active(signal) {\n\tif (signal.aborted) throw new OrganizationRefused(\"policy-unavailable\");\n}\n/** Dispatch can proceed only after an exact event and its independently retained checkpoint are confirmed. */\nvar OrganizationAudit = class {\n\tstream;\n\tkey;\n\tsink;\n\tanchor;\n\ttimeout;\n\tconstructor(options) {\n\t\tthis.stream = identifier(options.stream);\n\t\tthis.key = publicKey(options.publicKey);\n\t\tthis.timeout = integer(options.timeoutMs ?? 1e3, 1);\n\t\tif (this.timeout > 3e4 || typeof options.sink?.read !== \"function\" || typeof options.sink?.append !== \"function\" || typeof options.anchor?.load !== \"function\" || typeof options.anchor?.compareAndSet !== \"function\") throw new OrganizationRefused(\"invalid-schema\");\n\t\tthis.sink = Object.freeze({\n\t\t\tread: options.sink.read.bind(options.sink),\n\t\t\tappend: options.sink.append.bind(options.sink)\n\t\t});\n\t\tthis.anchor = Object.freeze({\n\t\t\tload: options.anchor.load.bind(options.anchor),\n\t\t\tcompareAndSet: options.anchor.compareAndSet.bind(options.anchor)\n\t\t});\n\t}\n\tasync bounded(work, signal) {\n\t\tconst controller = new AbortController();\n\t\tconst abort = () => controller.abort();\n\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\tif (signal?.aborted) controller.abort();\n\t\tlet rejectAbort;\n\t\tconst stopped = new Promise((_, reject) => {\n\t\t\trejectAbort = () => reject(new OrganizationRefused(\"policy-unavailable\"));\n\t\t\tcontroller.signal.addEventListener(\"abort\", rejectAbort, { once: true });\n\t\t\tif (controller.signal.aborted) rejectAbort();\n\t\t});\n\t\tconst timer = setTimeout(abort, this.timeout);\n\t\ttry {\n\t\t\treturn await Promise.race([Promise.resolve().then(() => {\n\t\t\t\tactive(controller.signal);\n\t\t\t\treturn work(controller.signal);\n\t\t\t}), stopped]);\n\t\t} catch {\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\tcontroller.signal.removeEventListener(\"abort\", rejectAbort);\n\t\t\tcontroller.abort();\n\t\t}\n\t}\n\tasync record(value, signal) {\n\t\tconst projected = event(value);\n\t\tawait this.bounded(async (lifetime) => {\n\t\t\tlet delay = 5;\n\t\t\tfor (;;) {\n\t\t\t\tactive(lifetime);\n\t\t\t\tconst anchored = checkpoint(await this.anchor.load(lifetime), this.stream, this.key);\n\t\t\t\tactive(lifetime);\n\t\t\t\tconst current = page(await this.sink.read(anchored.claims, lifetime), anchored.claims, this.key);\n\t\t\t\tactive(lifetime);\n\t\t\t\tif (!same(current.claims, anchored.claims)) {\n\t\t\t\t\tawait pause(delay, lifetime);\n\t\t\t\t\tdelay = Math.min(delay * 2, 50);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlet response;\n\t\t\t\ttry {\n\t\t\t\t\tresponse = record(await this.sink.append(anchored.claims, projected, lifetime), [\"entry\", \"head\"]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tactive(lifetime);\n\t\t\t\t\tif (!(error instanceof OrganizationAuditAppendConflict)) throw error;\n\t\t\t\t\tawait pause(delay, lifetime);\n\t\t\t\t\tdelay = Math.min(delay * 2, 50);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tactive(lifetime);\n\t\t\t\tconst written = entry(response.entry, anchored.claims);\n\t\t\t\tconst next = checkpoint(response.head, this.stream, this.key);\n\t\t\t\tif (organizationCanonical(written.event) !== organizationCanonical(projected) || !same(next.claims, {\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tstream: written.stream,\n\t\t\t\t\tsequence: written.sequence,\n\t\t\t\t\thash: written.hash\n\t\t\t\t})) throw new OrganizationRefused(\"invalid-proof\");\n\t\t\t\tconst confirmed = await this.anchor.compareAndSet(anchored.claims, next, lifetime);\n\t\t\t\tactive(lifetime);\n\t\t\t\tif (confirmed !== true) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}, signal);\n\t}\n\t/** Owner-only recovery of a valid already-written tail. Does not reset history, refund or retry any effect. */\n\tasync recover(signal) {\n\t\treturn this.bounded(async (lifetime) => {\n\t\t\tconst anchored = checkpoint(await this.anchor.load(lifetime), this.stream, this.key);\n\t\t\tactive(lifetime);\n\t\t\tconst current = page(await this.sink.read(anchored.claims, lifetime), anchored.claims, this.key);\n\t\t\tactive(lifetime);\n\t\t\tif (same(current.claims, anchored.claims)) return current.claims;\n\t\t\tconst confirmed = await this.anchor.compareAndSet(anchored.claims, current, lifetime);\n\t\t\tactive(lifetime);\n\t\t\tif (confirmed !== true) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\treturn current.claims;\n\t\t}, signal);\n\t}\n\t/** Readiness verifies retained evidence without adopting an unconfirmed tail or resetting history. */\n\tasync verify(signal) {\n\t\treturn this.bounded(async (lifetime) => {\n\t\t\tlet delay = 5;\n\t\t\tfor (;;) {\n\t\t\t\tconst anchored = checkpoint(await this.anchor.load(lifetime), this.stream, this.key);\n\t\t\t\tactive(lifetime);\n\t\t\t\tconst current = page(await this.sink.read(anchored.claims, lifetime), anchored.claims, this.key);\n\t\t\t\tactive(lifetime);\n\t\t\t\tif (same(current.claims, anchored.claims)) return anchored.claims;\n\t\t\t\tawait pause(delay, lifetime);\n\t\t\t\tdelay = Math.min(delay * 2, 50);\n\t\t\t}\n\t\t}, signal);\n\t}\n};\n//#endregion\n//#region src/git-asset.ts\nfunction gitOid(value) {\n\tif (typeof value !== \"string\" || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value) || /^0+$/.test(value)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn value;\n}\nfunction gitParameters(value) {\n\tconst params = record(value, [\n\t\t\"expectedRevision\",\n\t\t\"fence\",\n\t\t\"expectedOid\",\n\t\t\"candidateOid\"\n\t]);\n\treturn {\n\t\texpectedRevision: integer(params.expectedRevision),\n\t\tfence: integer(params.fence, 1),\n\t\texpectedOid: gitOid(params.expectedOid),\n\t\tcandidateOid: gitOid(params.candidateOid)\n\t};\n}\n/** Trusted asset-owner plumbing only. This class never clones/fetches, checks out, merges or runs user code. */\nvar OrganizationGitAsset = class {\n\tidentity;\n\tphaseTimeoutMs;\n\tpath;\n\tino;\n\tdev;\n\tref;\n\tgitPath;\n\tconstructor(options) {\n\t\tif (!isAbsolute(options.path) || !isAbsolute(options.gitPath) || !/^refs\\/heads\\/[a-zA-Z0-9][a-zA-Z0-9/_-]{0,120}$/.test(options.ref) || options.ref.endsWith(\"/\") || options.ref.includes(\"//\")) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthis.path = realpathSync(options.path);\n\t\tconst root = lstatSync(this.path);\n\t\tthis.ino = root.ino;\n\t\tthis.dev = root.dev;\n\t\tthis.ref = options.ref;\n\t\tthis.gitPath = realpathSync(options.gitPath);\n\t\tthis.phaseTimeoutMs = integer(options.phaseTimeoutMs ?? 1e3, 1);\n\t\tif (this.phaseTimeoutMs > 1e3) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthis.identity = createHash(\"sha256\").update(organizationCanonical([\n\t\t\tthis.path,\n\t\t\tthis.dev,\n\t\t\tthis.ino,\n\t\t\tthis.ref\n\t\t])).digest(\"hex\");\n\t\tthis.phase((run) => {\n\t\t\tif (run([\"rev-parse\", \"--is-bare-repository\"]) !== \"true\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\tthis.tip(run);\n\t\t});\n\t}\n\tverify() {\n\t\ttry {\n\t\t\tconst root = lstatSync(this.path);\n\t\t\tconst uid = process.getuid?.();\n\t\t\tif (!root.isDirectory() || root.ino !== this.ino || root.dev !== this.dev || (root.mode & 63) !== 0 || uid !== void 0 && uid !== root.uid) throw new Error(\"changed asset\");\n\t\t} catch {\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t}\n\t}\n\tphase(action) {\n\t\tconst start = performance.now();\n\t\tconst run = (args, input) => {\n\t\t\tthis.verify();\n\t\t\tconst remaining = this.phaseTimeoutMs - Math.ceil(performance.now() - start);\n\t\t\tif (remaining <= 0) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\ttry {\n\t\t\t\treturn execFileSync(this.gitPath, [\n\t\t\t\t\t\"--git-dir\",\n\t\t\t\t\tthis.path,\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"core.hooksPath=/dev/null\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"core.fsmonitor=false\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"gc.auto=0\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"commit.gpgSign=false\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"core.commitGraph=false\",\n\t\t\t\t\t...args\n\t\t\t\t], {\n\t\t\t\t\tinput,\n\t\t\t\t\tencoding: \"utf8\",\n\t\t\t\t\ttimeout: remaining,\n\t\t\t\t\tkillSignal: \"SIGKILL\",\n\t\t\t\t\tmaxBuffer: 64 * 1024,\n\t\t\t\t\tstdio: [\n\t\t\t\t\t\t\"pipe\",\n\t\t\t\t\t\t\"pipe\",\n\t\t\t\t\t\t\"pipe\"\n\t\t\t\t\t],\n\t\t\t\t\tenv: {\n\t\t\t\t\t\tGIT_CONFIG_NOSYSTEM: \"1\",\n\t\t\t\t\t\tGIT_CONFIG_GLOBAL: \"/dev/null\",\n\t\t\t\t\t\tGIT_NO_REPLACE_OBJECTS: \"1\",\n\t\t\t\t\t\tGIT_GRAFT_FILE: \"/dev/null\",\n\t\t\t\t\t\tGIT_TERMINAL_PROMPT: \"0\",\n\t\t\t\t\t\tGIT_ATTR_NOSYSTEM: \"1\",\n\t\t\t\t\t\tGIT_AUTHOR_NAME: \"Organization publication\",\n\t\t\t\t\t\tGIT_AUTHOR_EMAIL: \"broker@example.invalid\",\n\t\t\t\t\t\tGIT_COMMITTER_NAME: \"Organization publication\",\n\t\t\t\t\t\tGIT_COMMITTER_EMAIL: \"broker@example.invalid\",\n\t\t\t\t\t\tGIT_AUTHOR_DATE: \"2000-01-01T00:00:00Z\",\n\t\t\t\t\t\tGIT_COMMITTER_DATE: \"2000-01-01T00:00:00Z\"\n\t\t\t\t\t}\n\t\t\t\t}).trim();\n\t\t\t} catch (error) {\n\t\t\t\tif (args[0] === \"merge-base\" && typeof error === \"object\" && error !== null && \"status\" in error && error.status === 1) return \"\";\n\t\t\t\tthrow new OrganizationRefused(\"outcome-unknown\");\n\t\t\t}\n\t\t};\n\t\treturn action(run);\n\t}\n\ttip(run) {\n\t\tif (run([\n\t\t\t\"for-each-ref\",\n\t\t\t\"--format=%(symref)\",\n\t\t\tthis.ref\n\t\t]) !== \"\") throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn gitOid(run([\n\t\t\t\"show-ref\",\n\t\t\t\"--verify\",\n\t\t\t\"--hash\",\n\t\t\tthis.ref\n\t\t]));\n\t}\n\tprepare(digest, parameters) {\n\t\tif (!/^[a-f0-9]{64}$/.test(digest)) throw new OrganizationRefused(\"invalid-schema\");\n\t\tconst params = gitParameters(parameters);\n\t\treturn this.phase((run) => {\n\t\t\tif (this.tip(run) !== params.expectedOid || params.expectedOid === params.candidateOid) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tif (run([\n\t\t\t\t\"cat-file\",\n\t\t\t\t\"-t\",\n\t\t\t\tparams.candidateOid\n\t\t\t]) !== \"commit\") throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tif (run([\n\t\t\t\t\"merge-base\",\n\t\t\t\tparams.expectedOid,\n\t\t\t\tparams.candidateOid\n\t\t\t]) !== params.expectedOid) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tconst tree = gitOid(run([\n\t\t\t\t\"rev-parse\",\n\t\t\t\t\"--verify\",\n\t\t\t\t`${params.candidateOid}^{tree}`\n\t\t\t]));\n\t\t\tconst message = organizationCanonical({\n\t\t\t\tdomain: \"organization-git-publication-v1\",\n\t\t\t\tasset: this.identity,\n\t\t\t\tdigest,\n\t\t\t\t...params,\n\t\t\t\tnonce: randomUUID()\n\t\t\t});\n\t\t\tconst publishedOid = gitOid(run([\n\t\t\t\t\"commit-tree\",\n\t\t\t\t\"--no-gpg-sign\",\n\t\t\t\ttree,\n\t\t\t\t\"-p\",\n\t\t\t\tparams.candidateOid\n\t\t\t], `${message}\\n`));\n\t\t\treturn Object.freeze({\n\t\t\t\tasset: this.identity,\n\t\t\t\tdigest,\n\t\t\t\t...params,\n\t\t\t\tpublishedOid\n\t\t\t});\n\t\t});\n\t}\n\tpublish(intent) {\n\t\tif (intent.asset !== this.identity) throw new OrganizationRefused(\"operation-conflict\");\n\t\tconst expected = gitOid(intent.expectedOid);\n\t\tconst published = gitOid(intent.publishedOid);\n\t\tthis.phase((run) => {\n\t\t\tif (this.tip(run) !== expected) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\trun([\n\t\t\t\t\"update-ref\",\n\t\t\t\t\"--no-deref\",\n\t\t\t\tthis.ref,\n\t\t\t\tpublished,\n\t\t\t\texpected\n\t\t\t]);\n\t\t});\n\t}\n\twasPublished(intent) {\n\t\tif (intent.asset !== this.identity) throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn this.phase((run) => {\n\t\t\tconst tip = this.tip(run);\n\t\t\treturn run([\n\t\t\t\t\"merge-base\",\n\t\t\t\tgitOid(intent.publishedOid),\n\t\t\t\ttip\n\t\t\t]) === intent.publishedOid;\n\t\t});\n\t}\n};\n//#endregion\n//#region src/no-effect.ts\nconst NO_EFFECT_REASONS = [\n\t\"budget-exhausted\",\n\t\"not-authorized\",\n\t\"invalid-schema\",\n\t\"expired\",\n\t\"revoked\",\n\t\"operation-conflict\",\n\t\"operation-pending\"\n];\nfunction noEffectReason(value) {\n\tif (typeof value !== \"string\" || !NO_EFFECT_REASONS.includes(value)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn value;\n}\n/** Trusted asset-owner evidence of a confirmed transaction rollback, never an unverified provider error. */\nvar OrganizationNoEffect = class extends OrganizationRefused {\n\tusage;\n\tconstructor(reason, usage) {\n\t\tsuper(noEffectReason(reason));\n\t\tthis.usage = units(usage);\n\t}\n};\n//#endregion\n//#region src/state-actions.ts\nfunction transactional(action) {\n\ttry {\n\t\treturn action();\n\t} catch (error) {\n\t\tif (error instanceof OrganizationRefused && [\n\t\t\t\"not-authorized\",\n\t\t\t\"invalid-schema\",\n\t\t\t\"expired\",\n\t\t\t\"revoked\",\n\t\t\t\"operation-conflict\",\n\t\t\t\"operation-pending\"\n\t\t].includes(error.reason)) throw new OrganizationNoEffect(error.reason, {\n\t\t\ttokens: 0,\n\t\t\ttimeMs: 0,\n\t\t\tcostMicros: 0\n\t\t});\n\t\tthrow error;\n\t}\n}\n/** Owner-installed task state actions. Workers cannot choose roles, budget or approval policy. */\nfunction createOrganizationStateActions(ledger, options) {\n\tconst resource = identifier(options.resource);\n\tconst readRoles = Object.freeze(options.readRoles.map(identifier));\n\tconst writeRoles = Object.freeze(options.writeRoles.map(identifier));\n\tconst reservation = units(options.reservation);\n\tif (readRoles.length === 0 || writeRoles.length === 0 || new Set(readRoles).size !== readRoles.length || new Set(writeRoles).size !== writeRoles.length || typeof options.writeRequiresApproval !== \"boolean\") throw new OrganizationRefused(\"invalid-schema\");\n\tconst common = {\n\t\tresource,\n\t\treserve: () => reservation\n\t};\n\treturn Object.freeze([\n\t\tObject.freeze({\n\t\t\t...common,\n\t\t\toperation: \"state.read\",\n\t\t\troles: readRoles,\n\t\t\trequiresApproval: false,\n\t\t\treserve: (operation) => {\n\t\t\t\trecord(operation.parameters, []);\n\t\t\t\treturn reservation;\n\t\t\t},\n\t\t\texecute: async (_, context) => {\n\t\t\t\tconst result = transactional(() => ledger.readState(context.proof));\n\t\t\t\treturn {\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\trevision: result.revision,\n\t\t\t\t\t\tvalue: result.value\n\t\t\t\t\t},\n\t\t\t\t\tusage: {\n\t\t\t\t\t\ttokens: 0,\n\t\t\t\t\t\ttimeMs: 0,\n\t\t\t\t\t\tcostMicros: 0\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t}),\n\t\tObject.freeze({\n\t\t\t...common,\n\t\t\toperation: \"state.lease\",\n\t\t\troles: writeRoles,\n\t\t\trequiresApproval: false,\n\t\t\treserve: (operation) => {\n\t\t\t\tconst parameters = record(operation.parameters, [\"expectedRevision\", \"ttlMs\"]);\n\t\t\t\tinteger(parameters.expectedRevision);\n\t\t\t\tinteger(parameters.ttlMs, 1);\n\t\t\t\tif (Number(parameters.ttlMs) > 3e4) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\t\treturn reservation;\n\t\t\t},\n\t\t\texecute: async (_, context) => {\n\t\t\t\tconst result = transactional(() => ledger.leaseState(context.proof));\n\t\t\t\treturn {\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\trevision: result.revision,\n\t\t\t\t\t\tfence: result.fence,\n\t\t\t\t\t\texpiresAt: result.expiresAt\n\t\t\t\t\t},\n\t\t\t\t\tusage: {\n\t\t\t\t\t\ttokens: 0,\n\t\t\t\t\t\ttimeMs: 0,\n\t\t\t\t\t\tcostMicros: 0\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t}),\n\t\tObject.freeze({\n\t\t\t...common,\n\t\t\toperation: \"state.write\",\n\t\t\troles: writeRoles,\n\t\t\trequiresApproval: options.writeRequiresApproval,\n\t\t\treserve: (operation) => {\n\t\t\t\tconst parameters = record(operation.parameters, [\n\t\t\t\t\t\"expectedRevision\",\n\t\t\t\t\t\"fence\",\n\t\t\t\t\t\"value\"\n\t\t\t\t]);\n\t\t\t\tinteger(parameters.expectedRevision);\n\t\t\t\tinteger(parameters.fence, 1);\n\t\t\t\torganizationCanonical(parameters.value);\n\t\t\t\treturn reservation;\n\t\t\t},\n\t\t\texecute: async (_, context) => {\n\t\t\t\tconst result = transactional(() => ledger.writeState(context.proof));\n\t\t\t\treturn {\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\trevision: result.revision,\n\t\t\t\t\t\tvalue: result.value\n\t\t\t\t\t},\n\t\t\t\t\tusage: {\n\t\t\t\t\t\ttokens: 0,\n\t\t\t\t\t\ttimeMs: 0,\n\t\t\t\t\t\tcostMicros: 0\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t})\n\t]);\n}\n//#endregion\n//#region src/git-actions.ts\n/** Owner-pinned Git asset. Publication always requires separate exact operator approval. */\nfunction createOrganizationGitActions(ledger, options) {\n\tconst states = createOrganizationStateActions(ledger, {\n\t\t...options,\n\t\twriteRequiresApproval: true\n\t});\n\tconst asset = options.asset;\n\tif (options.reservation.timeMs < asset.phaseTimeoutMs * 3) throw new OrganizationRefused(\"invalid-schema\");\n\tconst lease = states[1];\n\tconst reservation = units(options.reservation);\n\tconst publish = Object.freeze({\n\t\tresource: lease.resource,\n\t\toperation: \"git.publish\",\n\t\troles: lease.roles,\n\t\trequiresApproval: true,\n\t\treserve: (operation) => {\n\t\t\tgitParameters(operation.parameters);\n\t\t\treturn reservation;\n\t\t},\n\t\texecute: async (_, context) => {\n\t\t\ttry {\n\t\t\t\tledger.prepareGitPublication(context.proof, asset);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof OrganizationRefused && [\n\t\t\t\t\t\"not-authorized\",\n\t\t\t\t\t\"invalid-schema\",\n\t\t\t\t\t\"expired\",\n\t\t\t\t\t\"revoked\",\n\t\t\t\t\t\"operation-conflict\",\n\t\t\t\t\t\"operation-pending\"\n\t\t\t\t].includes(error.reason)) throw new OrganizationNoEffect(error.reason, {\n\t\t\t\t\ttokens: 0,\n\t\t\t\t\ttimeMs: 0,\n\t\t\t\t\tcostMicros: 0\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst result = ledger.commitGitPublication(context.proof, asset);\n\t\t\treturn {\n\t\t\t\tvalue: {\n\t\t\t\t\trevision: result.revision,\n\t\t\t\t\tvalue: result.value\n\t\t\t\t},\n\t\t\t\tusage: {\n\t\t\t\t\ttokens: 0,\n\t\t\t\t\ttimeMs: 0,\n\t\t\t\t\tcostMicros: 0\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n\treturn Object.freeze([\n\t\tstates[0],\n\t\tlease,\n\t\tpublish\n\t]);\n}\n//#endregion\n//#region src/broker.ts\nfunction snapshotCall(value) {\n\tconst data = record(value, [\"request\", \"approval\"]);\n\tconst request = record(data.request, [\"claims\", \"signature\"]);\n\tconst approval = data.approval === null ? null : record(data.approval, [\"claims\", \"signature\"]);\n\tif (typeof request.signature !== \"string\" || approval !== null && typeof approval.signature !== \"string\") throw new OrganizationRefused(\"invalid-proof\");\n\treturn Object.freeze({\n\t\trequest: Object.freeze({\n\t\t\tclaims: requestClaims(request.claims),\n\t\t\tsignature: request.signature\n\t\t}),\n\t\tapproval: approval === null ? null : Object.freeze({\n\t\t\tclaims: approvalClaims(approval.claims),\n\t\t\tsignature: approval.signature\n\t\t})\n\t});\n}\n/** Worker requests can use only the action table installed by the broker owner. */\nvar OrganizationBroker = class {\n\taudience;\n\tledger;\n\tactions = /* @__PURE__ */ new Map();\n\tinterval;\n\tnow;\n\tactive = /* @__PURE__ */ new Set();\n\taudit;\n\tauditReadiness;\n\tclosed = false;\n\tconstructor(options) {\n\t\tthis.ledger = options.ledger;\n\t\tif (options.hosted === true) {\n\t\t\tthis.ledger.verifyAnchoredAuthority();\n\t\t\tif (!(options.audit instanceof OrganizationAudit)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\tthis.auditReadiness = options.audit.verify.bind(options.audit);\n\t\t}\n\t\tif (options.audit !== void 0) {\n\t\t\tif (typeof options.audit?.record !== \"function\") throw new OrganizationRefused(\"invalid-schema\");\n\t\t\tthis.audit = Object.freeze({ record: options.audit.record.bind(options.audit) });\n\t\t}\n\t\tthis.audience = options.ledger.audience;\n\t\tthis.interval = integer(options.policyIntervalMs ?? 100, 1);\n\t\tif (this.interval > 1e3) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthis.now = options.now ?? Date.now;\n\t\tfor (const action of options.actions) {\n\t\t\tconst resource = identifier(action.resource);\n\t\t\tconst operation = identifier(action.operation);\n\t\t\tconst roles = action.roles.map(identifier);\n\t\t\tif (roles.length === 0 || new Set(roles).size !== roles.length || typeof action.requiresApproval !== \"boolean\" || typeof action.reserve !== \"function\" || typeof action.execute !== \"function\") throw new OrganizationRefused(\"invalid-schema\");\n\t\t\tconst key = organizationCanonical([resource, operation]);\n\t\t\tif (this.actions.has(key)) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\tthis.actions.set(key, Object.freeze({\n\t\t\t\tresource,\n\t\t\t\toperation,\n\t\t\t\troles: Object.freeze(roles),\n\t\t\t\trequiresApproval: action.requiresApproval,\n\t\t\t\treserve: action.reserve.bind(action),\n\t\t\t\texecute: action.execute.bind(action)\n\t\t\t}));\n\t\t}\n\t}\n\tasync apply(value, signal) {\n\t\tif (this.closed) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tif (signal?.aborted) throw new OrganizationRefused(\"not-authorized\");\n\t\tawait this.auditReadiness?.(signal);\n\t\tif (this.closed || signal?.aborted) throw new OrganizationRefused(\"not-authorized\");\n\t\tconst call = snapshotCall(value);\n\t\tconst { request, grant } = this.ledger.authenticate(call.request);\n\t\tconst action = this.actions.get(organizationCanonical([request.operation.resource, request.operation.operation]));\n\t\tif (action === void 0 || !action.roles.includes(grant.role)) throw new OrganizationRefused(\"not-authorized\");\n\t\tconst reservation = units(action.reserve(request.operation));\n\t\tinteger(reservation.timeMs, 1);\n\t\tif (reservation.timeMs > 2147483647) throw new OrganizationRefused(\"invalid-schema\");\n\t\tconst result = this.ledger.reserve(call.request, reservation, call.approval, action.requiresApproval);\n\t\tif (result.kind === \"complete\") return result.receipt;\n\t\tif (result.kind === \"refused\") throw new OrganizationRefused(result.reason);\n\t\treturn this.execute(call.request, action, result, signal);\n\t}\n\tasync auditRecord(request, phase, signal) {\n\t\tif (this.audit === void 0) return;\n\t\tlet stopped;\n\t\tconst aborted = new Promise((_, reject) => {\n\t\t\tstopped = () => reject(new OrganizationRefused(\"outcome-unknown\"));\n\t\t\tsignal.addEventListener(\"abort\", stopped, { once: true });\n\t\t\tif (signal.aborted) stopped();\n\t\t});\n\t\ttry {\n\t\t\tawait Promise.race([Promise.resolve().then(() => {\n\t\t\t\tif (signal.aborted) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\t\treturn this.audit.record(organizationAuditEvent(request, phase), signal);\n\t\t\t}), aborted]);\n\t\t\tif (signal.aborted) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t} finally {\n\t\t\tsignal.removeEventListener(\"abort\", stopped);\n\t\t}\n\t}\n\tasync execute(envelope, action, reserved, signal) {\n\t\tconst request = envelope.claims;\n\t\tconst controller = new AbortController();\n\t\tthis.active.add(controller);\n\t\tconst abort = () => controller.abort();\n\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\tif (signal?.aborted || this.closed) controller.abort();\n\t\tconst remaining = Math.min(reserved.reservation.timeMs, request.expiresAt - this.now(), reserved.grant.expiresAt - this.now());\n\t\tconst deadline = setTimeout(abort, Math.max(0, remaining));\n\t\tconst policy = setInterval(() => {\n\t\t\ttry {\n\t\t\t\tthis.ledger.authenticate(envelope);\n\t\t\t} catch {\n\t\t\t\tcontroller.abort();\n\t\t\t}\n\t\t}, this.interval);\n\t\tconst start = performance.now();\n\t\tlet abortedListener;\n\t\ttry {\n\t\t\tconst aborted = new Promise((_, reject) => {\n\t\t\t\tabortedListener = () => reject(new OrganizationRefused(\"outcome-unknown\"));\n\t\t\t\tcontroller.signal.addEventListener(\"abort\", abortedListener, { once: true });\n\t\t\t\tif (controller.signal.aborted) abortedListener();\n\t\t\t});\n\t\t\tconst effect = Promise.resolve().then(async () => {\n\t\t\t\tif (controller.signal.aborted) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\t\tthis.ledger.authenticate(envelope);\n\t\t\t\tawait this.auditRecord(request, \"dispatch\", controller.signal);\n\t\t\t\tif (controller.signal.aborted || performance.now() - start > remaining) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\t\tthis.ledger.authenticate(envelope);\n\t\t\t\treturn action.execute(request.operation, {\n\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t\tproof: envelope,\n\t\t\t\t\toperationDigest: reserved.digest,\n\t\t\t\t\tidentity: reserved.grant,\n\t\t\t\t\treservation: reserved.reservation\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst returned = receipt(await Promise.race([effect, aborted]));\n\t\t\tthis.ledger.authenticate(envelope);\n\t\t\tif (controller.signal.aborted || performance.now() - start > remaining) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tawait this.auditRecord(request, \"complete\", controller.signal);\n\t\t\tthis.ledger.authenticate(envelope);\n\t\t\tif (controller.signal.aborted || performance.now() - start > remaining) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tconst completed = receipt({\n\t\t\t\tvalue: returned.value,\n\t\t\t\tusage: {\n\t\t\t\t\t...returned.usage,\n\t\t\t\t\ttimeMs: Math.max(returned.usage.timeMs, Math.ceil(performance.now() - start))\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis.ledger.settle(request, completed);\n\t\t\treturn completed;\n\t\t} catch (error) {\n\t\t\tif (error instanceof OrganizationNoEffect && !controller.signal.aborted && performance.now() - start <= remaining) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.auditRecord(request, \"refused\", controller.signal);\n\t\t\t\t\tif (controller.signal.aborted || performance.now() - start > remaining) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\t\t\tthis.ledger.confirmNoEffect(request, noEffectReason(error.reason), {\n\t\t\t\t\t\t...error.usage,\n\t\t\t\t\t\ttimeMs: Math.max(error.usage.timeMs, Math.ceil(performance.now() - start))\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.ledger.markUnknown(request);\n\t\t\t\t\t} catch {}\n\t\t\t\t\tthrow new OrganizationRefused(\"outcome-unknown\");\n\t\t\t\t}\n\t\t\t\tthrow new OrganizationRefused(error.reason);\n\t\t\t}\n\t\t\tcontroller.abort();\n\t\t\ttry {\n\t\t\t\tthis.ledger.markUnknown(request);\n\t\t\t} catch {}\n\t\t\ttry {\n\t\t\t\tawait this.auditRecord(request, \"unknown\", AbortSignal.timeout(1e3));\n\t\t\t} catch {}\n\t\t\tthrow new OrganizationRefused(\"outcome-unknown\");\n\t\t} finally {\n\t\t\tclearTimeout(deadline);\n\t\t\tclearInterval(policy);\n\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\tif (abortedListener !== void 0) controller.signal.removeEventListener(\"abort\", abortedListener);\n\t\t\tthis.active.delete(controller);\n\t\t}\n\t}\n\t/** Host shutdown: withdraw admission and signal outstanding trusted effects. */\n\tclose() {\n\t\tthis.closed = true;\n\t\tfor (const controller of this.active) controller.abort();\n\t}\n};\n//#endregion\n//#region src/shared-state.ts\n/** Internal SQLite owner: every call is made inside the ledger's authenticated operation transaction. */\nvar OrganizationSharedStateSql = class {\n\tdb;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tinitialize() {\n\t\tthis.db.exec(`CREATE TABLE shared_state (\n key TEXT PRIMARY KEY, value TEXT NOT NULL, revision INTEGER NOT NULL, fence INTEGER NOT NULL,\n holder TEXT, epoch INTEGER NOT NULL, expiresAt INTEGER NOT NULL\n ) STRICT;\n CREATE TABLE state_effects (digest TEXT PRIMARY KEY, grantId TEXT NOT NULL, value TEXT NOT NULL) STRICT;`);\n\t}\n\tkey(tenant, task, resource) {\n\t\treturn organizationCanonical([\n\t\t\tidentifier(tenant),\n\t\t\tidentifier(task),\n\t\t\tidentifier(resource)\n\t\t]);\n\t}\n\tcreate(tenant, task, resource, value) {\n\t\tconst key = this.key(tenant, task, resource);\n\t\tif (this.db.prepare(\"SELECT key FROM shared_state WHERE key=?\").get(key)) throw new OrganizationRefused(\"operation-conflict\");\n\t\tthis.db.prepare(\"INSERT INTO shared_state VALUES (?,?,0,0,NULL,0,0)\").run(key, organizationCanonical(value));\n\t}\n\trow(request) {\n\t\tconst key = this.key(request.tenant, request.task, request.operation.resource);\n\t\tconst row = this.db.prepare(\"SELECT * FROM shared_state WHERE key=?\").get(key);\n\t\tif (row === void 0) throw new OrganizationRefused(\"not-authorized\");\n\t\tif (typeof row.value !== \"string\" || row.holder !== null && typeof row.holder !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\tconst value = JSON.parse(row.value);\n\t\torganizationCanonical(value);\n\t\treturn {\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\trevision: integer(row.revision),\n\t\t\tfence: integer(row.fence),\n\t\t\tholder: row.holder,\n\t\t\tepoch: integer(row.epoch),\n\t\t\texpiresAt: integer(row.expiresAt)\n\t\t};\n\t}\n\tlease(request, grant, now) {\n\t\tif (request.operation.operation !== \"state.lease\") throw new OrganizationRefused(\"not-authorized\");\n\t\tconst parameters = record(request.operation.parameters, [\"expectedRevision\", \"ttlMs\"]);\n\t\tconst revision = integer(parameters.expectedRevision);\n\t\tconst ttl = integer(parameters.ttlMs, 1);\n\t\tif (ttl > 3e4) throw new OrganizationRefused(\"invalid-schema\");\n\t\tconst expiresAt = integer(now + ttl, 1);\n\t\tif (expiresAt > request.expiresAt || expiresAt > grant.expiresAt) throw new OrganizationRefused(\"expired\");\n\t\tconst row = this.row(request);\n\t\tif (revision !== row.revision) throw new OrganizationRefused(\"operation-conflict\");\n\t\tif (row.holder !== null && row.epoch === grant.epoch && row.expiresAt > now) throw new OrganizationRefused(\"operation-pending\");\n\t\tconst fence = integer(row.fence + 1, 1);\n\t\tthis.db.prepare(\"UPDATE shared_state SET fence=?,holder=?,epoch=?,expiresAt=? WHERE key=?\").run(fence, grant.id, grant.epoch, expiresAt, row.key);\n\t\treturn Object.freeze({\n\t\t\trevision,\n\t\t\tfence,\n\t\t\texpiresAt\n\t\t});\n\t}\n\tread(request) {\n\t\tif (request.operation.operation !== \"state.read\") throw new OrganizationRefused(\"not-authorized\");\n\t\trecord(request.operation.parameters, []);\n\t\tconst row = this.row(request);\n\t\treturn Object.freeze({\n\t\t\trevision: row.revision,\n\t\t\tvalue: row.value\n\t\t});\n\t}\n\twrite(request, grant, now) {\n\t\tif (request.operation.operation !== \"state.write\") throw new OrganizationRefused(\"not-authorized\");\n\t\tconst parameters = record(request.operation.parameters, [\n\t\t\t\"expectedRevision\",\n\t\t\t\"fence\",\n\t\t\t\"value\"\n\t\t]);\n\t\tthis.assertFence(request, grant, now, integer(parameters.expectedRevision), integer(parameters.fence, 1));\n\t\treturn this.replace(request, parameters.value);\n\t}\n\tassertFence(request, grant, now, revision, fence) {\n\t\tconst row = this.row(request);\n\t\tif (row.holder !== grant.id || row.epoch !== grant.epoch || row.fence !== fence || row.expiresAt <= now || row.revision !== revision) throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn row.value;\n\t}\n\treplace(request, value) {\n\t\tconst row = this.row(request);\n\t\tconst encoded = organizationCanonical(value);\n\t\tconst revision = integer(row.revision + 1, 1);\n\t\tthis.db.prepare(\"UPDATE shared_state SET value=?,revision=? WHERE key=?\").run(encoded, revision, row.key);\n\t\treturn Object.freeze({\n\t\t\trevision,\n\t\t\tvalue: JSON.parse(encoded)\n\t\t});\n\t}\n\trecoverGit(request, expectedRevision, expectedOid, publishedOid) {\n\t\tconst row = this.row(request);\n\t\tconst value = record(row.value, [\"oid\"]);\n\t\tif (row.revision !== expectedRevision || value.oid !== expectedOid) throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn this.replace(request, { oid: publishedOid });\n\t}\n};\n//#endregion\n//#region src/ledger-anchor.ts\nconst tables = [\n\t[\"metadata\", \"id\"],\n\t[\"budgets\", \"key\"],\n\t[\"grants\", \"id\"],\n\t[\"nonces\", \"tenant,actor,nonce\"],\n\t[\"approvals\", \"id\"],\n\t[\"operations\", \"key\"],\n\t[\"shared_state\", \"key\"],\n\t[\"state_effects\", \"digest\"],\n\t[\"git_intents\", \"digest\"]\n];\n/** Hash typed, length-delimited fields without exposing policy, parameters or receipts to the anchor. */\nfunction digest(db, ledger) {\n\tconst hash = createHash(\"sha256\");\n\tconst field = (value) => {\n\t\tif (typeof value === \"number\" && !Number.isSafeInteger(value)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tconst bytes = Buffer.from(value === null ? \"\" : String(value));\n\t\thash.update(`${value === null ? \"null\" : typeof value}:${bytes.length}:`).update(bytes);\n\t};\n\tfield(\"robota/organization-ledger-anchor/v1\");\n\tfield(ledger);\n\tfor (const [table, order] of tables) {\n\t\tfield(table);\n\t\tconst schema = db.prepare(\"SELECT sql FROM sqlite_schema WHERE type='table' AND name=?\").get(table);\n\t\tif (typeof schema?.sql !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\tfield(schema.sql);\n\t\tconst rows = db.prepare(`SELECT * FROM ${table} ORDER BY ${order}`).all();\n\t\tfield(rows.length);\n\t\tfor (const row of rows) {\n\t\t\tconst keys = Object.keys(row).sort();\n\t\t\tfield(keys.length);\n\t\t\tfor (const key of keys) {\n\t\t\t\tfield(key);\n\t\t\t\tfield(row[key]);\n\t\t\t}\n\t\t}\n\t}\n\treturn hash.digest(\"hex\");\n}\n/** Anchor advances before SQLite commit; uncertain confirmation freezes authority rather than refunds it. */\nvar OrganizationLedgerIntegrity = class {\n\tdb;\n\tledger;\n\tport;\n\tconstructor(db, port) {\n\t\tthis.db = db;\n\t\tthis.ledger = identifier(port.ledger);\n\t\tif (typeof port.read !== \"function\" || typeof port.compareAndSet !== \"function\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.port = Object.freeze({\n\t\t\tledger: this.ledger,\n\t\t\tread: port.read.bind(port),\n\t\t\tcompareAndSet: port.compareAndSet.bind(port)\n\t\t});\n\t}\n\tread() {\n\t\tconst head = this.port.read();\n\t\tif (head === void 0) return void 0;\n\t\tif (head === null || Object.keys(head).sort().join(\",\") !== \"digest,ledger,revision,version\" || head.version !== 1 || head.ledger !== this.ledger || typeof head.digest !== \"string\" || !/^[a-f0-9]{64}$/u.test(head.digest)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\treturn Object.freeze({\n\t\t\tversion: 1,\n\t\t\tledger: this.ledger,\n\t\t\trevision: integer(head.revision, 1),\n\t\t\tdigest: head.digest\n\t\t});\n\t}\n\tinitialize(create) {\n\t\tif (!create) {\n\t\t\tthis.verify();\n\t\t\treturn;\n\t\t}\n\t\tif (this.read() !== void 0) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.commit(void 0, {\n\t\t\tversion: 1,\n\t\t\tledger: this.ledger,\n\t\t\trevision: 1,\n\t\t\tdigest: digest(this.db, this.ledger)\n\t\t});\n\t}\n\tverify() {\n\t\tconst head = this.read();\n\t\tif (head === void 0 || head.digest !== digest(this.db, this.ledger)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\treturn head;\n\t}\n\tadvance(previous) {\n\t\tconst nextDigest = digest(this.db, this.ledger);\n\t\tif (nextDigest === previous.digest) return;\n\t\tthis.commit(previous, {\n\t\t\tversion: 1,\n\t\t\tledger: this.ledger,\n\t\t\trevision: integer(previous.revision + 1, 1),\n\t\t\tdigest: nextDigest\n\t\t});\n\t}\n\tcommit(expected, next) {\n\t\tthis.port.compareAndSet(expected, Object.freeze(next));\n\t\tconst confirmed = this.read();\n\t\tif (confirmed?.revision !== next.revision || confirmed.digest !== next.digest) throw new OrganizationRefused(\"policy-unavailable\");\n\t}\n};\n//#endregion\n//#region src/sqlite-ledger.ts\nconst UNIT_KEYS = [\n\t\"tokens\",\n\t\"timeMs\",\n\t\"costMicros\"\n];\nfunction scopeKey(kind, ...parts) {\n\tconst arity = {\n\t\tglobal: 0,\n\t\ttenant: 1,\n\t\ttask: 2,\n\t\tgrant: 1\n\t}[kind];\n\tif (arity === void 0 || parts.length !== arity) throw new OrganizationRefused(\"invalid-schema\");\n\treturn organizationCanonical([kind, ...parts]);\n}\n/** Durable policy/budgets live in the operator's domain, never in a worker checkpoint. */\nvar OrganizationLedger = class {\n\tdb;\n\tstate;\n\tpath;\n\tinode;\n\tclosed = false;\n\tnow;\n\tworkloadKey;\n\tapprovalKey;\n\tintegrity;\n\taudience;\n\tmaxGrantTtlMs;\n\tmaxRequestTtlMs;\n\tconstructor(options) {\n\t\tif (options.anchor !== void 0 && options.upgrade === true) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.audience = identifier(options.audience);\n\t\tthis.workloadKey = publicKey(options.workloadPublicKey);\n\t\tthis.approvalKey = publicKey(options.approvalPublicKey);\n\t\tif (this.workloadKey.export({\n\t\t\ttype: \"spki\",\n\t\t\tformat: \"der\"\n\t\t}).equals(this.approvalKey.export({\n\t\t\ttype: \"spki\",\n\t\t\tformat: \"der\"\n\t\t}))) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.maxGrantTtlMs = integer(options.maxGrantTtlMs ?? 3e5, 1);\n\t\tthis.maxRequestTtlMs = integer(options.maxRequestTtlMs ?? 3e4, 1);\n\t\tif (!isAbsolute(options.path)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tlet opened;\n\t\ttry {\n\t\t\tconst directory = realpathSync(dirname(options.path));\n\t\t\tconst root = lstatSync(directory);\n\t\t\tconst uid = process.getuid?.();\n\t\t\tif (!root.isDirectory() || (root.mode & 63) !== 0 || uid !== void 0 && root.uid !== uid) throw new Error(\"unowned directory\");\n\t\t\tthis.path = join(directory, basename(options.path));\n\t\t\tif (options.create === true) closeSync(openSync(this.path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 384));\n\t\t\tconst file = lstatSync(this.path);\n\t\t\tif (!file.isFile() || file.nlink !== 1 || (file.mode & 63) !== 0 || uid !== void 0 && file.uid !== uid) throw new Error(\"unowned database\");\n\t\t\tthis.inode = {\n\t\t\t\tino: file.ino,\n\t\t\t\tdev: file.dev\n\t\t\t};\n\t\t\tif (options.create !== true) this.verifyFile();\n\t\t\tconst sqlite = createRequire(import.meta.url)(\"node:sqlite\");\n\t\t\tthis.db = new sqlite.DatabaseSync(this.path, {\n\t\t\t\tallowExtension: false,\n\t\t\t\tenableDoubleQuotedStringLiterals: false\n\t\t\t});\n\t\t\topened = this.db;\n\t\t\tthis.state = new OrganizationSharedStateSql(this.db);\n\t\t\tthis.db.exec(\"PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;\");\n\t\t\tif (options.create === true) {\n\t\t\t\tthis.db.exec(`\n CREATE TABLE metadata (id INTEGER PRIMARY KEY CHECK(id=1), version INTEGER NOT NULL, epoch INTEGER NOT NULL, active INTEGER NOT NULL) STRICT;\n INSERT INTO metadata VALUES (1,3,1,1);\n CREATE TABLE budgets (key TEXT PRIMARY KEY, limits TEXT NOT NULL, spent TEXT NOT NULL, held TEXT NOT NULL, active INTEGER NOT NULL, stopped INTEGER NOT NULL) STRICT;\n CREATE TABLE grants (id TEXT PRIMARY KEY, claims TEXT NOT NULL, revoked INTEGER NOT NULL) STRICT;\n CREATE TABLE nonces (tenant TEXT NOT NULL, actor TEXT NOT NULL, nonce TEXT NOT NULL, PRIMARY KEY(tenant,actor,nonce)) STRICT;\n CREATE TABLE approvals (id TEXT PRIMARY KEY, digest TEXT NOT NULL) STRICT;\n CREATE TABLE operations (key TEXT PRIMARY KEY, digest TEXT NOT NULL, grantId TEXT NOT NULL, status TEXT NOT NULL, scopes TEXT NOT NULL, reservation TEXT NOT NULL, receipt TEXT) STRICT;\n `);\n\t\t\t\tthis.state.initialize();\n\t\t\t\tthis.initializeGit();\n\t\t\t}\n\t\t\tlet metadata = this.db.prepare(\"SELECT version FROM metadata WHERE id=1\").get();\n\t\t\tif ([1, 2].includes(Number(metadata?.version)) && options.upgrade === true) {\n\t\t\t\tthis.db.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\ttry {\n\t\t\t\t\tconst current = this.db.prepare(\"SELECT version FROM metadata WHERE id=1\").get();\n\t\t\t\t\tif (current?.version === 1) this.state.initialize();\n\t\t\t\t\tif (current?.version === 1 || current?.version === 2) {\n\t\t\t\t\t\tthis.initializeGit();\n\t\t\t\t\t\tthis.db.exec(\"UPDATE metadata SET version=3 WHERE id=1\");\n\t\t\t\t\t} else if (current?.version !== 3) throw new Error(\"unsupported database\");\n\t\t\t\t\tthis.db.exec(\"COMMIT\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.db.exec(\"ROLLBACK\");\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tmetadata = this.db.prepare(\"SELECT version FROM metadata WHERE id=1\").get();\n\t\t\t}\n\t\t\tif (metadata?.version !== 3 || this.db.prepare(\"PRAGMA quick_check\").get()?.quick_check !== \"ok\") throw new Error(\"invalid database\");\n\t\t\tthis.db.prepare(\"SELECT key,value,revision,fence,holder,epoch,expiresAt FROM shared_state LIMIT 0\").all();\n\t\t\tthis.db.prepare(\"SELECT digest,grantId,value FROM state_effects LIMIT 0\").all();\n\t\t\tthis.db.prepare(\"SELECT digest,grantId,value FROM git_intents LIMIT 0\").all();\n\t\t\tif (options.anchor !== void 0) {\n\t\t\t\tthis.integrity = new OrganizationLedgerIntegrity(this.db, options.anchor);\n\t\t\t\tthis.db.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\ttry {\n\t\t\t\t\tthis.integrity.initialize(options.create === true);\n\t\t\t\t\tthis.db.exec(\"COMMIT\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.db.exec(\"ROLLBACK\");\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\topened?.close();\n\t\t\t} catch {}\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t}\n\t}\n\tinitializeGit() {\n\t\tthis.db.exec(\"CREATE TABLE git_intents (digest TEXT PRIMARY KEY, grantId TEXT NOT NULL, value TEXT NOT NULL) STRICT;\");\n\t}\n\tverifyFile() {\n\t\tconst descriptor = openSync(this.path, constants.O_RDONLY | constants.O_NOFOLLOW);\n\t\ttry {\n\t\t\tconst file = fstatSync(descriptor);\n\t\t\tconst uid = process.getuid?.();\n\t\t\tconst header = Buffer.alloc(16);\n\t\t\tif (!file.isFile() || file.ino !== this.inode.ino || file.dev !== this.inode.dev || file.nlink !== 1 || (file.mode & 63) !== 0 || uid !== void 0 && file.uid !== uid || readSync(descriptor, header, 0, 16, 0) !== 16 || !header.equals(Buffer.from(\"SQLite format 3\\0\"))) throw new Error(\"changed database\");\n\t\t} finally {\n\t\t\tcloseSync(descriptor);\n\t\t}\n\t}\n\ttransaction(action) {\n\t\tif (this.closed) throw new OrganizationRefused(\"policy-unavailable\");\n\t\ttry {\n\t\t\tthis.verifyFile();\n\t\t\tthis.db.exec(\"BEGIN IMMEDIATE\");\n\t\t\ttry {\n\t\t\t\tconst checkpoint = this.integrity?.verify();\n\t\t\t\tconst result = action();\n\t\t\t\tif (checkpoint !== void 0) this.integrity.advance(checkpoint);\n\t\t\t\tthis.db.exec(\"COMMIT\");\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\tthis.db.exec(\"ROLLBACK\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (error instanceof OrganizationRefused) throw error;\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t}\n\t}\n\tmetadata() {\n\t\tconst row = this.db.prepare(\"SELECT version,epoch,active FROM metadata WHERE id=1\").get();\n\t\tif (row === void 0 || row.version !== 3) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tif (row.active !== 0 && row.active !== 1) throw new OrganizationRefused(\"policy-unavailable\");\n\t\treturn {\n\t\t\tepoch: integer(row.epoch, 1),\n\t\t\tactive: row.active === 1\n\t\t};\n\t}\n\tnewBudget(key, limits) {\n\t\tbudget(limits);\n\t\tif (this.db.prepare(\"SELECT key FROM budgets WHERE key=?\").get(key) !== void 0) throw new OrganizationRefused(\"operation-conflict\");\n\t\tconst zero = organizationCanonical({\n\t\t\ttokens: 0,\n\t\t\ttimeMs: 0,\n\t\t\tcostMicros: 0\n\t\t});\n\t\tthis.db.prepare(\"INSERT INTO budgets VALUES (?,?,?,?,0,0)\").run(key, organizationCanonical(limits), zero, zero);\n\t}\n\t/** Trusted administration only; these methods are not present on the HTTP broker ingress. */\n\tcreateGlobalBudget(limits) {\n\t\tthis.transaction(() => this.newBudget(scopeKey(\"global\"), limits));\n\t}\n\tcreateTenant(tenant, limits) {\n\t\tidentifier(tenant);\n\t\tthis.transaction(() => {\n\t\t\tthis.liveBudget(scopeKey(\"global\"));\n\t\t\tthis.newBudget(scopeKey(\"tenant\", tenant), limits);\n\t\t});\n\t}\n\tcreateTask(tenant, task, limits) {\n\t\tidentifier(tenant);\n\t\tidentifier(task);\n\t\tthis.transaction(() => {\n\t\t\tthis.liveBudget(scopeKey(\"tenant\", tenant));\n\t\t\tthis.newBudget(scopeKey(\"task\", tenant, task), limits);\n\t\t});\n\t}\n\tregisterGrant(envelope) {\n\t\tconst grant = grantClaims(envelope.claims);\n\t\tverifyEnvelope(\"workload\", envelope, this.workloadKey);\n\t\tthis.transaction(() => {\n\t\t\tconst metadata = this.metadata();\n\t\t\tcurrentTime(grant, this.now(), this.maxGrantTtlMs);\n\t\t\tif (!metadata.active || metadata.epoch !== grant.epoch || grant.audience !== this.audience) throw new OrganizationRefused(\"revoked\");\n\t\t\tthis.liveBudget(scopeKey(\"global\"));\n\t\t\tthis.liveBudget(scopeKey(\"tenant\", grant.tenant));\n\t\t\tthis.liveBudget(scopeKey(\"task\", grant.tenant, grant.task));\n\t\t\tif (grant.parent !== null) {\n\t\t\t\tconst parent = this.chain(grant.parent)[0];\n\t\t\t\tif (parent.tenant !== grant.tenant || parent.task !== grant.task || parent.audience !== grant.audience || parent.role !== grant.role || parent.notBefore > grant.notBefore || parent.expiresAt < grant.expiresAt || UNIT_KEYS.some((key) => grant.budget[key] > parent.budget[key]) || grant.budget.concurrency > parent.budget.concurrency || grant.scopes.some((scope) => {\n\t\t\t\t\tconst inherited = parent.scopes.find((candidate) => candidate.resource === scope.resource);\n\t\t\t\t\treturn inherited === void 0 || scope.operations.some((operation) => !inherited.operations.includes(operation));\n\t\t\t\t})) throw new OrganizationRefused(\"not-authorized\");\n\t\t\t}\n\t\t\tif (this.db.prepare(\"SELECT id FROM grants WHERE id=?\").get(grant.id)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tthis.db.prepare(\"INSERT INTO grants VALUES (?,?,0)\").run(grant.id, organizationCanonical(grant));\n\t\t\tthis.newBudget(scopeKey(\"grant\", grant.id), grant.budget);\n\t\t});\n\t}\n\tchain(grantId) {\n\t\tconst metadata = this.metadata();\n\t\tif (!metadata.active) throw new OrganizationRefused(\"revoked\");\n\t\tconst grants = [];\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tlet id = grantId;\n\t\twhile (id !== null) {\n\t\t\tif (seen.has(id) || seen.size >= 32) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\tseen.add(id);\n\t\t\tconst row = this.db.prepare(\"SELECT claims,revoked FROM grants WHERE id=?\").get(id);\n\t\t\tif (row === void 0 || row.revoked !== 0 || typeof row.claims !== \"string\") throw new OrganizationRefused(\"revoked\");\n\t\t\tconst grant = grantClaims(JSON.parse(row.claims));\n\t\t\tcurrentTime(grant, this.now(), this.maxGrantTtlMs);\n\t\t\tif (grant.epoch !== metadata.epoch || grant.audience !== this.audience) throw new OrganizationRefused(\"revoked\");\n\t\t\tthis.liveBudget(scopeKey(\"grant\", grant.id));\n\t\t\tgrants.push(grant);\n\t\t\tid = grant.parent;\n\t\t}\n\t\tconst leaf = grants[0];\n\t\tthis.liveBudget(scopeKey(\"global\"));\n\t\tthis.liveBudget(scopeKey(\"tenant\", leaf.tenant));\n\t\tthis.liveBudget(scopeKey(\"task\", leaf.tenant, leaf.task));\n\t\treturn grants;\n\t}\n\tcurrentGrant(grantId) {\n\t\treturn this.transaction(() => this.chain(identifier(grantId))[0]);\n\t}\n\t/** Owner inventory inspection, including expired/revoked grants; never grants execution authority. */\n\tregisteredGrant(grantId) {\n\t\treturn this.transaction(() => {\n\t\t\tconst row = this.db.prepare(\"SELECT claims FROM grants WHERE id=?\").get(identifier(grantId));\n\t\t\tif (typeof row?.claims !== \"string\") throw new OrganizationRefused(\"not-authorized\");\n\t\t\treturn grantClaims(JSON.parse(row.claims));\n\t\t});\n\t}\n\t/** Trusted supervisory accounting for an owner-installed single-purpose workload grant. */\n\tgrantOperationCount(grantId) {\n\t\treturn this.transaction(() => {\n\t\t\tthis.chain(identifier(grantId));\n\t\t\treturn integer(this.db.prepare(\"SELECT COUNT(*) AS count FROM operations WHERE grantId=?\").get(grantId)?.count);\n\t\t});\n\t}\n\t/** Owner composition can require integrity rather than silently accepting legacy SDK mode. */\n\tverifyAnchoredAuthority() {\n\t\tif (this.integrity === void 0) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.transaction(() => void 0);\n\t}\n\tauthenticateInside(envelope) {\n\t\tconst request = requestClaims(envelope.claims);\n\t\tconst grants = this.chain(request.grantId);\n\t\tconst grant = grants[0];\n\t\tverifyEnvelope(\"request\", envelope, publicKey(grant.publicKey));\n\t\tcurrentTime(request, this.now(), this.maxRequestTtlMs);\n\t\tif (request.notBefore < grant.notBefore || request.expiresAt > grant.expiresAt) throw new OrganizationRefused(\"expired\");\n\t\tif (request.tenant !== grant.tenant || request.task !== grant.task || request.actor !== grant.actor || request.audience !== grant.audience || request.epoch !== grant.epoch || !grant.scopes.some((scope) => scope.resource === request.operation.resource && scope.operations.includes(request.operation.operation))) throw new OrganizationRefused(\"not-authorized\");\n\t\treturn {\n\t\t\trequest,\n\t\t\tgrant,\n\t\t\tgrants\n\t\t};\n\t}\n\tauthenticate(envelope) {\n\t\treturn this.transaction(() => this.authenticateInside(envelope));\n\t}\n\t/** Owner administration only; state creation cannot overwrite an existing resource or its fence. */\n\tcreateStateResource(tenant, task, resource, value) {\n\t\tthis.transaction(() => {\n\t\t\tthis.liveBudget(scopeKey(\"global\"));\n\t\t\tthis.liveBudget(scopeKey(\"tenant\", identifier(tenant)));\n\t\t\tthis.liveBudget(scopeKey(\"task\", tenant, identifier(task)));\n\t\t\tthis.state.create(tenant, task, resource, value);\n\t\t});\n\t}\n\tactiveOperation(envelope) {\n\t\tconst result = this.authenticateInside(envelope);\n\t\tconst operation = this.operation(this.key(result.request));\n\t\tif (operation === void 0 || operation.status !== \"running\" || operation.digest !== organizationOperationDigest(result.request) || operation.grantId !== result.grant.id) throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn result;\n\t}\n\tstateOperation(envelope, action) {\n\t\treturn this.transaction(() => {\n\t\t\tconst { request, grant } = this.activeOperation(envelope);\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (this.db.prepare(\"SELECT digest FROM state_effects WHERE digest=?\").get(digest)) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tconst result = action(request, grant);\n\t\t\tthis.db.prepare(\"INSERT INTO state_effects VALUES (?,?,?)\").run(digest, grant.id, organizationCanonical(result));\n\t\t\treturn result;\n\t\t});\n\t}\n\tleaseState(envelope) {\n\t\treturn this.stateOperation(envelope, (request, grant) => this.state.lease(request, grant, this.now()));\n\t}\n\treadState(envelope) {\n\t\treturn this.stateOperation(envelope, (request) => this.state.read(request));\n\t}\n\twriteState(envelope) {\n\t\treturn this.stateOperation(envelope, (request, grant) => this.state.write(request, grant, this.now()));\n\t}\n\t/** Trusted Git owner only. Persist an unreachable receipt intent before any target ref can change. */\n\tprepareGitPublication(envelope, asset) {\n\t\treturn this.transaction(() => {\n\t\t\tconst { request, grant } = this.activeOperation(envelope);\n\t\t\tif (request.operation.operation !== \"git.publish\") throw new OrganizationRefused(\"not-authorized\");\n\t\t\tconst params = gitParameters(request.operation.parameters);\n\t\t\tif (record(this.state.assertFence(request, grant, this.now(), params.expectedRevision, params.fence), [\"oid\"]).oid !== params.expectedOid) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (this.db.prepare(\"SELECT digest FROM git_intents WHERE digest=?\").get(digest)) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tconst intent = asset.prepare(digest, params);\n\t\t\tthis.db.prepare(\"INSERT INTO git_intents VALUES (?,?,?)\").run(digest, grant.id, organizationCanonical(intent));\n\t\t\treturn intent;\n\t\t});\n\t}\n\tgitIntent(request, asset) {\n\t\tconst digest = organizationOperationDigest(request);\n\t\tconst row = this.db.prepare(\"SELECT grantId,value FROM git_intents WHERE digest=?\").get(digest);\n\t\tif (row === void 0) throw new OrganizationRefused(\"outcome-unknown\");\n\t\tif (row.grantId !== request.grantId || typeof row.value !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\tconst data = record(JSON.parse(row.value), [\n\t\t\t\"asset\",\n\t\t\t\"digest\",\n\t\t\t\"expectedRevision\",\n\t\t\t\"fence\",\n\t\t\t\"expectedOid\",\n\t\t\t\"candidateOid\",\n\t\t\t\"publishedOid\"\n\t\t]);\n\t\tconst params = gitParameters(request.operation.parameters);\n\t\tif (request.operation.operation !== \"git.publish\" || data.digest !== digest || data.asset !== asset.identity || Object.entries(params).some(([key, value]) => data[key] !== value) || typeof data.publishedOid !== \"string\") throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn data;\n\t}\n\t/** SQL locking serializes policy/fence checks with dispatch. External Git and SQL are NOT an atomic store. */\n\tcommitGitPublication(envelope, asset) {\n\t\treturn this.stateOperation(envelope, (request, grant) => {\n\t\t\tconst intent = this.gitIntent(request, asset);\n\t\t\tif (record(this.state.assertFence(request, grant, this.now(), intent.expectedRevision, intent.fence), [\"oid\"]).oid !== intent.expectedOid) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tasset.publish(intent);\n\t\t\treturn this.state.replace(request, { oid: intent.publishedOid });\n\t\t});\n\t}\n\t/** Owner-only proof of a past branch publication. No absent effect is refunded, no workload authority is restored. */\n\treconcileGitPublication(value, asset) {\n\t\tconst request = requestClaims(value);\n\t\tthis.transaction(() => {\n\t\t\tconst operation = this.operation(this.key(request));\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (operation === void 0 || operation.digest !== digest || operation.grantId !== request.grantId || ![\n\t\t\t\t\"running\",\n\t\t\t\t\"unknown\",\n\t\t\t\t\"complete\"\n\t\t\t].includes(operation.status)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tconst intent = this.gitIntent(request, asset);\n\t\t\tif (!asset.wasPublished(intent)) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tif (this.db.prepare(\"SELECT digest FROM state_effects WHERE digest=?\").get(digest) === void 0) {\n\t\t\t\tconst result = this.state.recoverGit(request, intent.expectedRevision, intent.expectedOid, intent.publishedOid);\n\t\t\t\tthis.db.prepare(\"INSERT INTO state_effects VALUES (?,?,?)\").run(digest, request.grantId, organizationCanonical(result));\n\t\t\t}\n\t\t});\n\t\treturn this.reconcileStateOperation(request);\n\t}\n\t/** Trusted asset-owner reconciliation only. The atomic state outcome proves this specific effect; no worker route exposes it. */\n\treconcileStateOperation(value) {\n\t\tconst request = requestClaims(value);\n\t\tconst outcome = this.transaction(() => {\n\t\t\tconst operation = this.operation(this.key(request));\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (operation === void 0 || operation.grantId !== request.grantId || operation.digest !== digest) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tif (operation.status === \"complete\" && operation.receipt !== null) return { complete: operation.receipt };\n\t\t\tif (![\"running\", \"unknown\"].includes(operation.status)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tconst effect = this.db.prepare(\"SELECT grantId,value FROM state_effects WHERE digest=?\").get(digest);\n\t\t\tif (effect === void 0) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tif (effect.grantId !== request.grantId || typeof effect.value !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\treturn { receipt: receipt({\n\t\t\t\tvalue: JSON.parse(effect.value),\n\t\t\t\tusage: operation.reservation\n\t\t\t}) };\n\t\t});\n\t\tif (outcome.complete !== void 0) return outcome.complete;\n\t\tthis.recordReceipt(request, outcome.receipt, \"complete\", true);\n\t\treturn outcome.receipt;\n\t}\n\tliveBudget(key) {\n\t\tconst state = this.storedBudget(key);\n\t\tif (state.stopped) throw new OrganizationRefused(\"revoked\");\n\t\treturn state;\n\t}\n\tstoredBudget(key) {\n\t\tconst row = this.db.prepare(\"SELECT * FROM budgets WHERE key=?\").get(key);\n\t\tif (row === void 0 || row.stopped !== 0 && row.stopped !== 1 || typeof row.limits !== \"string\" || typeof row.spent !== \"string\" || typeof row.held !== \"string\") throw new OrganizationRefused(\"revoked\");\n\t\treturn {\n\t\t\tlimits: budget(JSON.parse(row.limits)),\n\t\t\tspent: units(JSON.parse(row.spent)),\n\t\t\theld: units(JSON.parse(row.held)),\n\t\t\tactive: integer(row.active),\n\t\t\tstopped: row.stopped === 1\n\t\t};\n\t}\n\toperation(key) {\n\t\tconst row = this.db.prepare(\"SELECT * FROM operations WHERE key=?\").get(key);\n\t\tif (row === void 0) return void 0;\n\t\tif (typeof row.digest !== \"string\" || typeof row.grantId !== \"string\" || typeof row.status !== \"string\" || typeof row.scopes !== \"string\" || typeof row.reservation !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\tconst scopes = JSON.parse(row.scopes);\n\t\tif (!Array.isArray(scopes) || scopes.length < 4 || scopes.some((scope) => typeof scope !== \"string\") || new Set(scopes).size !== scopes.length || ![\n\t\t\t\"running\",\n\t\t\t\"unknown\",\n\t\t\t\"complete\",\n\t\t\t\"refused\"\n\t\t].includes(row.status) || !/^[a-f0-9]{64}$/.test(row.digest)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\treturn {\n\t\t\tdigest: row.digest,\n\t\t\tgrantId: row.grantId,\n\t\t\tstatus: row.status,\n\t\t\tscopes,\n\t\t\treservation: units(JSON.parse(row.reservation)),\n\t\t\treceipt: typeof row.receipt === \"string\" ? receipt(JSON.parse(row.receipt)) : null\n\t\t};\n\t}\n\treserve(envelope, reservation, approval, requiresApproval) {\n\t\tunits(reservation);\n\t\treturn this.transaction(() => {\n\t\t\tconst { request, grant, grants } = this.authenticateInside(envelope);\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (this.db.prepare(\"SELECT nonce FROM nonces WHERE tenant=? AND actor=? AND nonce=?\").get(request.tenant, request.actor, request.nonce) !== void 0) throw new OrganizationRefused(\"replayed\");\n\t\t\tconst key = scopeKey(\"task\", grant.tenant, grant.task) + \":\" + request.operation.idempotencyKey;\n\t\t\tconst previous = this.operation(key);\n\t\t\tif (previous !== void 0) {\n\t\t\t\tif (previous.digest !== digest || previous.grantId !== grant.id) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\t\tif (![\"complete\", \"refused\"].includes(previous.status) || previous.receipt === null) throw new OrganizationRefused(previous.status === \"unknown\" ? \"outcome-unknown\" : \"operation-pending\");\n\t\t\t\tthis.db.prepare(\"INSERT INTO nonces VALUES (?,?,?)\").run(request.tenant, request.actor, request.nonce);\n\t\t\t\tif (previous.status === \"refused\") return {\n\t\t\t\t\tkind: \"refused\",\n\t\t\t\t\tdigest,\n\t\t\t\t\treason: noEffectReason(record(previous.receipt.value, [\"refused\"]).refused)\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"complete\",\n\t\t\t\t\tdigest,\n\t\t\t\t\treceipt: previous.receipt\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (requiresApproval && approval === null) throw new OrganizationRefused(\"approval-required\");\n\t\t\tif (approval !== null) try {\n\t\t\t\tverifyEnvelope(\"approval\", approval, this.approvalKey);\n\t\t\t\tconst claims = approvalClaims(approval.claims);\n\t\t\t\tcurrentTime(claims, this.now(), this.maxGrantTtlMs);\n\t\t\t\tif (claims.tenant !== grant.tenant || claims.task !== grant.task || claims.actor !== grant.actor || claims.audience !== grant.audience || claims.epoch !== grant.epoch || claims.environment !== request.operation.environment || claims.operationDigest !== digest) throw new OrganizationRefused(\"approval-invalid\");\n\t\t\t\tif (this.db.prepare(\"SELECT id FROM approvals WHERE id=?\").get(claims.id)) throw new OrganizationRefused(\"approval-reused\");\n\t\t\t\tthis.db.prepare(\"INSERT INTO approvals VALUES (?,?)\").run(claims.id, digest);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof OrganizationRefused && error.reason === \"approval-reused\") throw error;\n\t\t\t\tthrow new OrganizationRefused(\"approval-invalid\");\n\t\t\t}\n\t\t\tconst scopes = [\n\t\t\t\tscopeKey(\"global\"),\n\t\t\t\tscopeKey(\"tenant\", grant.tenant),\n\t\t\t\tscopeKey(\"task\", grant.tenant, grant.task),\n\t\t\t\t...grants.map((item) => scopeKey(\"grant\", item.id))\n\t\t\t];\n\t\t\tfor (const scope of scopes) {\n\t\t\t\tconst state = this.liveBudget(scope);\n\t\t\t\tif (state.active >= state.limits.concurrency || UNIT_KEYS.some((unit) => reservation[unit] > state.limits[unit] - state.spent[unit] - state.held[unit])) throw new OrganizationRefused(\"budget-exhausted\");\n\t\t\t\tconst held = Object.fromEntries(UNIT_KEYS.map((unit) => [unit, state.held[unit] + reservation[unit]]));\n\t\t\t\tthis.db.prepare(\"UPDATE budgets SET held=?,active=active+1 WHERE key=?\").run(organizationCanonical(held), scope);\n\t\t\t}\n\t\t\tthis.db.prepare(\"INSERT INTO nonces VALUES (?,?,?)\").run(request.tenant, request.actor, request.nonce);\n\t\t\tthis.db.prepare(\"INSERT INTO operations VALUES (?,?,?,'running',?,?,NULL)\").run(key, digest, grant.id, organizationCanonical(scopes), organizationCanonical(reservation));\n\t\t\treturn {\n\t\t\t\tkind: \"reserved\",\n\t\t\t\tdigest,\n\t\t\t\tgrant,\n\t\t\t\treservation: Object.freeze({ ...reservation })\n\t\t\t};\n\t\t});\n\t}\n\tkey(request) {\n\t\treturn scopeKey(\"task\", request.tenant, request.task) + \":\" + request.operation.idempotencyKey;\n\t}\n\t/** A crash/unknown effect keeps every reservation. No request route can refund or retry it. */\n\tmarkUnknown(request) {\n\t\tthis.transaction(() => {\n\t\t\tconst key = this.key(request);\n\t\t\tconst row = this.operation(key);\n\t\t\tif (row === void 0 || row.digest !== organizationOperationDigest(request) || ![\"running\", \"unknown\"].includes(row.status)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tthis.db.prepare(\"UPDATE operations SET status='unknown' WHERE key=?\").run(key);\n\t\t});\n\t}\n\tsettle(request, receipt) {\n\t\tthis.recordReceipt(request, receipt, \"complete\");\n\t}\n\t/** External asset owner only: confirm an exact unknown effect, charge its retained bound, never restore authority. */\n\treconcileExternalOperation(value, confirmedValue) {\n\t\tconst request = requestClaims(value);\n\t\tconst outcome = this.transaction(() => {\n\t\t\tconst row = this.operation(this.key(request));\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (!row || row.digest !== digest || this.db.prepare(\"SELECT digest FROM state_effects WHERE digest=?\").get(digest) || this.db.prepare(\"SELECT digest FROM git_intents WHERE digest=?\").get(digest)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tif (row.status === \"complete\" && row.receipt !== null) {\n\t\t\t\tif (organizationCanonical(row.receipt.value) !== organizationCanonical(confirmedValue)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\t\treturn { cached: row.receipt };\n\t\t\t}\n\t\t\tif (![\"running\", \"unknown\"].includes(row.status)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\treturn { receipt: receipt({\n\t\t\t\tvalue: confirmedValue,\n\t\t\t\tusage: row.reservation\n\t\t\t}) };\n\t\t});\n\t\tif (outcome.cached) return outcome.cached;\n\t\tthis.recordReceipt(request, outcome.receipt, \"complete\", true);\n\t\treturn outcome.receipt;\n\t}\n\t/** Trusted asset owner only: a proved no-effect outcome, never a worker-provided refund assertion. */\n\tconfirmNoEffect(request, reason, usage) {\n\t\tthis.recordReceipt(request, {\n\t\t\tvalue: { refused: noEffectReason(reason) },\n\t\t\tusage\n\t\t}, \"refused\");\n\t}\n\trecordReceipt(request, receipt$1, status, allowUnknown = false) {\n\t\tconst validReceipt = receipt(receipt$1);\n\t\tconst usage = validReceipt.usage;\n\t\tconst encoded = organizationCanonical(validReceipt);\n\t\tthis.transaction(() => {\n\t\t\tconst key = this.key(request);\n\t\t\tconst row = this.operation(key);\n\t\t\tif (row === void 0 || row.digest !== organizationOperationDigest(request) || row.status !== \"running\" && !(allowUnknown && row.status === \"unknown\")) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tif (UNIT_KEYS.some((unit) => usage[unit] > row.reservation[unit])) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tif (status === \"refused\" && (this.db.prepare(\"SELECT digest FROM state_effects WHERE digest=?\").get(row.digest) || this.db.prepare(\"SELECT digest FROM git_intents WHERE digest=?\").get(row.digest))) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tfor (const scope of row.scopes) {\n\t\t\t\tconst stored = this.db.prepare(\"SELECT spent,held,active FROM budgets WHERE key=?\").get(scope);\n\t\t\t\tif (stored === void 0 || typeof stored.spent !== \"string\" || typeof stored.held !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\t\tconst spent = units(JSON.parse(stored.spent));\n\t\t\t\tconst held = units(JSON.parse(stored.held));\n\t\t\t\tinteger(stored.active, 1);\n\t\t\t\tconst nextSpent = Object.fromEntries(UNIT_KEYS.map((unit) => [unit, integer(spent[unit] + usage[unit])]));\n\t\t\t\tconst nextHeld = Object.fromEntries(UNIT_KEYS.map((unit) => [unit, integer(held[unit] - row.reservation[unit])]));\n\t\t\t\tthis.db.prepare(\"UPDATE budgets SET spent=?,held=?,active=active-1 WHERE key=?\").run(organizationCanonical(nextSpent), organizationCanonical(nextHeld), scope);\n\t\t\t}\n\t\t\tthis.db.prepare(\"UPDATE operations SET status=?,receipt=? WHERE key=?\").run(status, encoded, key);\n\t\t});\n\t}\n\trevokeGrant(grantId) {\n\t\tthis.transaction(() => {\n\t\t\tthis.db.prepare(\"UPDATE grants SET revoked=1 WHERE id=?\").run(identifier(grantId));\n\t\t});\n\t}\n\tstopTask(tenant, task) {\n\t\tthis.transaction(() => {\n\t\t\tthis.db.prepare(\"UPDATE budgets SET stopped=1 WHERE key=?\").run(scopeKey(\"task\", identifier(tenant), identifier(task)));\n\t\t});\n\t}\n\tstopTenant(tenant) {\n\t\tthis.transaction(() => {\n\t\t\tthis.db.prepare(\"UPDATE budgets SET stopped=1 WHERE key=?\").run(scopeKey(\"tenant\", identifier(tenant)));\n\t\t});\n\t}\n\temergencyStop() {\n\t\tthis.transaction(() => {\n\t\t\tthis.db.exec(\"UPDATE metadata SET active=0,epoch=epoch+1 WHERE id=1\");\n\t\t});\n\t}\n\tadvanceEpoch(epoch) {\n\t\tinteger(epoch, 1);\n\t\tthis.transaction(() => {\n\t\t\tif (epoch <= this.metadata().epoch) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tthis.db.prepare(\"UPDATE metadata SET epoch=? WHERE id=1\").run(epoch);\n\t\t});\n\t}\n\tbudgetState(kind, ...identity) {\n\t\treturn this.transaction(() => this.storedBudget(scopeKey(kind, ...identity.map(identifier))));\n\t}\n\tclose() {\n\t\tif (!this.closed) {\n\t\t\tthis.closed = true;\n\t\t\tthis.db.close();\n\t\t}\n\t}\n};\n//#endregion\n//#region src/file-ledger-anchor.ts\n/** Owner-selected independent custody directory. Never include it in a worker or authority-store backup. */\nvar OrganizationFileLedgerAnchor = class {\n\tledger;\n\tdirectory;\n\tfile;\n\tlock;\n\tconstructor(options) {\n\t\tthis.ledger = identifier(options.ledger);\n\t\tif (!isAbsolute(options.directory)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.directory = realpathSync(options.directory);\n\t\tconst stat = lstatSync(this.directory);\n\t\tif (!stat.isDirectory() || (stat.mode & 63) !== 0 || process.getuid !== void 0 && stat.uid !== process.getuid()) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.file = join(this.directory, \"head.json\");\n\t\tthis.lock = join(this.directory, \"head.lock\");\n\t}\n\tread() {\n\t\tlet fd;\n\t\ttry {\n\t\t\tfd = openSync(this.file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n\t\t\tconst stat = fstatSync(fd);\n\t\t\tif (!stat.isFile() || stat.size > 4096 || (stat.mode & 63) !== 0 || process.getuid !== void 0 && stat.uid !== process.getuid()) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\tconst value = JSON.parse(readFileSync(fd, \"utf8\"));\n\t\t\tthis.validate(value);\n\t\t\treturn Object.freeze({ ...value });\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return void 0;\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t} finally {\n\t\t\tif (fd !== void 0) closeSync(fd);\n\t\t}\n\t}\n\tvalidate(head) {\n\t\tif (!head || Object.keys(head).sort().join(\",\") !== \"digest,ledger,revision,version\" || head.version !== 1 || head.ledger !== this.ledger || !Number.isSafeInteger(head.revision) || head.revision < 1 || typeof head.digest !== \"string\" || !/^[a-f0-9]{64}$/u.test(head.digest)) throw new OrganizationRefused(\"policy-unavailable\");\n\t}\n\tcompareAndSet(expected, next) {\n\t\tthis.validate(next);\n\t\tif (expected !== void 0) this.validate(expected);\n\t\tif (next.revision !== (expected?.revision ?? 0) + 1) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tlet locked = false;\n\t\tlet temporary;\n\t\ttry {\n\t\t\tmkdirSync(this.lock, { mode: 448 });\n\t\t\tlocked = true;\n\t\t\tconst current = this.read();\n\t\t\tif (current === void 0 !== (expected === void 0) || current !== void 0 && organizationCanonical(current) !== organizationCanonical(expected)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\ttemporary = join(this.directory, `head-${randomUUID()}.tmp`);\n\t\t\tconst fd = openSync(temporary, \"wx\", 384);\n\t\t\ttry {\n\t\t\t\twriteFileSync(fd, organizationCanonical(next));\n\t\t\t\tfsyncSync(fd);\n\t\t\t} finally {\n\t\t\t\tcloseSync(fd);\n\t\t\t}\n\t\t\trenameSync(temporary, this.file);\n\t\t\ttemporary = void 0;\n\t\t\tconst directory = openSync(this.directory, constants.O_RDONLY);\n\t\t\ttry {\n\t\t\t\tfsyncSync(directory);\n\t\t\t} finally {\n\t\t\t\tcloseSync(directory);\n\t\t\t}\n\t\t} catch {\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t} finally {\n\t\t\tif (temporary !== void 0) try {\n\t\t\t\tunlinkSync(temporary);\n\t\t\t} catch {}\n\t\t\tif (locked) rmdirSync(this.lock);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/audit-http.ts\nfunction transport(options) {\n\tconst url = new URL(options.endpoint);\n\tif (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && [\"127.0.0.1\", \"[::1]\"].includes(url.hostname)) || url.username || url.password || url.search || url.hash || url.pathname !== \"/\" || typeof options.token !== \"string\" || !/^[A-Za-z0-9_-]{32,256}$/u.test(options.token)) throw new OrganizationRefused(\"invalid-schema\");\n\tconst token = options.token;\n\treturn async (path, value, signal, conflict = false) => {\n\t\ttry {\n\t\t\tconst response = await fetch(new URL(path, url), {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tredirect: \"error\",\n\t\t\t\tsignal,\n\t\t\t\theaders: {\n\t\t\t\t\tauthorization: `Bearer ${token}`,\n\t\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t\t},\n\t\t\t\tbody: organizationCanonical(value)\n\t\t\t});\n\t\t\tif (conflict && response.status === 409) {\n\t\t\t\tawait response.body?.cancel();\n\t\t\t\tthrow new OrganizationAuditAppendConflict();\n\t\t\t}\n\t\t\tif (!response.ok || response.body === null) {\n\t\t\t\tawait response.body?.cancel();\n\t\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t\t}\n\t\t\tconst chunks = [];\n\t\t\tlet size = 0;\n\t\t\tconst reader = response.body.getReader();\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst next = await reader.read();\n\t\t\t\t\tif (next.done) break;\n\t\t\t\t\tsize += next.value.length;\n\t\t\t\t\tif (size > 1024 * 1024) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\t\t\tchunks.push(next.value);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tawait reader.cancel();\n\t\t\t}\n\t\t\treturn JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(Buffer.concat(chunks)));\n\t\t} catch (error) {\n\t\t\tif (error instanceof OrganizationAuditAppendConflict) throw error;\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t}\n\t};\n}\n/** Concrete owner transport. Signed checkpoint verification remains in OrganizationAudit. */\nfunction createOrganizationAuditHttpPorts(options) {\n\tconst sink = transport(options.sink);\n\tconst anchor = transport(options.anchor);\n\treturn {\n\t\tsink: {\n\t\t\tread: async (after, signal) => await sink(\"/read\", after, signal),\n\t\t\tappend: async (expected, event, signal) => await sink(\"/append\", {\n\t\t\t\texpected,\n\t\t\t\tevent\n\t\t\t}, signal, true)\n\t\t},\n\t\tanchor: {\n\t\t\tload: async (signal) => await anchor(\"/load\", null, signal),\n\t\t\tcompareAndSet: async (expected, next, signal) => {\n\t\t\t\tconst result = await anchor(\"/cas\", {\n\t\t\t\t\texpected,\n\t\t\t\t\tnext\n\t\t\t\t}, signal);\n\t\t\t\tif (typeof result !== \"boolean\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/http-handler.ts\n/** One worker ingress. No minting, approval, policy, budget, refund or administration routes. */\nfunction createOrganizationHttpHandler(options) {\n\tconst url = new URL(options.audience);\n\tconst local = [\"127.0.0.1\", \"[::1]\"].includes(url.hostname);\n\tif (options.audience !== options.broker.audience || url.protocol !== \"https:\" && !(url.protocol === \"http:\" && local) || url.username !== \"\" || url.password !== \"\" || url.search !== \"\" || url.hash !== \"\" || url.pathname !== \"/\" || options.audience !== url.origin) throw new OrganizationRefused(\"invalid-schema\");\n\tconst timeoutMs = integer(options.bodyTimeoutMs ?? 2e3, 1);\n\tif (timeoutMs > 3e4) throw new OrganizationRefused(\"invalid-schema\");\n\treturn (request, response) => {\n\t\tconst controller = new AbortController();\n\t\tconst disconnected = () => {\n\t\t\tif (!response.writableFinished) controller.abort();\n\t\t};\n\t\tresponse.once(\"close\", disconnected);\n\t\tconst reply = (status, value) => {\n\t\t\tif (response.destroyed || response.writableEnded) return;\n\t\t\tresponse.writeHead(status, {\n\t\t\t\t\"content-type\": \"application/json; charset=utf-8\",\n\t\t\t\t\"cache-control\": \"no-store\",\n\t\t\t\t\"x-content-type-options\": \"nosniff\"\n\t\t\t});\n\t\t\tresponse.end(organizationCanonical(value));\n\t\t};\n\t\tlet timer;\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tconst sensitive = [\n\t\t\t\t\t\"host\",\n\t\t\t\t\t\"content-type\",\n\t\t\t\t\t\"content-length\",\n\t\t\t\t\t\"transfer-encoding\",\n\t\t\t\t\t\"origin\"\n\t\t\t\t];\n\t\t\t\tconst seen = /* @__PURE__ */ new Set();\n\t\t\t\tfor (let index = 0; index < request.rawHeaders.length; index += 2) {\n\t\t\t\t\tconst header = request.rawHeaders[index].toLowerCase();\n\t\t\t\t\tif (!sensitive.includes(header)) continue;\n\t\t\t\t\tif (seen.has(header)) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\t\t\tseen.add(header);\n\t\t\t\t}\n\t\t\t\tif (request.method !== \"POST\" || request.url !== \"/v1/apply\" || request.headers.host !== url.host || request.headers.origin !== void 0 || request.headers[\"content-type\"] !== \"application/json\" || request.headers[\"content-encoding\"] !== void 0) throw new OrganizationRefused(\"not-authorized\");\n\t\t\t\tconst length = request.headers[\"content-length\"];\n\t\t\t\tif (length !== void 0 && (!/^(0|[1-9][0-9]*)$/.test(length) || Number(length) > 64 * 1024)) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\t\tconst chunks = [];\n\t\t\t\tlet size = 0;\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t\trequest.destroy();\n\t\t\t\t}, timeoutMs);\n\t\t\t\tfor await (const chunk of request) {\n\t\t\t\t\tconst buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n\t\t\t\t\tsize += buffer.length;\n\t\t\t\t\tif (size > 64 * 1024) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\t\t\tchunks.push(buffer);\n\t\t\t\t}\n\t\t\t\tclearTimeout(timer);\n\t\t\t\ttimer = void 0;\n\t\t\t\tconst bytes = Buffer.concat(chunks);\n\t\t\t\tconst wire = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n\t\t\t\tconst data = JSON.parse(wire);\n\t\t\t\tif (wire !== organizationCanonical(data)) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\t\tconst receipt = await options.broker.apply(data, controller.signal);\n\t\t\t\treply(200, { receipt });\n\t\t\t} catch (error) {\n\t\t\t\tconst reason = error instanceof OrganizationRefused ? error.reason : \"invalid-schema\";\n\t\t\t\treply(reason === \"policy-unavailable\" ? 503 : 403, { refused: reason });\n\t\t\t\trequest.resume();\n\t\t\t} finally {\n\t\t\t\tif (timer !== void 0) clearTimeout(timer);\n\t\t\t\tresponse.removeListener(\"close\", disconnected);\n\t\t\t}\n\t\t})();\n\t};\n}\n//#endregion\nexport { OrganizationAudit, OrganizationAuditAppendConflict, OrganizationBroker, OrganizationFileLedgerAnchor, OrganizationGitAsset, OrganizationLedger, OrganizationNoEffect, OrganizationRefused, createOrganizationAuditHttpPorts, createOrganizationGitActions, createOrganizationHttpHandler, createOrganizationStateActions, organizationAuditEvent, organizationAuditGenesis, organizationAuditHash, organizationAuditSigningBytes, organizationCanonical, organizationOperationDigest, organizationSigningBytes, verifyOrganizationAudit };\n\n//# sourceMappingURL=index.js.map","import { OrganizationBroker, OrganizationRefused, organizationAuditEvent, organizationOperationDigest } from '@robota-sdk/agent-organization-host';\nimport type { OrganizationAudit, OrganizationLedger, IOrganizationAction, IOrganizationCall, IOrganizationGrant, IOrganizationReceipt, IOrganizationRequest, TOrganizationJson } from '@robota-sdk/agent-organization-host';\nimport type { IHostedIdentity } from './hosted-runtime-types.js';\n\nexport interface IHostedOrganizationWorker {\n readonly resource: string;\n readonly grantId: string;\n readonly identity: IHostedIdentity;\n readonly epoch: number;\n}\n\n/** Owner provider inventory must survive broker restart and exclude resources outside its custody. */\nexport interface IHostedOrganizationInventory {\n list(signal: AbortSignal): Promise<readonly IHostedOrganizationWorker[]>;\n /** Revalidate owner metadata before termination; return only after the provider acknowledges cleanup. */\n terminate(worker: IHostedOrganizationWorker, signal: AbortSignal): Promise<void>;\n}\n\nexport interface IHostedOrganizationIncidentOwners {\n readonly detection: string;\n readonly containment: string;\n readonly assessment: string;\n readonly recovery: string;\n /** Owner-installed incident channel; metadata only, no provider errors, credentials or request bodies. */\n report(event: {\n readonly kind: 'authority-unavailable' | 'cleanup-unresolved' | 'unknown-effect';\n readonly resources: readonly string[];\n readonly operationDigest?: string;\n }): Promise<void>;\n}\n\nexport interface IHostedOrganizationControlOptions {\n readonly ledger: OrganizationLedger;\n readonly audit: OrganizationAudit;\n readonly actions: readonly IOrganizationAction[];\n readonly inventory: IHostedOrganizationInventory;\n readonly incidentOwners: IHostedOrganizationIncidentOwners;\n readonly policyIntervalMs?: number;\n readonly providerTimeoutMs?: number;\n}\n\n/** Owner-side company composition. No administrator operations are exposed to workers or model tools. */\nexport class HostedOrganizationControl {\n private readonly ledger: OrganizationLedger;\n private readonly audit: OrganizationAudit;\n private readonly broker: OrganizationBroker;\n private readonly inventory: IHostedOrganizationInventory;\n private readonly incidents: IHostedOrganizationIncidentOwners;\n private readonly timeout: number;\n private readonly timer: ReturnType<typeof setInterval>;\n private readonly calls = new Map<AbortController, string>();\n private sweepPending?: Promise<void>;\n private closed = false;\n private quarantined = false;\n\n constructor(options: IHostedOrganizationControlOptions) {\n this.ledger = options.ledger;\n this.audit = options.audit;\n this.broker = new OrganizationBroker({ ledger: options.ledger, audit: options.audit, actions: options.actions, hosted: true, policyIntervalMs: options.policyIntervalMs });\n const interval = options.policyIntervalMs ?? 100;\n this.timeout = options.providerTimeoutMs ?? 10_000;\n if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 30_000 ||\n typeof options.inventory?.list !== 'function' || typeof options.inventory.terminate !== 'function' ||\n typeof options.incidentOwners?.report !== 'function' ||\n ['detection', 'containment', 'assessment', 'recovery'].some((key) => {\n const value = options.incidentOwners[key as 'detection'];\n return typeof value !== 'string' || value.trim().length === 0;\n })) throw new OrganizationRefused('invalid-schema');\n this.inventory = Object.freeze({ list: options.inventory.list.bind(options.inventory), terminate: options.inventory.terminate.bind(options.inventory) });\n this.incidents = Object.freeze({ ...options.incidentOwners, report: options.incidentOwners.report.bind(options.incidentOwners) });\n this.timer = setInterval(() => { void this.sweep().catch(() => undefined); }, interval);\n this.timer.unref();\n }\n\n private identity(grantId: string, identity: IHostedIdentity, epoch: number): IOrganizationGrant {\n const grant = this.ledger.currentGrant(grantId);\n // currentGrant verifies every delegation ancestor. Logical root/runtime bindings come from\n // the owner's provider inventory, and survive replacement of a revoked workload grant.\n if (grant.tenant !== identity.tenant || grant.task !== identity.task || grant.actor !== identity.actor ||\n grant.epoch !== epoch)\n throw new OrganizationRefused('not-authorized');\n return grant;\n }\n\n /** Admission uses current policy and retained audit evidence, never checkpoint authority. */\n async admit(worker: IHostedOrganizationWorker, signal?: AbortSignal): Promise<IOrganizationGrant> {\n if (this.closed || this.quarantined) throw new OrganizationRefused('policy-unavailable');\n this.ledger.verifyAnchoredAuthority();\n const grant = this.identity(worker.grantId, worker.identity, worker.epoch);\n await this.audit.verify(signal);\n const live = await this.inventory.list(signal === undefined ? AbortSignal.timeout(this.timeout) : AbortSignal.any([signal, AbortSignal.timeout(this.timeout)]));\n if (!live.some((entry) => entry.resource === worker.resource && entry.grantId === worker.grantId &&\n entry.epoch === worker.epoch && Object.entries(worker.identity).every(([key, value]) => entry.identity[key as keyof IHostedIdentity] === value)))\n throw new OrganizationRefused('not-authorized');\n if (this.closed || this.quarantined || signal?.aborted) throw new OrganizationRefused('not-authorized');\n this.identity(worker.grantId, worker.identity, worker.epoch);\n return grant;\n }\n\n async apply(call: IOrganizationCall, signal?: AbortSignal, onWithdrawal?: () => void): Promise<IOrganizationReceipt> {\n if (this.closed || this.quarantined) throw new OrganizationRefused('policy-unavailable');\n const controller = new AbortController();\n const withdraw = (): void => { onWithdrawal?.(); };\n controller.signal.addEventListener('abort', withdraw, { once: true });\n const abort = (): void => controller.abort();\n signal?.addEventListener('abort', abort, { once: true });\n if (signal?.aborted) controller.abort();\n this.calls.set(controller, call.request.claims.grantId);\n try { return await this.broker.apply(call, controller.signal); }\n catch (error) {\n if (error instanceof OrganizationRefused && error.reason === 'outcome-unknown') {\n await this.incidents.report({ kind: 'unknown-effect', resources: [call.request.claims.operation.resource], operationDigest: organizationOperationDigest(call.request.claims) }).catch(() => undefined);\n }\n throw error;\n }\n finally {\n this.calls.delete(controller);\n signal?.removeEventListener('abort', abort); controller.signal.removeEventListener('abort', withdraw);\n }\n }\n\n /** Owner commands persist policy withdrawal before terminating every affected provider worker. */\n private async afterWithdrawal(): Promise<void> {\n // An existing sweep may have evaluated policy before this withdrawal. Wait for it, then inspect again.\n await this.sweepPending?.catch(() => undefined);\n await this.sweep();\n }\n async stopGrant(grantId: string): Promise<void> { this.ledger.revokeGrant(grantId); await this.afterWithdrawal(); }\n async stopTask(tenant: string, task: string): Promise<void> { this.ledger.stopTask(tenant, task); await this.afterWithdrawal(); }\n async stopTenant(tenant: string): Promise<void> { this.ledger.stopTenant(tenant); await this.afterWithdrawal(); }\n async emergencyStop(): Promise<void> { this.ledger.emergencyStop(); await this.afterWithdrawal(); }\n\n /** Owner recovery channel only. A worker cannot supply the asset-owner confirmation capability. */\n async reconcileExternalOperation(request: IOrganizationRequest, assetOwner: {\n confirm(operationDigest: string, signal?: AbortSignal): Promise<TOrganizationJson>;\n }, signal?: AbortSignal): Promise<IOrganizationReceipt> {\n this.ledger.verifyAnchoredAuthority();\n const event = organizationAuditEvent(request, 'complete');\n const confirmed = await assetOwner.confirm(event.operationDigest, signal);\n await this.audit.record(event, signal);\n return this.ledger.reconcileExternalOperation(request, confirmed);\n }\n\n sweep(): Promise<void> {\n if (this.sweepPending !== undefined) return this.sweepPending;\n this.sweepPending = this.sweepOnce().finally(() => { this.sweepPending = undefined; });\n return this.sweepPending;\n }\n\n private async sweepOnce(): Promise<void> {\n const firstFailure = !this.closed && !this.quarantined;\n let unavailable = this.closed || this.quarantined;\n try { this.ledger.verifyAnchoredAuthority(); await this.audit.verify(AbortSignal.timeout(this.timeout)); }\n catch { unavailable = true; }\n if (unavailable && !this.closed) { this.quarantined = true; this.broker.close(); }\n for (const [controller, grantId] of this.calls) {\n try { if (unavailable) throw new OrganizationRefused('policy-unavailable'); this.ledger.currentGrant(grantId); }\n catch { controller.abort(); }\n }\n let workers: readonly IHostedOrganizationWorker[];\n try { workers = await this.inventory.list(AbortSignal.timeout(this.timeout)); }\n catch {\n this.quarantined = true;\n this.broker.close();\n for (const controller of this.calls.keys()) controller.abort();\n await this.incidents.report({ kind: 'cleanup-unresolved', resources: [] });\n throw new OrganizationRefused('policy-unavailable');\n }\n const stopped = workers.filter((worker) => {\n try { if (unavailable) return true; this.identity(worker.grantId, worker.identity, worker.epoch); return false; }\n catch { return true; }\n });\n const outcomes = await Promise.allSettled(stopped.map((worker) => this.inventory.terminate(worker, AbortSignal.timeout(this.timeout))));\n const unresolved = stopped.filter((_worker, index) => outcomes[index]!.status === 'rejected').map((worker) => worker.resource);\n if (unavailable && firstFailure) await this.incidents.report({ kind: 'authority-unavailable', resources: stopped.map((worker) => worker.resource) });\n if (unresolved.length > 0) {\n await this.incidents.report({ kind: 'cleanup-unresolved', resources: unresolved });\n throw new OrganizationRefused('policy-unavailable');\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n clearInterval(this.timer);\n this.broker.close();\n for (const controller of this.calls.keys()) controller.abort();\n await this.afterWithdrawal();\n }\n}\n","import { loadE2BSdk } from './e2b-sdk.js';\nimport type { SandboxInfo } from 'e2b/dist/index.mjs';\nimport { decodeHostedIdentity, identifier, positiveInteger } from './hosted-runtime-config.js';\nimport type { IHostedOrganizationInventory, IHostedOrganizationWorker } from './hosted-organization-control.js';\n\n/** Provider-backed inventory, including paused workers. Its management capability stays outside every worker. */\nexport function createE2BOrganizationInventory(options: {\n readonly apiKey: string;\n readonly controlPlane: string;\n readonly tenant: string;\n readonly requestTimeoutMs?: number;\n}): IHostedOrganizationInventory {\n const controlPlane = identifier(options.controlPlane, 'organization control plane');\n const tenant = identifier(options.tenant, 'organization tenant');\n const request = {\n apiKey: identifier(options.apiKey, 'E2B management credential'),\n requestTimeoutMs: positiveInteger(options.requestTimeoutMs ?? 10_000, 'E2B request timeout', 30_000),\n apiUrl: 'https://api.e2b.app', sandboxUrl: 'https://sandbox.e2b.app', domain: 'e2b.app', debug: false, retries: 0,\n };\n function owned(info: SandboxInfo): IHostedOrganizationWorker {\n if (info.metadata.organizationControlPlane !== controlPlane || info.metadata.tenant !== tenant)\n throw new Error('Organization inventory ownership mismatch');\n return Object.freeze({\n resource: identifier(info.sandboxId, 'organization worker'),\n grantId: identifier(info.metadata.organizationGrant, 'organization grant'),\n epoch: positiveInteger(Number(info.metadata.epoch), 'organization epoch'),\n identity: decodeHostedIdentity({ tenant: info.metadata.tenant, task: info.metadata.task, rootTask: info.metadata.rootTask, actor: info.metadata.actor, runtime: info.metadata.runtime }),\n });\n }\n return {\n async list(signal) {\n signal.throwIfAborted();\n const { Sandbox } = await loadE2BSdk();\n signal.throwIfAborted();\n const paginator = Sandbox.list({ ...request, query: { metadata: { organizationControlPlane: controlPlane, tenant }, state: ['running', 'paused'] }, limit: 100 });\n const workers: IHostedOrganizationWorker[] = [];\n const seen = new Set<string>();\n while (paginator.hasNext) {\n signal.throwIfAborted();\n for (const info of await paginator.nextItems({ ...request, signal })) {\n const worker = owned(info);\n if (seen.has(worker.resource) || workers.length >= 10_000) throw new Error('Organization inventory is incomplete');\n seen.add(worker.resource); workers.push(worker);\n }\n }\n return workers;\n },\n async terminate(worker, signal) {\n signal.throwIfAborted();\n const { Sandbox, SandboxNotFoundError } = await loadE2BSdk();\n signal.throwIfAborted();\n let info: SandboxInfo;\n try { info = await Sandbox.getInfo(worker.resource, { ...request, signal }); }\n catch (error) { if (error instanceof SandboxNotFoundError) return; throw new Error('Organization cleanup is unresolved'); }\n const current = owned(info);\n if (current.grantId !== worker.grantId || current.epoch !== worker.epoch ||\n Object.entries(worker.identity).some(([key, value]) => current.identity[key as keyof typeof current.identity] !== value))\n throw new Error('Organization cleanup ownership mismatch');\n // Do not abort away the deletion receipt; the SDK request timeout still bounds the call.\n await Sandbox.kill(worker.resource, request);\n },\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { OrganizationRefused, organizationSigningBytes } from '@robota-sdk/agent-organization-host';\nimport type { OrganizationLedger, IOrganizationRequest, IOrganizationEnvelope } from '@robota-sdk/agent-organization-host';\nimport { hostedAdmissionBytes, verifyHostedAdmissionProof } from './hosted-runtime-admission.js';\nimport type { IHostedAdmissionProof, IHostedRuntimeConfig, IHostedRuntimeUsage, THostedBackendRole } from './hosted-runtime-types.js';\nimport type { HostedOrganizationControl } from './hosted-organization-control.js';\nimport type { HostedOrganizationPayloads } from './hosted-organization-payloads.js';\n\nexport interface IHostedOrganizationBinding {\n readonly config: IHostedRuntimeConfig;\n readonly grantId: string;\n readonly token: string;\n readonly expiresAt: number;\n /** External issuer capabilities installed by the owner, never supplied by an HTTP caller. */\n signAdmission(role: THostedBackendRole, bytes: Uint8Array): string;\n signRequest(bytes: Uint8Array): string;\n}\n\n/** Actual stock CLI admission and OpenAI-wire ingress over durable company effects. No owner routes. */\nexport function createHostedOrganizationGateway(options: {\n readonly control: HostedOrganizationControl;\n readonly ledger: OrganizationLedger;\n readonly payloads: HostedOrganizationPayloads;\n readonly bindings: readonly IHostedOrganizationBinding[];\n readonly modelResource: string;\n}): (request: IncomingMessage, response: ServerResponse) => void {\n const bindings = [...options.bindings];\n const tokens = new Set<string>(); const runtimes = new Set<string>(); const grants = new Set<string>();\n for (const binding of bindings) {\n if (!/^[A-Za-z0-9_-]{32,256}$/u.test(binding.token) || tokens.has(binding.token) || runtimes.has(binding.config.identity.runtime) || grants.has(binding.grantId))\n throw new OrganizationRefused('invalid-schema');\n const grant = options.ledger.currentGrant(binding.grantId);\n if (grant.scopes.length !== 1 || grant.scopes[0]!.resource !== options.modelResource ||\n grant.scopes[0]!.operations.length !== 1 || grant.scopes[0]!.operations[0] !== 'generate')\n throw new OrganizationRefused('not-authorized');\n tokens.add(binding.token); runtimes.add(binding.config.identity.runtime); grants.add(binding.grantId);\n }\n const usage = (binding: IHostedOrganizationBinding): IHostedRuntimeUsage => {\n const budget = options.ledger.budgetState('grant', binding.grantId);\n return { sessions: 1, modelCalls: options.ledger.grantOperationCount(binding.grantId),\n modelTokens: budget.spent.tokens, costMicros: budget.spent.costMicros };\n };\n return (request, response) => {\n const controller = new AbortController();\n const disconnected = (): void => { if (!response.writableFinished) controller.abort(); };\n response.once('close', disconnected);\n const timeout = setTimeout(() => { controller.abort(); request.destroy(); response.destroy(); }, 30_000);\n const reply = (status: number, body: unknown): void => {\n if (response.destroyed || response.writableEnded) return;\n response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });\n response.end(JSON.stringify(body));\n };\n void (async () => {\n try {\n const seen = new Set<string>();\n for (let index = 0; index < request.rawHeaders.length; index += 2) {\n const key = request.rawHeaders[index]!.toLowerCase();\n if (!['host', 'authorization', 'idempotency-key', 'content-type', 'content-length', 'transfer-encoding', 'origin'].includes(key)) continue;\n if (seen.has(key)) throw new OrganizationRefused('invalid-schema'); seen.add(key);\n }\n if (request.method !== 'POST' || request.headers.origin !== undefined || request.headers['content-type'] !== 'application/json' || request.headers['content-encoding'] !== undefined)\n throw new OrganizationRefused('not-authorized');\n const chunks: Buffer[] = []; let size = 0;\n for await (const chunk of request) {\n const bytes = Buffer.from(chunk as Uint8Array); size += bytes.length;\n if (size > 4 * 1024 * 1024) throw new OrganizationRefused('invalid-schema'); chunks.push(bytes);\n }\n const bytes = Buffer.concat(chunks);\n const body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as Record<string, unknown>;\n if (!body || Array.isArray(body)) throw new OrganizationRefused('invalid-schema');\n const model = ['/v1/chat/completions', '/v1/responses'].includes(request.url ?? '');\n const binding = model\n ? bindings.find((entry) => request.headers.authorization === `Bearer ${entry.token}`)\n : bindings.find((entry) => (body.identity as { runtime?: unknown } | undefined)?.runtime === entry.config.identity.runtime);\n if (!binding || binding.expiresAt <= Date.now()) throw new OrganizationRefused('expired');\n const config = binding.config;\n if (request.headers.host !== new URL(config.broker.endpoint).host ||\n new URL(config.worker.endpoint).origin !== new URL(config.broker.endpoint).origin)\n throw new OrganizationRefused('not-authorized');\n const grant = await options.control.admit({ resource: config.worker.resource, grantId: binding.grantId, identity: config.identity, epoch: config.epoch }, controller.signal);\n if (!model) {\n const role = request.url === new URL(config.worker.endpoint).pathname ? 'worker'\n : request.url === new URL(config.broker.endpoint).pathname ? 'broker' : undefined;\n if (!role || typeof body.nonce !== 'string' || body.version !== 3 || body.role !== role ||\n body.resource !== config[role].resource || body.epoch !== config.epoch ||\n Object.entries(config.identity).some(([key, expected]) => (body.identity as Record<string, unknown>)?.[key] !== expected) ||\n JSON.stringify(body.snapshot) !== JSON.stringify(config.snapshot) || JSON.stringify(body.limits) !== JSON.stringify(config.limits))\n throw new OrganizationRefused('not-authorized');\n const issuedAt = Date.now();\n const unsigned: Omit<IHostedAdmissionProof, 'signature'> = { version: 3, identity: config.identity, role, resource: config[role].resource, nonce: body.nonce, epoch: config.epoch, issuedAt,\n expiresAt: Math.min(issuedAt + 60_000, binding.expiresAt, grant.expiresAt), snapshot: config.snapshot, ready: true, limits: config.limits, usage: role === 'broker' ? usage(binding) : null };\n const proof = { ...unsigned, signature: binding.signAdmission(role, hostedAdmissionBytes(unsigned)) };\n verifyHostedAdmissionProof(proof, config, role, body.nonce, Date.now());\n reply(200, proof); return;\n }\n const key = request.headers['idempotency-key'];\n if (typeof key !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/u.test(key)) throw new OrganizationRefused('invalid-schema');\n const payload = await options.payloads.put(grant.id, bytes);\n const now = Date.now();\n const claims: IOrganizationRequest = { version: 1, grantId: grant.id, tenant: grant.tenant, task: grant.task, actor: grant.actor, audience: grant.audience, epoch: grant.epoch, nonce: randomUUID(), notBefore: now,\n expiresAt: Math.min(now + 25_000, binding.expiresAt, grant.expiresAt), operation: { idempotencyKey: key, resource: options.modelResource, operation: 'generate', environment: 'hosted', parameters: { request: payload, surface: request.url === '/v1/responses' ? 'responses' : 'chat-completions' } } };\n const envelope: IOrganizationEnvelope<IOrganizationRequest> = { claims, signature: binding.signRequest(organizationSigningBytes('request', claims)) };\n await options.payloads.recordOperation(claims);\n const receipt = await options.control.apply({ request: envelope, approval: null }, controller.signal, () => response.destroy());\n const digest = (receipt.value as { response?: unknown } | null)?.response;\n if (typeof digest !== 'string') throw new OrganizationRefused('outcome-unknown');\n const returned = await options.payloads.get(grant.id, digest);\n const result = JSON.parse(returned.toString('utf8')) as Record<string, unknown>;\n if (body.stream === true) {\n response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });\n if (request.url === '/v1/responses') {\n const output = result.output as Array<{ type: string; content?: Array<{ type: string; text?: string }> }>;\n if (Array.isArray(output)) for (const item of output) {\n if (item.type === 'message' && Array.isArray(item.content)) for (const part of item.content) {\n if (part.type === 'output_text' && typeof part.text === 'string')\n response.write(`data: ${JSON.stringify({ type: 'response.output_text.delta', delta: part.text })}\\n\\n`);\n }\n }\n response.end(`data: ${JSON.stringify({ type: 'response.completed', response: result })}\\n\\n`);\n }\n else {\n const choices = result.choices as Array<{ index: number; message: Record<string, unknown>; finish_reason: unknown }>;\n if (!Array.isArray(choices)) throw new OrganizationRefused('outcome-unknown');\n response.write(`data: ${JSON.stringify({ ...result, object: 'chat.completion.chunk', choices: choices.map((choice) => ({ index: choice.index, delta: { ...choice.message,\n ...(Array.isArray(choice.message.tool_calls) ? { tool_calls: choice.message.tool_calls.map((tool, index) => ({ ...tool as object, index })) } : {}) }, finish_reason: null })) })}\\n\\n`);\n response.end(`data: ${JSON.stringify({ ...result, object: 'chat.completion.chunk', choices: choices.map((choice) => ({ index: choice.index, delta: {}, finish_reason: choice.finish_reason })) })}\\n\\ndata: [DONE]\\n\\n`);\n }\n } else reply(200, result);\n } catch (error) {\n if (response.headersSent) response.destroy();\n else reply(error instanceof OrganizationRefused && ['policy-unavailable', 'outcome-unknown'].includes(error.reason) ? 503 : 403,\n { error: { message: error instanceof OrganizationRefused ? error.message : 'Organization ingress refused', type: 'organization_refusal' } });\n request.resume();\n } finally { clearTimeout(timeout); response.removeListener('close', disconnected); }\n })();\n };\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport { open, realpath, stat, rename, unlink } from 'node:fs/promises';\nimport { isAbsolute, join } from 'node:path';\nimport { OrganizationRefused, organizationOperationDigest, organizationAuditEvent } from '@robota-sdk/agent-organization-host';\nimport type { IOrganizationRequest } from '@robota-sdk/agent-organization-host';\n\n/** Private owner content storage for model wire bytes; the bounded authority journal keeps only digests. */\nexport class HostedOrganizationPayloads {\n private constructor(private readonly directory: string) {}\n\n static async open(directory: string): Promise<HostedOrganizationPayloads> {\n if (!isAbsolute(directory)) throw new OrganizationRefused('policy-unavailable');\n const path = await realpath(directory);\n const info = await stat(path);\n if (!info.isDirectory() || (info.mode & 0o077) !== 0 ||\n (process.getuid !== undefined && info.uid !== process.getuid()))\n throw new OrganizationRefused('policy-unavailable');\n return new HostedOrganizationPayloads(path);\n }\n\n private path(grantId: string, digest: string): string {\n if (!/^[a-f0-9]{64}$/u.test(digest)) throw new OrganizationRefused('invalid-schema');\n const owner = createHash('sha256').update(grantId).digest('hex');\n return join(this.directory, `${owner}-${digest}.json`);\n }\n\n async put(grantId: string, bytes: Uint8Array): Promise<string> {\n if (bytes.length > 4 * 1024 * 1024) throw new OrganizationRefused('invalid-schema');\n const digest = createHash('sha256').update(bytes).digest('hex');\n const file = this.path(grantId, digest);\n await this.persist(file, bytes);\n return digest;\n }\n\n private async persist(file: string, bytes: Uint8Array): Promise<void> {\n const temporary = join(this.directory, `${randomUUID()}.tmp`);\n try {\n const handle = await open(temporary, 'wx', 0o600);\n try { await handle.writeFile(bytes); await handle.sync(); } finally { await handle.close(); }\n await rename(temporary, file);\n const directory = await open(this.directory, constants.O_RDONLY);\n try { await directory.sync(); } finally { await directory.close(); }\n } catch { throw new OrganizationRefused('policy-unavailable'); }\n finally { await unlink(temporary).catch(() => undefined); }\n }\n\n /** Owner outbox manifest. Digest addressing survives a broker crash without putting request claims in audit. */\n async recordOperation(request: IOrganizationRequest): Promise<void> {\n const digest = organizationOperationDigest(request);\n const requestDigest = await this.put(request.grantId, Buffer.from(JSON.stringify(request)));\n await this.persist(`${this.path(request.grantId, digest)}.operation`, Buffer.from(JSON.stringify({ requestDigest })));\n }\n\n async operation(grantId: string, digest: string): Promise<IOrganizationRequest> {\n const handle = await open(`${this.path(grantId, digest)}.operation`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n try {\n const info = await handle.stat();\n if (!info.isFile() || info.size > 4096 || (info.mode & 0o077) !== 0 ||\n (process.getuid !== undefined && info.uid !== process.getuid())) throw new OrganizationRefused('policy-unavailable');\n const index = JSON.parse(await handle.readFile('utf8')) as { requestDigest?: unknown };\n if (typeof index.requestDigest !== 'string') throw new OrganizationRefused('policy-unavailable');\n const request = JSON.parse((await this.get(grantId, index.requestDigest)).toString('utf8')) as IOrganizationRequest;\n organizationAuditEvent(request, 'complete');\n if (request.grantId !== grantId || organizationOperationDigest(request) !== digest)\n throw new OrganizationRefused('policy-unavailable');\n return request;\n } finally { await handle.close(); }\n }\n\n async get(grantId: string, digest: string): Promise<Buffer> {\n try {\n const handle = await open(this.path(grantId, digest), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n try {\n const info = await handle.stat();\n if (!info.isFile() || info.size > 4 * 1024 * 1024 || (info.mode & 0o077) !== 0 ||\n (process.getuid !== undefined && info.uid !== process.getuid())) throw new Error('unowned content');\n const bytes = await handle.readFile();\n if (createHash('sha256').update(bytes).digest('hex') !== digest) throw new Error('changed content');\n return bytes;\n } finally { await handle.close(); }\n } catch { throw new OrganizationRefused('policy-unavailable'); }\n }\n}\n","import { OrganizationNoEffect, OrganizationRefused } from '@robota-sdk/agent-organization-host';\nimport type { IOrganizationAction, IOrganizationUnits } from '@robota-sdk/agent-organization-host';\nimport type { HostedOrganizationPayloads } from './hosted-organization-payloads.js';\n\nexport interface IHostedOrganizationModelOptions {\n readonly payloads: HostedOrganizationPayloads;\n readonly endpoint: string;\n readonly apiKey: string;\n readonly model: string;\n readonly roles: readonly string[];\n readonly resource: string;\n readonly reservation: IOrganizationUnits;\n readonly maxInputBytes: number;\n readonly maxOutputTokens: number;\n readonly costMicrosPerToken: number;\n /** Declare only an upstream contract actually supported by the owner-selected provider. */\n readonly providerIdempotency: boolean;\n /** Owner-selected pure input counter for the exact immutable provider request, including tools/media. */\n countInputTokens(surface: 'responses' | 'chat-completions', request: Readonly<Record<string, unknown>>, signal: AbortSignal): Promise<number>;\n}\n\n/** Actual fixed-provider HTTP effect. No automatic retry; ambiguous outcomes retain the broker hold. */\nexport function createHostedOrganizationModelAction(options: IHostedOrganizationModelOptions): IOrganizationAction {\n const endpoint = new URL(options.endpoint);\n if ((endpoint.protocol !== 'https:' && !(endpoint.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(endpoint.hostname))) ||\n endpoint.username || endpoint.password || endpoint.search || endpoint.hash ||\n typeof options.apiKey !== 'string' || /[\\r\\n]/u.test(options.apiKey) || options.apiKey.length === 0 ||\n !Number.isSafeInteger(options.maxInputBytes) || options.maxInputBytes < 1 || options.maxInputBytes > 4 * 1024 * 1024 ||\n !Number.isSafeInteger(options.maxOutputTokens) || options.maxOutputTokens < 1 ||\n !Number.isSafeInteger(options.costMicrosPerToken) || options.costMicrosPerToken < 0 ||\n typeof options.countInputTokens !== 'function')\n throw new OrganizationRefused('invalid-schema');\n const reservation = Object.freeze({ ...options.reservation });\n const countInputTokens = options.countInputTokens.bind(options);\n const parameters = (value: unknown): { request: string; surface: 'responses' | 'chat-completions' } => {\n const data = value as { request?: unknown; surface?: unknown };\n if (!data || Object.keys(data).sort().join(',') !== 'request,surface' ||\n typeof data.request !== 'string' || !/^[a-f0-9]{64}$/u.test(data.request) ||\n !['responses', 'chat-completions'].includes(String(data.surface)))\n throw new OrganizationRefused('invalid-schema');\n return data as { request: string; surface: 'responses' | 'chat-completions' };\n };\n return {\n resource: options.resource, operation: 'generate', roles: [...options.roles], requiresApproval: false,\n reserve: (operation) => { parameters(operation.parameters); return reservation; },\n execute: async (operation, context) => {\n const input = parameters(operation.parameters);\n const wire = await options.payloads.get(context.identity.id, input.request);\n if (wire.length > options.maxInputBytes) throw new OrganizationRefused('invalid-schema');\n const body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(wire)) as Record<string, unknown>;\n if (!body || Array.isArray(body) || body.model !== options.model) throw new OrganizationRefused('not-authorized');\n const upstreamBody: Record<string, unknown> = { ...body, stream: false };\n if (['conversation', 'previous_response_id', 'prompt'].some((key) => upstreamBody[key] != null) ||\n (Array.isArray(upstreamBody.tools) && upstreamBody.tools.some((tool) => (tool as { type?: unknown })?.type !== 'function')))\n throw new OrganizationNoEffect('not-authorized', { tokens: 0, timeMs: 0, costMicros: 0 });\n delete upstreamBody.max_tokens;\n delete upstreamBody.max_completion_tokens;\n delete upstreamBody.max_output_tokens;\n delete upstreamBody.stream_options;\n upstreamBody[input.surface === 'responses' ? 'max_output_tokens' : 'max_completion_tokens'] = options.maxOutputTokens;\n upstreamBody.store = false;\n upstreamBody.n = input.surface === 'chat-completions' ? 1 : undefined;\n if (input.surface === 'responses') { delete upstreamBody.n; upstreamBody.background = false; }\n const encoded = JSON.stringify(upstreamBody);\n const inputTokens = await countInputTokens(input.surface, JSON.parse(encoded) as Record<string, unknown>, context.signal);\n const maximum = inputTokens + options.maxOutputTokens;\n if (!Number.isSafeInteger(inputTokens) || inputTokens < 0 || !Number.isSafeInteger(maximum) ||\n maximum > reservation.tokens || !Number.isSafeInteger(maximum * options.costMicrosPerToken) || maximum * options.costMicrosPerToken > reservation.costMicros)\n throw new OrganizationNoEffect('budget-exhausted', { tokens: 0, timeMs: 0, costMicros: 0 });\n context.signal.throwIfAborted();\n const response = await fetch(`${endpoint.href.replace(/\\/$/u, '')}/${input.surface === 'responses' ? 'responses' : 'chat/completions'}`, {\n method: 'POST', redirect: 'error', signal: context.signal,\n headers: { authorization: `Bearer ${options.apiKey}`, 'content-type': 'application/json',\n ...(options.providerIdempotency ? { 'Idempotency-Key': context.operationDigest } : {}) },\n body: encoded,\n });\n if (!response.ok || response.body === null) {\n await response.body?.cancel();\n throw new OrganizationRefused('outcome-unknown');\n }\n const chunks: Uint8Array[] = [];\n let size = 0;\n const reader = response.body.getReader();\n try {\n for (;;) {\n const next = await reader.read(); if (next.done) break;\n size += next.value.length;\n if (size > 4 * 1024 * 1024) throw new OrganizationRefused('outcome-unknown');\n chunks.push(next.value);\n }\n } finally { await reader.cancel(); }\n const bytes = Buffer.concat(chunks);\n const result = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as { usage?: { total_tokens?: unknown } };\n const tokens = result?.usage?.total_tokens;\n if (typeof tokens !== 'number' || !Number.isSafeInteger(tokens) || tokens < 0 || tokens > reservation.tokens ||\n !Number.isSafeInteger(tokens * options.costMicrosPerToken) || tokens * options.costMicrosPerToken > reservation.costMicros)\n throw new OrganizationRefused('outcome-unknown');\n const digest = await options.payloads.put(context.identity.id, bytes);\n return { value: { response: digest }, usage: { tokens, timeMs: 0, costMicros: tokens * options.costMicrosPerToken } };\n },\n };\n}\n","import { OrganizationRefused } from '@robota-sdk/agent-organization-host';\nimport type { IHostedOrganizationModelOptions } from './hosted-organization-model.js';\n\n/** Fixed owner counter transport. The owner encoder must preserve the provider's full input-token contract. */\nexport function createHostedOrganizationInputTokenCounter(options: {\n readonly endpoint: string;\n readonly apiKey: string;\n /** Explicit provider mapping: Responses counting accepts input/model/tools, while Chat needs its own verified counter. */\n encode(surface: 'responses' | 'chat-completions', request: Readonly<Record<string, unknown>>): unknown;\n}): IHostedOrganizationModelOptions['countInputTokens'] {\n const endpoint = new URL(options.endpoint);\n if ((endpoint.protocol !== 'https:' && !(endpoint.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(endpoint.hostname))) ||\n endpoint.username || endpoint.password || endpoint.search || endpoint.hash || typeof options.encode !== 'function' ||\n typeof options.apiKey !== 'string' || options.apiKey.length === 0 || /[\\r\\n]/u.test(options.apiKey))\n throw new OrganizationRefused('invalid-schema');\n const apiKey = options.apiKey; const encode = options.encode.bind(options);\n return async (surface, body, signal) => {\n const response = await fetch(endpoint, { method: 'POST', redirect: 'error', signal,\n headers: { authorization: `Bearer ${apiKey}`, 'content-type': 'application/json' }, body: JSON.stringify(encode(surface, body)) });\n if (!response.ok || response.body === null) { await response.body?.cancel(); throw new OrganizationRefused('policy-unavailable'); }\n const chunks: Uint8Array[] = []; let size = 0;\n const reader = response.body.getReader();\n try {\n for (;;) { const next = await reader.read(); if (next.done) break; size += next.value.length;\n if (size > 64 * 1024) throw new OrganizationRefused('policy-unavailable'); chunks.push(next.value); }\n } finally { await reader.cancel(); }\n const result = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))) as { input_tokens?: unknown };\n if (!Number.isSafeInteger(result?.input_tokens) || (result.input_tokens as number) < 0)\n throw new OrganizationRefused('policy-unavailable');\n return result.input_tokens as number;\n };\n}\n","import { createHash } from 'node:crypto';\nimport { posix } from 'node:path';\nimport {\n decodeHostedIdentity,\n exactKeys,\n hostedAdmissionError,\n identifier,\n positiveInteger,\n record,\n} from './hosted-runtime-config.js';\nimport { projectHostedSessionCheckpoint } from './hosted-session-checkpoint.js';\nimport type { IInteractiveSessionRecord } from '@robota-sdk/agent-interface-session';\nimport type { IHostedIdentity, IHostedSnapshot } from './hosted-runtime-types.js';\n\nexport interface IHostedCheckpointFile {\n readonly path: string;\n readonly bytes: Uint8Array;\n}\n\nexport interface IHostedFilesystemCheckpoint {\n readonly sourceWorker: string;\n readonly sourceRuntime: string;\n readonly sourceEpoch: number;\n readonly files: readonly IHostedCheckpointFile[];\n readonly session?: IInteractiveSessionRecord;\n}\n\n/** The reference and current identity come from the owner outside the worker, not the manifest. */\nexport function decodeHostedFilesystemCheckpoint(\n contents: Uint8Array,\n reference: IHostedSnapshot,\n current: { readonly identity: IHostedIdentity; readonly epoch: number },\n): IHostedFilesystemCheckpoint {\n if (\n contents.byteLength > 48 * 1024 * 1024 ||\n createHash('sha256').update(contents).digest('hex') !== reference.digest\n )\n throw hostedAdmissionError('filesystem checkpoint digest or size is invalid');\n let raw: Record<string, unknown>;\n try {\n raw = record(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(contents)), 'checkpoint');\n } catch {\n throw hostedAdmissionError('filesystem checkpoint is not valid UTF-8 JSON');\n }\n exactKeys(raw, ['version', 'id', 'identity', 'epoch', 'worker', 'files', ...(raw.version === 2 ? ['session'] : [])], 'checkpoint');\n if ((raw.version !== 1 && raw.version !== 2) || raw.id !== reference.id)\n throw hostedAdmissionError('filesystem checkpoint version or identity does not match');\n const identity = decodeHostedIdentity(raw.identity);\n const sourceEpoch = positiveInteger(raw.epoch, 'checkpoint epoch');\n const sourceWorker = identifier(raw.worker, 'checkpoint worker');\n if (\n ['tenant', 'task', 'rootTask'].some(\n (key) => identity[key as keyof IHostedIdentity] !== current.identity[key as keyof IHostedIdentity],\n ) ||\n identity.runtime === current.identity.runtime ||\n sourceEpoch >= current.epoch\n )\n throw hostedAdmissionError('filesystem checkpoint requires the same task and a fresh identity/epoch');\n if (!Array.isArray(raw.files) || raw.files.length > 1000)\n throw hostedAdmissionError('filesystem checkpoint file inventory is invalid');\n const paths = new Set<string>();\n let total = 0;\n const files = raw.files.map((value): IHostedCheckpointFile => {\n const file = record(value, 'checkpoint file');\n exactKeys(file, ['path', 'base64'], 'checkpoint file');\n const path = identifier(file.path, 'checkpoint file path');\n const first = path.split('/')[0];\n if (\n posix.isAbsolute(path) ||\n posix.normalize(path) !== path ||\n path === '.' ||\n path === '..' ||\n path.startsWith('../') ||\n path.endsWith('/') ||\n path.includes('\\\\') ||\n first === '.home' ||\n first === '.tmp' ||\n paths.has(path)\n )\n throw hostedAdmissionError('filesystem checkpoint path escapes or replaces private state');\n if (typeof file.base64 !== 'string' || file.base64.length > 44 * 1024 * 1024)\n throw hostedAdmissionError('filesystem checkpoint file encoding is invalid');\n const bytes = Buffer.from(file.base64, 'base64');\n total += bytes.byteLength;\n if (bytes.toString('base64') !== file.base64 || total > 32 * 1024 * 1024)\n throw hostedAdmissionError('filesystem checkpoint encoding or byte budget is invalid');\n paths.add(path);\n return Object.freeze({ path, bytes: new Uint8Array(bytes) });\n });\n for (const path of paths) {\n let parent = posix.dirname(path);\n while (parent !== '.') {\n if (paths.has(parent))\n throw hostedAdmissionError('filesystem checkpoint file conflicts with a directory');\n parent = posix.dirname(parent);\n }\n }\n return Object.freeze({ sourceWorker, sourceRuntime: identity.runtime, sourceEpoch, files,\n ...(raw.version === 2 ? { session: projectHostedSessionCheckpoint(raw.session, '/') } : {}),\n });\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport { loadE2BSdk } from './e2b-sdk.js';\nimport {\n decodeHostedIdentity,\n decodeHostedSnapshot,\n hostedAdmissionError,\n identifier,\n positiveInteger,\n} from './hosted-runtime-config.js';\nimport { decodeHostedFilesystemCheckpoint } from './hosted-filesystem-checkpoint.js';\nimport { hostedSessionCheckpointBytes } from './hosted-session-checkpoint.js';\nimport type { IHostedWorkerResumeSession } from './hosted-worker-execution-config.js';\nimport type { IHostedIdentity, IHostedSnapshot } from './hosted-runtime-types.js';\nimport type { Sandbox } from 'e2b/dist/index.mjs';\n\n/** Owner-side input. Sign admission only after this operation returns a verified resource receipt. */\nexport interface IE2BWorkerProvisioningOptions {\n readonly identity: IHostedIdentity;\n readonly epoch: number;\n readonly templateId: string;\n readonly apiKey: string;\n readonly brokerEndpoint: string;\n readonly lifetimeMs: number;\n readonly requestTimeoutMs: number;\n readonly signal: AbortSignal;\n readonly snapshot: IHostedSnapshot | null;\n /** Owner-issued organization binding retained in the provider inventory across broker restarts. */\n readonly organization?: { readonly controlPlane: string; readonly grantId: string };\n /** Bytes fetched from the owner's checkpoint store; never an E2B memory snapshot/template. */\n readonly checkpoint?: Uint8Array;\n}\n\nexport interface IE2BProvisionedWorker {\n readonly resource: string;\n readonly workspaceRoot: string;\n readonly operationId: string;\n readonly resumeSession?: IHostedWorkerResumeSession;\n readonly snapshot: IHostedSnapshot | null;\n release(): Promise<void>;\n}\n\n/** Reconciliation identifiers, without provider error text or credentials. */\nexport class E2BWorkerProvisioningError extends Error {\n constructor(\n readonly outcome: 'allocation-unknown' | 'cleanup-unresolved',\n readonly operationId: string,\n readonly resource?: string,\n ) {\n super(`E2B worker provisioning ${outcome}; owner reconciliation is required`);\n this.name = 'E2BWorkerProvisioningError';\n }\n}\n\n/** Create from a pinned clean baseline, restoring only bounded task files before issuing any authority. */\nexport async function provisionE2BTaskWorker(\n options: IE2BWorkerProvisioningOptions,\n): Promise<IE2BProvisionedWorker> {\n const identity = decodeHostedIdentity(options.identity);\n const epoch = positiveInteger(options.epoch, 'worker epoch');\n const templateId = identifier(options.templateId, 'E2B clean template');\n const snapshot = decodeHostedSnapshot(options.snapshot);\n if ((snapshot === null) !== (options.checkpoint === undefined) || snapshot?.id === templateId)\n throw hostedAdmissionError('worker recovery requires checkpoint bytes and a separate clean template');\n const checkpoint = snapshot === null\n ? undefined\n : decodeHostedFilesystemCheckpoint(options.checkpoint!, snapshot, { identity, epoch });\n let broker: URL;\n try {\n broker = new URL(options.brokerEndpoint);\n } catch {\n throw hostedAdmissionError('worker broker endpoint is invalid');\n }\n if (\n (broker.protocol !== 'https:' && !(broker.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(broker.hostname))) ||\n broker.username || broker.password || broker.search || broker.hash\n )\n throw hostedAdmissionError('worker broker endpoint requires owner-selected TLS or literal loopback');\n const request = {\n apiKey: identifier(options.apiKey, 'E2B management credential'),\n requestTimeoutMs: positiveInteger(options.requestTimeoutMs, 'E2B request timeout', 30_000),\n apiUrl: 'https://api.e2b.app',\n sandboxUrl: 'https://sandbox.e2b.app',\n domain: 'e2b.app',\n debug: false,\n retries: 0,\n };\n const lifetimeMs = positiveInteger(options.lifetimeMs, 'E2B lifetime', 86_400_000);\n const operationId = randomUUID();\n const metadata = {\n ...identity,\n epoch: String(epoch),\n operationId,\n ...(options.organization === undefined ? {} : {\n organizationControlPlane: identifier(options.organization.controlPlane, 'organization control plane'),\n organizationGrant: identifier(options.organization.grantId, 'organization grant'),\n }),\n ...(snapshot === null ? {} : {\n restoreMode: 'filesystem-v1',\n checkpointId: snapshot.id,\n checkpointDigest: snapshot.digest,\n sourceWorker: checkpoint!.sourceWorker,\n sourceRuntime: checkpoint!.sourceRuntime,\n sourceEpoch: String(checkpoint!.sourceEpoch),\n }),\n };\n options.signal.throwIfAborted();\n const { Sandbox } = await loadE2BSdk();\n options.signal.throwIfAborted();\n let sandbox: Sandbox;\n try {\n // Do not abort away the allocation receipt. No authority is issued while allocation is pending.\n sandbox = await Sandbox.create(templateId, {\n ...request,\n timeoutMs: lifetimeMs,\n metadata,\n envs: {},\n allowInternetAccess: false,\n network: { allowPublicTraffic: false, allowOut: [broker.hostname] },\n lifecycle: { onTimeout: 'kill', autoResume: false },\n });\n } catch {\n throw new E2BWorkerProvisioningError('allocation-unknown', operationId);\n }\n let resource: string;\n try {\n resource = identifier(sandbox.sandboxId, 'allocated worker');\n } catch {\n throw new E2BWorkerProvisioningError('allocation-unknown', operationId);\n }\n let releasing: Promise<void> | undefined;\n const release = (): Promise<void> => {\n if (releasing === undefined)\n releasing = Sandbox.kill(resource, request).then(() => undefined).catch(() => {\n throw new E2BWorkerProvisioningError('cleanup-unresolved', operationId, resource);\n });\n return releasing;\n };\n try {\n const info = await Sandbox.getInfo(resource, request).catch(() => {\n throw new E2BWorkerProvisioningError('allocation-unknown', operationId, resource);\n });\n if (info.sandboxId !== resource || Object.entries(metadata).some(([key, value]) => info.metadata[key] !== value))\n throw new E2BWorkerProvisioningError('allocation-unknown', operationId, resource);\n if (resource === checkpoint?.sourceWorker)\n throw hostedAdmissionError('provider returned the checkpoint source instead of a fresh worker');\n if (\n info.templateId !== templateId || info.state !== 'running' ||\n info.lifecycle?.onTimeout !== 'kill' || info.lifecycle.autoResume !== false ||\n info.allowInternetAccess !== false || info.network?.allowPublicTraffic !== false ||\n JSON.stringify(info.network.allowOut ?? []) !== JSON.stringify([broker.hostname]) ||\n (info.volumeMounts?.length ?? 0) !== 0 || info.network.egressProxy !== undefined ||\n Object.keys(info.network.rules ?? {}).length !== 0\n )\n throw hostedAdmissionError('allocated worker ownership, clean template or network posture is invalid');\n options.signal.throwIfAborted();\n // An atomic new directory cannot inherit checkpoint symlinks or old user/authority state.\n const created = await sandbox.commands.run(`umask 077; mktemp -d \"\\${TMPDIR:-/tmp}/agent-task-${operationId}-XXXXXXXXXX\"`, {\n cwd: '/', envs: {}, timeoutMs: options.requestTimeoutMs, requestTimeoutMs: options.requestTimeoutMs,\n });\n if (created.exitCode !== 0 || typeof created.stdout !== 'string')\n throw hostedAdmissionError('fresh worker workspace creation failed');\n const workspaceRoot = created.stdout.trim();\n if (\n !/^\\/[A-Za-z0-9._/-]+$/u.test(workspaceRoot) ||\n posix.normalize(workspaceRoot) !== workspaceRoot ||\n !new RegExp(`^agent-task-${operationId}-[A-Za-z0-9]{10}$`, 'u').test(posix.basename(workspaceRoot))\n )\n throw hostedAdmissionError('fresh worker workspace receipt is invalid');\n for (const file of checkpoint?.files ?? []) {\n options.signal.throwIfAborted();\n const path = posix.join(workspaceRoot, file.path);\n await sandbox.files.write(path, file.bytes.slice().buffer as ArrayBuffer, {\n requestTimeoutMs: options.requestTimeoutMs,\n });\n const restored = await sandbox.files.read(path, { format: 'bytes', requestTimeoutMs: options.requestTimeoutMs });\n if (!Buffer.from(restored).equals(Buffer.from(file.bytes)))\n throw hostedAdmissionError('restored filesystem checkpoint bytes do not match');\n }\n let resumeSession: IHostedWorkerResumeSession | undefined;\n if (checkpoint?.session !== undefined) {\n options.signal.throwIfAborted();\n const session = { ...checkpoint.session, cwd: workspaceRoot };\n const bytes = hostedSessionCheckpointBytes(session);\n const path = posix.join(workspaceRoot, '.home', '.checkpoint-sessions', `${session.id}.json`);\n await sandbox.files.write(path, Uint8Array.from(bytes).buffer, { requestTimeoutMs: options.requestTimeoutMs });\n const restored = await sandbox.files.read(path, { format: 'bytes', requestTimeoutMs: options.requestTimeoutMs });\n if (!Buffer.from(restored).equals(bytes))\n throw hostedAdmissionError('restored conversation checkpoint bytes do not match');\n resumeSession = Object.freeze({ id: session.id, path, digest: createHash('sha256').update(bytes).digest('hex') });\n }\n options.signal.throwIfAborted();\n return Object.freeze({ resource, workspaceRoot, operationId, snapshot, release,\n ...(resumeSession === undefined ? {} : { resumeSession }),\n });\n } catch (error) {\n if (error instanceof E2BWorkerProvisioningError && error.outcome === 'allocation-unknown') throw error;\n await release();\n if (options.signal.aborted) options.signal.throwIfAborted();\n if (error instanceof Error && error.message.startsWith('Hosted runtime admission refused:')) throw error;\n throw hostedAdmissionError('fresh worker provisioning or filesystem restoration failed');\n }\n}\n","import {\n createAccessTokenVerifier,\n parsePublicHttpsUrl,\n} from '@robota-sdk/agent-transport/node';\nimport type { IAccessTokenVerifierDeps } from '@robota-sdk/agent-transport/node';\nimport type {\n HostedOrganizationControl,\n IHostedOrganizationWorker,\n} from '../hosted-organization-control.js';\n\nexport interface IDesktopBinding {\n readonly id: string;\n readonly user: string;\n readonly client: string;\n readonly session: string;\n readonly worker: IHostedOrganizationWorker;\n}\nexport class DesktopRefused extends Error {\n constructor(readonly reason: string) {\n super(`Remote desktop refused: ${reason}`);\n }\n}\nexport interface IDesktopProof {\n readonly binding: IDesktopBinding;\n readonly jti: string;\n readonly expiresAt: number;\n readonly credentialExpiresAt: number;\n}\nexport interface IDesktopAuthorizationOptions {\n readonly publicUrl: string;\n readonly issuer: string;\n readonly control: HostedOrganizationControl;\n /** Owner-selected identities and sessions, never a caller's registry. */\n readonly bindings: readonly IDesktopBinding[];\n readonly verifierDeps?: IAccessTokenVerifierDeps;\n readonly now?: () => number;\n}\nexport function desktopBindingKey(binding: IDesktopBinding): string {\n return JSON.stringify([\n binding.id,\n binding.user,\n binding.client,\n binding.session,\n binding.worker.resource,\n binding.worker.grantId,\n binding.worker.epoch,\n binding.worker.identity.tenant,\n binding.worker.identity.task,\n binding.worker.identity.rootTask,\n binding.worker.identity.actor,\n binding.worker.identity.runtime,\n ]);\n}\n/** A freshly verified issuer credential still needs current company authority and exact session ownership. */\nexport class HostedDesktopAuthorization {\n readonly url: URL;\n private readonly now: () => number;\n private readonly bindings: readonly IDesktopBinding[];\n constructor(private readonly options: IDesktopAuthorizationOptions) {\n this.url = parsePublicHttpsUrl(options.publicUrl, 'Desktop runtime');\n parsePublicHttpsUrl(options.issuer, 'Desktop issuer');\n this.now = options.now ?? Date.now;\n this.bindings = options.bindings.map((binding) => {\n const copy = structuredClone(binding);\n Object.freeze(copy.worker.identity);\n Object.freeze(copy.worker);\n return Object.freeze(copy);\n });\n if (\n options.bindings.length === 0 ||\n options.bindings.length > 100 ||\n options.bindings.some((binding) =>\n [binding.id, binding.user, binding.client, binding.session].some(\n (value) =>\n typeof value !== 'string' ||\n value.length === 0 ||\n value.length > 256 ||\n /[\\r\\n]/u.test(value),\n ),\n ) ||\n new Set(options.bindings.map((binding) => binding.id)).size !== options.bindings.length\n )\n throw new DesktopRefused('owner-bindings');\n }\n binding(id: string): IDesktopBinding {\n const binding = this.bindings.find((entry) => entry.id === id);\n if (!binding) throw new DesktopRefused('owner-binding');\n return binding;\n }\n async verify(\n token: string,\n binding: IDesktopBinding,\n operator = false,\n signal?: AbortSignal,\n ): Promise<IDesktopProof> {\n signal?.throwIfAborted();\n if (!this.bindings.some((entry) => desktopBindingKey(entry) === desktopBindingKey(binding)))\n throw new DesktopRefused('owner-binding');\n // Pairing and readiness do not extend stale issuer keys during an outage.\n const verifier = createAccessTokenVerifier(\n {\n issuer: this.options.issuer,\n resource: operator ? `${this.url.href.replace(/\\/$/u, '')}/approval` : this.url.href,\n algorithms: ['EdDSA', 'ES256', 'RS256'],\n allowedSubjects: [binding.user],\n requiredScopes: operator ? ['desktop:approve'] : ['desktop:pair', 'desktop:drive'],\n },\n this.options.verifierDeps,\n );\n const verdict = await verifier.verify(token);\n if (!verdict.admitted) throw new DesktopRefused(verdict.refusal);\n // Decode only AFTER signature/issuer/audience/subject/scope verification.\n const claims = JSON.parse(\n Buffer.from(token.split('.')[1]!, 'base64url').toString('utf8'),\n ) as Record<string, unknown>;\n const now = this.now();\n if (\n typeof claims.iat !== 'number' ||\n !Number.isSafeInteger(claims.iat) ||\n typeof claims.exp !== 'number' ||\n !Number.isSafeInteger(claims.exp) ||\n claims.iat * 1000 > now ||\n claims.exp * 1000 <= now ||\n claims.exp - claims.iat > 120 ||\n (claims.nbf !== undefined &&\n (typeof claims.nbf !== 'number' ||\n !Number.isSafeInteger(claims.nbf) ||\n claims.nbf * 1000 > now)) ||\n typeof claims.jti !== 'string' ||\n !/^[A-Za-z0-9_-]{8,256}$/u.test(claims.jti)\n )\n throw new DesktopRefused('short-lived-credential');\n if (\n claims.sub !== binding.user ||\n claims.client_id !== binding.client ||\n claims.tenant !== binding.worker.identity.tenant ||\n claims.task !== binding.worker.identity.task ||\n claims.session !== binding.session ||\n claims.workload !== binding.worker.identity.runtime ||\n claims.epoch !== binding.worker.epoch\n )\n throw new DesktopRefused('session-ownership');\n signal?.throwIfAborted();\n const grant = await this.options.control.admit(binding.worker, signal);\n signal?.throwIfAborted();\n return {\n binding,\n jti: claims.jti,\n credentialExpiresAt: claims.exp * 1000,\n expiresAt: Math.min(claims.exp * 1000, grant.expiresAt, now + 60_000),\n };\n }\n async current(binding: IDesktopBinding, signal?: AbortSignal): Promise<void> {\n if (!this.bindings.some((entry) => desktopBindingKey(entry) === desktopBindingKey(binding)))\n throw new DesktopRefused('owner-binding');\n await this.options.control.admit(binding.worker, signal);\n }\n}\n","import { createHash, randomBytes, randomUUID } from 'node:crypto';\nimport {\n closeSync,\n constants,\n existsSync,\n fstatSync,\n fsyncSync,\n lstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmdirSync,\n writeFileSync,\n unlinkSync,\n} from 'node:fs';\nimport { isAbsolute, join } from 'node:path';\nimport type {\n IOrganizationLedgerAnchor,\n IOrganizationLedgerHead,\n} from '@robota-sdk/agent-organization-host';\nimport { DesktopRefused } from './authorization.js';\n\ninterface IConnection {\n generation: number;\n access: string;\n approval: string | null;\n expiresAt: number;\n connected: boolean;\n}\ninterface IState {\n version: 1;\n revision: number;\n spent: Record<string, number>;\n connections: Record<string, IConnection>;\n}\nexport interface IDesktopAccess {\n readonly key: string;\n readonly generation: number;\n readonly token: string;\n readonly approvalToken: string | null;\n readonly expiresAt: number;\n}\nconst digest = (value: string): string => createHash('sha256').update(value).digest('hex');\nconst sameHead = (a: IOrganizationLedgerHead | undefined, b: IOrganizationLedgerHead): boolean =>\n a?.version === b.version &&\n a.ledger === b.ledger &&\n a.revision === b.revision &&\n a.digest === b.digest;\n\n/** Replay and connection replacement survive restart; independent custody rejects restored authority. */\nexport class HostedDesktopAuthorityStore {\n private readonly directory: string;\n private readonly file: string;\n private readonly lock: string;\n constructor(\n options: { directory: string; anchor: IOrganizationLedgerAnchor; create?: boolean },\n private readonly now: () => number = Date.now,\n ) {\n this.anchor = options.anchor;\n if (!isAbsolute(options.directory)) throw new DesktopRefused('store-unavailable');\n this.directory = realpathSync(options.directory);\n const stat = lstatSync(this.directory);\n if (\n !stat.isDirectory() ||\n (stat.mode & 0o077) !== 0 ||\n (process.getuid !== undefined && stat.uid !== process.getuid())\n )\n throw new DesktopRefused('store-unavailable');\n this.file = join(this.directory, 'desktop-authority.json');\n this.lock = join(this.directory, 'desktop-authority.lock');\n if (options.create === true) {\n if (existsSync(this.file) || this.anchor.read() !== undefined)\n throw new DesktopRefused('store-unavailable');\n this.locked(() =>\n this.write(undefined, { version: 1, revision: 1, spent: {}, connections: {} }),\n );\n }\n this.read();\n }\n private readonly anchor: IOrganizationLedgerAnchor;\n private head(state: IState): IOrganizationLedgerHead {\n return {\n version: 1,\n ledger: this.anchor.ledger,\n revision: state.revision,\n digest: digest(JSON.stringify(state)),\n };\n }\n private read(): IState {\n const fd = openSync(\n this.file,\n constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,\n );\n try {\n const stat = fstatSync(fd);\n if (\n !stat.isFile() ||\n stat.size > 2 * 1024 * 1024 ||\n (stat.mode & 0o077) !== 0 ||\n (process.getuid !== undefined && stat.uid !== process.getuid())\n )\n throw new DesktopRefused('store-unavailable');\n const state = JSON.parse(readFileSync(fd, 'utf8')) as IState;\n const head = this.anchor.read();\n if (\n state.version !== 1 ||\n !Number.isSafeInteger(state.revision) ||\n state.revision < 1 ||\n !state.spent ||\n !state.connections ||\n !sameHead(head, this.head(state))\n )\n throw new DesktopRefused('store-unavailable');\n return state;\n } finally {\n closeSync(fd);\n }\n }\n private locked<T>(work: () => T): T {\n mkdirSync(this.lock, { mode: 0o700 });\n try {\n return work();\n } finally {\n rmdirSync(this.lock);\n }\n }\n private write(expected: IState | undefined, state: IState): void {\n const temporary = join(this.directory, `desktop-${randomUUID()}.tmp`);\n try {\n const fd = openSync(temporary, 'wx', 0o600);\n try {\n writeFileSync(fd, JSON.stringify(state));\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n const next = this.head(state);\n this.anchor.compareAndSet(expected === undefined ? undefined : this.head(expected), next);\n if (!sameHead(this.anchor.read(), next)) throw new DesktopRefused('store-unavailable');\n renameSync(temporary, this.file);\n const directory = openSync(this.directory, constants.O_RDONLY);\n try {\n fsyncSync(directory);\n } finally {\n closeSync(directory);\n }\n } finally {\n if (existsSync(temporary)) unlinkSync(temporary);\n }\n }\n private change<T>(update: (state: IState) => T): T {\n return this.locked(() => {\n const before = this.read();\n const next = structuredClone(before);\n const result = update(next);\n next.revision++;\n this.write(before, next);\n return result;\n });\n }\n pair(\n key: string,\n proofs: readonly { readonly id: string; readonly expiresAt: number }[],\n expiresAt: number,\n operator: boolean,\n ): IDesktopAccess {\n const token = randomBytes(32).toString('base64url');\n const approvalToken = operator ? randomBytes(32).toString('base64url') : null;\n return this.change((state) => {\n for (const [id, expiry] of Object.entries(state.spent))\n if (expiry <= this.now()) delete state.spent[id];\n if (\n expiresAt <= this.now() ||\n proofs.length === 0 ||\n new Set(proofs.map((proof) => proof.id)).size !== proofs.length ||\n proofs.some(\n (proof) => !Number.isSafeInteger(proof.expiresAt) || proof.expiresAt < expiresAt,\n ) ||\n Object.keys(state.spent).length + proofs.length > 4096 ||\n proofs.some((proof) => state.spent[digest(proof.id)] !== undefined)\n )\n throw new DesktopRefused('replayed-pairing');\n const hashed = digest(key);\n if (state.connections[hashed] === undefined && Object.keys(state.connections).length >= 100)\n throw new DesktopRefused('connection-capacity');\n const generation = (state.connections[hashed]?.generation ?? 0) + 1;\n state.connections[hashed] = {\n generation,\n access: digest(token),\n approval: approvalToken === null ? null : digest(approvalToken),\n expiresAt,\n connected: false,\n };\n for (const proof of proofs) state.spent[digest(proof.id)] = proof.expiresAt;\n return { key, generation, token, approvalToken, expiresAt };\n });\n }\n authorize(key: string, generation: number, token: string, operator = false): void {\n const entry = this.read().connections[digest(key)];\n if (\n !entry ||\n entry.generation !== generation ||\n entry.expiresAt <= this.now() ||\n (operator ? entry.approval : entry.access) !== digest(token)\n )\n throw new DesktopRefused('withdrawn-connection');\n }\n connect(key: string, generation: number, token: string): void {\n this.authorize(key, generation, token);\n this.change((state) => {\n const entry = state.connections[digest(key)]!;\n if (entry.generation !== generation || entry.expiresAt <= this.now() || entry.connected)\n throw new DesktopRefused('replayed-connection');\n entry.connected = true;\n });\n }\n approveOnce(key: string, generation: number, token: string, prompt: string): void {\n this.authorize(key, generation, token, true);\n this.change((state) => {\n const entry = state.connections[digest(key)]!;\n if (\n entry.generation !== generation ||\n entry.expiresAt <= this.now() ||\n entry.approval !== digest(token)\n )\n throw new DesktopRefused('withdrawn-connection');\n const nonce = digest(`approval:${key}:${prompt}`);\n if (state.spent[nonce] !== undefined) throw new DesktopRefused('replayed-approval');\n if (Object.keys(state.spent).length >= 4096) throw new DesktopRefused('approval-capacity');\n // An uncertain permission response cannot become permission to send it again after reconnect.\n state.spent[nonce] = Number.MAX_SAFE_INTEGER;\n });\n }\n revoke(key: string): void {\n this.change((state) => {\n const entry = state.connections[digest(key)];\n if (entry) {\n entry.generation++;\n entry.expiresAt = 0;\n }\n });\n }\n}\n","import { createHash } from 'node:crypto';\nimport { WebSocket } from 'ws';\nimport type {\n HostedOrganizationControl,\n IHostedOrganizationWorker,\n} from '../hosted-organization-control.js';\nimport { DesktopRefused } from './authorization.js';\n\nexport const DESKTOP_FRAME_BYTES = 128 * 1024;\nconst READS = new Set([\n 'get-messages',\n 'get-status',\n 'get-context',\n 'get-history',\n 'get-prompts',\n 'get-pending',\n 'get-executing',\n 'get-execution-workspace',\n 'get-execution-detail',\n 'project-status',\n 'project-diff',\n 'project-memory',\n 'get-usage-report',\n 'get-background-tasks',\n 'list-models',\n 'get-agent-definitions',\n]);\nconst hidden = new Set([\n 'sessions',\n 'session_list',\n 'session_renamed_in_list',\n 'session_deleted',\n 'ui_intent',\n 'settings',\n 'commands',\n]);\nexport function desktopPromptDigest(event: Record<string, unknown>): string {\n return createHash('sha256')\n .update('robota/desktop-permission/v1\\0')\n .update(JSON.stringify(event))\n .digest('hex');\n}\n/** One owner-held carrier connection pins the worker's session across desktop reconnects. */\nexport class HostedDesktopWorkerPort {\n readonly session: string;\n private readonly listeners = new Set<(frame: Record<string, unknown>) => void>();\n private readonly ended = new Set<() => void>();\n private readonly pending = new Map<string, { digest: string; event: Record<string, unknown> }>();\n private constructor(\n private readonly socket: WebSocket,\n session: string,\n readonly worker: IHostedOrganizationWorker,\n ) {\n this.session = session;\n socket.on('message', (bytes, binary) => {\n try {\n if (binary || Buffer.byteLength(String(bytes)) > DESKTOP_FRAME_BYTES)\n throw new DesktopRefused('worker-frame');\n const frame = JSON.parse(String(bytes)) as Record<string, unknown>;\n if (!frame || typeof frame !== 'object' || typeof frame.type !== 'string')\n throw new DesktopRefused('worker-frame');\n if (\n (frame.type === 'session_status' &&\n (frame.status as { sessionId?: unknown })?.sessionId !== this.session) ||\n frame.type === 'session_switched'\n )\n throw new DesktopRefused('worker-session-changed');\n if (hidden.has(frame.type)) return;\n if (frame.type === 'permission_request') {\n const event = frame.event as Record<string, unknown>;\n if (\n !event ||\n typeof event.id !== 'string' ||\n event.id.length > 256 ||\n typeof event.toolName !== 'string' ||\n this.pending.size >= 32\n )\n throw new DesktopRefused('worker-prompt');\n this.pending.set(event.id, { digest: desktopPromptDigest(event), event });\n }\n if (frame.type === 'prompt_resolved')\n this.pending.delete((frame.event as { id: string })?.id);\n for (const listener of this.listeners) listener(frame);\n } catch {\n this.close();\n }\n });\n socket.on('error', () => this.close());\n socket.on('close', () => {\n for (const listener of this.ended) listener();\n this.listeners.clear();\n this.ended.clear();\n this.pending.clear();\n });\n }\n static async connect(options: {\n readonly endpoint: string;\n readonly token: string;\n readonly worker: IHostedOrganizationWorker;\n readonly control: HostedOrganizationControl;\n readonly session?: string;\n readonly signal?: AbortSignal;\n }): Promise<HostedDesktopWorkerPort> {\n const url = new URL(options.endpoint);\n if (\n url.protocol !== 'ws:' ||\n !['127.0.0.1', '[::1]'].includes(url.hostname) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash ||\n url.pathname !== '/' ||\n typeof options.token !== 'string' ||\n options.token.length < 16 ||\n options.token.length > 8192\n )\n throw new DesktopRefused('owner-worker-endpoint');\n const signal = AbortSignal.any([\n AbortSignal.timeout(5000),\n ...(options.signal ? [options.signal] : []),\n ]);\n await options.control.admit(options.worker, signal);\n url.searchParams.set('token', options.token);\n const socket = new WebSocket(url, {\n maxPayload: DESKTOP_FRAME_BYTES,\n handshakeTimeout: 5000,\n followRedirects: false,\n });\n try {\n const session = await new Promise<string>((resolve, reject) => {\n let buffered = 0;\n const fail = (): void => reject(new DesktopRefused('worker-unavailable'));\n const receive = (data: unknown, binary: boolean): void => {\n try {\n buffered += Buffer.byteLength(String(data));\n if (binary || buffered > 1024 * 1024) return fail();\n const frame = JSON.parse(String(data)) as {\n type?: string;\n status?: { sessionId?: unknown };\n };\n if (frame.type !== 'session_status') return;\n const id = frame.status?.sessionId;\n if (\n typeof id !== 'string' ||\n id.length === 0 ||\n id.length > 256 ||\n (options.session !== undefined && id !== options.session)\n )\n return fail();\n resolve(id);\n } catch {\n fail();\n }\n };\n socket.once('open', () => socket.send(JSON.stringify({ type: 'get-status' })));\n socket.on('message', receive);\n socket.once('error', fail);\n socket.once('close', fail);\n signal.addEventListener('abort', fail, { once: true });\n const detach = (): void => {\n socket.off('message', receive);\n socket.off('error', fail);\n socket.off('close', fail);\n signal.removeEventListener('abort', fail);\n };\n socket.once('close', detach);\n // Detach discovery before the permanent receiver is installed.\n socket.on('message', function done(data) {\n try {\n if (JSON.parse(String(data)).type === 'session_status') {\n detach();\n socket.off('message', done);\n }\n } catch {\n /* Discovery refuses malformed frames through its receiver above. */\n }\n });\n });\n signal.throwIfAborted();\n await options.control.admit(options.worker, signal);\n signal.throwIfAborted();\n return new HostedDesktopWorkerPort(\n socket,\n session,\n Object.freeze(structuredClone(options.worker)),\n );\n } catch {\n socket.terminate();\n throw new DesktopRefused('worker-unavailable');\n }\n }\n onFrame(listener: (frame: Record<string, unknown>) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n onClose(listener: () => void): () => void {\n this.ended.add(listener);\n return () => this.ended.delete(listener);\n }\n ready(): void {\n if (this.socket.readyState !== WebSocket.OPEN) throw new DesktopRefused('worker-unavailable');\n }\n send(frame: Record<string, unknown>): Record<string, unknown> | undefined {\n this.ready();\n const bytes = JSON.stringify(frame);\n if (Buffer.byteLength(bytes) > DESKTOP_FRAME_BYTES || this.socket.bufferedAmount > 1024 * 1024)\n throw new DesktopRefused('frame-capacity');\n if (frame.type === 'get-commands') return { type: 'commands', commands: [], skills: [] };\n if (frame.type === 'list-sessions' && typeof frame.requestId === 'string')\n return {\n type: 'sessions',\n requestId: frame.requestId,\n listing: { currentSessionId: this.session, sessions: [], unreadableSessionIds: [] },\n };\n if (frame.type === 'submit') {\n if (\n typeof frame.prompt !== 'string' ||\n /^\\s*\\//u.test(frame.prompt) ||\n Object.keys(frame).some((key) => !['type', 'prompt'].includes(key))\n )\n throw new DesktopRefused('remote-command');\n } else if (\n !READS.has(String(frame.type)) &&\n frame.type !== 'abort' &&\n frame.type !== 'ask-response'\n )\n throw new DesktopRefused('remote-capability');\n if ('sessionId' in frame || 'driverId' in frame || 'tenant' in frame || 'task' in frame)\n throw new DesktopRefused('remote-ownership');\n this.socket.send(bytes);\n return undefined;\n }\n prompt(id: string, digest: string): void {\n if (this.pending.get(id)?.digest !== digest) throw new DesktopRefused('stale-approval');\n }\n approve(id: string, digest: string, allow: boolean): void {\n this.ready();\n this.prompt(id, digest);\n this.pending.delete(id);\n this.socket.send(JSON.stringify({ type: 'permission-response', id, result: allow }));\n }\n close(): void {\n this.socket.terminate();\n }\n}\n","import { ServerResponse } from 'node:http';\nimport { isIP } from 'node:net';\nimport { WebSocket, WebSocketServer } from 'ws';\nimport { bearerCredential, createBearerResourceServer } from '@robota-sdk/agent-transport/node';\nimport { DesktopRefused, desktopBindingKey } from './authorization.js';\nimport { DESKTOP_FRAME_BYTES } from './worker-port.js';\nimport type { HostedDesktopAuthorization, IDesktopBinding } from './authorization.js';\nimport type { HostedDesktopAuthorityStore, IDesktopAccess } from './authority-store.js';\nimport type { HostedDesktopWorkerPort } from './worker-port.js';\nimport type { IncomingMessage, Server } from 'node:http';\nimport type { Duplex } from 'node:stream';\n\ninterface IPaired {\n binding: IDesktopBinding;\n access: IDesktopAccess;\n jwt: string;\n operatorJwt?: string;\n port: HostedDesktopWorkerPort;\n}\nconst uniqueHeaders = new Set([\n 'authorization',\n 'x-desktop-operator-authorization',\n 'host',\n 'origin',\n 'x-forwarded-for',\n 'x-forwarded-host',\n 'x-forwarded-proto',\n]);\nconst address = (value: string | undefined): string =>\n (value ?? '').replace(/^::ffff:/u, '').toLowerCase();\n\n/** Outside workers: owns scoped ingress and a separate operator channel to one pinned task session. */\nexport class HostedDesktopGateway {\n private readonly wss = new WebSocketServer({ noServer: true, maxPayload: DESKTOP_FRAME_BYTES });\n private readonly paired = new Map<string, IPaired>();\n private readonly active = new Map<WebSocket, IPaired>();\n private readonly names;\n private readonly proxies: ReadonlySet<string>;\n private readonly interval: number;\n private closed = false;\n private readonly upgrades = new Set<Duplex>();\n constructor(\n private readonly options: {\n readonly server: Server;\n readonly authorization: HostedDesktopAuthorization;\n readonly store: HostedDesktopAuthorityStore;\n readonly ports: ReadonlyMap<string, HostedDesktopWorkerPort>;\n readonly trustedProxies?: readonly string[];\n readonly policyIntervalMs?: number;\n },\n ) {\n this.interval = options.policyIntervalMs ?? 1000;\n if (\n !Number.isSafeInteger(this.interval) ||\n this.interval < 100 ||\n this.interval > 5000 ||\n (options.trustedProxies ?? []).some((ip) => isIP(ip) === 0)\n )\n throw new DesktopRefused('gateway-configuration');\n this.proxies = new Set((options.trustedProxies ?? []).map(address));\n this.names = createBearerResourceServer({\n publicUrl: options.authorization.url.href,\n label: 'Desktop runtime',\n trustedProxies: options.trustedProxies,\n });\n for (const [id, port] of options.ports) {\n const binding = options.authorization.binding(id);\n if (\n binding.session !== port.session ||\n JSON.stringify(binding.worker) !== JSON.stringify(port.worker)\n )\n throw new DesktopRefused('owner-worker-binding');\n port.ready();\n }\n options.server.on('request', this.request);\n options.server.on('upgrade', this.upgrade);\n }\n private boundary(req: IncomingMessage, res: ServerResponse): boolean {\n const seen = new Set<string>();\n for (let index = 0; index < req.rawHeaders.length; index += 2) {\n const name = req.rawHeaders[index]!.toLowerCase();\n if (uniqueHeaders.has(name) && seen.has(name)) {\n res.writeHead(403).end();\n return false;\n }\n seen.add(name);\n }\n const forwarded = [...seen].some((name) => name.startsWith('x-forwarded-'));\n const trusted = this.proxies.has(address(req.socket.remoteAddress));\n if (\n (forwarded && !trusted) ||\n (!(req.socket as { encrypted?: boolean }).encrypted &&\n (!trusted || req.headers['x-forwarded-proto'] !== 'https')) ||\n (forwarded &&\n (req.headers['x-forwarded-proto'] !== 'https' ||\n req.headers['x-forwarded-host'] !== this.names.url.host))\n ) {\n res.writeHead(403).end();\n return false;\n }\n return this.names.checkNames(req, res);\n }\n private async bounded<T>(work: (signal: AbortSignal) => Promise<T>): Promise<T> {\n const abort = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work(abort.signal),\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n abort.abort();\n reject(new DesktopRefused('authority-timeout'));\n }, 5000);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n abort.abort();\n }\n }\n private async body(req: IncomingMessage): Promise<Record<string, unknown>> {\n const buffers: Buffer[] = [];\n let length = 0;\n for await (const chunk of req) {\n const buffer = Buffer.from(chunk as Uint8Array);\n length += buffer.length;\n if (length > 8192) throw new DesktopRefused('request-capacity');\n buffers.push(buffer);\n }\n const value = JSON.parse(Buffer.concat(buffers).toString('utf8')) as Record<string, unknown>;\n if (!value || typeof value !== 'object' || Array.isArray(value))\n throw new DesktopRefused('request-shape');\n return value;\n }\n private readonly request = (req: IncomingMessage, res: ServerResponse): void => {\n void this.handle(req, res).catch(() => {\n if (!res.headersSent) res.writeHead(403);\n res.end();\n });\n };\n private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n if (this.closed || !this.boundary(req, res)) return;\n if (\n req.method !== 'POST' ||\n ![\n `${this.names.url.pathname.replace(/\\/$/u, '')}/pair`,\n `${this.names.url.pathname.replace(/\\/$/u, '')}/approval`,\n ].includes(req.url ?? '')\n ) {\n res.writeHead(404).end();\n return;\n }\n const timer = setTimeout(() => req.destroy(), 5000);\n try {\n const body = await this.body(req);\n if (req.url?.endsWith('/pair')) {\n if (Object.keys(body).join(',') !== 'binding' || typeof body.binding !== 'string')\n throw new DesktopRefused('request-shape');\n const binding = this.options.authorization.binding(body.binding);\n const port = this.options.ports.get(binding.id);\n if (!port) throw new DesktopRefused('worker-unavailable');\n port.ready();\n const jwt = bearerCredential(req.headers.authorization);\n if (!jwt) throw new DesktopRefused('missing-token');\n const operatorJwt = bearerCredential(\n req.headers['x-desktop-operator-authorization'] as string | undefined,\n );\n if (req.headers['x-desktop-operator-authorization'] !== undefined && !operatorJwt)\n throw new DesktopRefused('operator-token');\n const { drive, operator } = await this.bounded(async (signal) => {\n const drive = await this.options.authorization.verify(jwt, binding, false, signal);\n const operator =\n operatorJwt === undefined\n ? undefined\n : await this.options.authorization.verify(operatorJwt, binding, true, signal);\n signal.throwIfAborted();\n return { drive, operator };\n });\n if (req.aborted || res.destroyed || this.closed)\n throw new DesktopRefused('connection-withdrawn');\n const key = desktopBindingKey(binding);\n const access = this.options.store.pair(\n key,\n [drive, ...(operator ? [operator] : [])].map((proof) => ({\n id: proof.jti,\n expiresAt: proof.credentialExpiresAt,\n })),\n Math.min(drive.expiresAt, operator?.expiresAt ?? drive.expiresAt),\n operator !== undefined,\n );\n this.paired.set(binding.id, { binding, access, jwt, operatorJwt, port });\n for (const [socket, previous] of this.active)\n if (previous.binding.id === binding.id) socket.terminate();\n res.setHeader('cache-control', 'no-store');\n res.setHeader('content-type', 'application/json');\n res.end(\n JSON.stringify({\n binding: binding.id,\n generation: access.generation,\n token: access.token,\n approvalToken: access.approvalToken,\n expiresAt: access.expiresAt,\n session: binding.session,\n }),\n );\n } else {\n if (\n Object.keys(body).sort().join(',') !== 'allow,binding,digest,generation,id' ||\n typeof body.binding !== 'string' ||\n !Number.isSafeInteger(body.generation) ||\n typeof body.id !== 'string' ||\n typeof body.digest !== 'string' ||\n !/^[a-f0-9]{64}$/u.test(body.digest) ||\n typeof body.allow !== 'boolean'\n )\n throw new DesktopRefused('request-shape');\n const pair = this.paired.get(body.binding);\n const token = bearerCredential(req.headers.authorization);\n if (!pair || pair.access.generation !== body.generation || !token || !pair.operatorJwt)\n throw new DesktopRefused('operator-token');\n this.options.store.authorize(pair.access.key, pair.access.generation, token, true);\n await this.bounded((signal) =>\n this.options.authorization.verify(pair.operatorJwt!, pair.binding, true, signal),\n );\n if (req.aborted || res.destroyed || this.closed)\n throw new DesktopRefused('connection-withdrawn');\n pair.port.prompt(body.id, body.digest);\n this.options.store.approveOnce(pair.access.key, pair.access.generation, token, body.digest);\n pair.port.approve(body.id, body.digest, body.allow);\n res.writeHead(204).end();\n }\n } finally {\n clearTimeout(timer);\n }\n }\n private readonly upgrade = (req: IncomingMessage, socket: Duplex, head: Buffer): void => {\n this.upgrades.add(socket);\n socket.once('close', () => this.upgrades.delete(socket));\n socket.once('error', () => socket.destroy());\n const res = new ServerResponse(req);\n res.assignSocket(socket as import('node:net').Socket);\n if (!this.boundary(req, res)) {\n res.on('finish', () => socket.destroy());\n return;\n }\n res.detachSocket(socket as import('node:net').Socket);\n void this.connect(req, socket, head).catch(() => {\n socket.end('HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n', () =>\n socket.destroy(),\n );\n });\n };\n private async connect(req: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {\n if (this.closed) throw new DesktopRefused('gateway-closed');\n const url = new URL(req.url!, this.names.url);\n if (\n req.method !== 'GET' ||\n url.pathname !== `${this.names.url.pathname.replace(/\\/$/u, '')}/connect` ||\n [...url.searchParams.keys()].sort().join(',') !== 'binding,generation'\n )\n throw new DesktopRefused('connection-shape');\n const pair = this.paired.get(url.searchParams.get('binding')!);\n const generation = Number(url.searchParams.get('generation'));\n const token = bearerCredential(req.headers.authorization);\n if (\n !pair ||\n !token ||\n !Number.isSafeInteger(generation) ||\n generation !== pair.access.generation\n )\n throw new DesktopRefused('withdrawn-connection');\n this.options.store.authorize(pair.access.key, generation, token);\n await this.bounded((signal) =>\n this.options.authorization.verify(pair.jwt, pair.binding, false, signal),\n );\n if (socket.destroyed || this.closed) throw new DesktopRefused('connection-withdrawn');\n pair.port.ready();\n this.options.store.connect(pair.access.key, generation, token);\n this.wss.handleUpgrade(req, socket, head, (ws) => this.attach(ws, pair, token));\n }\n private attach(ws: WebSocket, pair: IPaired, token: string): void {\n this.active.set(ws, pair);\n let checking = false;\n let queue = Promise.resolve();\n let queued = 0;\n const withdraw = (): void => ws.terminate();\n const validate = async (): Promise<void> => {\n this.options.store.authorize(pair.access.key, pair.access.generation, token);\n await this.bounded((signal) =>\n this.options.authorization.verify(pair.jwt, pair.binding, false, signal),\n );\n this.options.store.authorize(pair.access.key, pair.access.generation, token);\n };\n const timer = setInterval(() => {\n if (checking) return;\n checking = true;\n void validate()\n .catch(withdraw)\n .finally(() => {\n checking = false;\n });\n }, this.interval);\n timer.unref();\n const removeFrames = pair.port.onFrame((frame) => {\n try {\n this.options.store.authorize(pair.access.key, pair.access.generation, token);\n if (ws.readyState !== WebSocket.OPEN || ws.bufferedAmount > 1024 * 1024)\n throw new DesktopRefused('delivery-capacity');\n ws.send(JSON.stringify(frame));\n } catch {\n withdraw();\n }\n });\n const removeClose = pair.port.onClose(withdraw);\n ws.on('message', (data, binary) => {\n if (binary || ++queued > 16) {\n withdraw();\n return;\n }\n queue = queue\n .then(async () => {\n await validate();\n if (ws.readyState !== WebSocket.OPEN) return;\n const frame = JSON.parse(String(data)) as Record<string, unknown>;\n const response = pair.port.send(frame);\n if (response) ws.send(JSON.stringify(response));\n })\n .catch(withdraw)\n .finally(() => {\n queued--;\n });\n });\n ws.on('error', withdraw);\n ws.once('close', () => {\n clearInterval(timer);\n removeFrames();\n removeClose();\n this.active.delete(ws);\n });\n pair.port.send({ type: 'get-messages' });\n pair.port.send({ type: 'get-status' });\n pair.port.send({ type: 'get-prompts' });\n }\n /** Owner-only withdrawal; no administrator route is exposed. */\n revoke(binding: string): void {\n const key = desktopBindingKey(this.options.authorization.binding(binding));\n this.options.store.revoke(key);\n this.paired.delete(binding);\n for (const [socket, pair] of this.active) if (pair.binding.id === binding) socket.terminate();\n }\n async close(): Promise<void> {\n this.closed = true;\n this.options.server.off('request', this.request);\n this.options.server.off('upgrade', this.upgrade);\n for (const socket of this.upgrades) socket.destroy();\n for (const socket of this.active.keys()) socket.terminate();\n for (const port of this.options.ports.values()) port.close();\n this.paired.clear();\n await new Promise<void>((resolve) => this.wss.close(() => resolve()));\n }\n}\n"],"mappings":"g6BACA,IAAI,EAA0B,cAAc,KAAM,CACjD,OAAS,iBACT,aAAc,CACb,MAAM,6BAA6B,CACpC,CACD,EAGA,SAAS,GAAY,EAAO,CAC3B,IAAK,IAAM,KAAa,EAAO,CAC9B,IAAM,EAAQ,EAAU,YAAY,CAAC,EACrC,GAAI,GAAS,OAAS,GAAS,MAAO,MAAM,IAAI,CACjD,CACD,CAEA,SAASA,GAAsB,EAAO,CACrC,IAAM,EAA2B,IAAI,IACjC,EAAQ,EACZ,SAAS,EAAO,EAAM,EAAO,CAC5B,GAAI,EAAE,EAAQ,MAAQ,EAAQ,GAAI,MAAM,IAAI,EAC5C,GAAI,IAAS,MAAQ,OAAO,GAAS,UAAW,OAAO,KAAK,UAAU,CAAI,EAC1E,GAAI,OAAO,GAAS,SAEnB,OADA,GAAY,CAAI,EACT,KAAK,UAAU,CAAI,EAE3B,GAAI,OAAO,GAAS,SAAU,CAC7B,GAAI,CAA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CAAK,EACjC,GAAU,EAAG,KAAK,KAAK,UAAU,CAAQ,CAAC,CAChD,CAAC,CAAC,CACD,MAAM,CAAQ,CAAC,CACf,YAAc,CACb,GACF,CAAC,CACL,CAAC,EACD,EAAG,GAAG,QAAS,CAAQ,EACvB,EAAG,KAAK,YAAe,CACrB,cAAc,CAAK,EACnB,EAAa,EACb,EAAY,EACZ,KAAK,OAAO,OAAO,CAAE,CACvB,CAAC,EACD,EAAK,KAAK,KAAK,CAAE,KAAM,cAAe,CAAC,EACvC,EAAK,KAAK,KAAK,CAAE,KAAM,YAAa,CAAC,EACrC,EAAK,KAAK,KAAK,CAAE,KAAM,aAAc,CAAC,CACxC,CAEA,OAAO,EAAuB,CAC5B,IAAM,EAAM,EAAkB,KAAK,QAAQ,cAAc,QAAQ,CAAO,CAAC,EACzE,KAAK,QAAQ,MAAM,OAAO,CAAG,EAC7B,KAAK,OAAO,OAAO,CAAO,EAC1B,IAAK,GAAM,CAAC,EAAQ,KAAS,KAAK,OAAY,EAAK,QAAQ,KAAO,GAAS,EAAO,UAAU,CAC9F,CACA,MAAM,OAAuB,CAC3B,KAAK,OAAS,GACd,KAAK,QAAQ,OAAO,IAAI,UAAW,KAAK,OAAO,EAC/C,KAAK,QAAQ,OAAO,IAAI,UAAW,KAAK,OAAO,EAC/C,IAAK,IAAM,KAAU,KAAK,SAAU,EAAO,QAAQ,EACnD,IAAK,IAAM,KAAU,KAAK,OAAO,KAAK,EAAG,EAAO,UAAU,EAC1D,IAAK,IAAM,KAAQ,KAAK,QAAQ,MAAM,OAAO,EAAG,EAAK,MAAM,EAC3D,KAAK,OAAO,MAAM,EAClB,MAAM,IAAI,QAAe,GAAY,KAAK,IAAI,UAAY,EAAQ,CAAC,CAAC,CACtE,CACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["organizationCanonical","identifier","record","identifier","identifier","parsePublicHttpsUrl","createAccessTokenVerifier","createBearerResourceServer","bearerCredential"],"sources":["../../../agent-organization/dist/node/index.js","../../../agent-organization-host/dist/node/index.js","../../src/hosted/hosted-organization-control.ts","../../src/hosted/e2b-organization-inventory.ts","../../src/hosted/hosted-organization-gateway.ts","../../src/hosted/hosted-organization-payloads.ts","../../src/hosted/hosted-organization-model.ts","../../src/hosted/hosted-organization-token-counter.ts","../../src/hosted/hosted-filesystem-checkpoint.ts","../../src/hosted/e2b-worker-provisioning.ts","../../src/hosted/desktop/authorization.ts","../../src/hosted/desktop/authority-store.ts","../../src/hosted/desktop/worker-port.ts","../../src/hosted/desktop/gateway.ts"],"sourcesContent":["//#region src/error.ts\nvar OrganizationSchemaError = class extends Error {\n\treason = \"invalid-schema\";\n\tconstructor() {\n\t\tsuper(\"Invalid organization schema\");\n\t}\n};\n//#endregion\n//#region src/canonical.ts\nfunction validString(value) {\n\tfor (const character of value) {\n\t\tconst point = character.codePointAt(0);\n\t\tif (point >= 55296 && point <= 57343) throw new OrganizationSchemaError();\n\t}\n}\n/** Canonical JSON for a bounded, safe-integer subset; no float coercion. */\nfunction organizationCanonical(value) {\n\tconst visiting = /* @__PURE__ */ new Set();\n\tlet nodes = 0;\n\tfunction encode(item, depth) {\n\t\tif (++nodes > 4096 || depth > 32) throw new OrganizationSchemaError();\n\t\tif (item === null || typeof item === \"boolean\") return JSON.stringify(item);\n\t\tif (typeof item === \"string\") {\n\t\t\tvalidString(item);\n\t\t\treturn JSON.stringify(item);\n\t\t}\n\t\tif (typeof item === \"number\") {\n\t\t\tif (!Number.isSafeInteger(item) || Object.is(item, -0)) throw new OrganizationSchemaError();\n\t\t\treturn JSON.stringify(item);\n\t\t}\n\t\tif (typeof item !== \"object\" || visiting.has(item)) throw new OrganizationSchemaError();\n\t\tvisiting.add(item);\n\t\ttry {\n\t\t\tif (Array.isArray(item)) {\n\t\t\t\tif (Reflect.ownKeys(item).length !== item.length + 1) throw new OrganizationSchemaError();\n\t\t\t\treturn `[${Array.from({ length: item.length }, (_, index) => {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(item, String(index));\n\t\t\t\t\tif (descriptor === void 0 || !(\"value\" in descriptor)) throw new OrganizationSchemaError();\n\t\t\t\t\treturn encode(descriptor.value, depth + 1);\n\t\t\t\t}).join(\",\")}]`;\n\t\t\t}\n\t\t\tif (Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null) throw new OrganizationSchemaError();\n\t\t\tconst keys = Reflect.ownKeys(item);\n\t\t\tif (keys.some((key) => typeof key !== \"string\")) throw new OrganizationSchemaError();\n\t\t\treturn `{${keys.sort().map((key) => {\n\t\t\t\tvalidString(key);\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(item, key);\n\t\t\t\tif (!descriptor.enumerable || !(\"value\" in descriptor)) throw new OrganizationSchemaError();\n\t\t\t\treturn `${JSON.stringify(key)}:${encode(descriptor.value, depth + 1)}`;\n\t\t\t}).join(\",\")}}`;\n\t\t} finally {\n\t\t\tvisiting.delete(item);\n\t\t}\n\t}\n\tconst encoded = encode(value, 0);\n\tif (new TextEncoder().encode(encoded).byteLength > 64 * 1024) throw new OrganizationSchemaError();\n\treturn encoded;\n}\n//#endregion\n//#region src/validation.ts\nfunction exactRecord(value, keys) {\n\torganizationCanonical(value);\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new OrganizationSchemaError();\n\tconst record = value;\n\tif (Object.keys(record).length !== keys.length || keys.some((key) => !Object.hasOwn(record, key))) throw new OrganizationSchemaError();\n\treturn record;\n}\nfunction nonnegativeInteger(value, minimum = 0) {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || Object.is(value, -0) || value < minimum) throw new OrganizationSchemaError();\n\treturn value;\n}\nfunction organizationUnits(value) {\n\tconst data = exactRecord(value, [\n\t\t\"tokens\",\n\t\t\"timeMs\",\n\t\t\"costMicros\"\n\t]);\n\treturn Object.freeze({\n\t\ttokens: nonnegativeInteger(data.tokens),\n\t\ttimeMs: nonnegativeInteger(data.timeMs),\n\t\tcostMicros: nonnegativeInteger(data.costMicros)\n\t});\n}\nfunction organizationBudget(value) {\n\tconst data = exactRecord(value, [\n\t\t\"tokens\",\n\t\t\"timeMs\",\n\t\t\"costMicros\",\n\t\t\"concurrency\"\n\t]);\n\treturn Object.freeze({\n\t\ttokens: nonnegativeInteger(data.tokens),\n\t\ttimeMs: nonnegativeInteger(data.timeMs),\n\t\tcostMicros: nonnegativeInteger(data.costMicros),\n\t\tconcurrency: nonnegativeInteger(data.concurrency, 1)\n\t});\n}\n//#endregion\nexport { OrganizationSchemaError, organizationBudget, organizationCanonical, organizationUnits };\n\n//# sourceMappingURL=index.js.map","import { createRequire } from \"node:module\";\nimport { createHash, createPublicKey, randomUUID, verify } from \"node:crypto\";\nimport { OrganizationSchemaError, organizationBudget, organizationCanonical as organizationCanonical$1, organizationUnits } from \"@robota-sdk/agent-organization\";\nimport { execFileSync } from \"node:child_process\";\nimport { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, join } from \"node:path\";\nimport { performance } from \"node:perf_hooks\";\n//#region src/types.ts\nvar OrganizationRefused = class extends Error {\n\treason;\n\tconstructor(reason) {\n\t\tsuper(`Organization operation refused: ${reason}`);\n\t\tthis.reason = reason;\n\t}\n};\n//#endregion\n//#region src/canonical.ts\nfunction organizationCanonical(value) {\n\ttry {\n\t\treturn organizationCanonical$1(value);\n\t} catch (error) {\n\t\tif (error instanceof OrganizationSchemaError) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthrow error;\n\t}\n}\nfunction organizationSigningBytes(domain, claims) {\n\tif (![\n\t\t\"workload\",\n\t\t\"request\",\n\t\t\"approval\"\n\t].includes(domain)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Buffer.from(organizationCanonical([`robota/organization-${domain}/v1`, claims]), \"utf8\");\n}\nfunction organizationOperationDigest(request) {\n\treturn createHash(\"sha256\").update(organizationCanonical([\n\t\t\"robota/organization-operation/v1\",\n\t\trequest.grantId,\n\t\trequest.tenant,\n\t\trequest.task,\n\t\trequest.actor,\n\t\trequest.audience,\n\t\trequest.epoch,\n\t\trequest.operation\n\t]), \"utf8\").digest(\"hex\");\n}\n//#endregion\n//#region src/verification.ts\nfunction record(value, keys) {\n\torganizationCanonical(value);\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new OrganizationRefused(\"invalid-schema\");\n\tconst data = value;\n\tif (Object.keys(data).length !== keys.length || keys.some((key) => !Object.hasOwn(data, key))) throw new OrganizationRefused(\"invalid-schema\");\n\treturn data;\n}\nfunction identifier(value) {\n\tif (typeof value !== \"string\" || value.length < 1 || value.length > 256 || [...value].some((character) => {\n\t\tconst point = character.codePointAt(0);\n\t\treturn point < 32 || point === 127 || point >= 55296 && point <= 57343;\n\t})) throw new OrganizationRefused(\"invalid-schema\");\n\treturn value;\n}\nfunction integer(value, minimum = 0) {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || Object.is(value, -0) || value < minimum) throw new OrganizationRefused(\"invalid-schema\");\n\treturn value;\n}\nfunction units(value) {\n\ttry {\n\t\treturn organizationUnits(value);\n\t} catch (error) {\n\t\tif (error instanceof OrganizationSchemaError) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthrow error;\n\t}\n}\nfunction receipt(value) {\n\tconst data = record(value, [\"value\", \"usage\"]);\n\treturn Object.freeze({\n\t\tvalue: immutableJson(JSON.parse(organizationCanonical(data.value))),\n\t\tusage: units(data.usage)\n\t});\n}\nfunction budget(value) {\n\ttry {\n\t\treturn organizationBudget(value);\n\t} catch (error) {\n\t\tif (error instanceof OrganizationSchemaError) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthrow error;\n\t}\n}\nfunction publicKey(value) {\n\tif (typeof value !== \"string\" || value.length > 4096 || !value.startsWith(\"-----BEGIN PUBLIC KEY-----\")) throw new OrganizationRefused(\"invalid-schema\");\n\ttry {\n\t\tconst key = createPublicKey(value);\n\t\tif (key.asymmetricKeyType !== \"ed25519\") throw new Error(\"wrong type\");\n\t\treturn key;\n\t} catch {\n\t\tthrow new OrganizationRefused(\"invalid-proof\");\n\t}\n}\nfunction strings(value) {\n\tif (!Array.isArray(value) || value.length < 1 || value.length > 64) throw new OrganizationRefused(\"invalid-schema\");\n\tconst output = value.map(identifier);\n\tif (new Set(output).size !== output.length) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Object.freeze(output);\n}\nfunction immutableJson(value) {\n\tif (value !== null && typeof value === \"object\") {\n\t\tfor (const child of Object.values(value)) immutableJson(child);\n\t\tObject.freeze(value);\n\t}\n\treturn value;\n}\nfunction validity(data) {\n\tif (data.version !== 1 || integer(data.expiresAt, 1) <= integer(data.notBefore)) throw new OrganizationRefused(\"invalid-schema\");\n\tinteger(data.epoch, 1);\n}\nfunction grantClaims(value) {\n\tconst data = record(value, [\n\t\t\"version\",\n\t\t\"id\",\n\t\t\"tenant\",\n\t\t\"task\",\n\t\t\"actor\",\n\t\t\"role\",\n\t\t\"audience\",\n\t\t\"parent\",\n\t\t\"epoch\",\n\t\t\"notBefore\",\n\t\t\"expiresAt\",\n\t\t\"publicKey\",\n\t\t\"scopes\",\n\t\t\"budget\"\n\t]);\n\tvalidity(data);\n\tpublicKey(data.publicKey);\n\tif (!Array.isArray(data.scopes) || data.scopes.length < 1 || data.scopes.length > 64) throw new OrganizationRefused(\"invalid-schema\");\n\tconst scopes = data.scopes.map((value) => {\n\t\tconst scope = record(value, [\"resource\", \"operations\"]);\n\t\treturn Object.freeze({\n\t\t\tresource: identifier(scope.resource),\n\t\t\toperations: strings(scope.operations)\n\t\t});\n\t});\n\tif (new Set(scopes.map((scope) => scope.resource)).size !== scopes.length) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Object.freeze({\n\t\tversion: 1,\n\t\tid: identifier(data.id),\n\t\ttenant: identifier(data.tenant),\n\t\ttask: identifier(data.task),\n\t\tactor: identifier(data.actor),\n\t\trole: identifier(data.role),\n\t\taudience: identifier(data.audience),\n\t\tparent: data.parent === null ? null : identifier(data.parent),\n\t\tepoch: integer(data.epoch, 1),\n\t\tnotBefore: integer(data.notBefore),\n\t\texpiresAt: integer(data.expiresAt, 1),\n\t\tpublicKey: data.publicKey,\n\t\tscopes: Object.freeze(scopes),\n\t\tbudget: budget(data.budget)\n\t});\n}\nfunction requestClaims(value) {\n\tconst data = record(value, [\n\t\t\"version\",\n\t\t\"grantId\",\n\t\t\"tenant\",\n\t\t\"task\",\n\t\t\"actor\",\n\t\t\"audience\",\n\t\t\"epoch\",\n\t\t\"nonce\",\n\t\t\"notBefore\",\n\t\t\"expiresAt\",\n\t\t\"operation\"\n\t]);\n\tvalidity(data);\n\tconst operation = record(data.operation, [\n\t\t\"idempotencyKey\",\n\t\t\"resource\",\n\t\t\"operation\",\n\t\t\"environment\",\n\t\t\"parameters\"\n\t]);\n\treturn Object.freeze({\n\t\tversion: 1,\n\t\tgrantId: identifier(data.grantId),\n\t\ttenant: identifier(data.tenant),\n\t\ttask: identifier(data.task),\n\t\tactor: identifier(data.actor),\n\t\taudience: identifier(data.audience),\n\t\tepoch: integer(data.epoch, 1),\n\t\tnonce: identifier(data.nonce),\n\t\tnotBefore: integer(data.notBefore),\n\t\texpiresAt: integer(data.expiresAt, 1),\n\t\toperation: Object.freeze({\n\t\t\tidempotencyKey: identifier(operation.idempotencyKey),\n\t\t\tresource: identifier(operation.resource),\n\t\t\toperation: identifier(operation.operation),\n\t\t\tenvironment: identifier(operation.environment),\n\t\t\tparameters: immutableJson(JSON.parse(organizationCanonical(operation.parameters)))\n\t\t})\n\t});\n}\nfunction approvalClaims(value) {\n\tconst data = record(value, [\n\t\t\"version\",\n\t\t\"id\",\n\t\t\"tenant\",\n\t\t\"task\",\n\t\t\"actor\",\n\t\t\"audience\",\n\t\t\"epoch\",\n\t\t\"environment\",\n\t\t\"operationDigest\",\n\t\t\"notBefore\",\n\t\t\"expiresAt\"\n\t]);\n\tvalidity(data);\n\tif (typeof data.operationDigest !== \"string\" || !/^[a-f0-9]{64}$/.test(data.operationDigest)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Object.freeze({\n\t\tversion: 1,\n\t\tid: identifier(data.id),\n\t\ttenant: identifier(data.tenant),\n\t\ttask: identifier(data.task),\n\t\tactor: identifier(data.actor),\n\t\taudience: identifier(data.audience),\n\t\tepoch: integer(data.epoch, 1),\n\t\tenvironment: identifier(data.environment),\n\t\toperationDigest: data.operationDigest,\n\t\tnotBefore: integer(data.notBefore),\n\t\texpiresAt: integer(data.expiresAt, 1)\n\t});\n}\nfunction verifyEnvelope(domain, envelope, key) {\n\tconst data = record(envelope, [\"claims\", \"signature\"]);\n\tif (typeof data.signature !== \"string\" || !/^[A-Za-z0-9_-]{86}$/.test(data.signature)) throw new OrganizationRefused(\"invalid-proof\");\n\tconst signature = Buffer.from(data.signature, \"base64url\");\n\tif (signature.length !== 64 || signature.toString(\"base64url\") !== data.signature || !verify(null, organizationSigningBytes(domain, data.claims), key, signature)) throw new OrganizationRefused(\"invalid-proof\");\n}\nfunction currentTime(claims, now, maxTtlMs) {\n\tinteger(now);\n\tif (claims.expiresAt - claims.notBefore > maxTtlMs || now < claims.notBefore || now >= claims.expiresAt) throw new OrganizationRefused(\"expired\");\n}\n//#endregion\n//#region src/audit.ts\n/** A trusted sink may report this only when its expected-head CAS made no append. Other failures are ambiguous. */\nvar OrganizationAuditAppendConflict = class extends Error {\n\tconstructor() {\n\t\tsuper(\"Organization audit append conflict\");\n\t}\n};\nconst HASH = /^[0-9a-f]{64}$/;\nconst PHASES = [\n\t\"dispatch\",\n\t\"complete\",\n\t\"refused\",\n\t\"unknown\"\n];\nfunction digest$1(value) {\n\treturn createHash(\"sha256\").update(organizationCanonical(value), \"utf8\").digest(\"hex\");\n}\nfunction hash(value) {\n\tif (typeof value !== \"string\" || !HASH.test(value)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn value;\n}\nfunction head(value, stream) {\n\tconst data = record(value, [\n\t\t\"version\",\n\t\t\"stream\",\n\t\t\"sequence\",\n\t\t\"hash\"\n\t]);\n\tif (data.version !== 1 || data.stream !== stream) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Object.freeze({\n\t\tversion: 1,\n\t\tstream,\n\t\tsequence: integer(data.sequence),\n\t\thash: hash(data.hash)\n\t});\n}\nfunction event(value) {\n\tconst data = record(value, [\n\t\t\"phase\",\n\t\t\"operationDigest\",\n\t\t\"tenantDigest\",\n\t\t\"taskDigest\",\n\t\t\"actorDigest\",\n\t\t\"grantDigest\",\n\t\t\"epoch\"\n\t]);\n\tif (typeof data.phase !== \"string\" || !PHASES.includes(data.phase)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn Object.freeze({\n\t\tphase: data.phase,\n\t\toperationDigest: hash(data.operationDigest),\n\t\ttenantDigest: hash(data.tenantDigest),\n\t\ttaskDigest: hash(data.taskDigest),\n\t\tactorDigest: hash(data.actorDigest),\n\t\tgrantDigest: hash(data.grantDigest),\n\t\tepoch: integer(data.epoch, 1)\n\t});\n}\nfunction organizationAuditEvent(value, phase) {\n\tif (!PHASES.includes(phase)) throw new OrganizationRefused(\"invalid-schema\");\n\tconst request = requestClaims(value);\n\tconst pseudonym = (kind, parts) => digest$1([\n\t\t\"robota/organization-audit-identity/v1\",\n\t\tkind,\n\t\tparts\n\t]);\n\treturn Object.freeze({\n\t\tphase,\n\t\toperationDigest: organizationOperationDigest(request),\n\t\ttenantDigest: pseudonym(\"tenant\", [request.tenant]),\n\t\ttaskDigest: pseudonym(\"task\", [request.tenant, request.task]),\n\t\tactorDigest: pseudonym(\"actor\", [request.tenant, request.actor]),\n\t\tgrantDigest: pseudonym(\"grant\", [request.grantId]),\n\t\tepoch: request.epoch\n\t});\n}\nfunction organizationAuditGenesis(stream) {\n\tidentifier(stream);\n\treturn Object.freeze({\n\t\tversion: 1,\n\t\tstream,\n\t\tsequence: 0,\n\t\thash: digest$1([\"robota/organization-audit-genesis/v1\", stream])\n\t});\n}\nfunction organizationAuditHash(stream, sequence, previous, value) {\n\treturn digest$1([\n\t\t\"robota/organization-audit-entry/v1\",\n\t\tidentifier(stream),\n\t\tinteger(sequence, 1),\n\t\thash(previous),\n\t\tevent(value)\n\t]);\n}\n/** Public signing bytes for an external audit owner; this package never accepts its private key. */\nfunction organizationAuditSigningBytes(value) {\n\treturn Buffer.from(organizationCanonical([\"robota/organization-audit-checkpoint/v1\", head(value, identifier(value.stream))]), \"utf8\");\n}\nfunction checkpoint(value, stream, key) {\n\tconst data = record(value, [\"claims\", \"signature\"]);\n\tconst claims = head(data.claims, stream);\n\tif (typeof data.signature !== \"string\" || !/^[A-Za-z0-9_-]{86}$/.test(data.signature)) throw new OrganizationRefused(\"invalid-proof\");\n\tconst signature = Buffer.from(data.signature, \"base64url\");\n\tif (signature.length !== 64 || signature.toString(\"base64url\") !== data.signature || !verify(null, organizationAuditSigningBytes(claims), key, signature)) throw new OrganizationRefused(\"invalid-proof\");\n\tif (claims.sequence === 0 && claims.hash !== organizationAuditGenesis(stream).hash) throw new OrganizationRefused(\"invalid-proof\");\n\treturn Object.freeze({\n\t\tclaims,\n\t\tsignature: data.signature\n\t});\n}\nfunction entry(value, previous) {\n\tconst data = record(value, [\n\t\t\"stream\",\n\t\t\"sequence\",\n\t\t\"previous\",\n\t\t\"event\",\n\t\t\"hash\"\n\t]);\n\tconst safeEvent = event(data.event);\n\tif (data.stream !== previous.stream || data.sequence !== previous.sequence + 1 || data.previous !== previous.hash) throw new OrganizationRefused(\"invalid-proof\");\n\tconst computed = organizationAuditHash(previous.stream, integer(data.sequence, 1), previous.hash, safeEvent);\n\tif (data.hash !== computed) throw new OrganizationRefused(\"invalid-proof\");\n\treturn Object.freeze({\n\t\tstream: previous.stream,\n\t\tsequence: data.sequence,\n\t\tprevious: previous.hash,\n\t\tevent: safeEvent,\n\t\thash: computed\n\t});\n}\nfunction same(a, b) {\n\treturn a.stream === b.stream && a.sequence === b.sequence && a.hash === b.hash;\n}\nfunction page(value, start, key) {\n\tconst data = record(value, [\"entries\", \"head\"]);\n\tif (!Array.isArray(data.entries) || data.entries.length > 128) throw new OrganizationRefused(\"invalid-schema\");\n\tconst last = checkpoint(data.head, start.stream, key);\n\tlet current = start;\n\tfor (const item of data.entries) {\n\t\tconst next = entry(item, current);\n\t\tcurrent = {\n\t\t\tversion: 1,\n\t\t\tstream: next.stream,\n\t\t\tsequence: next.sequence,\n\t\t\thash: next.hash\n\t\t};\n\t}\n\tif (!same(current, last.claims)) throw new OrganizationRefused(\"invalid-proof\");\n\treturn last;\n}\n/** Verify a bounded continuation against pinned signed checkpoints, without trusting a mutable local head. */\nfunction verifyOrganizationAudit(entries, start, end, pinnedKey, pinnedStream) {\n\tconst key = publicKey(pinnedKey);\n\tconst first = checkpoint(start, identifier(pinnedStream), key);\n\treturn page({\n\t\tentries,\n\t\thead: end\n\t}, first.claims, key).claims;\n}\nfunction pause(milliseconds, signal) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst cleanup = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t};\n\t\tconst abort = () => {\n\t\t\tcleanup();\n\t\t\treject(new OrganizationRefused(\"policy-unavailable\"));\n\t\t};\n\t\tconst timer = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t}, milliseconds);\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\tif (signal.aborted) abort();\n\t});\n}\nfunction active(signal) {\n\tif (signal.aborted) throw new OrganizationRefused(\"policy-unavailable\");\n}\n/** Dispatch can proceed only after an exact event and its independently retained checkpoint are confirmed. */\nvar OrganizationAudit = class {\n\tstream;\n\tkey;\n\tsink;\n\tanchor;\n\ttimeout;\n\tconstructor(options) {\n\t\tthis.stream = identifier(options.stream);\n\t\tthis.key = publicKey(options.publicKey);\n\t\tthis.timeout = integer(options.timeoutMs ?? 1e3, 1);\n\t\tif (this.timeout > 3e4 || typeof options.sink?.read !== \"function\" || typeof options.sink?.append !== \"function\" || typeof options.anchor?.load !== \"function\" || typeof options.anchor?.compareAndSet !== \"function\") throw new OrganizationRefused(\"invalid-schema\");\n\t\tthis.sink = Object.freeze({\n\t\t\tread: options.sink.read.bind(options.sink),\n\t\t\tappend: options.sink.append.bind(options.sink)\n\t\t});\n\t\tthis.anchor = Object.freeze({\n\t\t\tload: options.anchor.load.bind(options.anchor),\n\t\t\tcompareAndSet: options.anchor.compareAndSet.bind(options.anchor)\n\t\t});\n\t}\n\tasync bounded(work, signal) {\n\t\tconst controller = new AbortController();\n\t\tconst abort = () => controller.abort();\n\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\tif (signal?.aborted) controller.abort();\n\t\tlet rejectAbort;\n\t\tconst stopped = new Promise((_, reject) => {\n\t\t\trejectAbort = () => reject(new OrganizationRefused(\"policy-unavailable\"));\n\t\t\tcontroller.signal.addEventListener(\"abort\", rejectAbort, { once: true });\n\t\t\tif (controller.signal.aborted) rejectAbort();\n\t\t});\n\t\tconst timer = setTimeout(abort, this.timeout);\n\t\ttry {\n\t\t\treturn await Promise.race([Promise.resolve().then(() => {\n\t\t\t\tactive(controller.signal);\n\t\t\t\treturn work(controller.signal);\n\t\t\t}), stopped]);\n\t\t} catch {\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\tcontroller.signal.removeEventListener(\"abort\", rejectAbort);\n\t\t\tcontroller.abort();\n\t\t}\n\t}\n\tasync record(value, signal) {\n\t\tconst projected = event(value);\n\t\tawait this.bounded(async (lifetime) => {\n\t\t\tlet delay = 5;\n\t\t\tfor (;;) {\n\t\t\t\tactive(lifetime);\n\t\t\t\tconst anchored = checkpoint(await this.anchor.load(lifetime), this.stream, this.key);\n\t\t\t\tactive(lifetime);\n\t\t\t\tconst current = page(await this.sink.read(anchored.claims, lifetime), anchored.claims, this.key);\n\t\t\t\tactive(lifetime);\n\t\t\t\tif (!same(current.claims, anchored.claims)) {\n\t\t\t\t\tawait pause(delay, lifetime);\n\t\t\t\t\tdelay = Math.min(delay * 2, 50);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlet response;\n\t\t\t\ttry {\n\t\t\t\t\tresponse = record(await this.sink.append(anchored.claims, projected, lifetime), [\"entry\", \"head\"]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tactive(lifetime);\n\t\t\t\t\tif (!(error instanceof OrganizationAuditAppendConflict)) throw error;\n\t\t\t\t\tawait pause(delay, lifetime);\n\t\t\t\t\tdelay = Math.min(delay * 2, 50);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tactive(lifetime);\n\t\t\t\tconst written = entry(response.entry, anchored.claims);\n\t\t\t\tconst next = checkpoint(response.head, this.stream, this.key);\n\t\t\t\tif (organizationCanonical(written.event) !== organizationCanonical(projected) || !same(next.claims, {\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tstream: written.stream,\n\t\t\t\t\tsequence: written.sequence,\n\t\t\t\t\thash: written.hash\n\t\t\t\t})) throw new OrganizationRefused(\"invalid-proof\");\n\t\t\t\tconst confirmed = await this.anchor.compareAndSet(anchored.claims, next, lifetime);\n\t\t\t\tactive(lifetime);\n\t\t\t\tif (confirmed !== true) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}, signal);\n\t}\n\t/** Owner-only recovery of a valid already-written tail. Does not reset history, refund or retry any effect. */\n\tasync recover(signal) {\n\t\treturn this.bounded(async (lifetime) => {\n\t\t\tconst anchored = checkpoint(await this.anchor.load(lifetime), this.stream, this.key);\n\t\t\tactive(lifetime);\n\t\t\tconst current = page(await this.sink.read(anchored.claims, lifetime), anchored.claims, this.key);\n\t\t\tactive(lifetime);\n\t\t\tif (same(current.claims, anchored.claims)) return current.claims;\n\t\t\tconst confirmed = await this.anchor.compareAndSet(anchored.claims, current, lifetime);\n\t\t\tactive(lifetime);\n\t\t\tif (confirmed !== true) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\treturn current.claims;\n\t\t}, signal);\n\t}\n\t/** Readiness verifies retained evidence without adopting an unconfirmed tail or resetting history. */\n\tasync verify(signal) {\n\t\treturn this.bounded(async (lifetime) => {\n\t\t\tlet delay = 5;\n\t\t\tfor (;;) {\n\t\t\t\tconst anchored = checkpoint(await this.anchor.load(lifetime), this.stream, this.key);\n\t\t\t\tactive(lifetime);\n\t\t\t\tconst current = page(await this.sink.read(anchored.claims, lifetime), anchored.claims, this.key);\n\t\t\t\tactive(lifetime);\n\t\t\t\tif (same(current.claims, anchored.claims)) return anchored.claims;\n\t\t\t\tawait pause(delay, lifetime);\n\t\t\t\tdelay = Math.min(delay * 2, 50);\n\t\t\t}\n\t\t}, signal);\n\t}\n};\n//#endregion\n//#region src/git-asset.ts\nfunction gitOid(value) {\n\tif (typeof value !== \"string\" || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value) || /^0+$/.test(value)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn value;\n}\nfunction gitParameters(value) {\n\tconst params = record(value, [\n\t\t\"expectedRevision\",\n\t\t\"fence\",\n\t\t\"expectedOid\",\n\t\t\"candidateOid\"\n\t]);\n\treturn {\n\t\texpectedRevision: integer(params.expectedRevision),\n\t\tfence: integer(params.fence, 1),\n\t\texpectedOid: gitOid(params.expectedOid),\n\t\tcandidateOid: gitOid(params.candidateOid)\n\t};\n}\n/** Trusted asset-owner plumbing only. This class never clones/fetches, checks out, merges or runs user code. */\nvar OrganizationGitAsset = class {\n\tidentity;\n\tphaseTimeoutMs;\n\tpath;\n\tino;\n\tdev;\n\tref;\n\tgitPath;\n\tconstructor(options) {\n\t\tif (!isAbsolute(options.path) || !isAbsolute(options.gitPath) || !/^refs\\/heads\\/[a-zA-Z0-9][a-zA-Z0-9/_-]{0,120}$/.test(options.ref) || options.ref.endsWith(\"/\") || options.ref.includes(\"//\")) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthis.path = realpathSync(options.path);\n\t\tconst root = lstatSync(this.path);\n\t\tthis.ino = root.ino;\n\t\tthis.dev = root.dev;\n\t\tthis.ref = options.ref;\n\t\tthis.gitPath = realpathSync(options.gitPath);\n\t\tthis.phaseTimeoutMs = integer(options.phaseTimeoutMs ?? 1e3, 1);\n\t\tif (this.phaseTimeoutMs > 1e3) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthis.identity = createHash(\"sha256\").update(organizationCanonical([\n\t\t\tthis.path,\n\t\t\tthis.dev,\n\t\t\tthis.ino,\n\t\t\tthis.ref\n\t\t])).digest(\"hex\");\n\t\tthis.phase((run) => {\n\t\t\tif (run([\"rev-parse\", \"--is-bare-repository\"]) !== \"true\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\tthis.tip(run);\n\t\t});\n\t}\n\tverify() {\n\t\ttry {\n\t\t\tconst root = lstatSync(this.path);\n\t\t\tconst uid = process.getuid?.();\n\t\t\tif (!root.isDirectory() || root.ino !== this.ino || root.dev !== this.dev || (root.mode & 63) !== 0 || uid !== void 0 && uid !== root.uid) throw new Error(\"changed asset\");\n\t\t} catch {\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t}\n\t}\n\tphase(action) {\n\t\tconst start = performance.now();\n\t\tconst run = (args, input) => {\n\t\t\tthis.verify();\n\t\t\tconst remaining = this.phaseTimeoutMs - Math.ceil(performance.now() - start);\n\t\t\tif (remaining <= 0) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\ttry {\n\t\t\t\treturn execFileSync(this.gitPath, [\n\t\t\t\t\t\"--git-dir\",\n\t\t\t\t\tthis.path,\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"core.hooksPath=/dev/null\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"core.fsmonitor=false\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"gc.auto=0\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"commit.gpgSign=false\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"core.commitGraph=false\",\n\t\t\t\t\t...args\n\t\t\t\t], {\n\t\t\t\t\tinput,\n\t\t\t\t\tencoding: \"utf8\",\n\t\t\t\t\ttimeout: remaining,\n\t\t\t\t\tkillSignal: \"SIGKILL\",\n\t\t\t\t\tmaxBuffer: 64 * 1024,\n\t\t\t\t\tstdio: [\n\t\t\t\t\t\t\"pipe\",\n\t\t\t\t\t\t\"pipe\",\n\t\t\t\t\t\t\"pipe\"\n\t\t\t\t\t],\n\t\t\t\t\tenv: {\n\t\t\t\t\t\tGIT_CONFIG_NOSYSTEM: \"1\",\n\t\t\t\t\t\tGIT_CONFIG_GLOBAL: \"/dev/null\",\n\t\t\t\t\t\tGIT_NO_REPLACE_OBJECTS: \"1\",\n\t\t\t\t\t\tGIT_GRAFT_FILE: \"/dev/null\",\n\t\t\t\t\t\tGIT_TERMINAL_PROMPT: \"0\",\n\t\t\t\t\t\tGIT_ATTR_NOSYSTEM: \"1\",\n\t\t\t\t\t\tGIT_AUTHOR_NAME: \"Organization publication\",\n\t\t\t\t\t\tGIT_AUTHOR_EMAIL: \"broker@example.invalid\",\n\t\t\t\t\t\tGIT_COMMITTER_NAME: \"Organization publication\",\n\t\t\t\t\t\tGIT_COMMITTER_EMAIL: \"broker@example.invalid\",\n\t\t\t\t\t\tGIT_AUTHOR_DATE: \"2000-01-01T00:00:00Z\",\n\t\t\t\t\t\tGIT_COMMITTER_DATE: \"2000-01-01T00:00:00Z\"\n\t\t\t\t\t}\n\t\t\t\t}).trim();\n\t\t\t} catch (error) {\n\t\t\t\tif (args[0] === \"merge-base\" && typeof error === \"object\" && error !== null && \"status\" in error && error.status === 1) return \"\";\n\t\t\t\tthrow new OrganizationRefused(\"outcome-unknown\");\n\t\t\t}\n\t\t};\n\t\treturn action(run);\n\t}\n\ttip(run) {\n\t\tif (run([\n\t\t\t\"for-each-ref\",\n\t\t\t\"--format=%(symref)\",\n\t\t\tthis.ref\n\t\t]) !== \"\") throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn gitOid(run([\n\t\t\t\"show-ref\",\n\t\t\t\"--verify\",\n\t\t\t\"--hash\",\n\t\t\tthis.ref\n\t\t]));\n\t}\n\tprepare(digest, parameters) {\n\t\tif (!/^[a-f0-9]{64}$/.test(digest)) throw new OrganizationRefused(\"invalid-schema\");\n\t\tconst params = gitParameters(parameters);\n\t\treturn this.phase((run) => {\n\t\t\tif (this.tip(run) !== params.expectedOid || params.expectedOid === params.candidateOid) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tif (run([\n\t\t\t\t\"cat-file\",\n\t\t\t\t\"-t\",\n\t\t\t\tparams.candidateOid\n\t\t\t]) !== \"commit\") throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tif (run([\n\t\t\t\t\"merge-base\",\n\t\t\t\tparams.expectedOid,\n\t\t\t\tparams.candidateOid\n\t\t\t]) !== params.expectedOid) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tconst tree = gitOid(run([\n\t\t\t\t\"rev-parse\",\n\t\t\t\t\"--verify\",\n\t\t\t\t`${params.candidateOid}^{tree}`\n\t\t\t]));\n\t\t\tconst message = organizationCanonical({\n\t\t\t\tdomain: \"organization-git-publication-v1\",\n\t\t\t\tasset: this.identity,\n\t\t\t\tdigest,\n\t\t\t\t...params,\n\t\t\t\tnonce: randomUUID()\n\t\t\t});\n\t\t\tconst publishedOid = gitOid(run([\n\t\t\t\t\"commit-tree\",\n\t\t\t\t\"--no-gpg-sign\",\n\t\t\t\ttree,\n\t\t\t\t\"-p\",\n\t\t\t\tparams.candidateOid\n\t\t\t], `${message}\\n`));\n\t\t\treturn Object.freeze({\n\t\t\t\tasset: this.identity,\n\t\t\t\tdigest,\n\t\t\t\t...params,\n\t\t\t\tpublishedOid\n\t\t\t});\n\t\t});\n\t}\n\tpublish(intent) {\n\t\tif (intent.asset !== this.identity) throw new OrganizationRefused(\"operation-conflict\");\n\t\tconst expected = gitOid(intent.expectedOid);\n\t\tconst published = gitOid(intent.publishedOid);\n\t\tthis.phase((run) => {\n\t\t\tif (this.tip(run) !== expected) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\trun([\n\t\t\t\t\"update-ref\",\n\t\t\t\t\"--no-deref\",\n\t\t\t\tthis.ref,\n\t\t\t\tpublished,\n\t\t\t\texpected\n\t\t\t]);\n\t\t});\n\t}\n\twasPublished(intent) {\n\t\tif (intent.asset !== this.identity) throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn this.phase((run) => {\n\t\t\tconst tip = this.tip(run);\n\t\t\treturn run([\n\t\t\t\t\"merge-base\",\n\t\t\t\tgitOid(intent.publishedOid),\n\t\t\t\ttip\n\t\t\t]) === intent.publishedOid;\n\t\t});\n\t}\n};\n//#endregion\n//#region src/no-effect.ts\nconst NO_EFFECT_REASONS = [\n\t\"budget-exhausted\",\n\t\"not-authorized\",\n\t\"invalid-schema\",\n\t\"expired\",\n\t\"revoked\",\n\t\"operation-conflict\",\n\t\"operation-pending\"\n];\nfunction noEffectReason(value) {\n\tif (typeof value !== \"string\" || !NO_EFFECT_REASONS.includes(value)) throw new OrganizationRefused(\"invalid-schema\");\n\treturn value;\n}\n/** Trusted asset-owner evidence of a confirmed transaction rollback, never an unverified provider error. */\nvar OrganizationNoEffect = class extends OrganizationRefused {\n\tusage;\n\tconstructor(reason, usage) {\n\t\tsuper(noEffectReason(reason));\n\t\tthis.usage = units(usage);\n\t}\n};\n//#endregion\n//#region src/state-actions.ts\nfunction transactional(action) {\n\ttry {\n\t\treturn action();\n\t} catch (error) {\n\t\tif (error instanceof OrganizationRefused && [\n\t\t\t\"not-authorized\",\n\t\t\t\"invalid-schema\",\n\t\t\t\"expired\",\n\t\t\t\"revoked\",\n\t\t\t\"operation-conflict\",\n\t\t\t\"operation-pending\"\n\t\t].includes(error.reason)) throw new OrganizationNoEffect(error.reason, {\n\t\t\ttokens: 0,\n\t\t\ttimeMs: 0,\n\t\t\tcostMicros: 0\n\t\t});\n\t\tthrow error;\n\t}\n}\n/** Owner-installed task state actions. Workers cannot choose roles, budget or approval policy. */\nfunction createOrganizationStateActions(ledger, options) {\n\tconst resource = identifier(options.resource);\n\tconst readRoles = Object.freeze(options.readRoles.map(identifier));\n\tconst writeRoles = Object.freeze(options.writeRoles.map(identifier));\n\tconst reservation = units(options.reservation);\n\tif (readRoles.length === 0 || writeRoles.length === 0 || new Set(readRoles).size !== readRoles.length || new Set(writeRoles).size !== writeRoles.length || typeof options.writeRequiresApproval !== \"boolean\") throw new OrganizationRefused(\"invalid-schema\");\n\tconst common = {\n\t\tresource,\n\t\treserve: () => reservation\n\t};\n\treturn Object.freeze([\n\t\tObject.freeze({\n\t\t\t...common,\n\t\t\toperation: \"state.read\",\n\t\t\troles: readRoles,\n\t\t\trequiresApproval: false,\n\t\t\treserve: (operation) => {\n\t\t\t\trecord(operation.parameters, []);\n\t\t\t\treturn reservation;\n\t\t\t},\n\t\t\texecute: async (_, context) => {\n\t\t\t\tconst result = transactional(() => ledger.readState(context.proof));\n\t\t\t\treturn {\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\trevision: result.revision,\n\t\t\t\t\t\tvalue: result.value\n\t\t\t\t\t},\n\t\t\t\t\tusage: {\n\t\t\t\t\t\ttokens: 0,\n\t\t\t\t\t\ttimeMs: 0,\n\t\t\t\t\t\tcostMicros: 0\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t}),\n\t\tObject.freeze({\n\t\t\t...common,\n\t\t\toperation: \"state.lease\",\n\t\t\troles: writeRoles,\n\t\t\trequiresApproval: false,\n\t\t\treserve: (operation) => {\n\t\t\t\tconst parameters = record(operation.parameters, [\"expectedRevision\", \"ttlMs\"]);\n\t\t\t\tinteger(parameters.expectedRevision);\n\t\t\t\tinteger(parameters.ttlMs, 1);\n\t\t\t\tif (Number(parameters.ttlMs) > 3e4) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\t\treturn reservation;\n\t\t\t},\n\t\t\texecute: async (_, context) => {\n\t\t\t\tconst result = transactional(() => ledger.leaseState(context.proof));\n\t\t\t\treturn {\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\trevision: result.revision,\n\t\t\t\t\t\tfence: result.fence,\n\t\t\t\t\t\texpiresAt: result.expiresAt\n\t\t\t\t\t},\n\t\t\t\t\tusage: {\n\t\t\t\t\t\ttokens: 0,\n\t\t\t\t\t\ttimeMs: 0,\n\t\t\t\t\t\tcostMicros: 0\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t}),\n\t\tObject.freeze({\n\t\t\t...common,\n\t\t\toperation: \"state.write\",\n\t\t\troles: writeRoles,\n\t\t\trequiresApproval: options.writeRequiresApproval,\n\t\t\treserve: (operation) => {\n\t\t\t\tconst parameters = record(operation.parameters, [\n\t\t\t\t\t\"expectedRevision\",\n\t\t\t\t\t\"fence\",\n\t\t\t\t\t\"value\"\n\t\t\t\t]);\n\t\t\t\tinteger(parameters.expectedRevision);\n\t\t\t\tinteger(parameters.fence, 1);\n\t\t\t\torganizationCanonical(parameters.value);\n\t\t\t\treturn reservation;\n\t\t\t},\n\t\t\texecute: async (_, context) => {\n\t\t\t\tconst result = transactional(() => ledger.writeState(context.proof));\n\t\t\t\treturn {\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\trevision: result.revision,\n\t\t\t\t\t\tvalue: result.value\n\t\t\t\t\t},\n\t\t\t\t\tusage: {\n\t\t\t\t\t\ttokens: 0,\n\t\t\t\t\t\ttimeMs: 0,\n\t\t\t\t\t\tcostMicros: 0\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t})\n\t]);\n}\n//#endregion\n//#region src/git-actions.ts\n/** Owner-pinned Git asset. Publication always requires separate exact operator approval. */\nfunction createOrganizationGitActions(ledger, options) {\n\tconst states = createOrganizationStateActions(ledger, {\n\t\t...options,\n\t\twriteRequiresApproval: true\n\t});\n\tconst asset = options.asset;\n\tif (options.reservation.timeMs < asset.phaseTimeoutMs * 3) throw new OrganizationRefused(\"invalid-schema\");\n\tconst lease = states[1];\n\tconst reservation = units(options.reservation);\n\tconst publish = Object.freeze({\n\t\tresource: lease.resource,\n\t\toperation: \"git.publish\",\n\t\troles: lease.roles,\n\t\trequiresApproval: true,\n\t\treserve: (operation) => {\n\t\t\tgitParameters(operation.parameters);\n\t\t\treturn reservation;\n\t\t},\n\t\texecute: async (_, context) => {\n\t\t\ttry {\n\t\t\t\tledger.prepareGitPublication(context.proof, asset);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof OrganizationRefused && [\n\t\t\t\t\t\"not-authorized\",\n\t\t\t\t\t\"invalid-schema\",\n\t\t\t\t\t\"expired\",\n\t\t\t\t\t\"revoked\",\n\t\t\t\t\t\"operation-conflict\",\n\t\t\t\t\t\"operation-pending\"\n\t\t\t\t].includes(error.reason)) throw new OrganizationNoEffect(error.reason, {\n\t\t\t\t\ttokens: 0,\n\t\t\t\t\ttimeMs: 0,\n\t\t\t\t\tcostMicros: 0\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst result = ledger.commitGitPublication(context.proof, asset);\n\t\t\treturn {\n\t\t\t\tvalue: {\n\t\t\t\t\trevision: result.revision,\n\t\t\t\t\tvalue: result.value\n\t\t\t\t},\n\t\t\t\tusage: {\n\t\t\t\t\ttokens: 0,\n\t\t\t\t\ttimeMs: 0,\n\t\t\t\t\tcostMicros: 0\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n\treturn Object.freeze([\n\t\tstates[0],\n\t\tlease,\n\t\tpublish\n\t]);\n}\n//#endregion\n//#region src/broker.ts\nfunction snapshotCall(value) {\n\tconst data = record(value, [\"request\", \"approval\"]);\n\tconst request = record(data.request, [\"claims\", \"signature\"]);\n\tconst approval = data.approval === null ? null : record(data.approval, [\"claims\", \"signature\"]);\n\tif (typeof request.signature !== \"string\" || approval !== null && typeof approval.signature !== \"string\") throw new OrganizationRefused(\"invalid-proof\");\n\treturn Object.freeze({\n\t\trequest: Object.freeze({\n\t\t\tclaims: requestClaims(request.claims),\n\t\t\tsignature: request.signature\n\t\t}),\n\t\tapproval: approval === null ? null : Object.freeze({\n\t\t\tclaims: approvalClaims(approval.claims),\n\t\t\tsignature: approval.signature\n\t\t})\n\t});\n}\n/** Worker requests can use only the action table installed by the broker owner. */\nvar OrganizationBroker = class {\n\taudience;\n\tledger;\n\tactions = /* @__PURE__ */ new Map();\n\tinterval;\n\tnow;\n\tactive = /* @__PURE__ */ new Set();\n\taudit;\n\tauditReadiness;\n\tclosed = false;\n\tconstructor(options) {\n\t\tthis.ledger = options.ledger;\n\t\tif (options.hosted === true) {\n\t\t\tthis.ledger.verifyAnchoredAuthority();\n\t\t\tif (!(options.audit instanceof OrganizationAudit)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\tthis.auditReadiness = options.audit.verify.bind(options.audit);\n\t\t}\n\t\tif (options.audit !== void 0) {\n\t\t\tif (typeof options.audit?.record !== \"function\") throw new OrganizationRefused(\"invalid-schema\");\n\t\t\tthis.audit = Object.freeze({ record: options.audit.record.bind(options.audit) });\n\t\t}\n\t\tthis.audience = options.ledger.audience;\n\t\tthis.interval = integer(options.policyIntervalMs ?? 100, 1);\n\t\tif (this.interval > 1e3) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthis.now = options.now ?? Date.now;\n\t\tfor (const action of options.actions) {\n\t\t\tconst resource = identifier(action.resource);\n\t\t\tconst operation = identifier(action.operation);\n\t\t\tconst roles = action.roles.map(identifier);\n\t\t\tif (roles.length === 0 || new Set(roles).size !== roles.length || typeof action.requiresApproval !== \"boolean\" || typeof action.reserve !== \"function\" || typeof action.execute !== \"function\") throw new OrganizationRefused(\"invalid-schema\");\n\t\t\tconst key = organizationCanonical([resource, operation]);\n\t\t\tif (this.actions.has(key)) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\tthis.actions.set(key, Object.freeze({\n\t\t\t\tresource,\n\t\t\t\toperation,\n\t\t\t\troles: Object.freeze(roles),\n\t\t\t\trequiresApproval: action.requiresApproval,\n\t\t\t\treserve: action.reserve.bind(action),\n\t\t\t\texecute: action.execute.bind(action)\n\t\t\t}));\n\t\t}\n\t}\n\tasync apply(value, signal) {\n\t\tif (this.closed) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tif (signal?.aborted) throw new OrganizationRefused(\"not-authorized\");\n\t\tawait this.auditReadiness?.(signal);\n\t\tif (this.closed || signal?.aborted) throw new OrganizationRefused(\"not-authorized\");\n\t\tconst call = snapshotCall(value);\n\t\tconst { request, grant } = this.ledger.authenticate(call.request);\n\t\tconst action = this.actions.get(organizationCanonical([request.operation.resource, request.operation.operation]));\n\t\tif (action === void 0 || !action.roles.includes(grant.role)) throw new OrganizationRefused(\"not-authorized\");\n\t\tconst reservation = units(action.reserve(request.operation));\n\t\tinteger(reservation.timeMs, 1);\n\t\tif (reservation.timeMs > 2147483647) throw new OrganizationRefused(\"invalid-schema\");\n\t\tconst result = this.ledger.reserve(call.request, reservation, call.approval, action.requiresApproval);\n\t\tif (result.kind === \"complete\") return result.receipt;\n\t\tif (result.kind === \"refused\") throw new OrganizationRefused(result.reason);\n\t\treturn this.execute(call.request, action, result, signal);\n\t}\n\tasync auditRecord(request, phase, signal) {\n\t\tif (this.audit === void 0) return;\n\t\tlet stopped;\n\t\tconst aborted = new Promise((_, reject) => {\n\t\t\tstopped = () => reject(new OrganizationRefused(\"outcome-unknown\"));\n\t\t\tsignal.addEventListener(\"abort\", stopped, { once: true });\n\t\t\tif (signal.aborted) stopped();\n\t\t});\n\t\ttry {\n\t\t\tawait Promise.race([Promise.resolve().then(() => {\n\t\t\t\tif (signal.aborted) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\t\treturn this.audit.record(organizationAuditEvent(request, phase), signal);\n\t\t\t}), aborted]);\n\t\t\tif (signal.aborted) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t} finally {\n\t\t\tsignal.removeEventListener(\"abort\", stopped);\n\t\t}\n\t}\n\tasync execute(envelope, action, reserved, signal) {\n\t\tconst request = envelope.claims;\n\t\tconst controller = new AbortController();\n\t\tthis.active.add(controller);\n\t\tconst abort = () => controller.abort();\n\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\tif (signal?.aborted || this.closed) controller.abort();\n\t\tconst remaining = Math.min(reserved.reservation.timeMs, request.expiresAt - this.now(), reserved.grant.expiresAt - this.now());\n\t\tconst deadline = setTimeout(abort, Math.max(0, remaining));\n\t\tconst policy = setInterval(() => {\n\t\t\ttry {\n\t\t\t\tthis.ledger.authenticate(envelope);\n\t\t\t} catch {\n\t\t\t\tcontroller.abort();\n\t\t\t}\n\t\t}, this.interval);\n\t\tconst start = performance.now();\n\t\tlet abortedListener;\n\t\ttry {\n\t\t\tconst aborted = new Promise((_, reject) => {\n\t\t\t\tabortedListener = () => reject(new OrganizationRefused(\"outcome-unknown\"));\n\t\t\t\tcontroller.signal.addEventListener(\"abort\", abortedListener, { once: true });\n\t\t\t\tif (controller.signal.aborted) abortedListener();\n\t\t\t});\n\t\t\tconst effect = Promise.resolve().then(async () => {\n\t\t\t\tif (controller.signal.aborted) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\t\tthis.ledger.authenticate(envelope);\n\t\t\t\tawait this.auditRecord(request, \"dispatch\", controller.signal);\n\t\t\t\tif (controller.signal.aborted || performance.now() - start > remaining) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\t\tthis.ledger.authenticate(envelope);\n\t\t\t\treturn action.execute(request.operation, {\n\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t\tproof: envelope,\n\t\t\t\t\toperationDigest: reserved.digest,\n\t\t\t\t\tidentity: reserved.grant,\n\t\t\t\t\treservation: reserved.reservation\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst returned = receipt(await Promise.race([effect, aborted]));\n\t\t\tthis.ledger.authenticate(envelope);\n\t\t\tif (controller.signal.aborted || performance.now() - start > remaining) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tawait this.auditRecord(request, \"complete\", controller.signal);\n\t\t\tthis.ledger.authenticate(envelope);\n\t\t\tif (controller.signal.aborted || performance.now() - start > remaining) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tconst completed = receipt({\n\t\t\t\tvalue: returned.value,\n\t\t\t\tusage: {\n\t\t\t\t\t...returned.usage,\n\t\t\t\t\ttimeMs: Math.max(returned.usage.timeMs, Math.ceil(performance.now() - start))\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis.ledger.settle(request, completed);\n\t\t\treturn completed;\n\t\t} catch (error) {\n\t\t\tif (error instanceof OrganizationNoEffect && !controller.signal.aborted && performance.now() - start <= remaining) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.auditRecord(request, \"refused\", controller.signal);\n\t\t\t\t\tif (controller.signal.aborted || performance.now() - start > remaining) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\t\t\tthis.ledger.confirmNoEffect(request, noEffectReason(error.reason), {\n\t\t\t\t\t\t...error.usage,\n\t\t\t\t\t\ttimeMs: Math.max(error.usage.timeMs, Math.ceil(performance.now() - start))\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.ledger.markUnknown(request);\n\t\t\t\t\t} catch {}\n\t\t\t\t\tthrow new OrganizationRefused(\"outcome-unknown\");\n\t\t\t\t}\n\t\t\t\tthrow new OrganizationRefused(error.reason);\n\t\t\t}\n\t\t\tcontroller.abort();\n\t\t\ttry {\n\t\t\t\tthis.ledger.markUnknown(request);\n\t\t\t} catch {}\n\t\t\ttry {\n\t\t\t\tawait this.auditRecord(request, \"unknown\", AbortSignal.timeout(1e3));\n\t\t\t} catch {}\n\t\t\tthrow new OrganizationRefused(\"outcome-unknown\");\n\t\t} finally {\n\t\t\tclearTimeout(deadline);\n\t\t\tclearInterval(policy);\n\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\tif (abortedListener !== void 0) controller.signal.removeEventListener(\"abort\", abortedListener);\n\t\t\tthis.active.delete(controller);\n\t\t}\n\t}\n\t/** Host shutdown: withdraw admission and signal outstanding trusted effects. */\n\tclose() {\n\t\tthis.closed = true;\n\t\tfor (const controller of this.active) controller.abort();\n\t}\n};\n//#endregion\n//#region src/shared-state.ts\n/** Internal SQLite owner: every call is made inside the ledger's authenticated operation transaction. */\nvar OrganizationSharedStateSql = class {\n\tdb;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tinitialize() {\n\t\tthis.db.exec(`CREATE TABLE shared_state (\n key TEXT PRIMARY KEY, value TEXT NOT NULL, revision INTEGER NOT NULL, fence INTEGER NOT NULL,\n holder TEXT, epoch INTEGER NOT NULL, expiresAt INTEGER NOT NULL\n ) STRICT;\n CREATE TABLE state_effects (digest TEXT PRIMARY KEY, grantId TEXT NOT NULL, value TEXT NOT NULL) STRICT;`);\n\t}\n\tkey(tenant, task, resource) {\n\t\treturn organizationCanonical([\n\t\t\tidentifier(tenant),\n\t\t\tidentifier(task),\n\t\t\tidentifier(resource)\n\t\t]);\n\t}\n\tcreate(tenant, task, resource, value) {\n\t\tconst key = this.key(tenant, task, resource);\n\t\tif (this.db.prepare(\"SELECT key FROM shared_state WHERE key=?\").get(key)) throw new OrganizationRefused(\"operation-conflict\");\n\t\tthis.db.prepare(\"INSERT INTO shared_state VALUES (?,?,0,0,NULL,0,0)\").run(key, organizationCanonical(value));\n\t}\n\trow(request) {\n\t\tconst key = this.key(request.tenant, request.task, request.operation.resource);\n\t\tconst row = this.db.prepare(\"SELECT * FROM shared_state WHERE key=?\").get(key);\n\t\tif (row === void 0) throw new OrganizationRefused(\"not-authorized\");\n\t\tif (typeof row.value !== \"string\" || row.holder !== null && typeof row.holder !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\tconst value = JSON.parse(row.value);\n\t\torganizationCanonical(value);\n\t\treturn {\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\trevision: integer(row.revision),\n\t\t\tfence: integer(row.fence),\n\t\t\tholder: row.holder,\n\t\t\tepoch: integer(row.epoch),\n\t\t\texpiresAt: integer(row.expiresAt)\n\t\t};\n\t}\n\tlease(request, grant, now) {\n\t\tif (request.operation.operation !== \"state.lease\") throw new OrganizationRefused(\"not-authorized\");\n\t\tconst parameters = record(request.operation.parameters, [\"expectedRevision\", \"ttlMs\"]);\n\t\tconst revision = integer(parameters.expectedRevision);\n\t\tconst ttl = integer(parameters.ttlMs, 1);\n\t\tif (ttl > 3e4) throw new OrganizationRefused(\"invalid-schema\");\n\t\tconst expiresAt = integer(now + ttl, 1);\n\t\tif (expiresAt > request.expiresAt || expiresAt > grant.expiresAt) throw new OrganizationRefused(\"expired\");\n\t\tconst row = this.row(request);\n\t\tif (revision !== row.revision) throw new OrganizationRefused(\"operation-conflict\");\n\t\tif (row.holder !== null && row.epoch === grant.epoch && row.expiresAt > now) throw new OrganizationRefused(\"operation-pending\");\n\t\tconst fence = integer(row.fence + 1, 1);\n\t\tthis.db.prepare(\"UPDATE shared_state SET fence=?,holder=?,epoch=?,expiresAt=? WHERE key=?\").run(fence, grant.id, grant.epoch, expiresAt, row.key);\n\t\treturn Object.freeze({\n\t\t\trevision,\n\t\t\tfence,\n\t\t\texpiresAt\n\t\t});\n\t}\n\tread(request) {\n\t\tif (request.operation.operation !== \"state.read\") throw new OrganizationRefused(\"not-authorized\");\n\t\trecord(request.operation.parameters, []);\n\t\tconst row = this.row(request);\n\t\treturn Object.freeze({\n\t\t\trevision: row.revision,\n\t\t\tvalue: row.value\n\t\t});\n\t}\n\twrite(request, grant, now) {\n\t\tif (request.operation.operation !== \"state.write\") throw new OrganizationRefused(\"not-authorized\");\n\t\tconst parameters = record(request.operation.parameters, [\n\t\t\t\"expectedRevision\",\n\t\t\t\"fence\",\n\t\t\t\"value\"\n\t\t]);\n\t\tthis.assertFence(request, grant, now, integer(parameters.expectedRevision), integer(parameters.fence, 1));\n\t\treturn this.replace(request, parameters.value);\n\t}\n\tassertFence(request, grant, now, revision, fence) {\n\t\tconst row = this.row(request);\n\t\tif (row.holder !== grant.id || row.epoch !== grant.epoch || row.fence !== fence || row.expiresAt <= now || row.revision !== revision) throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn row.value;\n\t}\n\treplace(request, value) {\n\t\tconst row = this.row(request);\n\t\tconst encoded = organizationCanonical(value);\n\t\tconst revision = integer(row.revision + 1, 1);\n\t\tthis.db.prepare(\"UPDATE shared_state SET value=?,revision=? WHERE key=?\").run(encoded, revision, row.key);\n\t\treturn Object.freeze({\n\t\t\trevision,\n\t\t\tvalue: JSON.parse(encoded)\n\t\t});\n\t}\n\trecoverGit(request, expectedRevision, expectedOid, publishedOid) {\n\t\tconst row = this.row(request);\n\t\tconst value = record(row.value, [\"oid\"]);\n\t\tif (row.revision !== expectedRevision || value.oid !== expectedOid) throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn this.replace(request, { oid: publishedOid });\n\t}\n};\n//#endregion\n//#region src/ledger-anchor.ts\nconst tables = [\n\t[\"metadata\", \"id\"],\n\t[\"budgets\", \"key\"],\n\t[\"grants\", \"id\"],\n\t[\"nonces\", \"tenant,actor,nonce\"],\n\t[\"approvals\", \"id\"],\n\t[\"operations\", \"key\"],\n\t[\"shared_state\", \"key\"],\n\t[\"state_effects\", \"digest\"],\n\t[\"git_intents\", \"digest\"]\n];\n/** Hash typed, length-delimited fields without exposing policy, parameters or receipts to the anchor. */\nfunction digest(db, ledger) {\n\tconst hash = createHash(\"sha256\");\n\tconst field = (value) => {\n\t\tif (typeof value === \"number\" && !Number.isSafeInteger(value)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tconst bytes = Buffer.from(value === null ? \"\" : String(value));\n\t\thash.update(`${value === null ? \"null\" : typeof value}:${bytes.length}:`).update(bytes);\n\t};\n\tfield(\"robota/organization-ledger-anchor/v1\");\n\tfield(ledger);\n\tfor (const [table, order] of tables) {\n\t\tfield(table);\n\t\tconst schema = db.prepare(\"SELECT sql FROM sqlite_schema WHERE type='table' AND name=?\").get(table);\n\t\tif (typeof schema?.sql !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\tfield(schema.sql);\n\t\tconst rows = db.prepare(`SELECT * FROM ${table} ORDER BY ${order}`).all();\n\t\tfield(rows.length);\n\t\tfor (const row of rows) {\n\t\t\tconst keys = Object.keys(row).sort();\n\t\t\tfield(keys.length);\n\t\t\tfor (const key of keys) {\n\t\t\t\tfield(key);\n\t\t\t\tfield(row[key]);\n\t\t\t}\n\t\t}\n\t}\n\treturn hash.digest(\"hex\");\n}\n/** Anchor advances before SQLite commit; uncertain confirmation freezes authority rather than refunds it. */\nvar OrganizationLedgerIntegrity = class {\n\tdb;\n\tledger;\n\tport;\n\tconstructor(db, port) {\n\t\tthis.db = db;\n\t\tthis.ledger = identifier(port.ledger);\n\t\tif (typeof port.read !== \"function\" || typeof port.compareAndSet !== \"function\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.port = Object.freeze({\n\t\t\tledger: this.ledger,\n\t\t\tread: port.read.bind(port),\n\t\t\tcompareAndSet: port.compareAndSet.bind(port)\n\t\t});\n\t}\n\tread() {\n\t\tconst head = this.port.read();\n\t\tif (head === void 0) return void 0;\n\t\tif (head === null || Object.keys(head).sort().join(\",\") !== \"digest,ledger,revision,version\" || head.version !== 1 || head.ledger !== this.ledger || typeof head.digest !== \"string\" || !/^[a-f0-9]{64}$/u.test(head.digest)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\treturn Object.freeze({\n\t\t\tversion: 1,\n\t\t\tledger: this.ledger,\n\t\t\trevision: integer(head.revision, 1),\n\t\t\tdigest: head.digest\n\t\t});\n\t}\n\tinitialize(create) {\n\t\tif (!create) {\n\t\t\tthis.verify();\n\t\t\treturn;\n\t\t}\n\t\tif (this.read() !== void 0) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.commit(void 0, {\n\t\t\tversion: 1,\n\t\t\tledger: this.ledger,\n\t\t\trevision: 1,\n\t\t\tdigest: digest(this.db, this.ledger)\n\t\t});\n\t}\n\tverify() {\n\t\tconst head = this.read();\n\t\tif (head === void 0 || head.digest !== digest(this.db, this.ledger)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\treturn head;\n\t}\n\tadvance(previous) {\n\t\tconst nextDigest = digest(this.db, this.ledger);\n\t\tif (nextDigest === previous.digest) return;\n\t\tthis.commit(previous, {\n\t\t\tversion: 1,\n\t\t\tledger: this.ledger,\n\t\t\trevision: integer(previous.revision + 1, 1),\n\t\t\tdigest: nextDigest\n\t\t});\n\t}\n\tcommit(expected, next) {\n\t\tthis.port.compareAndSet(expected, Object.freeze(next));\n\t\tconst confirmed = this.read();\n\t\tif (confirmed?.revision !== next.revision || confirmed.digest !== next.digest) throw new OrganizationRefused(\"policy-unavailable\");\n\t}\n};\n//#endregion\n//#region src/sqlite-ledger.ts\nconst UNIT_KEYS = [\n\t\"tokens\",\n\t\"timeMs\",\n\t\"costMicros\"\n];\nfunction scopeKey(kind, ...parts) {\n\tconst arity = {\n\t\tglobal: 0,\n\t\ttenant: 1,\n\t\ttask: 2,\n\t\tgrant: 1\n\t}[kind];\n\tif (arity === void 0 || parts.length !== arity) throw new OrganizationRefused(\"invalid-schema\");\n\treturn organizationCanonical([kind, ...parts]);\n}\n/** Durable policy/budgets live in the operator's domain, never in a worker checkpoint. */\nvar OrganizationLedger = class {\n\tdb;\n\tstate;\n\tpath;\n\tinode;\n\tclosed = false;\n\tnow;\n\tworkloadKey;\n\tapprovalKey;\n\tintegrity;\n\taudience;\n\tmaxGrantTtlMs;\n\tmaxRequestTtlMs;\n\tconstructor(options) {\n\t\tif (options.anchor !== void 0 && options.upgrade === true) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.audience = identifier(options.audience);\n\t\tthis.workloadKey = publicKey(options.workloadPublicKey);\n\t\tthis.approvalKey = publicKey(options.approvalPublicKey);\n\t\tif (this.workloadKey.export({\n\t\t\ttype: \"spki\",\n\t\t\tformat: \"der\"\n\t\t}).equals(this.approvalKey.export({\n\t\t\ttype: \"spki\",\n\t\t\tformat: \"der\"\n\t\t}))) throw new OrganizationRefused(\"invalid-schema\");\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.maxGrantTtlMs = integer(options.maxGrantTtlMs ?? 3e5, 1);\n\t\tthis.maxRequestTtlMs = integer(options.maxRequestTtlMs ?? 3e4, 1);\n\t\tif (!isAbsolute(options.path)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tlet opened;\n\t\ttry {\n\t\t\tconst directory = realpathSync(dirname(options.path));\n\t\t\tconst root = lstatSync(directory);\n\t\t\tconst uid = process.getuid?.();\n\t\t\tif (!root.isDirectory() || (root.mode & 63) !== 0 || uid !== void 0 && root.uid !== uid) throw new Error(\"unowned directory\");\n\t\t\tthis.path = join(directory, basename(options.path));\n\t\t\tif (options.create === true) closeSync(openSync(this.path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 384));\n\t\t\tconst file = lstatSync(this.path);\n\t\t\tif (!file.isFile() || file.nlink !== 1 || (file.mode & 63) !== 0 || uid !== void 0 && file.uid !== uid) throw new Error(\"unowned database\");\n\t\t\tthis.inode = {\n\t\t\t\tino: file.ino,\n\t\t\t\tdev: file.dev\n\t\t\t};\n\t\t\tif (options.create !== true) this.verifyFile();\n\t\t\tconst sqlite = createRequire(import.meta.url)(\"node:sqlite\");\n\t\t\tthis.db = new sqlite.DatabaseSync(this.path, {\n\t\t\t\tallowExtension: false,\n\t\t\t\tenableDoubleQuotedStringLiterals: false\n\t\t\t});\n\t\t\topened = this.db;\n\t\t\tthis.state = new OrganizationSharedStateSql(this.db);\n\t\t\tthis.db.exec(\"PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;\");\n\t\t\tif (options.create === true) {\n\t\t\t\tthis.db.exec(`\n CREATE TABLE metadata (id INTEGER PRIMARY KEY CHECK(id=1), version INTEGER NOT NULL, epoch INTEGER NOT NULL, active INTEGER NOT NULL) STRICT;\n INSERT INTO metadata VALUES (1,3,1,1);\n CREATE TABLE budgets (key TEXT PRIMARY KEY, limits TEXT NOT NULL, spent TEXT NOT NULL, held TEXT NOT NULL, active INTEGER NOT NULL, stopped INTEGER NOT NULL) STRICT;\n CREATE TABLE grants (id TEXT PRIMARY KEY, claims TEXT NOT NULL, revoked INTEGER NOT NULL) STRICT;\n CREATE TABLE nonces (tenant TEXT NOT NULL, actor TEXT NOT NULL, nonce TEXT NOT NULL, PRIMARY KEY(tenant,actor,nonce)) STRICT;\n CREATE TABLE approvals (id TEXT PRIMARY KEY, digest TEXT NOT NULL) STRICT;\n CREATE TABLE operations (key TEXT PRIMARY KEY, digest TEXT NOT NULL, grantId TEXT NOT NULL, status TEXT NOT NULL, scopes TEXT NOT NULL, reservation TEXT NOT NULL, receipt TEXT) STRICT;\n `);\n\t\t\t\tthis.state.initialize();\n\t\t\t\tthis.initializeGit();\n\t\t\t}\n\t\t\tlet metadata = this.db.prepare(\"SELECT version FROM metadata WHERE id=1\").get();\n\t\t\tif ([1, 2].includes(Number(metadata?.version)) && options.upgrade === true) {\n\t\t\t\tthis.db.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\ttry {\n\t\t\t\t\tconst current = this.db.prepare(\"SELECT version FROM metadata WHERE id=1\").get();\n\t\t\t\t\tif (current?.version === 1) this.state.initialize();\n\t\t\t\t\tif (current?.version === 1 || current?.version === 2) {\n\t\t\t\t\t\tthis.initializeGit();\n\t\t\t\t\t\tthis.db.exec(\"UPDATE metadata SET version=3 WHERE id=1\");\n\t\t\t\t\t} else if (current?.version !== 3) throw new Error(\"unsupported database\");\n\t\t\t\t\tthis.db.exec(\"COMMIT\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.db.exec(\"ROLLBACK\");\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tmetadata = this.db.prepare(\"SELECT version FROM metadata WHERE id=1\").get();\n\t\t\t}\n\t\t\tif (metadata?.version !== 3 || this.db.prepare(\"PRAGMA quick_check\").get()?.quick_check !== \"ok\") throw new Error(\"invalid database\");\n\t\t\tthis.db.prepare(\"SELECT key,value,revision,fence,holder,epoch,expiresAt FROM shared_state LIMIT 0\").all();\n\t\t\tthis.db.prepare(\"SELECT digest,grantId,value FROM state_effects LIMIT 0\").all();\n\t\t\tthis.db.prepare(\"SELECT digest,grantId,value FROM git_intents LIMIT 0\").all();\n\t\t\tif (options.anchor !== void 0) {\n\t\t\t\tthis.integrity = new OrganizationLedgerIntegrity(this.db, options.anchor);\n\t\t\t\tthis.db.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\ttry {\n\t\t\t\t\tthis.integrity.initialize(options.create === true);\n\t\t\t\t\tthis.db.exec(\"COMMIT\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.db.exec(\"ROLLBACK\");\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\topened?.close();\n\t\t\t} catch {}\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t}\n\t}\n\tinitializeGit() {\n\t\tthis.db.exec(\"CREATE TABLE git_intents (digest TEXT PRIMARY KEY, grantId TEXT NOT NULL, value TEXT NOT NULL) STRICT;\");\n\t}\n\tverifyFile() {\n\t\tconst descriptor = openSync(this.path, constants.O_RDONLY | constants.O_NOFOLLOW);\n\t\ttry {\n\t\t\tconst file = fstatSync(descriptor);\n\t\t\tconst uid = process.getuid?.();\n\t\t\tconst header = Buffer.alloc(16);\n\t\t\tif (!file.isFile() || file.ino !== this.inode.ino || file.dev !== this.inode.dev || file.nlink !== 1 || (file.mode & 63) !== 0 || uid !== void 0 && file.uid !== uid || readSync(descriptor, header, 0, 16, 0) !== 16 || !header.equals(Buffer.from(\"SQLite format 3\\0\"))) throw new Error(\"changed database\");\n\t\t} finally {\n\t\t\tcloseSync(descriptor);\n\t\t}\n\t}\n\ttransaction(action) {\n\t\tif (this.closed) throw new OrganizationRefused(\"policy-unavailable\");\n\t\ttry {\n\t\t\tthis.verifyFile();\n\t\t\tthis.db.exec(\"BEGIN IMMEDIATE\");\n\t\t\ttry {\n\t\t\t\tconst checkpoint = this.integrity?.verify();\n\t\t\t\tconst result = action();\n\t\t\t\tif (checkpoint !== void 0) this.integrity.advance(checkpoint);\n\t\t\t\tthis.db.exec(\"COMMIT\");\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\tthis.db.exec(\"ROLLBACK\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (error instanceof OrganizationRefused) throw error;\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t}\n\t}\n\tmetadata() {\n\t\tconst row = this.db.prepare(\"SELECT version,epoch,active FROM metadata WHERE id=1\").get();\n\t\tif (row === void 0 || row.version !== 3) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tif (row.active !== 0 && row.active !== 1) throw new OrganizationRefused(\"policy-unavailable\");\n\t\treturn {\n\t\t\tepoch: integer(row.epoch, 1),\n\t\t\tactive: row.active === 1\n\t\t};\n\t}\n\tnewBudget(key, limits) {\n\t\tbudget(limits);\n\t\tif (this.db.prepare(\"SELECT key FROM budgets WHERE key=?\").get(key) !== void 0) throw new OrganizationRefused(\"operation-conflict\");\n\t\tconst zero = organizationCanonical({\n\t\t\ttokens: 0,\n\t\t\ttimeMs: 0,\n\t\t\tcostMicros: 0\n\t\t});\n\t\tthis.db.prepare(\"INSERT INTO budgets VALUES (?,?,?,?,0,0)\").run(key, organizationCanonical(limits), zero, zero);\n\t}\n\t/** Trusted administration only; these methods are not present on the HTTP broker ingress. */\n\tcreateGlobalBudget(limits) {\n\t\tthis.transaction(() => this.newBudget(scopeKey(\"global\"), limits));\n\t}\n\tcreateTenant(tenant, limits) {\n\t\tidentifier(tenant);\n\t\tthis.transaction(() => {\n\t\t\tthis.liveBudget(scopeKey(\"global\"));\n\t\t\tthis.newBudget(scopeKey(\"tenant\", tenant), limits);\n\t\t});\n\t}\n\tcreateTask(tenant, task, limits) {\n\t\tidentifier(tenant);\n\t\tidentifier(task);\n\t\tthis.transaction(() => {\n\t\t\tthis.liveBudget(scopeKey(\"tenant\", tenant));\n\t\t\tthis.newBudget(scopeKey(\"task\", tenant, task), limits);\n\t\t});\n\t}\n\tregisterGrant(envelope) {\n\t\tconst grant = grantClaims(envelope.claims);\n\t\tverifyEnvelope(\"workload\", envelope, this.workloadKey);\n\t\tthis.transaction(() => {\n\t\t\tconst metadata = this.metadata();\n\t\t\tcurrentTime(grant, this.now(), this.maxGrantTtlMs);\n\t\t\tif (!metadata.active || metadata.epoch !== grant.epoch || grant.audience !== this.audience) throw new OrganizationRefused(\"revoked\");\n\t\t\tthis.liveBudget(scopeKey(\"global\"));\n\t\t\tthis.liveBudget(scopeKey(\"tenant\", grant.tenant));\n\t\t\tthis.liveBudget(scopeKey(\"task\", grant.tenant, grant.task));\n\t\t\tif (grant.parent !== null) {\n\t\t\t\tconst parent = this.chain(grant.parent)[0];\n\t\t\t\tif (parent.tenant !== grant.tenant || parent.task !== grant.task || parent.audience !== grant.audience || parent.role !== grant.role || parent.notBefore > grant.notBefore || parent.expiresAt < grant.expiresAt || UNIT_KEYS.some((key) => grant.budget[key] > parent.budget[key]) || grant.budget.concurrency > parent.budget.concurrency || grant.scopes.some((scope) => {\n\t\t\t\t\tconst inherited = parent.scopes.find((candidate) => candidate.resource === scope.resource);\n\t\t\t\t\treturn inherited === void 0 || scope.operations.some((operation) => !inherited.operations.includes(operation));\n\t\t\t\t})) throw new OrganizationRefused(\"not-authorized\");\n\t\t\t}\n\t\t\tif (this.db.prepare(\"SELECT id FROM grants WHERE id=?\").get(grant.id)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tthis.db.prepare(\"INSERT INTO grants VALUES (?,?,0)\").run(grant.id, organizationCanonical(grant));\n\t\t\tthis.newBudget(scopeKey(\"grant\", grant.id), grant.budget);\n\t\t});\n\t}\n\tchain(grantId) {\n\t\tconst metadata = this.metadata();\n\t\tif (!metadata.active) throw new OrganizationRefused(\"revoked\");\n\t\tconst grants = [];\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tlet id = grantId;\n\t\twhile (id !== null) {\n\t\t\tif (seen.has(id) || seen.size >= 32) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\tseen.add(id);\n\t\t\tconst row = this.db.prepare(\"SELECT claims,revoked FROM grants WHERE id=?\").get(id);\n\t\t\tif (row === void 0 || row.revoked !== 0 || typeof row.claims !== \"string\") throw new OrganizationRefused(\"revoked\");\n\t\t\tconst grant = grantClaims(JSON.parse(row.claims));\n\t\t\tcurrentTime(grant, this.now(), this.maxGrantTtlMs);\n\t\t\tif (grant.epoch !== metadata.epoch || grant.audience !== this.audience) throw new OrganizationRefused(\"revoked\");\n\t\t\tthis.liveBudget(scopeKey(\"grant\", grant.id));\n\t\t\tgrants.push(grant);\n\t\t\tid = grant.parent;\n\t\t}\n\t\tconst leaf = grants[0];\n\t\tthis.liveBudget(scopeKey(\"global\"));\n\t\tthis.liveBudget(scopeKey(\"tenant\", leaf.tenant));\n\t\tthis.liveBudget(scopeKey(\"task\", leaf.tenant, leaf.task));\n\t\treturn grants;\n\t}\n\tcurrentGrant(grantId) {\n\t\treturn this.transaction(() => this.chain(identifier(grantId))[0]);\n\t}\n\t/** Owner inventory inspection, including expired/revoked grants; never grants execution authority. */\n\tregisteredGrant(grantId) {\n\t\treturn this.transaction(() => {\n\t\t\tconst row = this.db.prepare(\"SELECT claims FROM grants WHERE id=?\").get(identifier(grantId));\n\t\t\tif (typeof row?.claims !== \"string\") throw new OrganizationRefused(\"not-authorized\");\n\t\t\treturn grantClaims(JSON.parse(row.claims));\n\t\t});\n\t}\n\t/** Trusted supervisory accounting for an owner-installed single-purpose workload grant. */\n\tgrantOperationCount(grantId) {\n\t\treturn this.transaction(() => {\n\t\t\tthis.chain(identifier(grantId));\n\t\t\treturn integer(this.db.prepare(\"SELECT COUNT(*) AS count FROM operations WHERE grantId=?\").get(grantId)?.count);\n\t\t});\n\t}\n\t/** Owner composition can require integrity rather than silently accepting legacy SDK mode. */\n\tverifyAnchoredAuthority() {\n\t\tif (this.integrity === void 0) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.transaction(() => void 0);\n\t}\n\tauthenticateInside(envelope) {\n\t\tconst request = requestClaims(envelope.claims);\n\t\tconst grants = this.chain(request.grantId);\n\t\tconst grant = grants[0];\n\t\tverifyEnvelope(\"request\", envelope, publicKey(grant.publicKey));\n\t\tcurrentTime(request, this.now(), this.maxRequestTtlMs);\n\t\tif (request.notBefore < grant.notBefore || request.expiresAt > grant.expiresAt) throw new OrganizationRefused(\"expired\");\n\t\tif (request.tenant !== grant.tenant || request.task !== grant.task || request.actor !== grant.actor || request.audience !== grant.audience || request.epoch !== grant.epoch || !grant.scopes.some((scope) => scope.resource === request.operation.resource && scope.operations.includes(request.operation.operation))) throw new OrganizationRefused(\"not-authorized\");\n\t\treturn {\n\t\t\trequest,\n\t\t\tgrant,\n\t\t\tgrants\n\t\t};\n\t}\n\tauthenticate(envelope) {\n\t\treturn this.transaction(() => this.authenticateInside(envelope));\n\t}\n\t/** Owner administration only; state creation cannot overwrite an existing resource or its fence. */\n\tcreateStateResource(tenant, task, resource, value) {\n\t\tthis.transaction(() => {\n\t\t\tthis.liveBudget(scopeKey(\"global\"));\n\t\t\tthis.liveBudget(scopeKey(\"tenant\", identifier(tenant)));\n\t\t\tthis.liveBudget(scopeKey(\"task\", tenant, identifier(task)));\n\t\t\tthis.state.create(tenant, task, resource, value);\n\t\t});\n\t}\n\tactiveOperation(envelope) {\n\t\tconst result = this.authenticateInside(envelope);\n\t\tconst operation = this.operation(this.key(result.request));\n\t\tif (operation === void 0 || operation.status !== \"running\" || operation.digest !== organizationOperationDigest(result.request) || operation.grantId !== result.grant.id) throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn result;\n\t}\n\tstateOperation(envelope, action) {\n\t\treturn this.transaction(() => {\n\t\t\tconst { request, grant } = this.activeOperation(envelope);\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (this.db.prepare(\"SELECT digest FROM state_effects WHERE digest=?\").get(digest)) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tconst result = action(request, grant);\n\t\t\tthis.db.prepare(\"INSERT INTO state_effects VALUES (?,?,?)\").run(digest, grant.id, organizationCanonical(result));\n\t\t\treturn result;\n\t\t});\n\t}\n\tleaseState(envelope) {\n\t\treturn this.stateOperation(envelope, (request, grant) => this.state.lease(request, grant, this.now()));\n\t}\n\treadState(envelope) {\n\t\treturn this.stateOperation(envelope, (request) => this.state.read(request));\n\t}\n\twriteState(envelope) {\n\t\treturn this.stateOperation(envelope, (request, grant) => this.state.write(request, grant, this.now()));\n\t}\n\t/** Trusted Git owner only. Persist an unreachable receipt intent before any target ref can change. */\n\tprepareGitPublication(envelope, asset) {\n\t\treturn this.transaction(() => {\n\t\t\tconst { request, grant } = this.activeOperation(envelope);\n\t\t\tif (request.operation.operation !== \"git.publish\") throw new OrganizationRefused(\"not-authorized\");\n\t\t\tconst params = gitParameters(request.operation.parameters);\n\t\t\tif (record(this.state.assertFence(request, grant, this.now(), params.expectedRevision, params.fence), [\"oid\"]).oid !== params.expectedOid) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (this.db.prepare(\"SELECT digest FROM git_intents WHERE digest=?\").get(digest)) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tconst intent = asset.prepare(digest, params);\n\t\t\tthis.db.prepare(\"INSERT INTO git_intents VALUES (?,?,?)\").run(digest, grant.id, organizationCanonical(intent));\n\t\t\treturn intent;\n\t\t});\n\t}\n\tgitIntent(request, asset) {\n\t\tconst digest = organizationOperationDigest(request);\n\t\tconst row = this.db.prepare(\"SELECT grantId,value FROM git_intents WHERE digest=?\").get(digest);\n\t\tif (row === void 0) throw new OrganizationRefused(\"outcome-unknown\");\n\t\tif (row.grantId !== request.grantId || typeof row.value !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\tconst data = record(JSON.parse(row.value), [\n\t\t\t\"asset\",\n\t\t\t\"digest\",\n\t\t\t\"expectedRevision\",\n\t\t\t\"fence\",\n\t\t\t\"expectedOid\",\n\t\t\t\"candidateOid\",\n\t\t\t\"publishedOid\"\n\t\t]);\n\t\tconst params = gitParameters(request.operation.parameters);\n\t\tif (request.operation.operation !== \"git.publish\" || data.digest !== digest || data.asset !== asset.identity || Object.entries(params).some(([key, value]) => data[key] !== value) || typeof data.publishedOid !== \"string\") throw new OrganizationRefused(\"operation-conflict\");\n\t\treturn data;\n\t}\n\t/** SQL locking serializes policy/fence checks with dispatch. External Git and SQL are NOT an atomic store. */\n\tcommitGitPublication(envelope, asset) {\n\t\treturn this.stateOperation(envelope, (request, grant) => {\n\t\t\tconst intent = this.gitIntent(request, asset);\n\t\t\tif (record(this.state.assertFence(request, grant, this.now(), intent.expectedRevision, intent.fence), [\"oid\"]).oid !== intent.expectedOid) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tasset.publish(intent);\n\t\t\treturn this.state.replace(request, { oid: intent.publishedOid });\n\t\t});\n\t}\n\t/** Owner-only proof of a past branch publication. No absent effect is refunded, no workload authority is restored. */\n\treconcileGitPublication(value, asset) {\n\t\tconst request = requestClaims(value);\n\t\tthis.transaction(() => {\n\t\t\tconst operation = this.operation(this.key(request));\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (operation === void 0 || operation.digest !== digest || operation.grantId !== request.grantId || ![\n\t\t\t\t\"running\",\n\t\t\t\t\"unknown\",\n\t\t\t\t\"complete\"\n\t\t\t].includes(operation.status)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tconst intent = this.gitIntent(request, asset);\n\t\t\tif (!asset.wasPublished(intent)) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tif (this.db.prepare(\"SELECT digest FROM state_effects WHERE digest=?\").get(digest) === void 0) {\n\t\t\t\tconst result = this.state.recoverGit(request, intent.expectedRevision, intent.expectedOid, intent.publishedOid);\n\t\t\t\tthis.db.prepare(\"INSERT INTO state_effects VALUES (?,?,?)\").run(digest, request.grantId, organizationCanonical(result));\n\t\t\t}\n\t\t});\n\t\treturn this.reconcileStateOperation(request);\n\t}\n\t/** Trusted asset-owner reconciliation only. The atomic state outcome proves this specific effect; no worker route exposes it. */\n\treconcileStateOperation(value) {\n\t\tconst request = requestClaims(value);\n\t\tconst outcome = this.transaction(() => {\n\t\t\tconst operation = this.operation(this.key(request));\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (operation === void 0 || operation.grantId !== request.grantId || operation.digest !== digest) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tif (operation.status === \"complete\" && operation.receipt !== null) return { complete: operation.receipt };\n\t\t\tif (![\"running\", \"unknown\"].includes(operation.status)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tconst effect = this.db.prepare(\"SELECT grantId,value FROM state_effects WHERE digest=?\").get(digest);\n\t\t\tif (effect === void 0) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tif (effect.grantId !== request.grantId || typeof effect.value !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\treturn { receipt: receipt({\n\t\t\t\tvalue: JSON.parse(effect.value),\n\t\t\t\tusage: operation.reservation\n\t\t\t}) };\n\t\t});\n\t\tif (outcome.complete !== void 0) return outcome.complete;\n\t\tthis.recordReceipt(request, outcome.receipt, \"complete\", true);\n\t\treturn outcome.receipt;\n\t}\n\tliveBudget(key) {\n\t\tconst state = this.storedBudget(key);\n\t\tif (state.stopped) throw new OrganizationRefused(\"revoked\");\n\t\treturn state;\n\t}\n\tstoredBudget(key) {\n\t\tconst row = this.db.prepare(\"SELECT * FROM budgets WHERE key=?\").get(key);\n\t\tif (row === void 0 || row.stopped !== 0 && row.stopped !== 1 || typeof row.limits !== \"string\" || typeof row.spent !== \"string\" || typeof row.held !== \"string\") throw new OrganizationRefused(\"revoked\");\n\t\treturn {\n\t\t\tlimits: budget(JSON.parse(row.limits)),\n\t\t\tspent: units(JSON.parse(row.spent)),\n\t\t\theld: units(JSON.parse(row.held)),\n\t\t\tactive: integer(row.active),\n\t\t\tstopped: row.stopped === 1\n\t\t};\n\t}\n\toperation(key) {\n\t\tconst row = this.db.prepare(\"SELECT * FROM operations WHERE key=?\").get(key);\n\t\tif (row === void 0) return void 0;\n\t\tif (typeof row.digest !== \"string\" || typeof row.grantId !== \"string\" || typeof row.status !== \"string\" || typeof row.scopes !== \"string\" || typeof row.reservation !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\tconst scopes = JSON.parse(row.scopes);\n\t\tif (!Array.isArray(scopes) || scopes.length < 4 || scopes.some((scope) => typeof scope !== \"string\") || new Set(scopes).size !== scopes.length || ![\n\t\t\t\"running\",\n\t\t\t\"unknown\",\n\t\t\t\"complete\",\n\t\t\t\"refused\"\n\t\t].includes(row.status) || !/^[a-f0-9]{64}$/.test(row.digest)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\treturn {\n\t\t\tdigest: row.digest,\n\t\t\tgrantId: row.grantId,\n\t\t\tstatus: row.status,\n\t\t\tscopes,\n\t\t\treservation: units(JSON.parse(row.reservation)),\n\t\t\treceipt: typeof row.receipt === \"string\" ? receipt(JSON.parse(row.receipt)) : null\n\t\t};\n\t}\n\treserve(envelope, reservation, approval, requiresApproval) {\n\t\tunits(reservation);\n\t\treturn this.transaction(() => {\n\t\t\tconst { request, grant, grants } = this.authenticateInside(envelope);\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (this.db.prepare(\"SELECT nonce FROM nonces WHERE tenant=? AND actor=? AND nonce=?\").get(request.tenant, request.actor, request.nonce) !== void 0) throw new OrganizationRefused(\"replayed\");\n\t\t\tconst key = scopeKey(\"task\", grant.tenant, grant.task) + \":\" + request.operation.idempotencyKey;\n\t\t\tconst previous = this.operation(key);\n\t\t\tif (previous !== void 0) {\n\t\t\t\tif (previous.digest !== digest || previous.grantId !== grant.id) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\t\tif (![\"complete\", \"refused\"].includes(previous.status) || previous.receipt === null) throw new OrganizationRefused(previous.status === \"unknown\" ? \"outcome-unknown\" : \"operation-pending\");\n\t\t\t\tthis.db.prepare(\"INSERT INTO nonces VALUES (?,?,?)\").run(request.tenant, request.actor, request.nonce);\n\t\t\t\tif (previous.status === \"refused\") return {\n\t\t\t\t\tkind: \"refused\",\n\t\t\t\t\tdigest,\n\t\t\t\t\treason: noEffectReason(record(previous.receipt.value, [\"refused\"]).refused)\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"complete\",\n\t\t\t\t\tdigest,\n\t\t\t\t\treceipt: previous.receipt\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (requiresApproval && approval === null) throw new OrganizationRefused(\"approval-required\");\n\t\t\tif (approval !== null) try {\n\t\t\t\tverifyEnvelope(\"approval\", approval, this.approvalKey);\n\t\t\t\tconst claims = approvalClaims(approval.claims);\n\t\t\t\tcurrentTime(claims, this.now(), this.maxGrantTtlMs);\n\t\t\t\tif (claims.tenant !== grant.tenant || claims.task !== grant.task || claims.actor !== grant.actor || claims.audience !== grant.audience || claims.epoch !== grant.epoch || claims.environment !== request.operation.environment || claims.operationDigest !== digest) throw new OrganizationRefused(\"approval-invalid\");\n\t\t\t\tif (this.db.prepare(\"SELECT id FROM approvals WHERE id=?\").get(claims.id)) throw new OrganizationRefused(\"approval-reused\");\n\t\t\t\tthis.db.prepare(\"INSERT INTO approvals VALUES (?,?)\").run(claims.id, digest);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof OrganizationRefused && error.reason === \"approval-reused\") throw error;\n\t\t\t\tthrow new OrganizationRefused(\"approval-invalid\");\n\t\t\t}\n\t\t\tconst scopes = [\n\t\t\t\tscopeKey(\"global\"),\n\t\t\t\tscopeKey(\"tenant\", grant.tenant),\n\t\t\t\tscopeKey(\"task\", grant.tenant, grant.task),\n\t\t\t\t...grants.map((item) => scopeKey(\"grant\", item.id))\n\t\t\t];\n\t\t\tfor (const scope of scopes) {\n\t\t\t\tconst state = this.liveBudget(scope);\n\t\t\t\tif (state.active >= state.limits.concurrency || UNIT_KEYS.some((unit) => reservation[unit] > state.limits[unit] - state.spent[unit] - state.held[unit])) throw new OrganizationRefused(\"budget-exhausted\");\n\t\t\t\tconst held = Object.fromEntries(UNIT_KEYS.map((unit) => [unit, state.held[unit] + reservation[unit]]));\n\t\t\t\tthis.db.prepare(\"UPDATE budgets SET held=?,active=active+1 WHERE key=?\").run(organizationCanonical(held), scope);\n\t\t\t}\n\t\t\tthis.db.prepare(\"INSERT INTO nonces VALUES (?,?,?)\").run(request.tenant, request.actor, request.nonce);\n\t\t\tthis.db.prepare(\"INSERT INTO operations VALUES (?,?,?,'running',?,?,NULL)\").run(key, digest, grant.id, organizationCanonical(scopes), organizationCanonical(reservation));\n\t\t\treturn {\n\t\t\t\tkind: \"reserved\",\n\t\t\t\tdigest,\n\t\t\t\tgrant,\n\t\t\t\treservation: Object.freeze({ ...reservation })\n\t\t\t};\n\t\t});\n\t}\n\tkey(request) {\n\t\treturn scopeKey(\"task\", request.tenant, request.task) + \":\" + request.operation.idempotencyKey;\n\t}\n\t/** A crash/unknown effect keeps every reservation. No request route can refund or retry it. */\n\tmarkUnknown(request) {\n\t\tthis.transaction(() => {\n\t\t\tconst key = this.key(request);\n\t\t\tconst row = this.operation(key);\n\t\t\tif (row === void 0 || row.digest !== organizationOperationDigest(request) || ![\"running\", \"unknown\"].includes(row.status)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tthis.db.prepare(\"UPDATE operations SET status='unknown' WHERE key=?\").run(key);\n\t\t});\n\t}\n\tsettle(request, receipt) {\n\t\tthis.recordReceipt(request, receipt, \"complete\");\n\t}\n\t/** External asset owner only: confirm an exact unknown effect, charge its retained bound, never restore authority. */\n\treconcileExternalOperation(value, confirmedValue) {\n\t\tconst request = requestClaims(value);\n\t\tconst outcome = this.transaction(() => {\n\t\t\tconst row = this.operation(this.key(request));\n\t\t\tconst digest = organizationOperationDigest(request);\n\t\t\tif (!row || row.digest !== digest || this.db.prepare(\"SELECT digest FROM state_effects WHERE digest=?\").get(digest) || this.db.prepare(\"SELECT digest FROM git_intents WHERE digest=?\").get(digest)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tif (row.status === \"complete\" && row.receipt !== null) {\n\t\t\t\tif (organizationCanonical(row.receipt.value) !== organizationCanonical(confirmedValue)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\t\treturn { cached: row.receipt };\n\t\t\t}\n\t\t\tif (![\"running\", \"unknown\"].includes(row.status)) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\treturn { receipt: receipt({\n\t\t\t\tvalue: confirmedValue,\n\t\t\t\tusage: row.reservation\n\t\t\t}) };\n\t\t});\n\t\tif (outcome.cached) return outcome.cached;\n\t\tthis.recordReceipt(request, outcome.receipt, \"complete\", true);\n\t\treturn outcome.receipt;\n\t}\n\t/** Trusted asset owner only: a proved no-effect outcome, never a worker-provided refund assertion. */\n\tconfirmNoEffect(request, reason, usage) {\n\t\tthis.recordReceipt(request, {\n\t\t\tvalue: { refused: noEffectReason(reason) },\n\t\t\tusage\n\t\t}, \"refused\");\n\t}\n\trecordReceipt(request, receipt$1, status, allowUnknown = false) {\n\t\tconst validReceipt = receipt(receipt$1);\n\t\tconst usage = validReceipt.usage;\n\t\tconst encoded = organizationCanonical(validReceipt);\n\t\tthis.transaction(() => {\n\t\t\tconst key = this.key(request);\n\t\t\tconst row = this.operation(key);\n\t\t\tif (row === void 0 || row.digest !== organizationOperationDigest(request) || row.status !== \"running\" && !(allowUnknown && row.status === \"unknown\")) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tif (UNIT_KEYS.some((unit) => usage[unit] > row.reservation[unit])) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tif (status === \"refused\" && (this.db.prepare(\"SELECT digest FROM state_effects WHERE digest=?\").get(row.digest) || this.db.prepare(\"SELECT digest FROM git_intents WHERE digest=?\").get(row.digest))) throw new OrganizationRefused(\"outcome-unknown\");\n\t\t\tfor (const scope of row.scopes) {\n\t\t\t\tconst stored = this.db.prepare(\"SELECT spent,held,active FROM budgets WHERE key=?\").get(scope);\n\t\t\t\tif (stored === void 0 || typeof stored.spent !== \"string\" || typeof stored.held !== \"string\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\t\tconst spent = units(JSON.parse(stored.spent));\n\t\t\t\tconst held = units(JSON.parse(stored.held));\n\t\t\t\tinteger(stored.active, 1);\n\t\t\t\tconst nextSpent = Object.fromEntries(UNIT_KEYS.map((unit) => [unit, integer(spent[unit] + usage[unit])]));\n\t\t\t\tconst nextHeld = Object.fromEntries(UNIT_KEYS.map((unit) => [unit, integer(held[unit] - row.reservation[unit])]));\n\t\t\t\tthis.db.prepare(\"UPDATE budgets SET spent=?,held=?,active=active-1 WHERE key=?\").run(organizationCanonical(nextSpent), organizationCanonical(nextHeld), scope);\n\t\t\t}\n\t\t\tthis.db.prepare(\"UPDATE operations SET status=?,receipt=? WHERE key=?\").run(status, encoded, key);\n\t\t});\n\t}\n\trevokeGrant(grantId) {\n\t\tthis.transaction(() => {\n\t\t\tthis.db.prepare(\"UPDATE grants SET revoked=1 WHERE id=?\").run(identifier(grantId));\n\t\t});\n\t}\n\tstopTask(tenant, task) {\n\t\tthis.transaction(() => {\n\t\t\tthis.db.prepare(\"UPDATE budgets SET stopped=1 WHERE key=?\").run(scopeKey(\"task\", identifier(tenant), identifier(task)));\n\t\t});\n\t}\n\tstopTenant(tenant) {\n\t\tthis.transaction(() => {\n\t\t\tthis.db.prepare(\"UPDATE budgets SET stopped=1 WHERE key=?\").run(scopeKey(\"tenant\", identifier(tenant)));\n\t\t});\n\t}\n\temergencyStop() {\n\t\tthis.transaction(() => {\n\t\t\tthis.db.exec(\"UPDATE metadata SET active=0,epoch=epoch+1 WHERE id=1\");\n\t\t});\n\t}\n\tadvanceEpoch(epoch) {\n\t\tinteger(epoch, 1);\n\t\tthis.transaction(() => {\n\t\t\tif (epoch <= this.metadata().epoch) throw new OrganizationRefused(\"operation-conflict\");\n\t\t\tthis.db.prepare(\"UPDATE metadata SET epoch=? WHERE id=1\").run(epoch);\n\t\t});\n\t}\n\tbudgetState(kind, ...identity) {\n\t\treturn this.transaction(() => this.storedBudget(scopeKey(kind, ...identity.map(identifier))));\n\t}\n\tclose() {\n\t\tif (!this.closed) {\n\t\t\tthis.closed = true;\n\t\t\tthis.db.close();\n\t\t}\n\t}\n};\n//#endregion\n//#region src/file-ledger-anchor.ts\n/** Owner-selected independent custody directory. Never include it in a worker or authority-store backup. */\nvar OrganizationFileLedgerAnchor = class {\n\tledger;\n\tdirectory;\n\tfile;\n\tlock;\n\tconstructor(options) {\n\t\tthis.ledger = identifier(options.ledger);\n\t\tif (!isAbsolute(options.directory)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.directory = realpathSync(options.directory);\n\t\tconst stat = lstatSync(this.directory);\n\t\tif (!stat.isDirectory() || (stat.mode & 63) !== 0 || process.getuid !== void 0 && stat.uid !== process.getuid()) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tthis.file = join(this.directory, \"head.json\");\n\t\tthis.lock = join(this.directory, \"head.lock\");\n\t}\n\tread() {\n\t\tlet fd;\n\t\ttry {\n\t\t\tfd = openSync(this.file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n\t\t\tconst stat = fstatSync(fd);\n\t\t\tif (!stat.isFile() || stat.size > 4096 || (stat.mode & 63) !== 0 || process.getuid !== void 0 && stat.uid !== process.getuid()) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\tconst value = JSON.parse(readFileSync(fd, \"utf8\"));\n\t\t\tthis.validate(value);\n\t\t\treturn Object.freeze({ ...value });\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return void 0;\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t} finally {\n\t\t\tif (fd !== void 0) closeSync(fd);\n\t\t}\n\t}\n\tvalidate(head) {\n\t\tif (!head || Object.keys(head).sort().join(\",\") !== \"digest,ledger,revision,version\" || head.version !== 1 || head.ledger !== this.ledger || !Number.isSafeInteger(head.revision) || head.revision < 1 || typeof head.digest !== \"string\" || !/^[a-f0-9]{64}$/u.test(head.digest)) throw new OrganizationRefused(\"policy-unavailable\");\n\t}\n\tcompareAndSet(expected, next) {\n\t\tthis.validate(next);\n\t\tif (expected !== void 0) this.validate(expected);\n\t\tif (next.revision !== (expected?.revision ?? 0) + 1) throw new OrganizationRefused(\"policy-unavailable\");\n\t\tlet locked = false;\n\t\tlet temporary;\n\t\ttry {\n\t\t\tmkdirSync(this.lock, { mode: 448 });\n\t\t\tlocked = true;\n\t\t\tconst current = this.read();\n\t\t\tif (current === void 0 !== (expected === void 0) || current !== void 0 && organizationCanonical(current) !== organizationCanonical(expected)) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\ttemporary = join(this.directory, `head-${randomUUID()}.tmp`);\n\t\t\tconst fd = openSync(temporary, \"wx\", 384);\n\t\t\ttry {\n\t\t\t\twriteFileSync(fd, organizationCanonical(next));\n\t\t\t\tfsyncSync(fd);\n\t\t\t} finally {\n\t\t\t\tcloseSync(fd);\n\t\t\t}\n\t\t\trenameSync(temporary, this.file);\n\t\t\ttemporary = void 0;\n\t\t\tconst directory = openSync(this.directory, constants.O_RDONLY);\n\t\t\ttry {\n\t\t\t\tfsyncSync(directory);\n\t\t\t} finally {\n\t\t\t\tcloseSync(directory);\n\t\t\t}\n\t\t} catch {\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t} finally {\n\t\t\tif (temporary !== void 0) try {\n\t\t\t\tunlinkSync(temporary);\n\t\t\t} catch {}\n\t\t\tif (locked) rmdirSync(this.lock);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/audit-http.ts\nfunction transport(options) {\n\tconst url = new URL(options.endpoint);\n\tif (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && [\"127.0.0.1\", \"[::1]\"].includes(url.hostname)) || url.username || url.password || url.search || url.hash || url.pathname !== \"/\" || typeof options.token !== \"string\" || !/^[A-Za-z0-9_-]{32,256}$/u.test(options.token)) throw new OrganizationRefused(\"invalid-schema\");\n\tconst token = options.token;\n\treturn async (path, value, signal, conflict = false) => {\n\t\ttry {\n\t\t\tconst response = await fetch(new URL(path, url), {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tredirect: \"error\",\n\t\t\t\tsignal,\n\t\t\t\theaders: {\n\t\t\t\t\tauthorization: `Bearer ${token}`,\n\t\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t\t},\n\t\t\t\tbody: organizationCanonical(value)\n\t\t\t});\n\t\t\tif (conflict && response.status === 409) {\n\t\t\t\tawait response.body?.cancel();\n\t\t\t\tthrow new OrganizationAuditAppendConflict();\n\t\t\t}\n\t\t\tif (!response.ok || response.body === null) {\n\t\t\t\tawait response.body?.cancel();\n\t\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t\t}\n\t\t\tconst chunks = [];\n\t\t\tlet size = 0;\n\t\t\tconst reader = response.body.getReader();\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst next = await reader.read();\n\t\t\t\t\tif (next.done) break;\n\t\t\t\t\tsize += next.value.length;\n\t\t\t\t\tif (size > 1024 * 1024) throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\t\t\tchunks.push(next.value);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tawait reader.cancel();\n\t\t\t}\n\t\t\treturn JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(Buffer.concat(chunks)));\n\t\t} catch (error) {\n\t\t\tif (error instanceof OrganizationAuditAppendConflict) throw error;\n\t\t\tthrow new OrganizationRefused(\"policy-unavailable\");\n\t\t}\n\t};\n}\n/** Concrete owner transport. Signed checkpoint verification remains in OrganizationAudit. */\nfunction createOrganizationAuditHttpPorts(options) {\n\tconst sink = transport(options.sink);\n\tconst anchor = transport(options.anchor);\n\treturn {\n\t\tsink: {\n\t\t\tread: async (after, signal) => await sink(\"/read\", after, signal),\n\t\t\tappend: async (expected, event, signal) => await sink(\"/append\", {\n\t\t\t\texpected,\n\t\t\t\tevent\n\t\t\t}, signal, true)\n\t\t},\n\t\tanchor: {\n\t\t\tload: async (signal) => await anchor(\"/load\", null, signal),\n\t\t\tcompareAndSet: async (expected, next, signal) => {\n\t\t\t\tconst result = await anchor(\"/cas\", {\n\t\t\t\t\texpected,\n\t\t\t\t\tnext\n\t\t\t\t}, signal);\n\t\t\t\tif (typeof result !== \"boolean\") throw new OrganizationRefused(\"policy-unavailable\");\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/http-handler.ts\n/** One worker ingress. No minting, approval, policy, budget, refund or administration routes. */\nfunction createOrganizationHttpHandler(options) {\n\tconst url = new URL(options.audience);\n\tconst local = [\"127.0.0.1\", \"[::1]\"].includes(url.hostname);\n\tif (options.audience !== options.broker.audience || url.protocol !== \"https:\" && !(url.protocol === \"http:\" && local) || url.username !== \"\" || url.password !== \"\" || url.search !== \"\" || url.hash !== \"\" || url.pathname !== \"/\" || options.audience !== url.origin) throw new OrganizationRefused(\"invalid-schema\");\n\tconst timeoutMs = integer(options.bodyTimeoutMs ?? 2e3, 1);\n\tif (timeoutMs > 3e4) throw new OrganizationRefused(\"invalid-schema\");\n\treturn (request, response) => {\n\t\tconst controller = new AbortController();\n\t\tconst disconnected = () => {\n\t\t\tif (!response.writableFinished) controller.abort();\n\t\t};\n\t\tresponse.once(\"close\", disconnected);\n\t\tconst reply = (status, value) => {\n\t\t\tif (response.destroyed || response.writableEnded) return;\n\t\t\tresponse.writeHead(status, {\n\t\t\t\t\"content-type\": \"application/json; charset=utf-8\",\n\t\t\t\t\"cache-control\": \"no-store\",\n\t\t\t\t\"x-content-type-options\": \"nosniff\"\n\t\t\t});\n\t\t\tresponse.end(organizationCanonical(value));\n\t\t};\n\t\tlet timer;\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tconst sensitive = [\n\t\t\t\t\t\"host\",\n\t\t\t\t\t\"content-type\",\n\t\t\t\t\t\"content-length\",\n\t\t\t\t\t\"transfer-encoding\",\n\t\t\t\t\t\"origin\"\n\t\t\t\t];\n\t\t\t\tconst seen = /* @__PURE__ */ new Set();\n\t\t\t\tfor (let index = 0; index < request.rawHeaders.length; index += 2) {\n\t\t\t\t\tconst header = request.rawHeaders[index].toLowerCase();\n\t\t\t\t\tif (!sensitive.includes(header)) continue;\n\t\t\t\t\tif (seen.has(header)) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\t\t\tseen.add(header);\n\t\t\t\t}\n\t\t\t\tif (request.method !== \"POST\" || request.url !== \"/v1/apply\" || request.headers.host !== url.host || request.headers.origin !== void 0 || request.headers[\"content-type\"] !== \"application/json\" || request.headers[\"content-encoding\"] !== void 0) throw new OrganizationRefused(\"not-authorized\");\n\t\t\t\tconst length = request.headers[\"content-length\"];\n\t\t\t\tif (length !== void 0 && (!/^(0|[1-9][0-9]*)$/.test(length) || Number(length) > 64 * 1024)) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\t\tconst chunks = [];\n\t\t\t\tlet size = 0;\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t\trequest.destroy();\n\t\t\t\t}, timeoutMs);\n\t\t\t\tfor await (const chunk of request) {\n\t\t\t\t\tconst buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n\t\t\t\t\tsize += buffer.length;\n\t\t\t\t\tif (size > 64 * 1024) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\t\t\tchunks.push(buffer);\n\t\t\t\t}\n\t\t\t\tclearTimeout(timer);\n\t\t\t\ttimer = void 0;\n\t\t\t\tconst bytes = Buffer.concat(chunks);\n\t\t\t\tconst wire = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n\t\t\t\tconst data = JSON.parse(wire);\n\t\t\t\tif (wire !== organizationCanonical(data)) throw new OrganizationRefused(\"invalid-schema\");\n\t\t\t\tconst receipt = await options.broker.apply(data, controller.signal);\n\t\t\t\treply(200, { receipt });\n\t\t\t} catch (error) {\n\t\t\t\tconst reason = error instanceof OrganizationRefused ? error.reason : \"invalid-schema\";\n\t\t\t\treply(reason === \"policy-unavailable\" ? 503 : 403, { refused: reason });\n\t\t\t\trequest.resume();\n\t\t\t} finally {\n\t\t\t\tif (timer !== void 0) clearTimeout(timer);\n\t\t\t\tresponse.removeListener(\"close\", disconnected);\n\t\t\t}\n\t\t})();\n\t};\n}\n//#endregion\nexport { OrganizationAudit, OrganizationAuditAppendConflict, OrganizationBroker, OrganizationFileLedgerAnchor, OrganizationGitAsset, OrganizationLedger, OrganizationNoEffect, OrganizationRefused, createOrganizationAuditHttpPorts, createOrganizationGitActions, createOrganizationHttpHandler, createOrganizationStateActions, organizationAuditEvent, organizationAuditGenesis, organizationAuditHash, organizationAuditSigningBytes, organizationCanonical, organizationOperationDigest, organizationSigningBytes, verifyOrganizationAudit };\n\n//# sourceMappingURL=index.js.map","import { OrganizationBroker, OrganizationRefused, organizationAuditEvent, organizationOperationDigest } from '@robota-sdk/agent-organization-host';\nimport type { OrganizationAudit, OrganizationLedger, IOrganizationAction, IOrganizationCall, IOrganizationGrant, IOrganizationReceipt, IOrganizationRequest, TOrganizationJson } from '@robota-sdk/agent-organization-host';\nimport type { IHostedIdentity } from './hosted-runtime-types.js';\n\nexport interface IHostedOrganizationWorker {\n readonly resource: string;\n readonly grantId: string;\n readonly identity: IHostedIdentity;\n readonly epoch: number;\n}\n\n/** Owner provider inventory must survive broker restart and exclude resources outside its custody. */\nexport interface IHostedOrganizationInventory {\n list(signal: AbortSignal): Promise<readonly IHostedOrganizationWorker[]>;\n /** Revalidate owner metadata before termination; return only after the provider acknowledges cleanup. */\n terminate(worker: IHostedOrganizationWorker, signal: AbortSignal): Promise<void>;\n}\n\nexport interface IHostedOrganizationIncidentOwners {\n readonly detection: string;\n readonly containment: string;\n readonly assessment: string;\n readonly recovery: string;\n /** Owner-installed incident channel; metadata only, no provider errors, credentials or request bodies. */\n report(event: {\n readonly kind: 'authority-unavailable' | 'cleanup-unresolved' | 'unknown-effect';\n readonly resources: readonly string[];\n readonly operationDigest?: string;\n }): Promise<void>;\n}\n\nexport interface IHostedOrganizationControlOptions {\n readonly ledger: OrganizationLedger;\n readonly audit: OrganizationAudit;\n readonly actions: readonly IOrganizationAction[];\n readonly inventory: IHostedOrganizationInventory;\n readonly incidentOwners: IHostedOrganizationIncidentOwners;\n readonly policyIntervalMs?: number;\n readonly providerTimeoutMs?: number;\n}\n\n/** Owner-side company composition. No administrator operations are exposed to workers or model tools. */\nexport class HostedOrganizationControl {\n private readonly ledger: OrganizationLedger;\n private readonly audit: OrganizationAudit;\n private readonly broker: OrganizationBroker;\n private readonly inventory: IHostedOrganizationInventory;\n private readonly incidents: IHostedOrganizationIncidentOwners;\n private readonly timeout: number;\n private readonly timer: ReturnType<typeof setInterval>;\n private readonly calls = new Map<AbortController, string>();\n private sweepPending?: Promise<void>;\n private closed = false;\n private quarantined = false;\n\n constructor(options: IHostedOrganizationControlOptions) {\n this.ledger = options.ledger;\n this.audit = options.audit;\n this.broker = new OrganizationBroker({ ledger: options.ledger, audit: options.audit, actions: options.actions, hosted: true, policyIntervalMs: options.policyIntervalMs });\n const interval = options.policyIntervalMs ?? 100;\n this.timeout = options.providerTimeoutMs ?? 10_000;\n if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 30_000 ||\n typeof options.inventory?.list !== 'function' || typeof options.inventory.terminate !== 'function' ||\n typeof options.incidentOwners?.report !== 'function' ||\n ['detection', 'containment', 'assessment', 'recovery'].some((key) => {\n const value = options.incidentOwners[key as 'detection'];\n return typeof value !== 'string' || value.trim().length === 0;\n })) throw new OrganizationRefused('invalid-schema');\n this.inventory = Object.freeze({ list: options.inventory.list.bind(options.inventory), terminate: options.inventory.terminate.bind(options.inventory) });\n this.incidents = Object.freeze({ ...options.incidentOwners, report: options.incidentOwners.report.bind(options.incidentOwners) });\n this.timer = setInterval(() => { void this.sweep().catch(() => undefined); }, interval);\n this.timer.unref();\n }\n\n private identity(grantId: string, identity: IHostedIdentity, epoch: number): IOrganizationGrant {\n const grant = this.ledger.currentGrant(grantId);\n // currentGrant verifies every delegation ancestor. Logical root/runtime bindings come from\n // the owner's provider inventory, and survive replacement of a revoked workload grant.\n if (grant.tenant !== identity.tenant || grant.task !== identity.task || grant.actor !== identity.actor ||\n grant.epoch !== epoch)\n throw new OrganizationRefused('not-authorized');\n return grant;\n }\n\n /** Admission uses current policy and retained audit evidence, never checkpoint authority. */\n async admit(worker: IHostedOrganizationWorker, signal?: AbortSignal): Promise<IOrganizationGrant> {\n if (this.closed || this.quarantined) throw new OrganizationRefused('policy-unavailable');\n this.ledger.verifyAnchoredAuthority();\n const grant = this.identity(worker.grantId, worker.identity, worker.epoch);\n await this.audit.verify(signal);\n const live = await this.inventory.list(signal === undefined ? AbortSignal.timeout(this.timeout) : AbortSignal.any([signal, AbortSignal.timeout(this.timeout)]));\n if (!live.some((entry) => entry.resource === worker.resource && entry.grantId === worker.grantId &&\n entry.epoch === worker.epoch && Object.entries(worker.identity).every(([key, value]) => entry.identity[key as keyof IHostedIdentity] === value)))\n throw new OrganizationRefused('not-authorized');\n if (this.closed || this.quarantined || signal?.aborted) throw new OrganizationRefused('not-authorized');\n this.identity(worker.grantId, worker.identity, worker.epoch);\n return grant;\n }\n\n async apply(call: IOrganizationCall, signal?: AbortSignal, onWithdrawal?: () => void): Promise<IOrganizationReceipt> {\n if (this.closed || this.quarantined) throw new OrganizationRefused('policy-unavailable');\n const controller = new AbortController();\n const withdraw = (): void => { onWithdrawal?.(); };\n controller.signal.addEventListener('abort', withdraw, { once: true });\n const abort = (): void => controller.abort();\n signal?.addEventListener('abort', abort, { once: true });\n if (signal?.aborted) controller.abort();\n this.calls.set(controller, call.request.claims.grantId);\n try { return await this.broker.apply(call, controller.signal); }\n catch (error) {\n if (error instanceof OrganizationRefused && error.reason === 'outcome-unknown') {\n await this.incidents.report({ kind: 'unknown-effect', resources: [call.request.claims.operation.resource], operationDigest: organizationOperationDigest(call.request.claims) }).catch(() => undefined);\n }\n throw error;\n }\n finally {\n this.calls.delete(controller);\n signal?.removeEventListener('abort', abort); controller.signal.removeEventListener('abort', withdraw);\n }\n }\n\n /** Owner commands persist policy withdrawal before terminating every affected provider worker. */\n private async afterWithdrawal(): Promise<void> {\n // An existing sweep may have evaluated policy before this withdrawal. Wait for it, then inspect again.\n await this.sweepPending?.catch(() => undefined);\n await this.sweep();\n }\n async stopGrant(grantId: string): Promise<void> { this.ledger.revokeGrant(grantId); await this.afterWithdrawal(); }\n async stopTask(tenant: string, task: string): Promise<void> { this.ledger.stopTask(tenant, task); await this.afterWithdrawal(); }\n async stopTenant(tenant: string): Promise<void> { this.ledger.stopTenant(tenant); await this.afterWithdrawal(); }\n async emergencyStop(): Promise<void> { this.ledger.emergencyStop(); await this.afterWithdrawal(); }\n\n /** Owner recovery channel only. A worker cannot supply the asset-owner confirmation capability. */\n async reconcileExternalOperation(request: IOrganizationRequest, assetOwner: {\n confirm(operationDigest: string, signal?: AbortSignal): Promise<TOrganizationJson>;\n }, signal?: AbortSignal): Promise<IOrganizationReceipt> {\n this.ledger.verifyAnchoredAuthority();\n const event = organizationAuditEvent(request, 'complete');\n const confirmed = await assetOwner.confirm(event.operationDigest, signal);\n await this.audit.record(event, signal);\n return this.ledger.reconcileExternalOperation(request, confirmed);\n }\n\n sweep(): Promise<void> {\n if (this.sweepPending !== undefined) return this.sweepPending;\n this.sweepPending = this.sweepOnce().finally(() => { this.sweepPending = undefined; });\n return this.sweepPending;\n }\n\n private async sweepOnce(): Promise<void> {\n const firstFailure = !this.closed && !this.quarantined;\n let unavailable = this.closed || this.quarantined;\n try { this.ledger.verifyAnchoredAuthority(); await this.audit.verify(AbortSignal.timeout(this.timeout)); }\n catch { unavailable = true; }\n if (unavailable && !this.closed) { this.quarantined = true; this.broker.close(); }\n for (const [controller, grantId] of this.calls) {\n try { if (unavailable) throw new OrganizationRefused('policy-unavailable'); this.ledger.currentGrant(grantId); }\n catch { controller.abort(); }\n }\n let workers: readonly IHostedOrganizationWorker[];\n try { workers = await this.inventory.list(AbortSignal.timeout(this.timeout)); }\n catch {\n this.quarantined = true;\n this.broker.close();\n for (const controller of this.calls.keys()) controller.abort();\n await this.incidents.report({ kind: 'cleanup-unresolved', resources: [] });\n throw new OrganizationRefused('policy-unavailable');\n }\n const stopped = workers.filter((worker) => {\n try { if (unavailable) return true; this.identity(worker.grantId, worker.identity, worker.epoch); return false; }\n catch { return true; }\n });\n const outcomes = await Promise.allSettled(stopped.map((worker) => this.inventory.terminate(worker, AbortSignal.timeout(this.timeout))));\n const unresolved = stopped.filter((_worker, index) => outcomes[index]!.status === 'rejected').map((worker) => worker.resource);\n if (unavailable && firstFailure) await this.incidents.report({ kind: 'authority-unavailable', resources: stopped.map((worker) => worker.resource) });\n if (unresolved.length > 0) {\n await this.incidents.report({ kind: 'cleanup-unresolved', resources: unresolved });\n throw new OrganizationRefused('policy-unavailable');\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n clearInterval(this.timer);\n this.broker.close();\n for (const controller of this.calls.keys()) controller.abort();\n await this.afterWithdrawal();\n }\n}\n","import { loadE2BSdk } from './e2b-sdk.js';\nimport type { SandboxInfo } from 'e2b/dist/index.mjs';\nimport { decodeHostedIdentity, identifier, positiveInteger } from './hosted-runtime-config.js';\nimport type { IHostedOrganizationInventory, IHostedOrganizationWorker } from './hosted-organization-control.js';\n\n/** Provider-backed inventory, including paused workers. Its management capability stays outside every worker. */\nexport function createE2BOrganizationInventory(options: {\n readonly apiKey: string;\n readonly controlPlane: string;\n readonly tenant: string;\n readonly requestTimeoutMs?: number;\n}): IHostedOrganizationInventory {\n const controlPlane = identifier(options.controlPlane, 'organization control plane');\n const tenant = identifier(options.tenant, 'organization tenant');\n const request = {\n apiKey: identifier(options.apiKey, 'E2B management credential'),\n requestTimeoutMs: positiveInteger(options.requestTimeoutMs ?? 10_000, 'E2B request timeout', 30_000),\n apiUrl: 'https://api.e2b.app', sandboxUrl: 'https://sandbox.e2b.app', domain: 'e2b.app', debug: false, retries: 0,\n };\n function owned(info: SandboxInfo): IHostedOrganizationWorker {\n if (info.metadata.organizationControlPlane !== controlPlane || info.metadata.tenant !== tenant)\n throw new Error('Organization inventory ownership mismatch');\n return Object.freeze({\n resource: identifier(info.sandboxId, 'organization worker'),\n grantId: identifier(info.metadata.organizationGrant, 'organization grant'),\n epoch: positiveInteger(Number(info.metadata.epoch), 'organization epoch'),\n identity: decodeHostedIdentity({ tenant: info.metadata.tenant, task: info.metadata.task, rootTask: info.metadata.rootTask, actor: info.metadata.actor, runtime: info.metadata.runtime }),\n });\n }\n return {\n async list(signal) {\n signal.throwIfAborted();\n const { Sandbox } = await loadE2BSdk();\n signal.throwIfAborted();\n const paginator = Sandbox.list({ ...request, query: { metadata: { organizationControlPlane: controlPlane, tenant }, state: ['running', 'paused'] }, limit: 100 });\n const workers: IHostedOrganizationWorker[] = [];\n const seen = new Set<string>();\n while (paginator.hasNext) {\n signal.throwIfAborted();\n for (const info of await paginator.nextItems({ ...request, signal })) {\n const worker = owned(info);\n if (seen.has(worker.resource) || workers.length >= 10_000) throw new Error('Organization inventory is incomplete');\n seen.add(worker.resource); workers.push(worker);\n }\n }\n return workers;\n },\n async terminate(worker, signal) {\n signal.throwIfAborted();\n const { Sandbox, SandboxNotFoundError } = await loadE2BSdk();\n signal.throwIfAborted();\n let info: SandboxInfo;\n try { info = await Sandbox.getInfo(worker.resource, { ...request, signal }); }\n catch (error) { if (error instanceof SandboxNotFoundError) return; throw new Error('Organization cleanup is unresolved'); }\n const current = owned(info);\n if (current.grantId !== worker.grantId || current.epoch !== worker.epoch ||\n Object.entries(worker.identity).some(([key, value]) => current.identity[key as keyof typeof current.identity] !== value))\n throw new Error('Organization cleanup ownership mismatch');\n // Do not abort away the deletion receipt; the SDK request timeout still bounds the call.\n await Sandbox.kill(worker.resource, request);\n },\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { OrganizationRefused, organizationSigningBytes } from '@robota-sdk/agent-organization-host';\nimport type { OrganizationLedger, IOrganizationRequest, IOrganizationEnvelope } from '@robota-sdk/agent-organization-host';\nimport { hostedAdmissionBytes, verifyHostedAdmissionProof } from './hosted-runtime-admission.js';\nimport type { IHostedAdmissionProof, IHostedRuntimeConfig, IHostedRuntimeUsage, THostedBackendRole } from './hosted-runtime-types.js';\nimport type { HostedOrganizationControl } from './hosted-organization-control.js';\nimport type { HostedOrganizationPayloads } from './hosted-organization-payloads.js';\n\nexport interface IHostedOrganizationBinding {\n readonly config: IHostedRuntimeConfig;\n readonly grantId: string;\n readonly token: string;\n readonly expiresAt: number;\n /** External issuer capabilities installed by the owner, never supplied by an HTTP caller. */\n signAdmission(role: THostedBackendRole, bytes: Uint8Array): string;\n signRequest(bytes: Uint8Array): string;\n}\n\n/** Actual stock CLI admission and OpenAI-wire ingress over durable company effects. No owner routes. */\nexport function createHostedOrganizationGateway(options: {\n readonly control: HostedOrganizationControl;\n readonly ledger: OrganizationLedger;\n readonly payloads: HostedOrganizationPayloads;\n readonly bindings: readonly IHostedOrganizationBinding[];\n readonly modelResource: string;\n}): (request: IncomingMessage, response: ServerResponse) => void {\n const bindings = [...options.bindings];\n type TAdmission = Awaited<ReturnType<HostedOrganizationControl['admit']>>;\n const pendingAdmissions = new Map<string, Promise<TAdmission>>();\n const tokens = new Set<string>(); const runtimes = new Set<string>(); const grants = new Set<string>();\n for (const binding of bindings) {\n if (!/^[A-Za-z0-9_-]{32,256}$/u.test(binding.token) || tokens.has(binding.token) || runtimes.has(binding.config.identity.runtime) || grants.has(binding.grantId))\n throw new OrganizationRefused('invalid-schema');\n const grant = options.ledger.currentGrant(binding.grantId);\n if (grant.scopes.length !== 1 || grant.scopes[0]!.resource !== options.modelResource ||\n grant.scopes[0]!.operations.length !== 1 || grant.scopes[0]!.operations[0] !== 'generate')\n throw new OrganizationRefused('not-authorized');\n tokens.add(binding.token); runtimes.add(binding.config.identity.runtime); grants.add(binding.grantId);\n }\n const usage = (binding: IHostedOrganizationBinding): IHostedRuntimeUsage => {\n const budget = options.ledger.budgetState('grant', binding.grantId);\n return { sessions: 1, modelCalls: options.ledger.grantOperationCount(binding.grantId),\n modelTokens: budget.spent.tokens, costMicros: budget.spent.costMicros };\n };\n const admit = async (binding: IHostedOrganizationBinding, signal: AbortSignal): Promise<TAdmission> => {\n if (signal.aborted) throw new OrganizationRefused('policy-unavailable');\n let pending = pendingAdmissions.get(binding.grantId);\n if (pending === undefined) {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 30_000);\n pending = options.control.admit(\n { resource: binding.config.worker.resource, grantId: binding.grantId, identity: binding.config.identity, epoch: binding.config.epoch },\n controller.signal,\n ).finally(() => {\n clearTimeout(timeout);\n pendingAdmissions.delete(binding.grantId);\n });\n void pending.catch(() => undefined);\n pendingAdmissions.set(binding.grantId, pending);\n }\n return new Promise<TAdmission>((resolve, reject) => {\n const aborted = (): void => {\n signal.removeEventListener('abort', aborted);\n reject(new OrganizationRefused('policy-unavailable'));\n };\n if (signal.aborted) {\n aborted();\n return;\n }\n signal.addEventListener('abort', aborted, { once: true });\n void pending!.then(\n (admission) => {\n signal.removeEventListener('abort', aborted);\n resolve(admission);\n },\n (error: unknown) => {\n signal.removeEventListener('abort', aborted);\n reject(error);\n },\n );\n });\n };\n return (request, response) => {\n const controller = new AbortController();\n const disconnected = (): void => { if (!response.writableFinished) controller.abort(); };\n response.once('close', disconnected);\n const timeout = setTimeout(() => { controller.abort(); request.destroy(); response.destroy(); }, 30_000);\n const reply = (status: number, body: unknown): void => {\n if (response.destroyed || response.writableEnded) return;\n response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });\n response.end(JSON.stringify(body));\n };\n void (async () => {\n try {\n const seen = new Set<string>();\n for (let index = 0; index < request.rawHeaders.length; index += 2) {\n const key = request.rawHeaders[index]!.toLowerCase();\n if (!['host', 'authorization', 'idempotency-key', 'content-type', 'content-length', 'transfer-encoding', 'origin'].includes(key)) continue;\n if (seen.has(key)) throw new OrganizationRefused('invalid-schema'); seen.add(key);\n }\n if (request.method !== 'POST' || request.headers.origin !== undefined || request.headers['content-type'] !== 'application/json' || request.headers['content-encoding'] !== undefined)\n throw new OrganizationRefused('not-authorized');\n const chunks: Buffer[] = []; let size = 0;\n for await (const chunk of request) {\n const bytes = Buffer.from(chunk as Uint8Array); size += bytes.length;\n if (size > 4 * 1024 * 1024) throw new OrganizationRefused('invalid-schema'); chunks.push(bytes);\n }\n const bytes = Buffer.concat(chunks);\n const body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as Record<string, unknown>;\n if (!body || Array.isArray(body)) throw new OrganizationRefused('invalid-schema');\n const model = ['/v1/chat/completions', '/v1/responses'].includes(request.url ?? '');\n const binding = model\n ? bindings.find((entry) => request.headers.authorization === `Bearer ${entry.token}`)\n : bindings.find((entry) => (body.identity as { runtime?: unknown } | undefined)?.runtime === entry.config.identity.runtime);\n if (!binding || binding.expiresAt <= Date.now()) throw new OrganizationRefused('expired');\n const config = binding.config;\n if (request.headers.host !== new URL(config.broker.endpoint).host ||\n new URL(config.worker.endpoint).origin !== new URL(config.broker.endpoint).origin)\n throw new OrganizationRefused('not-authorized');\n let role: THostedBackendRole | undefined;\n if (!model) {\n role = request.url === new URL(config.worker.endpoint).pathname ? 'worker'\n : request.url === new URL(config.broker.endpoint).pathname ? 'broker' : undefined;\n if (!role || typeof body.nonce !== 'string' || body.version !== 3 || body.role !== role ||\n body.resource !== config[role].resource || body.epoch !== config.epoch ||\n Object.entries(config.identity).some(([key, expected]) => (body.identity as Record<string, unknown>)?.[key] !== expected) ||\n JSON.stringify(body.snapshot) !== JSON.stringify(config.snapshot) || JSON.stringify(body.limits) !== JSON.stringify(config.limits))\n throw new OrganizationRefused('not-authorized');\n } else {\n const key = request.headers['idempotency-key'];\n if (typeof key !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/u.test(key)) throw new OrganizationRefused('invalid-schema');\n }\n const grant = await admit(binding, controller.signal);\n if (!model) {\n const issuedAt = Date.now();\n const unsigned: Omit<IHostedAdmissionProof, 'signature'> = { version: 3, identity: config.identity, role: role!, resource: config[role!].resource, nonce: body.nonce as string, epoch: config.epoch, issuedAt,\n expiresAt: Math.min(issuedAt + 60_000, binding.expiresAt, grant.expiresAt), snapshot: config.snapshot, ready: true, limits: config.limits, usage: role === 'broker' ? usage(binding) : null };\n const proof = { ...unsigned, signature: binding.signAdmission(role!, hostedAdmissionBytes(unsigned)) };\n verifyHostedAdmissionProof(proof, config, role!, body.nonce as string, Date.now());\n reply(200, proof); return;\n }\n const key = request.headers['idempotency-key'] as string;\n const payload = await options.payloads.put(grant.id, bytes);\n const now = Date.now();\n const claims: IOrganizationRequest = { version: 1, grantId: grant.id, tenant: grant.tenant, task: grant.task, actor: grant.actor, audience: grant.audience, epoch: grant.epoch, nonce: randomUUID(), notBefore: now,\n expiresAt: Math.min(now + 25_000, binding.expiresAt, grant.expiresAt), operation: { idempotencyKey: key, resource: options.modelResource, operation: 'generate', environment: 'hosted', parameters: { request: payload, surface: request.url === '/v1/responses' ? 'responses' : 'chat-completions' } } };\n const envelope: IOrganizationEnvelope<IOrganizationRequest> = { claims, signature: binding.signRequest(organizationSigningBytes('request', claims)) };\n await options.payloads.recordOperation(claims);\n const receipt = await options.control.apply({ request: envelope, approval: null }, controller.signal, () => response.destroy());\n const digest = (receipt.value as { response?: unknown } | null)?.response;\n if (typeof digest !== 'string') throw new OrganizationRefused('outcome-unknown');\n const returned = await options.payloads.get(grant.id, digest);\n const result = JSON.parse(returned.toString('utf8')) as Record<string, unknown>;\n if (body.stream === true) {\n response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });\n if (request.url === '/v1/responses') {\n const output = result.output as Array<{ type: string; content?: Array<{ type: string; text?: string }> }>;\n if (Array.isArray(output)) for (const item of output) {\n if (item.type === 'message' && Array.isArray(item.content)) for (const part of item.content) {\n if (part.type === 'output_text' && typeof part.text === 'string')\n response.write(`data: ${JSON.stringify({ type: 'response.output_text.delta', delta: part.text })}\\n\\n`);\n }\n }\n response.end(`data: ${JSON.stringify({ type: 'response.completed', response: result })}\\n\\n`);\n }\n else {\n const choices = result.choices as Array<{ index: number; message: Record<string, unknown>; finish_reason: unknown }>;\n if (!Array.isArray(choices)) throw new OrganizationRefused('outcome-unknown');\n response.write(`data: ${JSON.stringify({ ...result, object: 'chat.completion.chunk', choices: choices.map((choice) => ({ index: choice.index, delta: { ...choice.message,\n ...(Array.isArray(choice.message.tool_calls) ? { tool_calls: choice.message.tool_calls.map((tool, index) => ({ ...tool as object, index })) } : {}) }, finish_reason: null })) })}\\n\\n`);\n response.end(`data: ${JSON.stringify({ ...result, object: 'chat.completion.chunk', choices: choices.map((choice) => ({ index: choice.index, delta: {}, finish_reason: choice.finish_reason })) })}\\n\\ndata: [DONE]\\n\\n`);\n }\n } else reply(200, result);\n } catch (error) {\n if (response.headersSent) response.destroy();\n else reply(error instanceof OrganizationRefused && ['policy-unavailable', 'outcome-unknown'].includes(error.reason) ? 503 : 403,\n { error: { message: error instanceof OrganizationRefused ? error.message : 'Organization ingress refused', type: 'organization_refusal' } });\n request.resume();\n } finally { clearTimeout(timeout); response.removeListener('close', disconnected); }\n })();\n };\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport { open, realpath, stat, rename, unlink } from 'node:fs/promises';\nimport { isAbsolute, join } from 'node:path';\nimport { OrganizationRefused, organizationOperationDigest, organizationAuditEvent } from '@robota-sdk/agent-organization-host';\nimport type { IOrganizationRequest } from '@robota-sdk/agent-organization-host';\n\n/** Private owner content storage for model wire bytes; the bounded authority journal keeps only digests. */\nexport class HostedOrganizationPayloads {\n private constructor(private readonly directory: string) {}\n\n static async open(directory: string): Promise<HostedOrganizationPayloads> {\n if (!isAbsolute(directory)) throw new OrganizationRefused('policy-unavailable');\n const path = await realpath(directory);\n const info = await stat(path);\n if (!info.isDirectory() || (info.mode & 0o077) !== 0 ||\n (process.getuid !== undefined && info.uid !== process.getuid()))\n throw new OrganizationRefused('policy-unavailable');\n return new HostedOrganizationPayloads(path);\n }\n\n private path(grantId: string, digest: string): string {\n if (!/^[a-f0-9]{64}$/u.test(digest)) throw new OrganizationRefused('invalid-schema');\n const owner = createHash('sha256').update(grantId).digest('hex');\n return join(this.directory, `${owner}-${digest}.json`);\n }\n\n async put(grantId: string, bytes: Uint8Array): Promise<string> {\n if (bytes.length > 4 * 1024 * 1024) throw new OrganizationRefused('invalid-schema');\n const digest = createHash('sha256').update(bytes).digest('hex');\n const file = this.path(grantId, digest);\n await this.persist(file, bytes);\n return digest;\n }\n\n private async persist(file: string, bytes: Uint8Array): Promise<void> {\n const temporary = join(this.directory, `${randomUUID()}.tmp`);\n try {\n const handle = await open(temporary, 'wx', 0o600);\n try { await handle.writeFile(bytes); await handle.sync(); } finally { await handle.close(); }\n await rename(temporary, file);\n const directory = await open(this.directory, constants.O_RDONLY);\n try { await directory.sync(); } finally { await directory.close(); }\n } catch { throw new OrganizationRefused('policy-unavailable'); }\n finally { await unlink(temporary).catch(() => undefined); }\n }\n\n /** Owner outbox manifest. Digest addressing survives a broker crash without putting request claims in audit. */\n async recordOperation(request: IOrganizationRequest): Promise<void> {\n const digest = organizationOperationDigest(request);\n const requestDigest = await this.put(request.grantId, Buffer.from(JSON.stringify(request)));\n await this.persist(`${this.path(request.grantId, digest)}.operation`, Buffer.from(JSON.stringify({ requestDigest })));\n }\n\n async operation(grantId: string, digest: string): Promise<IOrganizationRequest> {\n const handle = await open(`${this.path(grantId, digest)}.operation`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n try {\n const info = await handle.stat();\n if (!info.isFile() || info.size > 4096 || (info.mode & 0o077) !== 0 ||\n (process.getuid !== undefined && info.uid !== process.getuid())) throw new OrganizationRefused('policy-unavailable');\n const index = JSON.parse(await handle.readFile('utf8')) as { requestDigest?: unknown };\n if (typeof index.requestDigest !== 'string') throw new OrganizationRefused('policy-unavailable');\n const request = JSON.parse((await this.get(grantId, index.requestDigest)).toString('utf8')) as IOrganizationRequest;\n organizationAuditEvent(request, 'complete');\n if (request.grantId !== grantId || organizationOperationDigest(request) !== digest)\n throw new OrganizationRefused('policy-unavailable');\n return request;\n } finally { await handle.close(); }\n }\n\n async get(grantId: string, digest: string): Promise<Buffer> {\n try {\n const handle = await open(this.path(grantId, digest), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n try {\n const info = await handle.stat();\n if (!info.isFile() || info.size > 4 * 1024 * 1024 || (info.mode & 0o077) !== 0 ||\n (process.getuid !== undefined && info.uid !== process.getuid())) throw new Error('unowned content');\n const bytes = await handle.readFile();\n if (createHash('sha256').update(bytes).digest('hex') !== digest) throw new Error('changed content');\n return bytes;\n } finally { await handle.close(); }\n } catch { throw new OrganizationRefused('policy-unavailable'); }\n }\n}\n","import { OrganizationNoEffect, OrganizationRefused } from '@robota-sdk/agent-organization-host';\nimport type { IOrganizationAction, IOrganizationUnits } from '@robota-sdk/agent-organization-host';\nimport type { HostedOrganizationPayloads } from './hosted-organization-payloads.js';\n\nexport interface IHostedOrganizationModelOptions {\n readonly payloads: HostedOrganizationPayloads;\n readonly endpoint: string;\n readonly apiKey: string;\n readonly model: string;\n readonly roles: readonly string[];\n readonly resource: string;\n readonly reservation: IOrganizationUnits;\n readonly maxInputBytes: number;\n readonly maxOutputTokens: number;\n readonly costMicrosPerToken: number;\n /** Declare only an upstream contract actually supported by the owner-selected provider. */\n readonly providerIdempotency: boolean;\n /** Owner-selected pure input counter for the exact immutable provider request, including tools/media. */\n countInputTokens(surface: 'responses' | 'chat-completions', request: Readonly<Record<string, unknown>>, signal: AbortSignal): Promise<number>;\n}\n\n/** Actual fixed-provider HTTP effect. No automatic retry; ambiguous outcomes retain the broker hold. */\nexport function createHostedOrganizationModelAction(options: IHostedOrganizationModelOptions): IOrganizationAction {\n const endpoint = new URL(options.endpoint);\n if ((endpoint.protocol !== 'https:' && !(endpoint.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(endpoint.hostname))) ||\n endpoint.username || endpoint.password || endpoint.search || endpoint.hash ||\n typeof options.apiKey !== 'string' || /[\\r\\n]/u.test(options.apiKey) || options.apiKey.length === 0 ||\n !Number.isSafeInteger(options.maxInputBytes) || options.maxInputBytes < 1 || options.maxInputBytes > 4 * 1024 * 1024 ||\n !Number.isSafeInteger(options.maxOutputTokens) || options.maxOutputTokens < 1 ||\n !Number.isSafeInteger(options.costMicrosPerToken) || options.costMicrosPerToken < 0 ||\n typeof options.countInputTokens !== 'function')\n throw new OrganizationRefused('invalid-schema');\n const reservation = Object.freeze({ ...options.reservation });\n const countInputTokens = options.countInputTokens.bind(options);\n const parameters = (value: unknown): { request: string; surface: 'responses' | 'chat-completions' } => {\n const data = value as { request?: unknown; surface?: unknown };\n if (!data || Object.keys(data).sort().join(',') !== 'request,surface' ||\n typeof data.request !== 'string' || !/^[a-f0-9]{64}$/u.test(data.request) ||\n !['responses', 'chat-completions'].includes(String(data.surface)))\n throw new OrganizationRefused('invalid-schema');\n return data as { request: string; surface: 'responses' | 'chat-completions' };\n };\n return {\n resource: options.resource, operation: 'generate', roles: [...options.roles], requiresApproval: false,\n reserve: (operation) => { parameters(operation.parameters); return reservation; },\n execute: async (operation, context) => {\n const input = parameters(operation.parameters);\n const wire = await options.payloads.get(context.identity.id, input.request);\n if (wire.length > options.maxInputBytes) throw new OrganizationRefused('invalid-schema');\n const body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(wire)) as Record<string, unknown>;\n if (!body || Array.isArray(body) || body.model !== options.model) throw new OrganizationRefused('not-authorized');\n const upstreamBody: Record<string, unknown> = { ...body, stream: false };\n if (['conversation', 'previous_response_id', 'prompt'].some((key) => upstreamBody[key] != null) ||\n (Array.isArray(upstreamBody.tools) && upstreamBody.tools.some((tool) => (tool as { type?: unknown })?.type !== 'function')))\n throw new OrganizationNoEffect('not-authorized', { tokens: 0, timeMs: 0, costMicros: 0 });\n delete upstreamBody.max_tokens;\n delete upstreamBody.max_completion_tokens;\n delete upstreamBody.max_output_tokens;\n delete upstreamBody.stream_options;\n upstreamBody[input.surface === 'responses' ? 'max_output_tokens' : 'max_completion_tokens'] = options.maxOutputTokens;\n upstreamBody.store = false;\n upstreamBody.n = input.surface === 'chat-completions' ? 1 : undefined;\n if (input.surface === 'responses') { delete upstreamBody.n; upstreamBody.background = false; }\n const encoded = JSON.stringify(upstreamBody);\n const inputTokens = await countInputTokens(input.surface, JSON.parse(encoded) as Record<string, unknown>, context.signal);\n const maximum = inputTokens + options.maxOutputTokens;\n if (!Number.isSafeInteger(inputTokens) || inputTokens < 0 || !Number.isSafeInteger(maximum) ||\n maximum > reservation.tokens || !Number.isSafeInteger(maximum * options.costMicrosPerToken) || maximum * options.costMicrosPerToken > reservation.costMicros)\n throw new OrganizationNoEffect('budget-exhausted', { tokens: 0, timeMs: 0, costMicros: 0 });\n context.signal.throwIfAborted();\n const response = await fetch(`${endpoint.href.replace(/\\/$/u, '')}/${input.surface === 'responses' ? 'responses' : 'chat/completions'}`, {\n method: 'POST', redirect: 'error', signal: context.signal,\n headers: { authorization: `Bearer ${options.apiKey}`, 'content-type': 'application/json',\n ...(options.providerIdempotency ? { 'Idempotency-Key': context.operationDigest } : {}) },\n body: encoded,\n });\n if (!response.ok || response.body === null) {\n await response.body?.cancel();\n throw new OrganizationRefused('outcome-unknown');\n }\n const chunks: Uint8Array[] = [];\n let size = 0;\n const reader = response.body.getReader();\n try {\n for (;;) {\n const next = await reader.read(); if (next.done) break;\n size += next.value.length;\n if (size > 4 * 1024 * 1024) throw new OrganizationRefused('outcome-unknown');\n chunks.push(next.value);\n }\n } finally { await reader.cancel(); }\n const bytes = Buffer.concat(chunks);\n const result = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as { usage?: { total_tokens?: unknown } };\n const tokens = result?.usage?.total_tokens;\n if (typeof tokens !== 'number' || !Number.isSafeInteger(tokens) || tokens < 0 || tokens > reservation.tokens ||\n !Number.isSafeInteger(tokens * options.costMicrosPerToken) || tokens * options.costMicrosPerToken > reservation.costMicros)\n throw new OrganizationRefused('outcome-unknown');\n const digest = await options.payloads.put(context.identity.id, bytes);\n return { value: { response: digest }, usage: { tokens, timeMs: 0, costMicros: tokens * options.costMicrosPerToken } };\n },\n };\n}\n","import { OrganizationRefused } from '@robota-sdk/agent-organization-host';\nimport type { IHostedOrganizationModelOptions } from './hosted-organization-model.js';\n\n/** Fixed owner counter transport. The owner encoder must preserve the provider's full input-token contract. */\nexport function createHostedOrganizationInputTokenCounter(options: {\n readonly endpoint: string;\n readonly apiKey: string;\n /** Explicit provider mapping: Responses counting accepts input/model/tools, while Chat needs its own verified counter. */\n encode(surface: 'responses' | 'chat-completions', request: Readonly<Record<string, unknown>>): unknown;\n}): IHostedOrganizationModelOptions['countInputTokens'] {\n const endpoint = new URL(options.endpoint);\n if ((endpoint.protocol !== 'https:' && !(endpoint.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(endpoint.hostname))) ||\n endpoint.username || endpoint.password || endpoint.search || endpoint.hash || typeof options.encode !== 'function' ||\n typeof options.apiKey !== 'string' || options.apiKey.length === 0 || /[\\r\\n]/u.test(options.apiKey))\n throw new OrganizationRefused('invalid-schema');\n const apiKey = options.apiKey; const encode = options.encode.bind(options);\n return async (surface, body, signal) => {\n const response = await fetch(endpoint, { method: 'POST', redirect: 'error', signal,\n headers: { authorization: `Bearer ${apiKey}`, 'content-type': 'application/json' }, body: JSON.stringify(encode(surface, body)) });\n if (!response.ok || response.body === null) { await response.body?.cancel(); throw new OrganizationRefused('policy-unavailable'); }\n const chunks: Uint8Array[] = []; let size = 0;\n const reader = response.body.getReader();\n try {\n for (;;) { const next = await reader.read(); if (next.done) break; size += next.value.length;\n if (size > 64 * 1024) throw new OrganizationRefused('policy-unavailable'); chunks.push(next.value); }\n } finally { await reader.cancel(); }\n const result = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))) as { input_tokens?: unknown };\n if (!Number.isSafeInteger(result?.input_tokens) || (result.input_tokens as number) < 0)\n throw new OrganizationRefused('policy-unavailable');\n return result.input_tokens as number;\n };\n}\n","import { createHash } from 'node:crypto';\nimport { posix } from 'node:path';\nimport {\n decodeHostedIdentity,\n exactKeys,\n hostedAdmissionError,\n identifier,\n positiveInteger,\n record,\n} from './hosted-runtime-config.js';\nimport { projectHostedSessionCheckpoint } from './hosted-session-checkpoint.js';\nimport type { IInteractiveSessionRecord } from '@robota-sdk/agent-interface-session';\nimport type { IHostedIdentity, IHostedSnapshot } from './hosted-runtime-types.js';\n\nexport interface IHostedCheckpointFile {\n readonly path: string;\n readonly bytes: Uint8Array;\n}\n\nexport interface IHostedFilesystemCheckpoint {\n readonly sourceWorker: string;\n readonly sourceRuntime: string;\n readonly sourceEpoch: number;\n readonly files: readonly IHostedCheckpointFile[];\n readonly session?: IInteractiveSessionRecord;\n}\n\n/** The reference and current identity come from the owner outside the worker, not the manifest. */\nexport function decodeHostedFilesystemCheckpoint(\n contents: Uint8Array,\n reference: IHostedSnapshot,\n current: { readonly identity: IHostedIdentity; readonly epoch: number },\n): IHostedFilesystemCheckpoint {\n if (\n contents.byteLength > 48 * 1024 * 1024 ||\n createHash('sha256').update(contents).digest('hex') !== reference.digest\n )\n throw hostedAdmissionError('filesystem checkpoint digest or size is invalid');\n let raw: Record<string, unknown>;\n try {\n raw = record(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(contents)), 'checkpoint');\n } catch {\n throw hostedAdmissionError('filesystem checkpoint is not valid UTF-8 JSON');\n }\n exactKeys(raw, ['version', 'id', 'identity', 'epoch', 'worker', 'files', ...(raw.version === 2 ? ['session'] : [])], 'checkpoint');\n if ((raw.version !== 1 && raw.version !== 2) || raw.id !== reference.id)\n throw hostedAdmissionError('filesystem checkpoint version or identity does not match');\n const identity = decodeHostedIdentity(raw.identity);\n const sourceEpoch = positiveInteger(raw.epoch, 'checkpoint epoch');\n const sourceWorker = identifier(raw.worker, 'checkpoint worker');\n if (\n ['tenant', 'task', 'rootTask'].some(\n (key) => identity[key as keyof IHostedIdentity] !== current.identity[key as keyof IHostedIdentity],\n ) ||\n identity.runtime === current.identity.runtime ||\n sourceEpoch >= current.epoch\n )\n throw hostedAdmissionError('filesystem checkpoint requires the same task and a fresh identity/epoch');\n if (!Array.isArray(raw.files) || raw.files.length > 1000)\n throw hostedAdmissionError('filesystem checkpoint file inventory is invalid');\n const paths = new Set<string>();\n let total = 0;\n const files = raw.files.map((value): IHostedCheckpointFile => {\n const file = record(value, 'checkpoint file');\n exactKeys(file, ['path', 'base64'], 'checkpoint file');\n const path = identifier(file.path, 'checkpoint file path');\n const first = path.split('/')[0];\n if (\n posix.isAbsolute(path) ||\n posix.normalize(path) !== path ||\n path === '.' ||\n path === '..' ||\n path.startsWith('../') ||\n path.endsWith('/') ||\n path.includes('\\\\') ||\n first === '.home' ||\n first === '.tmp' ||\n paths.has(path)\n )\n throw hostedAdmissionError('filesystem checkpoint path escapes or replaces private state');\n if (typeof file.base64 !== 'string' || file.base64.length > 44 * 1024 * 1024)\n throw hostedAdmissionError('filesystem checkpoint file encoding is invalid');\n const bytes = Buffer.from(file.base64, 'base64');\n total += bytes.byteLength;\n if (bytes.toString('base64') !== file.base64 || total > 32 * 1024 * 1024)\n throw hostedAdmissionError('filesystem checkpoint encoding or byte budget is invalid');\n paths.add(path);\n return Object.freeze({ path, bytes: new Uint8Array(bytes) });\n });\n for (const path of paths) {\n let parent = posix.dirname(path);\n while (parent !== '.') {\n if (paths.has(parent))\n throw hostedAdmissionError('filesystem checkpoint file conflicts with a directory');\n parent = posix.dirname(parent);\n }\n }\n return Object.freeze({ sourceWorker, sourceRuntime: identity.runtime, sourceEpoch, files,\n ...(raw.version === 2 ? { session: projectHostedSessionCheckpoint(raw.session, '/') } : {}),\n });\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport { loadE2BSdk } from './e2b-sdk.js';\nimport {\n decodeHostedIdentity,\n decodeHostedSnapshot,\n hostedAdmissionError,\n identifier,\n positiveInteger,\n} from './hosted-runtime-config.js';\nimport { decodeHostedFilesystemCheckpoint } from './hosted-filesystem-checkpoint.js';\nimport { hostedSessionCheckpointBytes } from './hosted-session-checkpoint.js';\nimport type { IHostedWorkerResumeSession } from './hosted-worker-execution-config.js';\nimport type { IHostedIdentity, IHostedSnapshot } from './hosted-runtime-types.js';\nimport type { Sandbox } from 'e2b/dist/index.mjs';\n\n/** Owner-side input. Sign admission only after this operation returns a verified resource receipt. */\nexport interface IE2BWorkerProvisioningOptions {\n readonly identity: IHostedIdentity;\n readonly epoch: number;\n readonly templateId: string;\n readonly apiKey: string;\n readonly brokerEndpoint: string;\n readonly lifetimeMs: number;\n readonly requestTimeoutMs: number;\n readonly signal: AbortSignal;\n readonly snapshot: IHostedSnapshot | null;\n /** Owner-issued organization binding retained in the provider inventory across broker restarts. */\n readonly organization?: { readonly controlPlane: string; readonly grantId: string };\n /** Bytes fetched from the owner's checkpoint store; never an E2B memory snapshot/template. */\n readonly checkpoint?: Uint8Array;\n}\n\nexport interface IE2BProvisionedWorker {\n readonly resource: string;\n readonly workspaceRoot: string;\n readonly operationId: string;\n readonly resumeSession?: IHostedWorkerResumeSession;\n readonly snapshot: IHostedSnapshot | null;\n release(): Promise<void>;\n}\n\n/** Reconciliation identifiers, without provider error text or credentials. */\nexport class E2BWorkerProvisioningError extends Error {\n constructor(\n readonly outcome: 'allocation-unknown' | 'cleanup-unresolved',\n readonly operationId: string,\n readonly resource?: string,\n ) {\n super(`E2B worker provisioning ${outcome}; owner reconciliation is required`);\n this.name = 'E2BWorkerProvisioningError';\n }\n}\n\n/** Create from a pinned clean baseline, restoring only bounded task files before issuing any authority. */\nexport async function provisionE2BTaskWorker(\n options: IE2BWorkerProvisioningOptions,\n): Promise<IE2BProvisionedWorker> {\n const identity = decodeHostedIdentity(options.identity);\n const epoch = positiveInteger(options.epoch, 'worker epoch');\n const templateId = identifier(options.templateId, 'E2B clean template');\n const snapshot = decodeHostedSnapshot(options.snapshot);\n if ((snapshot === null) !== (options.checkpoint === undefined) || snapshot?.id === templateId)\n throw hostedAdmissionError('worker recovery requires checkpoint bytes and a separate clean template');\n const checkpoint = snapshot === null\n ? undefined\n : decodeHostedFilesystemCheckpoint(options.checkpoint!, snapshot, { identity, epoch });\n let broker: URL;\n try {\n broker = new URL(options.brokerEndpoint);\n } catch {\n throw hostedAdmissionError('worker broker endpoint is invalid');\n }\n if (\n (broker.protocol !== 'https:' && !(broker.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(broker.hostname))) ||\n broker.username || broker.password || broker.search || broker.hash\n )\n throw hostedAdmissionError('worker broker endpoint requires owner-selected TLS or literal loopback');\n const request = {\n apiKey: identifier(options.apiKey, 'E2B management credential'),\n requestTimeoutMs: positiveInteger(options.requestTimeoutMs, 'E2B request timeout', 30_000),\n apiUrl: 'https://api.e2b.app',\n sandboxUrl: 'https://sandbox.e2b.app',\n domain: 'e2b.app',\n debug: false,\n retries: 0,\n };\n const lifetimeMs = positiveInteger(options.lifetimeMs, 'E2B lifetime', 86_400_000);\n const operationId = randomUUID();\n const metadata = {\n ...identity,\n epoch: String(epoch),\n operationId,\n ...(options.organization === undefined ? {} : {\n organizationControlPlane: identifier(options.organization.controlPlane, 'organization control plane'),\n organizationGrant: identifier(options.organization.grantId, 'organization grant'),\n }),\n ...(snapshot === null ? {} : {\n restoreMode: 'filesystem-v1',\n checkpointId: snapshot.id,\n checkpointDigest: snapshot.digest,\n sourceWorker: checkpoint!.sourceWorker,\n sourceRuntime: checkpoint!.sourceRuntime,\n sourceEpoch: String(checkpoint!.sourceEpoch),\n }),\n };\n options.signal.throwIfAborted();\n const { Sandbox } = await loadE2BSdk();\n options.signal.throwIfAborted();\n let sandbox: Sandbox;\n try {\n // Do not abort away the allocation receipt. No authority is issued while allocation is pending.\n sandbox = await Sandbox.create(templateId, {\n ...request,\n timeoutMs: lifetimeMs,\n metadata,\n envs: {},\n allowInternetAccess: false,\n network: { allowPublicTraffic: false, allowOut: [broker.hostname] },\n lifecycle: { onTimeout: 'kill', autoResume: false },\n });\n } catch {\n throw new E2BWorkerProvisioningError('allocation-unknown', operationId);\n }\n let resource: string;\n try {\n resource = identifier(sandbox.sandboxId, 'allocated worker');\n } catch {\n throw new E2BWorkerProvisioningError('allocation-unknown', operationId);\n }\n let releasing: Promise<void> | undefined;\n const release = (): Promise<void> => {\n if (releasing === undefined)\n releasing = Sandbox.kill(resource, request).then(() => undefined).catch(() => {\n throw new E2BWorkerProvisioningError('cleanup-unresolved', operationId, resource);\n });\n return releasing;\n };\n try {\n const info = await Sandbox.getInfo(resource, request).catch(() => {\n throw new E2BWorkerProvisioningError('allocation-unknown', operationId, resource);\n });\n if (info.sandboxId !== resource || Object.entries(metadata).some(([key, value]) => info.metadata[key] !== value))\n throw new E2BWorkerProvisioningError('allocation-unknown', operationId, resource);\n if (resource === checkpoint?.sourceWorker)\n throw hostedAdmissionError('provider returned the checkpoint source instead of a fresh worker');\n if (\n info.templateId !== templateId || info.state !== 'running' ||\n info.lifecycle?.onTimeout !== 'kill' || info.lifecycle.autoResume !== false ||\n info.allowInternetAccess !== false || info.network?.allowPublicTraffic !== false ||\n JSON.stringify(info.network.allowOut ?? []) !== JSON.stringify([broker.hostname]) ||\n (info.volumeMounts?.length ?? 0) !== 0 || info.network.egressProxy !== undefined ||\n Object.keys(info.network.rules ?? {}).length !== 0\n )\n throw hostedAdmissionError('allocated worker ownership, clean template or network posture is invalid');\n options.signal.throwIfAborted();\n // An atomic new directory cannot inherit checkpoint symlinks or old user/authority state.\n const created = await sandbox.commands.run(`umask 077; mktemp -d \"\\${TMPDIR:-/tmp}/agent-task-${operationId}-XXXXXXXXXX\"`, {\n cwd: '/', envs: {}, timeoutMs: options.requestTimeoutMs, requestTimeoutMs: options.requestTimeoutMs,\n });\n if (created.exitCode !== 0 || typeof created.stdout !== 'string')\n throw hostedAdmissionError('fresh worker workspace creation failed');\n const workspaceRoot = created.stdout.trim();\n if (\n !/^\\/[A-Za-z0-9._/-]+$/u.test(workspaceRoot) ||\n posix.normalize(workspaceRoot) !== workspaceRoot ||\n !new RegExp(`^agent-task-${operationId}-[A-Za-z0-9]{10}$`, 'u').test(posix.basename(workspaceRoot))\n )\n throw hostedAdmissionError('fresh worker workspace receipt is invalid');\n for (const file of checkpoint?.files ?? []) {\n options.signal.throwIfAborted();\n const path = posix.join(workspaceRoot, file.path);\n await sandbox.files.write(path, file.bytes.slice().buffer as ArrayBuffer, {\n requestTimeoutMs: options.requestTimeoutMs,\n });\n const restored = await sandbox.files.read(path, { format: 'bytes', requestTimeoutMs: options.requestTimeoutMs });\n if (!Buffer.from(restored).equals(Buffer.from(file.bytes)))\n throw hostedAdmissionError('restored filesystem checkpoint bytes do not match');\n }\n let resumeSession: IHostedWorkerResumeSession | undefined;\n if (checkpoint?.session !== undefined) {\n options.signal.throwIfAborted();\n const session = { ...checkpoint.session, cwd: workspaceRoot };\n const bytes = hostedSessionCheckpointBytes(session);\n const path = posix.join(workspaceRoot, '.home', '.checkpoint-sessions', `${session.id}.json`);\n await sandbox.files.write(path, Uint8Array.from(bytes).buffer, { requestTimeoutMs: options.requestTimeoutMs });\n const restored = await sandbox.files.read(path, { format: 'bytes', requestTimeoutMs: options.requestTimeoutMs });\n if (!Buffer.from(restored).equals(bytes))\n throw hostedAdmissionError('restored conversation checkpoint bytes do not match');\n resumeSession = Object.freeze({ id: session.id, path, digest: createHash('sha256').update(bytes).digest('hex') });\n }\n options.signal.throwIfAborted();\n return Object.freeze({ resource, workspaceRoot, operationId, snapshot, release,\n ...(resumeSession === undefined ? {} : { resumeSession }),\n });\n } catch (error) {\n if (error instanceof E2BWorkerProvisioningError && error.outcome === 'allocation-unknown') throw error;\n await release();\n if (options.signal.aborted) options.signal.throwIfAborted();\n if (error instanceof Error && error.message.startsWith('Hosted runtime admission refused:')) throw error;\n throw hostedAdmissionError('fresh worker provisioning or filesystem restoration failed');\n }\n}\n","import {\n createAccessTokenVerifier,\n parsePublicHttpsUrl,\n} from '@robota-sdk/agent-transport/node';\nimport type { IAccessTokenVerifierDeps } from '@robota-sdk/agent-transport/node';\nimport type {\n HostedOrganizationControl,\n IHostedOrganizationWorker,\n} from '../hosted-organization-control.js';\n\nexport interface IDesktopBinding {\n readonly id: string;\n readonly user: string;\n readonly client: string;\n readonly session: string;\n readonly worker: IHostedOrganizationWorker;\n}\nexport class DesktopRefused extends Error {\n constructor(readonly reason: string) {\n super(`Remote desktop refused: ${reason}`);\n }\n}\nexport interface IDesktopProof {\n readonly binding: IDesktopBinding;\n readonly jti: string;\n readonly expiresAt: number;\n readonly credentialExpiresAt: number;\n}\nexport interface IDesktopAuthorizationOptions {\n readonly publicUrl: string;\n readonly issuer: string;\n readonly control: HostedOrganizationControl;\n /** Owner-selected identities and sessions, never a caller's registry. */\n readonly bindings: readonly IDesktopBinding[];\n readonly verifierDeps?: IAccessTokenVerifierDeps;\n readonly now?: () => number;\n}\nexport function desktopBindingKey(binding: IDesktopBinding): string {\n return JSON.stringify([\n binding.id,\n binding.user,\n binding.client,\n binding.session,\n binding.worker.resource,\n binding.worker.grantId,\n binding.worker.epoch,\n binding.worker.identity.tenant,\n binding.worker.identity.task,\n binding.worker.identity.rootTask,\n binding.worker.identity.actor,\n binding.worker.identity.runtime,\n ]);\n}\n/** A freshly verified issuer credential still needs current company authority and exact session ownership. */\nexport class HostedDesktopAuthorization {\n readonly url: URL;\n private readonly now: () => number;\n private readonly bindings: readonly IDesktopBinding[];\n constructor(private readonly options: IDesktopAuthorizationOptions) {\n this.url = parsePublicHttpsUrl(options.publicUrl, 'Desktop runtime');\n parsePublicHttpsUrl(options.issuer, 'Desktop issuer');\n this.now = options.now ?? Date.now;\n this.bindings = options.bindings.map((binding) => {\n const copy = structuredClone(binding);\n Object.freeze(copy.worker.identity);\n Object.freeze(copy.worker);\n return Object.freeze(copy);\n });\n if (\n options.bindings.length === 0 ||\n options.bindings.length > 100 ||\n options.bindings.some((binding) =>\n [binding.id, binding.user, binding.client, binding.session].some(\n (value) =>\n typeof value !== 'string' ||\n value.length === 0 ||\n value.length > 256 ||\n /[\\r\\n]/u.test(value),\n ),\n ) ||\n new Set(options.bindings.map((binding) => binding.id)).size !== options.bindings.length\n )\n throw new DesktopRefused('owner-bindings');\n }\n binding(id: string): IDesktopBinding {\n const binding = this.bindings.find((entry) => entry.id === id);\n if (!binding) throw new DesktopRefused('owner-binding');\n return binding;\n }\n async verify(\n token: string,\n binding: IDesktopBinding,\n operator = false,\n signal?: AbortSignal,\n ): Promise<IDesktopProof> {\n signal?.throwIfAborted();\n if (!this.bindings.some((entry) => desktopBindingKey(entry) === desktopBindingKey(binding)))\n throw new DesktopRefused('owner-binding');\n // Pairing and readiness do not extend stale issuer keys during an outage.\n const verifier = createAccessTokenVerifier(\n {\n issuer: this.options.issuer,\n resource: operator ? `${this.url.href.replace(/\\/$/u, '')}/approval` : this.url.href,\n algorithms: ['EdDSA', 'ES256', 'RS256'],\n allowedSubjects: [binding.user],\n requiredScopes: operator ? ['desktop:approve'] : ['desktop:pair', 'desktop:drive'],\n },\n this.options.verifierDeps,\n );\n const verdict = await verifier.verify(token);\n if (!verdict.admitted) throw new DesktopRefused(verdict.refusal);\n // Decode only AFTER signature/issuer/audience/subject/scope verification.\n const claims = JSON.parse(\n Buffer.from(token.split('.')[1]!, 'base64url').toString('utf8'),\n ) as Record<string, unknown>;\n const now = this.now();\n if (\n typeof claims.iat !== 'number' ||\n !Number.isSafeInteger(claims.iat) ||\n typeof claims.exp !== 'number' ||\n !Number.isSafeInteger(claims.exp) ||\n claims.iat * 1000 > now ||\n claims.exp * 1000 <= now ||\n claims.exp - claims.iat > 120 ||\n (claims.nbf !== undefined &&\n (typeof claims.nbf !== 'number' ||\n !Number.isSafeInteger(claims.nbf) ||\n claims.nbf * 1000 > now)) ||\n typeof claims.jti !== 'string' ||\n !/^[A-Za-z0-9_-]{8,256}$/u.test(claims.jti)\n )\n throw new DesktopRefused('short-lived-credential');\n if (\n claims.sub !== binding.user ||\n claims.client_id !== binding.client ||\n claims.tenant !== binding.worker.identity.tenant ||\n claims.task !== binding.worker.identity.task ||\n claims.session !== binding.session ||\n claims.workload !== binding.worker.identity.runtime ||\n claims.epoch !== binding.worker.epoch\n )\n throw new DesktopRefused('session-ownership');\n signal?.throwIfAborted();\n const grant = await this.options.control.admit(binding.worker, signal);\n signal?.throwIfAborted();\n return {\n binding,\n jti: claims.jti,\n credentialExpiresAt: claims.exp * 1000,\n expiresAt: Math.min(claims.exp * 1000, grant.expiresAt, now + 60_000),\n };\n }\n async current(binding: IDesktopBinding, signal?: AbortSignal): Promise<void> {\n if (!this.bindings.some((entry) => desktopBindingKey(entry) === desktopBindingKey(binding)))\n throw new DesktopRefused('owner-binding');\n await this.options.control.admit(binding.worker, signal);\n }\n}\n","import { createHash, randomBytes, randomUUID } from 'node:crypto';\nimport {\n closeSync,\n constants,\n existsSync,\n fstatSync,\n fsyncSync,\n lstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmdirSync,\n writeFileSync,\n unlinkSync,\n} from 'node:fs';\nimport { isAbsolute, join } from 'node:path';\nimport type {\n IOrganizationLedgerAnchor,\n IOrganizationLedgerHead,\n} from '@robota-sdk/agent-organization-host';\nimport { DesktopRefused } from './authorization.js';\n\ninterface IConnection {\n generation: number;\n access: string;\n approval: string | null;\n expiresAt: number;\n connected: boolean;\n}\ninterface IState {\n version: 1;\n revision: number;\n spent: Record<string, number>;\n connections: Record<string, IConnection>;\n}\nexport interface IDesktopAccess {\n readonly key: string;\n readonly generation: number;\n readonly token: string;\n readonly approvalToken: string | null;\n readonly expiresAt: number;\n}\nconst digest = (value: string): string => createHash('sha256').update(value).digest('hex');\nconst sameHead = (a: IOrganizationLedgerHead | undefined, b: IOrganizationLedgerHead): boolean =>\n a?.version === b.version &&\n a.ledger === b.ledger &&\n a.revision === b.revision &&\n a.digest === b.digest;\n\n/** Replay and connection replacement survive restart; independent custody rejects restored authority. */\nexport class HostedDesktopAuthorityStore {\n private readonly directory: string;\n private readonly file: string;\n private readonly lock: string;\n constructor(\n options: { directory: string; anchor: IOrganizationLedgerAnchor; create?: boolean },\n private readonly now: () => number = Date.now,\n ) {\n this.anchor = options.anchor;\n if (!isAbsolute(options.directory)) throw new DesktopRefused('store-unavailable');\n this.directory = realpathSync(options.directory);\n const stat = lstatSync(this.directory);\n if (\n !stat.isDirectory() ||\n (stat.mode & 0o077) !== 0 ||\n (process.getuid !== undefined && stat.uid !== process.getuid())\n )\n throw new DesktopRefused('store-unavailable');\n this.file = join(this.directory, 'desktop-authority.json');\n this.lock = join(this.directory, 'desktop-authority.lock');\n if (options.create === true) {\n if (existsSync(this.file) || this.anchor.read() !== undefined)\n throw new DesktopRefused('store-unavailable');\n this.locked(() =>\n this.write(undefined, { version: 1, revision: 1, spent: {}, connections: {} }),\n );\n }\n this.read();\n }\n private readonly anchor: IOrganizationLedgerAnchor;\n private head(state: IState): IOrganizationLedgerHead {\n return {\n version: 1,\n ledger: this.anchor.ledger,\n revision: state.revision,\n digest: digest(JSON.stringify(state)),\n };\n }\n private read(): IState {\n const fd = openSync(\n this.file,\n constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,\n );\n try {\n const stat = fstatSync(fd);\n if (\n !stat.isFile() ||\n stat.size > 2 * 1024 * 1024 ||\n (stat.mode & 0o077) !== 0 ||\n (process.getuid !== undefined && stat.uid !== process.getuid())\n )\n throw new DesktopRefused('store-unavailable');\n const state = JSON.parse(readFileSync(fd, 'utf8')) as IState;\n const head = this.anchor.read();\n if (\n state.version !== 1 ||\n !Number.isSafeInteger(state.revision) ||\n state.revision < 1 ||\n !state.spent ||\n !state.connections ||\n !sameHead(head, this.head(state))\n )\n throw new DesktopRefused('store-unavailable');\n return state;\n } finally {\n closeSync(fd);\n }\n }\n private locked<T>(work: () => T): T {\n mkdirSync(this.lock, { mode: 0o700 });\n try {\n return work();\n } finally {\n rmdirSync(this.lock);\n }\n }\n private write(expected: IState | undefined, state: IState): void {\n const temporary = join(this.directory, `desktop-${randomUUID()}.tmp`);\n try {\n const fd = openSync(temporary, 'wx', 0o600);\n try {\n writeFileSync(fd, JSON.stringify(state));\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n const next = this.head(state);\n this.anchor.compareAndSet(expected === undefined ? undefined : this.head(expected), next);\n if (!sameHead(this.anchor.read(), next)) throw new DesktopRefused('store-unavailable');\n renameSync(temporary, this.file);\n const directory = openSync(this.directory, constants.O_RDONLY);\n try {\n fsyncSync(directory);\n } finally {\n closeSync(directory);\n }\n } finally {\n if (existsSync(temporary)) unlinkSync(temporary);\n }\n }\n private change<T>(update: (state: IState) => T): T {\n return this.locked(() => {\n const before = this.read();\n const next = structuredClone(before);\n const result = update(next);\n next.revision++;\n this.write(before, next);\n return result;\n });\n }\n pair(\n key: string,\n proofs: readonly { readonly id: string; readonly expiresAt: number }[],\n expiresAt: number,\n operator: boolean,\n ): IDesktopAccess {\n const token = randomBytes(32).toString('base64url');\n const approvalToken = operator ? randomBytes(32).toString('base64url') : null;\n return this.change((state) => {\n for (const [id, expiry] of Object.entries(state.spent))\n if (expiry <= this.now()) delete state.spent[id];\n if (\n expiresAt <= this.now() ||\n proofs.length === 0 ||\n new Set(proofs.map((proof) => proof.id)).size !== proofs.length ||\n proofs.some(\n (proof) => !Number.isSafeInteger(proof.expiresAt) || proof.expiresAt < expiresAt,\n ) ||\n Object.keys(state.spent).length + proofs.length > 4096 ||\n proofs.some((proof) => state.spent[digest(proof.id)] !== undefined)\n )\n throw new DesktopRefused('replayed-pairing');\n const hashed = digest(key);\n if (state.connections[hashed] === undefined && Object.keys(state.connections).length >= 100)\n throw new DesktopRefused('connection-capacity');\n const generation = (state.connections[hashed]?.generation ?? 0) + 1;\n state.connections[hashed] = {\n generation,\n access: digest(token),\n approval: approvalToken === null ? null : digest(approvalToken),\n expiresAt,\n connected: false,\n };\n for (const proof of proofs) state.spent[digest(proof.id)] = proof.expiresAt;\n return { key, generation, token, approvalToken, expiresAt };\n });\n }\n authorize(key: string, generation: number, token: string, operator = false): void {\n const entry = this.read().connections[digest(key)];\n if (\n !entry ||\n entry.generation !== generation ||\n entry.expiresAt <= this.now() ||\n (operator ? entry.approval : entry.access) !== digest(token)\n )\n throw new DesktopRefused('withdrawn-connection');\n }\n connect(key: string, generation: number, token: string): void {\n this.authorize(key, generation, token);\n this.change((state) => {\n const entry = state.connections[digest(key)]!;\n if (entry.generation !== generation || entry.expiresAt <= this.now() || entry.connected)\n throw new DesktopRefused('replayed-connection');\n entry.connected = true;\n });\n }\n approveOnce(key: string, generation: number, token: string, prompt: string): void {\n this.authorize(key, generation, token, true);\n this.change((state) => {\n const entry = state.connections[digest(key)]!;\n if (\n entry.generation !== generation ||\n entry.expiresAt <= this.now() ||\n entry.approval !== digest(token)\n )\n throw new DesktopRefused('withdrawn-connection');\n const nonce = digest(`approval:${key}:${prompt}`);\n if (state.spent[nonce] !== undefined) throw new DesktopRefused('replayed-approval');\n if (Object.keys(state.spent).length >= 4096) throw new DesktopRefused('approval-capacity');\n // An uncertain permission response cannot become permission to send it again after reconnect.\n state.spent[nonce] = Number.MAX_SAFE_INTEGER;\n });\n }\n revoke(key: string): void {\n this.change((state) => {\n const entry = state.connections[digest(key)];\n if (entry) {\n entry.generation++;\n entry.expiresAt = 0;\n }\n });\n }\n}\n","import { createHash } from 'node:crypto';\nimport { WebSocket } from 'ws';\nimport type {\n HostedOrganizationControl,\n IHostedOrganizationWorker,\n} from '../hosted-organization-control.js';\nimport { DesktopRefused } from './authorization.js';\n\nexport const DESKTOP_FRAME_BYTES = 128 * 1024;\nconst READS = new Set([\n 'get-messages',\n 'get-status',\n 'get-context',\n 'get-history',\n 'get-prompts',\n 'get-pending',\n 'get-executing',\n 'get-execution-workspace',\n 'get-execution-detail',\n 'project-status',\n 'project-diff',\n 'project-memory',\n 'get-usage-report',\n 'get-background-tasks',\n 'list-models',\n 'get-agent-definitions',\n]);\nconst hidden = new Set([\n 'sessions',\n 'session_list',\n 'session_renamed_in_list',\n 'session_deleted',\n 'ui_intent',\n 'settings',\n 'commands',\n]);\nexport function desktopPromptDigest(event: Record<string, unknown>): string {\n return createHash('sha256')\n .update('robota/desktop-permission/v1\\0')\n .update(JSON.stringify(event))\n .digest('hex');\n}\n/** One owner-held carrier connection pins the worker's session across desktop reconnects. */\nexport class HostedDesktopWorkerPort {\n readonly session: string;\n private readonly listeners = new Set<(frame: Record<string, unknown>) => void>();\n private readonly ended = new Set<() => void>();\n private readonly pending = new Map<string, { digest: string; event: Record<string, unknown> }>();\n private constructor(\n private readonly socket: WebSocket,\n session: string,\n readonly worker: IHostedOrganizationWorker,\n ) {\n this.session = session;\n socket.on('message', (bytes, binary) => {\n try {\n if (binary || Buffer.byteLength(String(bytes)) > DESKTOP_FRAME_BYTES)\n throw new DesktopRefused('worker-frame');\n const frame = JSON.parse(String(bytes)) as Record<string, unknown>;\n if (!frame || typeof frame !== 'object' || typeof frame.type !== 'string')\n throw new DesktopRefused('worker-frame');\n if (\n (frame.type === 'session_status' &&\n (frame.status as { sessionId?: unknown })?.sessionId !== this.session) ||\n frame.type === 'session_switched'\n )\n throw new DesktopRefused('worker-session-changed');\n if (hidden.has(frame.type)) return;\n if (frame.type === 'permission_request') {\n const event = frame.event as Record<string, unknown>;\n if (\n !event ||\n typeof event.id !== 'string' ||\n event.id.length > 256 ||\n typeof event.toolName !== 'string' ||\n this.pending.size >= 32\n )\n throw new DesktopRefused('worker-prompt');\n this.pending.set(event.id, { digest: desktopPromptDigest(event), event });\n }\n if (frame.type === 'prompt_resolved')\n this.pending.delete((frame.event as { id: string })?.id);\n for (const listener of this.listeners) listener(frame);\n } catch {\n this.close();\n }\n });\n socket.on('error', () => this.close());\n socket.on('close', () => {\n for (const listener of this.ended) listener();\n this.listeners.clear();\n this.ended.clear();\n this.pending.clear();\n });\n }\n static async connect(options: {\n readonly endpoint: string;\n readonly token: string;\n readonly worker: IHostedOrganizationWorker;\n readonly control: HostedOrganizationControl;\n readonly session?: string;\n readonly signal?: AbortSignal;\n }): Promise<HostedDesktopWorkerPort> {\n const url = new URL(options.endpoint);\n if (\n url.protocol !== 'ws:' ||\n !['127.0.0.1', '[::1]'].includes(url.hostname) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash ||\n url.pathname !== '/' ||\n typeof options.token !== 'string' ||\n options.token.length < 16 ||\n options.token.length > 8192\n )\n throw new DesktopRefused('owner-worker-endpoint');\n const signal = AbortSignal.any([\n AbortSignal.timeout(5000),\n ...(options.signal ? [options.signal] : []),\n ]);\n await options.control.admit(options.worker, signal);\n url.searchParams.set('token', options.token);\n const socket = new WebSocket(url, {\n maxPayload: DESKTOP_FRAME_BYTES,\n handshakeTimeout: 5000,\n followRedirects: false,\n });\n try {\n const session = await new Promise<string>((resolve, reject) => {\n let buffered = 0;\n const fail = (): void => reject(new DesktopRefused('worker-unavailable'));\n const receive = (data: unknown, binary: boolean): void => {\n try {\n buffered += Buffer.byteLength(String(data));\n if (binary || buffered > 1024 * 1024) return fail();\n const frame = JSON.parse(String(data)) as {\n type?: string;\n status?: { sessionId?: unknown };\n };\n if (frame.type !== 'session_status') return;\n const id = frame.status?.sessionId;\n if (\n typeof id !== 'string' ||\n id.length === 0 ||\n id.length > 256 ||\n (options.session !== undefined && id !== options.session)\n )\n return fail();\n resolve(id);\n } catch {\n fail();\n }\n };\n socket.once('open', () => socket.send(JSON.stringify({ type: 'get-status' })));\n socket.on('message', receive);\n socket.once('error', fail);\n socket.once('close', fail);\n signal.addEventListener('abort', fail, { once: true });\n const detach = (): void => {\n socket.off('message', receive);\n socket.off('error', fail);\n socket.off('close', fail);\n signal.removeEventListener('abort', fail);\n };\n socket.once('close', detach);\n // Detach discovery before the permanent receiver is installed.\n socket.on('message', function done(data) {\n try {\n if (JSON.parse(String(data)).type === 'session_status') {\n detach();\n socket.off('message', done);\n }\n } catch {\n /* Discovery refuses malformed frames through its receiver above. */\n }\n });\n });\n signal.throwIfAborted();\n await options.control.admit(options.worker, signal);\n signal.throwIfAborted();\n return new HostedDesktopWorkerPort(\n socket,\n session,\n Object.freeze(structuredClone(options.worker)),\n );\n } catch {\n socket.terminate();\n throw new DesktopRefused('worker-unavailable');\n }\n }\n onFrame(listener: (frame: Record<string, unknown>) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n onClose(listener: () => void): () => void {\n this.ended.add(listener);\n return () => this.ended.delete(listener);\n }\n ready(): void {\n if (this.socket.readyState !== WebSocket.OPEN) throw new DesktopRefused('worker-unavailable');\n }\n send(frame: Record<string, unknown>): Record<string, unknown> | undefined {\n this.ready();\n const bytes = JSON.stringify(frame);\n if (Buffer.byteLength(bytes) > DESKTOP_FRAME_BYTES || this.socket.bufferedAmount > 1024 * 1024)\n throw new DesktopRefused('frame-capacity');\n if (frame.type === 'get-commands') return { type: 'commands', commands: [], skills: [] };\n if (frame.type === 'list-sessions' && typeof frame.requestId === 'string')\n return {\n type: 'sessions',\n requestId: frame.requestId,\n listing: { currentSessionId: this.session, sessions: [], unreadableSessionIds: [] },\n };\n if (frame.type === 'submit') {\n if (\n typeof frame.prompt !== 'string' ||\n /^\\s*\\//u.test(frame.prompt) ||\n Object.keys(frame).some((key) => !['type', 'prompt'].includes(key))\n )\n throw new DesktopRefused('remote-command');\n } else if (\n !READS.has(String(frame.type)) &&\n frame.type !== 'abort' &&\n frame.type !== 'ask-response'\n )\n throw new DesktopRefused('remote-capability');\n if ('sessionId' in frame || 'driverId' in frame || 'tenant' in frame || 'task' in frame)\n throw new DesktopRefused('remote-ownership');\n this.socket.send(bytes);\n return undefined;\n }\n prompt(id: string, digest: string): void {\n if (this.pending.get(id)?.digest !== digest) throw new DesktopRefused('stale-approval');\n }\n approve(id: string, digest: string, allow: boolean): void {\n this.ready();\n this.prompt(id, digest);\n this.pending.delete(id);\n this.socket.send(JSON.stringify({ type: 'permission-response', id, result: allow }));\n }\n close(): void {\n this.socket.terminate();\n }\n}\n","import { ServerResponse } from 'node:http';\nimport { isIP } from 'node:net';\nimport { WebSocket, WebSocketServer } from 'ws';\nimport { bearerCredential, createBearerResourceServer } from '@robota-sdk/agent-transport/node';\nimport { DesktopRefused, desktopBindingKey } from './authorization.js';\nimport { DESKTOP_FRAME_BYTES } from './worker-port.js';\nimport type { HostedDesktopAuthorization, IDesktopBinding } from './authorization.js';\nimport type { HostedDesktopAuthorityStore, IDesktopAccess } from './authority-store.js';\nimport type { HostedDesktopWorkerPort } from './worker-port.js';\nimport type { IncomingMessage, Server } from 'node:http';\nimport type { Duplex } from 'node:stream';\n\ninterface IPaired {\n binding: IDesktopBinding;\n access: IDesktopAccess;\n jwt: string;\n operatorJwt?: string;\n port: HostedDesktopWorkerPort;\n}\nconst uniqueHeaders = new Set([\n 'authorization',\n 'x-desktop-operator-authorization',\n 'host',\n 'origin',\n 'x-forwarded-for',\n 'x-forwarded-host',\n 'x-forwarded-proto',\n]);\nconst address = (value: string | undefined): string =>\n (value ?? '').replace(/^::ffff:/u, '').toLowerCase();\n\n/** Outside workers: owns scoped ingress and a separate operator channel to one pinned task session. */\nexport class HostedDesktopGateway {\n private readonly wss = new WebSocketServer({ noServer: true, maxPayload: DESKTOP_FRAME_BYTES });\n private readonly paired = new Map<string, IPaired>();\n private readonly active = new Map<WebSocket, IPaired>();\n private readonly names;\n private readonly proxies: ReadonlySet<string>;\n private readonly interval: number;\n private closed = false;\n private readonly upgrades = new Set<Duplex>();\n constructor(\n private readonly options: {\n readonly server: Server;\n readonly authorization: HostedDesktopAuthorization;\n readonly store: HostedDesktopAuthorityStore;\n readonly ports: ReadonlyMap<string, HostedDesktopWorkerPort>;\n readonly trustedProxies?: readonly string[];\n readonly policyIntervalMs?: number;\n },\n ) {\n this.interval = options.policyIntervalMs ?? 1000;\n if (\n !Number.isSafeInteger(this.interval) ||\n this.interval < 100 ||\n this.interval > 5000 ||\n (options.trustedProxies ?? []).some((ip) => isIP(ip) === 0)\n )\n throw new DesktopRefused('gateway-configuration');\n this.proxies = new Set((options.trustedProxies ?? []).map(address));\n this.names = createBearerResourceServer({\n publicUrl: options.authorization.url.href,\n label: 'Desktop runtime',\n trustedProxies: options.trustedProxies,\n });\n for (const [id, port] of options.ports) {\n const binding = options.authorization.binding(id);\n if (\n binding.session !== port.session ||\n JSON.stringify(binding.worker) !== JSON.stringify(port.worker)\n )\n throw new DesktopRefused('owner-worker-binding');\n port.ready();\n }\n options.server.on('request', this.request);\n options.server.on('upgrade', this.upgrade);\n }\n private boundary(req: IncomingMessage, res: ServerResponse): boolean {\n const seen = new Set<string>();\n for (let index = 0; index < req.rawHeaders.length; index += 2) {\n const name = req.rawHeaders[index]!.toLowerCase();\n if (uniqueHeaders.has(name) && seen.has(name)) {\n res.writeHead(403).end();\n return false;\n }\n seen.add(name);\n }\n const forwarded = [...seen].some((name) => name.startsWith('x-forwarded-'));\n const trusted = this.proxies.has(address(req.socket.remoteAddress));\n if (\n (forwarded && !trusted) ||\n (!(req.socket as { encrypted?: boolean }).encrypted &&\n (!trusted || req.headers['x-forwarded-proto'] !== 'https')) ||\n (forwarded &&\n (req.headers['x-forwarded-proto'] !== 'https' ||\n req.headers['x-forwarded-host'] !== this.names.url.host))\n ) {\n res.writeHead(403).end();\n return false;\n }\n return this.names.checkNames(req, res);\n }\n private async bounded<T>(work: (signal: AbortSignal) => Promise<T>): Promise<T> {\n const abort = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work(abort.signal),\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n abort.abort();\n reject(new DesktopRefused('authority-timeout'));\n }, 5000);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n abort.abort();\n }\n }\n private async body(req: IncomingMessage): Promise<Record<string, unknown>> {\n const buffers: Buffer[] = [];\n let length = 0;\n for await (const chunk of req) {\n const buffer = Buffer.from(chunk as Uint8Array);\n length += buffer.length;\n if (length > 8192) throw new DesktopRefused('request-capacity');\n buffers.push(buffer);\n }\n const value = JSON.parse(Buffer.concat(buffers).toString('utf8')) as Record<string, unknown>;\n if (!value || typeof value !== 'object' || Array.isArray(value))\n throw new DesktopRefused('request-shape');\n return value;\n }\n private readonly request = (req: IncomingMessage, res: ServerResponse): void => {\n void this.handle(req, res).catch(() => {\n if (!res.headersSent) res.writeHead(403);\n res.end();\n });\n };\n private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n if (this.closed || !this.boundary(req, res)) return;\n if (\n req.method !== 'POST' ||\n ![\n `${this.names.url.pathname.replace(/\\/$/u, '')}/pair`,\n `${this.names.url.pathname.replace(/\\/$/u, '')}/approval`,\n ].includes(req.url ?? '')\n ) {\n res.writeHead(404).end();\n return;\n }\n const timer = setTimeout(() => req.destroy(), 5000);\n try {\n const body = await this.body(req);\n if (req.url?.endsWith('/pair')) {\n if (Object.keys(body).join(',') !== 'binding' || typeof body.binding !== 'string')\n throw new DesktopRefused('request-shape');\n const binding = this.options.authorization.binding(body.binding);\n const port = this.options.ports.get(binding.id);\n if (!port) throw new DesktopRefused('worker-unavailable');\n port.ready();\n const jwt = bearerCredential(req.headers.authorization);\n if (!jwt) throw new DesktopRefused('missing-token');\n const operatorJwt = bearerCredential(\n req.headers['x-desktop-operator-authorization'] as string | undefined,\n );\n if (req.headers['x-desktop-operator-authorization'] !== undefined && !operatorJwt)\n throw new DesktopRefused('operator-token');\n const { drive, operator } = await this.bounded(async (signal) => {\n const drive = await this.options.authorization.verify(jwt, binding, false, signal);\n const operator =\n operatorJwt === undefined\n ? undefined\n : await this.options.authorization.verify(operatorJwt, binding, true, signal);\n signal.throwIfAborted();\n return { drive, operator };\n });\n if (req.aborted || res.destroyed || this.closed)\n throw new DesktopRefused('connection-withdrawn');\n const key = desktopBindingKey(binding);\n const access = this.options.store.pair(\n key,\n [drive, ...(operator ? [operator] : [])].map((proof) => ({\n id: proof.jti,\n expiresAt: proof.credentialExpiresAt,\n })),\n Math.min(drive.expiresAt, operator?.expiresAt ?? drive.expiresAt),\n operator !== undefined,\n );\n this.paired.set(binding.id, { binding, access, jwt, operatorJwt, port });\n for (const [socket, previous] of this.active)\n if (previous.binding.id === binding.id) socket.terminate();\n res.setHeader('cache-control', 'no-store');\n res.setHeader('content-type', 'application/json');\n res.end(\n JSON.stringify({\n binding: binding.id,\n generation: access.generation,\n token: access.token,\n approvalToken: access.approvalToken,\n expiresAt: access.expiresAt,\n session: binding.session,\n }),\n );\n } else {\n if (\n Object.keys(body).sort().join(',') !== 'allow,binding,digest,generation,id' ||\n typeof body.binding !== 'string' ||\n !Number.isSafeInteger(body.generation) ||\n typeof body.id !== 'string' ||\n typeof body.digest !== 'string' ||\n !/^[a-f0-9]{64}$/u.test(body.digest) ||\n typeof body.allow !== 'boolean'\n )\n throw new DesktopRefused('request-shape');\n const pair = this.paired.get(body.binding);\n const token = bearerCredential(req.headers.authorization);\n if (!pair || pair.access.generation !== body.generation || !token || !pair.operatorJwt)\n throw new DesktopRefused('operator-token');\n this.options.store.authorize(pair.access.key, pair.access.generation, token, true);\n await this.bounded((signal) =>\n this.options.authorization.verify(pair.operatorJwt!, pair.binding, true, signal),\n );\n if (req.aborted || res.destroyed || this.closed)\n throw new DesktopRefused('connection-withdrawn');\n pair.port.prompt(body.id, body.digest);\n this.options.store.approveOnce(pair.access.key, pair.access.generation, token, body.digest);\n pair.port.approve(body.id, body.digest, body.allow);\n res.writeHead(204).end();\n }\n } finally {\n clearTimeout(timer);\n }\n }\n private readonly upgrade = (req: IncomingMessage, socket: Duplex, head: Buffer): void => {\n this.upgrades.add(socket);\n socket.once('close', () => this.upgrades.delete(socket));\n socket.once('error', () => socket.destroy());\n const res = new ServerResponse(req);\n res.assignSocket(socket as import('node:net').Socket);\n if (!this.boundary(req, res)) {\n res.on('finish', () => socket.destroy());\n return;\n }\n res.detachSocket(socket as import('node:net').Socket);\n void this.connect(req, socket, head).catch(() => {\n socket.end('HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n', () =>\n socket.destroy(),\n );\n });\n };\n private async connect(req: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {\n if (this.closed) throw new DesktopRefused('gateway-closed');\n const url = new URL(req.url!, this.names.url);\n if (\n req.method !== 'GET' ||\n url.pathname !== `${this.names.url.pathname.replace(/\\/$/u, '')}/connect` ||\n [...url.searchParams.keys()].sort().join(',') !== 'binding,generation'\n )\n throw new DesktopRefused('connection-shape');\n const pair = this.paired.get(url.searchParams.get('binding')!);\n const generation = Number(url.searchParams.get('generation'));\n const token = bearerCredential(req.headers.authorization);\n if (\n !pair ||\n !token ||\n !Number.isSafeInteger(generation) ||\n generation !== pair.access.generation\n )\n throw new DesktopRefused('withdrawn-connection');\n this.options.store.authorize(pair.access.key, generation, token);\n await this.bounded((signal) =>\n this.options.authorization.verify(pair.jwt, pair.binding, false, signal),\n );\n if (socket.destroyed || this.closed) throw new DesktopRefused('connection-withdrawn');\n pair.port.ready();\n this.options.store.connect(pair.access.key, generation, token);\n this.wss.handleUpgrade(req, socket, head, (ws) => this.attach(ws, pair, token));\n }\n private attach(ws: WebSocket, pair: IPaired, token: string): void {\n this.active.set(ws, pair);\n let checking = false;\n let queue = Promise.resolve();\n let queued = 0;\n const withdraw = (): void => ws.terminate();\n const validate = async (): Promise<void> => {\n this.options.store.authorize(pair.access.key, pair.access.generation, token);\n await this.bounded((signal) =>\n this.options.authorization.verify(pair.jwt, pair.binding, false, signal),\n );\n this.options.store.authorize(pair.access.key, pair.access.generation, token);\n };\n const timer = setInterval(() => {\n if (checking) return;\n checking = true;\n void validate()\n .catch(withdraw)\n .finally(() => {\n checking = false;\n });\n }, this.interval);\n timer.unref();\n const removeFrames = pair.port.onFrame((frame) => {\n try {\n this.options.store.authorize(pair.access.key, pair.access.generation, token);\n if (ws.readyState !== WebSocket.OPEN || ws.bufferedAmount > 1024 * 1024)\n throw new DesktopRefused('delivery-capacity');\n ws.send(JSON.stringify(frame));\n } catch {\n withdraw();\n }\n });\n const removeClose = pair.port.onClose(withdraw);\n ws.on('message', (data, binary) => {\n if (binary || ++queued > 16) {\n withdraw();\n return;\n }\n queue = queue\n .then(async () => {\n await validate();\n if (ws.readyState !== WebSocket.OPEN) return;\n const frame = JSON.parse(String(data)) as Record<string, unknown>;\n const response = pair.port.send(frame);\n if (response) ws.send(JSON.stringify(response));\n })\n .catch(withdraw)\n .finally(() => {\n queued--;\n });\n });\n ws.on('error', withdraw);\n ws.once('close', () => {\n clearInterval(timer);\n removeFrames();\n removeClose();\n this.active.delete(ws);\n });\n pair.port.send({ type: 'get-messages' });\n pair.port.send({ type: 'get-status' });\n pair.port.send({ type: 'get-prompts' });\n }\n /** Owner-only withdrawal; no administrator route is exposed. */\n revoke(binding: string): void {\n const key = desktopBindingKey(this.options.authorization.binding(binding));\n this.options.store.revoke(key);\n this.paired.delete(binding);\n for (const [socket, pair] of this.active) if (pair.binding.id === binding) socket.terminate();\n }\n async close(): Promise<void> {\n this.closed = true;\n this.options.server.off('request', this.request);\n this.options.server.off('upgrade', this.upgrade);\n for (const socket of this.upgrades) socket.destroy();\n for (const socket of this.active.keys()) socket.terminate();\n for (const port of this.options.ports.values()) port.close();\n this.paired.clear();\n await new Promise<void>((resolve) => this.wss.close(() => resolve()));\n }\n}\n"],"mappings":"+5BACA,IAAI,EAA0B,cAAc,KAAM,CACjD,OAAS,iBACT,aAAc,CACb,MAAM,6BAA6B,CACpC,CACD,EAGA,SAAS,GAAY,EAAO,CAC3B,IAAK,IAAM,KAAa,EAAO,CAC9B,IAAM,EAAQ,EAAU,YAAY,CAAC,EACrC,GAAI,GAAS,OAAS,GAAS,MAAO,MAAM,IAAI,CACjD,CACD,CAEA,SAASA,GAAsB,EAAO,CACrC,IAAM,EAA2B,IAAI,IACjC,EAAQ,EACZ,SAAS,EAAO,EAAM,EAAO,CAC5B,GAAI,EAAE,EAAQ,MAAQ,EAAQ,GAAI,MAAM,IAAI,EAC5C,GAAI,IAAS,MAAQ,OAAO,GAAS,UAAW,OAAO,KAAK,UAAU,CAAI,EAC1E,GAAI,OAAO,GAAS,SAEnB,OADA,GAAY,CAAI,EACT,KAA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