evolcore 0.0.40 → 0.0.41-test.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/claude-runner.js +21 -106
  5. package/dist/agents/codex-runner.js +451 -231
  6. package/dist/agents/ecagent-runner.js +30 -11
  7. package/dist/agents/gemini-runner.js +26 -6
  8. package/dist/agents/runner-types.js +11 -3
  9. package/dist/aun/ability-device-routing.js +26 -0
  10. package/dist/aun/aid/client.js +1 -1
  11. package/dist/aun/group/identity.js +8 -0
  12. package/dist/aun/msg/managed-operation.js +4 -4
  13. package/dist/aun/msg/p2p.js +27 -7
  14. package/dist/aun/storage/download.js +30 -0
  15. package/dist/aun/storage/index.js +14 -6
  16. package/dist/channels/aun.js +33 -4
  17. package/dist/channels/daemon.js +24 -4
  18. package/dist/cli/agent-command.js +2 -0
  19. package/dist/cli/agent-create.js +98 -19
  20. package/dist/cli/agent.js +10 -3
  21. package/dist/cli/aun-commands.js +82 -22
  22. package/dist/cli/daemon-commands.js +19 -10
  23. package/dist/cli/index.js +1 -1
  24. package/dist/cli/restart-monitor.js +17 -0
  25. package/dist/cli/session-command.js +128 -13
  26. package/dist/cli/stats.js +60 -4
  27. package/dist/cli/trigger-command.js +2 -2
  28. package/dist/config/access-policy.js +2 -0
  29. package/dist/config/config-operation-service.js +17 -6
  30. package/dist/config/gateway-config.js +1 -1
  31. package/dist/config/peer-role-resolver.js +10 -8
  32. package/dist/core/agent-application-service.js +11 -1
  33. package/dist/core/agent-ipc-registration.js +4 -0
  34. package/dist/core/auth/agent-delegation.js +80 -5
  35. package/dist/core/auth/authorization-audit.js +20 -3
  36. package/dist/core/auth/operation-catalog.js +8 -0
  37. package/dist/core/command/agent-control.js +91 -12
  38. package/dist/core/command/command-handler.js +57 -46
  39. package/dist/core/command/connect-menu.js +23 -2
  40. package/dist/core/command/menu-catalog.js +1 -0
  41. package/dist/core/command/menu-handler.js +38 -101
  42. package/dist/core/command/menu-protocol.js +9 -2
  43. package/dist/core/command/role-menu.js +7 -6
  44. package/dist/core/command/slash-gate.js +13 -10
  45. package/dist/core/command/slash-handler.js +34 -98
  46. package/dist/core/event-catalog.js +15 -0
  47. package/dist/core/ipc-registration.js +18 -1
  48. package/dist/core/memory/consolidation-trigger.js +1 -1
  49. package/dist/core/message/aun-ipc-sender.js +26 -5
  50. package/dist/core/message/aun-request-registry.js +97 -3
  51. package/dist/core/message/im-renderer.js +4 -0
  52. package/dist/core/message/message-admission.js +8 -4
  53. package/dist/core/message/message-bridge.js +40 -6
  54. package/dist/core/message/message-log.js +55 -0
  55. package/dist/core/message/message-queue.js +5 -5
  56. package/dist/core/message/response-engine.js +310 -136
  57. package/dist/core/model/model-catalog.js +7 -6
  58. package/dist/core/ownership/owner-resolver.js +2 -2
  59. package/dist/core/permission/ec-command-parser.js +110 -5
  60. package/dist/core/permission/tool-policy.js +28 -7
  61. package/dist/core/session/session-capsule.js +197 -0
  62. package/dist/core/session/session-manager.js +148 -14
  63. package/dist/core/session/session-mapper.js +2 -0
  64. package/dist/index.js +3 -3
  65. package/dist/ipc.js +22 -8
  66. package/dist/stats/budget.js +1 -1
  67. package/dist/stats/db.js +15 -0
  68. package/dist/stats/index.js +2 -2
  69. package/dist/stats/price-resolver.js +304 -5
  70. package/dist/stats/query.js +82 -3
  71. package/dist/stats/writer.js +38 -5
  72. package/dist/trigger/feedback.js +18 -7
  73. package/dist/trigger/manager.js +20 -3
  74. package/dist/trigger/parser.js +6 -3
  75. package/dist/trigger/patch.js +1 -1
  76. package/dist/trigger/system-definitions.js +43 -7
  77. package/dist/trigger/validation.js +13 -5
  78. package/dist/utils/error-utils.js +14 -0
  79. package/dist/utils/npm-ops.js +2 -1
  80. package/dist/utils/package-version-info.js +1 -1
  81. package/dist/utils/upgrade-jobs.js +45 -5
  82. package/kits/docs/INDEX.md +1 -1
  83. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  84. package/kits/docs/evolcore/INDEX.md +2 -1
  85. package/kits/docs/evolcore/agent-create.md +3 -2
  86. package/kits/docs/evolcore/agent.md +1 -1
  87. package/kits/docs/evolcore/config.md +1 -1
  88. package/kits/docs/evolcore/event.md +1 -0
  89. package/kits/docs/evolcore/fs.md +5 -0
  90. package/kits/docs/evolcore/menu-protocol.md +32 -0
  91. package/kits/docs/evolcore/msg.md +17 -1
  92. package/kits/docs/evolcore/session.md +14 -0
  93. package/kits/schemas/agent-config.schema.13.json +15 -0
  94. package/kits/skills/aid-ability/SKILL.md +35 -6
  95. package/kits/templates/session-capsule/recovery.md +5 -0
  96. package/kits/templates/session-capsule/renew.md +5 -0
  97. package/kits/templates/system-fragments/bootstrap.md +6 -6
  98. package/kits/templates/system-fragments/channel.md +1 -1
  99. package/package.json +3 -3
  100. package/dist/stats/billing.js +0 -215
@@ -15,15 +15,16 @@ import { catalogHash } from '../core/model/catalog-service.js';
15
15
  import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
16
16
  import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
17
17
  import { classifyError, ErrorType, getToolResultErrorText, isOutputTokenLimitError, isRetryableError } from '../utils/error-utils.js';
