From 112a601fec677a7b218643ee0ee78e3ba0f1f16d Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:29:13 -0800 Subject: [PATCH 1/2] feat(cli): `agent run --instance-id` runs a second instance on its own key A second instance of an agent (same name, another instanceId) gets its own token file, `@.json`, so its key never overwrites the default instance's. A key for one instance never runs as another, and the refusal names the command that runs it. Sessions, handled events, notices, the scratch folder and detach follow the token file's key, so every existing seat keeps its paths. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N4VWLCRBDAw5irQCF9SYye --- cli/__tests__/run-instance.test.mjs | 105 ++++++++++++++++++++++ cli/src/commands/agent.js | 130 +++++++++++++++++++++++----- 2 files changed, 215 insertions(+), 20 deletions(-) create mode 100644 cli/__tests__/run-instance.test.mjs diff --git a/cli/__tests__/run-instance.test.mjs b/cli/__tests__/run-instance.test.mjs new file mode 100644 index 0000000000..5e208ac318 --- /dev/null +++ b/cli/__tests__/run-instance.test.mjs @@ -0,0 +1,105 @@ +/** + * run-instance.test.mjs — F306 + * + * A second instance of an agent (same name, another instanceId) has its own + * key. `commonly agent run --instance-id ` runs that instance, and + * its token file is `@.json`, so it never overwrites the default + * instance's `.json`. A key for one instance never runs as another. + */ + +import { jest } from '@jest/globals'; +import os from 'os'; +import path from 'path'; +import fs from 'fs'; + +const tokensTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-run-instance-test-')); + +await jest.unstable_mockModule('os', () => { + const actual = os; + return { + ...actual, + default: { ...actual, homedir: () => tokensTmpDir }, + homedir: () => tokensTmpDir, + }; +}); + +const { + seatKey, parseRunInstanceId, runInstanceRefusal, saveAgentToken, loadAgentToken, performDetach, +} = await import('../src/commands/agent.js'); + +afterAll(() => { + fs.rmSync(tokensTmpDir, { recursive: true, force: true }); +}); + +describe('seatKey', () => { + test('the default instance keeps the bare name', () => { + expect(seatKey('nova')).toBe('nova'); + expect(seatKey('nova', 'default')).toBe('nova'); + expect(seatKey('nova', 'Default')).toBe('nova'); + }); + + test('another instance is keyed name@instance', () => { + expect(seatKey('nova', 'priya-nova')).toBe('nova@priya-nova'); + }); +}); + +describe('parseRunInstanceId', () => { + test('takes a plain instance id, and none when nothing names one', () => { + // Unnamed: the run keeps its old behaviour, keyed by the bare name. + expect(parseRunInstanceId(undefined, 'nova')).toBeNull(); + expect(parseRunInstanceId('default', 'nova')).toBe('default'); + expect(parseRunInstanceId('priya-nova', 'nova')).toBe('priya-nova'); + expect(parseRunInstanceId('team.v2_a', 'nova')).toBe('team.v2_a'); + }); + + test('refuses an id that could leave the tokens folder or is not an id', () => { + for (const bad of ['../x', 'a/b', 'a b', '', '@x', 'x'.repeat(65)]) { + expect(() => parseRunInstanceId(bad, 'nova')).toThrow(/--instance-id/); + } + }); + + test('refuses a flag on a name that already names an instance', () => { + expect(() => parseRunInstanceId('other', 'nova@priya-nova')).toThrow(/already names instance/); + // Naming the seat key alone selects that instance: that is how the daemon starts it. + expect(parseRunInstanceId(undefined, 'nova@priya-nova')).toBe('priya-nova'); + expect(parseRunInstanceId('priya-nova', 'nova@priya-nova')).toBe('priya-nova'); + }); +}); + +describe('runInstanceRefusal', () => { + test('passes a record for the instance asked for', () => { + expect(runInstanceRefusal({ record: { agentName: 'nova', instanceId: 'priya-nova' }, instanceId: 'priya-nova' })).toBeNull(); + expect(runInstanceRefusal({ record: { agentName: 'nova' }, instanceId: 'default' })).toBeNull(); + expect(runInstanceRefusal({ record: { agentName: 'nova', instanceId: 'PRIYA-NOVA' }, instanceId: 'priya-nova' })).toBeNull(); + }); + + test('refuses a key for another instance and names the command that runs it', () => { + const second = runInstanceRefusal({ record: { agentName: 'nova', instanceId: 'priya-nova' }, instanceId: 'default' }); + expect(second).toMatch(/instance priya-nova/); + expect(second).toContain('commonly agent run nova --instance-id priya-nova'); + const first = runInstanceRefusal({ record: { agentName: 'nova', instanceId: 'default' }, instanceId: 'priya-nova' }); + expect(first).toMatch(/instance default/); + expect(first).toContain('commonly agent run nova'); + expect(first).not.toContain('--instance-id'); + }); +}); + +describe('token files per instance', () => { + test("a second instance's key never overwrites the default instance's", () => { + saveAgentToken(seatKey('nova', 'default'), { agentName: 'nova', instanceId: 'default', runtimeToken: 'cm_agent_first' }); + saveAgentToken(seatKey('nova', 'priya-nova'), { agentName: 'nova', instanceId: 'priya-nova', runtimeToken: 'cm_agent_second' }); + expect(loadAgentToken('nova').runtimeToken).toBe('cm_agent_first'); + expect(loadAgentToken('nova@priya-nova').runtimeToken).toBe('cm_agent_second'); + expect(fs.existsSync(path.join(tokensTmpDir, '.commonly', 'tokens', 'nova@priya-nova.json'))).toBe(true); + }); + + test("detaching a second instance removes its own key and leaves the default's", async () => { + saveAgentToken('nova', { agentName: 'nova', instanceId: 'default', runtimeToken: 'cm_agent_first' }); + saveAgentToken('nova@priya-nova', { agentName: 'nova', instanceId: 'priya-nova', runtimeToken: 'cm_agent_second' }); + await performDetach({ + agentName: 'nova', instanceId: 'priya-nova', localKey: 'nova@priya-nova', skipBackend: true, + }); + expect(loadAgentToken('nova@priya-nova')).toBeNull(); + expect(loadAgentToken('nova').runtimeToken).toBe('cm_agent_first'); + }); +}); diff --git a/cli/src/commands/agent.js b/cli/src/commands/agent.js index a52137b950..44832dce33 100644 --- a/cli/src/commands/agent.js +++ b/cli/src/commands/agent.js @@ -197,6 +197,51 @@ export const loadAgentToken = (name) => { } }; +// ── Instances (F306) ───────────────────────────────────────────────────────── +// One agent can have more than one instance (same name, another instanceId), +// each with its own key. The default instance keeps `.json`; another +// is `@.json`, so its key never overwrites the default's. +const INSTANCE_ID_PATTERN = /^[A-Za-z0-9._-]{1,64}$/; +const isDefaultInstanceId = (instanceId) => String(instanceId || 'default').toLowerCase() === 'default'; + +export const seatKey = (agentName, instanceId) => ( + isDefaultInstanceId(instanceId) ? agentName : `${agentName}@${instanceId}` +); + +const runCommandFor = (agentName, instanceId) => ( + `commonly agent run ${agentName}${isDefaultInstanceId(instanceId) ? '' : ` --instance-id ${instanceId}`}` +); + +/** + * The instance `run ` was asked to start: --instance-id, or the one a + * seat key (`nova@priya-nova`, as the daemon names it) carries. Null when + * neither names one: that run behaves as it always has, keyed by the bare name + * whatever instance its key is for (a persona's BYO install is a non-default + * instance, and its page command names none). + * Throws on an id that is not a plain id, since it becomes part of a file name. + */ +export const parseRunInstanceId = (flag, name) => { + const at = String(name).indexOf('@'); + const fromName = at >= 0 ? String(name).slice(at + 1) : null; + if (flag !== undefined && fromName !== null && flag !== fromName) { + throw new Error(`'${name}' already names instance ${fromName}, so --instance-id ${flag} does not apply`); + } + const instanceId = flag !== undefined ? flag : fromName; + if (instanceId === null) return null; + if (!INSTANCE_ID_PATTERN.test(instanceId)) { + throw new Error(`--instance-id takes the instance's id (letters, digits, '.', '_' or '-'), not '${instanceId}'`); + } + return instanceId; +}; + +/** A key for one instance never runs as another: say which command runs it. */ +export const runInstanceRefusal = ({ record, instanceId }) => { + const keyInstance = record?.instanceId || 'default'; + if (String(keyInstance).toLowerCase() === String(instanceId || 'default').toLowerCase()) return null; + return `this key is for instance ${keyInstance} of '${record.agentName}', not instance ${instanceId || 'default'}. ` + + `To run it: ${runCommandFor(record.agentName, keyInstance)}`; +}; + export const deleteAgentToken = (name) => { const file = tokenFile(name); if (existsSync(file)) rmSync(file); @@ -1983,6 +2028,10 @@ export const performRun = ({ agentName, displayName = null, instanceId = 'default', + // F306: the token file's key, which names this seat's local state (sessions, + // handled events, notices, scratch folder). A second instance's is + // `@`; every other seat's is its bare name, as before. + localKey = null, podId = null, environment = null, // D245: the user's own Windows opt-in for this run; reaches the adapter's @@ -2058,6 +2107,7 @@ export const performRun = ({ pollLivenessCheckMs, onPollStalled, }) => { + const stateKey = localKey || agentName; const supervising = superviseRuns ?? superviseRunsByDefault(adapter?.name); reportRuntime = reportRuntime && WALKED_HARNESSES.includes(adapter?.name); { @@ -2250,7 +2300,7 @@ export const performRun = ({ // as binary-not-found — so we ensure it up front to avoid the confusing // diagnostic. ADR-008: when an environment spec was attached, the resolved // workspace path replaces the /tmp default. - const scratchCwd = join(tmpdir(), 'commonly-agents', agentName); + const scratchCwd = join(tmpdir(), 'commonly-agents', stateKey); const agentCwd = workspacePath || scratchCwd; if (!existsSync(agentCwd)) mkdirSync(agentCwd, { recursive: true }); // TASK-294: a pod can turn public after attach, so a workspace seat re-reads @@ -2604,7 +2654,7 @@ export const performRun = ({ // again on every resume (measured 2026-11-05 on codex 0.162.1 and claude // 2.1.318), so one refusal would refuse every later turn in this pod. The // next turn starts fresh; memory reaches it through the adapter's preamble. - if (isContentRefusal(error) && turn.resumedSession) clearSession(agentName, args.eventPodId); + if (isContentRefusal(error) && turn.resumedSession) clearSession(stateKey, args.eventPodId); throw error; } }; @@ -2626,7 +2676,7 @@ export const performRun = ({ const cliAgentName = (readSavedControls && !environment) || standaloneMachineRun ? agentName : null; const key = `model-unavailable:${failure.model || 'unknown'}${cliAgentName ? ':agent-config' : ''}`; try { - if (!noticeDue(agentName, key, MODEL_UNAVAILABLE_HINT_WINDOW_MS)) return; + if (!noticeDue(stateKey, key, MODEL_UNAVAILABLE_HINT_WINDOW_MS)) return; const delivery = await deliverTurnNotice({ client, podId: hintPodId, @@ -2636,7 +2686,7 @@ export const performRun = ({ log, }); if (!delivery.skipped && !delivery.refused) { - recordNotice(agentName, key); + recordNotice(stateKey, key); log(`model unavailable hint posted (${failure.model || 'model not named'})`); } } catch (noticeError) { @@ -2662,7 +2712,7 @@ export const performRun = ({ const key = `cant-answer:${notice.cause}:${waitingPod}`; try { // eslint-disable-next-line no-continue - if (!noticeDue(agentName, key, CANT_ANSWER_NOTICE_WINDOW_MS)) continue; + if (!noticeDue(stateKey, key, CANT_ANSWER_NOTICE_WINDOW_MS)) continue; // eslint-disable-next-line no-await-in-loop const delivery = await deliverChatReply({ client, @@ -2677,7 +2727,7 @@ export const performRun = ({ log(`[inbox.batch] pod ${waitingPod} was not told why this agent can't answer: ` + `${delivery.reason || 'the notice was not posted'}`); } else { - recordNotice(agentName, key); + recordNotice(stateKey, key); log(`[inbox.batch] told pod ${waitingPod} why this agent can't answer (${notice.cause})`); } } catch (noticeError) { @@ -2814,7 +2864,7 @@ export const performRun = ({ // TASK-440: a cold, large session starts fresh at wake instead of being // resumed. The restart note leads the prompt; memory still reaches the // fresh session through the adapter's preamble. - const sessionEntry = getSessionEntry(agentName, eventPodId, { binding: placement.binding }); + const sessionEntry = getSessionEntry(stateKey, eventPodId, { binding: placement.binding }); let sessionId = getSession(agentName, eventPodId, { binding: placement.binding }); let recycleBriefing = null; if (sessionId && shouldStartFreshSession({ @@ -3097,7 +3147,7 @@ export const performRun = ({ // TASK-440: record the context size this turn left behind, so the next // wake can decide whether to recycle. Adapters that report nothing keep // resuming. - setSession(agentName, eventPodId, result.newSessionId, { + setSession(stateKey, eventPodId, result.newSessionId, { binding: placement.binding, contextTokens: result.contextTokens ?? null, }); @@ -3859,7 +3909,7 @@ export const performRun = ({ const seenEventIds = new Set(); for (const entry of entries) { const eventId = String(entry.event._id); - if (seenEventIds.has(eventId) || wasEventHandled(agentName, entry.event._id)) { + if (seenEventIds.has(eventId) || wasEventHandled(stateKey, entry.event._id)) { entry.result = { outcome: 'no_action', reason: 'duplicate-delivery' }; log(`[${entry.event.type}] duplicate delivery ${entry.event._id} — re-acking without batch spawn`); } else { @@ -4518,7 +4568,7 @@ export const performRun = ({ // reached. Unacked, the kernel redelivers it. if (!entry.result) continue; if (entry.result?.reason !== 'duplicate-delivery') { - recordHandledEvent(agentName, event._id); + recordHandledEvent(stateKey, event._id); } try { const deliveryId = event.payload?.deliveryId; @@ -4554,7 +4604,7 @@ export const performRun = ({ } const [event] = group; let result; - if (wasEventHandled(agentName, event._id)) { + if (wasEventHandled(stateKey, event._id)) { result = { outcome: 'no_action', reason: 'duplicate-delivery' }; log(`[${event.type}] duplicate delivery ${event._id} — skipping spawn and re-acking`); } else { @@ -4650,7 +4700,7 @@ export const performRun = ({ // Record after successful processing but before ack. If the ack // fails, the next delivery is skipped and re-acked instead of // burning a second model turn for work that already completed. - recordHandledEvent(agentName, event._id); + recordHandledEvent(stateKey, event._id); } try { const deliveryId = event.payload?.deliveryId; @@ -4889,6 +4939,8 @@ export const performDetach = async ({ agentName, podId, instanceId = 'default', + // F306: the token file to remove; a second instance's is `@`. + localKey = null, skipBackend = false, log = () => {}, }) => { @@ -4919,9 +4971,10 @@ export const performDetach = async ({ } } - deleteAgentToken(agentName); - clearSessions(agentName); - log(`local: removed token file + session store for '${agentName}'`); + const stateKey = localKey || agentName; + deleteAgentToken(stateKey); + clearSessions(stateKey); + log(`local: removed token file + session store for '${stateKey}'`); return { backend: backendResult, localCleaned: true }; }; @@ -5322,6 +5375,7 @@ Docs: .command('run ') .description('Run the local-CLI wrapper loop for an attached agent') .option('--interval ', 'Poll interval in ms', '5000') + .option('--instance-id ', 'Run this instance of the agent, when it has more than one (default: default)') .option('--adapter ', `CLI to wrap on first-run bootstrap (${listPublicAdapterNames().join('|')}); an existing token file bound to a different adapter stops the run`) .option('--cascade-cap ', `Consecutive agent-triggered turns allowed per pod (env ${CASCADE_ENV_VARS.cap}, default ${CASCADE_DEFAULTS.cap})`) .option('--cascade-grace ', `Extra turns allowed when this seat was directly addressed; 0 disables the grace (env ${CASCADE_ENV_VARS.addressedGrace}, default ${CASCADE_DEFAULTS.addressedGrace})`) @@ -5329,7 +5383,19 @@ Docs: .option('--refusal-handoff ', 'Agent to @mention when the model provider refuses a request\'s content; the request is acked as refused, never retried') .option('--allow ', 'On first run of an agent that works in its folder, also let it edit files and run commands (write) and/or fetch web pages (web), comma-separated. Commands reach the network.') .option('--unsandboxed', 'Native Windows only: run this agent without a sandbox, with your own access to files and commands. It gets no connector grants. Codex can run commands in invite-only pods, where anyone in the pod, including people invited later, can direct it.') - .action(async (name, opts) => { + .action(async (typedName, opts) => { + // F306: the seat this run is. `name` is the local key (the token file, + // the log label, the daemon's plist); the server identity is the record's. + let instanceId; + try { + instanceId = parseRunInstanceId(opts.instanceId, typedName); + } catch (err) { + console.error(`${stamp()} [${typedName}] ${err.message}`); + process.exit(1); + } + const agentArg = String(typedName).split('@')[0]; + const named = instanceId !== null; + let name = named ? seatKey(agentArg, instanceId) : agentArg; if (opts.unsandboxed) { const flagRefusal = unsandboxedFlagRefusal(); if (flagRefusal) { @@ -5345,8 +5411,22 @@ Docs: process.exit(1); } let record = loadAgentToken(name); + // An instance's key saved by an older run, under the bare name: use it + // where it is, when it is that instance's (F306). + if (!record && named && name !== agentArg) { + const legacy = loadAgentToken(agentArg); + if (legacy && !runInstanceRefusal({ record: legacy, instanceId })) { + record = legacy; + name = agentArg; + } + } let bootstrapped = false; const saved = record; + const savedRefusal = record && named ? runInstanceRefusal({ record, instanceId }) : null; + if (savedRefusal) { + console.error(`${stamp()} [${name}] ${savedRefusal}`); + process.exit(1); + } if (record) { record = await adoptEnvToken({ record, @@ -5358,7 +5438,7 @@ Docs: // not a token file — bootstrap the record from them (#913). try { record = await bootstrapAgentRecordFromEnv({ - name, + name: agentArg, adapterOverride: opts.adapter || null, log: (line) => console.log(`${stamp()} [${name}] ${line}`), allow, @@ -5376,10 +5456,15 @@ Docs: console.error( `No token for '${name}'. Either export COMMONLY_API_URL + COMMONLY_AGENT_TOKEN` + ` (shown on the Connect your own agent page) and re-run, or:` - + ` commonly agent attach --pod --name ${name}`, + + ` commonly agent attach --pod --name ${agentArg}`, ); process.exit(1); } + const instanceRefusal = named ? runInstanceRefusal({ record, instanceId }) : null; + if (instanceRefusal) { + console.error(`${stamp()} [${name}] ${instanceRefusal}`); + process.exit(1); + } bootstrapped = true; } @@ -5447,8 +5532,11 @@ Docs: } if (saved && record !== saved) saveAgentToken(name, record); if (bootstrapped) { - saveAgentToken(record.agentName, record); - console.log(`${stamp()} [${name}] bootstrapped ${tokenFile(record.agentName)} from COMMONLY_AGENT_TOKEN (adapter: ${record.adapter})`); + // A named instance is saved under its seat key; an unnamed run keeps + // the bare name, as before. + const savedAs = named ? seatKey(record.agentName, record.instanceId) : record.agentName; + saveAgentToken(savedAs, record); + console.log(`${stamp()} [${name}] bootstrapped ${tokenFile(savedAs)} from COMMONLY_AGENT_TOKEN (adapter: ${record.adapter})`); } else if (savedSeatLacksDefaultSandbox(record)) { console.warn( `${stamp()} [${name}] this agent's saved settings declare no sandbox, so it runs without one. ` @@ -5528,6 +5616,7 @@ Docs: agentName: record.agentName, displayName: record.displayName || record.agentName, instanceId: record.instanceId, + localKey: name, podId: record.podId, environment: runEnvironment || null, hostUnconfined, @@ -5630,6 +5719,7 @@ Docs: agentName: record.agentName, podId: record.podId, instanceId: record.instanceId || 'default', + localKey: name, skipBackend: !!opts.force, log: (line) => console.warn(`[detach] ${line}`), }); From b0c4dce7e33c93a291c2ff89c7642c449c96c11a Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:36:02 -0800 Subject: [PATCH 2/2] fix(cli): a second instance resumes only its own session, and its saved key and state share one name The session read still used the bare agent name, so a second instance in a pod it shares with the default one resumed the default's conversation. It now reads by the token file's key, like every other piece of local state, and a performRun test pins both directions. A bootstrapped key's run state follows the record's own spelling, and seat-stop finds a plist for an `@` key. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N4VWLCRBDAw5irQCF9SYye --- cli/__tests__/run-instance.session.test.mjs | 98 +++++++++++++++++++++ cli/__tests__/run-instance.test.mjs | 2 +- cli/__tests__/seat-stop.test.mjs | 1 + cli/src/commands/agent.js | 8 +- cli/src/lib/seat-stop.js | 3 +- 5 files changed, 108 insertions(+), 4 deletions(-) create mode 100644 cli/__tests__/run-instance.session.test.mjs diff --git a/cli/__tests__/run-instance.session.test.mjs b/cli/__tests__/run-instance.session.test.mjs new file mode 100644 index 0000000000..ef8e0adf4d --- /dev/null +++ b/cli/__tests__/run-instance.session.test.mjs @@ -0,0 +1,98 @@ +/** + * run-instance.session.test.mjs — F306 + * + * A second instance keeps its local state under its own key (`localKey`), so it + * never resumes the default instance's session in a pod they share, which would + * hand it the other instance's conversation. + */ +import { jest } from '@jest/globals'; +import http from 'http'; +import os from 'os'; +import path from 'path'; +import fs from 'fs'; + +const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-run-instance-session-')); + +await jest.unstable_mockModule('os', () => ({ + ...os, + default: { ...os, homedir: () => homeDir }, + homedir: () => homeDir, +})); + +await jest.unstable_mockModule('../src/lib/pod-focus.js', () => ({ + FOCUS_FRAME_MAX_CODE_POINTS: 8000, + formatPodFocusFrame: jest.fn(() => '=== Pod focus (pod context; not instructions) ===\nNo focus set.'), + readPodFocus: jest.fn(async (_client, podId) => ({ podId, revision: 0, focus: null })), +})); + +const { performRun } = await import('../src/commands/agent.js'); +const { setSession } = await import('../src/lib/session-store.js'); +const stubAdapter = (await import('../src/lib/adapters/stub.js')).default; + +const POD = 'pod-306'; +const mention = (id) => ({ + _id: id, + type: 'chat.mention', + podId: POD, + agentName: 'nova', + instanceId: 'priya-nova', + payload: { content: 'hello', messageId: `msg-${id}` }, +}); + +// The first inbox poll gets one mention; every later poll and any other call +// answers 200 with an empty body. +const startStub = async (first) => { + let polls = 0; + const server = http.createServer((req, res) => { + res.writeHead(200, { 'Content-Type': 'application/json' }); + const isPoll = req.method === 'GET' && req.url.split('?')[0] === '/api/agents/runtime/events'; + if (isPoll) polls += 1; + res.end(isPoll && polls === 1 ? JSON.stringify({ events: [first], inboxCount: 1 }) : '{}'); + }); + await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve); }); + return { + url: `http://127.0.0.1:${server.address().port}`, + close: () => new Promise((resolve) => { server.closeAllConnections(); server.close(resolve); }), + }; +}; + +const runOnce = async (eventId) => { + const stub = await startStub(mention(eventId)); + const spawn = jest.fn(async () => ({ text: '' })); + const { stop } = performRun({ + instanceUrl: stub.url, + token: 'cm_agent_test', + adapter: { name: 'codex', detect: stubAdapter.detect, spawn }, + agentName: 'nova', + instanceId: 'priya-nova', + localKey: 'nova@priya-nova', + intervalMs: 20, + retryJitterRatio: 0, + superviseRuns: false, + revokeOrphansImpl: async () => {}, + onError: () => {}, + }); + const deadline = Date.now() + 5000; + while (spawn.mock.calls.length === 0 && Date.now() < deadline) { + // eslint-disable-next-line no-await-in-loop + await new Promise((resolve) => { setTimeout(resolve, 10); }); + } + await stop(); + await stub.close(); + return spawn.mock.calls[0]?.[1]; +}; + +afterAll(() => { fs.rmSync(homeDir, { recursive: true, force: true }); }); + +test("a second instance never resumes the default instance's session", async () => { + setSession('nova', POD, 'sess-default'); + const ctx = await runOnce('evt-306-a'); + expect(ctx).toBeDefined(); + expect(ctx.sessionId).not.toBe('sess-default'); +}); + +test('a second instance resumes its own session', async () => { + setSession('nova@priya-nova', POD, 'sess-second'); + const ctx = await runOnce('evt-306-b'); + expect(ctx.sessionId).toBe('sess-second'); +}); diff --git a/cli/__tests__/run-instance.test.mjs b/cli/__tests__/run-instance.test.mjs index 5e208ac318..c203480668 100644 --- a/cli/__tests__/run-instance.test.mjs +++ b/cli/__tests__/run-instance.test.mjs @@ -60,7 +60,7 @@ describe('parseRunInstanceId', () => { test('refuses a flag on a name that already names an instance', () => { expect(() => parseRunInstanceId('other', 'nova@priya-nova')).toThrow(/already names instance/); - // Naming the seat key alone selects that instance: that is how the daemon starts it. + // Naming the seat key alone selects that instance: `agent list` shows it that way. expect(parseRunInstanceId(undefined, 'nova@priya-nova')).toBe('priya-nova'); expect(parseRunInstanceId('priya-nova', 'nova@priya-nova')).toBe('priya-nova'); }); diff --git a/cli/__tests__/seat-stop.test.mjs b/cli/__tests__/seat-stop.test.mjs index 42934793ae..d84eaa1211 100644 --- a/cli/__tests__/seat-stop.test.mjs +++ b/cli/__tests__/seat-stop.test.mjs @@ -43,6 +43,7 @@ describe('seat-stop — ExitTimeOut', () => { expect(seatPlistPath('anvil', home)).toBe(join(home, 'Library', 'LaunchAgents', 'me.commonly.seat-anvil.plist')); expect(seatPlistPath('../x', home)).toBeNull(); expect(seatPlistPath('a/b', home)).toBeNull(); + expect(seatPlistPath('nova@priya-nova', home)).toBe(join(home, 'Library', 'LaunchAgents', 'me.commonly.seat-nova@priya-nova.plist')); }); test('reads ExitTimeOut from an XML plist, and only reads it', () => { diff --git a/cli/src/commands/agent.js b/cli/src/commands/agent.js index 44832dce33..d3a18296ac 100644 --- a/cli/src/commands/agent.js +++ b/cli/src/commands/agent.js @@ -214,7 +214,7 @@ const runCommandFor = (agentName, instanceId) => ( /** * The instance `run ` was asked to start: --instance-id, or the one a - * seat key (`nova@priya-nova`, as the daemon names it) carries. Null when + * seat key (`nova@priya-nova`, the token file's name) carries. Null when * neither names one: that run behaves as it always has, keyed by the bare name * whatever instance its key is for (a persona's BYO install is a non-default * instance, and its page command names none). @@ -2865,7 +2865,7 @@ export const performRun = ({ // resumed. The restart note leads the prompt; memory still reaches the // fresh session through the adapter's preamble. const sessionEntry = getSessionEntry(stateKey, eventPodId, { binding: placement.binding }); - let sessionId = getSession(agentName, eventPodId, { binding: placement.binding }); + let sessionId = getSession(stateKey, eventPodId, { binding: placement.binding }); let recycleBriefing = null; if (sessionId && shouldStartFreshSession({ lastTurn: sessionEntry?.lastTurn, @@ -5535,6 +5535,10 @@ Docs: // A named instance is saved under its seat key; an unnamed run keeps // the bare name, as before. const savedAs = named ? seatKey(record.agentName, record.instanceId) : record.agentName; + // The record's own spelling names the file, so the state this run keeps + // follows it there, and the next run finds both (case, or a token that + // belongs to another name). + if (named) name = savedAs; saveAgentToken(savedAs, record); console.log(`${stamp()} [${name}] bootstrapped ${tokenFile(savedAs)} from COMMONLY_AGENT_TOKEN (adapter: ${record.adapter})`); } else if (savedSeatLacksDefaultSandbox(record)) { diff --git a/cli/src/lib/seat-stop.js b/cli/src/lib/seat-stop.js index b650dab298..5fc4496764 100644 --- a/cli/src/lib/seat-stop.js +++ b/cli/src/lib/seat-stop.js @@ -26,7 +26,8 @@ import { armSupervisedGroupDeadline, killSupervisedGroups } from '@commonlyai/se export const DEFAULT_EXIT_TIMEOUT_S = 20; const MAX_MARGIN_MS = 5000; -const SEAT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +// `@` joins an agent and its instance in a second instance's key (F306). +const SEAT_NAME = /^[A-Za-z0-9][A-Za-z0-9._@-]*$/; /** The seat's launchd plist path, or null for a name that cannot be a file name. */ export const seatPlistPath = (name, home = homedir()) => (typeof name === 'string' && SEAT_NAME.test(name)