evolcore 0.0.39 → 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.
- package/CHANGELOG.md +93 -0
- package/README.md +31 -20
- package/bin/codex-managed-hook.mjs +11 -0
- package/bin/ec-safe-output.js +25 -3
- package/dist/agents/baseagent-availability.js +1 -0
- package/dist/agents/claude-runner.js +53 -152
- package/dist/agents/codex-runner.js +485 -241
- package/dist/agents/ecagent-runner.js +48 -18
- package/dist/agents/gemini-runner.js +27 -8
- package/dist/agents/runner-types.js +39 -9
- package/dist/aun/ability-device-routing.js +26 -0
- package/dist/aun/aid/client.js +1 -1
- package/dist/aun/aid/control-aid.js +23 -98
- package/dist/aun/aid/ownership-operation.js +1 -3
- package/dist/aun/group/identity.js +8 -0
- package/dist/aun/group/invite-service.js +6 -0
- package/dist/aun/msg/managed-operation.js +4 -4
- package/dist/aun/msg/p2p.js +28 -12
- package/dist/aun/storage/download.js +30 -0
- package/dist/aun/storage/index.js +14 -6
- package/dist/channels/aun.js +99 -52
- package/dist/channels/daemon.js +24 -4
- package/dist/channels/dingtalk.js +8 -2
- package/dist/channels/feishu.js +6 -1
- package/dist/channels/wecom.js +7 -3
- package/dist/cli/agent-command.js +2 -0
- package/dist/cli/agent-create.js +121 -23
- package/dist/cli/agent.js +10 -3
- package/dist/cli/aid-bind-command.js +4 -1
- package/dist/cli/aun-commands.js +82 -22
- package/dist/cli/daemon-commands.js +260 -26
- package/dist/cli/index.js +25 -13
- package/dist/cli/memory-command.js +33 -14
- package/dist/cli/restart-monitor.js +52 -13
- package/dist/cli/session-command.js +128 -13
- package/dist/cli/stats.js +60 -4
- package/dist/cli/task-context.js +1 -0
- package/dist/cli/trigger-command.js +2 -2
- package/dist/config/access-policy.js +2 -0
- package/dist/config/config-field-policy.js +1 -0
- package/dist/config/config-operation-service.js +17 -6
- package/dist/config/gateway-config.js +1 -1
- package/dist/config/peer-role-resolver.js +10 -8
- package/dist/contracts/ecweb-service-protocol.js +44 -0
- package/dist/core/agent-application-service.js +11 -1
- package/dist/core/agent-ipc-registration.js +4 -0
- package/dist/core/agent-runtime.js +6 -0
- package/dist/core/auth/agent-delegation.js +87 -9
- package/dist/core/auth/auth-gateway.js +3 -1
- package/dist/core/auth/authorization-audit.js +25 -4
- package/dist/core/auth/debug-context.js +5 -1
- package/dist/core/auth/operation-catalog.js +24 -0
- package/dist/core/command/agent-control.js +91 -12
- package/dist/core/command/command-handler.js +64 -47
- package/dist/core/command/connect-menu.js +23 -2
- package/dist/core/command/menu-catalog.js +49 -12
- package/dist/core/command/menu-handler.js +110 -105
- package/dist/core/command/menu-protocol.js +29 -3
- package/dist/core/command/role-menu.js +7 -6
- package/dist/core/command/slash-gate.js +22 -5
- package/dist/core/command/slash-handler.js +121 -102
- package/dist/core/event-catalog.js +17 -0
- package/dist/core/interaction-router.js +2 -1
- package/dist/core/ipc-registration.js +44 -8
- package/dist/core/memory/batch-meta.js +2 -0
- package/dist/core/memory/consolidation-context.js +42 -51
- package/dist/core/memory/consolidation-ops-records.js +39 -7
- package/dist/core/memory/consolidation-trigger.js +72 -65
- package/dist/core/memory/consolidation.js +226 -20
- package/dist/core/memory/memory-writer.js +160 -34
- package/dist/core/memory/relation-idle-monitor.js +287 -0
- package/dist/core/memory/relation-sweep.js +206 -0
- package/dist/core/message/aun-ipc-sender.js +31 -5
- package/dist/core/message/aun-request-registry.js +97 -3
- package/dist/core/message/im-renderer.js +4 -0
- package/dist/core/message/message-admission.js +8 -4
- package/dist/core/message/message-bridge.js +96 -53
- package/dist/core/message/message-log.js +72 -0
- package/dist/core/message/message-queue.js +11 -5
- package/dist/core/message/outbound.js +70 -0
- package/dist/core/message/peer-mode.js +7 -2
- package/dist/core/message/response-engine.js +633 -191
- package/dist/core/model/model-catalog.js +7 -6
- package/dist/core/ownership/owner-resolver.js +384 -178
- package/dist/core/permission/ec-command-parser.js +129 -8
- package/dist/core/permission/tool-policy.js +35 -14
- package/dist/core/role/runtime-policy.js +64 -0
- package/dist/core/session/session-capsule.js +197 -0
- package/dist/core/session/session-manager.js +172 -18
- package/dist/core/session/session-mapper.js +2 -0
- package/dist/core/system-session/memory.js +3 -18
- package/dist/ecweb/basic-settings-service.js +709 -0
- package/dist/ecweb/providers-service.js +172 -0
- package/dist/index.js +95 -7
- package/dist/ipc.js +100 -19
- package/dist/stats/budget.js +1 -1
- package/dist/stats/db.js +48 -0
- package/dist/stats/index.js +3 -3
- package/dist/stats/price-resolver.js +304 -5
- package/dist/stats/query.js +328 -3
- package/dist/stats/writer.js +79 -6
- package/dist/trigger/application-service.js +12 -0
- package/dist/trigger/authorization.js +2 -2
- package/dist/trigger/feedback.js +18 -7
- package/dist/trigger/history.js +36 -0
- package/dist/trigger/manager.js +20 -3
- package/dist/trigger/parser.js +6 -3
- package/dist/trigger/patch.js +1 -1
- package/dist/trigger/scheduler.js +3 -0
- package/dist/trigger/system-definitions.js +43 -7
- package/dist/trigger/validation.js +13 -5
- package/dist/utils/ecweb-supervisor.js +31 -10
- package/dist/utils/error-utils.js +22 -4
- package/dist/utils/evolcore-version.js +3 -2
- package/dist/utils/host-info.js +52 -0
- package/dist/utils/npm-ops.js +2 -1
- package/dist/utils/package-version-info.js +1 -1
- package/dist/utils/upgrade-jobs.js +45 -5
- package/ecagent/dist/harness/agent-harness.js +4 -1
- package/kits/docs/INDEX.md +1 -1
- package/kits/docs/aun/ABILITY_CALLING.md +20 -2
- package/kits/docs/evolcore/INDEX.md +3 -2
- package/kits/docs/evolcore/agent-create.md +3 -2
- package/kits/docs/evolcore/agent.md +1 -1
- package/kits/docs/evolcore/aid.md +29 -12
- package/kits/docs/evolcore/config.md +9 -7
- package/kits/docs/evolcore/event.md +1 -0
- package/kits/docs/evolcore/fs.md +5 -0
- package/kits/docs/evolcore/memory-architecture.md +3 -4
- package/kits/docs/evolcore/memory-consolidation.md +28 -7
- package/kits/docs/evolcore/memory-tags.md +1 -1
- package/kits/docs/evolcore/memory.md +1 -1
- package/kits/docs/evolcore/menu-client.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +38 -0
- package/kits/docs/evolcore/msg.md +18 -2
- package/kits/docs/evolcore/session.md +14 -0
- package/kits/eck_manifest.json +3 -3
- package/kits/rules/04-relation.md +3 -2
- package/kits/schemas/agent-config.schema.13.json +20 -1
- package/kits/skills/aid-ability/SKILL.md +35 -6
- package/kits/templates/memory-consolidation/generalize.md +32 -4
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/promote.md +10 -2
- package/kits/templates/session-capsule/recovery.md +5 -0
- package/kits/templates/session-capsule/renew.md +5 -0
- package/kits/templates/system-fragments/baseagent.md +5 -0
- package/kits/templates/system-fragments/bootstrap.md +6 -6
- package/kits/templates/system-fragments/channel.md +1 -1
- package/kits/templates/system-fragments/memory.md +12 -3
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/{rules/07-memory-and-thread.md → templates/system-fragments/thread.md} +17 -80
- package/package.json +3 -3
- 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,
|
|
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 {
|
|
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,159 +787,62 @@ export class CodexRunner {
|
|
|
765
787
|
}
|
|
766
788
|
this.threadSubscriptions.set(threadId, { client: targetClient, state: 'subscribed' });
|
|
767
789
|
}
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
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
|
|
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
|
|
784
|
-
if (
|
|
785
|
-
return { argv: classification.command.argv };
|
|
786
|
-
// Keep the approval/delegation parser aligned with the preflight parser:
|
|
787
|
-
// the session-managed `$TMPDIR` token is a permitted EC path reference.
|
|
788
|
-
const parsed = executable
|
|
789
|
-
? parseCodexCarrierCommand({ command, dialect, executable }, parseOptions)
|
|
790
|
-
: dialect === 'powershell'
|
|
791
|
-
? parseCodexCarrierCommand({ command, dialect }, parseOptions)
|
|
792
|
-
: parseLiteralShellCommand(command, parseOptions);
|
|
793
|
-
if (!parsed.ok)
|
|
794
|
-
return { parseFailure: parsed };
|
|
795
|
-
if (normalizeEvolcoreCommandArgv(parsed.argv)[0] !== 'ec')
|
|
806
|
+
const resolved = resolveCanonicalEvolcoreToolInput(toolInput, options);
|
|
807
|
+
if (resolved.kind === 'not-ec')
|
|
796
808
|
return {};
|
|
797
|
-
if (
|
|
809
|
+
if (resolved.kind === 'invalid')
|
|
810
|
+
return { parseFailure: resolved.failure };
|
|
811
|
+
const spec = resolved.spec;
|
|
812
|
+
if (containsLiteralManagedTmpDirOutsideSendContent(spec.argv)
|
|
813
|
+
|| containsUnresolvedManagedTmpDirReference(spec.argv)) {
|
|
798
814
|
return { parseFailure: {
|
|
799
|
-
issue: 'unsafe-expansion',
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
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,
|
|
804
819
|
} };
|
|
805
820
|
}
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
};
|
|
810
|
-
}
|
|
811
|
-
resolveCanonicalEcApproval(toolInput, managedTempDir, expectedCredentialToken) {
|
|
812
|
-
const rawCommand = typeof toolInput.command === 'string' ? toolInput.command : '';
|
|
813
|
-
if (/\\\$(?:TMPDIR|\{TMPDIR\})/i.test(rawCommand)
|
|
814
|
-
&& /\bec\s+fs\s+(?:cp|ls|stat|find|cat|mkdir|rm|mv|upload)\b/i.test(rawCommand)
|
|
815
|
-
&& !/\bec\s+(?:msg|group)\s+send\b/i.test(rawCommand)
|
|
816
|
-
&& !/\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) {
|
|
817
824
|
return { parseFailure: {
|
|
818
825
|
issue: 'unsafe-expansion', offset: 0, tokenIndex: 0,
|
|
819
|
-
dialect:
|
|
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,
|
|
820
832
|
} };
|
|
821
833
|
}
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
?
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
issue: 'invalid-control-char', offset: 0,
|
|
830
|
-
tokenIndex: explicitArgv.findIndex(value => value.includes('\0')),
|
|
831
|
-
dialect: 'posix', inputLength: 0,
|
|
832
|
-
} };
|
|
833
|
-
}
|
|
834
|
-
return containsLiteralManagedTmpDirOutsideSendContent(explicitArgv) || containsUnresolvedManagedTmpDirReference(explicitArgv)
|
|
835
|
-
? { parseFailure: { issue: 'unsafe-expansion', offset: 0, tokenIndex: 0, dialect: 'posix', inputLength: 0 } }
|
|
836
|
-
: { argv: canonicalizeEvolcoreCommandArgv(explicitArgv) };
|
|
837
|
-
}
|
|
838
|
-
const explicitCarrier = explicitArgv
|
|
839
|
-
? resolveCodexShellCarrierArgv(explicitArgv)
|
|
840
|
-
: undefined;
|
|
841
|
-
if (explicitCarrier !== undefined) {
|
|
842
|
-
return this.approvedLiteralEvolcoreCommand(explicitCarrier.command, managedTempDir, explicitCarrier.dialect, expectedCredentialToken, explicitCarrier.executable);
|
|
843
|
-
}
|
|
844
|
-
if (explicitArgv?.length === 1 && typeof explicitArgv[0] === 'string') {
|
|
845
|
-
const parsed = parseCodexToolCommand({ commandArgv: explicitArgv }, {
|
|
846
|
-
allowManagedTmpDir: true,
|
|
847
|
-
verifyShellExecutable: process.platform === 'win32',
|
|
848
|
-
...(managedTempDir ? { managedTempDir } : {}),
|
|
849
|
-
...(expectedCredentialToken !== undefined ? { expectedCredentialToken } : {}),
|
|
850
|
-
});
|
|
851
|
-
if (parsed.ok && parsed.argv[0] === 'ec') {
|
|
852
|
-
return containsLiteralManagedTmpDirOutsideSendContent(parsed.argv) || containsUnresolvedManagedTmpDirReference(parsed.argv)
|
|
853
|
-
? { parseFailure: { issue: 'unsafe-expansion', offset: 0, tokenIndex: 0, dialect: 'powershell', inputLength: explicitArgv[0].length } }
|
|
854
|
-
: { argv: canonicalizeEvolcoreCommandArgv(parsed.argv) };
|
|
855
|
-
}
|
|
856
|
-
if (!parsed.ok)
|
|
857
|
-
return { parseFailure: parsed };
|
|
858
|
-
}
|
|
859
|
-
if (hasCodexCmdCarrierEcIntent(toolInput)) {
|
|
860
|
-
const parsed = parseCodexToolCommand(toolInput, {
|
|
861
|
-
verifyShellExecutable: process.platform === 'win32',
|
|
862
|
-
...(expectedCredentialToken !== undefined ? { expectedCredentialToken } : {}),
|
|
863
|
-
});
|
|
864
|
-
if (!parsed.ok)
|
|
865
|
-
return { parseFailure: parsed };
|
|
866
|
-
if (parsed.argv[0] === 'ec') {
|
|
867
|
-
return containsLiteralManagedTmpDirOutsideSendContent(parsed.argv) || containsUnresolvedManagedTmpDirReference(parsed.argv)
|
|
868
|
-
? { parseFailure: {
|
|
869
|
-
issue: 'unsafe-expansion', offset: 0, tokenIndex: 0,
|
|
870
|
-
dialect: 'cmd', inputLength: 0,
|
|
871
|
-
} }
|
|
872
|
-
: {
|
|
873
|
-
argv: canonicalizeEvolcoreCommandArgv(parsed.argv),
|
|
874
|
-
...(parsed.credentialToken ? { credentialToken: parsed.credentialToken } : {}),
|
|
875
|
-
};
|
|
876
|
-
}
|
|
877
|
-
const command = typeof toolInput.command === 'string' ? toolInput.command : '';
|
|
878
|
-
const classification = classifyEvolcoreShellCommand(command, { dialect: 'cmd' });
|
|
879
|
-
return {
|
|
880
|
-
parseFailure: {
|
|
881
|
-
issue: classification.kind === 'composite' ? classification.issue : 'shell-composition',
|
|
882
|
-
offset: 0,
|
|
883
|
-
tokenIndex: 0,
|
|
884
|
-
dialect: 'cmd',
|
|
885
|
-
inputLength: command.length,
|
|
886
|
-
},
|
|
887
|
-
};
|
|
888
|
-
}
|
|
889
|
-
const command = typeof toolInput.command === 'string' ? toolInput.command : '';
|
|
890
|
-
const canonicalCommand = parseCodexShellCommandArgv(command, {
|
|
891
|
-
allowManagedTmpDir: true,
|
|
892
|
-
verifyShellExecutable: process.platform === 'win32',
|
|
893
|
-
...(managedTempDir ? { managedTempDir } : {}),
|
|
894
|
-
...(expectedCredentialToken !== undefined ? { expectedCredentialToken } : {}),
|
|
895
|
-
});
|
|
896
|
-
if (canonicalCommand?.[0] === 'ec') {
|
|
897
|
-
return containsLiteralManagedTmpDirOutsideSendContent(canonicalCommand) || containsUnresolvedManagedTmpDirReference(canonicalCommand)
|
|
898
|
-
? { parseFailure: {
|
|
899
|
-
issue: 'unsafe-expansion',
|
|
900
|
-
offset: 0,
|
|
901
|
-
tokenIndex: 0,
|
|
902
|
-
dialect: 'posix',
|
|
903
|
-
inputLength: command.length,
|
|
904
|
-
} }
|
|
905
|
-
: { argv: canonicalizeEvolcoreCommandArgv(canonicalCommand) };
|
|
906
|
-
}
|
|
907
|
-
const outer = parseLiteralShellCommand(command, {
|
|
908
|
-
allowManagedTmpDir: true,
|
|
909
|
-
...(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 } : {}),
|
|
910
841
|
});
|
|
911
|
-
if (!outer.ok) {
|
|
912
|
-
const classification = classifyEvolcoreShellCommand(command, {
|
|
913
|
-
allowManagedTmpDir: true,
|
|
914
|
-
...(managedTempDir ? { managedTempDir } : {}),
|
|
915
|
-
});
|
|
916
|
-
return classification.kind === 'composite' ? { parseFailure: outer } : {};
|
|
917
|
-
}
|
|
918
|
-
return {};
|
|
919
842
|
}
|
|
920
843
|
isManagedEvolcoreCommandIntent(toolInput) {
|
|
844
|
+
if (this.parseSafeOutputToolInput(toolInput))
|
|
845
|
+
return true;
|
|
921
846
|
if (Array.isArray(toolInput.commandArgv)) {
|
|
922
847
|
const rawArgv = toolInput.commandArgv;
|
|
923
848
|
if (!rawArgv.every(value => typeof value === 'string'))
|
|
@@ -941,21 +866,71 @@ export class CodexRunner {
|
|
|
941
866
|
const command = typeof toolInput.command === 'string' ? toolInput.command : '';
|
|
942
867
|
return classifyEvolcoreShellCommand(command).kind !== 'none';
|
|
943
868
|
}
|
|
944
|
-
armApprovedDelegationCommand(sessionId, argv, approvalId) {
|
|
869
|
+
armApprovedDelegationCommand(sessionId, argv, approvalId, specHash, executionSpec) {
|
|
945
870
|
const threadId = this.activeSessions.get(sessionId) ?? this.provisionalSessions.get(sessionId);
|
|
946
871
|
const sessionToken = threadId ? this.ensureThreadCredentialLoaded(threadId) : undefined;
|
|
947
|
-
const commandHash =
|
|
872
|
+
const commandHash = executionSpec
|
|
873
|
+
? hashDelegatedCommandArgv(executionSpec.argv, executionSpec)
|
|
874
|
+
: hashDelegatedCommandArgv(argv);
|
|
948
875
|
const arm = this.permissionContexts.get(sessionId)?.armApprovedDelegationCommand;
|
|
949
876
|
if (!sessionToken || !commandHash || !arm)
|
|
950
877
|
return false;
|
|
951
878
|
try {
|
|
952
|
-
return
|
|
879
|
+
return specHash === undefined
|
|
880
|
+
? arm(sessionToken, commandHash, approvalId)
|
|
881
|
+
: arm(sessionToken, commandHash, approvalId, specHash);
|
|
953
882
|
}
|
|
954
883
|
catch (error) {
|
|
955
884
|
logger.warn(`[CodexRunner] delegation arm callback failed: session=${sessionId} error=${error instanceof Error ? error.message : String(error)}`);
|
|
956
885
|
return false;
|
|
957
886
|
}
|
|
958
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
|
+
}
|
|
959
934
|
sessionTokenForSession(sessionId, threadId) {
|
|
960
935
|
const candidates = [
|
|
961
936
|
threadId,
|
|
@@ -1313,6 +1288,12 @@ export class CodexRunner {
|
|
|
1313
1288
|
this.resetAppServerClient();
|
|
1314
1289
|
}
|
|
1315
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
|
+
}
|
|
1316
1297
|
getModelCatalog() {
|
|
1317
1298
|
return getRunnerCatalog('codex', this.resolvedConfig.agentAid, this.currentProviderConfig());
|
|
1318
1299
|
}
|
|
@@ -1718,6 +1699,7 @@ export class CodexRunner {
|
|
|
1718
1699
|
role: context.role,
|
|
1719
1700
|
permissionMode: normalizeExecutionPermissionMode(this.chatModes.get(sessionKey) ?? this.currentMode),
|
|
1720
1701
|
allowReadonlySourceDiagnostics: context.allowReadonlySourceDiagnostics === true,
|
|
1702
|
+
safeOutputHelperPath: path.join(getPackageRoot(), 'bin', 'ec-safe-output.js'),
|
|
1721
1703
|
projectPath: preflightProjectPath,
|
|
1722
1704
|
workspacePath: preflightProjectPath,
|
|
1723
1705
|
});
|
|
@@ -1726,42 +1708,125 @@ export class CodexRunner {
|
|
|
1726
1708
|
await recordPreToolUseDenial(preflight.policyCode ?? 'tool_preflight_denied', reason);
|
|
1727
1709
|
return { ok: true, applicable: true, decision: 'deny', reason };
|
|
1728
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
|
+
};
|
|
1729
1745
|
// A tracked interactive thread still needs an authenticated, explicit
|
|
1730
1746
|
// allow so the managed hook can fail closed when no runner matches.
|
|
1731
|
-
if (!context.preToolUsePolicyHook)
|
|
1732
|
-
|
|
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
|
+
}
|
|
1733
1756
|
try {
|
|
1734
1757
|
const result = context.preToolUsePolicyHook(toolName, normalizedInput);
|
|
1735
1758
|
if (result?.block) {
|
|
1736
1759
|
const policyCode = result.policyCode ?? 'session_policy_hook';
|
|
1737
1760
|
const reason = result.reason ?? 'session policy denied this tool call';
|
|
1738
1761
|
await recordPreToolUseDenial(policyCode, reason);
|
|
1762
|
+
const key = this.safeOutputCallKey(threadId, callId);
|
|
1763
|
+
if (key)
|
|
1764
|
+
this.registeredSafeOutputCalls.delete(key);
|
|
1765
|
+
if (policyCode === 'proactive_circuit_break')
|
|
1766
|
+
context.onProactiveCircuitBreak?.();
|
|
1739
1767
|
return { ok: true, applicable: true, decision: 'deny', reason };
|
|
1740
1768
|
}
|
|
1741
|
-
|
|
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
|
+
};
|
|
1742
1776
|
}
|
|
1743
1777
|
catch (error) {
|
|
1744
1778
|
const reason = `policy hook failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
1745
1779
|
await recordPreToolUseDenial('pre_tool_use_hook_failed', reason);
|
|
1780
|
+
const key = this.safeOutputCallKey(threadId, callId);
|
|
1781
|
+
if (key)
|
|
1782
|
+
this.registeredSafeOutputCalls.delete(key);
|
|
1746
1783
|
return { ok: false, applicable: true, decision: 'deny', reason };
|
|
1747
1784
|
}
|
|
1748
1785
|
}
|
|
1749
1786
|
setPermissionGateway(gw) { this.permissionGateway = gw; }
|
|
1750
1787
|
// ── Stream management (needed by MessageProcessor) ──
|
|
1751
|
-
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;
|
|
1752
1793
|
this.activeStreams.set(key, stream);
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
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;
|
|
1756
1816
|
const hadTurn = this.activeTurns.has(key);
|
|
1757
1817
|
const provisionalThread = this.provisionalSessions.get(key);
|
|
1758
1818
|
const subscribedThreadId = this.activeTurns.get(key)?.threadId
|
|
1759
1819
|
?? this.activeSessions.get(key)
|
|
1760
1820
|
?? provisionalThread;
|
|
1761
1821
|
const subscription = subscribedThreadId ? this.threadSubscriptions.get(subscribedThreadId) : undefined;
|
|
1762
|
-
this.activeStreams.
|
|
1763
|
-
|
|
1764
|
-
|
|
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
|
+
}
|
|
1765
1830
|
// A stale runner-start path may dispose the stream without ever entering
|
|
1766
1831
|
// transformAppServerStream. Reclaim its provisional thread, but preserve
|
|
1767
1832
|
// a replacement run that has already installed a new controller/turn.
|
|
@@ -1776,6 +1841,7 @@ export class CodexRunner {
|
|
|
1776
1841
|
}
|
|
1777
1842
|
if (release) {
|
|
1778
1843
|
this.activeOperationReleases.delete(key);
|
|
1844
|
+
this.activeOperationReleaseTargets.delete(key);
|
|
1779
1845
|
if (releaseAfterSubscription) {
|
|
1780
1846
|
void releaseAfterSubscription.then(release, release);
|
|
1781
1847
|
}
|
|
@@ -1791,6 +1857,35 @@ export class CodexRunner {
|
|
|
1791
1857
|
const operations = this.queryOperations.get(sessionId);
|
|
1792
1858
|
return !!operations && [...operations].some(operation => !taskId || operation.taskId === taskId);
|
|
1793
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
|
+
}
|
|
1794
1889
|
cancelQueuedTurn(sessionId, identity) {
|
|
1795
1890
|
const operation = [...(this.queryOperations.get(sessionId) ?? [])].find(candidate => !candidate.lockAcquired
|
|
1796
1891
|
&& candidate.taskId === identity.taskId
|
|
@@ -1915,6 +2010,7 @@ export class CodexRunner {
|
|
|
1915
2010
|
finally {
|
|
1916
2011
|
if (this.activeOperationReleases.get(sessionId) === release) {
|
|
1917
2012
|
this.activeOperationReleases.delete(sessionId);
|
|
2013
|
+
this.activeOperationReleaseTargets.delete(sessionId);
|
|
1918
2014
|
}
|
|
1919
2015
|
release();
|
|
1920
2016
|
}
|
|
@@ -1937,12 +2033,14 @@ export class CodexRunner {
|
|
|
1937
2033
|
? this.cachedThreadForTopic(sessionId, topicAgentSessionId)
|
|
1938
2034
|
: initialAgentSessionId || this.activeSessions.get(sessionId);
|
|
1939
2035
|
const operationKey = this.threadOperationKey(modelOverride?.recovery?.agentSessionId || knownThreadId, sessionId);
|
|
2036
|
+
this.dropExpiredPendingInterrupt(sessionId, modelOverride?.turn);
|
|
1940
2037
|
const operation = {
|
|
1941
2038
|
controller: new AbortController(),
|
|
1942
2039
|
taskId: modelOverride?.turn?.taskId ?? this.permissionContexts.get(sessionId)?.taskId,
|
|
1943
|
-
generation: modelOverride?.turn?.generation,
|
|
2040
|
+
generation: modelOverride?.turn?.generation ?? this.permissionContexts.get(sessionId)?.turn?.generation,
|
|
1944
2041
|
lockAcquired: false,
|
|
1945
2042
|
};
|
|
2043
|
+
const operationTarget = this.targetForOperation(operation);
|
|
1946
2044
|
const operations = this.queryOperations.get(sessionId) ?? new Set();
|
|
1947
2045
|
operations.add(operation);
|
|
1948
2046
|
this.queryOperations.set(sessionId, operations);
|
|
@@ -1955,12 +2053,16 @@ export class CodexRunner {
|
|
|
1955
2053
|
releaseLock?.();
|
|
1956
2054
|
};
|
|
1957
2055
|
try {
|
|
2056
|
+
if (operationTarget && this.consumePendingInterrupt(sessionId, operationTarget)) {
|
|
2057
|
+
throw Object.assign(new Error('Codex operation interrupted before startup'), { name: 'AbortError' });
|
|
2058
|
+
}
|
|
1958
2059
|
await waitForCodexOperation(this.assertInterruptSettled(sessionId, modelOverride?.recovery?.agentSessionId || knownThreadId), operation.controller.signal);
|
|
1959
2060
|
releaseLock = await this.acquireThreadOperation(operationKey, 'thread/resume+turn/start', operation.controller.signal);
|
|
1960
2061
|
operation.lockAcquired = true;
|
|
1961
2062
|
await waitForCodexOperation(this.assertInterruptSettled(sessionId, modelOverride?.recovery?.agentSessionId || knownThreadId), operation.controller.signal);
|
|
1962
2063
|
const stream = await this.runQueryLocked(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv, operation.controller);
|
|
1963
2064
|
this.activeOperationReleases.set(sessionId, release);
|
|
2065
|
+
this.activeOperationReleaseTargets.set(sessionId, operationTarget);
|
|
1964
2066
|
return this.holdThreadOperation(stream, sessionId, release);
|
|
1965
2067
|
}
|
|
1966
2068
|
catch (error) {
|
|
@@ -2014,7 +2116,7 @@ export class CodexRunner {
|
|
|
2014
2116
|
const callApprovalPolicy = this.toApprovalPolicy(callMode);
|
|
2015
2117
|
const executionSandbox = this.buildExecutionSandboxOptions(sessionId, callMode, projectPath, modelOverride?.bootstrapAgentMdPath, modelOverride?.personalMdPath, undefined);
|
|
2016
2118
|
const appServer = this.getAppServerClient(callMode === 'fullaccess', modelOverride?.provider);
|
|
2017
|
-
this.dropExpiredPendingInterrupt(sessionId);
|
|
2119
|
+
this.dropExpiredPendingInterrupt(sessionId, modelOverride?.turn);
|
|
2018
2120
|
const effectiveApprovalPolicy = callApprovalPolicy;
|
|
2019
2121
|
const capabilityConfig = await this.resolveCapabilityThreadConfig(projectPath);
|
|
2020
2122
|
const userInputConfig = { features: {
|
|
@@ -2070,14 +2172,22 @@ export class CodexRunner {
|
|
|
2070
2172
|
// topic bindings remain authoritative and fail closed.
|
|
2071
2173
|
if (topicBinding || recoverySessionId || modelOverride?.asyncQuestionAnswer || !isCodexNoRolloutError(error))
|
|
2072
2174
|
throw error;
|
|
2073
|
-
if (typeof sessionManager?.clearMainSessionBackendIfMatches !== 'function')
|
|
2074
|
-
throw error;
|
|
2075
2175
|
const missingThreadId = agentSessionId;
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
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
|
+
}
|
|
2081
2191
|
}
|
|
2082
2192
|
if (this.activeSessions.get(sessionId) === missingThreadId)
|
|
2083
2193
|
this.activeSessions.delete(sessionId);
|
|
@@ -2141,7 +2251,16 @@ export class CodexRunner {
|
|
|
2141
2251
|
this.threadProjectPaths.set(threadId, path.resolve(projectPath));
|
|
2142
2252
|
this.bindExternalToolBoundary(threadId, externalToolConfig);
|
|
2143
2253
|
const controller = operationController ?? new AbortController();
|
|
2144
|
-
|
|
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
|
+
}
|
|
2145
2264
|
const answer = modelOverride?.asyncQuestionAnswer;
|
|
2146
2265
|
if (answer && answer.providerThreadId !== threadId) {
|
|
2147
2266
|
throw new Error('Async question reply cannot resume a different Codex thread');
|
|
@@ -2152,6 +2271,8 @@ export class CodexRunner {
|
|
|
2152
2271
|
const state = {
|
|
2153
2272
|
threadId,
|
|
2154
2273
|
sessionId,
|
|
2274
|
+
taskId: turn?.taskId,
|
|
2275
|
+
generation: turn?.generation,
|
|
2155
2276
|
projectPath,
|
|
2156
2277
|
model: callModel,
|
|
2157
2278
|
modelContextId,
|
|
@@ -2216,6 +2337,8 @@ export class CodexRunner {
|
|
|
2216
2337
|
sessionId,
|
|
2217
2338
|
parentThreadId: threadId,
|
|
2218
2339
|
turnId: childTurnId,
|
|
2340
|
+
taskId: state.taskId,
|
|
2341
|
+
generation: state.generation,
|
|
2219
2342
|
});
|
|
2220
2343
|
}
|
|
2221
2344
|
else if (notification.method === 'turn/completed') {
|
|
@@ -2240,10 +2363,12 @@ export class CodexRunner {
|
|
|
2240
2363
|
const startedTurnId = this.extractTurnId(notification);
|
|
2241
2364
|
if (startedTurnId && !state.turnId) {
|
|
2242
2365
|
state.turnId = startedTurnId;
|
|
2243
|
-
this.
|
|
2244
|
-
|
|
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))) {
|
|
2245
2370
|
void interruptStartedTurn(startedTurnId);
|
|
2246
|
-
this.
|
|
2371
|
+
this.clearActiveTurn(sessionId, runTarget);
|
|
2247
2372
|
}
|
|
2248
2373
|
}
|
|
2249
2374
|
}
|
|
@@ -2259,17 +2384,18 @@ export class CodexRunner {
|
|
|
2259
2384
|
this.endAppServerQueueWhenSubagentsDone(queue, state);
|
|
2260
2385
|
}
|
|
2261
2386
|
});
|
|
2262
|
-
if (controller.signal.aborted || this.consumePendingInterrupt(sessionId)) {
|
|
2387
|
+
if (controller.signal.aborted || (runTarget && this.consumePendingInterrupt(sessionId, runTarget))) {
|
|
2263
2388
|
controller.abort('User interrupt');
|
|
2264
2389
|
queue.end();
|
|
2265
|
-
this.
|
|
2266
|
-
this.
|
|
2390
|
+
this.clearActiveController(sessionId, controller);
|
|
2391
|
+
this.clearActiveStream(sessionId, runTarget);
|
|
2267
2392
|
if (!resumingThread)
|
|
2268
2393
|
this.cleanupProvisionalThread(sessionId, threadId);
|
|
2269
2394
|
logger.info(`[CodexRunner] Applied pending interrupt before turn start: ${sessionId}`);
|
|
2270
2395
|
return this.transformAppServerStream(queue, sessionId, state, controller, unsubscribe, appServer);
|
|
2271
2396
|
}
|
|
2272
2397
|
try {
|
|
2398
|
+
operationController?.signal.throwIfAborted();
|
|
2273
2399
|
const turnResponse = await appServer.turnStart(threadId, input, {
|
|
2274
2400
|
cwd: projectPath,
|
|
2275
2401
|
model: callModel,
|
|
@@ -2320,7 +2446,9 @@ export class CodexRunner {
|
|
|
2320
2446
|
const turnId = turnResponse.turn?.id;
|
|
2321
2447
|
if (turnId && !state.turnId) {
|
|
2322
2448
|
state.turnId = turnId;
|
|
2323
|
-
this.
|
|
2449
|
+
this.setActiveTurn(sessionId, {
|
|
2450
|
+
threadId, turnId, taskId: state.taskId, generation: state.generation,
|
|
2451
|
+
});
|
|
2324
2452
|
}
|
|
2325
2453
|
if (!resumingThread && turnId) {
|
|
2326
2454
|
// Check immediately, but leave a just-created rollout as a candidate.
|
|
@@ -2328,14 +2456,14 @@ export class CodexRunner {
|
|
|
2328
2456
|
// the short settle window below.
|
|
2329
2457
|
await state.confirmProvisional?.(0);
|
|
2330
2458
|
}
|
|
2331
|
-
if (turnId && (controller.signal.aborted || this.consumePendingInterrupt(sessionId))) {
|
|
2459
|
+
if (turnId && (controller.signal.aborted || (runTarget && this.consumePendingInterrupt(sessionId, runTarget)))) {
|
|
2332
2460
|
if (!state.turnCompleted && !['completed', 'failed', 'interrupted'].includes(turnResponse.turn?.status)) {
|
|
2333
2461
|
await interruptStartedTurn(turnId);
|
|
2334
2462
|
}
|
|
2335
2463
|
controller.abort('User interrupt');
|
|
2336
|
-
this.
|
|
2337
|
-
this.
|
|
2338
|
-
this.
|
|
2464
|
+
this.clearActiveController(sessionId, controller);
|
|
2465
|
+
this.clearActiveStream(sessionId, runTarget);
|
|
2466
|
+
this.clearActiveTurn(sessionId, runTarget);
|
|
2339
2467
|
}
|
|
2340
2468
|
const status = turnResponse.turn?.status;
|
|
2341
2469
|
if (status === 'completed' || status === 'failed') {
|
|
@@ -2348,9 +2476,10 @@ export class CodexRunner {
|
|
|
2348
2476
|
catch (error) {
|
|
2349
2477
|
unsubscribe();
|
|
2350
2478
|
await this.releaseThreadSubscription(appServer, threadId, 'turn-start-failed');
|
|
2351
|
-
this.
|
|
2352
|
-
this.
|
|
2353
|
-
|
|
2479
|
+
this.clearActiveController(sessionId, controller);
|
|
2480
|
+
this.clearActiveTurn(sessionId, runTarget);
|
|
2481
|
+
if (runTarget)
|
|
2482
|
+
this.consumePendingInterrupt(sessionId, runTarget);
|
|
2354
2483
|
if (!resumingThread)
|
|
2355
2484
|
this.cleanupProvisionalThread(sessionId, threadId);
|
|
2356
2485
|
throw error;
|
|
@@ -2358,37 +2487,64 @@ export class CodexRunner {
|
|
|
2358
2487
|
return this.transformAppServerStream(queue, sessionId, state, controller, unsubscribe, appServer);
|
|
2359
2488
|
}
|
|
2360
2489
|
// ── Interrupt ──
|
|
2361
|
-
async interrupt(sessionKey) {
|
|
2362
|
-
this.permissionContexts.get(sessionKey)?.pauseController?.cancel();
|
|
2490
|
+
async interrupt(sessionKey, target) {
|
|
2363
2491
|
const operations = this.queryOperations.get(sessionKey);
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
}
|
|
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' }));
|
|
2368
2495
|
}
|
|
2369
2496
|
const controller = this.activeAbortControllers.get(sessionKey);
|
|
2370
2497
|
const activeTurn = this.activeTurns.get(sessionKey);
|
|
2371
|
-
const
|
|
2372
|
-
|
|
2373
|
-
const
|
|
2374
|
-
|
|
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)
|
|
2375
2516
|
: Promise.resolve();
|
|
2376
|
-
const interruptSubagents = this.interruptSubagentTurns(sessionKey);
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
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');
|
|
2381
2527
|
if (hadActiveState) {
|
|
2382
|
-
this.activeAbortControllers.
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
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}`);
|
|
2386
2540
|
}
|
|
2387
2541
|
await Promise.all([interruptTurn, interruptSubagents]);
|
|
2388
2542
|
}
|
|
2389
|
-
async interruptSubagentTurns(sessionId, parentThreadId) {
|
|
2543
|
+
async interruptSubagentTurns(sessionId, parentThreadId, target) {
|
|
2390
2544
|
const entries = [...this.activeSubagentTurns.entries()]
|
|
2391
|
-
.filter(([, active]) => active.sessionId === sessionId
|
|
2545
|
+
.filter(([, active]) => active.sessionId === sessionId
|
|
2546
|
+
&& (!parentThreadId || active.parentThreadId === parentThreadId)
|
|
2547
|
+
&& (!target || matchesCodexTask(active, target)));
|
|
2392
2548
|
await Promise.all(entries.map(async ([childThreadId, active]) => {
|
|
2393
2549
|
await this.interruptAppServerTurn(childThreadId, active.turnId).catch(() => { });
|
|
2394
2550
|
const current = this.activeSubagentTurns.get(childThreadId);
|
|
@@ -2396,21 +2552,34 @@ export class CodexRunner {
|
|
|
2396
2552
|
this.activeSubagentTurns.delete(childThreadId);
|
|
2397
2553
|
}));
|
|
2398
2554
|
}
|
|
2399
|
-
rememberPendingInterrupt(sessionId) {
|
|
2400
|
-
this.pendingInterrupts.
|
|
2555
|
+
rememberPendingInterrupt(sessionId, target) {
|
|
2556
|
+
const entries = this.pendingInterrupts.get(sessionId) ?? [];
|
|
2557
|
+
entries.push({ requestedAt: Date.now(), target });
|
|
2558
|
+
this.pendingInterrupts.set(sessionId, entries);
|
|
2401
2559
|
}
|
|
2402
|
-
consumePendingInterrupt(sessionId) {
|
|
2403
|
-
|
|
2560
|
+
consumePendingInterrupt(sessionId, target) {
|
|
2561
|
+
const entries = this.pendingInterrupts.get(sessionId);
|
|
2562
|
+
if (!entries?.length)
|
|
2404
2563
|
return false;
|
|
2405
|
-
const
|
|
2406
|
-
|
|
2407
|
-
|
|
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;
|
|
2408
2572
|
}
|
|
2409
|
-
dropExpiredPendingInterrupt(sessionId) {
|
|
2410
|
-
const
|
|
2411
|
-
if (
|
|
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
|
|
2412
2582
|
this.pendingInterrupts.delete(sessionId);
|
|
2413
|
-
}
|
|
2414
2583
|
}
|
|
2415
2584
|
async interruptAppServerTurn(threadId, turnId) {
|
|
2416
2585
|
const sessionId = this.findSessionKeyByThread(threadId);
|
|
@@ -2555,13 +2724,17 @@ export class CodexRunner {
|
|
|
2555
2724
|
&& this.threadSubscriptions.get(capturedThreadId) === capturedSubscription) {
|
|
2556
2725
|
await this.releaseThreadSubscription(capturedSubscription.client, capturedThreadId, 'session-closed');
|
|
2557
2726
|
}
|
|
2558
|
-
if (capturedStream !== undefined && this.activeStreams.get(sessionId) === capturedStream)
|
|
2727
|
+
if (capturedStream !== undefined && this.activeStreams.get(sessionId) === capturedStream) {
|
|
2559
2728
|
this.activeStreams.delete(sessionId);
|
|
2560
|
-
|
|
2729
|
+
this.activeStreamTargets.delete(sessionId);
|
|
2730
|
+
}
|
|
2731
|
+
if (capturedController !== undefined && this.activeAbortControllers.get(sessionId) === capturedController) {
|
|
2561
2732
|
this.activeAbortControllers.delete(sessionId);
|
|
2733
|
+
this.activeAbortTargets.delete(sessionId);
|
|
2734
|
+
}
|
|
2562
2735
|
if (capturedTurn !== undefined && this.activeTurns.get(sessionId) === capturedTurn)
|
|
2563
2736
|
this.activeTurns.delete(sessionId);
|
|
2564
|
-
if (
|
|
2737
|
+
if (!lifecycleReplaced)
|
|
2565
2738
|
this.pendingInterrupts.delete(sessionId);
|
|
2566
2739
|
if (this.permissionContexts.get(sessionId) === capturedPermissionContext)
|
|
2567
2740
|
this.permissionContexts.delete(sessionId);
|
|
@@ -2581,6 +2754,7 @@ export class CodexRunner {
|
|
|
2581
2754
|
}
|
|
2582
2755
|
this.clearTrackedApprovalItemsForThread(capturedThreadId);
|
|
2583
2756
|
this.cleanupChildThreadsForSession(sessionId);
|
|
2757
|
+
this.activeOperationReleaseTargets.delete(sessionId);
|
|
2584
2758
|
this.pruneThreadOperationLocks();
|
|
2585
2759
|
}
|
|
2586
2760
|
}
|
|
@@ -2614,6 +2788,10 @@ export class CodexRunner {
|
|
|
2614
2788
|
}
|
|
2615
2789
|
this.activeSessions.delete(sessionId);
|
|
2616
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);
|
|
2617
2795
|
this.steeringTails.delete(sessionId);
|
|
2618
2796
|
this.chatModes.delete(sessionId);
|
|
2619
2797
|
this.threadProjectPaths.delete(threadId);
|
|
@@ -3094,6 +3272,16 @@ export class CodexRunner {
|
|
|
3094
3272
|
return undefined;
|
|
3095
3273
|
return JSON.stringify([threadId, turnId, itemId]);
|
|
3096
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
|
+
}
|
|
3097
3285
|
trackApprovalItemNotification(notification) {
|
|
3098
3286
|
const params = (notification.params || {});
|
|
3099
3287
|
const item = params.item && typeof params.item === 'object' ? params.item : undefined;
|
|
@@ -3101,6 +3289,9 @@ export class CodexRunner {
|
|
|
3101
3289
|
const threadId = this.requestThreadId(params);
|
|
3102
3290
|
const turnId = params.turnId ?? params.turn_id;
|
|
3103
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
|
+
}
|
|
3104
3295
|
if (notification.method === 'item/started' && key && item && threadId) {
|
|
3105
3296
|
this.trackedApprovalItems.set(key, {
|
|
3106
3297
|
threadId,
|
|
@@ -3373,6 +3564,8 @@ export class CodexRunner {
|
|
|
3373
3564
|
`reason=${policyResult.reason ?? 'policy denied'} executed=false`);
|
|
3374
3565
|
const policyCode = policyResult.policyCode ?? 'session_policy_hook';
|
|
3375
3566
|
const policyReason = policyResult.reason ?? 'session policy denied approval';
|
|
3567
|
+
if (policyCode === 'proactive_circuit_break')
|
|
3568
|
+
permissionContext?.onProactiveCircuitBreak?.();
|
|
3376
3569
|
this.rememberToolDenial(request, params, {
|
|
3377
3570
|
decision: 'deny',
|
|
3378
3571
|
decisionSource: 'policy',
|
|
@@ -3436,10 +3629,41 @@ export class CodexRunner {
|
|
|
3436
3629
|
const isCommandApproval = request.method === 'item/commandExecution/requestApproval'
|
|
3437
3630
|
|| request.method === 'execCommandApproval';
|
|
3438
3631
|
const sessionCredential = this.sessionTokenForSession(sessionKey, typeof params.threadId === 'string' ? params.threadId : undefined);
|
|
3439
|
-
|
|
3632
|
+
let canonicalEcApproval = isCommandApproval
|
|
3440
3633
|
? this.resolveCanonicalEcApproval(toolInput, this.getManagedTempDir(sessionKey), sessionCredential)
|
|
3441
3634
|
: undefined;
|
|
3442
|
-
const
|
|
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;
|
|
3443
3667
|
// Canonical parsing is authoritative. Intent classification remains a
|
|
3444
3668
|
// fail-closed signal for malformed EC-shaped commands that cannot be armed.
|
|
3445
3669
|
const managedEcIntent = isCommandApproval && (approvedCommand?.[0] === 'ec' || this.isManagedEvolcoreCommandIntent(toolInput));
|
|
@@ -3521,7 +3745,7 @@ export class CodexRunner {
|
|
|
3521
3745
|
return await denyInfrastructure('delegation_token_mismatch', 'EC command approval contains a delegation token different from the active thread credential');
|
|
3522
3746
|
}
|
|
3523
3747
|
if ((hasSessionCredential || canArmDelegation)
|
|
3524
|
-
&& !this.armApprovedDelegationCommand(sessionKey, approvedCommand,
|
|
3748
|
+
&& !this.armApprovedDelegationCommand(sessionKey, approvedCommand, approvalItemId, canonicalEcApproval?.specHash, preToolOutput)) {
|
|
3525
3749
|
return await denyInfrastructure('delegation_not_armed', 'EC command approval failed to arm delegation');
|
|
3526
3750
|
}
|
|
3527
3751
|
}
|
|
@@ -3857,25 +4081,9 @@ export class CodexRunner {
|
|
|
3857
4081
|
}
|
|
3858
4082
|
async collectUserInputAnswer(sessionKey, question) {
|
|
3859
4083
|
const options = Array.isArray(question.options) ? question.options : [];
|
|
3860
|
-
const fallback = options[0]?.label ? [String(options[0].label)] : [''];
|
|
3861
4084
|
const context = this.permissionContexts.get(sessionKey);
|
|
3862
4085
|
if (context?.approvalInteractionPolicy === 'deny') {
|
|
3863
|
-
|
|
3864
|
-
const labels = options
|
|
3865
|
-
.map((option) => typeof option?.label === 'string' ? option.label.trim() : '')
|
|
3866
|
-
.filter(Boolean);
|
|
3867
|
-
if (labels.length > 0) {
|
|
3868
|
-
const prompt = `${String(question.header ?? '')} ${String(question.question ?? '')}`;
|
|
3869
|
-
const isPlanApproval = /\bplan\b|计划|方案/i.test(prompt);
|
|
3870
|
-
const affirmative = isPlanApproval
|
|
3871
|
-
? labels.find(label => {
|
|
3872
|
-
const kind = this.classifyMcpApprovalLabel(label);
|
|
3873
|
-
return kind === 'allow_once' || kind === 'allow_persistent';
|
|
3874
|
-
})
|
|
3875
|
-
: undefined;
|
|
3876
|
-
return [affirmative ?? labels[0]];
|
|
3877
|
-
}
|
|
3878
|
-
return ['当前为无人值守 Trigger,请基于已有上下文选择最安全合理的方案并继续执行。'];
|
|
4086
|
+
throw new Error('无人值守任务不能自动回答用户问题');
|
|
3879
4087
|
}
|
|
3880
4088
|
const canFreeText = question.isOther !== false || options.length === 0;
|
|
3881
4089
|
const sendPrompt = context?.adapter && context.channelId
|
|
@@ -3887,8 +4095,8 @@ export class CodexRunner {
|
|
|
3887
4095
|
: this.sendPromptFn;
|
|
3888
4096
|
if (!context?.interactionRouter || !sendPrompt) {
|
|
3889
4097
|
if (sendPrompt)
|
|
3890
|
-
await sendPrompt(this.formatUserInputFallback(question
|
|
3891
|
-
|
|
4098
|
+
await sendPrompt(this.formatUserInputFallback(question));
|
|
4099
|
+
throw new Error('用户问题没有可用的交互路由,已拒绝自动选择');
|
|
3892
4100
|
}
|
|
3893
4101
|
const requestId = `codex-ask-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
3894
4102
|
const buttonArgMap = {};
|
|
@@ -3914,6 +4122,9 @@ export class CodexRunner {
|
|
|
3914
4122
|
title: String(question.header || '问题'),
|
|
3915
4123
|
body: bodyLines.join('\n'),
|
|
3916
4124
|
buttons,
|
|
4125
|
+
...(typeof question.recommendedOption === 'string'
|
|
4126
|
+
? { recommendedOption: buttons.find(button => button.label === question.recommendedOption)?.key }
|
|
4127
|
+
: {}),
|
|
3917
4128
|
allowCustomInput: canFreeText,
|
|
3918
4129
|
},
|
|
3919
4130
|
fallback: {
|
|
@@ -3951,14 +4162,19 @@ export class CodexRunner {
|
|
|
3951
4162
|
}
|
|
3952
4163
|
if (!sent) {
|
|
3953
4164
|
router.unmarkWaiting(sessionKey);
|
|
3954
|
-
|
|
4165
|
+
throw new Error('用户问题卡片投递失败,已拒绝自动选择');
|
|
3955
4166
|
}
|
|
3956
4167
|
return new Promise((resolve) => {
|
|
3957
4168
|
router.register(requestId, sessionKey, (action, values) => {
|
|
3958
|
-
|
|
4169
|
+
const answer = this.parseUserInputAction(action, values, options, []);
|
|
4170
|
+
if (answer.length === 0 || answer.every(item => !item.trim()))
|
|
4171
|
+
return false;
|
|
4172
|
+
resolve(answer);
|
|
4173
|
+
return true;
|
|
3959
4174
|
}, {
|
|
3960
4175
|
initiatorId: context.userId,
|
|
3961
4176
|
fallbackCommand: 'ask',
|
|
4177
|
+
retainOnRejected: true,
|
|
3962
4178
|
});
|
|
3963
4179
|
if (waitMarked) {
|
|
3964
4180
|
router.unmarkWaiting(sessionKey);
|
|
@@ -3986,13 +4202,13 @@ export class CodexRunner {
|
|
|
3986
4202
|
}
|
|
3987
4203
|
return action.trim() ? [action.trim()] : fallback;
|
|
3988
4204
|
}
|
|
3989
|
-
formatUserInputFallback(question
|
|
4205
|
+
formatUserInputFallback(question) {
|
|
3990
4206
|
const options = Array.isArray(question.options) ? question.options : [];
|
|
3991
4207
|
const lines = [String(question.header || '问题'), String(question.question || '')].filter(Boolean);
|
|
3992
4208
|
if (options.length > 0) {
|
|
3993
4209
|
lines.push('', ...options.map((option, index) => `${index + 1}. ${String(option.label || `选项 ${index + 1}`)}${option.description ? ` — ${option.description}` : ''}`));
|
|
3994
4210
|
}
|
|
3995
|
-
lines.push('',
|
|
4211
|
+
lines.push('', '等待用户选择后继续。');
|
|
3996
4212
|
return lines.join('\n');
|
|
3997
4213
|
}
|
|
3998
4214
|
findSessionKeyByThread(threadId, conversationId) {
|
|
@@ -4032,6 +4248,8 @@ export class CodexRunner {
|
|
|
4032
4248
|
const command = Array.isArray(rawCommand) ? rawCommand.join(' ') : (rawCommand || '');
|
|
4033
4249
|
return {
|
|
4034
4250
|
command,
|
|
4251
|
+
...(typeof params.itemId === 'string' ? { itemId: params.itemId } : {}),
|
|
4252
|
+
...(typeof params.callId === 'string' ? { callId: params.callId } : {}),
|
|
4035
4253
|
...(Array.isArray(rawCommand) ? { commandArgv: rawCommand } : {}),
|
|
4036
4254
|
cwd: params.cwd ?? trackedItem?.cwd,
|
|
4037
4255
|
reason: params.reason,
|
|
@@ -4999,13 +5217,17 @@ export class CodexRunner {
|
|
|
4999
5217
|
unsubscribe();
|
|
5000
5218
|
await this.releaseThreadSubscription(appServer, state.threadId, 'turn-finished');
|
|
5001
5219
|
if (this.activeAbortControllers.get(sessionId) === controller) {
|
|
5002
|
-
this.
|
|
5220
|
+
this.clearActiveController(sessionId, controller);
|
|
5003
5221
|
}
|
|
5004
5222
|
const activeTurn = this.activeTurns.get(sessionId);
|
|
5005
5223
|
if (activeTurn?.threadId === state.threadId
|
|
5006
5224
|
&& (!state.turnId || activeTurn.turnId === state.turnId)) {
|
|
5007
5225
|
this.activeTurns.delete(sessionId);
|
|
5008
5226
|
}
|
|
5227
|
+
if (this.activeStreamTargets.get(sessionId)?.taskId === state.taskId
|
|
5228
|
+
&& this.activeStreamTargets.get(sessionId)?.generation === state.generation) {
|
|
5229
|
+
this.activeStreamTargets.delete(sessionId);
|
|
5230
|
+
}
|
|
5009
5231
|
if (!state.committed)
|
|
5010
5232
|
this.cleanupProvisionalThread(sessionId, state.threadId);
|
|
5011
5233
|
for (const childThreadId of state.activeSubagentThreads)
|
|
@@ -5020,7 +5242,12 @@ export class CodexRunner {
|
|
|
5020
5242
|
const turnId = this.extractTurnId(notification);
|
|
5021
5243
|
if (turnId) {
|
|
5022
5244
|
state.turnId = turnId;
|
|
5023
|
-
this.
|
|
5245
|
+
this.setActiveTurn(sessionId, {
|
|
5246
|
+
threadId: state.threadId,
|
|
5247
|
+
turnId,
|
|
5248
|
+
taskId: state.taskId,
|
|
5249
|
+
generation: state.generation,
|
|
5250
|
+
});
|
|
5024
5251
|
}
|
|
5025
5252
|
// turn/start 已落地并回执 turn/started ⇒ 用户输入已被 app-server 接受。
|
|
5026
5253
|
// 此后中断不能把该输入当作「未提交」重放,否则会产生重复用户轮次。
|
|
@@ -5402,10 +5629,24 @@ export class CodexRunner {
|
|
|
5402
5629
|
const isError = exitCode !== undefined
|
|
5403
5630
|
? exitCode !== 0
|
|
5404
5631
|
: item.status === 'failed' || item.status === 'declined';
|
|
5632
|
+
const rawOutput = item.aggregatedOutput ?? '';
|
|
5633
|
+
const commandStr = Array.isArray(item.command)
|
|
5634
|
+
? item.command.join(' ')
|
|
5635
|
+
: typeof item.command === 'string' ? item.command : '';
|
|
5636
|
+
const isApplyPatchFailure = isError
|
|
5637
|
+
&& /apply_patch/i.test(commandStr)
|
|
5638
|
+
&& /The last line of the patch must be|Invalid patch/i.test(rawOutput);
|
|
5639
|
+
const isApplyPatchArgFailure = isError
|
|
5640
|
+
&& /--codex-run-as-apply-patch requires a UTF-8 PATCH argument/i.test(rawOutput);
|
|
5641
|
+
const applyPatchHint = isApplyPatchFailure
|
|
5642
|
+
? '\n[EvolCore 提示] apply_patch 在 Windows 上通过 .bat shim 调用时会截断多行参数,补丁末尾 *** End Patch 被丢弃。正确做法:改用 FileChange 工具直接写文件,或绕过 .bat 直接调用 codex.exe --codex-run-as-apply-patch。不要继续用 here-string 变体重试。'
|
|
5643
|
+
: isApplyPatchArgFailure
|
|
5644
|
+
? '\n[EvolCore 提示] --codex-run-as-apply-patch 要求补丁内容通过命令行参数传入,不接受 PowerShell here-string 直接输出到 stdout 的方式。正确做法:改用 FileChange 工具直接写文件。'
|
|
5645
|
+
: '';
|
|
5405
5646
|
yield {
|
|
5406
5647
|
type: 'tool_result',
|
|
5407
5648
|
name: 'Shell',
|
|
5408
|
-
result:
|
|
5649
|
+
result: rawOutput + applyPatchHint,
|
|
5409
5650
|
...(item.aggregatedOutput != null ? { outputKind: 'combined' } : {}),
|
|
5410
5651
|
...(blockedFields ?? {
|
|
5411
5652
|
isError,
|
|
@@ -5871,6 +6112,7 @@ export class CodexRunner {
|
|
|
5871
6112
|
this.threadExternalToolFingerprints.clear();
|
|
5872
6113
|
this.threadExternalToolBoundaries.clear();
|
|
5873
6114
|
this.trackedApprovalItems.clear();
|
|
6115
|
+
this.registeredSafeOutputCalls.clear();
|
|
5874
6116
|
this.pendingInterrupts.clear();
|
|
5875
6117
|
for (const record of this.unconfirmedInterrupts.values())
|
|
5876
6118
|
record.unsubscribe?.();
|
|
@@ -5880,6 +6122,8 @@ export class CodexRunner {
|
|
|
5880
6122
|
this.chatModes.clear();
|
|
5881
6123
|
this.pruneThreadOperationLocks();
|
|
5882
6124
|
this.threadOperationLocks.clear();
|
|
6125
|
+
this.activeOperationReleases.clear();
|
|
6126
|
+
this.activeOperationReleaseTargets.clear();
|
|
5883
6127
|
await Promise.all([
|
|
5884
6128
|
...[...this.retiredProviderClients].map(client => client.close()),
|
|
5885
6129
|
this.appServerClient?.close(),
|