evolcore 0.0.43-test.5 → 0.0.43-test.7
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 +95 -0
- package/bin/ecmsg.js +281 -81
- package/dist/agents/baseagent-availability.js +20 -5
- package/dist/agents/baseagent.js +2 -2
- package/dist/agents/claude-runner.js +19 -4
- package/dist/agents/codex/app-server-client.js +36 -3
- package/dist/agents/codex-runner.js +75 -8
- package/dist/aun/group/invite-service.js +3 -2
- package/dist/aun/msg/p2p.js +6 -1
- package/dist/aun/service-proxy.js +18 -6
- package/dist/channels/aun.js +306 -30
- package/dist/cli/agent-create.js +18 -8
- package/dist/cli/aun-commands.js +9 -1
- package/dist/cli/daemon-commands.js +34 -65
- package/dist/cli/daemon-lifecycle-client.js +61 -0
- package/dist/cli/ecmsg-gateway.js +38 -3
- package/dist/cli/events-command.js +73 -0
- package/dist/cli/index.js +31 -14
- package/dist/cli/init.js +75 -0
- package/dist/cli/invoke-command.js +182 -0
- package/dist/cli/managed-command-guard.js +6 -1
- package/dist/cli/provider-command.js +1 -1
- package/dist/cli/restart-monitor.js +67 -50
- package/dist/cli/services-command.js +111 -0
- package/dist/cli/task-context.js +38 -1
- package/dist/cli/team-workspace-command.js +134 -0
- package/dist/cli/thread-command.js +6 -2
- package/dist/cli/watch-logs.js +6 -4
- package/dist/cli/watch-msg.js +1 -1
- package/dist/config/boot-log.js +6 -4
- package/dist/config/builtin-roles.js +2 -2
- package/dist/config/config-field-policy.js +2 -2
- package/dist/config/config-manager.js +1 -8
- package/dist/config/invoke-ipc-service.js +118 -0
- package/dist/config/peer-role-resolver.js +1 -1
- package/dist/config/provider-identity-migration.js +92 -17
- package/dist/config/provider-local-sync.js +2 -0
- package/dist/config/providers-config.js +13 -0
- package/dist/config/providers-management.js +100 -10
- package/dist/config/role-service.js +8 -8
- package/dist/config/role-store.js +22 -22
- package/dist/config/schema-migration.js +86 -88
- package/dist/config/snapshot.js +70 -41
- package/dist/config-store.js +2 -1
- package/dist/core/agent-reload-coordinator.js +6 -4
- package/dist/core/agent-runtime.js +146 -15
- package/dist/core/auth/delegation-authorization.js +66 -0
- package/dist/core/auth/operation-catalog.js +20 -0
- package/dist/core/baseagent-loader.js +75 -42
- package/dist/core/channel-loader.js +45 -13
- package/dist/core/channel-runtime.js +116 -45
- package/dist/core/command/agent-control.js +1 -1
- package/dist/core/command/agent-storage-menu.js +1 -1
- package/dist/core/command/chatmode-config.js +2 -36
- package/dist/core/command/command-handler.js +58 -16
- package/dist/core/command/data-root-resolver.js +32 -23
- package/dist/core/command/eventcenter-menu.js +338 -0
- package/dist/core/command/menu-catalog.js +8 -0
- package/dist/core/command/menu-handler.js +206 -87
- package/dist/core/command/menu-protocol.js +142 -22
- package/dist/core/command/menu-query-batch.js +194 -0
- package/dist/core/command/role-menu.js +27 -15
- package/dist/core/command/slash-gate.js +1 -1
- package/dist/core/command/slash-handler.js +34 -42
- package/dist/core/command/team-workspace-bootstrap.js +350 -0
- package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
- package/dist/core/command/team-workspace-initializer.js +2 -0
- package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
- package/dist/core/command/team-workspace-job-store.js +88 -0
- package/dist/core/command/team-workspace-management-service.js +2 -0
- package/dist/core/command/team-workspace-management-store.js +96 -0
- package/dist/core/command/team-workspace-management.js +265 -0
- package/dist/core/command/team-workspace-members-menu.js +88 -0
- package/dist/core/command/team-workspace-store.js +612 -0
- package/dist/core/command/team-workspace-team.js +193 -0
- package/dist/core/daemon-control.js +45 -15
- package/dist/core/daemon-lifecycle.js +478 -75
- package/dist/core/handoff/dispatcher.js +9 -3
- package/dist/core/handoff/runtime.js +130 -42
- package/dist/core/handoff/store.js +190 -2
- package/dist/core/handoff/types.js +5 -0
- package/dist/core/initialization/service.js +4 -4
- package/dist/core/invoke/executors/index.js +13 -0
- package/dist/core/invoke/executors/media.js +283 -0
- package/dist/core/invoke/executors/text.js +198 -0
- package/dist/core/invoke/invoke-service.js +157 -0
- package/dist/core/invoke/style-router.js +48 -0
- package/dist/core/invoke/types.js +19 -0
- package/dist/core/ipc-registration.js +51 -11
- package/dist/core/lifecycle-notice.js +10 -4
- package/dist/core/memory/consolidation.js +7 -5
- package/dist/core/message/aun-ipc-sender.js +149 -19
- package/dist/core/message/im-renderer.js +28 -84
- package/dist/core/message/message-bridge.js +57 -4
- package/dist/core/message/message-queue.js +46 -4
- package/dist/core/message/message-utils.js +10 -2
- package/dist/core/message/peer-mode.js +7 -34
- package/dist/core/message/pending-hints.js +4 -10
- package/dist/core/message/response-engine.js +163 -52
- package/dist/core/message/send-options.js +7 -4
- package/dist/core/message/send-routing.js +55 -7
- package/dist/core/ownership/owner-resolver.js +8 -0
- package/dist/core/permission/ec-command-parser.js +14 -3
- package/dist/core/permission/protected-paths.js +12 -2
- package/dist/core/permission/shell-environment.js +9 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
- package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
- package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
- package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
- package/dist/core/session/session-file-health.js +243 -0
- package/dist/core/session/session-fs-store.js +163 -3
- package/dist/core/session/session-idle-monitor.js +9 -1
- package/dist/core/session/session-manager.js +36 -2
- package/dist/core/task/task-recovery-service.js +13 -2
- package/dist/core/thread/command-parser.js +9 -2
- package/dist/core/thread/thread-operation.js +21 -2
- package/dist/core/thread/thread-route.js +13 -2
- package/dist/directory/owner-directory-admission.js +42 -30
- package/dist/directory/owner-directory-cache.js +143 -126
- package/dist/directory/owner-directory-query-operation.js +9 -8
- package/dist/eck/kit-renderer.js +7 -5
- package/dist/ecweb/basic-settings-service.js +1 -1
- package/dist/ecweb/message-context-service.js +0 -4
- package/dist/ecweb/runtime/lifecycle.js +14 -8
- package/dist/ecweb/runtime/supervisor.js +62 -30
- package/dist/event-center/admission-materializer.js +114 -0
- package/dist/event-center/bus-gate.js +136 -0
- package/dist/event-center/bus-host.js +290 -0
- package/dist/event-center/bus-resolver.js +120 -0
- package/dist/event-center/center-config.js +100 -0
- package/dist/event-center/client-factory.js +50 -0
- package/dist/event-center/daemon.js +45 -0
- package/dist/event-center/directory-source.js +53 -0
- package/dist/event-center/dispatcher.js +157 -0
- package/dist/event-center/event-log.js +110 -0
- package/dist/event-center/index-generator.js +63 -0
- package/dist/event-center/ipc-operation.js +308 -0
- package/dist/event-center/ledger.js +52 -0
- package/dist/event-center/pack-loader.js +202 -0
- package/dist/event-center/pack-manager.js +85 -0
- package/dist/event-center/registry.js +238 -0
- package/dist/event-center/runtime.js +641 -0
- package/dist/event-center/script-runner.js +356 -0
- package/dist/event-center/types.js +35 -0
- package/dist/event-center/validation.js +413 -0
- package/dist/index.js +751 -268
- package/dist/ipc.js +66 -12
- package/dist/paths.js +20 -0
- package/dist/product.js +14 -0
- package/dist/proxy/manager.js +43 -18
- package/dist/proxy/service-supervisor.js +78 -35
- package/dist/response-system/engines/v1/index.js +0 -1
- package/dist/response-system/modes/single-session/index.js +1 -1
- package/dist/services/dispatcher.js +100 -0
- package/dist/services/idempotency.js +90 -0
- package/dist/services/identity.js +52 -0
- package/dist/services/index-generator.js +70 -0
- package/dist/services/index.js +449 -0
- package/dist/services/ipc-operation.js +458 -0
- package/dist/services/ledger.js +52 -0
- package/dist/services/message-log.js +112 -0
- package/dist/services/pack-manager.js +204 -0
- package/dist/services/reply.js +55 -0
- package/dist/services/router.js +95 -0
- package/dist/services/script-runner.js +422 -0
- package/dist/services/service-payload.js +70 -0
- package/dist/services/types.js +18 -0
- package/dist/services/validation.js +297 -0
- package/dist/trigger/application-service.js +21 -1
- package/dist/trigger/audit.js +19 -4
- package/dist/trigger/authorization.js +14 -5
- package/dist/trigger/event-source.js +1 -1
- package/dist/trigger/history.js +176 -7
- package/dist/trigger/ipc-service.js +3 -1
- package/dist/trigger/manager.js +1 -3
- package/dist/trigger/scheduler.js +78 -5
- package/dist/trigger/script-sandbox.js +118 -22
- package/dist/utils/cross-platform.js +175 -13
- package/dist/utils/evolcore-version.js +69 -27
- package/dist/utils/host-info.js +11 -8
- package/dist/utils/instance-registry.js +19 -13
- package/dist/utils/npm-ops.js +48 -0
- package/dist/utils/process-introspect.js +109 -10
- package/dist/utils/startup-trace.js +222 -44
- package/dist/utils/windows-shell-trust.js +80 -6
- package/kits/docs/INDEX.md +2 -2
- package/kits/docs/aun/ABILITY_CALLING.md +10 -17
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +5 -2
- package/kits/docs/evolcore/ability.md +4 -0
- package/kits/docs/evolcore/aid.md +1 -1
- package/kits/docs/evolcore/ctl.md +2 -1
- package/kits/docs/evolcore/event-center.md +207 -0
- package/kits/docs/evolcore/file-navigation.md +10 -264
- package/kits/docs/evolcore/fs.md +3 -2
- package/kits/docs/evolcore/group.md +2 -2
- package/kits/docs/evolcore/memory-architecture.md +2 -0
- package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +21 -0
- package/kits/docs/evolcore/msg.md +27 -8
- package/kits/docs/evolcore/provider.md +23 -3
- package/kits/docs/evolcore/response.md +5 -5
- package/kits/docs/evolcore/services.md +277 -0
- package/kits/docs/evolcore/task.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +41 -0
- package/kits/eck_manifest.json +45 -7
- package/kits/eck_message_manifest.json +3 -3
- package/kits/rules/02-navigation.md +10 -1
- package/kits/rules/06-channel.md +5 -6
- package/kits/schemas/_meta.json +17 -6
- package/kits/schemas/agent-config.schema.19.json +5 -7
- package/kits/schemas/agent-config.schema.20.json +936 -0
- package/kits/schemas/daemon.schema.1.json +5 -0
- package/kits/schemas/daemon.schema.2.json +5 -0
- package/kits/schemas/daemon.schema.3.json +2 -1
- package/kits/schemas/daemon.schema.4.json +2 -1
- package/kits/schemas/daemon.schema.5.json +2 -1
- package/kits/schemas/daemon.schema.6.json +1 -1
- package/kits/schemas/daemon.schema.7.json +1 -1
- package/kits/schemas/daemon.schema.8.json +2 -1
- package/kits/schemas/daemon.schema.9.json +2 -1
- package/kits/schemas/relation-config.schema.12.json +2 -3
- package/kits/schemas/role-config.schema.2.json +4 -4
- package/kits/schemas/role-registry.schema.1.json +2 -2
- package/kits/schemas/single-session.schema.1.json +1 -1
- package/kits/schemas/single-session.schema.2.json +1 -1
- package/kits/schemas/single-session.schema.3.json +1 -1
- package/kits/skills/.switches.json +1 -5
- package/kits/skills/ability/SKILL.md +56 -0
- package/kits/skills/ability/references/calling.md +56 -0
- package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
- package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
- package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
- package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
- package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
- package/kits/skills/ec-agent-create/SKILL.md +0 -1
- package/kits/skills/ec-group/SKILL.md +8 -5
- package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
- package/kits/skills/ec-service-proxy/SKILL.md +34 -5
- package/kits/skills/ec-trigger/SKILL.md +4 -4
- package/kits/skills/personal-assistant/SKILL.md +6 -6
- package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
- package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
- package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
- package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
- package/kits/skills/thread-ops/SKILL.md +10 -10
- package/kits/templates/system-fragments/channel.md +3 -3
- package/kits/templates/system-fragments/commands.md +9 -7
- package/kits/templates/system-fragments/reply.md +2 -6
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +11 -9
- package/package.json +5 -6
- package/dist/cli/pa-workspace-command.js +0 -225
- package/dist/core/command/pa-workspace-store.js +0 -468
- package/dist/core/relation/pa-team.js +0 -132
- package/kits/docs/evolcore/pa-workspace.md +0 -51
- package/kits/skills/aid-ability/SKILL.md +0 -244
- package/kits/skills/ec-ability/SKILL.md +0 -67
- package/kits/skills/ec-ability/references/workflows.md +0 -15
|
@@ -1697,6 +1697,13 @@ export const getProtocolOwners = (subjectAid) => ownerResolver.protocolOwners(su
|
|
|
1697
1697
|
export const getOwners = (subjectAid) => ownerResolver.owners(subjectAid);
|
|
1698
1698
|
export const getConfiguredOwners = (subjectAid) => ownerResolver.configuredOwnerList(subjectAid);
|
|
1699
1699
|
export const getDaemonOwners = () => ownerResolver.daemonOwners();
|
|
1700
|
+
export function resolveContextOwner(selfAid, directoryOwnerAid) {
|
|
1701
|
+
const ownerAid = selfAid ? getProtocolOwner(selfAid) : undefined;
|
|
1702
|
+
if (ownerAid && directoryOwnerAid && ownerAid !== directoryOwnerAid) {
|
|
1703
|
+
return { ownerAid, mismatch: { protocolOwnerAid: ownerAid, directoryOwnerAid } };
|
|
1704
|
+
}
|
|
1705
|
+
return { ownerAid };
|
|
1706
|
+
}
|
|
1700
1707
|
export async function refreshOwnershipForAuthorization(subjectAid, options = {}) {
|
|
1701
1708
|
const daemonAid = ownerResolver.getDaemonAid();
|
|
1702
1709
|
const ownershipSubjectAid = daemonAid && subjectAid === `${daemonAid}#daemon` ? daemonAid : subjectAid;
|
|
@@ -1714,6 +1721,7 @@ export async function refreshOwnershipForAuthorization(subjectAid, options = {})
|
|
|
1714
1721
|
throw new OwnershipError('OWNER_REFRESH_FAILED', `Ownership refresh failed (${failure.refreshFailure.code}): ${failure.refreshFailure.reason}`);
|
|
1715
1722
|
}
|
|
1716
1723
|
}
|
|
1724
|
+
return views;
|
|
1717
1725
|
}
|
|
1718
1726
|
export async function assertOwnershipAuthorization(context) {
|
|
1719
1727
|
if (context?.internalContactAuthorization && context.selfAid && context.actor?.principalId) {
|
|
@@ -386,11 +386,11 @@ const APPLY_PATCH_EXECUTABLE_BASENAMES = new Set([
|
|
|
386
386
|
'apply_patch.ps1',
|
|
387
387
|
]);
|
|
388
388
|
const EVOLCORE_SUBCOMMANDS = new Set([
|
|
389
|
-
'ability', 'agent', 'aid', 'bench', 'config', 'peer', 'ctl', 'data', 'diag', 'diagnose',
|
|
389
|
+
'ability', 'agent', 'aid', 'bench', 'config', 'events', 'peer', 'ctl', 'data', 'diag', 'diagnose',
|
|
390
390
|
'fs', 'gateway', 'group', 'init', 'link-rules', 'logs', 'menu-client',
|
|
391
391
|
'mode', 'model', 'msg', 'mv', 'net', 'queue', 'response', 'restart',
|
|
392
392
|
'restart-monitor', 'rpc', 'start', 'stats', 'status', 'stop', 'storage', 'task',
|
|
393
|
-
'trigger', 'proxy', 'version', 'watch', 'session', '
|
|
393
|
+
'trigger', 'proxy', 'version', 'watch', 'session', 'team', 'upgrade', 'update',
|
|
394
394
|
]);
|
|
395
395
|
// Development/install entrypoints that are part of this repository's CLI.
|
|
396
396
|
// Only these exact relative paths are canonicalized; arbitrary Node scripts
|
|
@@ -1691,7 +1691,17 @@ function resolveCodexPowerShellCarrierString(command) {
|
|
|
1691
1691
|
// PowerShell credential-prefix parser sees them.
|
|
1692
1692
|
const quote = nested[0];
|
|
1693
1693
|
if (nested.length >= 2 && nested.endsWith(quote)) {
|
|
1694
|
-
|
|
1694
|
+
if (quote === '"' && /\\[\\"$`]/u.test(nested)) {
|
|
1695
|
+
const decoded = parseLiteralShellCommand(nested, { dialect: 'posix' });
|
|
1696
|
+
if (decoded.ok && decoded.argv.length === 1)
|
|
1697
|
+
nested = decoded.argv[0];
|
|
1698
|
+
else {
|
|
1699
|
+
failure = parseFailure('invalid-quote', nested, 0, 0, 'powershell');
|
|
1700
|
+
nested = nested.slice(1, -1);
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
else
|
|
1704
|
+
nested = nested.slice(1, -1);
|
|
1695
1705
|
}
|
|
1696
1706
|
else {
|
|
1697
1707
|
failure = parseFailure('invalid-quote', nested, 0, 0, 'powershell');
|
|
@@ -3378,6 +3388,7 @@ export function containsLiteralManagedTmpDirOutsideSendContent(argv) {
|
|
|
3378
3388
|
const READ_ONLY_SUBCOMMANDS = new Set([
|
|
3379
3389
|
'thread.list', 'thread.show', 'thread.history', 'thread.peers',
|
|
3380
3390
|
'thread.summary', 'msg.history', 'msg.online', 'trigger.list', 'trigger.show',
|
|
3391
|
+
'events.status', 'events.ledger', 'events.tail', 'events.doctor', 'events.allowlist:show',
|
|
3381
3392
|
'directory.list', 'directory.info', 'aid.show', 'aid.list', 'aid.lookup',
|
|
3382
3393
|
'peer.list', 'help', 'status',
|
|
3383
3394
|
]);
|
|
@@ -49,6 +49,8 @@ const L_CLASS_RELATIVE_PATTERNS = [
|
|
|
49
49
|
/^backups\/config(?:\/|$)/,
|
|
50
50
|
/^agents\/[^/]+\/triggers(?:\/|$)/,
|
|
51
51
|
/^agents\/[^/]+\/roles(?:\/|$)/,
|
|
52
|
+
/^agents\/[^/]+\/events(?:\/|$)/,
|
|
53
|
+
/^agents\/[^/]+\/services(?:\/|$)/,
|
|
52
54
|
];
|
|
53
55
|
const L_CLASS_REFERENCE_PATTERNS = [
|
|
54
56
|
/(?:^|[^A-Za-z0-9_.-])daemon\.json(?=$|[^A-Za-z0-9_.-])/,
|
|
@@ -56,6 +58,8 @@ const L_CLASS_REFERENCE_PATTERNS = [
|
|
|
56
58
|
/(?:^|[^A-Za-z0-9_.-])backups[\\/]config(?:[\\/]|$|[\s"';&|<>)},])/,
|
|
57
59
|
/(?:^|[^A-Za-z0-9_.-])agents[\\/][^/\\\s"']+[\\/]triggers(?:[\\/]|$|[\s"';&|<>)},])/,
|
|
58
60
|
/(?:^|[^A-Za-z0-9_.-])agents[\\/][^/\\\s"']+[\\/]roles(?:[\\/]|$|[\s"';&|<>)},])/,
|
|
61
|
+
/(?:^|[^A-Za-z0-9_.-])agents[\\/][^/\\\s"']+[\\/]events(?:[\\/]|$|[\s"';&|<>)},])/,
|
|
62
|
+
/(?:^|[^A-Za-z0-9_.-])agents[\\/][^/\\\s"']+[\\/]services(?:[\\/]|$|[\s"';&|<>)},])/,
|
|
59
63
|
];
|
|
60
64
|
function normalizeForComparison(value) {
|
|
61
65
|
const resolved = path.resolve(value);
|
|
@@ -438,6 +442,10 @@ export function getLClassWritePatterns(root = resolveRoot()) {
|
|
|
438
442
|
return [
|
|
439
443
|
path.join(absoluteRoot, 'agents', '*', 'triggers'),
|
|
440
444
|
path.join(absoluteRoot, 'agents', '*', 'triggers') + '/**',
|
|
445
|
+
path.join(absoluteRoot, 'agents', '*', 'events'),
|
|
446
|
+
path.join(absoluteRoot, 'agents', '*', 'events') + '/**',
|
|
447
|
+
path.join(absoluteRoot, 'agents', '*', 'services'),
|
|
448
|
+
path.join(absoluteRoot, 'agents', '*', 'services') + '/**',
|
|
441
449
|
path.join(absoluteRoot, 'agents', '*', 'roles') + '/**',
|
|
442
450
|
];
|
|
443
451
|
}
|
|
@@ -606,7 +614,7 @@ export function getExistingLClassReadOnlyTargets(root = resolveRoot(), options =
|
|
|
606
614
|
}
|
|
607
615
|
const ownRoot = path.join(agentsDir, selfAid);
|
|
608
616
|
for (const relative of [
|
|
609
|
-
'config.json', 'contact.json', 'contact-operations.jsonl', 'roles', 'triggers',
|
|
617
|
+
'config.json', 'contact.json', 'contact-operations.jsonl', 'roles', 'triggers', 'events', 'services',
|
|
610
618
|
])
|
|
611
619
|
addExistingTarget(targets, path.join(ownRoot, relative));
|
|
612
620
|
try {
|
|
@@ -625,6 +633,8 @@ export function getExistingLClassReadOnlyTargets(root = resolveRoot(), options =
|
|
|
625
633
|
if (!entry.isDirectory())
|
|
626
634
|
continue;
|
|
627
635
|
addExistingTarget(targets, path.join(agentsDir, entry.name, 'triggers'));
|
|
636
|
+
addExistingTarget(targets, path.join(agentsDir, entry.name, 'events'));
|
|
637
|
+
addExistingTarget(targets, path.join(agentsDir, entry.name, 'services'));
|
|
628
638
|
addExistingTarget(targets, path.join(agentsDir, entry.name, 'roles'));
|
|
629
639
|
}
|
|
630
640
|
}
|
|
@@ -1017,7 +1027,7 @@ export function lClassGrantIncludesProtectedPath(value, options = {}) {
|
|
|
1017
1027
|
// relations/<peer> 本身时才覆盖它,更深的路径(如 relations/<peer>/memory/…)不会。
|
|
1018
1028
|
if (segments[2] === 'relations')
|
|
1019
1029
|
return segments.length <= 4;
|
|
1020
|
-
return ['config.json', 'contact.json', 'contact-operations.jsonl', 'roles', 'triggers']
|
|
1030
|
+
return ['config.json', 'contact.json', 'contact-operations.jsonl', 'roles', 'triggers', 'events', 'services']
|
|
1021
1031
|
.includes(segments[2]);
|
|
1022
1032
|
}
|
|
1023
1033
|
return false;
|
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
import { CODEX_HEADER_ENV_PREFIX, SERVICE_SESSION_ENV_NAMES } from '../../product.js';
|
|
2
|
+
const SERVICE_SESSION_ENV = new Set(SERVICE_SESSION_ENV_NAMES);
|
|
3
|
+
/** Preserve infrastructure and application settings without inheriting task authority. */
|
|
4
|
+
export function sanitizeServiceEnvironment(input) {
|
|
5
|
+
return Object.fromEntries(Object.entries(input).filter(([name]) => {
|
|
6
|
+
const normalized = name.toUpperCase();
|
|
7
|
+
return !SERVICE_SESSION_ENV.has(normalized) && !normalized.startsWith(CODEX_HEADER_ENV_PREFIX);
|
|
8
|
+
}));
|
|
9
|
+
}
|
|
1
10
|
const SHELL_CODE_INJECTION_ENV = new Set([
|
|
2
11
|
'BASH_ENV',
|
|
3
12
|
'BASHOPTS',
|
|
@@ -11,6 +11,7 @@ import { buildCliSessionPreview } from '../session-title.js';
|
|
|
11
11
|
import path from 'path';
|
|
12
12
|
import fs from 'fs';
|
|
13
13
|
import os from 'os';
|
|
14
|
+
import { visitSessionHistory } from '../session-fs-store.js';
|
|
14
15
|
export class ClaudeSessionFileAdapter {
|
|
15
16
|
baseagent = 'claude';
|
|
16
17
|
getSessionFilePath(projectPath, agentSessionId) {
|
|
@@ -60,6 +61,29 @@ export class ClaudeSessionFileAdapter {
|
|
|
60
61
|
return null;
|
|
61
62
|
return this.readSessionPreview(sessionFile).title;
|
|
62
63
|
}
|
|
64
|
+
async readMenuSummary(projectPath, agentSessionId) {
|
|
65
|
+
let turns = 0;
|
|
66
|
+
let validInfo = true;
|
|
67
|
+
const messages = [];
|
|
68
|
+
try {
|
|
69
|
+
await visitSessionHistory(this.getSessionFilePath(projectPath, agentSessionId), event => {
|
|
70
|
+
if (event?.type !== 'user' || event.message?.role !== 'user')
|
|
71
|
+
return;
|
|
72
|
+
const content = event.message.content;
|
|
73
|
+
if (!(Array.isArray(content) && content.every((part) => part.type === 'tool_result')))
|
|
74
|
+
turns++;
|
|
75
|
+
const text = this.extractRawUserText(content);
|
|
76
|
+
if (text)
|
|
77
|
+
messages.push(text);
|
|
78
|
+
}, () => { validInfo = false; });
|
|
79
|
+
return { turns: validInfo ? turns : 0, firstMessage: buildCliSessionPreview(messages, 'claude').title };
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (error.code !== 'ENOENT')
|
|
83
|
+
logger.warn('[ClaudeAdapter] Failed to read menu summary', error);
|
|
84
|
+
return { turns: 0, firstMessage: null };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
63
87
|
/**
|
|
64
88
|
* 单遍扫描会话文件,返回预览标题及是否含真人消息。
|
|
65
89
|
* - title:第一条真人消息(跳过脚手架 prompt);全是脚手架时退回首条脚手架文本作兜底
|
|
@@ -15,6 +15,7 @@ import { logger } from '../../../utils/logger.js';
|
|
|
15
15
|
import path from 'path';
|
|
16
16
|
import fs from 'fs';
|
|
17
17
|
import os from 'os';
|
|
18
|
+
import { visitSessionHistory } from '../session-fs-store.js';
|
|
18
19
|
const requireFromHere = createRequire(import.meta.url);
|
|
19
20
|
let sqliteModule; // undefined = not tried, null = unavailable
|
|
20
21
|
export const sanitizeCodexThreadTitle = sanitizeSessionTitle;
|
|
@@ -37,6 +38,7 @@ export class CodexSessionFileAdapter {
|
|
|
37
38
|
db = null;
|
|
38
39
|
dbInitialized = false;
|
|
39
40
|
rolloutPathCache = new Map();
|
|
41
|
+
rolloutFilesScan;
|
|
40
42
|
constructor(codexHome = path.join(os.homedir(), '.codex')) {
|
|
41
43
|
this.codexHome = codexHome;
|
|
42
44
|
}
|
|
@@ -235,6 +237,84 @@ export class CodexSessionFileAdapter {
|
|
|
235
237
|
return null;
|
|
236
238
|
return this.readUserMessageFromRollout(rolloutPath, 'first');
|
|
237
239
|
}
|
|
240
|
+
async findRolloutFileAsync(agentSessionId, preferred) {
|
|
241
|
+
for (const candidate of [preferred, this.rolloutPathCache.get(agentSessionId)]) {
|
|
242
|
+
if (typeof candidate !== 'string' || !candidate)
|
|
243
|
+
continue;
|
|
244
|
+
try {
|
|
245
|
+
await fs.promises.access(candidate);
|
|
246
|
+
return candidate;
|
|
247
|
+
}
|
|
248
|
+
catch { /* Rescan moved rollouts. */ }
|
|
249
|
+
}
|
|
250
|
+
this.rolloutPathCache.delete(agentSessionId);
|
|
251
|
+
const scan = async (dir) => {
|
|
252
|
+
const files = [];
|
|
253
|
+
let entries;
|
|
254
|
+
try {
|
|
255
|
+
entries = await fs.promises.readdir(dir, { withFileTypes: true });
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
return files;
|
|
259
|
+
}
|
|
260
|
+
for (const entry of entries) {
|
|
261
|
+
const file = path.join(dir, entry.name);
|
|
262
|
+
if (entry.isDirectory())
|
|
263
|
+
files.push(...await scan(file));
|
|
264
|
+
else if (entry.name.endsWith('.jsonl')) {
|
|
265
|
+
files.push(file);
|
|
266
|
+
const id = /([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.jsonl$/i.exec(entry.name)?.[1];
|
|
267
|
+
if (id && !this.rolloutPathCache.has(id))
|
|
268
|
+
this.rolloutPathCache.set(id, file);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return files;
|
|
272
|
+
};
|
|
273
|
+
// Concurrent topic reads share discovery. Misses are never cached across scans.
|
|
274
|
+
const pending = this.rolloutFilesScan ??= scan(path.join(this.codexHome, 'sessions'));
|
|
275
|
+
try {
|
|
276
|
+
const file = (await pending).find(file => path.basename(file).includes(agentSessionId)) ?? null;
|
|
277
|
+
if (file)
|
|
278
|
+
this.rolloutPathCache.set(agentSessionId, file);
|
|
279
|
+
return file;
|
|
280
|
+
}
|
|
281
|
+
finally {
|
|
282
|
+
if (this.rolloutFilesScan === pending)
|
|
283
|
+
this.rolloutFilesScan = undefined;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
async readMenuSummary(_projectPath, agentSessionId) {
|
|
287
|
+
let row;
|
|
288
|
+
try {
|
|
289
|
+
row = this.getDb()?.prepare('SELECT first_user_message, rollout_path FROM threads WHERE id = ?').get(agentSessionId);
|
|
290
|
+
}
|
|
291
|
+
catch (error) {
|
|
292
|
+
logger.warn('[CodexAdapter] menu summary DB query failed:', error);
|
|
293
|
+
}
|
|
294
|
+
const rollout = await this.findRolloutFileAsync(agentSessionId, row?.rollout_path);
|
|
295
|
+
let turns = 0;
|
|
296
|
+
let rolloutRead = false;
|
|
297
|
+
const messages = [];
|
|
298
|
+
if (rollout) {
|
|
299
|
+
try {
|
|
300
|
+
await visitSessionHistory(rollout, event => {
|
|
301
|
+
if (event?.type === 'turn_context')
|
|
302
|
+
turns++;
|
|
303
|
+
if (event?.type === 'event_msg' && event.payload?.type === 'user_message' && event.payload.message) {
|
|
304
|
+
messages.push(String(event.payload.message));
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
rolloutRead = true;
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
turns = 0;
|
|
311
|
+
messages.length = 0;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const initial = buildCliSessionPreview([row?.first_user_message], 'codex');
|
|
315
|
+
return { turns, firstMessage: row && (initial.hasReal || !rollout || !rolloutRead)
|
|
316
|
+
? initial.title : buildCliSessionPreview(messages, 'codex').title };
|
|
317
|
+
}
|
|
238
318
|
readLastUserMessage(projectPath, agentSessionId) {
|
|
239
319
|
// 1. 优先查 state DB 获取 rollout_path
|
|
240
320
|
const db = this.getDb();
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import path from 'path';
|
|
3
|
+
import { visitSessionHistory } from '../session-fs-store.js';
|
|
3
4
|
import { agentSessionsDir } from '../../../paths.js';
|
|
4
5
|
function projectDirectory(projectPath, agentAid) {
|
|
5
6
|
if (!agentAid?.trim())
|
|
@@ -72,6 +73,27 @@ export class EcagentSessionFileAdapter {
|
|
|
72
73
|
.find(item => item.type === 'message' && item.message?.role === 'user');
|
|
73
74
|
return preview(messageText(entry?.message?.content));
|
|
74
75
|
}
|
|
76
|
+
async readMenuSummary(projectPath, agentSessionId, agentAid) {
|
|
77
|
+
let turns = 0;
|
|
78
|
+
let firstMessage = null;
|
|
79
|
+
const dir = projectDirectory(projectPath, agentAid);
|
|
80
|
+
if (!dir)
|
|
81
|
+
return { turns, firstMessage };
|
|
82
|
+
try {
|
|
83
|
+
const name = (await fs.promises.readdir(dir)).find(name => name.endsWith(`_${agentSessionId}.jsonl`));
|
|
84
|
+
if (name)
|
|
85
|
+
await visitSessionHistory(path.join(dir, name), (entry, line) => {
|
|
86
|
+
if (line === 0 || entry?.type !== 'message' || entry.message?.role !== 'user')
|
|
87
|
+
return;
|
|
88
|
+
if (turns++ === 0)
|
|
89
|
+
firstMessage = preview(messageText(entry.message.content));
|
|
90
|
+
});
|
|
91
|
+
return { turns, firstMessage };
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return { turns: 0, firstMessage: null };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
75
97
|
readLastUserMessage(projectPath, agentSessionId, agentAid) {
|
|
76
98
|
const entries = this.readEntries(projectPath, agentSessionId, agentAid)
|
|
77
99
|
.filter(item => item.type === 'message' && item.message?.role === 'user');
|
|
@@ -120,6 +120,45 @@ export class GeminiSessionFileAdapter {
|
|
|
120
120
|
readFirstMessage(projectPath, agentSessionId) {
|
|
121
121
|
return this.readUserMessage(projectPath, agentSessionId, 'first');
|
|
122
122
|
}
|
|
123
|
+
async readMenuSummary(projectPath, agentSessionId) {
|
|
124
|
+
const home = this.getGeminiHome();
|
|
125
|
+
let projectKey;
|
|
126
|
+
try {
|
|
127
|
+
const data = JSON.parse(await fs.promises.readFile(path.join(home, 'projects.json'), 'utf8'));
|
|
128
|
+
const mapped = data?.projects?.[projectPath];
|
|
129
|
+
if (typeof mapped === 'string' && mapped.trim())
|
|
130
|
+
projectKey = mapped;
|
|
131
|
+
}
|
|
132
|
+
catch { /* Match the existing project-root fallback. */ }
|
|
133
|
+
if (!projectKey) {
|
|
134
|
+
try {
|
|
135
|
+
for (const entry of await fs.promises.readdir(path.join(home, 'tmp'), { withFileTypes: true })) {
|
|
136
|
+
if (!entry.isDirectory())
|
|
137
|
+
continue;
|
|
138
|
+
try {
|
|
139
|
+
if ((await fs.promises.readFile(path.join(home, 'tmp', entry.name, '.project_root'), 'utf8')).trim() === projectPath) {
|
|
140
|
+
projectKey = entry.name;
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
catch { /* Ignore broken project roots. */ }
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
catch { /* Use the basename fallback. */ }
|
|
148
|
+
}
|
|
149
|
+
const dir = path.join(home, 'tmp', projectKey ?? path.basename(projectPath), 'chats');
|
|
150
|
+
try {
|
|
151
|
+
const name = (await fs.promises.readdir(dir)).find(name => name.includes(agentSessionId.slice(0, 8)) && name.endsWith('.json'));
|
|
152
|
+
if (!name)
|
|
153
|
+
return { turns: 0, firstMessage: null };
|
|
154
|
+
const data = JSON.parse(await fs.promises.readFile(path.join(dir, name), 'utf8'));
|
|
155
|
+
return { turns: (data.messages || []).filter((message) => message.type === 'user').length,
|
|
156
|
+
firstMessage: this.buildSessionPreview(data).title };
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return { turns: 0, firstMessage: null };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
123
162
|
readLastUserMessage(projectPath, agentSessionId) {
|
|
124
163
|
return this.readUserMessage(projectPath, agentSessionId, 'last');
|
|
125
164
|
}
|
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import fsPromises from 'fs/promises';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
6
|
+
import path from 'path';
|
|
2
7
|
import { logger } from '../../utils/logger.js';
|
|
8
|
+
import { withFileLock } from '../../utils/atomic-write.js';
|
|
3
9
|
/**
|
|
4
10
|
* 检查会话文件健康度(接收完整文件路径)
|
|
5
11
|
*/
|
|
@@ -43,3 +49,240 @@ export async function backupSessionFile(sessionFile) {
|
|
|
43
49
|
logger.info(`[SessionFileHealth] Backup created: ${backupPath}`);
|
|
44
50
|
return backupPath;
|
|
45
51
|
}
|
|
52
|
+
const requireFromHere = createRequire(import.meta.url);
|
|
53
|
+
const repairHash = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
54
|
+
function syncRepairDirectory(directory) {
|
|
55
|
+
if (process.platform === 'win32')
|
|
56
|
+
return;
|
|
57
|
+
const fd = fs.openSync(directory, 'r');
|
|
58
|
+
try {
|
|
59
|
+
fs.fsyncSync(fd);
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
fs.closeSync(fd);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function writeRepairSnapshot(file, content) {
|
|
66
|
+
const fd = fs.openSync(file, 'wx', 0o600);
|
|
67
|
+
try {
|
|
68
|
+
fs.writeFileSync(fd, content);
|
|
69
|
+
fs.fsyncSync(fd);
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
fs.closeSync(fd);
|
|
73
|
+
}
|
|
74
|
+
syncRepairDirectory(path.dirname(file));
|
|
75
|
+
}
|
|
76
|
+
function codexMetadata(bytes, threadId) {
|
|
77
|
+
const end = bytes.indexOf(10);
|
|
78
|
+
const line = bytes.subarray(0, end < 0 ? bytes.length : end).toString('utf8');
|
|
79
|
+
const event = JSON.parse(line);
|
|
80
|
+
if (event.type !== 'session_meta' || !(event.payload?.id || event.payload?.session_id)
|
|
81
|
+
|| [event.payload.id, event.payload.session_id].some(id => id !== undefined && id !== threadId)
|
|
82
|
+
|| typeof event.payload.model_provider !== 'string' || !event.payload.model_provider) {
|
|
83
|
+
throw new Error('Codex Provider repair rejected: session metadata does not match the bound thread');
|
|
84
|
+
}
|
|
85
|
+
return { line, end: end < 0 ? bytes.length : end, provider: event.payload.model_provider };
|
|
86
|
+
}
|
|
87
|
+
function rewriteCodexProvider(bytes, threadId, provider) {
|
|
88
|
+
const header = codexMetadata(bytes, threadId);
|
|
89
|
+
const property = /("model_provider"\s*:\s*)"(?:\\.|[^"\\])*"/g;
|
|
90
|
+
const matches = [...header.line.matchAll(property)];
|
|
91
|
+
if (matches.length !== 1)
|
|
92
|
+
throw new Error('Codex Provider repair rejected: ambiguous Provider metadata');
|
|
93
|
+
const line = header.line.replace(property, (_value, prefix) => prefix + JSON.stringify(provider));
|
|
94
|
+
const expected = JSON.parse(header.line);
|
|
95
|
+
expected.payload.model_provider = provider;
|
|
96
|
+
if (!isDeepStrictEqual(JSON.parse(line), expected))
|
|
97
|
+
throw new Error('Codex Provider repair changed unrelated metadata');
|
|
98
|
+
return Buffer.concat([Buffer.from(line), bytes.subarray(header.end)]);
|
|
99
|
+
}
|
|
100
|
+
function readCodexProviderHeader(file, threadId) {
|
|
101
|
+
const fd = fs.openSync(file, 'r');
|
|
102
|
+
try {
|
|
103
|
+
const chunks = [];
|
|
104
|
+
let length = 0;
|
|
105
|
+
while (length < 1024 * 1024) {
|
|
106
|
+
const chunk = Buffer.alloc(16 * 1024);
|
|
107
|
+
const read = fs.readSync(fd, chunk, 0, chunk.length, null);
|
|
108
|
+
if (!read)
|
|
109
|
+
return codexMetadata(Buffer.concat(chunks), threadId).provider;
|
|
110
|
+
const end = chunk.subarray(0, read).indexOf(10);
|
|
111
|
+
chunks.push(chunk.subarray(0, end < 0 ? read : end + 1));
|
|
112
|
+
if (end >= 0)
|
|
113
|
+
return codexMetadata(Buffer.concat(chunks), threadId).provider;
|
|
114
|
+
length += read;
|
|
115
|
+
}
|
|
116
|
+
throw new Error('Codex Provider repair rejected: oversized session metadata');
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
fs.closeSync(fd);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function assertRepairFile(file, root) {
|
|
123
|
+
const relative = path.relative(root, fs.realpathSync(file));
|
|
124
|
+
const stat = fs.lstatSync(file);
|
|
125
|
+
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)
|
|
126
|
+
|| !stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) {
|
|
127
|
+
throw new Error('Codex Provider repair rejected: unsafe storage path');
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Change only the Provider of an existing Codex thread. Rollout bytes after the
|
|
132
|
+
* header and the EC/backend IDs are preserved. The durable intent plus before
|
|
133
|
+
* snapshot recover a crash between the filesystem rename and SQLite commit.
|
|
134
|
+
* This is called only by the runner for an authoritative EC thread binding.
|
|
135
|
+
*/
|
|
136
|
+
export async function repairCodexSessionProvider(options) {
|
|
137
|
+
const { threadId, provider } = options;
|
|
138
|
+
if (!/^evolcore_registry_[a-f0-9]{20}$/.test(provider)) {
|
|
139
|
+
throw new Error('Codex Provider repair requires a resolved registry Provider');
|
|
140
|
+
}
|
|
141
|
+
const home = fs.realpathSync(options.codexHome);
|
|
142
|
+
const rollout = path.resolve(options.sessionFile);
|
|
143
|
+
const sessions = ['sessions', 'archived_sessions'].find(name => {
|
|
144
|
+
const relative = path.relative(path.join(home, name), rollout);
|
|
145
|
+
return relative && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
|
|
146
|
+
});
|
|
147
|
+
if (!sessions || !path.basename(rollout).endsWith(threadId + '.jsonl')) {
|
|
148
|
+
throw new Error('Codex Provider repair rejected: rollout is outside Codex session storage');
|
|
149
|
+
}
|
|
150
|
+
assertRepairFile(rollout, fs.realpathSync(path.join(home, sessions)));
|
|
151
|
+
const databaseName = fs.readdirSync(home).filter(name => /^state_\d+\.sqlite$/.test(name))
|
|
152
|
+
.sort((a, b) => Number(b.match(/\d+/)[0]) - Number(a.match(/\d+/)[0]))[0];
|
|
153
|
+
if (!databaseName)
|
|
154
|
+
throw new Error('Codex Provider repair requires a supported thread index');
|
|
155
|
+
const database = path.join(home, databaseName);
|
|
156
|
+
assertRepairFile(database, home);
|
|
157
|
+
const { DatabaseSync } = requireFromHere('node:sqlite');
|
|
158
|
+
const directory = rollout + '.provider-repair';
|
|
159
|
+
const journalFile = path.join(directory, 'intent.json');
|
|
160
|
+
const readIndex = () => {
|
|
161
|
+
const db = new DatabaseSync(database, { readOnly: true });
|
|
162
|
+
try {
|
|
163
|
+
const row = db.prepare('SELECT model_provider, rollout_path FROM threads WHERE id = ?').get(threadId);
|
|
164
|
+
if (!row || typeof row.model_provider !== 'string' || typeof row.rollout_path !== 'string'
|
|
165
|
+
|| path.resolve(row.rollout_path) !== rollout)
|
|
166
|
+
throw new Error('Codex thread index does not match its rollout');
|
|
167
|
+
return row;
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
db.close();
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
if (!fs.existsSync(journalFile) && readCodexProviderHeader(rollout, threadId) === provider
|
|
174
|
+
&& readIndex().model_provider === provider)
|
|
175
|
+
return false;
|
|
176
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
177
|
+
if (fs.lstatSync(directory).isSymbolicLink()
|
|
178
|
+
|| fs.realpathSync(directory) !== path.join(path.dirname(fs.realpathSync(rollout)), path.basename(directory))) {
|
|
179
|
+
throw new Error('Codex Provider repair rejected: unsafe backup directory');
|
|
180
|
+
}
|
|
181
|
+
return withFileLock(path.join(directory, 'operation.lock'), async () => {
|
|
182
|
+
const before = fs.readFileSync(rollout);
|
|
183
|
+
const index = readIndex();
|
|
184
|
+
const header = codexMetadata(before, threadId);
|
|
185
|
+
if (!fs.existsSync(journalFile) && header.provider === provider && index.model_provider === provider)
|
|
186
|
+
return false;
|
|
187
|
+
await options.releaseThread();
|
|
188
|
+
assertRepairFile(rollout, fs.realpathSync(path.join(home, sessions)));
|
|
189
|
+
if (repairHash(fs.readFileSync(rollout)) !== repairHash(before)
|
|
190
|
+
|| !isDeepStrictEqual(readIndex(), index))
|
|
191
|
+
throw new Error('Codex session changed while preparing Provider repair');
|
|
192
|
+
const apply = (intent) => {
|
|
193
|
+
const backupRoot = path.join(directory, path.basename(path.dirname(intent.backup)));
|
|
194
|
+
if (intent.version !== 1 || intent.threadId !== threadId || intent.database !== database
|
|
195
|
+
|| intent.rollout !== rollout || path.resolve(intent.indexedPath) !== rollout
|
|
196
|
+
|| intent.backup !== path.join(backupRoot, 'before.snapshot')
|
|
197
|
+
|| intent.next !== path.join(backupRoot, 'after.snapshot')
|
|
198
|
+
|| !/^evolcore_registry_[a-f0-9]{20}$/.test(intent.provider)) {
|
|
199
|
+
throw new Error('Invalid Codex Provider repair journal');
|
|
200
|
+
}
|
|
201
|
+
assertRepairFile(intent.backup, directory);
|
|
202
|
+
const original = fs.readFileSync(intent.backup);
|
|
203
|
+
const replacement = rewriteCodexProvider(original, threadId, intent.provider);
|
|
204
|
+
if (repairHash(original) !== intent.beforeHash || repairHash(replacement) !== intent.afterHash) {
|
|
205
|
+
throw new Error('Codex Provider repair snapshot failed integrity verification');
|
|
206
|
+
}
|
|
207
|
+
const db = new DatabaseSync(database);
|
|
208
|
+
let transaction = false;
|
|
209
|
+
let replaced = false;
|
|
210
|
+
try {
|
|
211
|
+
db.exec('PRAGMA busy_timeout = 3000');
|
|
212
|
+
db.exec('BEGIN IMMEDIATE');
|
|
213
|
+
transaction = true;
|
|
214
|
+
const row = db.prepare('SELECT model_provider, rollout_path FROM threads WHERE id = ?').get(threadId);
|
|
215
|
+
const currentHash = repairHash(fs.readFileSync(rollout));
|
|
216
|
+
if (!row || row.rollout_path !== intent.indexedPath
|
|
217
|
+
|| ![intent.previousProvider, intent.provider].includes(row.model_provider)
|
|
218
|
+
|| ![intent.beforeHash, intent.afterHash].includes(currentHash)) {
|
|
219
|
+
throw new Error('Codex Provider repair conflicts with newer session data');
|
|
220
|
+
}
|
|
221
|
+
if (currentHash !== intent.afterHash) {
|
|
222
|
+
if (fs.existsSync(intent.next)) {
|
|
223
|
+
assertRepairFile(intent.next, directory);
|
|
224
|
+
if (repairHash(fs.readFileSync(intent.next)) !== intent.afterHash)
|
|
225
|
+
throw new Error('Invalid repair snapshot');
|
|
226
|
+
}
|
|
227
|
+
else
|
|
228
|
+
writeRepairSnapshot(intent.next, replacement);
|
|
229
|
+
fs.chmodSync(intent.next, fs.statSync(rollout).mode & 0o777);
|
|
230
|
+
fs.renameSync(intent.next, rollout);
|
|
231
|
+
replaced = true;
|
|
232
|
+
syncRepairDirectory(path.dirname(rollout));
|
|
233
|
+
}
|
|
234
|
+
if (row.model_provider !== intent.provider) {
|
|
235
|
+
const changed = db.prepare('UPDATE threads SET model_provider = ? WHERE id = ? AND model_provider = ?')
|
|
236
|
+
.run(intent.provider, threadId, intent.previousProvider);
|
|
237
|
+
if (changed.changes !== 1)
|
|
238
|
+
throw new Error('Codex Provider repair index update conflicted');
|
|
239
|
+
}
|
|
240
|
+
db.exec('COMMIT');
|
|
241
|
+
transaction = false;
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
if (transaction)
|
|
245
|
+
db.exec('ROLLBACK');
|
|
246
|
+
if (replaced && repairHash(fs.readFileSync(rollout)) === intent.afterHash) {
|
|
247
|
+
const rollback = path.join(backupRoot, 'rollback-' + randomUUID() + '.snapshot');
|
|
248
|
+
writeRepairSnapshot(rollback, original);
|
|
249
|
+
fs.chmodSync(rollback, fs.statSync(rollout).mode & 0o777);
|
|
250
|
+
fs.renameSync(rollback, rollout);
|
|
251
|
+
syncRepairDirectory(path.dirname(rollout));
|
|
252
|
+
}
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
db.close();
|
|
257
|
+
}
|
|
258
|
+
fs.unlinkSync(journalFile);
|
|
259
|
+
syncRepairDirectory(directory);
|
|
260
|
+
};
|
|
261
|
+
if (fs.existsSync(journalFile)) {
|
|
262
|
+
assertRepairFile(journalFile, directory);
|
|
263
|
+
apply(JSON.parse(fs.readFileSync(journalFile, 'utf8')));
|
|
264
|
+
}
|
|
265
|
+
const bytes = fs.readFileSync(rollout);
|
|
266
|
+
const current = readIndex();
|
|
267
|
+
if (codexMetadata(bytes, threadId).provider !== provider || current.model_provider !== provider) {
|
|
268
|
+
if (codexMetadata(bytes, threadId).provider !== current.model_provider) {
|
|
269
|
+
throw new Error('Codex Provider repair rejected: rollout and index disagree');
|
|
270
|
+
}
|
|
271
|
+
const backupRoot = path.join(directory, randomUUID());
|
|
272
|
+
fs.mkdirSync(backupRoot, { mode: 0o700 });
|
|
273
|
+
const replacement = rewriteCodexProvider(bytes, threadId, provider);
|
|
274
|
+
const intent = {
|
|
275
|
+
version: 1, threadId, database, rollout, indexedPath: current.rollout_path,
|
|
276
|
+
previousProvider: current.model_provider, provider,
|
|
277
|
+
beforeHash: repairHash(bytes), afterHash: repairHash(replacement),
|
|
278
|
+
backup: path.join(backupRoot, 'before.snapshot'), next: path.join(backupRoot, 'after.snapshot'),
|
|
279
|
+
};
|
|
280
|
+
writeRepairSnapshot(intent.backup, bytes);
|
|
281
|
+
writeRepairSnapshot(intent.next, replacement);
|
|
282
|
+
writeRepairSnapshot(journalFile, JSON.stringify(intent));
|
|
283
|
+
apply(intent);
|
|
284
|
+
}
|
|
285
|
+
logger.info(`[SessionFileHealth] Codex Provider repaired: thread=${threadId} provider=${provider}`);
|
|
286
|
+
return true;
|
|
287
|
+
});
|
|
288
|
+
}
|