@gnldev/server 0.1.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,oIAAoI;AACpI,OAAO,EAAE,IAAI,EAAgB,MAAM,MAAM,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAqB,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,WAAW,EAAE,WAAW,EAAE,kBAAkB,EAAE,SAAS,EAAE,eAAe,EAAE,SAAS,EAAE,cAAc,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,eAAe,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEvgB,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,eAAe,EAAE,WAAW,EAAyD,MAAM,cAAc,CAAC;AACzJ,oFAAoF;AACpF,6GAA6G;AAC7G,iGAAiG;AACjG,gGAAgG;AAChG,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAE7F,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAE3C,4HAA4H;AAC5H,MAAM,uBAAuB,GAAG,OAAO,C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YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,+FAA+F;AAC/F,oGAAoG;AACpG,OAAO,EAAE,gBAAgB,EAAsB,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE7E;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,aAAa,CAC3B,MAAwD,EACxD,OAAuB,EAAE;IAEzB,OAAO,cAAc,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;AAClD,CAAC","sourcesContent":["// @gnldev/server — serves the createGnl registry over HTTP (auto-REST + OpenAPI). Every endpoint\n// descends into runDurable → exactly-once/durability inherited for free. (The durable counterpart of the common auto-REST pattern.)\nimport { Hono, type Context } from 'hono';\nimport { toFetchHandler, type FetchHandler } from './handler.js';\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport { createGnl, agentVisibleToOrg, withOrg, withOrgStorage, ORG_RECORD_PRE, checkBudget, getOrgUsage, budgetsEnforceable, toJournal, asReaderJournal, appendLog, cancelAgentRun, RunLimitExceededError, ToolLoopDetectedError, RunThreadMismatchError, blockedErrorCode, upstreamFailure, sealRequestContext, fingerprintAgent, recordAgent, approveAgent, blockAgent, isAgentServable, listAgentRegistry, callerConflictCode, describeProtections, formatProtections, teachingError, resolveWorkIdentity } from '@gnldev/durable';\nimport type { CreateGnlConfig, Journal, JournalReader, BudgetLimit, UsageCostCache, RunLimits, ResolvedWorkIdentity, WorkScopeKind } from '@gnldev/durable';\nimport { makeGate, normalizeAuth, principalOf, isPlatformAdmin, CLIENT_ROLE, type AuthProvider, type ReadWriteAuth, type Principal } from '@gnldev/auth';\n// P0.4 @gnldev/workflow is zero-dependency (see its package.json) — depending on it\n// from @gnldev/server is a clean one-way edge (server→workflow), NOT circular: @gnldev/durable's registry.ts\n// deliberately stays workflow-agnostic (WorkflowLike is a structural type, no import) to avoid a\n// durable→workflow edge; server has no such constraint and needs the real functions at runtime.\nimport { listWorkflowRuns, getWorkflowRunStatus, cancelWorkflowRun } from '@gnldev/workflow';\nimport type { WorkflowRunStatus } from '@gnldev/workflow';\nimport { buildOpenApi } from './openapi.js';\nimport { EDGE_ERROR_CODES } from './edge-errors.js';\nimport { pipeAgentStream } from './sse.js';\n\n/** (audit: A2A unsigned) — signature window: a request with a timestamp this old/future is rejected (replay resistance). */\nconst A2A_TIMESTAMP_WINDOW_MS = 300_000; // ±300s\n\n/**\n * Verifies the `x-gnl-signature`/`x-gnl-timestamp` header pair produced by @gnldev/a2a's\n * `createA2ATool({ secret })`: signature = HMAC-SHA256(secret, timestamp + '.' + rawBody) hex, compared\n * with `timingSafeEqual` (closed to timing attacks). A second layer INDEPENDENT of the existing auth gate\n * (makeGate/opts.auth) — one asks identity/permission, the other verifies message integrity/origin; both\n * are opt-in and don't affect each other.\n * Invalid/missing → Response (401); valid → undefined.\n */\nfunction verifyA2ASignature(c: Context, rawBody: string, secret: string): Response | undefined {\n const signature = c.req.header('x-gnl-signature');\n const timestamp = c.req.header('x-gnl-timestamp');\n if (!signature || !timestamp) {\n return c.json({ error: 'A2A signature headers missing (x-gnl-signature/x-gnl-timestamp)', code: EDGE_ERROR_CODES.a2aSignatureMissing }, 401);\n }\n const ts = Number(timestamp);\n if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > A2A_TIMESTAMP_WINDOW_MS) {\n return c.json({ error: 'A2A timestamp outside window (±300s) — suspected replay', code: EDGE_ERROR_CODES.a2aTimestampInvalid }, 401);\n }\n const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest();\n const provided = Buffer.from(signature, 'hex');\n if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {\n return c.json({ error: 'A2A signature invalid', code: EDGE_ERROR_CODES.a2aSignatureInvalid }, 401);\n }\n return undefined;\n}\n\n/**\n * `Idempotency-Key` names the WORK — it is a `workKey` alias, and no longer a `runId` one.\n *\n * IT CHANGED AXIS, DELIBERATELY (package #5 of docs/RUNID-WORKKEY-HEYET-KARARI.md §8). FAZ-1 wired\n * this header to `body.runId`, which was the closest thing that existed at the time and the wrong\n * half of the pair: the IETF draft's key names the OPERATION a client is trying to perform, and a\n * client that retries sends the same key because it is the same job. That is a `workKey`'s\n * definition, word for word. A raw runId is an address the engine issued; nobody's gateway knows one.\n *\n * The consequence is visible and meant to be: the header now produces a derived `run1_` id, and in a\n * `'resource'` scope with nobody named it is REFUSED (§6) rather than run for nobody. That is louder\n * than what it replaced, and the loud direction is the cheap one — the quiet direction delivers one\n * caller's work to another caller's door.\n *\n * The precedence below is @gnldev/chat-adapter's, adopted rather than re-argued: whatever the BODY\n * said wins, the header only speaks when the body said nothing. A gateway, a proxy or a client\n * library commonly stamps this header on its own, while the body is a decision the calling\n * APPLICATION made — so header-first would let an intermediary silently change what a request means.\n *\n * Mutates the freshly parsed body rather than threading a new variable through ~60 lines of gates.\n * The object is per-request and local (parseJsonBody), and the A2A signature — computed over the RAW\n * bytes — has already been verified by the time this runs, so nothing downstream is deciding anything\n * on the strength of the body being untouched.\n */\nfunction adoptIdempotencyKey(c: Context, body: { runId?: string; workKey?: string }): void {\n if (body.runId || body.workKey) return;\n const header = c.req.header('Idempotency-Key');\n if (header) body.workKey = header;\n}\n\n/**\n * The id this call will run under, worked out BEFORE the door is called.\n *\n * Three things here need the id and none of them can wait for the run to start: the ownership gate\n * reads `<runId>:input`, the cancel registry is keyed by it, and `X-Gnl-Run-Id` has to name the run\n * that answered. So the route resolves the identity itself — with @gnldev/durable's OWN gate\n * function, not a local copy of it (see resolveWorkIdentity's note) — and then hands the door the\n * `workKey`, never the id it just computed. The door resolves the same tuple and gets the same\n * answer; passing the id instead would silently drop the declaration, and the declaration is the\n * only readable answer to \"which run was the invoice job?\".\n *\n * The scope comes from the AGENT (`gnl.agent(name).workScope`), never from the request body: which\n * address a name is unique within is a property of the work, and the dangerous half of that enum\n * ('org' — see AgentConfig.workScope) must not be reachable from a request. The workflow door is the\n * documented exception and states its own reason.\n */\nfunction identityOrError(\n resolve: () => ResolvedWorkIdentity,\n): ResolvedWorkIdentity | { error: string } {\n try {\n return resolve();\n } catch (e) {\n // The gate's refusals are teaching sentences (both-identities, missing address) — 400 with the\n // engine's own words, because re-wording them here is how two surfaces end up explaining the\n // same rule differently.\n return { error: String((e as { message?: string })?.message ?? e) };\n }\n}\n\n/** Both halves absent — the one refusal the gate would phrase as an engine call, said as a route. */\nconst NO_IDENTITY = 'runId or workKey required (see docs: one names an id, the other names the work)';\n\n/**\n * Had this id been run before this call? — the `X-Gnl-Idempotency-Status` answer.\n *\n * The same question `runDurable` asks itself (`frozenInput !== undefined`) and the same one the\n * streaming path already answers via `__gnlPriorRun`; asked here with one point read so the generate\n * path can answer it too, and so both endpoints answer it the SAME way. It is an observability\n * contract, not a byte-identity guarantee — `replay` means \"this id had journaled input when the\n * call arrived\", which is what a client reconciling duplicate submissions needs to know.\n */\nasync function hadPriorInput(journal: Journal, runId: string): Promise<boolean> {\n try {\n return (await journal.get(`${runId}:input`)) !== undefined;\n } catch {\n return false; // a reader that cannot answer is not evidence either way\n }\n}\n\n/**\n * The header pair every run/stream response carries (§8's header contract).\n *\n * `X-Gnl-Run-Id` is a CORRELATION handle — the opaque id of the run this call landed on, for logs,\n * traces and Studio. It is NOT the retry key: to retry, send the same `workKey` again. That\n * distinction is the whole point of the split, and it only becomes visible once the id is derived —\n * a caller who names work has no other way to learn which run answered.\n *\n * `X-Gnl-Work-Key` is deliberately NOT echoed: headers are a log surface in practice (proxies, CDNs,\n * HAR files), and free text does not go there by default.\n */\nfunction stampRunHeaders(res: Response, runId: string, prior?: boolean): Response {\n res.headers.set('X-Gnl-Run-Id', runId);\n if (prior !== undefined) res.headers.set('X-Gnl-Idempotency-Status', prior ? 'replay' : 'new');\n return res;\n}\n\n/** Same as the old `c.req.json()` `.catch(() => ({}))` behavior: malformed/empty body → `{}`. */\nfunction parseJsonBody(raw: string): any {\n try {\n return raw ? JSON.parse(raw) : {};\n } catch {\n return {};\n }\n}\n\n/**\n * D4-FGA (EE-2): structural mirror of @gnldev/auth-ee's `FgaResource`/`FgaAction` — @gnldev/server does NOT\n * depend on the paid @gnldev/auth-ee package, so these are typed here rather than imported (see\n * `RestApiOptions.resourceAuth` below).\n */\nexport interface ResourceAuthResource {\n type: 'agent' | 'workflow' | 'tool' | 'run';\n id: string;\n}\n/**\n * The verbs @gnldev/server ACTUALLY dispatches, and the ones it does not.\n *\n * DISPATCHED: `'run'` (agent run/stream/resume, workflow run) and `'cancel'` (run/workflow cancel).\n *\n * NOT DISPATCHED: `'read'`. It is kept in the union because the union is open (`string & {}`) and a\n * host may dispatch its own verbs — but nothing in this package ever calls the gate with it, so a\n * host that writes an `action === 'read'` branch gets a rule that never runs. That was measured as a\n * real hazard rather than a cosmetic one: a signature that names a verb reads as a promise that the\n * verb is checked, and the read paths are exactly where subject binding was missing\n * (`subjectBinding`). Read authorisation lives there, not here.\n *\n * `'resume'` IS dispatched — but as `'run'`: resuming executes the agent and carries `approvals`,\n * so denying `run` while allowing `resume` would be the wrong way round (see the resume endpoint's\n * own note). The member stays for hosts that want to distinguish them in their own dispatch.\n */\nexport type ResourceAuthAction = 'run' | 'read' | 'cancel' | 'resume' | (string & {});\n\n/** Per-request multi-organization (opt-in): resolve organization from the request → journal is scoped to that organization. */\nexport interface OrgOptions {\n /** Resolve the organization from the request. If not given, the `x-gnl-org` header is read. */\n /**\n * Takes a web `Request`, not a Hono `Context` — kept in step with @gnldev/studio, and for the same\n * reason: a host binding this handler from Express or Fastify has a Request and no Context.\n */\n resolve?: (req: Request) => string | undefined | Promise<string | undefined>;\n /** true → a request without an organization gets 400. false (default) → a request without an organization runs in the shared scope. */\n required?: boolean;\n /**\n * HARDENING (opt-in): reject any request whose resolved organization is NOT explicitly REGISTERED\n * (an `__org__:<id>` record written by studio's `POST /organizations`; a DELETED org is a `null`\n * tombstone → also rejected → its ghost tokens stop working). Default false = the legacy IMPLICIT-org\n * behavior (an org springs into existence on first activity, no registration needed) — byte-for-byte\n * unchanged. Turn ON for strict provisioning: only orgs you deliberately created may run. NOTE: requires\n * a registration PATH in the deployment (studio's org management, or a direct `__org__:<id>` write);\n * with it on and no such path, every org-scoped request is rejected. */\n requireRegistration?: boolean;\n /**\n * Ceiling on how many per-organization registries are held in memory at once (default 512).\n *\n * The cache is keyed by the RESOLVED organization id, and with `requireRegistration` off — the\n * default — that id is whatever `resolve` returned, i.e. the `x-gnl-org` header. Every distinct\n * value built a full `createGnl` registry and kept it forever, so a loop over random header values\n * grew the process until it died. Nothing in the request has to be valid for that: an unregistered\n * org is served, and serving it is what allocates.\n *\n * Least-recently-used entries are evicted past the cap. Eviction is state-preserving, and the parts\n * that could have made it otherwise were measured rather than assumed: an instance is a CACHE over\n * the org-scoped journal (memory comes from `memoryFactory(scoped)`, the frozen model spec lives in\n * the journal), `createGnl` opens no connections and starts no timers, the rebuild re-derives\n * `withOrg(base, id)` without double-scoping the key prefix, and cancellation is unaffected because\n * `inflight` hangs off the API closure keyed `org:<id>:<runId>` — not off the instance — so the key\n * survives a rebuild.\n *\n * The one exception is a `memoryFactory` that IGNORES its argument and returns a process-local store.\n * That is a split rather than a loss: an in-flight run holds the evicted instance by reference, so\n * for a window one organization has two live stores and half a conversation lands in the one nothing\n * will read again. A factory that uses the journal it is handed — which is why it is handed one —\n * has no such window.\n *\n * Raise it if you legitimately serve more than 512 organizations from one process and want them all\n * warm. A non-integer or a value below 1 is REJECTED at construction, `Infinity` included: the growth\n * this bounds is reachable by anyone who can send a header, so opting out of the bound is not a\n * setting, and a negative one used to spin the eviction loop forever.\n */\n maxInstances?: number;\n}\n\nexport interface RestApiOptions {\n /** OpenAPI title. */\n title?: string;\n /**\n * Optional auth (opt-in). If not given, all endpoints are OPEN (existing behavior). Accepts an\n * AuthProvider (@gnldev/auth or the paid @gnldev/auth-ee) or a backward-compatible {read,write} predicate pair.\n * GET → read, POST → write.\n */\n auth?: AuthProvider | ReadWriteAuth;\n /**\n * Who a request is allowed to speak FOR, on the read paths.\n *\n * `'declared'` (default, today's behaviour): the expectation comes only from what the CALLER\n * states (`?resourceId=` or the body). State nobody and nothing is checked — the rule was written\n * for operators, who work across an organization by design and name nobody.\n *\n * `'strict'`: an authenticated NON-OPERATOR identity speaks for ITSELF. `principal.id` becomes the\n * expectation and a caller-supplied name cannot replace it.\n *\n * WHY THE OPTION EXISTS RATHER THAN A STRAIGHT FIX. Measured on a deployment that hands user-store\n * tokens to end users: `mallory` read `GET /threads` (the whole subject inventory), then\n * `/threads/t-ayse/messages` (`AYSE-SECRET`), then `/runs/r-ayse` (the full journal) — all 200,\n * and naming someone else explicitly was 200 as well. The same identity is a SUBJECT when it\n * writes (`resolveResourceId`) and an OPERATOR when it reads; that asymmetry is the hole.\n *\n * It is not flipped by default because doing so turns today's 200s into 403s for every deployment\n * whose operators read across their organization — which is the documented, intended use. The flag\n * lets a deployment that gives end users tokens close the hole now; the default follows once the\n * operator/end-user split has a first-class shape.\n */\n subjectBinding?: 'declared' | 'strict';\n /**\n * DELIBERATE permission for a provider-less API in production. Auth remains opt-in; but in\n * NODE_ENV=production, calling createRestApi without `auth` throws a setup ERROR — silent fail-open is\n * disabled (audit #2). Set this flag to true if open access is genuinely intended. Outside production:\n * only a single console.warn on the first request.\n */\n allowOpenAccess?: boolean;\n /**\n * Opt-in multi-organization support: each request descends into that organization's journal (withOrg)\n * → runs, memory, and exactly-once guarantees are isolated per organization. The resolved organization\n * is injected into requestContext as `org` (visible to dynamic agents). The registry is lazily built\n * and cached per organization.\n */\n org?: OrgOptions;\n /**\n * Budget/quota FALLBACK limits (ENFORCED on the write path): an organization's effective limit is\n * journal's `__budget__:<id>`/`__budget__:default` (managed from Studio) > `perOrg[id]` > `default`.\n * A new run/stream/workflow request from an organization that is over budget gets 402 (resume remains\n * free — suspended work can finish). Even without this option, budgets written to the journal are\n * enforced (no limit → cost-free early exit).\n */\n budgets?: { default?: BudgetLimit; perOrg?: Record<string, BudgetLimit> };\n /**\n * SERVER-SIDE UPPER BOUND (opt-in) for per-run cost cap + loop detection. The `limits` in the\n * request body (client request) CANNOT EXCEED this cap — the effective limit for each field is computed\n * as `min(server, client)` (see `clampLimits`); if the client doesn't specify a field, the server cap\n * applies, and if neither server nor client specifies it, that field is never enforced. If neither is\n * given (default), behavior is preserved EXACTLY AS IS (unlimited).\n */\n limits?: RunLimits;\n /**\n * (audit: A2A unsigned) — opt-in A2A request verification: if given, the `x-gnl-signature`/\n * `x-gnl-timestamp` header pair produced by `@gnldev/a2a`'s `createA2ATool({ secret })` becomes REQUIRED on\n * `/agents/:name/run` POSTs (see verifyA2ASignature) — missing/wrong signature or a timestamp outside\n * ±300s → 401. If not given, behavior is preserved EXACTLY AS IS (unsigned requests are accepted as\n * before). Works TOGETHER WITH the existing auth gate (opts.auth) — the two are independent layers,\n * both must pass.\n */\n a2aSecret?: string;\n /**\n * D4-FGA (EE-2) opt-in hook: fine-grained (resource-scoped) authorization, consulted AFTER the existing\n * coarse gate (opts.auth) already allowed the request — on agents run/stream, workflows run, and the\n * two cancel endpoints (`/runs/:id/cancel`, `/workflows/runs/:id/cancel`). A denial → 403\n * `{error, code: 'resource_denied'}`, distinct from the coarse gate's 403 (which carries no `code`).\n * Structurally typed (`ResourceAuthResource`/`ResourceAuthAction` above) — @gnldev/server does NOT import\n * @gnldev/auth-ee; an EE user wires this to `createEnterpriseAuth(...).checkResource` (see @gnldev/auth-ee's\n * `createFga`/`EnterpriseAuthProvider.checkResource`), e.g.:\n * resourceAuth: (p, r, a) => enterpriseAuth.checkResource!(p, r, a).then((res) => res.allowed)\n * If NOT given, behavior is preserved EXACTLY AS IS (no resource-level gate — existing coarse auth only).\n */\n resourceAuth?: (principal: Principal | null, resource: ResourceAuthResource, action: ResourceAuthAction) => Promise<boolean> | boolean;\n /**\n * Agent approval registry (opt-in governance gate, default false — BACKWARD COMPAT: existing\n * deployments are byte-for-byte unchanged). When true, run/resume/stream ALSO require the target\n * agent to be `approved` in the journal-backed registry (@gnldev/durable's `isAgentServable`) — a\n * pending/changed/blocked agent gets 403 `{error, code: 'agent_not_approved'}`. Every `config.agents`\n * entry is recorded (idempotent, fingerprinted) once at construction so a platform-admin can review\n * it via `GET /agents/registry` and approve/block it (see the `/agents/registry*` endpoints below) —\n * those endpoints are ALWAYS available (regardless of this flag) so approval can be set up ahead of\n * turning the gate on.\n */\n requireAgentApproval?: boolean;\n /**\n * The startup protection matrix (default ON). Set false when something ELSE is already printing\n * one for this config.\n *\n * That is not hypothetical: `gnl dev` mounts this host and prints its own matrix, and its version\n * knows one thing this one cannot — that the dev server DERIVES a memory store the project's\n * `src/app.ts` will not have. Two blocks describing the same config, one of them less informed, is\n * how a reader learns to skip both. This flag exists so there is exactly one.\n *\n * It is an opt-OUT rather than an opt-in on purpose: the matrix is most needed by the deployment\n * that has not thought about any of these rows.\n */\n protectionsBanner?: boolean;\n}\n\n/**\n * Merge the server cap with the client request — the STRICTER one (smaller number) wins, the\n * client can NEVER loosen the server cap. If neither side gives a field, that field ends up absent (never\n * enforced) — the existing unlimited behavior is preserved.\n */\n/** Longest accepted `resourceId`. Generous for a user id / customer key, short of an accidental blob. */\nconst MAX_RESOURCE_ID = 200;\n\n/**\n * The one sentence a client credential gets when it names nobody — written once, sent from both the\n * read gate and the write gate.\n *\n * Two copies of this string used to sit twenty lines apart, and the sentence they held (\"resourceId is\n * required for a client credential: name the end user this request acts for\") was accurate and taught\n * nothing. Consider who reads it: somebody who swapped an operator token for an application token,\n * watched every request start answering 400, and has no reason to suspect the two credentials are\n * governed by DIFFERENT rules. That asymmetry is the whole answer, and the sentence did not contain it.\n *\n * NOTE carries the measured cost rather than a caution, because the cost is what makes this a refusal\n * instead of a default. It is recorded verbatim in resolveResourceId's own header: with one\n * application credential and no subject, the memory layer either wrote no thread record at all (bearer\n * → `principal.id` undefined → `listThreads` empty for everyone) or wrote ONE owner shared by every\n * end user — and in that state user B read user A's stored note.\n *\n * HELP names the REST exception on purpose. On the adapters, a body-supplied subject is the hole the\n * context seal exists to close; here it is the ONLY channel a client credential has, because a bearer\n * token carries no per-caller identity to derive one from. Someone who has read the adapter rule and\n * meets this error needs to be told why the same field is right in one place and forbidden in the\n * other, or the two rules read as a contradiction.\n */\nconst CLIENT_SUBJECT_REQUIRED = teachingError({\n error: 'resourceId is required: this request used an application credential and named no end user.',\n note:\n 'an application credential acts on behalf of YOUR users — that is what separates it from an\\n' +\n 'operator credential, which works across the whole organization and names nobody. With no\\n' +\n 'subject there is nothing to scope threads, recall and ownership to: measured, every end user\\n' +\n 'shared one memory bucket and read each other\\'s stored notes, or got no thread records at all.',\n help:\n 'Send the id your own app already has for the logged-in user: `?resourceId=<user>` on reads,\\n' +\n '`{ \"resourceId\": \"<user>\" }` in the body on writes.\\n' +\n 'Yes — the body, on THIS surface only. The chat/AG-UI adapters must never take a subject from\\n' +\n 'the body (a caller would be naming whoever they like); a bearer token has no per-caller\\n' +\n 'identity to derive one from, so naming it IS the credential\\'s job here.',\n});\n\n/**\n * WHOSE run this is — the subject the memory layer scopes on (`ThreadRecord.resourceId`, and working\n * memory's `res:<id>` key).\n *\n * Two deployment shapes need two different answers, and the precedence falls out of which one is in\n * use rather than being a policy choice:\n *\n * • The deployment binds an identity PER CALLER (basic auth, or @gnldev/auth-ee's per-user tokens).\n * Then `principal.id` IS the subject, and a body field must never override it — otherwise a user\n * names someone else and reads their memory.\n * • The deployment holds ONE application credential (the `client` class: a customer's backend\n * serving many end users). Then there is no per-caller identity — `principal.id` is undefined for\n * a bearer token — so the subject can only come from the request. The credential is trusted to\n * speak for its own users, which is the same trust that already lets it run agents at all.\n *\n * Measured before this existed: with a bearer token the server derived `resourceId` from `principal.id`\n * (undefined), the memory layer creates a thread record only when a resourceId is present, and so a\n * customer's backend produced ZERO thread records — `listThreads` had nothing to return for anyone.\n * Under basic auth it produced one shared owner (the application's own username), which put every end\n * user in ONE working-memory bucket: measured, user B read user A's stored note.\n *\n * An INVALID value is a 400, not a silent drop. A caller that sent a resourceId believes its data is\n * scoped; dropping it quietly would hand back exactly the shared-bucket behaviour above while the\n * caller thought it had asked for separation.\n */\nfunction resolveResourceId(\n principalId: string | undefined,\n raw: unknown,\n isClient = false,\n): { resourceId?: string } | { error: string } {\n if (principalId) return { resourceId: principalId };\n // An APPLICATION credential acts FOR an end user — that is what distinguishes it from an operator\n // credential, and it is the only reason it is trusted to assert a subject at all. So it must name\n // one. Silence used to mean \"unchecked\", which put an application's own users in the position the\n // shared bucket did: nothing separated them, and nothing said so.\n //\n // Deliberately keyed on the CLASS, not on the route. An operator (superAdmin/admin/viewer) works\n // across an organization's data by design and names nobody; the same rule applied to it would be\n // wrong, which is exactly the mistake the first version made by treating \"absent\" the same way for\n // everyone.\n if (raw === undefined || raw === null) {\n return isClient\n ? { error: CLIENT_SUBJECT_REQUIRED }\n : {};\n }\n if (typeof raw !== 'string') return { error: 'resourceId must be a string' };\n if (raw.length === 0) return { error: 'resourceId must not be empty' };\n if (raw.length > MAX_RESOURCE_ID) return { error: `resourceId must be at most ${MAX_RESOURCE_ID} characters` };\n // It becomes part of a storage key (`res:<id>`), and it is echoed back in listings. Control\n // characters serve no purpose in an identifier and are the part of the input space that surprises\n // key parsers and log readers; everything printable is left alone, because a customer's own user ids\n // are not ours to shape.\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(raw)) return { error: 'resourceId must not contain control characters' };\n return { resourceId: raw };\n}\n\nfunction clampLimits(server?: RunLimits, client?: RunLimits): RunLimits | undefined {\n if (!server && !client) return undefined;\n const stricter = (s?: number, c?: number): number | undefined =>\n s == null ? c : c == null ? s : Math.min(s, c);\n const out: RunLimits = {};\n const maxCostUsd = stricter(server?.maxCostUsd, client?.maxCostUsd);\n const maxTokens = stricter(server?.maxTokens, client?.maxTokens);\n const maxToolCalls = stricter(server?.maxToolCalls, client?.maxToolCalls);\n const maxRepeats = stricter(server?.loopDetection?.maxRepeats, client?.loopDetection?.maxRepeats);\n if (maxCostUsd != null) out.maxCostUsd = maxCostUsd;\n if (maxTokens != null) out.maxTokens = maxTokens;\n if (maxToolCalls != null) out.maxToolCalls = maxToolCalls;\n if (maxRepeats != null) out.loopDetection = { maxRepeats };\n return Object.keys(out).length ? out : undefined;\n}\n\n/** Leak-free metadata from agent records (the model object is hidden → only string id / 'custom'). */\nexport interface AgentMeta {\n name: string;\n model: string;\n system?: string;\n hasTools: boolean;\n maxSteps: number;\n /** Orgs this org-scoped agent belongs to (UI label); undefined for global agents. */\n orgs?: string[];\n}\n\n/** Agent metadata FILTERED by the caller's org (an invisible org-scoped agent doesn't appear in the list). */\nfunction listAgentMeta(config: CreateGnlConfig, callerOrgId?: string): AgentMeta[] {\n const sharedTools = config.tools ? Object.keys(config.tools).length : 0;\n return Object.entries(config.agents ?? {})\n .filter(([, a]) => agentVisibleToOrg(a, callerOrgId))\n .map(([name, a]) => ({\n name,\n model: typeof a.model === 'string' ? a.model : 'custom', // dynamic/chain/object → 'custom'\n system: typeof a.system === 'string' ? a.system : undefined, // dynamic system is never leaked\n hasTools: sharedTools + (a.tools && typeof a.tools === 'object' ? Object.keys(a.tools).length : 0) > 0,\n maxSteps: a.maxSteps ?? 12,\n ...(a.orgs?.length ? { orgs: a.orgs } : {}),\n }));\n}\n\n/**\n * Produces a Hono router from a createGnl configuration:\n * POST /agents/:name/run {runId, prompt|messages, threadId?, approvals?}\n * POST /agents/:name/resume {runId, approvals?} (input is read from the journal)\n * POST /agents/:name/stream SSE\n * GET /agents agent metadata\n * POST /workflows/:name/run {runId?, input, resume?} (suspend/resume/cancel safe)\n * GET /workflows workflow metadata (name + steps)\n * GET /workflows/runs P0.4: wfrun: registry query (?status=suspended|completed|canceled)\n * POST /workflows/runs/:id/cancel P0.4: durable cross-process workflow cancel\n * GET /runs/:id journal timeline\n * GET /runs run summaries\n * GET /usage scope's token/cost usage + effective budget limit\n * GET /openapi.json generated schema (agent + workflow)\n */\n/**\n * Decision #1: run-limit errors return 422 (Unprocessable Content) with a machine-readable body — the\n * request is valid but couldn't be processed under the given `limits` instruction. NOT 429 (SDKs\n * auto-retry 429, whereas the error is deterministic; Retry-After can't be computed), NOT 402 (402 is\n * specific to ORGANIZATION budget — remediation differs: raise budget ≠ raise limits + resume with the\n * SAME runId). If it doesn't match, returns undefined → the caller falls through to the generic 400 path.\n */\nfunction limitErrorResponse(c: Context, e: unknown): Response | undefined {\n if (e instanceof RunLimitExceededError || (e as any)?.name === 'RunLimitExceededError') {\n const err = e as RunLimitExceededError;\n return c.json({ error: err.message, code: EDGE_ERROR_CODES.runLimitExceeded, detail: err.detail, resumable: true }, 422);\n }\n if (e instanceof ToolLoopDetectedError || (e as any)?.name === 'ToolLoopDetectedError') {\n const err = e as ToolLoopDetectedError;\n return c.json({ error: err.message, code: EDGE_ERROR_CODES.toolLoopDetected, detail: err.detail, resumable: true }, 422);\n }\n return undefined;\n}\n\n/**\n * K1: makes SideEffectRetryBlockedError/RunBusyError/RetryLimitExceededError thrown by runDurable\n * (see errorFromBlocked, run.ts) consistent with the `BLOCKED_CODES` mapping on the SSE path (sse.ts).\n * The code comes from @gnldev/durable#blockedErrorCode (the ONE source of truth, based on err.name); the\n * HTTP status/`resumable` choice is IDENTICAL to the `onError` in examples/app/src/server.ts:\n * side_effect_retry_blocked/run_busy → 409 + resumable:true (resolved via approval/retry);\n * retry_limit_exceeded → 422, NO resumable (a permanent 'failed' is left in the journal, the same runId\n * won't resume). If it doesn't match, returns undefined → the caller falls through to the generic 400\n * path.\n */\n/**\n * The caller re-used a `runId` that belongs to a different conversation.\n *\n * 409 and NOT the generic 400: the request is well-formed and collides with something that already\n * exists, which is what Conflict means; 400 would tell the caller to fix the request when what needs\n * fixing is the id. `resumable` is ABSENT rather than false — the three blocked errors below carry\n * `resumable: true` because the same runId succeeds once the block clears, and this one never will for\n * this thread, so advertising it as retryable would put a client in a loop.\n *\n * Kept out of `blockedErrorCode`'s map for that same reason: those are runs blocked pending a\n * resolution, this is a caller mistake with no resolution path. Without this branch it fell through to\n * the generic 400, which serialises `message` ALONE — measured on both routes: no `code`, and the\n * `detail` naming the two threads was built and then dropped, leaving a consumer to parse the sentence.\n * That is the practice the typed error was added to end.\n */\nfunction threadMismatchResponse(c: Context, e: unknown, workKey?: string): Response | undefined {\n if (!(e instanceof RunThreadMismatchError) && (e as { name?: string })?.name !== 'RunThreadMismatchError') return undefined;\n const err = e as RunThreadMismatchError;\n return c.json({ error: err.message, code: 'run_thread_mismatch', detail: withWorkKey(err.detail, workKey) }, 409);\n}\n\n/**\n * The caller's own name for the work, put back into the refusal (§8, rules 1-3).\n *\n * FROM THE REQUEST, never from storage. The distinction is the tombstone rule (§10.3): a swept run\n * keeps only a HASH of its workKey, on purpose, so a refusal that read the name back out of the\n * journal would be resurrecting something a deletion was supposed to have removed. Reflecting what\n * the caller just sent gives up nothing — they already know it — and keeps \"deleted stays deleted\"\n * true while the error still speaks.\n *\n * `detail` and not `error`: the sentence is the single most casually logged field in any HTTP\n * client, and a workKey is a business name (\"the invoice being issued\", \"device 7742\"). Rule 1 keeps\n * it out of the prose; rule 2 puts it where a program looks.\n *\n * A non-object `detail` is replaced rather than merged — there is nothing to merge into, and losing\n * a bare string here has no consumer: every typed error in the family carries an object.\n */\nfunction withWorkKey(detail: unknown, workKey?: string): unknown {\n if (workKey === undefined) return detail;\n return detail && typeof detail === 'object' ? { ...(detail as Record<string, unknown>), workKey } : { workKey };\n}\n\n/**\n * FAZ-4 caller-conflict family — same 409-without-resumable contract as threadMismatchResponse\n * above (the id/content/actor is what needs fixing, not the request shape; none clears on retry).\n */\nfunction callerConflictResponse(c: Context, e: unknown, workKey?: string): Response | undefined {\n // K9: the code map is durable's CALLER_CONFLICT_CODES export — one source, three consumers\n // (server, chat-adapter, agui); a literal copy per consumer is exactly the drift that left one\n // route unmapped. threadMismatchResponse still answers first in every chain, so its entry here is\n // unreachable duplication, kept for consumers that skip the dedicated renderer.\n const code = callerConflictCode(e);\n if (!code) return undefined;\n const err = e as { message?: string; detail?: unknown };\n return c.json({ error: err.message, code, detail: withWorkKey(err.detail, workKey) }, 409);\n}\n\nfunction blockedErrorResponse(c: Context, e: unknown): Response | undefined {\n const code = blockedErrorCode(e);\n if (!code) return undefined;\n const err = e as { message?: string; detail?: unknown } | null | undefined;\n const body = { error: err?.message ?? String(e), code, detail: err?.detail };\n const res = code === 'retry_limit_exceeded' ? c.json(body, 422) : c.json({ ...body, resumable: true }, 409);\n // The docs promise Retry-After on run_busy (\"the same request is correct; it is only early\") —\n // same fixed delay chat-route stamps; the lock heartbeat makes any small number honest.\n if (code === 'run_busy') res.headers.set('Retry-After', '5');\n return res;\n}\n\n/**\n * A failure that came from the model provider, answered as one.\n *\n * Without this the provider's failure fell through to the generic 400 — measured, a free endpoint\n * answering 429 reached the caller as `400 \"Failed after 3 attempts. Last error: Too Many Requests\"`,\n * which tells a retrying client to stop retrying at the exact moment it should wait. The status\n * choices and their reasoning live in @gnldev/durable#upstreamFailure; this only renders them, plus\n * `Retry-After` when the upstream named a delay.\n */\nfunction upstreamErrorResponse(c: Context, e: unknown): Response | undefined {\n const up = upstreamFailure(e);\n if (!up) return undefined;\n const err = e as { message?: string } | null | undefined;\n const body = {\n error: err?.message ?? String(e),\n code: up.code,\n ...(up.upstreamStatus !== undefined ? { upstreamStatus: up.upstreamStatus } : {}),\n ...(up.retryAfter !== undefined ? { retryAfter: up.retryAfter } : {}),\n };\n const res = c.json(body, up.status);\n if (up.retryAfter !== undefined) res.headers.set('Retry-After', String(up.retryAfter));\n return res;\n}\n\nfunction restApiApp(config: CreateGnlConfig, opts: RestApiOptions = {}): Hono {\n // storage.runs (RunJournal) returns paginated listRuns → toJournal bridges it to the old array contract\n // (routes /runs, /usage, withOrg, and the budget gate all see the same shape).\n // `storage` is bridged by toJournal; `journal` is whatever the host passed — and the README's own\n // quickstart passes `new SqliteStorage(...).runs`, a RunJournal whose listRuns returns a Page. Every\n // reader-side consumer here (GET /runs, /usage, withOrg, the budget gate) expects the array contract,\n // so GET /runs?limit= died on `all.filter is not a function` and the bare GET /runs returned a page\n // Object where its documented contract promises an array. asReaderJournal presents one shape for both.\n const baseJournal = (config.storage ? toJournal(config.storage.runs) : asReaderJournal(config.journal as object)) as Journal & JournalReader;\n // A conversation store handed over as an OBJECT has no organization boundary, and this host had no\n // guard for it. Refused at setup rather than at the first leak.\n //\n // `orgInstance` below builds a per-organization registry with `{ ...config, journal: scoped }` — but\n // the spread carried `config.memory` through untouched, and `createGnl` resolves memory as\n // `config.memory ?? memoryFactory(...)` (registry.ts), so the object won and the factory was never\n // called. Every organization therefore shared ONE `Memory`: threads, messages, working memory and\n // observations are keyed by a caller-chosen `threadId` alone, so naming another organization's thread was\n // enough to read it. Studio refuses exactly this shape and says so at boot; this host served it.\n //\n // `memory: false` stays valid — that is the host saying \"no conversation store\", which needs no\n // boundary. A factory is fine: it is called per organization with that organization's journal.\n if (opts.org && config.memory) { // `false` is falsy here — an explicit \"no store\" needs no boundary\n throw new Error(\n 'createRestApi: `memory` was passed as an object while `org` is configured. That object owns its ' +\n 'own store and cannot be given an organization boundary, so every organization would share one ' +\n 'set of threads. Pass `memoryFactory` instead — it is called per organization with that ' +\n \"organization's journal — or set `memory: false`.\",\n );\n }\n const defaultInstance = { gnl: createGnl(config), journal: baseJournal, orgId: undefined as string | undefined };\n const names = Object.keys(config.agents ?? {});\n const workflowNames = Object.keys(config.workflows ?? {});\n const app = new Hono();\n\n /**\n * Agent approval registry: every `config.agents` entry is recorded into `baseJournal` ONCE at\n * construction (idempotent — recordAgent handles first-sight/drift/unchanged). `createRestApi` itself\n * stays SYNCHRONOUS (returns the Hono app directly, existing callers `const api = createRestApi(...)`\n * would break if this returned a Promise) — so boot recording is fire-and-forget from here, but the\n * promise is CACHED and every request path that depends on registry state (the approval gate below,\n * `GET /agents/registry`, approve/block) `await`s it first, so no request can race ahead of boot.\n * A failure (e.g. a non-writable journal) is warned, not thrown — the registry becomes best-effort\n * stale rather than breaking the server (mirrors the budget/warn patterns elsewhere in this file).\n */\n const agentRegistryBoot: Promise<void> = (async () => {\n for (const [agentName, cfg] of Object.entries(config.agents ?? {})) {\n await recordAgent(baseJournal, agentName, fingerprintAgent(agentName, cfg));\n }\n })().catch((e) => {\n console.warn('@gnldev/server: agent registry boot recording failed (approval state may be stale):', e);\n });\n // Opt-in auth gate: endpoints are open without a provider; in production this is only possible with\n // allowOpenAccess: true (otherwise makeGate throws at setup), outside production a single warning is issued on the first request.\n const authProvider = normalizeAuth(opts.auth);\n const { allow, allowP, deny } = makeGate(authProvider, { allowOpenAccess: opts.allowOpenAccess });\n\n // WHAT IS ACTUALLY PROTECTING THIS HOST, printed once at construction.\n //\n // The rows come from @gnldev/durable's describeProtections and are NOT re-derived here — deliberately. A\n // banner maintained next to the config rather than derived from it is how `gnl dev` came to print\n // \"(auth: protected)\" for a project whose only credential was one this framework had published.\n // One derivation, every surface.\n //\n // The identity row is the half durable cannot see, so this file fills it in, and it answers the\n // question this host actually implements (resolveResourceId, ~250 lines up): with an auth provider\n // the subject is the authenticated principal; without one there is no principal at all and the\n // subject can only come from the request body. That is a real difference in what an ownership gate\n // is worth, so it is stated rather than flattened into a ✓.\n if (opts.protectionsBanner !== false) console.log(\n formatProtections(\n describeProtections(config, {\n surface: 'createRestApi',\n identity: authProvider\n ? { bound: true, via: 'the authenticated principal', from: 'explicit' }\n : {\n bound: false,\n from: 'default',\n note: 'no auth in front: the subject comes from `body.resourceId`, so ownership gates are only as good as the caller',\n },\n }),\n { title: `gnl ${opts.title ?? 'api'} — protections` },\n ).join('\\n'),\n );\n\n // F1 — read the raw body and, when an a2aSecret is configured, verify the A2A HMAC signature over it\n // BEFORE parsing. Applied to EVERY agent-invoking endpoint (run/resume/stream + workflow run), not\n // just /run — otherwise the same agents were invocable UNSIGNED via /stream or /resume, bypassing the\n // replay/integrity gate by changing the endpoint. Returns the parsed body, or a deny Response.\n async function readSignedBody(c: Context): Promise<{ body: any } | { denied: Response }> {\n const rawBody = await c.req.text();\n if (opts.a2aSecret) {\n const sigDenied = verifyA2ASignature(c, rawBody, opts.a2aSecret);\n if (sigDenied) return { denied: sigDenied };\n }\n return { body: parseJsonBody(rawBody) };\n }\n // STRICT multi-org model = PAID gate: on ONLY when the auth provider (paid @gnldev/auth-ee, valid\n // license) reports the `multiOrganization` capability. When on, an unbound identity is NO LONGER a\n // super-admin by default — it must carry the EXPLICIT platform-admin grant (scope: 'platform'),\n // otherwise it is fail-closed. When OFF (free/host-org/no-auth) behavior is preserved EXACTLY: an\n // org-less identity is the legacy operator (sees the shared/root scope).\n const strictMultiOrg = authProvider?.capabilities?.().multiOrganization === true;\n /**\n * Whether this deployment has organizations at all — and therefore whether the fail-closed rules\n * below apply.\n *\n * It used to be `strictMultiOrg` alone, deliberately: the fail-closed net was described as a\n * paid-only behaviour change. Measured consequence, on the free tier with `org` configured: an\n * authenticated admin carrying NO org binding read BOTH organizations' runs (200), while the same\n * request under a provider declaring `multiOrganization: true` was refused (403). Declaring the\n * PAID capability was what made the deployment safe — so the sentence \"the tier that does not pay\n * is the less isolated one\" was literally true. Isolation must not depend on a paid feature flag.\n *\n * `capabilities()` cannot carry this either way: it is an object the CALLER supplies (auth/types.ts),\n * so it states an intent, never proves one. What does prove it is that the host configured `org` —\n * a deployment that routes by organization is one where an identity belonging to none is not the\n * accidental operator.\n *\n * Single-operator deployments are untouched: with no `org` option and no capability, this is false\n * and every path below behaves exactly as before.\n *\n * The `authProvider` term carries the no-auth case, and belongs HERE rather than at each call site.\n * An ABSENT provider is the deliberate no-auth mode: there is no identity to isolate ON, so every\n * caller is the operator. `scope()` below spelled that out inline, but the studio twin did not, and\n * the omission locked a no-auth `org: {}` deployment out of its own `/organizations` surface. One\n * derived expression is the fix that cannot be forgotten at the next call site. `strictMultiOrg`\n * already implies a provider (it reads one), so this only affects the `opts.org` branch.\n */\n const orgIsolationActive = !!authProvider && (strictMultiOrg || !!opts.org);\n // HARDENING: one-time warn when a multi-org deployment serves an org-less request in the shared scope (see scope()).\n let warnedSharedOrgFallback = false;\n // Org registration record prefix: ORG_RECORD_PRE, imported from @gnldev/durable. It was a local\n // literal here and another in @gnldev/studio, and `adoptIntoOrg` needs the same one — three copies\n // of a key that decides whether an organization resolves is three chances to change two of them.\n\n\n // Multi-organization: lazy registry per organization (same agent config, journal scoped to the\n // organization). Since the registry is per-org, model-fallback freezing and memory are also isolated\n // per organization.\n type Instance = typeof defaultInstance;\n const orgs = new Map<string, Instance>();\n // See OrgOptions.maxInstances. A `Map` iterates in insertion order, so re-inserting on every hit\n // makes the first key the least recently used one.\n //\n // REJECTED at construction rather than clamped. This started as `Math.max(1, …)`, and the clamp was\n // doing far more than reading like a tidy default: with a negative cap, `orgs.size > -5` is\n // permanently true while `orgs.delete(undefined)` never shrinks the map, so the eviction loop spins\n // forever and the request never returns. A silent clamp also hides the milder version of the same\n // typo — `maxInstances: 0` would quietly rebuild every organization's registry on every request. A\n // value that can only be a mistake should say so at boot, where it costs one line to see.\n const maxOrgInstances = opts.org?.maxInstances ?? 512;\n if (!Number.isInteger(maxOrgInstances) || maxOrgInstances < 1) {\n throw new Error(\n `createRestApi: \\`org.maxInstances\\` must be a positive integer (got ${String(opts.org?.maxInstances)}). ` +\n 'It is the ceiling on how many per-organization registries are cached in memory; omit it for the default of 512.',\n );\n }\n let warnedOrgEviction = false;\n function orgInstance(id: string): Instance {\n let inst = orgs.get(id);\n if (inst) orgs.delete(id); // re-inserted below, moving it to the most-recently-used end\n if (!inst) {\n // `memory` is dropped explicitly, not left to the spread. The guard at construction already\n // refuses an object here, so this only removes a value that cannot exist — but stating it means\n // the next field added to `CreateGnlConfig` cannot silently ride the spread into every\n // organization the way this one did. `memoryFactory` receives the scoped source, so each\n // organization gets its own store over its own keys.\n const { memory: _sharedMemory, ...perOrg } = config;\n if (config.storage) {\n // A `Storage` has SIX ports and this used to keep exactly one of them. The line was\n // `storage: undefined, journal: withOrg(baseJournal, id)`: the run journal was scoped and\n // `memory`, `vectors`, `work`, `cache` and `meta` were thrown away, so an organization's\n // registry fell back to whatever `createGnl` derived from the journal alone — and every\n // organization's threads, corpus, queue, cache and metadata lived in one shared set of keys.\n // The leaks found one at a time through studio (knowledge search, the jobs list, cache\n // invalidate) were this, seen through different routes.\n //\n // `withOrgStorage` scopes all six. No `journal` is passed alongside it on purpose: `createGnl`\n // resolves `config.storage ? config.storage.runs : config.journal`, so the storage's own\n // already-scoped `runs` is the journal — passing a separately-scoped one would be a second\n // wrapper around the same data and the two would disagree about which is authoritative.\n const scopedStorage = withOrgStorage(config.storage, id);\n const scoped = toJournal(scopedStorage.runs) as Journal & JournalReader;\n inst = { gnl: createGnl({ ...perOrg, storage: scopedStorage, journal: undefined }), journal: scoped, orgId: id };\n } else {\n // Journal-only deployment: there is no `Storage` to scope, so this stays exactly as it was.\n // The other five ports do not exist here — `createGnl` derives what it needs from the journal —\n // so there is nothing this path is missing.\n const scoped = withOrg(baseJournal, id) as Journal & JournalReader;\n inst = { gnl: createGnl({ ...perOrg, storage: undefined, journal: scoped }), journal: scoped, orgId: id };\n }\n }\n orgs.set(id, inst);\n while (orgs.size > maxOrgInstances) {\n const lru = orgs.keys().next().value as string;\n orgs.delete(lru);\n // Once, not per eviction: a deployment genuinely serving more orgs than the cap would otherwise\n // print a line per request, and the operator only needs to learn the ceiling exists.\n if (!warnedOrgEviction) {\n warnedOrgEviction = true;\n console.warn(\n `@gnldev/server: more than ${maxOrgInstances} organizations are active in this process — evicting the least recently used registry (starting with '${lru}'). ` +\n 'Evicted organizations are rebuilt on their next request and read the same journal keys. Raise `org.maxInstances` if this is your real organization count rather than header noise.',\n );\n }\n }\n return inst;\n }\n /**\n * Resolve the request scope. An organization bound to identity (Principal.orgId, verified during\n * allow()) OVERRIDES the header and enforces isolation even if the org option is NOT SET UP (the\n * Cred.orgId promise: \"organization isolation is enforced by identity\"). If the bound identity requests\n * a different organization, 403.\n */\n /**\n * Refuses when the caller STATED whose run it expects (`?resourceId=`) and the run says otherwise.\n *\n * The owner is read from the run's own frozen `:input` entry — the same place `threadId` and `agent`\n * live — so there is no second source to keep in sync and no extra table to migrate. Reading it\n * costs one point-read on a key the journal already holds.\n *\n * Silent on: no expectation stated, no owner recorded, or a journal that cannot answer. See the\n * route JSDoc for why neither absence is treated as a denial.\n */\n /** Whether THIS caller is an application credential (see @gnldev/auth CLIENT_ROLE). */\n const isClient = (c: Context): boolean => principalOf(c.req.raw)?.roles?.includes(CLIENT_ROLE) === true;\n\n /**\n * Refuses a client-credential request that names no end user.\n *\n * The single choke point for the rule, and a conformance test walks `routeTable` to prove every\n * route touching end-user data reaches it — the alternative is a rule that holds on the routes\n * someone remembered, which is how the first version of this shipped with the write paths open.\n *\n * Operators are untouched: `superAdmin`/`admin`/`viewer` work across an organization by design and\n * name nobody. That asymmetry IS the rule — it is about which credential is asking, not which route.\n */\n function clientSubjectDenied(c: Context, supplied?: unknown): Response | undefined {\n if (!isClient(c)) return undefined;\n const named = typeof supplied === 'string' ? supplied : c.req.query('resourceId');\n if (named) return undefined;\n // The SAME constant the read gate returns — not a second copy of the sentence. Two copies is\n // where this started, and a test now asserts the two paths answer byte for byte.\n return c.json({ error: CLIENT_SUBJECT_REQUIRED }, 400);\n }\n\n /**\n * Refuses when a request names a thread that belongs to a different end user.\n *\n * The READ side had this from the start; the WRITE side did not, and the gap was not theoretical.\n * Measured before this existed, with one `client` credential serving two end users: Mallory posted\n * `{ threadId: 'thread-alice', resourceId: 'mallory' }` to `POST /agents/:name/run` and the prompt\n * handed to the model was Alice's history verbatim — `[{user:'my PIN is 4417'}, {assistant:'ok'},\n * {user:'what did I say before?'}]`. The identical claim on `GET /threads/:id/messages` answered 403.\n * Worse than disclosure: the turn is APPENDED to that thread, so the next reader of Alice's own\n * conversation sees a stranger's message inside it.\n *\n * Why it was missed, written down because the shape recurs: the ownership rule was applied to the\n * routes that were open on the screen. Runs got it at the read path, then at cancel and resume; the\n * SUBJECT of a thread never got it anywhere but the read. The conformance walk that exists to stop\n * exactly this drove every route with a subject-less client and proved a subject is REQUIRED — it\n * never once paired a valid subject with a thread belonging to someone else, so 3645 tests passed\n * over the hole. A helper rather than a fourth copy: the copies are how the first three sites\n * drifted apart.\n *\n * SILENT when the store cannot answer (`getThreadResource` is optional on `Memory`) or when the\n * thread has no recorded owner — a first turn creates the thread, so refusing an unknown owner would\n * refuse every new conversation. Same permissiveness as the read route, same wording on refusal:\n * it reveals neither the real owner nor whether the thread exists.\n */\n async function threadOwnershipDenied(\n c: Context,\n s: Instance,\n threadId: unknown,\n subject: string | undefined,\n ): Promise<Response | undefined> {\n if (typeof threadId !== 'string' || !threadId || !subject) return undefined;\n const getOwner = s.gnl.memory?.getThreadResource;\n if (!getOwner) return undefined;\n let owner: string | undefined;\n try {\n owner = await getOwner.call(s.gnl.memory, threadId);\n } catch {\n return undefined; // a store that cannot answer is not evidence of a mismatch\n }\n if (!owner || owner === subject) return undefined;\n return c.json({ error: 'access denied: this thread belongs to a different resourceId' }, 403);\n }\n\n /**\n * The subject an authenticated identity is BOUND to, under `subjectBinding: 'strict'`.\n *\n * `undefined` means \"not bound\" and the caller's own claim is used, exactly as before: no principal\n * (open deployments), an operator, or a principal the provider gave no id — `roleAuth`'s bearer\n * tokens deliberately carry no `id` (role-auth.ts), so a token-only setup keeps today's behaviour\n * even with the flag on. Binding only bites where there IS a per-user identity to bind to.\n */\n function boundSubjectOf(c: Context): string | undefined {\n // Bayrak KONTROLÜ BURADA: üç okuma yolu da aynı kuralı tek yerden okusun. İlk yazışta kontrol\n // yalnız `ownershipDenied`'daydı ve thread yolları bayraksız da bağlanıyordu — yani varsayılanı\n // sessizce çevirmiş oluyordum. Testte yakalandı (varsayılan 403 döndü, 200 beklenirken).\n if (opts.subjectBinding !== 'strict') return undefined;\n const p = principalOf(c.req.raw);\n if (!p?.id || isClient(c) || isPlatformAdmin(p)) return undefined;\n return p.id;\n }\n\n async function ownershipDenied(c: Context, s: Instance, runId: string, fromBody?: unknown): Promise<Response | undefined> {\n // The query string is the uniform source, so a GET and a POST state the expectation the same way.\n // `fromBody` exists for the POST paths whose caller naturally puts it in the JSON it is already\n // sending; the query still wins, so one route cannot be checked against two different claims.\n // STRICT binding: an authenticated non-operator speaks for itself, and its own name OUTRANKS\n // anything the request states — otherwise the caller could simply name the victim and match.\n // Operators are exempt on purpose: `isPlatformAdmin` and the org-scoped roles work across an\n // organization and name nobody, which is the documented asymmetry this whole rule rests on.\n const expected = boundSubjectOf(c) ?? c.req.query('resourceId') ?? (typeof fromBody === 'string' ? fromBody : undefined);\n if (!expected) return undefined;\n let owner: string | undefined;\n try {\n owner = (await s.journal.get<{ resourceId?: string }>(`${runId}:input`))?.resourceId;\n } catch {\n return undefined; // a reader that cannot serve the entry is not evidence of a mismatch\n }\n if (!owner || owner === expected) return undefined;\n // The message names neither the real owner nor whether the run exists — a caller guessing ids\n // would otherwise learn both from the refusal.\n return c.json({ error: 'access denied: this run belongs to a different resourceId' }, 403);\n }\n\n /**\n * The question the ENGINE would have asked, asked here because on `/resume` the engine cannot.\n *\n * Everywhere else a re-drive of somebody else's raw runId meets `RunActorMismatchError`: the run's\n * `actor` is stamped at birth from the sealed identity, and the second caller arrives with their\n * own. Measured on `POST /agents/:name/run` with a run belonging to 'u-ayse' — a caller whose\n * credential carries the name 'mallory' gets 409 `run_actor_mismatch`, whether they declare nothing\n * or declare the victim's name to satisfy `ownershipDenied`. That lock is unconditional; it has no\n * `subjectBinding` flag in front of it.\n *\n * `/resume` was the hole, and for a structural reason rather than a missing line. A resume is\n * self-contained: it reads the subject back out of the FROZEN `:input` and seals THAT (see the\n * route), which is right — the second half of a conversation must not change owner. But the actor\n * stamp is printed from the same seal, so the engine ends up comparing the run's owner with the\n * run's own owner and can never disagree. Measured: the same 'mallory', the same runId, 409 on\n * `/run` and 200 + the victim's text on `/resume` — with `approvals` in the body, which is the\n * exact sentence the route's own comment forbids.\n *\n * So the comparison is made against the caller's OWN name and nothing they said: a claim in the\n * query or the body is the attacker's to write, and naming the victim is how the edge gate gets\n * satisfied. Deliberately NOT `boundSubjectOf` — that one is behind `subjectBinding: 'strict'`,\n * and the property being restored here is not the binding option, it is parity with a lock the\n * engine already applies unconditionally on every other route.\n *\n * SAME EXEMPTIONS AS THE ENGINE, on purpose, so the parity claim stays true in both directions: a\n * credential with no name of its own (the operator bearer, whose `id` is absent by design, and the\n * `client` application credential, which speaks for a user rather than as one) stamps no actor and\n * so is asked nothing; a run with no stamp — everything born before the stamp existed — is not\n * refused either, because `/run` does not refuse it. This gate never refuses what `/run` serves.\n *\n * ONE EXEMPTION THE ENGINE DOES NOT HAVE: platform-admin. The engine's actor lock would 409 an\n * admin re-driving someone's run on `/run`; this gate waves the same admin through on `/resume`,\n * deliberately — Studio's approve flow IS an operator resuming a stranger's run, and refusing it\n * here would break the inbox. So the parity claim is one-directional for admins: never stricter\n * than the engine, knowingly looser on this one credential.\n */\n async function actorParityDenied(c: Context, s: Instance, runId: unknown): Promise<Response | undefined> {\n if (typeof runId !== 'string' || !runId) return undefined;\n const p = principalOf(c.req.raw);\n if (!p?.id || isClient(c) || isPlatformAdmin(p)) return undefined;\n let stamped: string | undefined;\n try {\n stamped = (await s.journal.get<{ actor?: string }>(`${runId}:input`))?.actor;\n } catch {\n return undefined; // a reader that cannot serve the entry is not evidence of a mismatch\n }\n if (!stamped || stamped === p.id) return undefined;\n // Word for word what `ownershipDenied` answers on this same route: the refusal names neither the\n // real owner nor whether the run exists, and one route should not have two vocabularies for one\n // refusal. The engine's 409 carries both names and stays where it is — it is reached by callers\n // who are re-driving their OWN work, not by the caller this gate is for.\n return c.json({ error: 'access denied: this run belongs to a different resourceId' }, 403);\n }\n\n async function scope(c: Context): Promise<Instance | { error: string; status: 400 | 403 }> {\n const principal = principalOf(c.req.raw);\n const bound = principal?.orgId;\n // B2 — organization isolation must NOT depend on the paid license capability: when the host configured\n // per-request orgs (opts.org) with an auth provider that produces NO principal (e.g. legacy\n // {read,write} auth whose authenticate()=null), the raw `x-gnl-org` header would drive the scope\n // with ZERO identity binding — cross-organization read/write. There is no identity to isolate on, so this\n // combination is unsafe regardless of the license → fail closed. (An ABSENT auth provider is the\n // deliberate single-operator/no-auth mode and is unaffected.)\n if (orgIsolationActive && authProvider && !principal) {\n return { error: 'access denied: organization isolation is configured but this auth provider binds no identity to an organization (fail-closed)', status: 403 };\n }\n // STRICT (EE multi-org) FAIL-CLOSED: an authenticated identity with NO org binding AND NO explicit\n // platform-admin grant gets 403 — it is NOT the accidental super-admin. Kept license-gated on\n // purpose: the FREE tier's contract is that an unbound admin is the legacy cross-org OPERATOR\n // (see auth-org.test 'operator scenario'); a host wanting strict isolation binds every token's\n // Cred.orgId or runs the paid strict-multi-org model.\n if (orgIsolationActive && principal && !bound && !isPlatformAdmin(principal)) {\n return { error: 'access denied: no organization scope and no platform-admin grant (fail-closed)', status: 403 };\n }\n // If neither the org option nor an identity-bound organization exists → shared default (existing behavior).\n if (!opts.org && !bound) return defaultInstance;\n const resolve = opts.org?.resolve ?? ((req: Request) => req.headers.get('x-gnl-org') ?? undefined);\n const requested = await resolve(c.req.raw);\n if (bound && requested && requested !== bound) {\n return { error: `organization mismatch: identity is bound to organization '${bound}'`, status: 403 };\n }\n const id = bound ?? requested;\n if (!id) {\n if (opts.org?.required) return { error: 'organization required (x-gnl-org header)', status: 400 };\n // HARDENING (silent cross-organization mixing): multi-org IS configured (`opts.org` set — we passed the\n // single-org early-return above) yet this request carries NO org and NO org-bound identity, so\n // it lands in the SHARED (unprefixed) scope alongside every other org-less request. That is a\n // potential data-mixing footgun a misconfigured client (missing x-gnl-org header) hits SILENTLY.\n // Behavior is unchanged (still served in shared scope — an operator who set `required:false`\n // opted into this), but it is no longer silent: warn ONCE so the operator discovers they likely\n // want `org.required = true` for strict organization isolation.\n if (!warnedSharedOrgFallback) {\n warnedSharedOrgFallback = true;\n console.warn('@gnldev/server: multi-org is configured but a request resolved NO organization → served in the SHARED scope (its data mixes with other org-less requests). Set `org.required = true` to reject such requests instead (fail-closed). This warning fires once.');\n }\n return defaultInstance;\n }\n // HARDENING (opt-in): the resolved org must be EXPLICITLY REGISTERED. Without this, an org-bound\n // identity (or an x-gnl-org header) runs under `org:<id>:` whether or not that org was ever created\n // a deleted org's still-valid tokens keep working, and a typo'd header silently forks a new\n // namespace. The `__org__:<id>` record (studio POST /organizations) is the registration; a `null`\n // value is a deletion tombstone → also rejected. Root-level read (records live on baseJournal, not\n // org-prefixed). Default off → legacy implicit-org behavior unchanged.\n if (opts.org?.requireRegistration) {\n const reg = await baseJournal.get(ORG_RECORD_PRE + id);\n if (reg == null) return { error: `organization '${id}' is not registered`, status: 403 };\n }\n try {\n return orgInstance(id);\n } catch (e: any) {\n return { error: String(e?.message ?? e), status: 400 };\n }\n }\n\n /**\n * D4-FGA (EE-2): consults `opts.resourceAuth` (if configured) AFTER the caller's existing coarse gate\n * (allow/allowP) — a distinct, ADDITIVE narrowing layer, never a replacement for it. No-op (undefined)\n * when `resourceAuth` is unset → existing behavior is preserved exactly.\n */\n async function resourceGate(\n c: Context,\n principal: Principal | null,\n resource: ResourceAuthResource,\n action: ResourceAuthAction,\n ): Promise<Response | undefined> {\n if (!opts.resourceAuth) return undefined;\n const allowed = await opts.resourceAuth(principal, resource, action);\n return allowed ? undefined : c.json({ error: `resource access denied: ${resource.type}:${resource.id}`, code: EDGE_ERROR_CODES.resourceDenied }, 403);\n }\n\n /**\n * Org-scoped agent gate (run/resume/stream). An unknown agent AND an org-invisible agent return the\n * EXACT SAME 404 → a non-owning org cannot even learn the agent EXISTS (no existence leak). Runs\n * AFTER the write gate, BEFORE execute. Global agents (no `orgs`) and operators (orgId undefined /\n * auth off) always pass → full backward-compat.\n */\n function agentGate(c: Context, name: string, orgId: string | undefined): Response | undefined {\n const cfg = config.agents?.[name];\n if (!cfg || !agentVisibleToOrg(cfg, orgId)) return c.json({ error: `agent '${name}' not registered` }, 404);\n return undefined;\n }\n\n /**\n * WHICH ADDRESS a `workKey` is unique within, for this agent — read from the AGENT's declaration\n * and never from the request.\n *\n * Read off `config` rather than the per-org registry because they are the same declaration: an\n * org-scoped instance is built from this very config, so there is nothing per-instance to consult.\n * `agentGate` has already answered \"is there such an agent\" by the time this is called.\n *\n * The default matters more than it looks: `'resource'` is the noisy-and-cheap mistake (the work\n * runs twice), `'org'` is the quiet-and-dangerous one (two tenants share one run). §6 chooses which\n * way to be wrong.\n */\n function agentWorkScope(name: string): WorkScopeKind {\n return config.agents?.[name]?.workScope ?? 'resource';\n }\n\n /**\n * Agent approval gate (opt-in via `opts.requireAgentApproval`) — a SEPARATE async check called RIGHT\n * AFTER `agentGate` in run/resume/stream (visibility 404 stays first: an org that can't even see the\n * agent gets 404, not a 403 about its approval status). No-op when the flag is off → byte-for-byte\n * existing behavior. Awaits `agentRegistryBoot` first so a request can never race ahead of the\n * construction-time registry recording (see its JSDoc above).\n */\n async function agentApprovalGate(c: Context, name: string): Promise<Response | undefined> {\n if (!opts.requireAgentApproval) return undefined;\n await agentRegistryBoot;\n if (await isAgentServable(baseJournal, name)) return undefined;\n return c.json({ error: 'agent not approved to serve', code: EDGE_ERROR_CODES.agentNotApproved }, 403);\n }\n\n /**\n * PLATFORM-ADMIN gate for the agent registry endpoints below — mirrors @gnldev/studio's\n * `requirePlatformAdmin` (packages/studio/src/server.ts). Approval is a PLATFORM decision (should this\n * code-agent serve AT ALL), never per-org, so an org-bound identity is always denied; in the strict\n * multi-org model an unbound identity additionally needs the EXPLICIT platform-admin grant.\n */\n function requirePlatformAdmin(c: Context, orgBoundMsg: string): Response | undefined {\n const p = principalOf(c.req.raw);\n if (p?.orgId) return c.json({ error: orgBoundMsg }, 403);\n if (orgIsolationActive && !isPlatformAdmin(p)) {\n return c.json({ error: 'platform-admin required (fail-closed: no org scope and no platform-admin grant)' }, 403);\n }\n return undefined;\n }\n\n // Budget/quota WRITE PATH gate. Budgets are PER-ORG:\n // org ON + a request without an organization (root) → the root scope is NOT an organization, it\n // spans the total across all organizations; the per-org `default` limit does not apply to it\n // (otherwise it would produce a false 402).\n // org OFF → a single global scope can use the `default` limit (a legitimate global cap).\n // Effective limit: journal `__budget__:*` (managed from Studio) > opts.budgets fallback. Completed run\n // costs are memoized in costCache → a full deep journal read isn't repeated on every write.\n const usageCostCache: UsageCostCache = new Map();\n const budgetsConfigured = !!(opts.budgets?.default || opts.budgets?.perOrg);\n if (budgetsConfigured && !budgetsEnforceable(baseJournal)) {\n console.warn('@gnldev/server: budgets configured but journal does not support listRuns → quota CANNOT be enforced (fail-open).');\n }\n const effectiveFallback = (orgId?: string): BudgetLimit | undefined =>\n (orgId ? opts.budgets?.perOrg?.[orgId] : undefined) ?? opts.budgets?.default;\n async function budgetGate(c: Context, s: Instance): Promise<Response | undefined> {\n // If not an organization (org on + root scope), per-org budget doesn't apply.\n if (!s.orgId && opts.org) return undefined;\n const check = await checkBudget(baseJournal, s.orgId, effectiveFallback(s.orgId), usageCostCache);\n return check.exceeded\n ? c.json({ error: 'budget/quota exceeded — new run rejected', code: EDGE_ERROR_CODES.budgetExceeded, usage: check.usage, limit: check.limit }, 402)\n : undefined;\n }\n\n /**\n * \"Resume intent\" test (H2/1.3): if state ALREADY exists in the journal for the given runId (a\n * pending tool approval, a suspended/paused workflow, or the exactly-once repeat of a completed run),\n * this is NOT new work, it's a continuation of existing work — budgetGate is SKIPPED (otherwise\n * suspended work in an over-budget organization could NEVER be finished, an exactly-once violation).\n * For new-work requests (where the runId has no trace at all in the journal) the gate is ENFORCED\n * normally — no regression. `listKeys` is an optional Journal capability; without it, intent can't be\n * detected and it fails closed (the gate behaves normally; only this optimization is missed).\n */\n async function isResumeIntent(journal: Journal, runId: string): Promise<boolean> {\n if (typeof journal.listKeys !== 'function') return false;\n try {\n return (await journal.listKeys(`${runId}:`)).length > 0;\n } catch {\n return false;\n }\n }\n\n /**\n * P0.3 in-process registry of the AbortControllers backing CURRENTLY IN-FLIGHT\n * `/run` and `/stream` generations, keyed by an ORG-SCOPED key (NOT the raw runId — two different\n * organizations may legitimately use the SAME client-supplied runId for unrelated work; a flat\n * `runId → controllers` map would let org A's cancel abort org B's generation, a cross-organization\n * correctness/security bug). `POST /runs/:id/cancel` below aborts every controller registered under\n * an id. Deliberately per-INSTANCE (a plain Map, not journal-backed) — see the cancel handler's JSDoc\n * for the honest multi-worker limitation.\n */\n const inflight = new Map<string, Set<AbortController>>();\n const inflightKey = (s: Instance, runId: string): string => (s.orgId ? `org:${s.orgId}:${runId}` : runId);\n function registerInflight(key: string, ctrl: AbortController): void {\n let set = inflight.get(key);\n if (!set) { set = new Set(); inflight.set(key, set); }\n set.add(ctrl);\n }\n function unregisterInflight(key: string, ctrl: AbortController): void {\n const set = inflight.get(key);\n if (!set) return;\n set.delete(ctrl);\n if (set.size === 0) inflight.delete(key);\n }\n\n /**\n * Actor attribution — the SAME derivation `audit()` below uses, extracted so the agent-registry\n * approve/block endpoints can pass it as `approveAgent`/`blockAgent`'s `by` argument without\n * duplicating the logic. Priority: an authenticated principal.id > the `x-gnl-actor` header (the\n * PERSON behind a shared token) > `role:<role>` > 'anon'.\n */\n function actorOf(c: Context): string {\n const p = principalOf(c.req.raw);\n return p?.id ?? c.req.header('x-gnl-actor') ?? (p?.roles[0] ? `role:${p.roles[0]}` : 'anon');\n }\n\n /**\n * P0.3: minimal governance log for this package's own mutating endpoints — mirrors @gnldev/studio's\n * `audit()` helper (packages/studio/src/server.ts) but scoped down: @gnldev/server has no broader\n * governance surface (org/user CRUD, agent versioning, …) to log — `run.cancel`/`workflow.cancel` plus\n * the agent-registry `agent.approve`/`agent.block` actions. Writes to the SAME `__audit__` journal\n * namespace studio uses (via the shared `appendLog` primitive) so a consumer reading either surface's\n * journal sees one merged trail. Best-effort: a journal write failure never breaks the request that\n * triggered it.\n */\n async function audit(c: Context, orgId: string | undefined, action: 'run.cancel' | 'workflow.cancel' | 'agent.approve' | 'agent.block', target: string, detail?: unknown): Promise<void> {\n try {\n const actor = actorOf(c);\n const p = principalOf(c.req.raw);\n const org = p?.orgId ?? orgId;\n /**\n * `actingAs` — an UNBOUND identity operating inside an organization, which `org` cannot express.\n *\n * `org` answers \"which organization was this about\" and fills from the actor's own binding or\n * from the scope the request resolved. Both give the same value for a platform-admin working\n * inside someone else's organization, so the record cannot distinguish \"acme's admin cancelled\n * acme's run\" from \"the operator cancelled acme's run\" — and the second is the event a customer\n * would ask about.\n *\n * Set only when the actor has NO organization of their own and the request resolved into one.\n * A bound identity never has it: acting inside your own organization is not acting as anyone.\n *\n * It lives here rather than in @gnldev/studio because this is the only surface where it can\n * happen. Studio refuses an explicit org header on every non-GET (its v1 read-only rule), so on\n * a write its ALS only ever holds the caller's own binding — I put the field there first and\n * measured that it could never fill.\n *\n * `reason` is whatever the caller sent in `x-gnl-reason`. Optional on purpose: required would\n * break every existing operator script the day it shipped, and a trail nobody can write to is\n * worse than one with blanks.\n */\n const actingAs = !p?.orgId && orgId ? orgId : undefined;\n const reason = c.req.header('x-gnl-reason')?.slice(0, 300);\n // ALWAYS the ROOT journal (baseJournal), NEVER an org-scoped view — the `__audit__` contract\n // (see @gnldev/studio server.ts's /audit reader) is a SINGLE root-level trail with the organization\n // carried as a PAYLOAD FIELD for filtering. An org-prefixed write (`org:<id>:__audit__:…`) would\n // be invisible to studio's audit view (it deliberately reads the root journal for exactly this reason).\n await appendLog(baseJournal, '__audit__', {\n actor, action, target,\n ...(org ? { org } : {}),\n ...(actingAs ? { actingAs } : {}),\n ...(reason ? { reason } : {}),\n ...(detail !== undefined ? { detail } : {}),\n });\n } catch { /* audit is best-effort — swallow */ }\n }\n\n app.post('/agents/:name/run', async (c) => {\n // Running an agent is the `agents:run` permission (member + admin; viewer denied). In the free tier\n // this reduces to 'write' → identical to the previous allow(c,'write') (admin only) → no regression.\n if (!(await allowP(c.req.raw, 'agents:run'))) return deny(c.req.raw, 'write');\n const name = c.req.param('name');\n // Signature verification operates on the raw body bytes (the SAME string HMAC'd on the client side).\n const parsed = await readSignedBody(c);\n if ('denied' in parsed) return parsed.denied;\n const body = parsed.body as any;\n adoptIdempotencyKey(c, body);\n if (!body.runId && !body.workKey) return c.json({ error: NO_IDENTITY }, 400);\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n const gated = agentGate(c, name, s.orgId);\n if (gated) return gated;\n const approvalDenied = await agentApprovalGate(c, name);\n if (approvalDenied) return approvalDenied;\n // P1.7: computed once here (was previously re-derived below) — also needed by the D4-FGA resourceGate\n // check right below, which runs AFTER the coarse allowP('agents:run') gate above.\n const principal = principalOf(c.req.raw);\n const resourceDenied = await resourceGate(c, principal, { type: 'agent', id: name }, 'run');\n if (resourceDenied) return resourceDenied;\n // WHOSE run this is — see resolveResourceId. A per-caller identity wins; otherwise the request says.\n const subject = resolveResourceId(principal?.id, body.resourceId, isClient(c));\n if ('error' in subject) return c.json({ error: subject.error }, 400);\n // WHICH RUN — see identityOrError. From here on `runId` is the run's id (raw or derived) and\n // `declared` is the caller's name for the work: the door is handed the NAME, the gates below use\n // the ID, and a refusal reflects the name back.\n const identity = identityOrError(() => resolveWorkIdentity(`agent:${name}`, {\n ...(body.runId !== undefined ? { runId: body.runId } : {}),\n ...(body.workKey !== undefined ? { workKey: body.workKey } : {}),\n scopeKind: agentWorkScope(name),\n ...(subject.resourceId ? { resourceId: subject.resourceId } : {}),\n ...((s.orgId ?? principal?.orgId) ? { orgId: s.orgId ?? principal?.orgId } : {}),\n anonymous: 'refuse',\n surface: `POST /agents/${name}/run`,\n }));\n if ('error' in identity) return c.json({ error: identity.error }, 400);\n const runId = identity.runId!;\n const declared = identity.work?.workKey;\n { const denied = await threadOwnershipDenied(c, s, body.threadId, subject.resourceId); if (denied) return denied; }\n // KOŞUM SAHİPLİĞİ — `/resume`'un kapattığı deliğin aynısı buraya da geliyordu. Bu rotanın kendi\n // yorumu \"aynı runId + approvals = resume niyeti\" diyor (aşağıdaki bütçe kapısı da öyle\n // davranıyor), ama sahiplik yalnız THREAD üzerinden sorulup KOŞUM üzerinden hiç sorulmuyordu:\n // threadId gönderilmeyen bir istekte tek kapı da sessiz kalıyordu. Sömürü, sahipsiz doğan\n // koşumlara dayanıyordu — bu turda o üretim de kapandı (persistInput benimsenen sahibi yazıyor),\n // ama iki düzeltme birbirinin yerine geçmez: biri sahipsizliği azaltır, bu onu SORAR.\n // Türetilmiş id'de kapı yine sorar: `'org'` kapsamında iki özne TEK digest paylaşır, yani\n // sahipliği hash'in kendisi garanti etmez.\n { const denied = await ownershipDenied(c, s, runId, body.resourceId); if (denied) return denied; }\n // CONSISTENT with 1.3: continuing a suspended run from this endpoint with the SAME runId + approvals\n // (like stream does) is also resume intent → if there's a trace in the journal the budget gate is\n // skipped; new runIds are still ENFORCED (no regression).\n if (!(await isResumeIntent(s.journal, runId))) {\n const over = await budgetGate(c, s);\n if (over) return over;\n }\n // §8's replay signal, read BEFORE the run — see hadPriorInput.\n const prior = await hadPriorInput(s.journal, runId);\n // P0.3: register an org-scoped AbortController so POST /runs/:id/cancel can stop THIS generation.\n // Composed with the client's own disconnect signal (P0.2) via AbortSignal.any — whichever fires\n // first wins; either way the journal keeps whatever prefix already completed (resumable, same as P0.2).\n const ctrl = new AbortController();\n const key = inflightKey(s, runId);\n registerInflight(key, ctrl);\n try {\n // P1.7 seal the AUTHENTICATED identity into context — a body-supplied\n // `context.__gnl_orgId`/`__gnl_resourceId`/`__gnl_threadId` (spoof attempt) is stripped and\n // replaced by (or removed in favor of) the server-derived value. See sealRequestContext.\n const r = await s.gnl.run(name, {\n // The NAME when the caller declared one (so the door writes it into the run's record), the\n // raw id otherwise. Never both — the gate above already refused that.\n ...(declared !== undefined ? { workKey: declared } : { runId }),\n prompt: body.prompt,\n messages: body.messages,\n threadId: body.threadId,\n approvals: body.approvals,\n context: sealRequestContext(\n // Not merged here, because sealRequestContext writes `org` itself from the server-derived\n // value. This is a simplification, NOT a fix: measured over 21 body shapes × 4 server states\n // — including a prototype-polluted body, a getter for `org`, a null-prototype object and an\n // empty-string orgId — the merge and the seal never disagree, because the seal's first act is\n // an unconditional delete that dominates anything written here. The security property lives\n // entirely in sealRequestContext; the earlier version of this comment claimed otherwise.\n body.context ?? {},\n { orgId: s.orgId ?? principal?.orgId, resourceId: subject.resourceId },\n ),\n limits: clampLimits(opts.limits, body.limits),\n // P0.2 a client disconnect stops generation instead of billing tokens to\n // completion — an abort mid-run does NOT break resumable behavior, the journal keeps whatever\n // prefix already completed and a later call with the SAME runId resumes/replays as before.\n // P0.3: OR an explicit cancel via POST /runs/:id/cancel (ctrl.signal) — same non-destructive semantics.\n abortSignal: AbortSignal.any([c.req.raw.signal, ctrl.signal]),\n });\n // `finishReason` is here because without it an empty answer is unreadable. A run whose model\n // returned nothing answers 200 with `text: \"\"` — identical, on the wire, to a model that\n // legitimately chose to say nothing. Measured in the field: a provider returned an empty\n // response with `finishReason: 'unknown'`, the run was journaled as completed, and the caller\n // had no way to tell the two apart. The framework already knows which happened; it just was\n // not saying. Additive field, so existing clients are unaffected.\n // `replayedToolCalls` rides along for the same reason as finishReason: the engine knows this\n // answer came from the journal instead of executing (replay-disclosure envelope), and a UI that\n // wants to badge it should not have to infer it from prose. Additive; absent on fresh work.\n return stampRunHeaders(\n c.json({ ok: true, runId, text: r.text, interrupts: r.interrupts, finishReason: r.finishReason, ...((r as { replayedToolCalls?: unknown[] }).replayedToolCalls?.length ? { replayedToolCalls: (r as { replayedToolCalls?: unknown[] }).replayedToolCalls } : {}) }),\n runId,\n prior,\n );\n } catch (e: any) {\n // The correlation handle rides on refusals too: a caller who named work and got a 409 has no\n // other way to learn which run it collided with.\n return stampRunHeaders(\n limitErrorResponse(c, e) ?? threadMismatchResponse(c, e, declared) ?? callerConflictResponse(c, e, declared) ?? blockedErrorResponse(c, e) ?? upstreamErrorResponse(c, e) ?? c.json({ error: String(e?.message ?? e) }, 400),\n runId,\n );\n } finally {\n unregisterInflight(key, ctrl);\n }\n });\n\n app.post('/agents/:name/resume', async (c) => {\n if (!(await allowP(c.req.raw, 'agents:run'))) return deny(c.req.raw, 'write');\n const name = c.req.param('name');\n const parsed = await readSignedBody(c); // F1: A2A signature enforced here too\n if ('denied' in parsed) return parsed.denied;\n const body = parsed.body as any;\n if (!body.runId) return c.json({ error: 'runId required' }, 400);\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n const gated = agentGate(c, name, s.orgId);\n if (gated) return gated;\n const approvalDenied = await agentApprovalGate(c, name);\n if (approvalDenied) return approvalDenied;\n // Resume needs the same resource gate the other five endpoints have, and it needs it MORE than\n // they do: the body carries `approvals`, so a caller who is denied /run could otherwise resume a\n // run someone else started and approve the exact tool call the human gate had stopped. Denying\n // the cheap path while leaving the dangerous one open is the wrong way round.\n const resourceDenied = await resourceGate(c, principalOf(c.req.raw), { type: 'agent', id: name }, 'run');\n if (resourceDenied) return resourceDenied;\n // …and the FREE-tier half of the same concern. `resourceGate` is the paid FGA surface; a deployment\n // without it had nothing here at all, so one end user could resume another's run — and `approvals`\n // is exactly the field that decides a tool call a human gate had stopped. The caller states whose\n // run it believes this to be (`?resourceId=`, or `resourceId` in the body it is already sending)\n // and is refused when the run says otherwise. Unstated stays permitted: see ownershipDenied.\n { const denied = clientSubjectDenied(c, body.resourceId); if (denied) return denied; }\n { const denied = await ownershipDenied(c, s, body.runId, body.resourceId); if (denied) return denied; }\n // …and the half of the same rule that no declaration can satisfy. The gate above asks about the\n // subject the CALLER STATED; this one asks the question the engine asks on every other route and\n // cannot ask on this one, because the identity this route seals is the run's own. See\n // actorParityDenied — measured, `/run` answered 409 and `/resume` answered 200 to the same caller.\n { const denied = await actorParityDenied(c, s, body.runId); if (denied) return denied; }\n // CONSISTENT with H2/1.3: only a REAL resume (there's a trace in the journal) skips the budget\n // gate — otherwise this endpoint would be an unlimited backdoor (bypassing the quota with a\n // traceless/made-up runId). Without a trace (typo/abuse) it's ENFORCED normally; input also comes\n // back empty and the request fails harmlessly.\n if (!(await isResumeIntent(s.journal, body.runId))) {\n const over = await budgetGate(c, s);\n if (over) return over;\n }\n // Read the input from the journal → no need to re-supply the prompt (self-contained resume).\n const input = (await s.journal.get<any>(`${body.runId}:input`)) ?? {};\n try {\n const r = await s.gnl.run(name, {\n runId: body.runId,\n approvals: body.approvals,\n // Sealed like run and stream. This path built the context by hand and therefore carried\n // neither `__gnl_resourceId` nor `__gnl_threadId`, so a dynamic `system`/`model`/`tools`\n // function saw an identity on a fresh run and none on the resume of that same run — the two\n // halves of one conversation disagreeing about who the caller is.\n context: sealRequestContext({}, {\n orgId: s.orgId ?? principalOf(c.req.raw)?.orgId,\n // From the FROZEN `:input`, for the same reason the prompt and threadId below are: a resume\n // is self-contained and the client does not re-send it. Deriving it from the resuming\n // caller instead would let the second half of a conversation belong to someone else —\n // and on the shared-application-credential shape it resolved to undefined anyway.\n resourceId: input.resourceId ?? principalOf(c.req.raw)?.id,\n }),\n limits: clampLimits(opts.limits, body.limits),\n ...(input.messages ? { messages: input.messages } : { prompt: input.prompt }),\n // The threadId comes from `:input` for the same reason the prompt does: a resume is\n // self-contained and the client does not re-send it. Without it the registry's memory has no\n // thread to append to — runDurable's append is conditioned on `memory && threadId` — so the\n // assistant's reply to an approved call never entered the conversation. Measured: the user\n // asks for a charge, a human approves it, the charge goes through, and the thread still holds\n // only the user's message. The next turn's model sees no charge and no answer.\n ...(input.threadId ? { threadId: input.threadId } : {}),\n });\n // `finishReason` is here because without it an empty answer is unreadable. A run whose model\n // returned nothing answers 200 with `text: \"\"` — identical, on the wire, to a model that\n // legitimately chose to say nothing. Measured in the field: a provider returned an empty\n // response with `finishReason: 'unknown'`, the run was journaled as completed, and the caller\n // had no way to tell the two apart. The framework already knows which happened; it just was\n // not saying. Additive field, so existing clients are unaffected.\n // `replayedToolCalls` rides along for the same reason as finishReason: the engine knows this\n // answer came from the journal instead of executing (replay-disclosure envelope), and a UI that\n // wants to badge it should not have to infer it from prose. Additive; absent on fresh work.\n return c.json({ ok: true, runId: body.runId, text: r.text, interrupts: r.interrupts, finishReason: r.finishReason, ...((r as { replayedToolCalls?: unknown[] }).replayedToolCalls?.length ? { replayedToolCalls: (r as { replayedToolCalls?: unknown[] }).replayedToolCalls } : {}) });\n } catch (e: any) {\n return limitErrorResponse(c, e) ?? threadMismatchResponse(c, e) ?? callerConflictResponse(c, e) ?? blockedErrorResponse(c, e) ?? upstreamErrorResponse(c, e) ?? c.json({ error: String(e?.message ?? e) }, 400);\n }\n });\n\n /**\n * ── Liveness and readiness ──────────────────────────────────────────────────────────────────\n *\n * Deliberately UNAUTHENTICATED. Every orchestrator that would use these — Docker, Fly, Cloud Run,\n * Kubernetes, a load balancer — probes before it has, or ever will have, a credential. A health\n * check behind auth is a health check nothing can call.\n *\n * That makes what they SAY the design question. They report reachability and nothing else: no agent\n * names, no org information, no counts, no configuration. In particular `/ready` never returns the\n * underlying error text — a Postgres connection failure routinely carries the host, database and\n * user in its message, and this endpoint is world-readable. The operator gets the reason from the\n * logs; the probe gets a status code.\n *\n * TWO ROUTES, because they answer two different questions and conflating them causes the wrong\n * action:\n * /health — is this process alive? No I/O at all. A failing DEPENDENCY must not make an\n * Orchestrator kill and restart a perfectly healthy process; restarting it does not\n * Reconnect anyone's database.\n * /ready — can it serve? Touches the journal, so a process whose storage is unreachable is\n * Pulled OUT of the load balancer while staying alive to recover.\n * Point liveness probes at the first and readiness/traffic probes at the second.\n */\n app.get('/health', (c) => c.json({ status: 'ok', uptimeSec: Math.floor(process.uptime()) }));\n\n /**\n * `/ready` is unauthenticated, so anyone who can reach the port decides how often it touches the\n * database. The read itself is cheap (5000 sequential in-memory gets ≈ 66ms), so this is not about\n * CPU — it is about what a BURST costs against a real database: each request is a real query, and\n * when storage HANGS each one parks an uncancelled promise, and its connection, for the whole 2s\n * budget. Two bounds, both closed over THIS app instance:\n * - one probe in flight at a time — concurrent requests await the same promise, so a burst parks\n * One connection rather than one per request;\n * - a settled answer is reused for 1s. Readiness probes fire on second-scale periods (Kubernetes'\n * PeriodSeconds defaults to 10, Fly and Cloud Run sit in the same range), so a 1s window changes\n * No orchestrator's view of this process while collapsing any burst to ≤1 query per second.\n * Deliberately NOT module-level state: `createRestApi` can be called more than once in a process\n * (tests do, and so does anyone mounting two APIs over different storage), and two apps sharing one\n * cache would answer for each other's journal.\n * The 2s budget and the response contract are unchanged by any of this.\n */\n const readyBudgetMs = 2_000;\n const readyCacheMs = 1_000;\n // The warning is one line per FAILED probe, and a failing probe is exactly the moment an unauthenticated\n // caller can repeat cheaply — an outage plus a probe loop (or a hostile client) turns the operator's log\n // into noise that hides the first, useful line. 30s is the shortest interval that still keeps the failure\n // visible in a log tail while surviving an hour of outage in ~120 lines. The first failure after a quiet\n // period always warns again, so a recurrence is never silent.\n const readyWarnEveryMs = 30_000;\n let readyCache: { at: number; ok: boolean } | undefined;\n let readyInFlight: Promise<boolean> | undefined;\n let readyWarnedAt = 0;\n\n /** Resolves the readiness answer, from cache, from a probe already running, or from a new one. */\n const probeReady = (): Promise<boolean> => {\n // Date.now rather than a timer so the window is readable — and testable — without a clock of its own.\n if (readyCache && Date.now() - readyCache.at < readyCacheMs) return Promise.resolve(readyCache.ok);\n if (readyInFlight) return readyInFlight;\n const probe = (async () => {\n // A read is enough to prove the connection is usable, and cannot disturb any run's state. The\n // key is deliberately one that never exists.\n await baseJournal.get('__gnl_readiness_probe__');\n return true;\n })();\n let timer: ReturnType<typeof setTimeout> | undefined;\n // Bounded on purpose: an unreachable database usually HANGS rather than refusing, and a probe that\n // hangs is read as a timeout by some orchestrators and as success by others. Answer either way.\n const timeout = new Promise<false>((resolve) => { timer = setTimeout(() => resolve(false), readyBudgetMs); });\n // Assigned synchronously — anything that arrives before the race settles must find this promise.\n readyInFlight = Promise.race([probe.catch(() => false), timeout]).then((ok) => {\n if (timer) clearTimeout(timer);\n readyCache = { at: Date.now(), ok };\n readyInFlight = undefined;\n return ok;\n });\n return readyInFlight;\n };\n\n app.get('/ready', async (c) => {\n const ok = await probeReady();\n if (!ok) {\n // The reason stays in the logs; the response says only that storage is not reachable.\n const now = Date.now();\n if (now - readyWarnedAt >= readyWarnEveryMs) {\n readyWarnedAt = now;\n console.warn('@gnldev/server: readiness probe failed — the journal did not answer within ' + readyBudgetMs + 'ms (repeats suppressed for ' + readyWarnEveryMs / 1000 + 's)');\n }\n return c.json({ status: 'unavailable', storage: 'unreachable' }, 503);\n }\n return c.json({ status: 'ready' });\n });\n\n // Metadata list of registered agents (for the client/playground agent selector).\n // Org-scoped: an org-bound caller only sees GLOBAL agents + agents whose `orgs` include their org.\n app.get('/agents', async (c) => {\n if (!(await allowP(c.req.raw, 'catalog:read'))) return deny(c.req.raw, 'read');\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n return c.json(listAgentMeta(config, s.orgId));\n });\n\n // ── Agent approval registry (governance surface — see RestApiOptions.requireAgentApproval) ──────\n // Platform-level: \"should this code-agent serve AT ALL\" is never a per-org decision, so every endpoint\n // here is platform-admin gated (requirePlatformAdmin) REGARDLESS of whether requireAgentApproval is\n // turned on — an operator can review/approve agents ahead of flipping the enforcement flag.\n app.get('/agents/registry', async (c) => {\n if (!(await allowP(c.req.raw, 'catalog:read'))) return deny(c.req.raw, 'read');\n { const denied = requirePlatformAdmin(c, 'an org-bound identity cannot view the agent registry (operator required)'); if (denied) return denied; }\n await agentRegistryBoot;\n try {\n return c.json(await listAgentRegistry(baseJournal));\n } catch (e: any) {\n return c.json({ error: String(e?.message ?? e) }, 501);\n }\n });\n\n app.post('/agents/registry/:name/approve', async (c) => {\n if (!(await allowP(c.req.raw, 'agents:approve'))) return deny(c.req.raw, 'write');\n { const denied = requirePlatformAdmin(c, 'an org-bound identity cannot approve an agent (operator required)'); if (denied) return denied; }\n await agentRegistryBoot;\n const name = decodeURIComponent(c.req.param('name'));\n const body = (await c.req.json().catch(() => ({}))) as { note?: string };\n const rec = await approveAgent(baseJournal, name, actorOf(c), body.note);\n await audit(c, undefined, 'agent.approve', name, body.note !== undefined ? { note: body.note } : undefined);\n return c.json({ ok: true, record: rec });\n });\n\n app.post('/agents/registry/:name/block', async (c) => {\n if (!(await allowP(c.req.raw, 'agents:block'))) return deny(c.req.raw, 'write');\n { const denied = requirePlatformAdmin(c, 'an org-bound identity cannot block an agent (operator required)'); if (denied) return denied; }\n await agentRegistryBoot;\n const name = decodeURIComponent(c.req.param('name'));\n const body = (await c.req.json().catch(() => ({}))) as { note?: string };\n const rec = await blockAgent(baseJournal, name, actorOf(c), body.note);\n await audit(c, undefined, 'agent.block', name, body.note !== undefined ? { note: body.note } : undefined);\n return c.json({ ok: true, record: rec });\n });\n\n // Streaming run: text-delta/tool-call/... SSE events, finally interrupt + done (same durability).\n app.post('/agents/:name/stream', async (c) => {\n if (!(await allowP(c.req.raw, 'agents:run'))) return deny(c.req.raw, 'write');\n const name = c.req.param('name');\n const parsed = await readSignedBody(c); // F1: A2A signature enforced here too\n if ('denied' in parsed) return parsed.denied;\n const body = parsed.body as any;\n adoptIdempotencyKey(c, body);\n if (!body.runId && !body.workKey) return c.json({ error: NO_IDENTITY }, 400);\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n const gated = agentGate(c, name, s.orgId);\n if (gated) return gated;\n const approvalDenied = await agentApprovalGate(c, name);\n if (approvalDenied) return approvalDenied;\n // P1.7: computed once here (was previously re-derived below) — also needed by the D4-FGA resourceGate\n // check right below, which runs AFTER the coarse allowP('agents:run') gate above.\n const principal = principalOf(c.req.raw);\n const resourceDenied = await resourceGate(c, principal, { type: 'agent', id: name }, 'run');\n if (resourceDenied) return resourceDenied;\n // WHOSE run this is — see resolveResourceId. A per-caller identity wins; otherwise the request says.\n const subject = resolveResourceId(principal?.id, body.resourceId, isClient(c));\n if ('error' in subject) return c.json({ error: subject.error }, 400);\n // WHICH RUN — the same resolution `/agents/:name/run` makes, and deliberately not a variation of\n // it: a rule that held on one of these two doors is a rule missing from the other.\n const identity = identityOrError(() => resolveWorkIdentity(`agent:${name}`, {\n ...(body.runId !== undefined ? { runId: body.runId } : {}),\n ...(body.workKey !== undefined ? { workKey: body.workKey } : {}),\n scopeKind: agentWorkScope(name),\n ...(subject.resourceId ? { resourceId: subject.resourceId } : {}),\n ...((s.orgId ?? principal?.orgId) ? { orgId: s.orgId ?? principal?.orgId } : {}),\n anonymous: 'refuse',\n surface: `POST /agents/${name}/stream`,\n }));\n if ('error' in identity) return c.json({ error: identity.error }, 400);\n const runId = identity.runId!;\n const declared = identity.work?.workKey;\n { const denied = await threadOwnershipDenied(c, s, body.threadId, subject.resourceId); if (denied) return denied; }\n // KOŞUM SAHİPLİĞİ — `/resume`'un kapattığı deliğin aynısı buraya da geliyordu. Bu rotanın kendi\n // yorumu \"aynı runId + approvals = resume niyeti\" diyor (aşağıdaki bütçe kapısı da öyle\n // davranıyor), ama sahiplik yalnız THREAD üzerinden sorulup KOŞUM üzerinden hiç sorulmuyordu:\n // threadId gönderilmeyen bir istekte tek kapı da sessiz kalıyordu. Sömürü, sahipsiz doğan\n // koşumlara dayanıyordu — bu turda o üretim de kapandı (persistInput benimsenen sahibi yazıyor),\n // ama iki düzeltme birbirinin yerine geçmez: biri sahipsizliği azaltır, bu onu SORAR.\n { const denied = await ownershipDenied(c, s, runId, body.resourceId); if (denied) return denied; }\n // 1.3: resume intent via approvals+runId (a pending tool approval) → the budget gate is skipped\n // CONSISTENTLY with /agents/:name/resume (otherwise a pending interrupt in an over-budget\n // organization would never finish).\n if (!(await isResumeIntent(s.journal, runId))) {\n const over = await budgetGate(c, s);\n if (over) return over;\n }\n // P0.3: same registry as /agents/:name/run — composed with the client's disconnect signal (P0.2).\n const ctrl = new AbortController();\n const key = inflightKey(s, runId);\n registerInflight(key, ctrl);\n let result: any;\n try {\n // P1.7: same identity-sealing as /agents/:name/run above — see sealRequestContext.\n result = await s.gnl.stream(name, {\n // The name when one was declared, the raw id otherwise — see the same line in /run.\n ...(declared !== undefined ? { workKey: declared } : { runId }),\n prompt: body.prompt,\n messages: body.messages,\n threadId: body.threadId,\n approvals: body.approvals,\n context: sealRequestContext(\n // Not merged here, because sealRequestContext writes `org` itself from the server-derived\n // value. This is a simplification, NOT a fix: measured over 21 body shapes × 4 server states\n // — including a prototype-polluted body, a getter for `org`, a null-prototype object and an\n // empty-string orgId — the merge and the seal never disagree, because the seal's first act is\n // an unconditional delete that dominates anything written here. The security property lives\n // entirely in sealRequestContext; the earlier version of this comment claimed otherwise.\n body.context ?? {},\n { orgId: s.orgId ?? principal?.orgId, resourceId: subject.resourceId },\n ),\n limits: clampLimits(opts.limits, body.limits),\n // P0.2 same as /agents/:name/run above — stop generation (and its token\n // billing) on client disconnect. Deliberately compatible with W3 resumable SSE just below: an\n // abort only stops THIS response's fullStream early: the journal still has whatever prefix\n // completed before the abort, so a resumed/replayed call with the SAME runId (with or without\n // Last-Event-ID) sees the same journal state it would have without the abort.\n // P0.3: OR an explicit cancel via POST /runs/:id/cancel (ctrl.signal) — same non-destructive semantics.\n abortSignal: AbortSignal.any([c.req.raw.signal, ctrl.signal]),\n });\n } catch (e: any) {\n unregisterInflight(key, ctrl);\n return stampRunHeaders(\n limitErrorResponse(c, e) ?? threadMismatchResponse(c, e, declared) ?? callerConflictResponse(c, e, declared) ?? blockedErrorResponse(c, e) ?? upstreamErrorResponse(c, e) ?? c.json({ error: String(e?.message ?? e) }, 400),\n runId,\n );\n }\n // P0.3 cleanup: `s.gnl.stream(...)` above only resolves the STREAM RESULT object — the actual\n // fullStream consumption (and hence \"this generation is done\") happens INSIDE pipeAgentStream's\n // streamSSE callback below, which Hono drives independently of this handler's return (it doesn't\n // block on the SSE body finishing). Reaching INTO the streaming path to unregister exactly when the\n // response body closes would mean contorting sse.ts's generic event loop for one caller's\n // bookkeeping — not worth it. Instead: `result.finishReason` (a Vercel AI SDK StreamTextResult\n // promise — see sse.ts's own `await Promise.resolve(result.finishReason)`) settles exactly when\n // fullStream is fully drained (success OR error), which is a genuinely reachable, non-contorting\n // completion hook — use it. Swallowed on rejection (a stream error already produces its own `error`\n // SSE event in pipeAgentStream); this is ONLY registry bookkeeping.\n void Promise.resolve(result.finishReason).catch(() => {}).finally(() => unregisterInflight(key, ctrl));\n // Disconnect-recovery — if there's a Last-Event-ID header (sent automatically by\n // EventSource) or body.lastEventId, events the client has already seen are not rewritten (see the note in sse.ts).\n const lastEventIdRaw = c.req.header('Last-Event-ID') ?? body.lastEventId;\n const lastEventId = lastEventIdRaw != null && lastEventIdRaw !== '' ? Number(lastEventIdRaw) : undefined;\n // `__gnlPriorRun` is streamDurable's own answer to the replay question (run.ts), so the streamed\n // path uses it rather than the pre-read: same question, asked by the code that already knows.\n return stampRunHeaders(\n pipeAgentStream(c, runId, result, Number.isFinite(lastEventId as number) ? { lastEventId } : undefined),\n runId,\n (result as { __gnlPriorRun?: boolean })?.__gnlPriorRun === true,\n );\n });\n\n // Metadata list of registered workflows (name + steps + kind).\n app.get('/workflows', async (c) => ((await allowP(c.req.raw, 'catalog:read')) ? c.json(defaultInstance.gnl.listWorkflows()) : deny(c.req.raw, 'read')));\n\n // Run the workflow durably: {runId?, input}. If runId is given, it can be resumed with the same runId.\n app.post('/workflows/:name/run', async (c) => {\n if (!(await allowP(c.req.raw, 'workflow:run'))) return deny(c.req.raw, 'write');\n const name = c.req.param('name');\n if (!workflowNames.includes(name)) return c.json({ error: `workflow '${name}' not registered` }, 404);\n const parsed = await readSignedBody(c); // F1: A2A signature enforced here too\n if ('denied' in parsed) return parsed.denied;\n const body = parsed.body as any;\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n // D4-FGA: runs AFTER the coarse allow(c,'write') gate above.\n const principal = principalOf(c.req.raw);\n const resourceDenied = await resourceGate(c, principal, { type: 'workflow', id: name }, 'run');\n if (resourceDenied) return resourceDenied;\n // KİMLİK KAPILARI. Bu rota ajan rotalarındaki üç kapının HİÇBİRİNE uğramıyordu, ve eksiklik\n // görünmüyordu çünkü iş akışı koşumları sahipsiz doğuyordu: sorulacak bir sahip yoktu. Sahip\n // kaydı geldi (registry.ts runWorkflowInner) — kapılar da gelmeli, yoksa yazılan sahibi kimse\n // sormuyor demektir.\n //\n // (a) BAĞLI ÖZNE BEYANI EZER — ajan /run'daki `resolveResourceId(principal?.id, …)` kuralının\n // bu rotadaki karşılığı. Ezmeseydi mallory kurbanın adını gövdeye yazar, sahip kaydı kurbanı\n // gösterirdi: sahiplik kaydı bir korumadan bir kimliğe bürünme aracına dönerdi.\n //\n // `boundSubjectOf` kullanılıyor, `resolveResourceId` değil — ikisi aynı şey değil ve fark\n // BURADA önemli: `resolveResourceId` her `principal.id`'yi özne sayar, yani basic-auth ile\n // çalışan bir OPERATÖRÜN org düzeyi iş akışına birdenbire kendi adını sahip yazardı. Bu rotanın\n // belgeli muafiyeti (\"org düzeyi iş, öznesi yok\") tam olarak o durumu koruyor. `boundSubjectOf`\n // operatörü ve uygulama kimliğini muaf tutar, ve yalnız `subjectBinding: 'strict'` altında ısırır.\n const subject = boundSubjectOf(c) ?? (body.resourceId ? String(body.resourceId) : undefined);\n // WHICH RUN. The workflow door takes its scope PER CALL — unlike the agent doors, where it is the\n // agent's declaration — and this route passes the body's through, because a workflow has no\n // config site to declare it on and `workScope: 'org'` is the whole point of the jobs that arrive\n // here: a nightly reconciliation belongs to the installation, not to whoever's cron fired it.\n // The value is VALIDATED rather than coerced: an unrecognised string silently becoming\n // `'resource'` would be the quiet half of §6's asymmetry, and a typo is not a scope decision.\n if (body.workScope !== undefined && body.workScope !== 'resource' && body.workScope !== 'org') {\n return c.json({ error: \"workScope must be 'resource' or 'org'\" }, 400);\n }\n const identity = identityOrError(() => resolveWorkIdentity(`wf:${name}`, {\n ...(body.runId !== undefined ? { runId: String(body.runId) } : {}),\n ...(body.workKey !== undefined ? { workKey: body.workKey } : {}),\n scopeKind: (body.workScope as WorkScopeKind | undefined) ?? 'resource',\n ...(subject ? { resourceId: subject } : {}),\n ...((s.orgId ?? principal?.orgId) ? { orgId: s.orgId ?? principal?.orgId } : {}),\n // This door keeps its loud anonymous fallback — `runWorkflow` generates a name and says so.\n anonymous: 'allow',\n surface: `POST /workflows/${name}/run`,\n }));\n if ('error' in identity) return c.json({ error: identity.error }, 400);\n const runId = identity.runId;\n const declared = identity.work?.workKey;\n // (b) AYNI runId'yle YENİDEN GİRİŞ. Aşağıdaki H2 notu bu rotanın iş akışı için TEK resume\n // mekanizması olduğunu söylüyor: aynı runId = devam. Yani runId'yi bilen biri kurbanın koşumunu\n // sürdürüp dönen `steps[].output` içinde adım çıktılarını okuyabiliyordu — `/agents/:name/resume`\n // için kapatılan deliğin kelimesi kelimesine aynısı, komşu uçta. runId beyan edilmemişse\n // sorulacak bir koşum da yok (üretilen ad yepyeni).\n if (runId) {\n const denied = await ownershipDenied(c, s, runId, body.resourceId);\n if (denied) return denied;\n }\n // H2: this endpoint with the same runId is the ONLY resume mechanism for a workflow. If runId is\n // given AND there's already a trace in the journal (suspended/paused) this is a resume → the budget\n // gate is skipped (new work is still ENFORCED).\n if (!(runId && (await isResumeIntent(s.journal, runId)))) {\n const over = await budgetGate(c, s);\n if (over) return over;\n }\n // P0.4: register an org-scoped AbortController in the SAME `inflight` map used by agent runs, but\n // under a `wf:` sub-namespace — a client-supplied workflow runId and an agent runId could collide,\n // so keying them into the SAME bucket would let `/runs/:id/cancel` (agent-only) abort a workflow run\n // by accident. Only `POST /workflows/runs/:id/cancel` below targets this namespace; only registered\n // when body.runId is known (an auto-generated runId has no addressable key for a future cancel).\n const ctrl = new AbortController();\n const wfKey = runId ? 'wf:' + inflightKey(s, runId) : undefined;\n if (wfKey) registerInflight(wfKey, ctrl);\n try {\n const wfOpts = {\n // The name when the caller declared one, the raw id otherwise, nothing when neither — the\n // door's own anonymous fallback then mints (and announces) a name.\n ...(declared !== undefined\n ? { workKey: declared, ...(body.workScope ? { workScope: body.workScope as WorkScopeKind } : {}) }\n : runId ? { runId } : {}),\n // KİMLİK. İş akışı koşumları yapısal olarak sahipsiz doğuyordu ve bunun görünür sonucu şuydu:\n // `POST /workflows/runs/:id/cancel` sahiplik kapısını çağırıyor ama kapı sahibi hiç bulamıyor,\n // yani kontrol her zaman sessizce geçiyordu. Muafiyet (\"org düzeyi iş, öznesi yok\") ajan\n // İÇİNDEN doğan iş akışları için yanlış: o, belli bir kullanıcının koşumundan çıkıyor.\n // Beyan edilmezse hiçbir şey yazılmaz — muafiyet korunur, uydurulmuş sahip olmaz.\n ...(subject ? { resourceId: subject } : {}),\n ...(body.threadId ? { threadId: String(body.threadId) } : {}),\n // (c) MÜHÜR — ajan rotalarındaki desenin aynısı (`sealRequestContext`). Gövdenin kendi\n // `context`'i BİLEREK alınmıyor: bu rota bugün onu hiç okumuyor, dolayısıyla mühürlenecek bir\n // sızma yüzeyi de yok; `body.context`'i buraya bağlamak, kapatmak için var olan yüzeyi ÖNCE\n // açmak olurdu. Mühürlenen tek şey sunucunun kendi türettiği kimlik — /agents/:name/resume\n // ile birebir aynı biçim. Motorun içindeki `serverIdentityOf` mühürlü değeri gövdeden gelene\n // tercih ediyor, yani thread sahiplik kapısı ve sahip kaydı aynı çifti görüyor.\n context: sealRequestContext({}, {\n orgId: s.orgId ?? principal?.orgId,\n ...(subject ? { resourceId: subject } : {}),\n }),\n // P0.4 typed resume: `{ [waitId]: payload }` — journaled before any step runs (see waitForResume).\n ...(body.resume ? { resume: body.resume } : {}),\n // Composed with the client's disconnect signal — same non-destructive semantics as P0.2/P0.3 for\n // agent runs: an abort just stops new steps, the journal keeps whatever prefix already completed.\n signal: AbortSignal.any([c.req.raw.signal, ctrl.signal]),\n };\n const result = await s.gnl.runWorkflow(name, body.input, wfOpts);\n // The result already carries the id (the door generates one when nobody named anything), so\n // the header echoes THAT rather than the route's guess — the two agree, and only one of them\n // is authoritative.\n const res = c.json({ ok: true, ...result });\n const effective = (result as { runId?: string }).runId ?? runId;\n return effective ? stampRunHeaders(res, effective) : res;\n } catch (e: any) {\n const res = limitErrorResponse(c, e) ?? threadMismatchResponse(c, e, declared) ?? callerConflictResponse(c, e, declared) ?? blockedErrorResponse(c, e) ?? upstreamErrorResponse(c, e) ?? c.json({ error: String(e?.message ?? e) }, 400);\n return runId ? stampRunHeaders(res, runId) : res;\n } finally {\n if (wfKey) unregisterInflight(wfKey, ctrl);\n }\n });\n\n /**\n * P0.4 the suspended/completed/canceled workflow-run REGISTRY query — every run\n * in ONE `wfrun:` prefix scan (see @gnldev/workflow's listWorkflowRuns). Org-scoped via `scope(c)`/\n * `s.journal`: `wfrun:<runId>` keys are NOT runId-prefixed but `withOrg` still prefixes them\n * unconditionally (prefixes EVERY key), so organization isolation holds automatically — see the\n * `statusKey` JSDoc in workflow.ts. `listKeys` is an optional Journal capability; without it\n * `listWorkflowRuns` throws a clear error — surfaced as 501 (capability-missing, same pattern as\n * studio's own listKeys-gated routes) rather than a silent empty list.\n */\n app.get('/workflows/runs', async (c) => {\n if (!(await allowP(c.req.raw, 'runs:read'))) return deny(c.req.raw, 'read');\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n const statusRaw = c.req.query('status');\n let status: WorkflowRunStatus['status'] | undefined;\n if (statusRaw != null) {\n if (statusRaw !== 'suspended' && statusRaw !== 'completed' && statusRaw !== 'canceled') {\n return c.json({ error: `invalid status '${statusRaw}' (expected 'suspended', 'completed', or 'canceled')` }, 400);\n }\n status = statusRaw;\n }\n // WHOSE workflow runs — `/runs` next door does exactly this, and the two lists were reachable\n // with the SAME credential: the gate went onto the agent-run inventory and this one was left\n // showing every subject's row to anyone who could read. The exemption this route used to claim\n // (\"org-level bookkeeping, not per-end-user\") stopped being true the moment a workflow run\n // started carrying an owner.\n const resourceId = boundSubjectOf(c) ?? c.req.query('resourceId');\n // Before anything is read, for the reason the cancel route states: the requirement is about the\n // CREDENTIAL, not the target, so an application that has not said who it acts for must not learn\n // what exists.\n { const denied = clientSubjectDenied(c, resourceId); if (denied) return denied; }\n try {\n const runs = await listWorkflowRuns(s.journal, status ? { status } : {});\n if (!resourceId) return c.json(runs); // operatör: org boyunca çalışır, kimseyi adlandırmaz\n // The `wfrun:` record carries no subject — the owner lives in `<runId>:input`, which is where\n // the ownership gate, `listRunsPaged({resourceId})` and `purgeResource` all look. A point read\n // per row, only on the filtered path; the registry scan already reads one record per row.\n const mine: WorkflowRunStatus[] = [];\n for (const r of runs) {\n let owner: string | undefined;\n // An UNREADABLE owner excludes the row. Note this is the opposite call from `ownershipDenied`,\n // deliberately: there, silence is refusing to call an unanswered question a mismatch; here,\n // silence would be putting a row nobody can vouch for INTO someone's personal list. A hidden\n // row is a smaller wrong than a leaked one, and an ownerless run is filtered out for the same\n // reason `listRunsPaged({resourceId})` filters it out — a subject's list holds that subject's\n // work, not everything that failed to say otherwise.\n try { owner = (await s.journal.get<{ resourceId?: string }>(`${r.runId}:input`))?.resourceId; } catch { continue; }\n if (owner === resourceId) mine.push(r);\n }\n return c.json(mine);\n } catch (e: any) {\n return c.json({ error: String(e?.message ?? e) }, 501);\n }\n });\n\n /**\n * P0.4: durably cancels a workflow run — reaches it on OTHER workers at its next step boundary (the\n * `_canceled` flag is checked before EVERY step by runResumable), terminal (a canceled run refuses to\n * resume forever). Visibility: EITHER the `wfrun:` registry record exists OR the `_suspend` marker does\n * (a run mid-flight whose advisory registry write failed still leaves this trace) — neither existing\n * means the run doesn't exist IN THIS SCOPE (cross-org 404, same no-existence-leak pattern as\n * agentGate/`/runs/:id/cancel`). ALSO aborts any in-flight controller registered for this workflow run\n * (the `wf:`-namespaced bucket registered by POST /workflows/:name/run above) — best-effort, same\n * multi-worker honesty caveat as `/runs/:id/cancel`.\n */\n app.post('/workflows/runs/:id/cancel', async (c) => {\n if (!(await allowP(c.req.raw, 'run:cancel'))) return deny(c.req.raw, 'write');\n const runId = decodeURIComponent(c.req.param('id'));\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n // BEFORE the visibility 404: the requirement is about the CREDENTIAL, not about the target, so a\n // client that names nobody must not get as far as learning whether a run exists. Ordered the other\n // way it answered 404-vs-403 to a caller who had not identified who it was acting for, which is a\n // (small) existence oracle handed out for free.\n { const denied = clientSubjectDenied(c); if (denied) return denied; }\n const status = await getWorkflowRunStatus(s.journal, runId);\n const visible = status !== undefined || (await s.journal.get(`${runId}:wf:_suspend`)) !== undefined;\n if (!visible) return c.json({ error: `workflow run '${runId}' not found` }, 404);\n // Same expectation-check as the agent-run cancel next door — a workflow run carries an owner for\n // the same reason and stopping one is the same act.\n { const denied = await ownershipDenied(c, s, runId); if (denied) return denied; }\n // D4-FGA: runs AFTER the coarse allow(c,'write') gate above.\n const resourceDenied = await resourceGate(c, principalOf(c.req.raw), { type: 'workflow', id: runId }, 'cancel');\n if (resourceDenied) return resourceDenied;\n const cancelled = await cancelWorkflowRun(s.journal, runId, {});\n const wfKey = 'wf:' + inflightKey(s, runId);\n const set = inflight.get(wfKey);\n if (set) for (const ctrl of set) ctrl.abort();\n await audit(c, s.orgId, 'workflow.cancel', runId, { cancelled });\n return c.json(cancelled\n ? { ok: true, cancelled: true }\n : { ok: true, cancelled: false, note: 'run already completed' });\n });\n\n /**\n * P0.3 GET /runs — paginated + filtered when any query param is given;\n * EXACTLY the legacy array response with NO params (backward compat — existing clients/tests that\n * assert on `runs[0].runId` etc. see byte-identical behavior).\n * ?limit= clamped to [1, 1000] (default 50 — same default every adapter's own listRuns uses)\n * ?cursor= opaque — pass back a page's `nextCursor` verbatim\n * ?status= 'completed' | 'suspended' | 'failed' | 'running' | 'canceled' — else 400\n * ?agent= exact match against RunSummary.agent\n */\n app.get('/runs', async (c) => {\n if (!(await allowP(c.req.raw, 'runs:read'))) return deny(c.req.raw, 'read');\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n const limitRaw = c.req.query('limit');\n const cursor = c.req.query('cursor');\n const statusRaw = c.req.query('status');\n const agent = c.req.query('agent');\n // WHOSE runs. An application credential serving many end users lists one user's runs with this;\n // it is the read half of the `resourceId` the run was started with (see resolveResourceId).\n // STRICT: bağlı kimlik kendi listesine iner ve beyanı EZER. Bu satır olmadan /threads'ten\n // silinen envanter buradan aynen okunuyordu — üstelik `threadId` + `resourceId` alanlarıyla,\n // yani kapanan deliğin HEDEF LİSTESİNİ geri veriyordu. Aynı sınıf, komşu uç: kapıyı üç yere\n // koyup dördüncüsünü atlamak, kapıyı hiç koymamakla aynı kapıdan geçilmesini engellemiyor.\n const resourceId = boundSubjectOf(c) ?? c.req.query('resourceId');\n // Checked BEFORE the no-params shortcut below, which is the branch that would otherwise hand a\n // client the whole organization's run list — the exact read this rule exists to scope.\n { const denied = clientSubjectDenied(c, resourceId); if (denied) return denied; }\n if (limitRaw == null && cursor == null && statusRaw == null && agent == null && resourceId == null) {\n return c.json(await s.journal.listRuns()); // no params → legacy array (unchanged)\n }\n // A list rather than a chain of !==: this validation has lagged the vocabulary at every widening\n // ('failed', then 'running', now 'canceled'), and a chain invites the next one. The message is\n // built from the same list, so it can never advertise a smaller vocabulary than it accepts.\n const RUN_STATUSES = ['completed', 'suspended', 'failed', 'running', 'canceled'] as const;\n let status: (typeof RUN_STATUSES)[number] | undefined;\n if (statusRaw != null) {\n if (!(RUN_STATUSES as readonly string[]).includes(statusRaw)) {\n return c.json({ error: `invalid status '${statusRaw}' (expected one of ${RUN_STATUSES.join(', ')})` }, 400);\n }\n status = statusRaw as (typeof RUN_STATUSES)[number];\n }\n const limit = limitRaw != null ? Math.max(1, Math.min(1000, Math.trunc(Number(limitRaw)) || 50)) : undefined;\n const q = {\n ...(limit != null ? { limit } : {}),\n ...(cursor ? { cursor } : {}),\n ...(status ? { status } : {}),\n ...(agent ? { agent } : {}),\n ...(resourceId ? { resourceId } : {}),\n };\n const paged = (s.journal as Partial<JournalReader>).listRunsPaged;\n if (typeof paged === 'function') {\n return c.json(await paged.call(s.journal, q));\n }\n // P0.3 fallback: the scoped journal doesn't offer the paged capability (e.g. a bare custom\n // JournalReader) — apply the SAME filter+limit semantics over the legacy array instead of failing\n // the request. Honest cost: this materializes EVERY run before filtering/slicing (the array method\n // already does that internally); acceptable since it only triggers when the paged capability is\n // genuinely absent. `source` is intentionally NOT stamped on the response — the shape stays\n // identical to the paged branch above ({items, nextCursor}) so callers don't need to branch on it.\n const all = await s.journal.listRuns();\n const filtered = all.filter((r) => (status ? r.status === status : true) && (agent ? r.agent === agent : true)\n && (resourceId ? r.resourceId === resourceId : true));\n const start = cursor ? Number(cursor) || 0 : 0;\n const lim = limit ?? 50;\n const items = filtered.slice(start, start + lim);\n const next = start + lim;\n return c.json({ items, nextCursor: next < filtered.length ? String(next) : undefined });\n });\n\n /**\n * P0.3 cancel in-flight generation for a run on THIS server instance.\n * HONESTY (multi-worker): `inflight` is a plain in-process Map — this endpoint can only abort\n * controllers registered on the SAME process that received THIS request. Behind a load balancer with\n * multiple workers, a run's `/stream` may be in-flight on a DIFFERENT worker than the one that\n * receives the cancel → `cancelled: 0` even though the run is genuinely still running elsewhere.\n * Closing that gap needs a journal-level cancel FLAG that every worker polls during generation\n * (deliberately deferred — see P0.4/P2). The run itself is UNAFFECTED by this\n * limitation: it stays resumable either way (the journal prefix is intact — cancel never deletes\n * anything, it only stops NEW tokens/tool-calls from being produced on this instance).\n */\n app.post('/runs/:id/cancel', async (c) => {\n if (!(await allowP(c.req.raw, 'run:cancel'))) return deny(c.req.raw, 'write');\n const runId = decodeURIComponent(c.req.param('id'));\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n // Org-scope visibility: a run from another organization is invisible through THIS scope's prefixed\n // journal (withOrg strips/prefixes every key) — `:input` is written by every run() /stream() call\n // (persistInput, run.ts) so its absence means either the run never existed or it belongs to a\n // different organization; both cases return the SAME 404 (no existence leak, same pattern as agentGate).\n // BEFORE the visibility 404: the requirement is about the CREDENTIAL, not about the target, so a\n // client that names nobody must not get as far as learning whether a run exists. Ordered the other\n // way it answered 404-vs-403 to a caller who had not identified who it was acting for, which is a\n // (small) existence oracle handed out for free.\n { const denied = clientSubjectDenied(c); if (denied) return denied; }\n const visible = await s.journal.get(`${runId}:input`);\n if (visible === undefined) return c.json({ error: `run '${runId}' not found` }, 404);\n // Stopping someone else's work is a write, and an application credential serves many end users\n // under one token — so the SAME `?resourceId=` expectation the read path honours is honoured here.\n { const denied = await ownershipDenied(c, s, runId); if (denied) return denied; }\n // D4-FGA: runs AFTER the coarse allow(c,'write') gate above.\n const resourceDenied = await resourceGate(c, principalOf(c.req.raw), { type: 'run', id: runId }, 'cancel');\n if (resourceDenied) return resourceDenied;\n const key = inflightKey(s, runId);\n const set = inflight.get(key);\n const cancelled = set ? set.size : 0;\n if (set) for (const ctrl of set) ctrl.abort();\n // P2-cancel (wave 2, opt-in `?durable=true`): ALSO write the journal cancel flag — reaches runs\n // in-flight on OTHER workers (they stop at their next fresh model step) and makes the run refuse\n // every future resume (terminal, like a compensated run; recovery = forkRun). WITHOUT the flag the\n // default behavior is byte-identical to P0.3: in-process abort only, run stays resumable.\n const durable = c.req.query('durable') === 'true';\n if (durable) await cancelAgentRun(s.journal, runId, { reason: 'api-cancel' });\n await audit(c, s.orgId, 'run.cancel', runId, { cancelled, durable });\n return c.json(cancelled > 0\n ? { ok: true, cancelled, durable }\n : { ok: true, cancelled: 0, durable, note: durable ? 'no in-flight generation on this instance — durable flag written, other workers stop at their next step' : 'no in-flight generation on this instance' });\n });\n // Token-based usage report: total usage of the request scope (organization/shared) + effective limit.\n app.get('/usage', async (c) => {\n if (!(await allowP(c.req.raw, 'money:read'))) return deny(c.req.raw, 'read');\n // Spend is metered PER ORGANIZATION — there is no end-user dimension for a client credential to\n // name, so the rule that every client request names a subject cannot be satisfied here. That is\n // the answer, not an exception to work around: an application serving end users has no business\n // reading its customer's billing, and this route was the one place the client class could.\n if (isClient(c)) return c.json({ error: 'usage is organization-level: not available to a client credential' }, 403);\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n // In root scope (org on), the per-org limit doesn't apply → only usage is reported, limit is null.\n const rootUnderOrg = !s.orgId && !!opts.org;\n const check = rootUnderOrg\n ? { exceeded: false, usage: await getOrgUsage(baseJournal, s.orgId, usageCostCache), limit: undefined }\n : await checkBudget(baseJournal, s.orgId, effectiveFallback(s.orgId), usageCostCache);\n const usage = check.limit ? check.usage : await getOrgUsage(baseJournal, s.orgId, usageCostCache);\n return c.json({ org: s.orgId ?? null, usage, limit: check.limit ?? null, exceeded: check.exceeded });\n });\n /**\n * `?resourceId=` here is a CHECK, not a filter: \"I believe this run belongs to X — confirm it.\"\n *\n * It exists because the deployment shape this server is built for cannot answer that question on its\n * own. An application credential (the `client` class) serves many end users under ONE token, so the\n * caller's own identity says nothing about whose run this is; without an ownership check the\n * customer's backend has to keep a private runId→user table and trust itself to consult it on every\n * request. Passing the expectation and being refused is the cheaper, harder-to-forget shape.\n *\n * DELIBERATELY not fail-open on an absent expectation, and deliberately not fail-CLOSED on an absent\n * owner either: a run started before this field existed (or by a single-operator deployment that\n * never sets one) has no owner to compare against, and refusing those would break every existing\n * caller to protect data that has no subject. The rule is only: when BOTH sides are known and they\n * disagree, refuse. What that rules out is the mistake worth ruling out — a caller that DID state an\n * expectation being handed someone else's run anyway.\n */\n /**\n * Conversations, READ ONLY.\n *\n * The data was already here — every run with a `threadId` writes one — but only @gnldev/studio had\n * routes to it, so the API a customer's backend actually talks to could create a user's threads and\n * never list them. Serving a per-user conversation list meant either giving that backend a Studio\n * credential or keeping a parallel copy of the mapping.\n *\n * The write half (rename, delete, purge messages) deliberately stays in Studio: it is operator\n * surgery on stored history, not something an application does while serving a request.\n *\n * `?resourceId=` here is a FILTER, matching Studio's route of the same name — the underlying\n * `listThreads` has taken this argument since threads existed. Without it an org-scoped caller gets\n * its organization's threads, which is the same breadth `GET /runs` already answers with.\n */\n app.get('/threads', async (c) => {\n if (!(await allowP(c.req.raw, 'threads:read'))) return deny(c.req.raw, 'read');\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n const memory = s.gnl.memory;\n // An empty list, not a 404/501: \"this deployment keeps no conversations\" and \"this user has none\"\n // are the same answer to the caller, and the route existing is what lets a client stop branching.\n { const denied = clientSubjectDenied(c); if (denied) return denied; }\n // STRICT: bağlı kimlik KENDİ listesini görür. Bu satır olmadan parametresiz istek\n // `listAllThreads()`e düşüyor ve tek çağrıda TÜM öznelerin envanterini veriyor — ölçüldü.\n const resourceId = boundSubjectOf(c) ?? (c.req.query('resourceId') || undefined);\n // Two METHODS, not one with an optional argument — see Memory.listThreads. Passing a bare string\n // to the one-resource method is what silently unfiltered @gnldev/studio's own thread list.\n if (resourceId) {\n if (!memory?.listThreads) return c.json([]);\n return c.json(await memory.listThreads({ resourceId }));\n }\n if (!memory?.listAllThreads) return c.json([]);\n return c.json(await memory.listAllThreads());\n });\n /**\n * A thread's messages. `?resourceId=` is a CHECK here rather than a filter — the same shape\n * `GET /runs/:id` uses, and for the same reason: the caller names the thread, so the only useful\n * question left is whether it belongs to who the caller thinks it does.\n *\n * Enforced against the THREAD's own record rather than a run's, because a thread outlives the run\n * that created it and is the thing being asked for. Silent when the store cannot answer who owns a\n * thread — a Memory implementation is free to omit `getThreadResource`, and a missing capability is\n * not evidence of a mismatch.\n */\n app.get('/threads/:id/messages', async (c) => {\n if (!(await allowP(c.req.raw, 'threads:read'))) return deny(c.req.raw, 'read');\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n const memory = s.gnl.memory;\n if (!memory?.getMessages) return c.json([]);\n { const denied = clientSubjectDenied(c); if (denied) return denied; }\n const threadId = decodeURIComponent(c.req.param('id'));\n // STRICT: beklenti çağıranın BEYANI değil KİMLİĞİ. Beyan tek başına bir kontrol değildir —\n // saldırgan kurbanın adını yazınca eşleşme sağlanıyordu, yani kapı kendi anahtarını dağıtıyordu.\n const expected = boundSubjectOf(c) ?? c.req.query('resourceId');\n if (expected && memory.getThreadResource) {\n const owner = await memory.getThreadResource(threadId);\n // Names neither the real owner nor whether the thread exists — a caller guessing ids would\n // otherwise learn both from the refusal (same wording as the run-ownership check).\n if (owner && owner !== expected) {\n return c.json({ error: 'access denied: this thread belongs to a different resourceId' }, 403);\n }\n }\n return c.json(await memory.getMessages(threadId));\n });\n app.get('/runs/:id', async (c) => {\n if (!(await allowP(c.req.raw, 'runs:read'))) return deny(c.req.raw, 'read');\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n const runId = decodeURIComponent(c.req.param('id'));\n { const d = clientSubjectDenied(c); if (d) return d; }\n const denied = await ownershipDenied(c, s, runId);\n if (denied) return denied;\n return c.json(await s.journal.readRun(runId));\n });\n /**\n * Agent names FILTERED by the caller's org, exactly as `/agents` and `agentGate` filter them.\n *\n * `names` is every agent in the config, computed once at construction. Serving that verbatim handed\n * a caller from org B a complete list of org A's agent names, which is the one fact `agentGate` is\n * written to withhold — it answers the same 404 for \"no such agent\" and \"not yours\" precisely so a\n * non-owning org cannot learn an agent EXISTS. The schema route published the list next door.\n *\n * Built per request rather than once, because the answer depends on who is asking. Workflows have no\n * org dimension anywhere in the config, so `workflowNames` stays whole.\n */\n app.get('/openapi.json', async (c) => {\n if (!(await allowP(c.req.raw, 'catalog:read'))) return deny(c.req.raw, 'read');\n const s = await scope(c);\n if ('error' in s) return c.json({ error: s.error }, s.status);\n const visible = names.filter((n) => agentVisibleToOrg(config.agents?.[n] ?? {}, s.orgId));\n return c.json(buildOpenApi(visible, workflowNames, opts.title));\n });\n\n return app;\n}\n\nexport type { FetchHandler, RouteInfo } from './handler.js';\nexport { buildOpenApi } from './openapi.js';\n// The edge's own codes, exported for the same reason durable exports its two maps: a check can\n// enumerate them, and `@gnldev/agui` prints two of them from the same constant. See edge-errors.ts.\nexport { EDGE_ERROR_CODES, type EdgeErrorCode } from './edge-errors.js';\nexport { pipeAgentStream, interruptsFromSteps, sseResponse } from './sse.js';\n\n/**\n * The REST API as a fetch handler.\n *\n * Hono host: app.mount('/api', createRestApi(config))\n * Anything else: bridge it (see @gnldev/studio/node for the same job on the Studio side)\n * Standalone: serve({ fetch: createRestApi(config).fetch })\n *\n * The `run?: never; agent?: never` is a guard, not decoration. Every field of `CreateGnlConfig` is\n * optional, so ANY object satisfies it — including the REGISTRY that `createGnl(config)` returns,\n * which is the one thing callers reach for by mistake (`createRestApi(gnl)` instead of\n * `createRestApi(config)`). It typechecked, started, and then answered every request from an empty\n * config: no agents, no journal, and nothing anywhere saying so. `run` and `agent` exist on the\n * registry and on no config, so naming them `never` rejects exactly that object and costs a real\n * config nothing. Documented because it was shipped wrong in the guide first, and because a\n * signature that looks decorative is the kind that gets \"simplified\" away.\n */\nexport function createRestApi(\n config: CreateGnlConfig & { run?: never; agent?: never },\n opts: RestApiOptions = {},\n): FetchHandler {\n return toFetchHandler(restApiApp(config, opts));\n}\n"]}
package/dist/node.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { FetchHandler } from './handler.js';
3
+ /**
4
+ * Turns a fetch handler into a Node request listener.
5
+ *
6
+ * @experimental Closes the SSE/flush class of bug inside the Node bridge — a hand-written bridge
7
+ * that omits `res.flushHeaders()` withholds the head until the first chunk, so a quiet event stream
8
+ * hangs the client forever and nothing throws. It also answers plainly when a body parser upstream
9
+ * has already drained the request, instead of letting the endpoint blame the caller.
10
+ *
11
+ * What it does NOT do: audit the rest of your middleware chain, or touch path prefixes — a host that
12
+ * mounts under a sub-path has already stripped it from `req.url` (Express) or has not (Koa, Fastify,
13
+ * node:http), and only the host knows which.
14
+ *
15
+ * ```ts
16
+ * const api = createRestApi(config);
17
+ *
18
+ * express().use('/api', toNodeHandler(api)); // Express — before express.json()
19
+ * await fastify.register(middie); fastify.use('/api', toNodeHandler(api)); // Fastify
20
+ * koa.use(c2k((rq, rs, _next) => toNodeHandler(api)(rq, rs))); // Koa — three params, see below
21
+ * createServer(toNodeHandler(api)); // node:http
22
+ * ```
23
+ *
24
+ * On Koa, the middleware must declare THREE parameters even though it never calls the third:
25
+ * `koa-connect` switches on `fn.length` and, below three, assumes the middleware does not terminate
26
+ * the response — it calls `next()` immediately and Koa writes its own 404 over what was already
27
+ * sent. Measured: `ERR_HTTP_HEADERS_SENT` and a 404 on every route, from a two-parameter version of
28
+ * the same working code.
29
+ *
30
+ * Bind at the MIDDLEWARE layer, never as a route, and put it ahead of the body parser. Measured:
31
+ * `fastify.all('/api/*', …)` runs AFTER Fastify's built-in JSON parser has drained the stream —
32
+ * every GET passes, a POST with a body answers 400. Through `@fastify/middie` the same handler runs
33
+ * before parsing and works, with the host's own routes keeping their parsed bodies.
34
+ */
35
+ export declare function toNodeHandler(handler: FetchHandler): (req: IncomingMessage, res: ServerResponse) => Promise<void> | undefined;