Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: allow scanner grants without cost or elapsed limits

atomantic86c479765daf
diff --git a/client/src/components/cos/AgentResultLine.jsx b/client/src/components/cos/AgentResultLine.jsx
index 40c83936b3..476f054c64 100644
--- a/client/src/components/cos/AgentResultLine.jsx
+++ b/client/src/components/cos/AgentResultLine.jsx
@@ -59,9 +59,9 @@ export function SecurityScanEvidence({ scanner, control }) {
{scanner.status === 'invalid-input' && <div>Input rejected before scanner launch</div>}
{scanner.preflight && <div>Input rejections: {formatCount(scanner.preflight.rejectedRequests)} · Last: {scanner.preflight.lastError.field} item {formatCount(scanner.preflight.lastError.index + 1)} — {scanner.preflight.lastError.code}</div>}
<div>Model: {scanner.model ?? 'unknown'} · Effort: {scanner.effort ?? 'unknown'} · Auth: {scanner.auth}</div>
- <div>Estimated baseline: {scanner.estimatedCostUsd == null ? 'unknown' : formatUsd(scanner.estimatedCostUsd, { maximumFractionDigits: 4 })} · Estimate cap: {scanner.maxCostUsd == null ? 'unknown' : formatUsd(scanner.maxCostUsd, { maximumFractionDigits: 4 })} (API-equivalent USD)</div>
+ <div>Estimated baseline: {scanner.estimatedCostUsd == null ? 'unknown' : formatUsd(scanner.estimatedCostUsd, { maximumFractionDigits: 4 })} · Estimate cap: {scanner.maxCostUsd == null ? 'unknown' : scanner.maxCostUsd === 'unlimited' ? 'none (no estimate cap)' : formatUsd(scanner.maxCostUsd, { maximumFractionDigits: 4 })} (API-equivalent USD)</div>
<div>Short-context estimates do not measure billed charges or ChatGPT subscription quota.</div>
- <div>Time limit: {scanner.timeLimitSeconds == null ? 'unknown' : `${formatCount(scanner.timeLimitSeconds)}s`} · Exit: {scanner.exitCode ?? 'unknown'}</div>
+ <div>Time limit: {scanner.timeLimitSeconds == null ? 'unknown' : scanner.timeLimitSeconds === 'unlimited' ? 'none (no elapsed-time deadline)' : `${formatCount(scanner.timeLimitSeconds)}s`} · Exit: {scanner.exitCode ?? 'unknown'}</div>
<div>Artifacts — findings: {scanner.artifacts?.findings == null ? 'unknown' : scanner.artifacts.findings ? 'saved' : 'absent'}; coverage: {scanner.artifacts?.coverage == null ? 'unknown' : scanner.artifacts.coverage ? 'saved' : 'absent'}</div>
{(control?.cleanup || scanner.cleanup) && <div>Process cleanup: {control?.cleanup || scanner.cleanup}</div>}
</div>
diff --git a/client/src/components/cos/AgentResultLine.test.jsx b/client/src/components/cos/AgentResultLine.test.jsx
index 14504a9e27..9d081ba757 100644
--- a/client/src/components/cos/AgentResultLine.test.jsx
+++ b/client/src/components/cos/AgentResultLine.test.jsx
@@ -58,6 +58,22 @@ it('shows runner observations during execution without requiring an agent comple
expect(screen.queryByText('Completed successfully')).not.toBeInTheDocument();
});
+it('distinguishes explicit unlimited grants from unknown, zero and saved bounded limits', () => {
+ const scanner = { source: 'runner', status: 'running', auth: 'chatgpt', maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' };
+ const view = render(<SecurityScanEvidence scanner={scanner} />);
+ expect(screen.getByText(/Time limit: none \(no elapsed-time deadline\)/)).toBeInTheDocument();
+ expect(screen.getByText(/Estimate cap: none \(no estimate cap\)/)).toBeInTheDocument();
+ view.rerender(<SecurityScanEvidence scanner={{ ...scanner, maxCostUsd: null, timeLimitSeconds: null }} />);
+ expect(screen.getByText(/Estimate cap: unknown/)).toBeInTheDocument();
+ expect(screen.getByText(/Time limit: unknown/)).toBeInTheDocument();
+ view.rerender(<SecurityScanEvidence scanner={{ ...scanner, maxCostUsd: 0, timeLimitSeconds: 0 }} />);
+ expect(screen.getByText(/Estimate cap: \$0.00/)).toBeInTheDocument();
+ expect(screen.getByText(/Time limit: 0s/)).toBeInTheDocument();
+ view.rerender(<SecurityScanEvidence scanner={{ ...scanner, maxCostUsd: 25, timeLimitSeconds: 1200 }} />);
+ expect(screen.getByText(/Estimate cap: \$25.00/)).toBeInTheDocument();
+ expect(screen.getByText(/Time limit: 1,200s/)).toBeInTheDocument();
+});
+
it('distinguishes connection loss from the last trusted runner observation', () => {
render(<SecurityScanEvidence scanner={{ source: 'runner', status: 'running', auth: 'chatgpt' }} control={{ status: 'interrupted', cleanup: 'unconfirmed' }} />);
expect(screen.getByText(/interrupted \(runner connection lost\)/)).toBeInTheDocument();
diff --git a/docs/SECURITY_SCANNER_RUNTIME.md b/docs/SECURITY_SCANNER_RUNTIME.md
index b014bfa0c1..3647a3d2e0 100644
--- a/docs/SECURITY_SCANNER_RUNTIME.md
+++ b/docs/SECURITY_SCANNER_RUNTIME.md
@@ -26,21 +26,41 @@ so a successful correction does not erase validation history.
The immutable dispatch grant uses the effective outer Codex command's model and
effort, including saved flags and supported-effort clamping. Missing or conflicting
-pins make the scanner unavailable. New dispatches receive a $25 API-equivalent
-short-context estimate cap and a 1,200-second process-group deadline. Existing
-$2/180-second grants retain their original limits; no receipt is reset or upgraded.
-Both policies require explicit ChatGPT authentication. API-key environment variables
-are not passed to this subprocess. The cap uses the scanner's short-context baseline;
-in-flight work can exceed it. These estimates measure neither billed charges nor
-ChatGPT subscription quota, and cannot be converted to a weekly usage percentage.
-A cybersecurity-policy refusal stops the scanner and outer request without automatic
-continuation, retry or fallback.
+pins make the scanner unavailable. New dispatches explicitly save `"unlimited"`
+for both `maxCostUsd` and `timeLimitSeconds`: PortOS imposes neither an estimate cap
+nor an elapsed-time deadline. `null` remains unknown and numeric zero remains zero;
+omitted fields cannot create a grant. Existing $2/180-second and $25/1,200-second
+grants retain their original limits; no receipt is reset or upgraded. All policies
+require explicit ChatGPT authentication, with no API fallback. API-key and scanner
+project-config environment variables are not passed to the subprocess.
-The server waits up to 1,210 seconds for the scanner POST, allowing the longest
-grant plus cleanup to complete. That request uses the existing transport dispatcher
-without undici's shorter header/body inactivity ceilings; the whole-exchange timeout
-still applies and the request is never automatically retried. Status and Stop calls
-retain their 15-second transport timeout. None of these waits extends a saved grant.
+The installed Codex Security 0.2.0 configuration schema documents omission of
+`maxCostUsd` as no limit. PortOS omits `--max-cost` for unlimited grants; it never
+passes zero, null or an invented large budget. The CLI loads a project file only
+when explicitly selected by `--config` or `CODEX_SECURITY_PROJECT_CONFIG`; neither
+is provided. Thus a repository configuration cannot silently reinstate a cap.
+The adapter retains its existing `--mode standard` and does not pass `--max-time`.
+Provider quota, rate and safety limits still apply. For saved bounded grants the
+cap uses the short-context API-equivalent baseline; in-flight work can exceed it.
+These estimates measure neither billed charges nor ChatGPT subscription quota,
+and cannot be converted to a weekly usage percentage. The final CLI JSON supplies
+`cost.estimatedUsd` as the baseline even without a cap; a missing, malformed or
+oversized result remains unknown. A cybersecurity-policy
+refusal stops the scanner and outer request without continuation, retry or fallback.
+
+The scanner POST has no elapsed timeout and uses the existing transport dispatcher
+without undici's header/body inactivity ceilings. The canonical loopback curl request
+also disables its elapsed timeout. The HTTP servers and dev proxy impose no response
+wait cutoff on this route; incoming-request/header and keep-alive limits do not
+limit a scan after its request body has arrived. Status and Stop calls retain their
+15-second transport timeout. Requests are never automatically retried, and none of
+these waits extends a saved bounded grant.
+
+For an unlimited grant, the whole outer audit session also skips silence-based
+continue nudges and stalled badges, including later validation or fix work. Startup
+readiness, explicit provider failures/refusals, completion signals, manual Stop and
+actual process exit remain active. Job maintenance/recovery checks process ownership
+and liveness; quiet work is not an elapsed-time failure.
The runner owns a separate POSIX process group. A small IPC supervisor waits until
its ownership receipt is durable before launching the scanner. Losing the runner
diff --git a/server/cos-runner/securityScan.js b/server/cos-runner/securityScan.js
index 5f907505a7..884a1330f9 100644
--- a/server/cos-runner/securityScan.js
+++ b/server/cos-runner/securityScan.js
@@ -157,7 +157,9 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, t
await ensureDir(outputDir);
await chmod(outputDir, 0o700);
const args = [...cli.args, 'scan', agent.workspacePath, '--mode', 'standard', '--auth', 'chatgpt', '--headless', '--json',
- '--model', entry.grant.model, '--effort', entry.grant.effort, '--max-cost', String(entry.grant.maxCostUsd),
+ '--model', entry.grant.model, '--effort', entry.grant.effort,
+ // codex-security documents omission as no cap; 0/null are not CLI limits.
+ ...(typeof entry.grant.maxCostUsd === 'number' ? ['--max-cost', String(entry.grant.maxCostUsd)] : []),
'--output-dir', outputDir, '--scan-prompt-file', promptFile,
...paths.flatMap(path => ['--path', path]), ...knowledgeBase.flatMap(path => ['--knowledge-base', path])];
const env = Object.fromEntries(Object.entries(environment).filter(([key]) => ENV_KEYS.has(key)));
@@ -172,6 +174,10 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, t
if (entry.stopReason) { entry.evidence.status = entry.stopReason; return { evidence: entry.evidence, artifactDirectory: directory }; }
const detectRefusal = createContentRefusalDetector();
let logTail = '';
+ // --json reports cost even without --max-cost. Bound the whole stdout
+ // document; a truncated/oversized result is unknown, never a guessed cost.
+ let resultJson = '';
+ let resultJsonOversized = false;
let logWrites = Promise.resolve();
let logError;
const logPath = join(directory, 'scan.log');
@@ -223,7 +229,13 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, t
cancel();
}
};
- child.stdout.on('data', consume);
+ child.stdout.on('data', chunk => {
+ if (!resultJsonOversized) {
+ resultJson += String(chunk);
+ if (resultJson.length > 1024 * 1024) { resultJson = ''; resultJsonOversized = true; }
+ }
+ consume(chunk);
+ });
child.stderr.on('data', consume);
const streamsEnded = Promise.all([child.stdout, child.stderr].map(stream =>
new Promise(resolve => { stream.once('end', resolve); stream.once('close', resolve); })));
@@ -239,7 +251,9 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, t
Promise.all([streamsEnded, exitCleanup]).then(() => resolveExit({ code, signal }));
});
child.once('close', (code, signalName) => resolveExit({ code, signal: signalName }));
- deadline = setTimeout(() => { entry.stopReason ||= 'time-limit'; cancel(); }, entry.grant.timeLimitSeconds * 1000);
+ if (typeof entry.grant.timeLimitSeconds === 'number' && entry.grant.timeLimitSeconds > 0) {
+ deadline = setTimeout(() => { entry.stopReason ||= 'time-limit'; cancel(); }, entry.grant.timeLimitSeconds * 1000);
+ }
if (entry.stopReason) cancel();
});
await atomicWrite(join(agentsDir, id, 'security-scan-process.json'), entry.owner);
@@ -256,6 +270,11 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, t
entry.evidence.status = entry.stopReason || (exit.code === 0 && !exit.failed && entry.evidence.cleanup === 'confirmed' ? 'completed' : 'failed');
const costs = [...logTail.matchAll(/short-context budget baseline:\s*\$([\d.]+)/g)];
if (costs.length) entry.evidence.estimatedCostUsd = Number(costs.at(-1)[1]);
+ if (resultJson && !resultJsonOversized) {
+ let result; try { result = JSON.parse(resultJson); } catch { /* Partial output stays unknown. */ }
+ const baseline = (result?.data ?? result)?.cost?.estimatedUsd;
+ if (typeof baseline === 'number' && Number.isFinite(baseline) && baseline >= 0) entry.evidence.estimatedCostUsd = baseline;
+ }
if (!entry.stopReason && /(?:exceeds?|exceeded).*?(?:max.cost|budget)|budget.*?(?:exceeded|limit reached)/i.test(logTail)) entry.evidence.status = 'budget-limit';
const files = await readdir(outputDir).catch(() => null);
entry.evidence.artifacts = { findings: files?.includes('findings.json') ?? null, coverage: files?.includes('coverage.json') ?? null };
diff --git a/server/cos-runner/securityScan.process.test.js b/server/cos-runner/securityScan.process.test.js
index 633992d9f3..f524fba8e6 100644
--- a/server/cos-runner/securityScan.process.test.js
+++ b/server/cos-runner/securityScan.process.test.js
@@ -28,7 +28,7 @@ it.skipIf(process.platform === 'win32')('reaps a real inherited worker after the
getAgent: () => ({ workspacePath: join(root, 'repo') }),
resolveCli: async () => ({ command: process.execPath, args: [fixture] }),
});
- await manager.register('agent-example', { model: 'example-model', effort: 'medium', auth: 'chatgpt', maxCostUsd: 2, timeLimitSeconds: 180 });
+ await manager.register('agent-example', { model: 'example-model', effort: 'medium', auth: 'chatgpt', maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' });
const result = await manager.start('agent-example', { prompt: 'Synthetic lifecycle fixture', paths: ['.'] });
owners.push(JSON.parse(await readFile(join(root, 'agents/agent-example/security-scan-process.json'), 'utf8')));
const workerPid = Number(await readFile(join(result.artifactDirectory, 'results/worker.pid'), 'utf8'));
diff --git a/server/cos-runner/securityScan.test.js b/server/cos-runner/securityScan.test.js
index d13d42f559..d95c4b3443 100644
--- a/server/cos-runner/securityScan.test.js
+++ b/server/cos-runner/securityScan.test.js
@@ -7,8 +7,9 @@ import { join } from 'path';
import { tmpdir } from 'os';
import { createSecurityScanManager } from './securityScan.js';
-const grant = { model: 'example-model', effort: 'medium', auth: 'chatgpt', maxCostUsd: 25, timeLimitSeconds: 1200 };
+const grant = { model: 'example-model', effort: 'medium', auth: 'chatgpt', maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' };
const legacyGrant = { ...grant, maxCostUsd: 2, timeLimitSeconds: 180 };
+const boundedGrant = { ...grant, maxCostUsd: 25, timeLimitSeconds: 1200 };
let root;
const outerAgents = [];
beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'scanner-runtime-test-')); await mkdir(join(root, 'repo')); });
@@ -39,7 +40,7 @@ function setup({ finish, ...overrides } = {}) {
emitEvidence: async (_id, value) => { evidence.push(value); },
resolveCli: async () => ({ command: 'installed-scanner', args: [] }), spawnProcess, kill,
cleanupGroup: async () => true, tempRoot: root,
- environment: { PATH: '/example/bin', HOME: root, OPENAI_API_KEY: 'example-not-a-key', PORTOS_API_TOKEN: 'example-not-a-token' },
+ environment: { PATH: '/example/bin', HOME: root, OPENAI_API_KEY: 'example-not-a-key', PORTOS_API_TOKEN: 'example-not-a-token', CODEX_SECURITY_PROJECT_CONFIG: '/example/ambient-budget.yaml' },
...overrides });
return { manager, agent, spawnProcess, kill, spawned, evidence };
}
@@ -206,7 +207,7 @@ describe.skipIf(process.platform === 'win32')('runner-owned scanner lifecycle',
expect(h.spawnProcess).not.toHaveBeenCalled();
});
- it.each([grant, legacyGrant])('pins the $maxCostUsd / $timeLimitSeconds launch grant and records successful evidence without API credentials', async launchGrant => {
+ it.each([grant, legacyGrant, boundedGrant])('pins the $maxCostUsd / $timeLimitSeconds launch grant and records successful evidence without API credentials', async launchGrant => {
const h = setup();
await h.manager.register('agent-example', launchGrant);
const run = h.manager.start('agent-example', input);
@@ -214,14 +215,22 @@ describe.skipIf(process.platform === 'win32')('runner-owned scanner lifecycle',
expect(args).toContain('--auth');
expect(args.slice(args.indexOf('--auth'), args.indexOf('--auth') + 2)).toEqual(['--auth', 'chatgpt']);
expect(args.slice(args.indexOf('--model'), args.indexOf('--model') + 4)).toEqual(['--model', 'example-model', '--effort', 'medium']);
- expect(args.slice(args.indexOf('--max-cost'), args.indexOf('--max-cost') + 2)).toEqual(['--max-cost', String(launchGrant.maxCostUsd)]);
+ if (launchGrant.maxCostUsd === 'unlimited') expect(args).not.toContain('--max-cost');
+ else expect(args.slice(args.indexOf('--max-cost'), args.indexOf('--max-cost') + 2)).toEqual(['--max-cost', String(launchGrant.maxCostUsd)]);
+ expect(args).not.toContain('--max-time');
+ expect(args).not.toContain('--config');
+ expect(options.env).not.toHaveProperty('CODEX_SECURITY_PROJECT_CONFIG');
expect(options.env).not.toHaveProperty('OPENAI_API_KEY');
expect(options.env).not.toHaveProperty('PORTOS_API_TOKEN');
expect(options.stdio[0]).toBe('ignore');
const output = args[args.indexOf('--output-dir') + 1];
await writeFile(join(output, 'findings.json'), '[]');
await writeFile(join(output, 'coverage.json'), '{}');
- child.stdout.write(`short-context budget baseline: $0.25 of $${launchGrant.maxCostUsd}.00 limit\n`);
+ if (launchGrant.maxCostUsd === 'unlimited') {
+ child.stderr.write('Synthetic progress on stderr.\n');
+ child.stdout.write('{\n \"cost\": {\n \"estimatedUsd\":');
+ child.stdout.write(' 0.25, \"estimatedUsdRange\": {\"min\":0.25,\"max\":0.5} }\n}\n');
+ } else child.stdout.write(`short-context budget baseline: $0.25 of $${launchGrant.maxCostUsd}.00 limit\n`);
child.emit('close', 0, null);
const result = await run;
expect(result.evidence).toMatchObject({ source: 'runner', status: 'completed', model: 'example-model', effort: 'medium',
@@ -230,6 +239,25 @@ describe.skipIf(process.platform === 'win32')('runner-owned scanner lifecycle',
expect(h.evidence.map(e => e.status)).toEqual(['not-run', 'running', 'completed']);
});
+ it.each([
+ ['zero baseline', '{"data":{"cost":{"estimatedUsd":0}}}', 0],
+ ['missing baseline', '{"cost":{"estimatedUsdRange":{"min":1,"max":2}}}', null],
+ ['unknown baseline', '{"cost":{"estimatedUsd":null}}', null],
+ ['invalid numeric string', '{"cost":{"estimatedUsd":"2"}}', null],
+ ['negative baseline', '{"cost":{"estimatedUsd":-1}}', null],
+ ['nonfinite baseline', '{"cost":{"estimatedUsd":1e400}}', null],
+ ['truncated JSON', '{"cost":{"estimatedUsd":2}', null],
+ ['oversized JSON', JSON.stringify({ padding: 'x'.repeat(1024 * 1024), cost: { estimatedUsd: 2 } }), null],
+ ])('records only a known numeric final estimate: %s', async (_name, output, estimatedCostUsd) => {
+ const h = setup();
+ await h.manager.register('agent-example', grant);
+ const run = h.manager.start('agent-example', input);
+ const { child } = await h.spawned;
+ child.stdout.write(output);
+ child.emit('close', 0, null);
+ expect((await run).evidence).toMatchObject({ status: 'completed', maxCostUsd: 'unlimited', estimatedCostUsd });
+ });
+
it('rejects request overrides and shares a single attempt across duplicate or lost-response requests', async () => {
const h = setup();
await h.manager.register('agent-example', grant);
@@ -317,7 +345,37 @@ describe.skipIf(process.platform === 'win32')('runner-owned scanner lifecycle',
await h.manager.stop('agent-example');
await run;
});
- it.each([grant, legacyGrant])('enforces the saved $timeLimitSeconds second deadline without renewing a stuck child', async launchGrant => {
+ it('leaves a quiet no-deadline scan running until manual Stop and never renews it', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', grant);
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const run = h.manager.start('agent-example', input);
+ const { child } = await h.spawned;
+ await vi.advanceTimersByTimeAsync(48 * 60 * 60 * 1000);
+ expect(h.kill).not.toHaveBeenCalled();
+ expect((await h.manager.read('agent-example'))).toMatchObject({ status: 'running', timeLimitSeconds: 'unlimited' });
+ child.stdout.write('Still reviewing source.\n');
+ const stopped = await h.manager.stop('agent-example');
+ expect(stopped).toMatchObject({ status: 'interrupted', cleanup: 'confirmed', timeLimitSeconds: 'unlimited' });
+ expect(h.kill).toHaveBeenCalledWith(child, 'SIGTERM', { processGroup: true });
+ expect(await h.manager.start('agent-example', input)).toEqual(await run);
+ expect(h.spawnProcess).toHaveBeenCalledOnce();
+ });
+
+ it('preserves a saved estimate cap and terminal budget evidence without retry', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', boundedGrant);
+ const run = h.manager.start('agent-example', input);
+ const { child, args } = await h.spawned;
+ expect(args.slice(args.indexOf('--max-cost'), args.indexOf('--max-cost') + 2)).toEqual(['--max-cost', '25']);
+ child.stdout.write('short-context budget baseline: $25.01\nBudget limit reached\n');
+ child.emit('close', 2, null);
+ expect((await run).evidence).toMatchObject({ status: 'budget-limit', maxCostUsd: 25, estimatedCostUsd: 25.01, timeLimitSeconds: 1200, exitCode: 2 });
+ expect(await h.manager.start('agent-example', input)).toEqual(await run);
+ expect(h.spawnProcess).toHaveBeenCalledOnce();
+ });
+
+ it.each([boundedGrant, legacyGrant])('enforces the saved $timeLimitSeconds second deadline without renewing a stuck child', async launchGrant => {
const kill = vi.fn();
const h = setup({ kill, cleanupGroup: async () => false });
await h.manager.register('agent-example', launchGrant);
diff --git a/server/lib/securityScanEvidence.js b/server/lib/securityScanEvidence.js
index 9db0f2ea95..70659119a9 100644
--- a/server/lib/securityScanEvidence.js
+++ b/server/lib/securityScanEvidence.js
@@ -11,9 +11,10 @@ export const securityScanEvidenceSchema = z.object({
model: z.string().regex(/^[a-zA-Z0-9_.:-]{1,100}$/).nullable(),
effort: z.enum(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']).nullable(),
auth: z.enum(['chatgpt', 'api-key', 'unknown']),
- maxCostUsd: nullableCost,
+ maxCostUsd: z.union([nullableCost, z.literal('unlimited')]),
estimatedCostUsd: nullableCost,
- timeLimitSeconds: z.number().int().nonnegative().nullable(),
+ // Explicit unlimited values survive JSON; null still means unknown, zero is zero.
+ timeLimitSeconds: z.union([z.number().int().nonnegative().nullable(), z.literal('unlimited')]),
exitCode: z.number().int().nullable(),
artifacts: z.object({ findings: z.boolean().nullable(), coverage: z.boolean().nullable() }).strict(),
cleanup: z.enum(['not-needed', 'confirmed', 'unconfirmed']).optional(),
@@ -27,12 +28,9 @@ export const securityScanEvidenceSchema = z.object({
}).strict().optional(),
}).strict().refine(value => value.status !== 'completed' || value.exitCode === 0);
-// New dispatches receive this server-owned policy. The cost cap bounds the
-// scanner's short-context API-equivalent estimate, not billing or subscription quota.
-const NEW_SCAN_LIMITS = Object.freeze({ maxCostUsd: 25, timeLimitSeconds: 1200 });
-// Allow the longest grant to expire and finish process-group cleanup before
-// the server-to-runner exchange gives up. This does not extend a saved grant.
-export const SECURITY_SCAN_REQUEST_TIMEOUT_MS = (NEW_SCAN_LIMITS.timeLimitSeconds + 10) * 1000;
+// New dispatches impose neither an estimate cap nor an elapsed-time deadline.
+// Provider quota, rate and safety limits remain in force.
+const NEW_SCAN_LIMITS = Object.freeze({ maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' });
const legacySecurityScanGrantSchema = z.object({
model: z.string().regex(/^[a-zA-Z0-9_.:-]{1,100}$/).nullable(),
effort: z.enum(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']).nullable(),
@@ -42,12 +40,13 @@ const legacySecurityScanGrantSchema = z.object({
}).strict();
// Saved grants retain their original pair of limits; accepting them must never
-// upgrade an existing attempt. Neither policy is accepted from a scan request.
+// upgrade an existing attempt. No policy is accepted from a scan request.
export const securityScanGrantSchema = z.union([
legacySecurityScanGrantSchema.extend({
maxCostUsd: z.literal(NEW_SCAN_LIMITS.maxCostUsd),
timeLimitSeconds: z.literal(NEW_SCAN_LIMITS.timeLimitSeconds),
}),
+ legacySecurityScanGrantSchema.extend({ maxCostUsd: z.literal(25), timeLimitSeconds: z.literal(1200) }),
legacySecurityScanGrantSchema,
]);
diff --git a/server/lib/securityScanEvidence.test.js b/server/lib/securityScanEvidence.test.js
index 362162fec1..c37958e4e3 100644
--- a/server/lib/securityScanEvidence.test.js
+++ b/server/lib/securityScanEvidence.test.js
@@ -11,6 +11,9 @@ const parse = value => parseSecurityScanEvidence(`Delivered the requested change
it('retains timeout evidence and distinguishes a zero budget from unknown values', () => {
expect(parse(report)).toEqual({ ...report, source: 'agent-report' });
expect(parse({ ...report, maxCostUsd: null }).maxCostUsd).toBeNull();
+ const unlimited = { ...report, maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' };
+ expect(parseRunnerSecurityScanEvidence({ ...JSON.parse(JSON.stringify(unlimited)), source: 'runner', sequence: 1 })).toEqual({ ...unlimited, source: 'runner', sequence: 1 });
+ expect(parse({ ...report, maxCostUsd: undefined })).toBeNull();
});
it('rejects fabricated completion, ambiguous reports and fields that could disclose private data', () => {
@@ -22,15 +25,17 @@ it('rejects fabricated completion, ambiguous reports and fields that could discl
});
it('derives scanner pins from effective argv and refuses conflicting or implicit defaults', () => {
- expect(securityScanGrantFromArgs(['--model', 'saved-model', '-c', 'model_reasoning_effort="high"'])).toEqual({ model: 'saved-model', effort: 'high', auth: 'chatgpt', maxCostUsd: 25, timeLimitSeconds: 1200 });
+ expect(securityScanGrantFromArgs(['--model', 'saved-model', '-c', 'model_reasoning_effort="high"'])).toEqual({ model: 'saved-model', effort: 'high', auth: 'chatgpt', maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' });
expect(securityScanGrantFromArgs(['--model=selected-model', '--config=model="another-model"', '-cmodel_reasoning_effort=low'])).toMatchObject({ model: null, effort: 'low' });
- expect(securityScanGrantFromArgs([])).toEqual({ model: null, effort: null, auth: 'chatgpt', maxCostUsd: 25, timeLimitSeconds: 1200 });
+ expect(securityScanGrantFromArgs([])).toEqual({ model: null, effort: null, auth: 'chatgpt', maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' });
});
it('preserves legacy grants and rejects mixed limits or authentication overrides', () => {
const legacy = { model: 'saved-model', effort: 'medium', auth: 'chatgpt', maxCostUsd: 2, timeLimitSeconds: 180 };
expect(securityScanGrantSchema.parse(legacy)).toEqual(legacy);
- for (const override of [{ maxCostUsd: 25 }, { timeLimitSeconds: 1200 }, { maxCostUsd: 100, timeLimitSeconds: 3600 }, { auth: 'api-key' }, { auth: 'auto' }]) {
+ const bounded = { ...legacy, maxCostUsd: 25, timeLimitSeconds: 1200 };
+ expect(securityScanGrantSchema.parse(bounded)).toEqual(bounded);
+ for (const override of [{ maxCostUsd: 25 }, { maxCostUsd: 'unlimited' }, { timeLimitSeconds: 'unlimited' }, { maxCostUsd: null, timeLimitSeconds: null }, { maxCostUsd: undefined, timeLimitSeconds: undefined }, { maxCostUsd: 0, timeLimitSeconds: 0 }, { timeLimitSeconds: 0 }, { timeLimitSeconds: 1200 }, { maxCostUsd: 25, timeLimitSeconds: null }, { maxCostUsd: 100, timeLimitSeconds: 3600 }, { auth: 'api-key' }, { auth: 'auto' }]) {
expect(securityScanGrantSchema.safeParse({ ...legacy, ...override }).success).toBe(false);
}
});
diff --git a/server/routes/securityScan.test.js b/server/routes/securityScan.test.js
index 6a2ea526a5..adc825fdad 100644
--- a/server/routes/securityScan.test.js
+++ b/server/routes/securityScan.test.js
@@ -41,7 +41,7 @@ it('requires existing host authority before consuming a scanner grant', async ()
});
it.each([
- ['model', 'another-model'], ['effort', 'high'], ['maxCostUsd', 100], ['timeLimitSeconds', 3600], ['auth', 'api-key'],
+ ['model', 'another-model'], ['effort', 'high'], ['maxCostUsd', 100], ['timeLimitSeconds', 3600], ['timeLimitSeconds', 'unlimited'], ['maxCostUsd', 'unlimited'], ['auth', 'api-key'],
])('rejects a %s override at the public request boundary', async (field, value) => {
const result = await request(appFor('127.0.0.1')).post(endpoint).send({ ...input, [field]: value });
expect(result.status).toBe(400);
diff --git a/server/services/agentManagement.claimResume.test.js b/server/services/agentManagement.claimResume.test.js
index 59b004131e..dcfbc14d51 100644
--- a/server/services/agentManagement.claimResume.test.js
+++ b/server/services/agentManagement.claimResume.test.js
@@ -207,7 +207,7 @@ it('pins a security scanner grant to effective CLI settings and registers aliase
blockAndBail: message => { throw new Error(JSON.stringify(message)); }, cleanupOnError: message => { throw new Error(message); },
}, { spawnViaRunner });
expect(spawnViaRunner).toHaveBeenCalledWith('agent-scanner', task, expect.objectContaining({
- securityScanGrant: { model: 'saved-model', effort: 'high', auth: 'chatgpt', maxCostUsd: 25, timeLimitSeconds: 1200 },
+ securityScanGrant: { model: 'saved-model', effort: 'high', auth: 'chatgpt', maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' },
}));
expect(updateAgent).toHaveBeenCalledWith('agent-scanner', { metadata: expect.objectContaining({ taskAnalysisType: 'security', securityScanGrant: expect.any(Object) }) });
});
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index cf674e7f68..08077a6750 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -697,6 +697,8 @@ describe('buildLightContextPrompt', () => {
expect(prompt.systemPrompt).toContain('subscription ChatGPT authentication');
expect(prompt.systemPrompt).toContain('saved grants retain their original limits');
expect(prompt.systemPrompt).toContain('Wait for the single request to finish');
+ expect(prompt.systemPrompt).toContain('--max-time 0');
+ expect(prompt.systemPrompt).toContain('no PortOS estimate cap or elapsed-time deadline');
expect(prompt.systemPrompt).not.toContain('npx --yes');
expect(prompt.systemPrompt).toContain('deliver supported findings even when another probe is blocked');
expect(prompt.systemPrompt).toContain('## Completion (No Code Output)');
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 0602944aac..b986b5590a 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -364,6 +364,7 @@ export async function spawnTuiAgent({
runId,
model,
provider,
+ securityScanGrant,
prompt,
tuiConfig,
cwd,
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index ef90d37dd1..21a351e6a2 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -733,6 +733,7 @@ describe('spawnTuiAgent runtime', () => {
prOpenedBy: overrides.prOpenedBy ?? stampPrOpenedBy(overrides, task, provider),
leanMode: overrides.leanMode ?? false,
useDurableRunner: overrides.useDurableRunner ?? false,
+ securityScanGrant: overrides.securityScanGrant ?? null,
safetyProfile: overrides.safetyProfile ?? null,
...helpers,
});
@@ -2064,6 +2065,35 @@ describe('spawnTuiAgent runtime', () => {
// module-private), so each nudge lands within a tick of its threshold.
const SIGNAL_POLL_MS = 5000;
+ it.each([
+ { maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited', nudges: false },
+ { maxCostUsd: 2, timeLimitSeconds: 180, nudges: true },
+ ])('honors a trusted $timeLimitSeconds scanner grant through a quiet outer audit', async ({ nudges, ...limits }) => {
+ runSpawn({ securityScanGrant: { model: 'example-model', effort: 'medium', auth: 'chatgpt', ...limits } });
+ await flushMicrotasks();
+ await capturedOnData(Buffer.from('Codex booting...\n' + CODEX_COMPOSER));
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(pasteCount()).toBe(1);
+ await capturedOnData(Buffer.from('do the thing\n'));
+ await vi.advanceTimersByTimeAsync(4000);
+ // Both scanner work and the later source/fix/test phase can be silent.
+ await capturedOnData(Buffer.from('Reviewing source and validating fixes.\n'));
+ vi.mocked(shellService.pasteToSession).mockClear();
+ vi.mocked(shellService.writeToSession).mockClear();
+ await vi.advanceTimersByTimeAsync(nudges ? STALL_NUDGE_IDLE_MS + SIGNAL_POLL_MS : 2 * 60 * 60 * 1000);
+ if (nudges) {
+ expect(shellService.pasteToSession).toHaveBeenCalledWith(SESSION_ID, STALL_NUDGE_TEXT, expect.anything());
+ } else {
+ expect(shellService.pasteToSession).not.toHaveBeenCalled();
+ expect(shellService.writeToSession).not.toHaveBeenCalled();
+ expect(cosAgentLifecycle.updateAgent).not.toHaveBeenCalledWith('agent-1', { metadata: { phase: 'stalled' } });
+ }
+ expect(shellService.killSession).not.toHaveBeenCalled();
+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();
+ await capturedOnExit({ exitCode: 1, killed: false });
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledOnce();
+ });
+
// ── Stalled session: the turn just ended, with the task unfinished ─────────
// agent-bb3061af (2026-09-17): the run finished its /simplify pass, printed
// "Next: /do:pr", ended its turn and sat at an idle composer. Nothing was on
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index 132d9bc713..28bf645788 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -477,6 +477,7 @@ export function createTuiSessionController({
runId,
model,
provider,
+ securityScanGrant,
prompt,
tuiConfig,
cwd,
@@ -1914,7 +1915,10 @@ export function createTuiSessionController({
// network call takes, non-terminal the whole time, and it may yet paste a
// nudge of its own. And `promptSubmittedAt`, because before the prompt is
// in the promptTimer owns delivery — silence there is startup, not a stall.
- if (sessionPhase !== 'running' || !promptSubmittedAt) return;
+ // A no-deadline security audit may be quiet during the scan AND its later
+ // validation/fix work. Silence alone must not inject another turn or badge
+ // it as stalled. Explicit provider failures and terminal signals above stay active.
+ if (sessionPhase !== 'running' || !promptSubmittedAt || securityScanGrant?.timeLimitSeconds === 'unlimited') return;
const stalled = stallNudgeGate.takeNudge(now, lastOutputAt);
if (!stalled) return;
// Read the sentinel here rather than on every tick: its watcher polls on its
diff --git a/server/services/agentTuiSpawning/sessionController.test.js b/server/services/agentTuiSpawning/sessionController.test.js
index 08cf1d3d1b..033e0ff59a 100644
--- a/server/services/agentTuiSpawning/sessionController.test.js
+++ b/server/services/agentTuiSpawning/sessionController.test.js
@@ -45,6 +45,7 @@ function makeController({
provider = { id: 'codex-tui', name: 'Codex' },
tuiConfig = TUI_CONFIG,
prompt = 'do the work',
+ securityScanGrant = null,
sentinelRead = async () => sentinelSummary ?? '',
} = {}) {
// A DISTINCT closer per arm: the merge-gate case below has to tell the
@@ -75,6 +76,7 @@ function makeController({
runId: 'run-1',
model: 'gpt-5-codex',
provider,
+ securityScanGrant,
prompt,
tuiConfig,
cwd: '/tmp/workspace',
@@ -285,7 +287,7 @@ describe('Codex terminal model-access rejection (#9319)', () => {
};
it('stops all recovery when a trusted scanner refusal arrives before the outer TUI exits', async () => {
- const { controller, ...seams } = await submitted();
+ const { controller, ...seams } = await submitted({ securityScanGrant: { model: 'example-model', effort: 'medium', auth: 'chatgpt', maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' } });
seams.write.mockClear();
seams.paste.mockClear();
await controller.refuseScanner();
diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.js
index cd61834874..2335bfd7f8 100644
--- a/server/services/cosRunnerClient.js
+++ b/server/services/cosRunnerClient.js
@@ -10,7 +10,6 @@ import { io } from 'socket.io-client';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
import { readResponseJson } from '../lib/readResponseJson.js';
import { PORTS } from '../lib/ports.js';
-import { SECURITY_SCAN_REQUEST_TIMEOUT_MS } from '../lib/securityScanEvidence.js';
const COS_RUNNER_URL = process.env.COS_RUNNER_URL || `http://localhost:${PORTS.COS}`;
@@ -455,14 +454,14 @@ export async function spawnAgentViaRunner(options) {
export async function requestSecurityScanViaRunner(agentId, { input, stop = false } = {}) {
const path = `/agents/${encodeURIComponent(agentId)}/security-scan${stop ? '/stop' : ''}`;
- // A scanner may be silent through its entire grant. Keep undici's default
- // five-minute ceiling below this path from preempting our bounded exchange.
+ // A scanner may validly stay silent indefinitely. Its owned process lifecycle
+ // settles this request; neither fetch nor undici may impose an elapsed/idle cap.
const dispatcher = input ? (await import('../lib/aiToolkit/internal/streamTransport.js')).streamTransportDispatcher() : null;
const response = await fetchWithTimeout(`${COS_RUNNER_URL}${path}`, {
method: input || stop ? 'POST' : 'GET',
...(dispatcher ? { dispatcher } : {}),
...(input ? { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) } : {}),
- }, input ? SECURITY_SCAN_REQUEST_TIMEOUT_MS : 15000);
+ }, input ? 0 : 15000);
const result = await readRunnerJson(response);
if (!response.ok) throw Object.assign(new Error(result.error || 'Scanner runner unavailable'), { status: response.status });
return result;
diff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.js
index 52e9cba323..6b53a457a8 100644
--- a/server/services/cosRunnerClient.test.js
+++ b/server/services/cosRunnerClient.test.js
@@ -60,9 +60,9 @@ describe('cosRunnerClient', () => {
vi.clearAllMocks();
});
- it('keeps one silent scanner request open through its grant and cleanup without shorter transport ceilings', async () => {
+ it('keeps one silent scanner request open without elapsed or transport inactivity ceilings', async () => {
const { fetchWithTimeout: actualFetch } = await vi.importActual('../lib/fetchWithTimeout.js');
- const evidence = { status: 'time-limit', timeLimitSeconds: 1200, cleanup: 'confirmed' };
+ const evidence = { status: 'interrupted', timeLimitSeconds: 'unlimited', cleanup: 'confirmed' };
let finish;
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
fetchWithTimeout.mockImplementationOnce(actualFetch);
@@ -72,8 +72,8 @@ describe('cosRunnerClient', () => {
await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalledOnce());
const options = fetchSpy.mock.calls[0][1];
expect(options.dispatcher).toBe(streamTransportDispatcher());
- expect(fetchWithTimeout).toHaveBeenCalledWith(expect.stringContaining('/security-scan'), expect.any(Object), 1210000);
- await vi.advanceTimersByTimeAsync(1205000);
+ expect(fetchWithTimeout).toHaveBeenCalledWith(expect.stringContaining('/security-scan'), expect.any(Object), 0);
+ await vi.advanceTimersByTimeAsync(48 * 60 * 60 * 1000);
expect(options.signal.aborted).toBe(false);
finish(mockResponse(true, { evidence }));
expect(await pending).toEqual({ evidence });
@@ -84,6 +84,17 @@ describe('cosRunnerClient', () => {
}
});
+ it('surfaces a broken scanner connection once while status and Stop retain bounded waits', async () => {
+ fetchWithTimeout.mockRejectedValueOnce(new Error('synthetic connection loss'));
+ await expect(requestSecurityScanViaRunner('agent-example', { input: { prompt: 'Audit source.', paths: ['.'] } })).rejects.toThrow('synthetic connection loss');
+ expect(fetchWithTimeout).toHaveBeenCalledOnce();
+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { evidence: { status: 'interrupted' } }));
+ await requestSecurityScanViaRunner('agent-example');
+ await requestSecurityScanViaRunner('agent-example', { stop: true });
+ expect(fetchWithTimeout).toHaveBeenNthCalledWith(2, expect.stringContaining('/security-scan'), { method: 'GET' }, 15000);
+ expect(fetchWithTimeout).toHaveBeenNthCalledWith(3, expect.stringContaining('/security-scan/stop'), { method: 'POST' }, 15000);
+ });
+
// ===========================================================================
// initCosRunnerConnection
// ===========================================================================
diff --git a/server/services/promptSections/securityAudit.js b/server/services/promptSections/securityAudit.js
index 5bcf866d5a..5f5bc8fada 100644
--- a/server/services/promptSections/securityAudit.js
+++ b/server/services/promptSections/securityAudit.js
@@ -20,8 +20,8 @@ After reading the target threat model and completing repository-wide discovery,
{ "prompt": "The actual threat model, selected audit area and report-only restrictions", "paths": ["relative/source/path"], "knowledgeBase": ["AGENTS.md"] }
Choose real workspace-relative files; include available architecture/security documents in knowledgeBase. Keep outer issue-filing and completion commands out of the scanner prompt.
-Request one scanner execution: \`${command} --data-binary @<private-request-file>\`.
-The runner owns the installed Codex Security CLI and enforces this run's saved grant: resolved model and effort, subscription ChatGPT authentication, an API-equivalent short-context estimate cap and a process-group deadline. Read the actual limits from runner evidence; saved grants retain their original limits. Those settings cannot be changed in the request. Wait for the single request to finish; a quiet response does not authorize another execution. No installation, API-key fallback, additional workers, patching or publication is permitted. Do not invoke a separate CLI, SDK or cloud scan: an unavailable runner/installation/model is a visible limitation, not permission for a different execution path.
+Request one scanner execution: \`${command} --max-time 0 --data-binary @<private-request-file>\`.
+The runner owns the installed Codex Security CLI and enforces this run's saved grant: resolved model and effort, subscription ChatGPT authentication, saved limits. New grants explicitly record unlimited for both maxCostUsd and timeLimitSeconds: no PortOS estimate cap or elapsed-time deadline. Read the actual limits from runner evidence; saved grants retain their original limits. Unknown or absent evidence is not proof of unlimited execution. Provider quota, rate and safety limits still apply. Those settings cannot be changed in the request. Wait for the single request to finish; a quiet response does not authorize another execution. No installation, API-key fallback, additional workers, patching or publication is permitted. Do not invoke a separate CLI, SDK or cloud scan: an unavailable runner/installation/model is a visible limitation, not permission for a different execution path.
The response contains trusted runner evidence plus a private artifactDirectory. Read any saved findings/coverage there, challenge reachability against callers/tests/history, and preserve this task's remediation/file-issues mode and delivery requirements. Only an explicit runner status of invalid-input permits correction: no scanner has launched. Use preflight.lastError's field and zero-based index to locate the bad input, verify the replacement in the workspace, and submit corrected paths through this same endpoint. Concurrent requests share the current result. Do not resubmit after any other result or transport error; the runner retains one execution and its diagnostics independently of your completion. A stopped or restarted grant cannot be reopened. Finish permitted source inspection and deliver supported findings even when another probe is blocked.