Job tokens and policies
A job token is the only credential a runtime ever presents to the gateway. It is minted by the gateway (never by the caller), lives only in gateway memory as a sha256 hash, is bound to one ledger row, one client and one compiled set of grants, and dies on revoke, on TTL expiry or when its ledger row settles. A policy is a JSON or YAML file that says which models, tools, limits, identity mode and egress hosts a job may have; the gateway merges a chain of policies into compiled grants at registration.
Token format
| Property | Value | Source |
|---|---|---|
| Format | afj_ + 43 base64url chars (afj_ + randomBytes(32).toString('base64url')) | registrations.ts registerJob |
| Regex | ^afj_[A-Za-z0-9_-]{43}$ (JOB_TOKEN, also JobToken in agent-types and RunnerEnv in the runner) | registrations.ts, packages/agent-types/src/gateway-control.ts |
| Storage | sha256(token) hex as the key of an in-memory Map; nothing persisted or logged | registrations.ts header comment |
| Presentation | x-api-key header, or authorization with the bearer scheme (never both) | proxy.ts authenticate |
| Lifetime | ttlMs from the registration, 1 to 900 000 ms (MAX_TTL_MS); capped by a bound subject's TTL | control.ts, registrations.ts |
| Redaction | every logged string is scrubbed with the pattern afj_[A-Za-z0-9_-]{43} | packages/agent-core/src/redaction.ts |
Lifecycle
Dropping a job (#dropJob) aborts every in-flight call tracked for that token hash (audit reason revoked on the model
path), removes the job and its request-id index, and revokes the subject-token cache entry, which zeroes the stored
subject token and every exchanged token.
Per-turn issuance
Tokens are issued per turn (session) or per step attempt (factory), never per session or per job.
| Caller | Control token | requestId shape | jobId | policyIds | TTL | Code |
|---|---|---|---|---|---|---|
Core worker, session turn (prepareTurn) | worker | session-<sessionId>/<messageId>#<attempt> | none | { role: 'session-readonly' } | timeoutMs default (120 000) + GATEWAY_TTL_MARGIN_MS (60 000) | apps/worker/src/activities.ts |
| Claude runtime in gateway mode (sync api run, in-process session turn) | api or worker | api: api/<uuid> | none | { role: 'session-readonly' } | timeoutMs + ttlMarginMs, refused above 900 s | packages/agent-runtime-claude/src/runtime.ts |
SandboxRuntime (factory step) | worker | the step's request id | required | policyIdsByProfile[profile], default { role: 'factory-<role>' } | timeoutMs + ttlMarginMs (default 60 000), refused above 900 s | apps/worker/src/sandbox/sandbox-runtime.ts |
Failure handling:
- Registration failure (any non-201, 5 s timeout in
httpControl.register): the core worker settles the row at 0 and throws a retryablegateway_unavailable; the runtime yieldsinternal_errorwith that text, cost 0. - Revoke is best effort with
REVOKE_TIMEOUT_MS = 1000. A failed revoke leaves two backstops: the TTL (at most 15 minutes) and the settled ledger row (the next call gets 401registration_stale). prepareTurnrevokes the registrations of every earlier attempt (<prefix>1to<prefix>attempts-1), because an earlier exec worker may still be running on a lost host.SandboxRuntimerevokes as soon as aresultline is claimed, before waiting for the container to exit.
Registration (POST /control/v1/jobs)
Request body (JobBody, strict): jobId (optional, JobId), requestId (1 to 256 chars), client (1 to 64),
policyIds (app, role, task, each optional, ^[^\s*]{1,128}$), ttlMs (integer 1 to 900 000).
API-token restrictions (FL-2): the api control token may only register session-readonly jobs for request ids matching
API_REQUEST_ID = ^api\/<uuid v4 shape>$, never a row that carries a jobId, and may revoke only registrations it
created (another's looks absent, 404). The worker token may register any row and revoke any registration, so it can
always clear a squatted one.
Subjects and identity binding
POST /control/v1/subjects (api token only) stores a user's IdP token for one turn: body turnKey
(^[^#\s]{1,256}$), subjectId, subjectToken (up to 16 384 chars), ttlMs. An unbound subject expires after
SUBJECT_BIND_WINDOW_MS = 60000 (or its TTL if shorter). A job registered with requestId whose turn key
(requestId up to #) matches a live subject is bound to it: the job's TTL becomes min(ttlMs, subject remaining),
one copy of the subject token goes into SubjectTokenCache keyed by the job token hash, and the job's audit identity
is obo. Without a subject the identity is none (or service when the grants say so). OBO exchange is used only on
the MCP path; see MCP registry.
Response
{ jobToken, hookTools, expiresAt }. hookTools lists the mcp__agentforge__<name> hook names for granted tools that
actually made it into the job's catalog; expiresAt is epoch ms. The runtime receives RuntimeGrants
(hookTools matching ^mcp__agentforge__[a-z][a-z0-9_]*$, and optionally mcp.url plus mcp.jobToken); the MCP URL
must be https, or http on loopback, with path /mcp and no credentials, query or hash (L6).
Policy files
loadPolicies(dir) in packages/agent-governance/src/loader.ts:
- Reads every
*.yaml,*.ymland*.jsonfile directly in the directory (non-recursive, sorted). - Each file at most
MAX_POLICY_FILE_BYTES= 262 144 bytes (256 KiB). - YAML with the core schema only: no custom tags, no
<<merge keys, unique keys,maxAliasCount: 0(no alias bombs). - Duplicate
level/idpairs, zero org policies or more than one org policy refuse startup.
Schema (Policy, strict)
| Field | Type | Notes |
|---|---|---|
level | org, app, role, task | |
id | exact name, max 128 | no wildcards or whitespace |
models.allow | exact names | required at org level |
maxTokens | positive integer | |
limits | maxTurns, timeoutMs, maxBudgetUsd | GrantLimits |
tools.allow, tools.deny | tool names like knowledge.search (^[a-z][a-z0-9]*(\.[a-z][a-z0-9_]*)+$) | tools.allow required at org level |
requireApproval | tool names | |
identity.mode | obo or service | service not allowed at org level |
identity.allowServiceOverride | boolean | org level only |
egress.allow | exact hostnames |
Merge rules (merge in compile.ts)
| Field | Rule |
|---|---|
| Chain order | starts with the org policy; levels strictly ordered org, app, role, task, each at most once; else invalid_chain |
models, tools, egress allow lists | start from the org list (absent = []); each lower level intersects; an absent lower list inherits, a present one (even []) narrows |
tools.deny | union over all levels; any deny removes the tool whatever is allowed |
requireApproval | union over all levels |
maxTokens, each limits key | minimum over levels; absent means unlimited |
identityMode | obo unless a level below org sets service, the org sets allowServiceOverride: true, and no level sets obo; service without the org override throws identity_override_denied |
compile then derives hookTools: mcp__agentforge__ + the tool name with . replaced by _. Two tools mapping to
the same hook name throw hook_name_collision. The result is validated as CompiledGrants: models, maxTokens?,
tools, hookTools, limits, requireApproval, identityMode, egressAllow.
At registration the gateway also removes every requireApproval tool from the catalog input (approval is not
implemented, M4), then compiles the catalog against the registry for the named role.
Error codes
PolicyErrorCode | Raised by | When |
|---|---|---|
read_failed | loader | directory or file unreadable |
too_large | loader | file over 256 KiB |
parse_failed | loader | JSON or YAML error, YAML warning |
invalid_policy | loader | schema violation |
duplicate_policy | loader | same level/id twice |
missing_org | loader, control | no org policy |
multiple_org | loader | more than one org policy |
invalid_chain | merge, control | wrong order or unknown policy id at registration |
identity_override_denied | merge | service mode without org override |
hook_name_collision | compile | two tools map to one hook name |
At startup any of these stops the gateway. At registration an unknown policy id, a PolicyError or a RegistryError
is a 400 "policy compile failed" with an error log carrying the code and no audit row (operator bug, plan 6.4).
Baked default policies
The gateway image copies apps/gateway/policies/*.json to /policies (root-owned, mode 0444), so it starts with no
mount (ADR 0003 of the 2026-11-13 session: swarm secrets cannot deliver a policy directory).
| File | Content |
|---|---|
org.json | level: org, id: agentforge-default, models.allow: [claude-haiku-5-5, claude-sonnet-5-5], tools.allow: [], egress.allow: [], identity: { mode: obo, allowServiceOverride: false } |
session-readonly.json | level: role, same two models, tools.allow: [] |
factory-planner.json, factory-coder.json, factory-reviewer.json | level: role and id only (inherit the org grants) |
Consequences: every job gets at most haiku and sonnet (further narrowed by GATEWAY_MODELS) and no tools; an unknown
role id is a 400 at registration; a second org file refuses startup (multiple_org). An operator may mount a full
directory over /policies or point GATEWAY_POLICY_DIR elsewhere; policy changes otherwise need a new image tag.
Sources
apps/gateway/src/registrations.ts(JOB_TOKEN,hashToken,turnKeyOf,Registrations,SUBJECT_BIND_WINDOW_MS,JobDropped)apps/gateway/src/control.ts(JobBody,SubjectBody,API_JOB_ROLE,API_REQUEST_ID,MAX_TTL_MS)apps/gateway/src/identity/subject-token-cache.tspackages/agent-governance/src/schema.ts,packages/agent-governance/src/loader.ts,packages/agent-governance/src/compile.ts(merge,compile,HOOK_TOOL_PREFIX)packages/agent-types/src/grants.ts(CompiledGrants,RuntimeGrants,GatewayMcpUrl),packages/agent-types/src/gateway-control.ts(httpControl,JobRegistration)apps/worker/src/activities.ts(prepareTurn,finishTurn,revoke),apps/worker/src/runtime.ts(GATEWAY_TTL_MARGIN_MS)packages/agent-runtime-claude/src/runtime.ts(SESSION_ROLE_POLICY,REVOKE_TIMEOUT_MS,GATEWAY_UNAVAILABLE,MAX_TTL_MS)apps/worker/src/sandbox/sandbox-runtime.ts,apps/worker/src/sandbox/contract.ts(DEFAULT_POLICY_IDS_BY_PROFILE,TTL_MARGIN_MS)packages/agent-core/src/redaction.ts,packages/agent-core/src/config.ts(DEFAULT_CONFIG)apps/gateway/policies/README.mdand the JSON files beside it,apps/gateway/Dockerfiledocs/sessions/2026-11-13-agentforge-app02-test-and-worker-fleet/adr/0003-temporal-acl-only-and-baked-gateway-policy.md