Skip to main content

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​

PropertyValueSource
Formatafj_ + 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
Storagesha256(token) hex as the key of an in-memory Map; nothing persisted or loggedregistrations.ts header comment
Presentationx-api-key header, or authorization with the bearer scheme (never both)proxy.ts authenticate
LifetimettlMs from the registration, 1 to 900 000 ms (MAX_TTL_MS); capped by a bound subject's TTLcontrol.ts, registrations.ts
Redactionevery 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.

CallerControl tokenrequestId shapejobIdpolicyIdsTTLCode
Core worker, session turn (prepareTurn)workersession-<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 workerapi: api/<uuid>none{ role: 'session-readonly' }timeoutMs + ttlMarginMs, refused above 900 spackages/agent-runtime-claude/src/runtime.ts
SandboxRuntime (factory step)workerthe step's request idrequiredpolicyIdsByProfile[profile], default { role: 'factory-<role>' }timeoutMs + ttlMarginMs (default 60 000), refused above 900 sapps/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 retryable gateway_unavailable; the runtime yields internal_error with 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 401 registration_stale).
  • prepareTurn revokes the registrations of every earlier attempt (<prefix>1 to <prefix>attempts-1), because an earlier exec worker may still be running on a lost host.
  • SandboxRuntime revokes as soon as a result line 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, *.yml and *.json file 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/id pairs, zero org policies or more than one org policy refuse startup.

Schema (Policy, strict)​

FieldTypeNotes
levelorg, app, role, task
idexact name, max 128no wildcards or whitespace
models.allowexact namesrequired at org level
maxTokenspositive integer
limitsmaxTurns, timeoutMs, maxBudgetUsdGrantLimits
tools.allow, tools.denytool names like knowledge.search (^[a-z][a-z0-9]*(\.[a-z][a-z0-9_]*)+$)tools.allow required at org level
requireApprovaltool names
identity.modeobo or serviceservice not allowed at org level
identity.allowServiceOverridebooleanorg level only
egress.allowexact hostnames

Merge rules (merge in compile.ts)​

FieldRule
Chain orderstarts with the org policy; levels strictly ordered org, app, role, task, each at most once; else invalid_chain
models, tools, egress allow listsstart from the org list (absent = []); each lower level intersects; an absent lower list inherits, a present one (even []) narrows
tools.denyunion over all levels; any deny removes the tool whatever is allowed
requireApprovalunion over all levels
maxTokens, each limits keyminimum over levels; absent means unlimited
identityModeobo 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​

PolicyErrorCodeRaised byWhen
read_failedloaderdirectory or file unreadable
too_largeloaderfile over 256 KiB
parse_failedloaderJSON or YAML error, YAML warning
invalid_policyloaderschema violation
duplicate_policyloadersame level/id twice
missing_orgloader, controlno org policy
multiple_orgloadermore than one org policy
invalid_chainmerge, controlwrong order or unknown policy id at registration
identity_override_deniedmergeservice mode without org override
hook_name_collisioncompiletwo 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).

FileContent
org.jsonlevel: 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.jsonlevel: role, same two models, tools.allow: []
factory-planner.json, factory-coder.json, factory-reviewer.jsonlevel: 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.ts
  • packages/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.md and the JSON files beside it, apps/gateway/Dockerfile
  • docs/sessions/2026-11-13-agentforge-app02-test-and-worker-fleet/adr/0003-temporal-acl-only-and-baked-gateway-policy.md