Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(codex): record the agent identity instead of asserting it

freshjuiceze4f45cfc54a8
diff --git a/src/core/agents/codex-thread-id-route.test.ts b/src/core/agents/codex-thread-id-route.test.ts
index 92735c83e..ad798e12f 100644
--- a/src/core/agents/codex-thread-id-route.test.ts
+++ b/src/core/agents/codex-thread-id-route.test.ts
@@ -14,7 +14,7 @@ import { hookServer } from './hook-server'
import { nodeAuthToken } from './node-auth-token'
import { initPlatform, resetPlatformForTests } from '../platform'
import { fakePlatform } from '../platform-fake'
-import { codexThreadIdentityRoot } from '../codex-identity-proxy'
+import { codexThreadIdentityRoot, type CodexThreadAgent } from '../codex-identity-proxy'
const SECRET = Buffer.alloc(32, 3)
// Another instance's secret ⇒ another instance's kid ⇒ the `legacy` failover verdict.
@@ -26,10 +26,10 @@ const NODE = 'node-thread-route'
const UNSAFE_THREAD_IDS = ['.', '..', '../x', 'a/b', '', 'x'.repeat(129)]
let dir = ''
-let bound: { nodeId: string; threadId: string }[] = []
+let bound: { nodeId: string; threadId: string; agent?: CodexThreadAgent }[] = []
let identityEvents: { nodeId: string; mode: string; reason?: string }[] = []
-function bind(threadId: string): Promise<Response> {
+function bind(threadId: string, agentId?: string): Promise<Response> {
return fetch(`http://127.0.0.1:${hookServer.getPort()}/codex-thread/bind`, {
method: 'POST',
headers: {
@@ -37,7 +37,9 @@ function bind(threadId: string): Promise<Response> {
'X-Nodeterm-Node-Token': nodeAuthToken(SECRET, NODE),
'content-type': 'application/x-www-form-urlencoded'
},
- body: `nodeId=${encodeURIComponent(NODE)}&threadId=${encodeURIComponent(threadId)}`
+ body:
+ `nodeId=${encodeURIComponent(NODE)}&threadId=${encodeURIComponent(threadId)}` +
+ (agentId === undefined ? '' : `&agentId=${encodeURIComponent(agentId)}`)
})
}
@@ -47,8 +49,8 @@ beforeAll(async () => {
initPlatform(fakePlatform({ userDataDir: dir }))
await hookServer.start()
hookServer.setNodeAuthSecret(SECRET)
- hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId }) => {
- bound.push({ nodeId, threadId })
+ hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId, agent }) => {
+ bound.push({ nodeId, threadId, agent })
})
hookServer.setCodexIdentityListener((e) => {
identityEvents.push(e)
@@ -140,3 +142,43 @@ describe('/codex-thread/fallback refuses only a forged token', () => {
expect(identityEvents).toEqual([])
})
})
+
+// The route decides the CANVAS-CONTROL GRANT; it never accepts one.
+//
+// The agent id is echoed by the pane because the pane is the only durable holder of it — a tmux
+// session outlives the app, so a bind after a restart is the common case and nothing server-side
+// still remembers what agent a node runs. That echo is not a capability claim: reaching this route
+// takes a token this instance minted FOR THIS NODE, so the caller IS the node, and the record it
+// shapes is re-exported only into that node's own tool shells. What must not be echoed is the
+// grant, and it is not: the route runs `canControlCanvas` itself, the same predicate in the same
+// process that `buildPtyEnv` used to gate the pane, so there is exactly ONE decider.
+describe('/codex-thread/bind derives the grant from the agent id it is given', () => {
+ it('grants canvas control for codex, which is unconditionally capable', async () => {
+ expect((await bind('thread-ok', 'codex')).status).toBe(204)
+ expect(bound[0].agent).toEqual({ agentId: 'codex', canvasControl: true })
+ })
+
+ it('WITHHOLDS the grant for a custom agent that inherits nothing', async () => {
+ // The narrowing the whole change is for: a claimed id cannot manufacture a grant the capability
+ // table refuses. With no base resolver registered, `custom:abc` resolves to itself and is not in
+ // CANVAS_CONTROL_CAPABLE — so the record says so, and the prelude will export no grant.
+ expect((await bind('thread-custom', 'custom:abc')).status).toBe(204)
+ expect(bound[0].agent).toEqual({ agentId: 'custom:abc', canvasControl: false })
+ })
+
+ it('writes a PRE-AGENT record when no agent id is sent', async () => {
+ // An older launcher, or a pane whose NODETERM_AGENT_ID did not survive. `undefined` here is what
+ // makes the record carry no agent line, which reads back with the documented implied values —
+ // the behaviour that shipped before this field existed.
+ expect((await bind('thread-bare')).status).toBe(204)
+ expect(bound[0].agent).toBeUndefined()
+ })
+
+ it('treats an agent id outside the alphabet as absent, not as a reason to refuse the bind', async () => {
+ // Degrade to nothing, never to something wrong — and never to a dead node: the thread binding is
+ // what keeps the session attached to its canvas node, and losing that over a label would be a
+ // far worse failure than an unlabelled record.
+ expect((await bind('thread-bad-agent', 'bad id')).status).toBe(204)
+ expect(bound[0].agent).toBeUndefined()
+ })
+})
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index 25a6ebdf3..9b6c77115 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -10,7 +10,7 @@ import type { CodexIdentityEvent } from '../../shared/types'
import type { NodeTokenVerdict } from './node-auth-token'
import { nodeTokenDir } from './node-token-files'
import { isForeignKidToken, isSafeNodeId, verifyNodeToken } from './node-auth-token'
-import { isSafeThreadId } from '../codex-identity-proxy'
+import { isSafeCodexAgentId, isSafeThreadId, type CodexThreadAgent } from '../codex-identity-proxy'
import { isSafeAccountId } from '../../shared/codex-account'
import {
controlPolicy,
@@ -285,6 +285,7 @@ class HookServer {
cwd: string
hookEndpoint: string
accountId?: string
+ agent?: CodexThreadAgent
}) => Promise<string>)
| null = null
private codexThreadBindHandler:
@@ -293,6 +294,7 @@ class HookServer {
threadId: string
hookEndpoint: string
accountId?: string
+ agent?: CodexThreadAgent
}) => Promise<void>)
| null = null
private codexIdentityListener: ((e: CodexIdentityEvent) => void) | null = null
@@ -956,6 +958,30 @@ class HookServer {
return
}
const accountId = rawAccountId || undefined
+ // THE PANE'S OWN AGENT LABEL, echoed back so the ownership record can carry it.
+ //
+ // Why the client is asked at all, when `hookEndpoint` below is deliberately the server's own
+ // answer: the agent id is a fact about a tmux session that OUTLIVES this process, and the
+ // launcher POSTing here runs inside that pane with the `NODETERM_AGENT_ID` `buildPtyEnv` put
+ // there. Nothing on the server side is as durable — an in-memory map from `buildPtyEnv` is
+ // empty for every node whose pane predates this app run, which is the norm after a restart and
+ // permanent for a node in a project the user has not opened.
+ //
+ // It is not a capability claim. A caller only reaches this line by presenting a token this
+ // instance minted FOR THIS NODE (`nodeTokenVerified` above, strict), so it is the node; the
+ // record it shapes is re-exported into that same node's own tool shells and nowhere else; and
+ // the env var it sets is not what authorizes anything (see `identityGate` — the per-node token
+ // is). Lying about it buys the liar the label they already had.
+ //
+ // THE GRANT IS NOT ECHOED. It is derived here by `canControlCanvas` — the same predicate, in
+ // the same process, that `buildPtyEnv` used to gate the pane — so there is exactly ONE decider
+ // and a forged agent id cannot manufacture a grant the table would refuse. An unparseable or
+ // absent id writes a PRE-AGENT record, which reads back with the documented implied values:
+ // the behaviour that shipped before this field existed.
+ const rawAgentId = form.agentId ?? ''
+ const agent: CodexThreadAgent | undefined = isSafeCodexAgentId(rawAgentId)
+ ? { agentId: rawAgentId, canvasControl: canControlCanvas(rawAgentId) }
+ : undefined
if (verb === 'start') {
const cwd = form.cwd ?? ''
if (!path.isAbsolute(cwd)) {
@@ -969,7 +995,8 @@ class HookServer {
nodeId,
cwd,
hookEndpoint: this.endpointFilePath(),
- accountId
+ accountId,
+ agent
})
// Same predicate the record store gates on, so a thread id the store would refuse can
// never be handed back to a launcher that will then `resume` it.
@@ -998,7 +1025,8 @@ class HookServer {
nodeId,
threadId,
hookEndpoint: this.endpointFilePath(),
- accountId
+ accountId,
+ agent
})
this.codexIdentityListener?.({ nodeId, mode: 'shared' })
res.writeHead(204)
diff --git a/src/core/codex-identity-proxy.test.ts b/src/core/codex-identity-proxy.test.ts
index 28e8a5879..5de37fc42 100644
--- a/src/core/codex-identity-proxy.test.ts
+++ b/src/core/codex-identity-proxy.test.ts
@@ -367,3 +367,189 @@ describe('account-scoped ownership', () => {
expect(resolveCodexThreadNodeIdentity('thread-1', recordsRoot, 'acct-B')).toBe('node-2')
})
})
+
+// ── The agent dimension: the record names the agent, and the prelude stops guessing ───────────
+//
+// `NODETERM_AGENT_ID` and `NODETERM_CANVAS_CONTROL` used to be constants in the sh prelude
+// (`codex`, granted). Both are `buildPtyEnv`'s answers about the PANE, so the constants mislabelled
+// every custom agent inheriting the codex harness and asserted a grant the pane might not hold.
+// Now they ride the record, inside the signature.
+//
+// The invariant these tests exist for is that the three preimage generations are SELECTED by the
+// record's shape and never tried in turn: a record that names an agent must not be verifiable under
+// a preimage that ignores the agent, or the field could be stripped or rewritten at will.
+const sign6 = (
+ threadId: string,
+ scope: string,
+ nodeId: string,
+ endpoint: string,
+ agentId: string,
+ grant: boolean
+): string =>
+ b64url(
+ createHmac('sha256', FIXED_SECRET)
+ .update(`${threadId}\0${scope}\0${nodeId}\0${endpoint}\0${agentId}\0${grant ? '1' : '0'}`)
+ .digest()
+ )
+
+const recordFile = (threadId: string): string => path.join(recordsRoot, threadId)
+
+describe('agent identity in the ownership record', () => {
+ beforeEach(() => setCodexThreadIdentityAuthSecret(FIXED_SECRET))
+
+ it('round-trips the agent id and the grant', () => {
+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/e', recordsRoot, undefined, {
+ agentId: 'custom:abc',
+ canvasControl: false
+ })
+ const got = readCodexThreadIdentity('thread-1', recordsRoot)
+ expect(got?.agentId).toBe('custom:abc')
+ expect(got?.canvasControl).toBe(false)
+ expect(got?.agentDeclared).toBe(true)
+ })
+
+ it('reads a PRE-AGENT record as codex with the grant, and says the id was not declared', () => {
+ // The back-compat contract, and the reason it is safe: every record written before these fields
+ // existed came from this same Codex spine, and codex is unconditionally canvas-control-capable,
+ // so the implied pair reproduces exactly what the prelude used to hardcode.
+ fs.mkdirSync(recordsRoot, { recursive: true })
+ fs.writeFileSync(
+ recordFile('legacy-1'),
+ `accountId=\nnodeId=node-1\nendpoint=/data/e\nsignature=${sign4('legacy-1', 'system', 'node-1', '/data/e')}\n`
+ )
+ const got = readCodexThreadIdentity('legacy-1', recordsRoot)
+ expect(got?.nodeId).toBe('node-1')
+ expect(got?.agentId).toBe('codex')
+ expect(got?.canvasControl).toBe(true)
+ // The distinguishing bit: `codex` here is an IMPLICATION, not a claim, and callers that rewrite
+ // the record need to know the difference (see the no-downgrade test below).
+ expect(got?.agentDeclared).toBe(false)
+ })
+
+ it('refuses a record whose agent id was edited after signing', () => {
+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/e', recordsRoot, undefined, {
+ agentId: 'codex',
+ canvasControl: true
+ })
+ const raw = fs.readFileSync(recordFile('thread-1'), 'utf8')
+ fs.writeFileSync(recordFile('thread-1'), raw.replace('agentId=codex', 'agentId=custom:evil'))
+ expect(readCodexThreadIdentity('thread-1', recordsRoot)).toBeUndefined()
+ })
+
+ it('refuses a record whose GRANT was edited after signing', () => {
+ // The whole reason the grant is inside the signature: it is a capability the prelude exports
+ // into an agent's shell, so an unsigned copy would be a grant anyone who can write the file
+ // could add.
+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/e', recordsRoot, undefined, {
+ agentId: 'custom:abc',
+ canvasControl: false
+ })
+ const raw = fs.readFileSync(recordFile('thread-1'), 'utf8')
+ fs.writeFileSync(recordFile('thread-1'), raw.replace('canvasControl=0', 'canvasControl=1'))
+ expect(readCodexThreadIdentity('thread-1', recordsRoot)).toBeUndefined()
+ })
+
+ it('never verifies an agent-carrying record under the pre-agent preimage', () => {
+ // THE SELECTION RULE. This record is signed with the valid 4-tuple for its node+endpoint, so a
+ // verifier that fell through generations would accept it and then read `custom:evil` — the door
+ // through which the agent id becomes forgeable. Selecting by shape closes it.
+ fs.mkdirSync(recordsRoot, { recursive: true })
+ fs.writeFileSync(
+ recordFile('thread-1'),
+ `accountId=\nnodeId=node-1\nendpoint=/data/e\nagentId=custom:evil\ncanvasControl=1\n` +
+ `signature=${sign4('thread-1', 'system', 'node-1', '/data/e')}\n`
+ )
+ expect(readCodexThreadIdentity('thread-1', recordsRoot)).toBeUndefined()
+ })
+
+ it('accepts a hand-signed 6-tuple record, so the preimage is the documented one', () => {
+ fs.mkdirSync(recordsRoot, { recursive: true })
+ fs.writeFileSync(
+ recordFile('thread-1'),
+ `accountId=\nnodeId=node-1\nendpoint=/data/e\nagentId=custom:abc\ncanvasControl=0\n` +
+ `signature=${sign6('thread-1', 'system', 'node-1', '/data/e', 'custom:abc', false)}\n`
+ )
+ expect(readCodexThreadIdentity('thread-1', recordsRoot)?.agentId).toBe('custom:abc')
+ })
+
+ it('binds the agent id under a managed account scope too', () => {
+ bindCodexThreadIdentity('thread-1', 'node-1', '/data/e', live([]), recordsRoot, 'acct-A', {
+ agentId: 'custom:abc',
+ canvasControl: true
+ })
+ expect(readCodexThreadIdentity('thread-1', recordsRoot, 'acct-A')?.agentId).toBe('custom:abc')
+ // Scope binding is unchanged: the managed record is still invisible at the system scope.
+ expect(readCodexThreadIdentity('thread-1', recordsRoot)).toBeUndefined()
+ })
+
+ it('a rebind WITHOUT an agent id keeps the one already recorded', () => {
+ // A pane whose NODETERM_AGENT_ID did not survive, or an older launcher, must not strip the line
+ // and send the prelude back to guessing `codex` — for a custom codex-based node that guess is
+ // the exact mislabel this slice removes.
+ bindCodexThreadIdentity('thread-1', 'node-1', '/data/e', live([]), recordsRoot, undefined, {
+ agentId: 'custom:abc',
+ canvasControl: false
+ })
+ bindCodexThreadIdentity('thread-1', 'node-1', '/data/e2', live([]), recordsRoot)
+ const got = readCodexThreadIdentity('thread-1', recordsRoot)
+ expect(got?.hookEndpoint).toBe('/data/e2')
+ expect(got?.agentId).toBe('custom:abc')
+ expect(got?.canvasControl).toBe(false)
+ })
+
+ it('a rebind of a PRE-AGENT record does not write the implied codex as a claim', () => {
+ // The other half of the rule. `codex` was an implication of an old record's shape; promoting it
+ // to a signed claim would make a wrong guess permanent for a custom node.
+ fs.mkdirSync(recordsRoot, { recursive: true })
+ fs.writeFileSync(
+ recordFile('legacy-1'),
+ `accountId=\nnodeId=node-1\nendpoint=/data/e\nsignature=${sign4('legacy-1', 'system', 'node-1', '/data/e')}\n`
+ )
+ bindCodexThreadIdentity('legacy-1', 'node-1', '/data/e2', live([]), recordsRoot)
+ expect(fs.readFileSync(recordFile('legacy-1'), 'utf8')).not.toContain('agentId=')
+ expect(readCodexThreadIdentity('legacy-1', recordsRoot)?.agentDeclared).toBe(false)
+ })
+
+ it('a later bind that DOES know the agent id upgrades a pre-agent record in place', () => {
+ fs.mkdirSync(recordsRoot, { recursive: true })
+ fs.writeFileSync(
+ recordFile('legacy-1'),
+ `accountId=\nnodeId=node-1\nendpoint=/data/e\nsignature=${sign4('legacy-1', 'system', 'node-1', '/data/e')}\n`
+ )
+ bindCodexThreadIdentity('legacy-1', 'node-1', '/data/e', live([]), recordsRoot, undefined, {
+ agentId: 'custom:abc',
+ canvasControl: true
+ })
+ expect(readCodexThreadIdentity('legacy-1', recordsRoot)?.agentId).toBe('custom:abc')
+ })
+
+ it('refuses an EMPTY agentId line rather than reading it as codex', () => {
+ // The fallback is keyed on the LINE BEING ABSENT, never on the value being empty. Keying it on
+ // the value would mean a record that carries an `agentId=` line can still land on the `codex`
+ // guess — the exact mislabel this slice removes, reinstated by a shape we do accept as input.
+ // This record is even signed for `codex`, so a value-keyed reader would verify it happily.
+ fs.mkdirSync(recordsRoot, { recursive: true })
+ fs.writeFileSync(
+ recordFile('thread-1'),
+ `accountId=\nnodeId=node-1\nendpoint=/data/e\nagentId=\ncanvasControl=1\n` +
+ `signature=${sign6('thread-1', 'system', 'node-1', '/data/e', 'codex', true)}\n`
+ )
+ expect(readCodexThreadIdentity('thread-1', recordsRoot)).toBeUndefined()
+ })
+
+ it('refuses to write an agent id outside the accepted alphabet', () => {
+ // Re-validated at the write as well as the read: the value ends up as an environment variable in
+ // an agent's shell, and a signature only proves we wrote the bytes, not that they are a shape we
+ // still accept.
+ for (const bad of ['', 'a b', 'a\nb', 'a/b', 'x'.repeat(129)]) {
+ expect(
+ () =>
+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/e', recordsRoot, undefined, {
+ agentId: bad,
+ canvasControl: true
+ }),
+ JSON.stringify(bad)
+ ).toThrow()
+ }
+ })
+})
diff --git a/src/core/codex-identity-proxy.ts b/src/core/codex-identity-proxy.ts
index fcd10558e..6a0dbc419 100644
--- a/src/core/codex-identity-proxy.ts
+++ b/src/core/codex-identity-proxy.ts
@@ -27,6 +27,17 @@
* rejected, so an account can never be edited to speak for another's threads. Records written
* before this slice carry no `accountId=` line and are verified with the original 3-tuple preimage
* at the system scope only — the one back-compat door, and it is a system-scope door.
+ *
+ * AGENT IDENTITY: a record also carries `agentId=` and `canvasControl=`, because the prelude
+ * re-exports both into a tool shell and used to HARDCODE them (`codex`, granted). Hardcoding
+ * mislabels every custom agent that inherits the codex harness (`custom:<uuid>`, not `codex`) and
+ * asserts a grant the pane may not hold — `buildPtyEnv` gates it on `canControlCanvas`, and
+ * `SHARED_IDENTITY_CAPABLE ⊆ CANVAS_CONTROL_CAPABLE` is the only reason the two agree today, a
+ * coincidence the list's own comment invites the next agent to break. The HMAC therefore binds the
+ * 6-tuple (threadId, accountScope, nodeId, hookEndpoint, agentId, canvasControl). A record with no
+ * `agentId=` line is pre-agent and is read with the implied values `codex` + granted, which is
+ * exactly what it meant when it was written; the preimages are SELECTED by shape, never tried in
+ * turn, so a record that names an agent can never be verified by one that ignores it.
*/
import {
chmodSync,
@@ -112,6 +123,45 @@ export function isSafeThreadId(id: string): boolean {
)
}
+/**
+ * The agent identity a record may carry, and the canvas-control grant that goes with it.
+ *
+ * WHY THE RECORD CARRIES THIS AT ALL: the sh prelude re-exports a tool shell's `NODETERM_*`, and it
+ * used to HARDCODE `NODETERM_AGENT_ID=codex` and `NODETERM_CANVAS_CONTROL=1`. Both are facts about
+ * the PANE that only `hookServer.buildPtyEnv` knows — it sets `NODETERM_AGENT_ID` to the node's own
+ * agent id (which is `custom:<uuid>` for a custom agent declaring `baseAgent: 'codex'`, not
+ * `codex`) and gates the grant on `canControlCanvas`. A constant in the prelude is the prelude
+ * asserting what it cannot know: it mislabels every custom codex-based agent, and it hands out a
+ * grant the pane may not hold. Recording them is what lets the prelude EXPORT WHAT THE RECORD SAYS.
+ *
+ * The grant is not merely derived from the agent id here because the prelude is POSIX sh and cannot
+ * evaluate `canControlCanvas` — the membership list plus the custom-agent base resolver live in
+ * TypeScript. So the decision is made once, on the desktop, by the same predicate `buildPtyEnv`
+ * uses, and travels as a boolean.
+ *
+ * BOTH FIELDS ARE INSIDE THE SIGNATURE. They name a capability the prelude then exports into an
+ * agent's environment, which is exactly the class of field `identitySignature` exists to protect —
+ * an unsigned `canvasControl=1` line would be a grant anyone who can write the file could add.
+ */
+export interface CodexThreadAgent {
+ /** The node's own agent id — `codex`, or a `custom:<uuid>` inheriting it. */
+ agentId: string
+ /** Whether `canControlCanvas` granted this node canvas control at spawn. */
+ canvasControl: boolean
+}
+
+/**
+ * Agent ids are `codex` or `custom:<uuid>`, so the alphabet needs `:` on top of the node-id one.
+ * Bounded and re-validated for the same reason every other recovered field is: the value becomes an
+ * environment variable in an agent's shell, and the file it comes from is data we parse, not code.
+ */
+const AGENT_ID_CHARSET = /^[A-Za-z0-9._:-]+$/
+const MAX_AGENT_ID = 128
+
+export function isSafeCodexAgentId(id: string): boolean {
+ return typeof id === 'string' && id.length > 0 && id.length <= MAX_AGENT_ID && AGENT_ID_CHARSET.test(id)
+}
+
let identityAuthSecret: Buffer | null = null
/** Injected by the shell once, from the same keychain-backed secret the hook server signs with. */
@@ -139,11 +189,35 @@ export function codexThreadIdentityRoot(): string {
}
/**
- * The current 4-tuple preimage: HMAC-SHA256(threadId ␀ accountScope ␀ nodeId ␀ hookEndpoint). The
- * account scope binds the record to ONE account; without it a record for account A could be moved,
- * byte-for-byte, into account B's directory and still verify.
+ * The current 6-tuple preimage:
+ * HMAC-SHA256(threadId ␀ accountScope ␀ nodeId ␀ hookEndpoint ␀ agentId ␀ canvasControl).
+ *
+ * The account scope binds the record to ONE account; without it a record for account A could be
+ * moved, byte-for-byte, into account B's directory and still verify. The agent id and the grant
+ * joined the preimage for the same reason they joined the record: the prelude exports both, so an
+ * unsigned copy of either would be a capability anyone able to write the file could edit.
*/
function identitySignature(
+ threadId: string,
+ scope: string,
+ nodeId: string,
+ hookEndpoint: string,
+ agent: CodexThreadAgent
+): string {
+ if (!identityAuthSecret) throw new Error('NodeTerm Codex identity authentication is unavailable')
+ return createHmac('sha256', identityAuthSecret)
+ .update(
+ `${threadId}\0${scope}\0${nodeId}\0${hookEndpoint}\0${agent.agentId}\0${agent.canvasControl ? '1' : '0'}`
+ )
+ .digest('base64url')
+}
+
+/**
+ * The pre-agent 4-tuple preimage (no agent dimension). Accepted ONLY for a record that carries no
+ * `agentId=` line — one written before this slice. See `recordSignatureValid` for why the two
+ * preimages are mutually exclusive rather than tried in turn.
+ */
+function accountScopedIdentitySignature(
threadId: string,
scope: string,
nodeId: string,
@@ -187,6 +261,18 @@ function signatureEquals(presented: string, expected: string): boolean {
* scope, so a scope-less signature can never be honoured under a managed account. (The mutations
* that redden these tests are the HMAC one and the `scope === SYSTEM_ACCOUNT_SCOPE` fallback guard;
* check (1) is redundant with the scope-bound HMAC and is documented as such.)
+ *
+ * THREE PREIMAGE GENERATIONS, SELECTED — NOT TRIED IN TURN. Which one applies is decided by which
+ * LINES the record carries, and exactly one branch runs:
+ * - an `agentId=` line ⇒ the current 6-tuple, and ONLY that;
+ * - no agent line but an `accountId=` line ⇒ the 4-tuple (an S6-era record);
+ * - neither, at the system scope ⇒ the 3-tuple (a pre-S6 record).
+ * Selecting rather than falling through is the load-bearing part. A record that DOES name an agent
+ * must never verify under a preimage that ignores the agent: that is the door through which an
+ * `agentId=custom:…` line could be stripped or rewritten and the record still accepted, putting the
+ * prelude back to guessing `codex` — the precise defect this generation exists to close. A caller
+ * that wants the old behaviour must present an old-SHAPED record, and an old-shaped record gets the
+ * documented implied values (see `parseCodexThreadIdentity`), never a mix of the two.
*/
function recordSignatureValid(threadId: string, dirScope: string, record: ParsedRecord): boolean {
if (!record.signature || !identityAuthSecret) return false
@@ -195,32 +281,46 @@ function recordSignatureValid(threadId: string, dirScope: string, record: Parsed
const lineScope = record.accountId || SYSTEM_ACCOUNT_SCOPE
if (lineScope !== scope) return false
}
- let expected = ''
try {
- expected = identitySignature(threadId, scope, record.nodeId, record.hookEndpoint)
- } catch {
- return false
- }
- if (signatureEquals(record.signature, expected)) return true
- if (!record.accountLinePresent && scope === SYSTEM_ACCOUNT_SCOPE) {
- try {
+ if (record.agentDeclared) {
return signatureEquals(
record.signature,
- legacyIdentitySignature(threadId, record.nodeId, record.hookEndpoint)
+ identitySignature(threadId, scope, record.nodeId, record.hookEndpoint, {
+ agentId: record.agentId,
+ canvasControl: record.canvasControl
+ })
)
- } catch {
- return false
}
+ if (record.accountLinePresent) {
+ return signatureEquals(
+ record.signature,
+ accountScopedIdentitySignature(threadId, scope, record.nodeId, record.hookEndpoint)
+ )
+ }
+ return (
+ scope === SYSTEM_ACCOUNT_SCOPE &&
+ signatureEquals(
+ record.signature,
+ legacyIdentitySignature(threadId, record.nodeId, record.hookEndpoint)
+ )
+ )
+ } catch {
+ return false
}
- return false
}
-export interface CodexThreadIdentity {
+export interface CodexThreadIdentity extends CodexThreadAgent {
/** '' for the system account; a managed account id otherwise. */
accountId: string
nodeId: string
hookEndpoint: string
signature: string
+ /**
+ * Whether the record NAMED its agent, as opposed to implying `codex` by being pre-agent. Callers
+ * that rewrite a record need the difference: re-writing an implication as a signed claim is how a
+ * custom codex-based node's guess would become permanent (see `bindCodexThreadIdentity`).
+ */
+ agentDeclared: boolean
}
interface ParsedRecord extends CodexThreadIdentity {
@@ -253,11 +353,24 @@ function parseCodexThreadIdentity(raw: string): ParsedRecord {
// line cannot be smuggled in to disagree with the first.
if (!(key in values)) values[key] = line.slice(separator + 1)
}
+ // THE IMPLIED VALUES OF A PRE-AGENT RECORD, and why they are safe. Every record written before
+ // this slice was written by this same Codex identity spine, so its node ran the codex CLI —
+ // `codex` is the right agent id for it, and `codex` is unconditionally in
+ // `CANVAS_CONTROL_CAPABLE`, so its implied grant reproduces today's behaviour exactly. This is
+ // therefore a faithful reading of an old record, not a guess about a new one.
+ //
+ // The fallback is keyed on the LINE BEING ABSENT (`'agentId' in values`), never on the value
+ // being empty or unparseable. A record that names an agent is read as naming that agent; there is
+ // no input that carries an agent id and still lands on `codex`.
+ const agentLinePresent = 'agentId' in values
return {
accountId: values.accountId ?? '',
nodeId: values.nodeId ?? '',
hookEndpoint: values.endpoint ?? '',
signature: values.signature ?? '',
+ agentId: agentLinePresent ? (values.agentId ?? '') : 'codex',
+ canvasControl: agentLinePresent ? values.canvasControl === '1' : true,
+ agentDeclared: agentLinePresent,
accountLinePresent: 'accountId' in values
}
}
@@ -283,12 +396,19 @@ export function readIdentityCandidate(
}
const record = parseCodexThreadIdentity(raw)
if (!validCodexIdentity(record.nodeId, record.hookEndpoint)) return undefined
+ // An agent id that reached the record is re-validated before the signature check, exactly as the
+ // node id and endpoint are: the value becomes an environment variable in an agent's shell, and a
+ // valid signature only proves WE wrote the bytes, not that they are still a shape we accept.
+ if (record.agentDeclared && !isSafeCodexAgentId(record.agentId)) return undefined
if (!recordSignatureValid(threadId, norm, record)) return undefined
return {
accountId: record.accountId,
nodeId: record.nodeId,
hookEndpoint: record.hookEndpoint,
- signature: record.signature
+ signature: record.signature,
+ agentId: record.agentId,
+ canvasControl: record.canvasControl,
+ agentDeclared: record.agentDeclared
}
}
@@ -375,19 +495,36 @@ export function codexThreadIdentityHasLiveConflict(
return liveOwners.size > 1
}
-/** Write (or replace) the record for `threadId` under its account scope, atomically. */
+/**
+ * Write (or replace) the record for `threadId` under its account scope, atomically.
+ *
+ * `agent` is what the prelude will export as this thread's `NODETERM_AGENT_ID` /
+ * `NODETERM_CANVAS_CONTROL`. Omitting it writes a PRE-AGENT record — the old shape, read back with
+ * the documented implied values (`codex`, grant on). That is the honest degrade for a caller that
+ * genuinely does not know the node's agent id, and it reproduces the behaviour this slice replaced;
+ * it is not a default to reach for when the id IS available.
+ */
export function writeCodexThreadIdentity(
threadId: string,
nodeId: string,
hookEndpoint: string,
root = codexThreadIdentityRoot(),
- accountId?: string
+ accountId?: string,
+ agent?: CodexThreadAgent
): void {
if (!isSafeThreadId(threadId) || !validCodexIdentity(nodeId, hookEndpoint)) {
throw new Error('Invalid NodeTerm Codex thread identity')
}
+ if (agent && !isSafeCodexAgentId(agent.agentId)) {
+ throw new Error('Invalid NodeTerm Codex thread identity')
+ }
const scope = accountScope(accountId) // throws on an id that could escape the mapping directory
- const signature = identitySignature(threadId, scope, nodeId, hookEndpoint)
+ const signature = agent
+ ? identitySignature(threadId, scope, nodeId, hookEndpoint, agent)
+ : accountScopedIdentitySignature(threadId, scope, nodeId, hookEndpoint)
+ const agentLines = agent
+ ? `agentId=${agent.agentId}\ncanvasControl=${agent.canvasControl ? '1' : '0'}\n`
+ : ''
const file = identityFile(threadId, scope, root)
const dir = path.dirname(file)
const tmp = path.join(dir, `.${threadId}.${process.pid}.${Date.now()}`)
@@ -396,7 +533,7 @@ export function writeCodexThreadIdentity(
try {
writeFileSync(
tmp,
- `accountId=${accountId ?? ''}\nnodeId=${nodeId}\nendpoint=${hookEndpoint}\nsignature=${signature}\n`,
+ `accountId=${accountId ?? ''}\nnodeId=${nodeId}\nendpoint=${hookEndpoint}\n${agentLines}signature=${signature}\n`,
{
encoding: 'utf8',
mode: 0o600
@@ -427,7 +564,8 @@ export function bindCodexThreadIdentity(
hookEndpoint: string,
isNodeLive: (nodeId: string) => boolean,
root = codexThreadIdentityRoot(),
- accountId?: string
+ accountId?: string,
+ agent?: CodexThreadAgent
): void {
if (!isSafeThreadId(threadId) || !validCodexIdentity(nodeId, hookEndpoint)) {
throw new Error('Invalid NodeTerm Codex thread identity')
@@ -437,8 +575,31 @@ export function bindCodexThreadIdentity(
if (existing && existing.nodeId !== nodeId && isNodeLive(existing.nodeId)) {
throw new Error('Codex thread is already bound to another live node')
}
- if (existing && existing.nodeId === nodeId && existing.hookEndpoint === hookEndpoint) return
- writeCodexThreadIdentity(threadId, nodeId, hookEndpoint, root, accountId)
+ // NEVER DOWNGRADE A RECORD THAT ALREADY NAMES ITS AGENT. A rebind arriving without an agent id
+ // (an older client, or a pane whose NODETERM_AGENT_ID did not survive) must not strip the line
+ // and send the prelude back to guessing `codex` — the same rule `recordSignatureValid` enforces
+ // at the signature, applied at the write. What we already know is kept; only what we are told
+ // replaces it. `agentDeclared` and not a truthy `agentId` is the test, because a PRE-AGENT record
+ // reads back as `codex` by implication and re-writing that implication as a signed claim is
+ // exactly the mislabel — for a custom codex-based node it would make the guess permanent.
+ const carried =
+ agent ??
+ (existing?.agentDeclared
+ ? { agentId: existing.agentId, canvasControl: existing.canvasControl }
+ : undefined)
+ // A rebind that would change nothing writes nothing. The agent identity is part of "nothing" now,
+ // so a caller that learns the id later still upgrades a pre-agent record in place.
+ if (
+ existing &&
+ existing.nodeId === nodeId &&
+ existing.hookEndpoint === hookEndpoint &&
+ existing.agentDeclared === !!carried &&
+ (!carried ||
+ (existing.agentId === carried.agentId && existing.canvasControl === carried.canvasControl))
+ ) {
+ return
+ }
+ writeCodexThreadIdentity(threadId, nodeId, hookEndpoint, root, accountId, carried)
}
/**
@@ -664,6 +825,7 @@ if [ "\${1-}" = resume ]; then
# live node owns it; two clients on one thread is worse than one plain session, so we fall back.
if nt_post 20 --data-urlencode "nodeId=$NODETERM_NODE_ID" --data-urlencode "threadId=\${2-}" \\
--data-urlencode "accountId=\${NODETERM_CODEX_ACCOUNT_ID-}" \\
+ --data-urlencode "agentId=\${NODETERM_AGENT_ID-}" \\
"http://localhost:\${NODETERM_HOOK_PORT-0}/codex-thread/bind" >/dev/null; then
exec codex --remote unix:// "$@"
fi
@@ -671,8 +833,14 @@ if [ "\${1-}" = resume ]; then
exec codex "$@"
fi
+# THIS PANE'S OWN LABEL travels with both calls, and the pane is the only durable holder of it:
+# tmux sessions outlive the app, so a bind arriving after a restart is the common case and nothing
+# server-side still remembers what agent this node runs. The server re-derives the canvas-control
+# grant from it rather than trusting a claim (see handleCodexThread); an absent or unparseable
+# value writes a pre-agent record and the prelude falls back to codex, i.e. the old behaviour.
nt_thread=$(nt_post ${CODEX_THREAD_START_CLIENT_MAX_S} --data-urlencode "nodeId=$NODETERM_NODE_ID" --data-urlencode "cwd=$PWD" \\
--data-urlencode "accountId=\${NODETERM_CODEX_ACCOUNT_ID-}" \\
+ --data-urlencode "agentId=\${NODETERM_AGENT_ID-}" \\
"http://localhost:\${NODETERM_HOOK_PORT-0}/codex-thread/start") || nt_thread=''
nt_thread=$(printf %s "$nt_thread" | tr -d '\\r\\n')
case "$nt_thread" in
diff --git a/src/core/codex-launcher-sh.test.ts b/src/core/codex-launcher-sh.test.ts
index a8c204dcd..643282c75 100644
--- a/src/core/codex-launcher-sh.test.ts
+++ b/src/core/codex-launcher-sh.test.ts
@@ -36,8 +36,8 @@ let dir = ''
let launcher = ''
let binDir = ''
let argvLog = ''
-let started: Array<{ nodeId: string; cwd: string; accountId?: string }> = []
-let bound: Array<{ nodeId: string; threadId: string; accountId?: string }> = []
+let started: Array<{ nodeId: string; cwd: string; accountId?: string; agentId?: string }> = []
+let bound: Array<{ nodeId: string; threadId: string; accountId?: string; agentId?: string }> = []
let fallbacks: Array<{ nodeId: string; reason?: string }> = []
let startAnswer: (() => string) | null = null
let startDelayMs = 0
@@ -65,14 +65,14 @@ beforeAll(async () => {
fs.writeFileSync(launcher, buildCodexLauncherScript('true'), { mode: 0o755 })
await hookServer.start()
hookServer.setNodeAuthSecret(SECRET)
- hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd, accountId }) => {
- started.push({ nodeId, cwd, accountId })
+ hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd, accountId, agent }) => {
+ started.push({ nodeId, cwd, accountId, agentId: agent?.agentId })
if (startDelayMs) await new Promise((r) => setTimeout(r, startDelayMs))
if (!startAnswer) throw new Error('start refused')
return startAnswer()
})
- hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId, accountId }) => {
- bound.push({ nodeId, threadId, accountId })
+ hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId, accountId, agent }) => {
+ bound.push({ nodeId, threadId, accountId, agentId: agent?.agentId })
if (!bindAnswer) throw new Error('bind refused')
bindAnswer()
})
@@ -557,3 +557,36 @@ describe('per-node capability (the authorization the shared bearer cannot give)'
expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'thread-bind-refused' }])
})
})
+
+// THIS PANE'S AGENT LABEL travels in the POST body on both calls.
+//
+// The pane is the only durable holder of it: a tmux session outlives the app, so a bind arriving
+// after a restart is the common case and nothing server-side still remembers what agent a node
+// runs. The server re-derives the canvas-control grant from the id rather than trusting a claim
+// (see codex-thread-id-route.test.ts), so what travels here is a label, not a capability — and
+// like the account id it must stay in the BODY, never on argv, where a shared host's `ps` reads it.
+describe('the pane agent id reaches the record', () => {
+ it('threads NODETERM_AGENT_ID through start', async () => {
+ await callLauncher([], { NODETERM_AGENT_ID: 'custom:abc' })
+ expect(started).toEqual([
+ { nodeId: 'node-1', cwd: fs.realpathSync(dir), agentId: 'custom:abc' }
+ ])
+ expect(codexArgv().join(' ')).not.toContain('custom:abc')
+ })
+
+ it('threads it through a resume bind too', async () => {
+ await callLauncher(['resume', 'thread-xyz'], { NODETERM_AGENT_ID: 'custom:abc' })
+ expect(bound).toEqual([
+ { nodeId: 'node-1', threadId: 'thread-xyz', agentId: 'custom:abc' }
+ ])
+ expect(codexArgv().join(' ')).not.toContain('custom:abc')
+ })
+
+ it('starts a thread with no label when the pane carries none, rather than failing', async () => {
+ // `${NODETERM_AGENT_ID-}` under `set -u` and an unset var: the launch must still work. A node
+ // whose label is missing gets a pre-agent record, which is the pre-feature behaviour.
+ await callLauncher([], { NODETERM_AGENT_ID: '' })
+ expect(started).toEqual([{ nodeId: 'node-1', cwd: fs.realpathSync(dir) }])
+ expect(fallbacks).toEqual([])
+ })
+})
diff --git a/src/core/codex-thread-identity-sh.test.ts b/src/core/codex-thread-identity-sh.test.ts
index 101322d54..77d70761d 100644
--- a/src/core/codex-thread-identity-sh.test.ts
+++ b/src/core/codex-thread-identity-sh.test.ts
@@ -177,3 +177,86 @@ describe('codex thread identity prelude — account scoping', () => {
).toBe('||')
})
})
+
+// ── The prelude EXPORTS WHAT THE RECORD SAYS ─────────────────────────────────────────────────
+//
+// `NODETERM_AGENT_ID=codex` and `NODETERM_CANVAS_CONTROL=1` used to be constants here. Both are
+// `buildPtyEnv`'s answers about the pane — it labels a node with its OWN agent id (`custom:<uuid>`
+// for a custom agent inheriting the codex harness) and gates the grant on `canControlCanvas` — so
+// the constants mislabelled every such node and asserted a grant the pane might not hold.
+//
+// A SECOND script, deliberately, rather than widening the printf above: every expectation in this
+// file is a pin on behaviour that must not change for a pre-agent record, and rewriting them all to
+// carry a new field would destroy that evidence.
+let agentScript = ''
+
+beforeAll(() => {
+ agentScript = path.join(dir, 'prelude-agent.sh')
+ fs.writeFileSync(
+ agentScript,
+ `#!/bin/sh\n${codexThreadIdentityResolverSh(root)}\n` +
+ `printf '%s|%s|%s\\n' "\${NODETERM_NODE_ID-}" "\${NODETERM_AGENT_ID-}" "\${NODETERM_CANVAS_CONTROL-}"\n`,
+ { mode: 0o755 }
+ )
+})
+
+/** node|agentId|canvasControl, so the exported label and grant can both be asserted. */
+async function resolveAgent(env: Record<string, string>): Promise<string> {
+ const { stdout } = await run('/bin/sh', [agentScript], {
+ env: { PATH: process.env.PATH ?? '', HOME: dir, ...env }
+ })
+ return stdout.trim()
+}
+
+/** A record body that NAMES its agent and grant, as every record written now does. */
+function agentBody(nodeId: string, agentId: string, grant: boolean): string {
+ return (
+ `accountId=\nnodeId=${nodeId}\nendpoint=${dir}/hook-endpoint.env\n` +
+ `agentId=${agentId}\ncanvasControl=${grant ? '1' : '0'}\nsignature=x\n`
+ )
+}
+
+describe('codex thread identity prelude — the exported agent label and grant', () => {
+ it('exports the recorded agent id, not the constant codex', async () => {
+ record('thr-a', agentBody('node-7', 'custom:abc', true))
+ expect(await resolveAgent({ CODEX_THREAD_ID: 'thr-a' })).toBe('node-7|custom:abc|1')
+ })
+
+ it('leaves the grant UNSET when the record withholds it', async () => {
+ // Absent, never '0' — both shims gate on `[ -z "$NODETERM_CANVAS_CONTROL" ]`, and this is the
+ // shape `buildPtyEnv` produces for an agent `canControlCanvas` refuses.
+ record('thr-b', agentBody('node-7', 'custom:abc', false))
+ expect(await resolveAgent({ CODEX_THREAD_ID: 'thr-b' })).toBe('node-7|custom:abc|')
+ })
+
+ it('falls back to codex WITH the grant for a pre-agent record', async () => {
+ // The back-compat contract, exercised end to end: a record written before these fields existed
+ // came from this same Codex spine, and codex is unconditionally canvas-control-capable.
+ record('thr-c', body('node-7'))
+ expect(await resolveAgent({ CODEX_THREAD_ID: 'thr-c' })).toBe('node-7|codex|1')
+ })
+
+ it('resolves NOTHING when the recorded agent id is outside the alphabet', async () => {
+ // Re-validated here because this prelude cannot check the signature (no key in an agent's
+ // shell), and the value becomes an environment variable. A bad shape resolves nothing at all
+ // rather than falling back to codex — the record is not one we wrote, so none of it is trusted.
+ record('thr-d', agentBody('node-7', 'bad id', true))
+ expect(await resolveAgent({ CODEX_THREAD_ID: 'thr-d' })).toBe('||')
+ })
+
+ it('carries the agent label through a managed account scope', async () => {
+ scopedRecord(
+ 'acct-A',
+ 'thr-e',
+ `accountId=acct-A\nnodeId=node-A\nendpoint=${dir}/hook-endpoint.env\n` +
+ `agentId=custom:abc\ncanvasControl=0\nsignature=x\n`
+ )
+ expect(
+ await resolveAgent({ CODEX_THREAD_ID: 'thr-e', NODETERM_CODEX_ACCOUNT_ID: 'acct-A' })
+ ).toBe('node-A|custom:abc|')
+ })
+
+ it('is valid POSIX sh', async () => {
+ await expect(run('/bin/sh', ['-n', agentScript])).resolves.toBeTruthy()
+ })
+})
diff --git a/src/core/codex-thread-identity-sh.ts b/src/core/codex-thread-identity-sh.ts
index a2150ab45..5aab2bf1f 100644
--- a/src/core/codex-thread-identity-sh.ts
+++ b/src/core/codex-thread-identity-sh.ts
@@ -23,6 +23,18 @@
* change nothing (Property 3 / Constraint 8, the same fail-closed posture as the TypeScript
* `resolveCodexThreadNodeIdentity`).
*
+ * WHAT IT EXPORTS IS WHAT THE RECORD SAYS — it does not decide. `NODETERM_AGENT_ID` and
+ * `NODETERM_CANVAS_CONTROL` used to be constants here (`codex`, granted), and both are facts only
+ * `hookServer.buildPtyEnv` knows: it labels the node with its OWN agent id, which for a custom
+ * agent inheriting the codex harness is `custom:<uuid>`, and it gates the grant on
+ * `canControlCanvas`. Asserting them here mislabelled every such node, and asserted a grant that
+ * agrees with the pane today only because `SHARED_IDENTITY_CAPABLE ⊆ CANVAS_CONTROL_CAPABLE` — a
+ * coincidence that list's own comment invites the next shared-identity agent to break. So the pair
+ * is recorded at bind time and read back here. A PRE-AGENT record (written before those fields
+ * existed) carries neither and means `codex` with the grant, which is precisely what it meant when
+ * it was written; a record that names an agent is exported as it stands, grant included, and never
+ * falls back to the guess.
+ *
* Inert for every other agent: without `CODEX_THREAD_ID` the whole block is skipped. A machine with
* no managed accounts has no subdirs, so the scan reduces to the one bare-root read S4 did — the
* legacy layout keeps resolving byte-for-byte (Constraint 12).
@@ -56,8 +68,11 @@ if [ -z "\${NODETERM_NODE_ID-}" ] && [ -n "\${CODEX_THREAD_ID-}" ]; then
nt_codex_matches=0
nt_codex_node=''
nt_codex_endpoint=''
+ nt_codex_agent=''
+ nt_codex_grant=''
# Validate one candidate record file for an expected scope, parsed as DATA. On success it
- # records the node/endpoint and counts the match. $1=file, $2=expected scope ('' = system).
+ # records the node/endpoint/agent/grant and counts the match. $1=file, $2=expected scope
+ # ('' = system).
nt_codex_try() {
[ -r "$1" ] || return 0
nt_a=$(sed -n 's/^accountId=//p' "$1" | head -n 1)
@@ -69,11 +84,36 @@ if [ -z "\${NODETERM_NODE_ID-}" ] && [ -n "\${CODEX_THREAD_ID-}" ]; then
esac
nt_n=$(sed -n 's/^nodeId=//p' "$1" | head -n 1)
nt_e=$(sed -n 's/^endpoint=//p' "$1" | head -n 1)
+ nt_g=$(sed -n 's/^agentId=//p' "$1" | head -n 1)
+ nt_c=$(sed -n 's/^canvasControl=//p' "$1" | head -n 1)
case "$nt_n" in ''|*[!A-Za-z0-9._-]*) return 0 ;; esac
case "$nt_e" in /*) ;; *) return 0 ;; esac
+ # SPACES ARE ADMITTED DELIBERATELY, and this line is the reason to say so. The endpoint is
+ # this app's own data-dir path, which on macOS is "~/Library/Application Support/…" — a
+ # filter without the space would reject every macOS record and silently disable the whole
+ # recovery there. What the value is used FOR is what makes that safe: both shims DOT-SOURCE
+ # it with the dot command (canvas-control-core.ts / context-link-core.ts) and the
+ # socket it names then reaches curl --unix-socket "$NODETERM_HOOK_SOCK" — every expansion
+ # inside double quotes, so a space cannot split into extra arguments. The charset is what
+ # keeps quoting and command substitution out; the leading slash above keeps it absolute.
[ "$(printf %s "$nt_e" | tr -cd 'A-Za-z0-9._/ -')" = "$nt_e" ] || return 0
+ # A PRE-AGENT record (no agentId line, or an empty one) means codex with canvas control:
+ # every record written before the agent fields existed was written by this same Codex
+ # spine, and codex is unconditionally canvas-control-capable, so the implied pair
+ # reproduces what this prelude hardcoded. A record that DOES name an agent is exported as
+ # it stands and never falls back to the guess — including its grant, which is then the
+ # canControlCanvas answer the pane itself got, not an assumption made here.
+ case "$nt_g" in
+ '')
+ nt_g=codex
+ nt_c=1
+ ;;
+ *[!A-Za-z0-9._:-]*) return 0 ;;
+ esac
nt_codex_node=$nt_n
nt_codex_endpoint=$nt_e
+ nt_codex_agent=$nt_g
+ nt_codex_grant=$nt_c
nt_codex_matches=$((nt_codex_matches + 1))
}
case "\${NODETERM_CODEX_ACCOUNT_ID-}" in
@@ -102,9 +142,17 @@ if [ -z "\${NODETERM_NODE_ID-}" ] && [ -n "\${CODEX_THREAD_ID-}" ]; then
then
NODETERM_NODE_ID="$nt_codex_node"
NODETERM_HOOK_ENDPOINT="$nt_codex_endpoint"
- NODETERM_AGENT_ID=codex
- NODETERM_CANVAS_CONTROL=1
- export NODETERM_NODE_ID NODETERM_HOOK_ENDPOINT NODETERM_AGENT_ID NODETERM_CANVAS_CONTROL
+ NODETERM_AGENT_ID="$nt_codex_agent"
+ export NODETERM_NODE_ID NODETERM_HOOK_ENDPOINT NODETERM_AGENT_ID
+ # The grant is EXPORTED ONLY WHEN THE RECORD CARRIES IT, and is left UNSET otherwise —
+ # absent, never '0', the same shape buildPtyEnv produces, because both shims gate on
+ # \`[ -z "$NODETERM_CANVAS_CONTROL" ]\`. Withholding is the honest degrade: the tool shell
+ # loses a verb its pane still has, whereas asserting a grant the pane was denied is the
+ # widening this file must never do.
+ if [ "$nt_codex_grant" = 1 ]; then
+ NODETERM_CANVAS_CONTROL=1
+ export NODETERM_CANVAS_CONTROL
+ fi
fi
;;
esac
diff --git a/src/main/codex-identity-record-wiring.test.ts b/src/main/codex-identity-record-wiring.test.ts
new file mode 100644
index 000000000..fb496a58d
--- /dev/null
+++ b/src/main/codex-identity-record-wiring.test.ts
@@ -0,0 +1,60 @@
+// The shell must FORWARD the agent identity into the ownership record, and no type can make it.
+//
+// `hookServer.setCodexThread{Start,Bind}Handler` take a request object. A handler that destructures
+// `{ nodeId, cwd, hookEndpoint, accountId }` and drops `agent` is perfectly well-typed — an object
+// destructure is allowed to ignore properties — and so is a call to `writeCodexThreadIdentity`
+// that omits its optional trailing argument. So the whole agent dimension can be plumbed through
+// core, the route, the launcher and the sh prelude, pass `npm run typecheck`, pass every unit test,
+// and still be INERT in the shipped desktop app: every record written would carry no agent line,
+// every one would read back as the implied `codex` with the grant, and the mislabel this exists to
+// remove would survive untouched with a green suite. That happened once while writing this change.
+//
+// It is the same class of hole `hook-verified-parity.test.ts` was written for — "the boundary tests
+// cannot tell you a field is MISSING" — and the same remedy: pin it at SOURCE level.
+//
+// Only `src/main` registers these handlers today. If the Server Edition ever grows a shared-Codex
+// leg it must be added to `SHELLS` below, or it inherits exactly this silence.
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import { join } from 'path'
+
+const SHELLS = [{ name: 'desktop', file: join(__dirname, 'index.ts') }] as const
+
+/**
+ * The text of one handler registration: from its `setCodexThread…Handler(` to the closing `})` that
+ * ends the call. Found by brace-free scanning for the terminator at the registration's own
+ * indentation, which is enough here and keeps the guard free of a TS parser.
+ */
+function handlerBody(source: string, setter: string): string {
+ const start = source.indexOf(`hookServer.${setter}(`)
+ expect(start, `${setter} is not registered — this guard is looking at the wrong file`).toBeGreaterThan(-1)
+ const end = source.indexOf('\n })', start)
+ expect(end, `${setter} has no recognisable end`).toBeGreaterThan(start)
+ return source.slice(start, end)
+}
+
+describe('the desktop shell forwards Codex agent identity into the ownership record', () => {
+ for (const shell of SHELLS) {
+ const source = readFileSync(shell.file, 'utf8')
+
+ for (const [setter, writer] of [
+ ['setCodexThreadStartHandler', 'writeCodexThreadIdentity'],
+ ['setCodexThreadBindHandler', 'bindCodexThreadIdentity']
+ ] as const) {
+ const body = handlerBody(source, setter)
+
+ it(`${shell.name}: ${setter} destructures the agent off the request`, () => {
+ // Without this the field is silently dropped at the very first line of the handler.
+ expect(body).toMatch(/\{[^}]*\bagent\b[^}]*\}/)
+ })
+
+ it(`${shell.name}: ${setter} passes it to ${writer}`, () => {
+ const call = body.slice(body.indexOf(writer))
+ expect(call, `${writer} is not called in ${setter}`).not.toBe('')
+ // The argument list must actually name it. A record written without it is a PRE-AGENT
+ // record: legal, readable, and wrong for every node whose agent is not plain codex.
+ expect(call).toMatch(/\bagent\b/)
+ })
+ }
+ }
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index 70f2b3b8a..99789b197 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1703,12 +1703,16 @@ app.whenReady().then(async () => {
// workspace that no longer holds it) is free to be re-claimed; one whose owner is still there is
// not, and the launcher then falls back rather than putting two clients on one conversation.
const codexNodeIsLive = (nodeId: string): boolean => !!workspaceStore.getNode(nodeId)
- hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd, hookEndpoint, accountId }) => {
+ // `agent` is the pane's own label plus the grant the route derived from it; passing it is what
+ // makes the record name its agent instead of leaving the sh prelude to guess `codex`. Omitting it
+ // compiles perfectly — the destructure would just ignore the field — so the feature would ship
+ // INERT on this shell with a green typecheck. `codex-identity-record-wiring.test.ts` pins it.
+ hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd, hookEndpoint, accountId, agent }) => {
const threadId = await startCodexThread(cwd)
- writeCodexThreadIdentity(threadId, nodeId, hookEndpoint, undefined, accountId)
+ writeCodexThreadIdentity(threadId, nodeId, hookEndpoint, undefined, accountId, agent)
return threadId
})
- hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId, hookEndpoint, accountId }) => {
+ hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId, hookEndpoint, accountId, agent }) => {
// Ask the app-server whether this conversation exists BEFORE recording that a node owns it.
// The id reaching us is whatever the node persisted — it can be stale, or from a session that
// ran under plain codex and the shared server has never heard of. Binding it anyway writes a
@@ -1717,7 +1721,15 @@ app.whenReady().then(async () => {
if (!(await codexThreadExists(threadId))) {
throw new Error('Codex thread is unknown to the shared app-server')
}
- bindCodexThreadIdentity(threadId, nodeId, hookEndpoint, codexNodeIsLive, undefined, accountId)
+ bindCodexThreadIdentity(
+ threadId,
+ nodeId,
+ hookEndpoint,
+ codexNodeIsLive,
+ undefined,
+ accountId,
+ agent
+ )
})
// SSH_ASKPASS relay (ssh-project.ts): lets the ControlMaster, which has no tty, route a
// passphrase-protected identity file's prompt back through the app instead of failing auth.