18
+ import { findModelSpec, getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
18
19
  import { renderActionAsText } from '../core/interaction-router.js';
19
20
  import { buildEnvelope, isInteractionSendAccepted, sendInteractionPayload } from '../core/message/message-utils.js';
20
21
  import { resolveCodexCapabilityThreadConfigForProject } from '../core/capability/capability-manager.js';
21
- import { AGENT_DELEGATION_TOKEN_ENV, CODEX_SESSION_TOKEN_ENV, hashDelegatedCommandArgv } from '../core/auth/agent-delegation.js';
22
+ import { AGENT_DELEGATION_TOKEN_ENV, CODEX_SESSION_TOKEN_ENV, hashDelegatedCommandArgv, hashDelegatedCommandSpec, parseDelegatedExecutionSpec, } from '../core/auth/agent-delegation.js';
22
23
  import { sanitizeShellExecutionEnvironment } from '../core/permission/shell-environment.js';
23
- import { classifyEvolcoreShellCommand, containsLiteralManagedTmpDirOutsideSendContent, containsUnresolvedManagedTmpDirReference, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, canonicalizeEvolcoreCommandArgv, parseCodexToolCommand, parseCodexCarrierCommand, parseLiteralShellCommand, parseCodexShellCommandArgv, resolveCodexShellCarrierArgv, parseShellApplyPatchInvocation, } from '../core/permission/ec-command-parser.js';
24
+ import { classifyEvolcoreShellCommand, containsLiteralManagedTmpDirOutsideSendContent, containsUnresolvedManagedTmpDirReference, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseLiteralShellArgv, resolveCodexShellCarrierArgv, parseShellApplyPatchInvocation, resolveCanonicalEvolcoreToolInput, serializeCanonicalEvolcoreExecutionSpec, } from '../core/permission/ec-command-parser.js';
24
25
  import { compareVersions } from '../utils/npm-ops.js';
25
- import { agentCodexTokenPath, resolvePaths, resolveRoot } from '../paths.js';
26
- import { findModelSpec } from '../stats/billing.js';
26
+ import { agentCodexTokenPath, getPackageRoot, resolvePaths, resolveRoot } from '../paths.js';
27
+ import { MAIN_CLI_BIN } from '../product.js';
27
28
  import { ensureSessionRuntimeDir, getManagedTaskTempDir } from '../cli/task-context.js';
28
29
  import { buildTranscriptTurns } from '../core/session/session-transcript.js';
29
30
  import { CodexSessionFileAdapter } from '../core/session/adapters/codex-session-file-adapter.js';
@@ -157,6 +158,22 @@ function codexItemErrorFields(item) {
157
158
  const errorDetailCode = normalizeToolErrorDetailCode(rawCode);
158
159
  return errorDetailCode ? { errorDetailCode } : {};
159
160
  }
161
+ function attachCanonicalMetadata(argv, metadata) {
162
+ const result = { argv };
163
+ for (const [key, value] of Object.entries(metadata)) {
164
+ if (value === undefined)
165
+ continue;
166
+ Object.defineProperty(result, key, {
167
+ value,
168
+ enumerable: false,
169
+ configurable: true,
170
+ });
171
+ }
172
+ return result;
173
+ }
174
+ function matchesCodexTask(identity, target) {
175
+ return identity?.taskId === target.taskId && identity.generation === target.generation;
176
+ }
160
177
  function waitForCodexOperation(operation, signal) {
161
178
  return new Promise((resolve, reject) => {
162
179
  const onAbort = () => {
@@ -421,7 +438,10 @@ export class CodexRunner {
421
438
  modelContextId;
422
439
  effort;
423
440
  activeAbortControllers = new Map();
441
+ /** Identity of the run owning each session-scoped abort controller. */
442
+ activeAbortTargets = new Map();
424
443
  activeStreams = new Map();
444
+ activeStreamTargets = new Map();
425
445
  activeSessions = new Map(); // sessionId → threadId
426
446
  /** New threads held in memory until the exact first turn is visible in the rollout. */
427
447
  provisionalSessions = new Map();
@@ -434,12 +454,14 @@ export class CodexRunner {
434
454
  threadExternalToolBoundaries = new Map();
435
455
  trackedApprovalItems = new Map();
436
456
  pendingToolDenials = new Map();
457
+ registeredSafeOutputCalls = new Map();
437
458
  pendingInterrupts = new Map();
438
459
  unconfirmedInterrupts = new Map();
439
460
  steeringTails = new Map();
440
461
  threadOperationLocks = new Map();
441
462
  queryOperations = new Map();
442
463
  activeOperationReleases = new Map();
464
+ activeOperationReleaseTargets = new Map();
443
465
  /** Last app-server client that loaded each thread, including unsubscribed threads. */
444
466
  threadSubscriptions = new Map();
445
467
  /** Ordinary sessions stay behind the EvolCore H/L filesystem guard. */
@@ -765,173 +787,62 @@ export class CodexRunner {
765
787
  }
766
788
  this.threadSubscriptions.set(threadId, { client: targetClient, state: 'subscribed' });
767
789
  }
768
- approvedLiteralEvolcoreCommand(command, managedTempDir, dialect = 'posix', expectedCredentialToken, executable) {
769
- if (/\\\$(?:TMPDIR|\{TMPDIR\})/i.test(command)
770
- && /\bec\s+fs\s+(?:cp|ls|stat|find|cat|mkdir|rm|mv|upload)\b/i.test(command)) {
771
- return { parseFailure: {
772
- issue: 'unsafe-expansion', offset: 0, tokenIndex: 0,
773
- dialect, inputLength: command.length,
774
- } };
790
+ resolveCanonicalEcApproval(toolInput, managedTempDir, expectedCredentialToken) {
791
+ const rawCommand = typeof toolInput.command === 'string' ? toolInput.command : '';
792
+ const safeOutput = this.parseSafeOutputToolInput(toolInput);
793
+ if (safeOutput) {
794
+ return attachCanonicalMetadata([...safeOutput.spec.argv], {
795
+ spec: safeOutput.spec,
796
+ executionSpec: serializeCanonicalEvolcoreExecutionSpec(safeOutput.spec),
797
+ specHash: hashDelegatedCommandSpec(safeOutput.spec) ?? undefined,
798
+ });
775
799
  }
776
- const parseOptions = {
800
+ const options = {
777
801
  allowManagedTmpDir: true,
778
- dialect,
779
802
  verifyShellExecutable: process.platform === 'win32',
780
803
  ...(managedTempDir ? { managedTempDir } : {}),
781
804
  ...(expectedCredentialToken !== undefined ? { expectedCredentialToken } : {}),
782
805
  };
783
- const classification = classifyEvolcoreShellCommand(command, parseOptions);
784
- if (classification.kind === 'bounded-output') {
785
- return { argv: canonicalizeEvolcoreCommandArgv(classification.command.argv) };
786
- }
787
- // Keep the approval/delegation parser aligned with the preflight parser:
788
- // the session-managed `$TMPDIR` token is a permitted EC path reference.
789
- const parsed = executable
790
- ? parseCodexCarrierCommand({ command, dialect, executable }, parseOptions)
791
- : dialect === 'powershell'
792
- ? parseCodexCarrierCommand({ command, dialect }, parseOptions)
793
- : parseLiteralShellCommand(command, parseOptions);
794
- if (!parsed.ok)
795
- return { parseFailure: parsed };
796
- if (normalizeEvolcoreCommandArgv(parsed.argv)[0] !== 'ec')
806
+ const resolved = resolveCanonicalEvolcoreToolInput(toolInput, options);
807
+ if (resolved.kind === 'not-ec')
797
808
  return {};
798
- if (containsLiteralManagedTmpDirOutsideSendContent(parsed.argv)) {
809
+ if (resolved.kind === 'invalid')
810
+ return { parseFailure: resolved.failure };
811
+ const spec = resolved.spec;
812
+ if (containsLiteralManagedTmpDirOutsideSendContent(spec.argv)
813
+ || containsUnresolvedManagedTmpDirReference(spec.argv)) {
799
814
  return { parseFailure: {
800
- issue: 'unsafe-expansion',
801
- offset: 0,
802
- tokenIndex: 0,
803
- dialect: dialect ?? 'posix',
804
- inputLength: command.length,
815
+ issue: 'unsafe-expansion', offset: 0, tokenIndex: 0,
816
+ dialect: spec.dialect, inputLength: rawCommand.length,
817
+ canonicalizationStage: 'managed-temp-argv',
818
+ wrapper: spec.wrapper,
805
819
  } };
806
820
  }
807
- return {
808
- argv: canonicalizeEvolcoreCommandArgv(parsed.argv),
809
- ...(parsed.credentialToken ? { credentialToken: parsed.credentialToken } : {}),
810
- };
811
- }
812
- resolveCanonicalEcApproval(toolInput, managedTempDir, expectedCredentialToken) {
813
- const rawCommand = typeof toolInput.command === 'string' ? toolInput.command : '';
814
- if (/\\\$(?:TMPDIR|\{TMPDIR\})/i.test(rawCommand)
815
- && /\bec\s+fs\s+(?:cp|ls|stat|find|cat|mkdir|rm|mv|upload)\b/i.test(rawCommand)
816
- && !/\bec\s+(?:msg|group)\s+send\b/i.test(rawCommand)
817
- && !/\bec\s+trigger\s+(?:create|set|update)\b/i.test(rawCommand)) {
821
+ const unresolvedOutput = spec.outputPath?.startsWith('$TMPDIR')
822
+ && (!managedTempDir || !path.isAbsolute(managedTempDir));
823
+ if (unresolvedOutput) {
818
824
  return { parseFailure: {
819
825
  issue: 'unsafe-expansion', offset: 0, tokenIndex: 0,
820
- dialect: 'posix', inputLength: rawCommand.length,
826
+ dialect: spec.dialect, inputLength: rawCommand.length,
827
+ canonicalizationStage: 'managed-temp-resolution',
828
+ wrapper: spec.wrapper,
829
+ redirectDetected: true,
830
+ managedTempPath: true,
831
+ managedTempResolved: false,
821
832
  } };
822
833
  }
823
- const explicitArgv = Array.isArray(toolInput.commandArgv)
824
- && toolInput.commandArgv.every(value => typeof value === 'string')
825
- ? toolInput.commandArgv
826
- : undefined;
827
- if (explicitArgv && normalizeEvolcoreCommandArgv(explicitArgv)[0] === 'ec') {
828
- if (explicitArgv.some(value => value.includes('\0'))) {
829
- return { parseFailure: {
830
- issue: 'invalid-control-char', offset: 0,
831
- tokenIndex: explicitArgv.findIndex(value => value.includes('\0')),
832
- dialect: 'posix', inputLength: 0,
833
- } };
834
- }
835
- return containsLiteralManagedTmpDirOutsideSendContent(explicitArgv) || containsUnresolvedManagedTmpDirReference(explicitArgv)
836
- ? { parseFailure: { issue: 'unsafe-expansion', offset: 0, tokenIndex: 0, dialect: 'posix', inputLength: 0 } }
837
- : { argv: canonicalizeEvolcoreCommandArgv(explicitArgv) };
838
- }
839
- const explicitCarrier = explicitArgv
840
- ? resolveCodexShellCarrierArgv(explicitArgv)
841
- : undefined;
842
- if (explicitCarrier !== undefined) {
843
- return this.approvedLiteralEvolcoreCommand(explicitCarrier.command, managedTempDir, explicitCarrier.dialect, expectedCredentialToken, explicitCarrier.executable);
844
- }
845
- if (explicitArgv?.length === 1 && typeof explicitArgv[0] === 'string') {
846
- const parsed = parseCodexToolCommand({ commandArgv: explicitArgv }, {
847
- allowManagedTmpDir: true,
848
- verifyShellExecutable: process.platform === 'win32',
849
- ...(managedTempDir ? { managedTempDir } : {}),
850
- ...(expectedCredentialToken !== undefined ? { expectedCredentialToken } : {}),
851
- });
852
- if (parsed.ok && parsed.argv[0] === 'ec') {
853
- return containsLiteralManagedTmpDirOutsideSendContent(parsed.argv) || containsUnresolvedManagedTmpDirReference(parsed.argv)
854
- ? { parseFailure: { issue: 'unsafe-expansion', offset: 0, tokenIndex: 0, dialect: 'powershell', inputLength: explicitArgv[0].length } }
855
- : { argv: canonicalizeEvolcoreCommandArgv(parsed.argv) };
856
- }
857
- if (!parsed.ok)
858
- return { parseFailure: parsed };
859
- }
860
- if (hasCodexCmdCarrierEcIntent(toolInput)) {
861
- const parsed = parseCodexToolCommand(toolInput, {
862
- verifyShellExecutable: process.platform === 'win32',
863
- ...(expectedCredentialToken !== undefined ? { expectedCredentialToken } : {}),
864
- });
865
- if (!parsed.ok)
866
- return { parseFailure: parsed };
867
- if (parsed.argv[0] === 'ec') {
868
- return containsLiteralManagedTmpDirOutsideSendContent(parsed.argv) || containsUnresolvedManagedTmpDirReference(parsed.argv)
869
- ? { parseFailure: {
870
- issue: 'unsafe-expansion', offset: 0, tokenIndex: 0,
871
- dialect: 'cmd', inputLength: 0,
872
- } }
873
- : {
874
- argv: canonicalizeEvolcoreCommandArgv(parsed.argv),
875
- ...(parsed.credentialToken ? { credentialToken: parsed.credentialToken } : {}),
876
- };
877
- }
878
- const command = typeof toolInput.command === 'string' ? toolInput.command : '';
879
- const classification = classifyEvolcoreShellCommand(command, { dialect: 'cmd' });
880
- return {
881
- parseFailure: {
882
- issue: classification.kind === 'composite' ? classification.issue : 'shell-composition',
883
- offset: 0,
884
- tokenIndex: 0,
885
- dialect: 'cmd',
886
- inputLength: command.length,
887
- },
888
- };
889
- }
890
- const command = typeof toolInput.command === 'string' ? toolInput.command : '';
891
- const canonicalCommand = parseCodexShellCommandArgv(command, {
892
- allowManagedTmpDir: true,
893
- verifyShellExecutable: process.platform === 'win32',
894
- ...(managedTempDir ? { managedTempDir } : {}),
895
- ...(expectedCredentialToken !== undefined ? { expectedCredentialToken } : {}),
896
- });
897
- if (canonicalCommand?.[0] === 'ec') {
898
- return containsLiteralManagedTmpDirOutsideSendContent(canonicalCommand) || containsUnresolvedManagedTmpDirReference(canonicalCommand)
899
- ? { parseFailure: {
900
- issue: 'unsafe-expansion',
901
- offset: 0,
902
- tokenIndex: 0,
903
- dialect: 'posix',
904
- inputLength: command.length,
905
- } }
906
- : { argv: canonicalizeEvolcoreCommandArgv(canonicalCommand) };
907
- }
908
- const outer = parseLiteralShellCommand(command, {
909
- allowManagedTmpDir: true,
910
- ...(managedTempDir ? { managedTempDir } : {}),
834
+ return attachCanonicalMetadata(spec.argv, {
835
+ spec,
836
+ ...(spec.wrapper !== 'literal' ? {
837
+ executionSpec: serializeCanonicalEvolcoreExecutionSpec(spec),
838
+ specHash: hashDelegatedCommandSpec(spec) ?? undefined,
839
+ } : {}),
840
+ ...(resolved.credentialToken ? { credentialToken: resolved.credentialToken } : {}),
911
841
  });
912
- if (!outer.ok) {
913
- const classification = classifyEvolcoreShellCommand(command, {
914
- allowManagedTmpDir: true,
915
- ...(managedTempDir ? { managedTempDir } : {}),
916
- });
917
- if (classification.kind === 'bounded-output'
918
- && normalizeEvolcoreCommandArgv(classification.command.argv)[0] === 'ec') {
919
- const argv = classification.command.argv;
920
- return containsLiteralManagedTmpDirOutsideSendContent(argv) || containsUnresolvedManagedTmpDirReference(argv)
921
- ? { parseFailure: {
922
- issue: 'unsafe-expansion',
923
- offset: 0,
924
- tokenIndex: 0,
925
- dialect: 'posix',
926
- inputLength: command.length,
927
- } }
928
- : { argv: canonicalizeEvolcoreCommandArgv(argv) };
929
- }
930
- return { parseFailure: outer };
931
- }
932
- return {};
933
842
  }
934
843
  isManagedEvolcoreCommandIntent(toolInput) {
844
+ if (this.parseSafeOutputToolInput(toolInput))
845
+ return true;
935
846
  if (Array.isArray(toolInput.commandArgv)) {
936
847
  const rawArgv = toolInput.commandArgv;
937
848
  if (!rawArgv.every(value => typeof value === 'string'))
@@ -955,21 +866,71 @@ export class CodexRunner {
955
866
  const command = typeof toolInput.command === 'string' ? toolInput.command : '';
956
867
  return classifyEvolcoreShellCommand(command).kind !== 'none';
957
868
  }
958
- armApprovedDelegationCommand(sessionId, argv, approvalId) {
869
+ armApprovedDelegationCommand(sessionId, argv, approvalId, specHash, executionSpec) {
959
870
  const threadId = this.activeSessions.get(sessionId) ?? this.provisionalSessions.get(sessionId);
960
871
  const sessionToken = threadId ? this.ensureThreadCredentialLoaded(threadId) : undefined;
961
- const commandHash = hashDelegatedCommandArgv(argv);
872
+ const commandHash = executionSpec
873
+ ? hashDelegatedCommandArgv(executionSpec.argv, executionSpec)
874
+ : hashDelegatedCommandArgv(argv);
962
875
  const arm = this.permissionContexts.get(sessionId)?.armApprovedDelegationCommand;
963
876
  if (!sessionToken || !commandHash || !arm)
964
877
  return false;
965
878
  try {
966
- return arm(sessionToken, commandHash, approvalId);
879
+ return specHash === undefined
880
+ ? arm(sessionToken, commandHash, approvalId)
881
+ : arm(sessionToken, commandHash, approvalId, specHash);
967
882
  }
968
883
  catch (error) {
969
884
  logger.warn(`[CodexRunner] delegation arm callback failed: session=${sessionId} error=${error instanceof Error ? error.message : String(error)}`);
970
885
  return false;
971
886
  }
972
887
  }
888
+ parseSafeOutputCommand(command) {
889
+ const argv = typeof command === 'string' ? parseLiteralShellArgv(command) : [...command];
890
+ if (!argv || argv.length !== 3 || argv[0] !== process.execPath)
891
+ return undefined;
892
+ const expectedHelper = path.resolve(getPackageRoot(), 'bin', 'ec-safe-output.js');
893
+ if (path.resolve(argv[1]) !== expectedHelper)
894
+ return undefined;
895
+ let payload;
896
+ try {
897
+ const parsed = JSON.parse(Buffer.from(argv[2], 'base64url').toString('utf8'));
898
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
899
+ return undefined;
900
+ payload = parsed;
901
+ }
902
+ catch {
903
+ return undefined;
904
+ }
905
+ const spec = parseDelegatedExecutionSpec(payload.executionSpec);
906
+ if (payload.v !== 3 || payload.kind !== 'ec' || !spec
907
+ || !Array.isArray(payload.argv)
908
+ || JSON.stringify(spec.argv) !== JSON.stringify([MAIN_CLI_BIN, ...payload.argv.slice(1)])
909
+ || spec.cwd !== payload.cwd
910
+ || spec.outputPath !== payload.outputPath
911
+ || !!spec.mergeStderr !== !!payload.mergeStderr
912
+ || JSON.stringify(spec.filterChain ?? []) !== JSON.stringify(payload.filterChain ?? [])
913
+ || JSON.stringify(spec.suffixArgv ?? []) !== JSON.stringify(payload.suffixArgv ?? []))
914
+ return undefined;
915
+ return { spec, argv };
916
+ }
917
+ parseSafeOutputToolInput(input) {
918
+ if (Array.isArray(input.commandArgv) && input.commandArgv.every(value => typeof value === 'string')) {
919
+ const rawArgv = input.commandArgv;
920
+ const direct = this.parseSafeOutputCommand(rawArgv);
921
+ if (direct)
922
+ return direct;
923
+ const carrier = resolveCodexShellCarrierArgv(rawArgv);
924
+ if (carrier) {
925
+ const nested = this.parseSafeOutputCommand(carrier.command);
926
+ if (nested)
927
+ return nested;
928
+ }
929
+ }
930
+ return typeof input.command === 'string'
931
+ ? this.parseSafeOutputCommand(input.command)
932
+ : undefined;
933
+ }
973
934
  sessionTokenForSession(sessionId, threadId) {
974
935
  const candidates = [
975
936
  threadId,
@@ -1327,6 +1288,12 @@ export class CodexRunner {
1327
1288
  this.resetAppServerClient();
1328
1289
  }
1329
1290
  getModel() { return this.model; }
1291
+ /** 返回当前网关 /v1/models 的价格缓存(1h TTL,stale-while-revalidate)。
1292
+ * 缺失/过期时异步触发刷新,本轮先返回旧值或 undefined(回退本地价表)。 */
1293
+ getGatewayPricing() {
1294
+ const conn = this.currentProviderConfig();
1295
+ return getSharedGatewayPricing(conn.baseUrl, conn.apiKey, conn.headers);
1296
+ }
1330
1297
  getModelCatalog() {
1331
1298
  return getRunnerCatalog('codex', this.resolvedConfig.agentAid, this.currentProviderConfig());
1332
1299
  }
@@ -1732,6 +1699,7 @@ export class CodexRunner {
1732
1699
  role: context.role,
1733
1700
  permissionMode: normalizeExecutionPermissionMode(this.chatModes.get(sessionKey) ?? this.currentMode),
1734
1701
  allowReadonlySourceDiagnostics: context.allowReadonlySourceDiagnostics === true,
1702
+ safeOutputHelperPath: path.join(getPackageRoot(), 'bin', 'ec-safe-output.js'),
1735
1703
  projectPath: preflightProjectPath,
1736
1704
  workspacePath: preflightProjectPath,
1737
1705
  });
@@ -1740,44 +1708,125 @@ export class CodexRunner {
1740
1708
  await recordPreToolUseDenial(preflight.policyCode ?? 'tool_preflight_denied', reason);
1741
1709
  return { ok: true, applicable: true, decision: 'deny', reason };
1742
1710
  }
1711
+ const updatedInput = preflight.behavior === 'allow' && preflight.input !== normalizedInput
1712
+ ? preflight.input
1713
+ : undefined;
1714
+ let safeExecutionSpec;
1715
+ if (updatedInput && preflight.behavior === 'allow' && preflight.executionSpec
1716
+ && typeof updatedInput.command === 'string') {
1717
+ const safeOutput = this.parseSafeOutputCommand(updatedInput.command);
1718
+ const key = this.safeOutputCallKey(threadId, callId);
1719
+ if (!safeOutput || !key) {
1720
+ const reason = '安全 EC 输出命令无法校验执行规格';
1721
+ await recordPreToolUseDenial('ec_execution_spec_unavailable', reason);
1722
+ return { ok: true, applicable: true, decision: 'deny', reason };
1723
+ }
1724
+ this.registeredSafeOutputCalls.set(key, {
1725
+ spec: safeOutput.spec,
1726
+ updatedArgv: safeOutput.argv,
1727
+ expiresAt: Date.now() + 30_000,
1728
+ });
1729
+ safeExecutionSpec = safeOutput.spec;
1730
+ }
1731
+ const bindSafeExecutionSpec = async () => {
1732
+ if (!safeExecutionSpec)
1733
+ return true;
1734
+ const specHash = hashDelegatedCommandSpec(safeExecutionSpec);
1735
+ const commandHash = hashDelegatedCommandArgv(safeExecutionSpec.argv, safeExecutionSpec);
1736
+ if (callId && sessionToken && specHash && commandHash
1737
+ && this.armApprovedDelegationCommand(sessionKey, safeExecutionSpec.argv, callId, specHash, safeExecutionSpec))
1738
+ return true;
1739
+ await recordPreToolUseDenial('ec_execution_spec_unavailable', '安全 EC 输出命令无法绑定到当前工具调用');
1740
+ const key = this.safeOutputCallKey(threadId, callId);
1741
+ if (key)
1742
+ this.registeredSafeOutputCalls.delete(key);
1743
+ return false;
1744
+ };
1743
1745
  // A tracked interactive thread still needs an authenticated, explicit
1744
1746
  // allow so the managed hook can fail closed when no runner matches.
1745
- if (!context.preToolUsePolicyHook)
1746
- return { ok: true, applicable: true, decision: 'allow' };
1747
+ if (!context.preToolUsePolicyHook) {
1748
+ if (!await bindSafeExecutionSpec()) {
1749
+ return { ok: true, applicable: true, decision: 'deny', reason: '安全 EC 输出命令无法绑定到当前工具调用' };
1750
+ }
1751
+ return {
1752
+ ok: true, applicable: true, decision: 'allow',
1753
+ ...(updatedInput ? { updatedInput } : {}),
1754
+ };
1755
+ }
1747
1756
  try {
1748
1757
  const result = context.preToolUsePolicyHook(toolName, normalizedInput);
1749
1758
  if (result?.block) {
1750
1759
  const policyCode = result.policyCode ?? 'session_policy_hook';
1751
1760
  const reason = result.reason ?? 'session policy denied this tool call';
1752
1761
  await recordPreToolUseDenial(policyCode, reason);
1762
+ const key = this.safeOutputCallKey(threadId, callId);
1763
+ if (key)
1764
+ this.registeredSafeOutputCalls.delete(key);
1753
1765
  if (policyCode === 'proactive_circuit_break')
1754
1766
  context.onProactiveCircuitBreak?.();
1755
1767
  return { ok: true, applicable: true, decision: 'deny', reason };
1756
1768
  }
1757
- return { ok: true, applicable: true, decision: 'allow' };
1769
+ if (!await bindSafeExecutionSpec()) {
1770
+ return { ok: true, applicable: true, decision: 'deny', reason: '安全 EC 输出命令无法绑定到当前工具调用' };
1771
+ }
1772
+ return {
1773
+ ok: true, applicable: true, decision: 'allow',
1774
+ ...(updatedInput ? { updatedInput } : {}),
1775
+ };
1758
1776
  }
1759
1777
  catch (error) {
1760
1778
  const reason = `policy hook failed: ${error instanceof Error ? error.message : String(error)}`;
1761
1779
  await recordPreToolUseDenial('pre_tool_use_hook_failed', reason);
1780
+ const key = this.safeOutputCallKey(threadId, callId);
1781
+ if (key)
1782
+ this.registeredSafeOutputCalls.delete(key);
1762
1783
  return { ok: false, applicable: true, decision: 'deny', reason };
1763
1784
  }
1764
1785
  }
1765
1786
  setPermissionGateway(gw) { this.permissionGateway = gw; }
1766
1787
  // ── Stream management (needed by MessageProcessor) ──
1767
- registerStream(key, stream) {
1788
+ registerStream(key, stream, target) {
1789
+ const currentTarget = this.activeStreamTargets.get(key);
1790
+ if (target && currentTarget && !matchesCodexTask(currentTarget, target)
1791
+ && currentTarget.generation > target.generation)
1792
+ return;
1768
1793
  this.activeStreams.set(key, stream);
1769
- }
1770
- cleanupStream(key) {
1771
- const hadController = this.activeAbortControllers.has(key);
1794
+ this.activeStreamTargets.set(key, target ?? this.activeAbortTargets.get(key));
1795
+ }
1796
+ cleanupStream(key, target) {
1797
+ const currentStreamTarget = this.activeStreamTargets.get(key);
1798
+ const currentAbortTarget = this.activeAbortTargets.get(key);
1799
+ const releaseTarget = this.activeOperationReleaseTargets.get(key);
1800
+ if (target && ((currentStreamTarget && !matchesCodexTask(currentStreamTarget, target))
1801
+ || (currentAbortTarget && !matchesCodexTask(currentAbortTarget, target))))
1802
+ return;
1803
+ if (target && this.activeOperationReleases.has(key) && !matchesCodexTask(releaseTarget, target))
1804
+ return;
1805
+ const operations = this.queryOperations.get(key);
1806
+ if (target && [...(operations ?? [])].some(operation => {
1807
+ const operationTarget = this.targetForOperation(operation);
1808
+ return operationTarget
1809
+ && operationTarget.generation > target.generation
1810
+ && !matchesCodexTask(operationTarget, target);
1811
+ }))
1812
+ return;
1813
+ const capturedController = this.activeAbortControllers.get(key);
1814
+ const capturedStream = this.activeStreams.get(key);
1815
+ const hadController = capturedController !== undefined;
1772
1816
  const hadTurn = this.activeTurns.has(key);
1773
1817
  const provisionalThread = this.provisionalSessions.get(key);
1774
1818
  const subscribedThreadId = this.activeTurns.get(key)?.threadId
1775
1819
  ?? this.activeSessions.get(key)
1776
1820
  ?? provisionalThread;
1777
1821
  const subscription = subscribedThreadId ? this.threadSubscriptions.get(subscribedThreadId) : undefined;
1778
- this.activeStreams.delete(key);
1779
- this.activeAbortControllers.delete(key);
1780
- this.pendingInterrupts.delete(key);
1822
+ if (this.activeStreams.get(key) === capturedStream) {
1823
+ this.activeStreams.delete(key);
1824
+ this.activeStreamTargets.delete(key);
1825
+ }
1826
+ if (capturedController !== undefined && this.activeAbortControllers.get(key) === capturedController) {
1827
+ this.activeAbortControllers.delete(key);
1828
+ this.activeAbortTargets.delete(key);
1829
+ }
1781
1830
  // A stale runner-start path may dispose the stream without ever entering
1782
1831
  // transformAppServerStream. Reclaim its provisional thread, but preserve
1783
1832
  // a replacement run that has already installed a new controller/turn.
@@ -1792,6 +1841,7 @@ export class CodexRunner {
1792
1841
  }
1793
1842
  if (release) {
1794
1843
  this.activeOperationReleases.delete(key);
1844
+ this.activeOperationReleaseTargets.delete(key);
1795
1845
  if (releaseAfterSubscription) {
1796
1846
  void releaseAfterSubscription.then(release, release);
1797
1847
  }
@@ -1807,6 +1857,35 @@ export class CodexRunner {
1807
1857
  const operations = this.queryOperations.get(sessionId);
1808
1858
  return !!operations && [...operations].some(operation => !taskId || operation.taskId === taskId);
1809
1859
  }
1860
+ targetForOperation(operation) {
1861
+ if (!operation.taskId || !Number.isSafeInteger(operation.generation))
1862
+ return undefined;
1863
+ return { taskId: operation.taskId, generation: operation.generation };
1864
+ }
1865
+ clearActiveController(sessionId, controller) {
1866
+ if (this.activeAbortControllers.get(sessionId) !== controller)
1867
+ return;
1868
+ this.activeAbortControllers.delete(sessionId);
1869
+ this.activeAbortTargets.delete(sessionId);
1870
+ }
1871
+ setActiveTurn(sessionId, turn) {
1872
+ const current = this.activeTurns.get(sessionId);
1873
+ if (current?.generation !== undefined && turn.generation !== undefined
1874
+ && current.generation > turn.generation)
1875
+ return;
1876
+ this.activeTurns.set(sessionId, turn);
1877
+ }
1878
+ clearActiveStream(sessionId, target) {
1879
+ if (target && !matchesCodexTask(this.activeStreamTargets.get(sessionId), target))
1880
+ return;
1881
+ this.activeStreams.delete(sessionId);
1882
+ this.activeStreamTargets.delete(sessionId);
1883
+ }
1884
+ clearActiveTurn(sessionId, target) {
1885
+ if (target && !matchesCodexTask(this.activeTurns.get(sessionId), target))
1886
+ return;
1887
+ this.activeTurns.delete(sessionId);
1888
+ }
1810
1889
  cancelQueuedTurn(sessionId, identity) {
1811
1890
  const operation = [...(this.queryOperations.get(sessionId) ?? [])].find(candidate => !candidate.lockAcquired
1812
1891
  && candidate.taskId === identity.taskId
@@ -1931,6 +2010,7 @@ export class CodexRunner {
1931
2010
  finally {
1932
2011
  if (this.activeOperationReleases.get(sessionId) === release) {
1933
2012
  this.activeOperationReleases.delete(sessionId);
2013
+ this.activeOperationReleaseTargets.delete(sessionId);
1934
2014
  }
1935
2015
  release();
1936
2016
  }
@@ -1953,12 +2033,14 @@ export class CodexRunner {
1953
2033
  ? this.cachedThreadForTopic(sessionId, topicAgentSessionId)
1954
2034
  : initialAgentSessionId || this.activeSessions.get(sessionId);
1955
2035
  const operationKey = this.threadOperationKey(modelOverride?.recovery?.agentSessionId || knownThreadId, sessionId);
2036
+ this.dropExpiredPendingInterrupt(sessionId, modelOverride?.turn);
1956
2037
  const operation = {
1957
2038
  controller: new AbortController(),
1958
2039
  taskId: modelOverride?.turn?.taskId ?? this.permissionContexts.get(sessionId)?.taskId,
1959
- generation: modelOverride?.turn?.generation,
2040
+ generation: modelOverride?.turn?.generation ?? this.permissionContexts.get(sessionId)?.turn?.generation,
1960
2041
  lockAcquired: false,
1961
2042
  };
2043
+ const operationTarget = this.targetForOperation(operation);
1962
2044
  const operations = this.queryOperations.get(sessionId) ?? new Set();
1963
2045
  operations.add(operation);
1964
2046
  this.queryOperations.set(sessionId, operations);
@@ -1971,12 +2053,16 @@ export class CodexRunner {
1971
2053
  releaseLock?.();
1972
2054
  };
1973
2055
  try {
2056
+ if (operationTarget && this.consumePendingInterrupt(sessionId, operationTarget)) {
2057
+ throw Object.assign(new Error('Codex operation interrupted before startup'), { name: 'AbortError' });
2058
+ }
1974
2059
  await waitForCodexOperation(this.assertInterruptSettled(sessionId, modelOverride?.recovery?.agentSessionId || knownThreadId), operation.controller.signal);
1975
2060
  releaseLock = await this.acquireThreadOperation(operationKey, 'thread/resume+turn/start', operation.controller.signal);
1976
2061
  operation.lockAcquired = true;
1977
2062
  await waitForCodexOperation(this.assertInterruptSettled(sessionId, modelOverride?.recovery?.agentSessionId || knownThreadId), operation.controller.signal);
1978
2063
  const stream = await this.runQueryLocked(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv, operation.controller);
1979
2064
  this.activeOperationReleases.set(sessionId, release);
2065
+ this.activeOperationReleaseTargets.set(sessionId, operationTarget);
1980
2066
  return this.holdThreadOperation(stream, sessionId, release);
1981
2067
  }
1982
2068
  catch (error) {
@@ -2030,7 +2116,7 @@ export class CodexRunner {
2030
2116
  const callApprovalPolicy = this.toApprovalPolicy(callMode);
2031
2117
  const executionSandbox = this.buildExecutionSandboxOptions(sessionId, callMode, projectPath, modelOverride?.bootstrapAgentMdPath, modelOverride?.personalMdPath, undefined);
2032
2118
  const appServer = this.getAppServerClient(callMode === 'fullaccess', modelOverride?.provider);
2033
- this.dropExpiredPendingInterrupt(sessionId);
2119
+ this.dropExpiredPendingInterrupt(sessionId, modelOverride?.turn);
2034
2120
  const effectiveApprovalPolicy = callApprovalPolicy;
2035
2121
  const capabilityConfig = await this.resolveCapabilityThreadConfig(projectPath);
2036
2122
  const userInputConfig = { features: {
@@ -2086,14 +2172,22 @@ export class CodexRunner {
2086
2172
  // topic bindings remain authoritative and fail closed.
2087
2173
  if (topicBinding || recoverySessionId || modelOverride?.asyncQuestionAnswer || !isCodexNoRolloutError(error))
2088
2174
  throw error;
2089
- if (typeof sessionManager?.clearMainSessionBackendIfMatches !== 'function')
2090
- throw error;
2091
2175
  const missingThreadId = agentSessionId;
2092
- const cleared = await sessionManager.clearMainSessionBackendIfMatches(sessionId, missingThreadId);
2093
- if (cleared !== 'cleared' && cleared !== 'already_clear') {
2094
- const recoveryError = new Error(`Codex missing-rollout recovery rejected: ${cleared}`);
2095
- recoveryError.code = 'CODEX_MISSING_ROLLOUT_RECOVERY_REJECTED';
2096
- throw recoveryError;
2176
+ if (modelOverride?.capsule) {
2177
+ const recovered = await modelOverride.capsule.recover(missingThreadId, prompt, systemPromptAppend);
2178
+ prompt = recovered.prompt;
2179
+ systemPromptAppend = recovered.systemPrompt;
2180
+ threadOptions.developerInstructions = [systemPromptAppend, managedTempInstruction].filter(Boolean).join('\n\n') || undefined;
2181
+ }
2182
+ else {
2183
+ if (typeof sessionManager?.clearMainSessionBackendIfMatches !== 'function')
2184
+ throw error;
2185
+ const cleared = await sessionManager.clearMainSessionBackendIfMatches(sessionId, missingThreadId);
2186
+ if (cleared !== 'cleared' && cleared !== 'already_clear') {
2187
+ const recoveryError = new Error(`Codex missing-rollout recovery rejected: ${cleared}`);
2188
+ recoveryError.code = 'CODEX_MISSING_ROLLOUT_RECOVERY_REJECTED';
2189
+ throw recoveryError;
2190
+ }
2097
2191
  }
2098
2192
  if (this.activeSessions.get(sessionId) === missingThreadId)
2099
2193
  this.activeSessions.delete(sessionId);
@@ -2157,7 +2251,16 @@ export class CodexRunner {
2157
2251
  this.threadProjectPaths.set(threadId, path.resolve(projectPath));
2158
2252
  this.bindExternalToolBoundary(threadId, externalToolConfig);
2159
2253
  const controller = operationController ?? new AbortController();
2160
- this.activeAbortControllers.set(sessionId, controller);
2254
+ const runTarget = turn && Number.isSafeInteger(turn.generation)
2255
+ ? { taskId: turn.taskId, generation: turn.generation }
2256
+ : undefined;
2257
+ const currentAbortTarget = this.activeAbortTargets.get(sessionId);
2258
+ const ownsAbortSlot = !currentAbortTarget
2259
+ || !!runTarget && runTarget.generation >= currentAbortTarget.generation;
2260
+ if (ownsAbortSlot) {
2261
+ this.activeAbortControllers.set(sessionId, controller);
2262
+ this.activeAbortTargets.set(sessionId, runTarget);
2263
+ }
2161
2264
  const answer = modelOverride?.asyncQuestionAnswer;
2162
2265
  if (answer && answer.providerThreadId !== threadId) {
2163
2266
  throw new Error('Async question reply cannot resume a different Codex thread');
@@ -2168,6 +2271,8 @@ export class CodexRunner {
2168
2271
  const state = {
2169
2272
  threadId,
2170
2273
  sessionId,
2274
+ taskId: turn?.taskId,
2275
+ generation: turn?.generation,
2171
2276
  projectPath,
2172
2277
  model: callModel,
2173
2278
  modelContextId,
@@ -2232,6 +2337,8 @@ export class CodexRunner {
2232
2337
  sessionId,
2233
2338
  parentThreadId: threadId,
2234
2339
  turnId: childTurnId,
2340
+ taskId: state.taskId,
2341
+ generation: state.generation,
2235
2342
  });
2236
2343
  }
2237
2344
  else if (notification.method === 'turn/completed') {
@@ -2256,10 +2363,12 @@ export class CodexRunner {
2256
2363
  const startedTurnId = this.extractTurnId(notification);
2257
2364
  if (startedTurnId && !state.turnId) {
2258
2365
  state.turnId = startedTurnId;
2259
- this.activeTurns.set(sessionId, { threadId, turnId: startedTurnId });
2260
- if (controller.signal.aborted || this.consumePendingInterrupt(sessionId)) {
2366
+ this.setActiveTurn(sessionId, {
2367
+ threadId, turnId: startedTurnId, taskId: state.taskId, generation: state.generation,
2368
+ });
2369
+ if (controller.signal.aborted || (runTarget && this.consumePendingInterrupt(sessionId, runTarget))) {
2261
2370
  void interruptStartedTurn(startedTurnId);
2262
- this.activeTurns.delete(sessionId);
2371
+ this.clearActiveTurn(sessionId, runTarget);
2263
2372
  }
2264
2373
  }
2265
2374
  }
@@ -2275,17 +2384,18 @@ export class CodexRunner {
2275
2384
  this.endAppServerQueueWhenSubagentsDone(queue, state);
2276
2385
  }
2277
2386
  });
2278
- if (controller.signal.aborted || this.consumePendingInterrupt(sessionId)) {
2387
+ if (controller.signal.aborted || (runTarget && this.consumePendingInterrupt(sessionId, runTarget))) {
2279
2388
  controller.abort('User interrupt');
2280
2389
  queue.end();
2281
- this.activeAbortControllers.delete(sessionId);
2282
- this.activeStreams.delete(sessionId);
2390
+ this.clearActiveController(sessionId, controller);
2391
+ this.clearActiveStream(sessionId, runTarget);
2283
2392
  if (!resumingThread)
2284
2393
  this.cleanupProvisionalThread(sessionId, threadId);
2285
2394
  logger.info(`[CodexRunner] Applied pending interrupt before turn start: ${sessionId}`);
2286
2395
  return this.transformAppServerStream(queue, sessionId, state, controller, unsubscribe, appServer);
2287
2396
  }
2288
2397
  try {
2398
+ operationController?.signal.throwIfAborted();
2289
2399
  const turnResponse = await appServer.turnStart(threadId, input, {
2290
2400
  cwd: projectPath,
2291
2401
  model: callModel,
@@ -2336,7 +2446,9 @@ export class CodexRunner {
2336
2446
  const turnId = turnResponse.turn?.id;
2337
2447
  if (turnId && !state.turnId) {
2338
2448
  state.turnId = turnId;
2339
- this.activeTurns.set(sessionId, { threadId, turnId });
2449
+ this.setActiveTurn(sessionId, {
2450
+ threadId, turnId, taskId: state.taskId, generation: state.generation,
2451
+ });
2340
2452
  }
2341
2453
  if (!resumingThread && turnId) {
2342
2454
  // Check immediately, but leave a just-created rollout as a candidate.
@@ -2344,14 +2456,14 @@ export class CodexRunner {
2344
2456
  // the short settle window below.
2345
2457
  await state.confirmProvisional?.(0);
2346
2458
  }
2347
- if (turnId && (controller.signal.aborted || this.consumePendingInterrupt(sessionId))) {
2459
+ if (turnId && (controller.signal.aborted || (runTarget && this.consumePendingInterrupt(sessionId, runTarget)))) {
2348
2460
  if (!state.turnCompleted && !['completed', 'failed', 'interrupted'].includes(turnResponse.turn?.status)) {
2349
2461
  await interruptStartedTurn(turnId);
2350
2462
  }
2351
2463
  controller.abort('User interrupt');
2352
- this.activeAbortControllers.delete(sessionId);
2353
- this.activeStreams.delete(sessionId);
2354
- this.activeTurns.delete(sessionId);
2464
+ this.clearActiveController(sessionId, controller);
2465
+ this.clearActiveStream(sessionId, runTarget);
2466
+ this.clearActiveTurn(sessionId, runTarget);
2355
2467
  }
2356
2468
  const status = turnResponse.turn?.status;
2357
2469
  if (status === 'completed' || status === 'failed') {
@@ -2364,9 +2476,10 @@ export class CodexRunner {
2364
2476
  catch (error) {
2365
2477
  unsubscribe();
2366
2478
  await this.releaseThreadSubscription(appServer, threadId, 'turn-start-failed');
2367
- this.activeAbortControllers.delete(sessionId);
2368
- this.activeTurns.delete(sessionId);
2369
- this.pendingInterrupts.delete(sessionId);
2479
+ this.clearActiveController(sessionId, controller);
2480
+ this.clearActiveTurn(sessionId, runTarget);
2481
+ if (runTarget)
2482
+ this.consumePendingInterrupt(sessionId, runTarget);
2370
2483
  if (!resumingThread)
2371
2484
  this.cleanupProvisionalThread(sessionId, threadId);
2372
2485
  throw error;
@@ -2374,37 +2487,64 @@ export class CodexRunner {
2374
2487
  return this.transformAppServerStream(queue, sessionId, state, controller, unsubscribe, appServer);
2375
2488
  }
2376
2489
  // ── Interrupt ──
2377
- async interrupt(sessionKey) {
2378
- this.permissionContexts.get(sessionKey)?.pauseController?.cancel();
2490
+ async interrupt(sessionKey, target) {
2379
2491
  const operations = this.queryOperations.get(sessionKey);
2380
- for (const operation of operations ?? []) {
2381
- if (operation.lockAcquired) {
2382
- operation.controller.abort(Object.assign(new Error('Codex operation interrupted'), { name: 'AbortError' }));
2383
- }
2492
+ const matchingOperations = [...(operations ?? [])].filter(operation => target ? matchesCodexTask(this.targetForOperation(operation), target) : operation.lockAcquired);
2493
+ for (const operation of matchingOperations) {
2494
+ operation.controller.abort(Object.assign(new Error('Codex operation interrupted'), { name: 'AbortError' }));
2384
2495
  }
2385
2496
  const controller = this.activeAbortControllers.get(sessionKey);
2386
2497
  const activeTurn = this.activeTurns.get(sessionKey);
2387
- const hadActiveState = !!controller || !!activeTurn || this.activeStreams.has(sessionKey)
2388
- || [...(operations ?? [])].some(operation => operation.lockAcquired);
2389
- const interruptTurn = activeTurn
2390
- ? this.interruptAppServerTurn(activeTurn.threadId, activeTurn.turnId)
2498
+ const matchingController = controller && (!target || matchesCodexTask(this.activeAbortTargets.get(sessionKey), target))
2499
+ ? controller : undefined;
2500
+ const matchingTurn = activeTurn && (!target || matchesCodexTask(activeTurn, target)) ? activeTurn : undefined;
2501
+ const matchingStream = this.activeStreams.has(sessionKey)
2502
+ && (!target || matchesCodexTask(this.activeStreamTargets.get(sessionKey), target));
2503
+ const hadActiveState = !!matchingController || !!matchingTurn || matchingStream || matchingOperations.length > 0;
2504
+ const hasPendingTarget = target
2505
+ && (this.pendingInterrupts.get(sessionKey) ?? []).some(entry => matchesCodexTask(entry.target, target));
2506
+ if (target && !hadActiveState && !hasPendingTarget) {
2507
+ const activeOperation = [...(operations ?? [])].some(operation => operation.lockAcquired);
2508
+ if (activeOperation)
2509
+ return;
2510
+ }
2511
+ if (!target || hadActiveState || hasPendingTarget) {
2512
+ this.permissionContexts.get(sessionKey)?.pauseController?.cancel();
2513
+ }
2514
+ const interruptTurn = matchingTurn
2515
+ ? this.interruptAppServerTurn(matchingTurn.threadId, matchingTurn.turnId)
2391
2516
  : Promise.resolve();
2392
- const interruptSubagents = this.interruptSubagentTurns(sessionKey);
2393
- if (!activeTurn && !operations?.size)
2394
- this.rememberPendingInterrupt(sessionKey);
2395
- if (controller)
2396
- controller.abort('User interrupt');
2517
+ const interruptSubagents = this.interruptSubagentTurns(sessionKey, matchingTurn?.threadId, target);
2518
+ // Only a task-scoped request may be retained for a runner that has not
2519
+ // reached its first turn yet. A session-only interrupt must never poison
2520
+ // a later task during this startup gap.
2521
+ if (target && !hadActiveState && !hasPendingTarget && !(operations && operations.size > 0)
2522
+ && !controller && !activeTurn && !this.activeStreams.has(sessionKey)) {
2523
+ this.rememberPendingInterrupt(sessionKey, target);
2524
+ }
2525
+ if (matchingController)
2526
+ matchingController.abort('User interrupt');
2397
2527
  if (hadActiveState) {
2398
- this.activeAbortControllers.delete(sessionKey);
2399
- this.activeStreams.delete(sessionKey);
2400
- this.activeTurns.delete(sessionKey);
2401
- logger.info(`[CodexRunner] Interrupted session: ${sessionKey}`);
2528
+ if (matchingController && this.activeAbortControllers.get(sessionKey) === matchingController) {
2529
+ this.clearActiveController(sessionKey, matchingController);
2530
+ }
2531
+ if (matchingStream && (!target || this.activeStreamTargets.get(sessionKey)?.taskId === target?.taskId
2532
+ && this.activeStreamTargets.get(sessionKey)?.generation === target?.generation)) {
2533
+ this.activeStreams.delete(sessionKey);
2534
+ this.activeStreamTargets.delete(sessionKey);
2535
+ }
2536
+ if (matchingTurn && (!target || matchesCodexTask(this.activeTurns.get(sessionKey), target))) {
2537
+ this.activeTurns.delete(sessionKey);
2538
+ }
2539
+ logger.info(`[CodexRunner] Interrupted ${target ? `task=${target.taskId} generation=${target.generation}` : 'session'}: ${sessionKey}`);
2402
2540
  }
2403
2541
  await Promise.all([interruptTurn, interruptSubagents]);
2404
2542
  }
2405
- async interruptSubagentTurns(sessionId, parentThreadId) {
2543
+ async interruptSubagentTurns(sessionId, parentThreadId, target) {
2406
2544
  const entries = [...this.activeSubagentTurns.entries()]
2407
- .filter(([, active]) => active.sessionId === sessionId && (!parentThreadId || active.parentThreadId === parentThreadId));
2545
+ .filter(([, active]) => active.sessionId === sessionId
2546
+ && (!parentThreadId || active.parentThreadId === parentThreadId)
2547
+ && (!target || matchesCodexTask(active, target)));
2408
2548
  await Promise.all(entries.map(async ([childThreadId, active]) => {
2409
2549
  await this.interruptAppServerTurn(childThreadId, active.turnId).catch(() => { });
2410
2550
  const current = this.activeSubagentTurns.get(childThreadId);
@@ -2412,21 +2552,34 @@ export class CodexRunner {
2412
2552
  this.activeSubagentTurns.delete(childThreadId);
2413
2553
  }));
2414
2554
  }
2415
- rememberPendingInterrupt(sessionId) {
2416
- this.pendingInterrupts.set(sessionId, Date.now());
2555
+ rememberPendingInterrupt(sessionId, target) {
2556
+ const entries = this.pendingInterrupts.get(sessionId) ?? [];
2557
+ entries.push({ requestedAt: Date.now(), target });
2558
+ this.pendingInterrupts.set(sessionId, entries);
2417
2559
  }
2418
- consumePendingInterrupt(sessionId) {
2419
- if (!this.pendingInterrupts.has(sessionId))
2560
+ consumePendingInterrupt(sessionId, target) {
2561
+ const entries = this.pendingInterrupts.get(sessionId);
2562
+ if (!entries?.length)
2420
2563
  return false;
2421
- const requestedAt = this.pendingInterrupts.get(sessionId);
2422
- this.pendingInterrupts.delete(sessionId);
2423
- return Date.now() - requestedAt <= this.pendingInterruptTtlMs;
2564
+ const now = Date.now();
2565
+ const matching = entries.findIndex(entry => matchesCodexTask(entry.target, target) && now - entry.requestedAt <= this.pendingInterruptTtlMs);
2566
+ const remaining = entries.filter((entry, index) => index !== matching && now - entry.requestedAt <= this.pendingInterruptTtlMs);
2567
+ if (remaining.length > 0)
2568
+ this.pendingInterrupts.set(sessionId, remaining);
2569
+ else
2570
+ this.pendingInterrupts.delete(sessionId);
2571
+ return matching >= 0;
2424
2572
  }
2425
- dropExpiredPendingInterrupt(sessionId) {
2426
- const requestedAt = this.pendingInterrupts.get(sessionId);
2427
- if (requestedAt !== undefined && Date.now() - requestedAt > this.pendingInterruptTtlMs) {
2573
+ dropExpiredPendingInterrupt(sessionId, currentTarget) {
2574
+ const entries = this.pendingInterrupts.get(sessionId);
2575
+ if (!entries)
2576
+ return;
2577
+ const active = entries.filter(entry => Date.now() - entry.requestedAt <= this.pendingInterruptTtlMs
2578
+ && (!currentTarget || entry.target.generation >= currentTarget.generation));
2579
+ if (active.length > 0)
2580
+ this.pendingInterrupts.set(sessionId, active);
2581
+ else
2428
2582
  this.pendingInterrupts.delete(sessionId);
2429
- }
2430
2583
  }
2431
2584
  async interruptAppServerTurn(threadId, turnId) {
2432
2585
  const sessionId = this.findSessionKeyByThread(threadId);
@@ -2571,13 +2724,17 @@ export class CodexRunner {
2571
2724
  && this.threadSubscriptions.get(capturedThreadId) === capturedSubscription) {
2572
2725
  await this.releaseThreadSubscription(capturedSubscription.client, capturedThreadId, 'session-closed');
2573
2726
  }
2574
- if (capturedStream !== undefined && this.activeStreams.get(sessionId) === capturedStream)
2727
+ if (capturedStream !== undefined && this.activeStreams.get(sessionId) === capturedStream) {
2575
2728
  this.activeStreams.delete(sessionId);
2576
- if (capturedController !== undefined && this.activeAbortControllers.get(sessionId) === capturedController)
2729
+ this.activeStreamTargets.delete(sessionId);
2730
+ }
2731
+ if (capturedController !== undefined && this.activeAbortControllers.get(sessionId) === capturedController) {
2577
2732
  this.activeAbortControllers.delete(sessionId);
2733
+ this.activeAbortTargets.delete(sessionId);
2734
+ }
2578
2735
  if (capturedTurn !== undefined && this.activeTurns.get(sessionId) === capturedTurn)
2579
2736
  this.activeTurns.delete(sessionId);
2580
- if (this.pendingInterrupts.has(sessionId) && !lifecycleReplaced)
2737
+ if (!lifecycleReplaced)
2581
2738
  this.pendingInterrupts.delete(sessionId);
2582
2739
  if (this.permissionContexts.get(sessionId) === capturedPermissionContext)
2583
2740
  this.permissionContexts.delete(sessionId);
@@ -2597,6 +2754,7 @@ export class CodexRunner {
2597
2754
  }
2598
2755
  this.clearTrackedApprovalItemsForThread(capturedThreadId);
2599
2756
  this.cleanupChildThreadsForSession(sessionId);
2757
+ this.activeOperationReleaseTargets.delete(sessionId);
2600
2758
  this.pruneThreadOperationLocks();
2601
2759
  }
2602
2760
  }
@@ -2630,6 +2788,10 @@ export class CodexRunner {
2630
2788
  }
2631
2789
  this.activeSessions.delete(sessionId);
2632
2790
  this.activeTurns.delete(sessionId);
2791
+ this.activeAbortTargets.delete(sessionId);
2792
+ this.activeStreamTargets.delete(sessionId);
2793
+ this.activeOperationReleaseTargets.delete(sessionId);
2794
+ this.activeOperationReleases.delete(sessionId);
2633
2795
  this.steeringTails.delete(sessionId);
2634
2796
  this.chatModes.delete(sessionId);
2635
2797
  this.threadProjectPaths.delete(threadId);
@@ -3110,6 +3272,16 @@ export class CodexRunner {
3110
3272
  return undefined;
3111
3273
  return JSON.stringify([threadId, turnId, itemId]);
3112
3274
  }
3275
+ safeOutputCallKey(threadId, callId) {
3276
+ return callId ? JSON.stringify([threadId, callId]) : undefined;
3277
+ }
3278
+ pruneRegisteredSafeOutputCalls() {
3279
+ const now = Date.now();
3280
+ for (const [key, value] of this.registeredSafeOutputCalls) {
3281
+ if (value.expiresAt <= now)
3282
+ this.registeredSafeOutputCalls.delete(key);
3283
+ }
3284
+ }
3113
3285
  trackApprovalItemNotification(notification) {
3114
3286
  const params = (notification.params || {});
3115
3287
  const item = params.item && typeof params.item === 'object' ? params.item : undefined;
@@ -3117,6 +3289,9 @@ export class CodexRunner {
3117
3289
  const threadId = this.requestThreadId(params);
3118
3290
  const turnId = params.turnId ?? params.turn_id;
3119
3291
  const key = this.approvalItemKey(threadId, turnId, itemId);
3292
+ if (notification.method === 'item/completed' && threadId && typeof itemId === 'string') {
3293
+ this.registeredSafeOutputCalls.delete(JSON.stringify([threadId, itemId]));
3294
+ }
3120
3295
  if (notification.method === 'item/started' && key && item && threadId) {
3121
3296
  this.trackedApprovalItems.set(key, {
3122
3297
  threadId,
@@ -3454,10 +3629,41 @@ export class CodexRunner {
3454
3629
  const isCommandApproval = request.method === 'item/commandExecution/requestApproval'
3455
3630
  || request.method === 'execCommandApproval';
3456
3631
  const sessionCredential = this.sessionTokenForSession(sessionKey, typeof params.threadId === 'string' ? params.threadId : undefined);
3457
- const canonicalEcApproval = isCommandApproval
3632
+ let canonicalEcApproval = isCommandApproval
3458
3633
  ? this.resolveCanonicalEcApproval(toolInput, this.getManagedTempDir(sessionKey), sessionCredential)
3459
3634
  : undefined;
3460
- const approvedCommand = canonicalEcApproval?.argv;
3635
+ const approvalItemId = approvalCallId ?? approvalRequestId;
3636
+ const approvalThreadId = this.requestThreadId(params) ?? sessionKey;
3637
+ const preToolOutput = canonicalEcApproval?.executionSpec
3638
+ ? parseDelegatedExecutionSpec(canonicalEcApproval.executionSpec)
3639
+ : undefined;
3640
+ if (preToolOutput) {
3641
+ this.pruneRegisteredSafeOutputCalls();
3642
+ const key = this.safeOutputCallKey(approvalThreadId, approvalItemId);
3643
+ const registered = key ? this.registeredSafeOutputCalls.get(key) : undefined;
3644
+ const safeOutput = this.parseSafeOutputToolInput(toolInput);
3645
+ if (key)
3646
+ this.registeredSafeOutputCalls.delete(key);
3647
+ if (!registered || !safeOutput
3648
+ || JSON.stringify(registered.updatedArgv) !== JSON.stringify(safeOutput.argv)
3649
+ || hashDelegatedCommandSpec(registered.spec) !== hashDelegatedCommandSpec(preToolOutput)) {
3650
+ canonicalEcApproval = {
3651
+ parseFailure: {
3652
+ issue: 'shell-composition',
3653
+ offset: 0,
3654
+ tokenIndex: 0,
3655
+ dialect: preToolOutput.dialect,
3656
+ inputLength: typeof toolInput.command === 'string' ? toolInput.command.length : 0,
3657
+ canonicalizationStage: 'safe-output-binding',
3658
+ wrapper: preToolOutput.wrapper,
3659
+ redirectDetected: true,
3660
+ },
3661
+ };
3662
+ }
3663
+ }
3664
+ const approvedCommand = !canonicalEcApproval?.parseFailure && preToolOutput
3665
+ ? [...preToolOutput.argv]
3666
+ : !canonicalEcApproval?.parseFailure ? canonicalEcApproval?.argv : undefined;
3461
3667
  // Canonical parsing is authoritative. Intent classification remains a
3462
3668
  // fail-closed signal for malformed EC-shaped commands that cannot be armed.
3463
3669
  const managedEcIntent = isCommandApproval && (approvedCommand?.[0] === 'ec' || this.isManagedEvolcoreCommandIntent(toolInput));
@@ -3539,7 +3745,7 @@ export class CodexRunner {
3539
3745
  return await denyInfrastructure('delegation_token_mismatch', 'EC command approval contains a delegation token different from the active thread credential');
3540
3746
  }
3541
3747
  if ((hasSessionCredential || canArmDelegation)
3542
- && !this.armApprovedDelegationCommand(sessionKey, approvedCommand, approvalCallId ?? approvalRequestId)) {
3748
+ && !this.armApprovedDelegationCommand(sessionKey, approvedCommand, approvalItemId, canonicalEcApproval?.specHash, preToolOutput)) {
3543
3749
  return await denyInfrastructure('delegation_not_armed', 'EC command approval failed to arm delegation');
3544
3750
  }
3545
3751
  }
@@ -4042,6 +4248,8 @@ export class CodexRunner {
4042
4248
  const command = Array.isArray(rawCommand) ? rawCommand.join(' ') : (rawCommand || '');
4043
4249
  return {
4044
4250
  command,
4251
+ ...(typeof params.itemId === 'string' ? { itemId: params.itemId } : {}),
4252
+ ...(typeof params.callId === 'string' ? { callId: params.callId } : {}),
4045
4253
  ...(Array.isArray(rawCommand) ? { commandArgv: rawCommand } : {}),
4046
4254
  cwd: params.cwd ?? trackedItem?.cwd,
4047
4255
  reason: params.reason,
@@ -5009,13 +5217,17 @@ export class CodexRunner {
5009
5217
  unsubscribe();
5010
5218
  await this.releaseThreadSubscription(appServer, state.threadId, 'turn-finished');
5011
5219
  if (this.activeAbortControllers.get(sessionId) === controller) {
5012
- this.activeAbortControllers.delete(sessionId);
5220
+ this.clearActiveController(sessionId, controller);
5013
5221
  }
5014
5222
  const activeTurn = this.activeTurns.get(sessionId);
5015
5223
  if (activeTurn?.threadId === state.threadId
5016
5224
  && (!state.turnId || activeTurn.turnId === state.turnId)) {
5017
5225
  this.activeTurns.delete(sessionId);
5018
5226
  }
5227
+ if (this.activeStreamTargets.get(sessionId)?.taskId === state.taskId
5228
+ && this.activeStreamTargets.get(sessionId)?.generation === state.generation) {
5229
+ this.activeStreamTargets.delete(sessionId);
5230
+ }
5019
5231
  if (!state.committed)
5020
5232
  this.cleanupProvisionalThread(sessionId, state.threadId);
5021
5233
  for (const childThreadId of state.activeSubagentThreads)
@@ -5030,7 +5242,12 @@ export class CodexRunner {
5030
5242
  const turnId = this.extractTurnId(notification);
5031
5243
  if (turnId) {
5032
5244
  state.turnId = turnId;
5033
- this.activeTurns.set(sessionId, { threadId: state.threadId, turnId });
5245
+ this.setActiveTurn(sessionId, {
5246
+ threadId: state.threadId,
5247
+ turnId,
5248
+ taskId: state.taskId,
5249
+ generation: state.generation,
5250
+ });
5034
5251
  }
5035
5252
  // turn/start 已落地并回执 turn/started ⇒ 用户输入已被 app-server 接受。
5036
5253
  // 此后中断不能把该输入当作「未提交」重放,否则会产生重复用户轮次。
@@ -5895,6 +6112,7 @@ export class CodexRunner {
5895
6112
  this.threadExternalToolFingerprints.clear();
5896
6113
  this.threadExternalToolBoundaries.clear();
5897
6114
  this.trackedApprovalItems.clear();
6115
+ this.registeredSafeOutputCalls.clear();
5898
6116
  this.pendingInterrupts.clear();
5899
6117
  for (const record of this.unconfirmedInterrupts.values())
5900
6118
  record.unsubscribe?.();
@@ -5904,6 +6122,8 @@ export class CodexRunner {
5904
6122
  this.chatModes.clear();
5905
6123
  this.pruneThreadOperationLocks();
5906
6124
  this.threadOperationLocks.clear();
6125
+ this.activeOperationReleases.clear();
6126
+ this.activeOperationReleaseTargets.clear();
5907
6127
  await Promise.all([
5908
6128
  ...[...this.retiredProviderClients].map(client => client.close()),
5909
6129
  this.appServerClient?.close(),