evolcore 0.0.43-test.3 → 0.0.43-test.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/bin/ecmsg.js +492 -0
  3. package/bin/install-codex-managed-hooks.mjs +130 -8
  4. package/dist/ability/application-service.js +37 -0
  5. package/dist/ability/resources.js +28 -0
  6. package/dist/ability/runtime.js +6 -1
  7. package/dist/agents/claude-runner.js +7 -5
  8. package/dist/agents/codex/app-server-client.js +0 -12
  9. package/dist/agents/codex-runner.js +12 -54
  10. package/dist/agents/ecagent-runner.js +130 -35
  11. package/dist/aun/aid/agentmd.js +56 -12
  12. package/dist/aun/aid/control-aid.js +15 -0
  13. package/dist/aun/aid/identity.js +8 -0
  14. package/dist/aun/aid/ownership-operation.js +12 -3
  15. package/dist/aun/menu/client.js +8 -7
  16. package/dist/aun/menu/index.js +1 -1
  17. package/dist/aun/menu/transport.js +8 -5
  18. package/dist/aun/service-proxy.js +3 -0
  19. package/dist/channels/aun.js +56 -22
  20. package/dist/channels/daemon.js +12 -4
  21. package/dist/cli/agent-command.js +5 -0
  22. package/dist/cli/agent-create.js +32 -8
  23. package/dist/cli/agent.js +9 -3
  24. package/dist/cli/aid-bind-command.js +3 -0
  25. package/dist/cli/aun-commands.js +12 -5
  26. package/dist/cli/code-stats.js +451 -213
  27. package/dist/cli/ctl-command.js +1 -3
  28. package/dist/cli/daemon-commands.js +42 -21
  29. package/dist/cli/directory.js +7 -8
  30. package/dist/cli/ecmsg-gateway.js +204 -0
  31. package/dist/cli/getmeta-command.js +2 -1
  32. package/dist/cli/index.js +6 -0
  33. package/dist/cli/init.js +58 -18
  34. package/dist/cli/provider-command.js +82 -5
  35. package/dist/cli/restart-monitor.js +11 -19
  36. package/dist/cli/stats.js +8 -1
  37. package/dist/cli/task-context.js +3 -0
  38. package/dist/cli/trigger-command.js +20 -14
  39. package/dist/config/boot-log.js +23 -2
  40. package/dist/config/config-field-policy.js +2 -0
  41. package/dist/config/config-manager.js +13 -17
  42. package/dist/config/daemon-services.js +1 -0
  43. package/dist/config/peer-role-resolver.js +6 -6
  44. package/dist/config/provider-identity-migration.js +202 -0
  45. package/dist/config/provider-identity.js +37 -0
  46. package/dist/config/provider-ipc-service.js +40 -3
  47. package/dist/config/provider-local-sync.js +153 -0
  48. package/dist/config/providers-config.js +32 -4
  49. package/dist/config/providers-management.js +144 -68
  50. package/dist/config/providers.js +4 -1
  51. package/dist/config/role-schema.js +3 -3
  52. package/dist/config/schema-migration.js +188 -3
  53. package/dist/core/agent-application-service.js +11 -0
  54. package/dist/core/agent-ipc-registration.js +2 -0
  55. package/dist/core/agent-runtime.js +45 -11
  56. package/dist/core/auth/auth-gateway.js +8 -6
  57. package/dist/core/auth/delegation-diagnostics.js +6 -2
  58. package/dist/core/auth/operation-authorizer.js +5 -2
  59. package/dist/core/auth/operation-catalog.js +6 -4
  60. package/dist/core/baseagent-loader.js +11 -3
  61. package/dist/core/bootstrap-service.js +8 -0
  62. package/dist/core/channel-loader.js +61 -23
  63. package/dist/core/command/agent-control.js +4 -1
  64. package/dist/core/command/chatmode-config.js +46 -0
  65. package/dist/core/command/cli-intent-parser.js +2 -1
  66. package/dist/core/command/command-handler.js +16 -20
  67. package/dist/core/command/daemon-diagnostics.js +2 -1
  68. package/dist/core/command/menu-catalog.js +1 -1
  69. package/dist/core/command/menu-handler.js +16 -16
  70. package/dist/core/command/menu-protocol.js +4 -2
  71. package/dist/core/command/provider-menu.js +4 -2
  72. package/dist/core/command/role-menu.js +2 -2
  73. package/dist/core/command/slash-handler.js +56 -42
  74. package/dist/core/daemon-lifecycle.js +35 -17
  75. package/dist/core/event-catalog.js +19 -0
  76. package/dist/core/evolagent-registry.js +3 -0
  77. package/dist/core/handoff/runtime.js +9 -3
  78. package/dist/core/initialization/service.js +4 -3
  79. package/dist/core/ipc-registration.js +6 -0
  80. package/dist/core/message/aun-ipc-sender.js +81 -3
  81. package/dist/core/message/im-renderer.js +24 -19
  82. package/dist/core/message/message-admission.js +13 -2
  83. package/dist/core/message/response-engine.js +40 -41
  84. package/dist/core/message/send-options.js +40 -0
  85. package/dist/core/message/send-routing.js +310 -0
  86. package/dist/core/model/model-capabilities.js +37 -0
  87. package/dist/core/model/model-catalog.js +6 -2
  88. package/dist/core/ownership/owner-resolver.js +117 -14
  89. package/dist/core/permission/ec-command-parser.js +195 -27
  90. package/dist/core/permission/readonly-shell-query.js +66 -7
  91. package/dist/core/permission/tool-error-code.js +13 -1
  92. package/dist/core/permission/tool-policy.js +74 -20
  93. package/dist/core/plugin-lifecycle.js +6 -2
  94. package/dist/core/relation/pa-team.js +7 -2
  95. package/dist/core/relation/same-owner-proof.js +131 -0
  96. package/dist/core/session/session-idle-monitor.js +94 -16
  97. package/dist/core/session/session-manager.js +69 -16
  98. package/dist/core/thread/thread-route.js +5 -2
  99. package/dist/directory/owner-directory-cache.js +690 -99
  100. package/dist/directory/owner-directory-markdown.js +146 -36
  101. package/dist/directory/owner-directory-query-operation.js +7 -9
  102. package/dist/directory/owner-directory-scope.js +12 -0
  103. package/dist/directory/owner-directory-search.js +5 -1
  104. package/dist/directory/owner-directory-store.js +28 -0
  105. package/dist/ecweb/basic-settings-service.js +15 -1
  106. package/dist/ecweb/message-context-service.js +2 -2
  107. package/dist/ecweb/providers-service.js +3 -1
  108. package/dist/ecweb/runtime/lifecycle.js +38 -5
  109. package/dist/ecweb/runtime/supervisor.js +157 -49
  110. package/dist/index.js +202 -38
  111. package/dist/paths.js +2 -1
  112. package/dist/proxy/manager.js +2 -0
  113. package/dist/proxy/service-supervisor.js +379 -143
  114. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  115. package/dist/trigger/application-service.js +1 -0
  116. package/dist/trigger/audit.js +3 -2
  117. package/dist/trigger/authorization.js +2 -3
  118. package/dist/trigger/event-source.js +4 -0
  119. package/dist/trigger/feedback.js +26 -2
  120. package/dist/trigger/history.js +4 -3
  121. package/dist/trigger/ipc-service.js +24 -19
  122. package/dist/trigger/manager.js +3 -5
  123. package/dist/trigger/parser.js +4 -21
  124. package/dist/trigger/patch.js +3 -15
  125. package/dist/trigger/scheduler.js +48 -13
  126. package/dist/trigger/system-definitions.js +2 -2
  127. package/dist/trigger/validation.js +4 -13
  128. package/dist/utils/autostart.js +2 -2
  129. package/dist/utils/cross-platform.js +36 -8
  130. package/dist/utils/error-utils.js +8 -0
  131. package/dist/utils/macos-autostart.js +31 -0
  132. package/dist/utils/model-prices.jsonl +15 -8
  133. package/dist/utils/process-introspect.js +21 -1
  134. package/dist/utils/public-suffix.js +5811 -0
  135. package/dist/utils/startup-trace.js +7 -1
  136. package/dist/utils/windows-autostart.js +42 -7
  137. package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
  138. package/ecagent/dist/harness/compaction/compaction.js +4 -4
  139. package/ecagent/dist/harness/env/nodejs.js +46 -2
  140. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  141. package/kits/docs/channels/aun.md +1 -1
  142. package/kits/docs/channels/feishu.md +2 -2
  143. package/kits/docs/context-assembly.md +20 -4
  144. package/kits/docs/evolcore/INDEX.md +3 -2
  145. package/kits/docs/evolcore/agent.md +2 -2
  146. package/kits/docs/evolcore/aid.md +8 -2
  147. package/kits/docs/evolcore/ctl.md +13 -4
  148. package/kits/docs/evolcore/directory.md +48 -15
  149. package/kits/docs/evolcore/file-navigation.md +63 -49
  150. package/kits/docs/evolcore/group.md +6 -6
  151. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  152. package/kits/docs/evolcore/menu-protocol.md +33 -3
  153. package/kits/docs/evolcore/model.md +5 -3
  154. package/kits/docs/evolcore/msg.md +28 -27
  155. package/kits/docs/evolcore/provider.md +39 -5
  156. package/kits/docs/evolcore/response.md +3 -1
  157. package/kits/docs/evolcore/thread-chain.md +12 -14
  158. package/kits/docs/evolcore/tool-authorization.md +21 -1
  159. package/kits/docs/evolcore/trigger.md +12 -9
  160. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  161. package/kits/docs/prompt-loading-architecture.md +30 -20
  162. package/kits/eck_manifest.auxiliary.json +5 -5
  163. package/kits/eck_manifest.json +28 -49
  164. package/kits/eck_manifest.memory.json +18 -18
  165. package/kits/rules/01-overview.md +43 -45
  166. package/kits/rules/02-navigation.md +44 -53
  167. package/kits/rules/03-identity.md +21 -25
  168. package/kits/rules/04-relation.md +23 -33
  169. package/kits/rules/05-venue.md +24 -25
  170. package/kits/rules/06-channel.md +3 -3
  171. package/kits/schemas/_meta.json +20 -27
  172. package/kits/schemas/agent-config.schema.19.json +10 -6
  173. package/kits/schemas/providers.schema.2.json +74 -0
  174. package/kits/schemas/relation-config.schema.12.json +2 -2
  175. package/kits/schemas/role-config.schema.2.json +5 -5
  176. package/kits/schemas/role-registry.schema.1.json +1 -1
  177. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  178. package/kits/skills/ec-service-proxy/SKILL.md +3 -0
  179. package/kits/skills/ec-trigger/SKILL.md +4 -4
  180. package/kits/skills/ec-trigger/references/examples.md +1 -1
  181. package/kits/templates/system-fragments/channel.md +5 -5
  182. package/kits/templates/system-fragments/commands.md +3 -2
  183. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  184. package/kits/templates/system-fragments/identity.md +0 -1
  185. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  186. package/kits/templates/system-fragments/reply.md +47 -28
  187. package/kits/templates/system-fragments/session.md +2 -9
  188. package/kits/templates/system-fragments/thread.md +5 -5
  189. package/package.json +17 -13
  190. package/kits/schemas/agent-config.schema.20.json +0 -925
  191. package/kits/schemas/relation-config.schema.13.json +0 -289
  192. package/kits/schemas/role-config.schema.3.json +0 -1038
@@ -121,6 +121,23 @@ function windowsPostinstallNotice() {
121
121
  );
122
122
  }
123
123
 
124
+ function normalizeTomlTables(value) {
125
+ if (Array.isArray(value)) return value.map(normalizeTomlTables);
126
+ if (value && typeof value === 'object') {
127
+ const prototype = Object.getPrototypeOf(value);
128
+ if (prototype === null || prototype === Object.prototype) {
129
+ const table = Object.create(null);
130
+ for (const [key, entry] of Object.entries(value)) table[key] = normalizeTomlTables(entry);
131
+ return table;
132
+ }
133
+ }
134
+ return value;
135
+ }
136
+
137
+ function equalTomlTables(left, right) {
138
+ return isDeepStrictEqual(normalizeTomlTables(left), normalizeTomlTables(right));
139
+ }
140
+
124
141
  function removeManagedBlock(source) {
125
142
  const original = parseToml(source);
126
143
  if (!source.includes(markerStart) && !source.includes(markerEnd)) return source;
@@ -131,7 +148,7 @@ function removeManagedBlock(source) {
131
148
  const block = parseToml(matches[0][0]);
132
149
  const groups = block.hooks?.PreToolUse;
133
150
  if (!Array.isArray(groups) || groups.length !== 1
134
- || !isDeepStrictEqual(block, { hooks: { PreToolUse: groups } })) throw unsafe();
151
+ || !equalTomlTables(block, { hooks: { PreToolUse: groups } })) throw unsafe();
135
152
  const content = source.replace(matches[0][0], '');
136
153
  const retained = parseToml(content);
137
154
  const originalGroups = original.hooks?.PreToolUse;
@@ -139,12 +156,12 @@ function removeManagedBlock(source) {
139
156
  // Markers inside a TOML string are not comments. Prove that removing the
140
157
  // block removes only its Hook group, with every other policy unchanged.
141
158
  const safe = originalGroups.some((group, index) => {
142
- if (!isDeepStrictEqual(group, groups[0])) return false;
143
- const expected = structuredClone(original);
159
+ if (!equalTomlTables(group, groups[0])) return false;
160
+ const expected = parseToml(source);
144
161
  expected.hooks.PreToolUse.splice(index, 1);
145
162
  if (!expected.hooks.PreToolUse.length && !retained.hooks?.PreToolUse) delete expected.hooks.PreToolUse;
146
163
  if (!Object.keys(expected.hooks).length && !retained.hooks) delete expected.hooks;
147
- return isDeepStrictEqual(expected, retained);
164
+ return equalTomlTables(expected, retained);
148
165
  });
149
166
  if (!safe) throw unsafe();
150
167
  return content;
@@ -255,7 +272,7 @@ export function buildManagedRequirements(source, { targetDirectory, nodePath, ho
255
272
  ],
256
273
  },
257
274
  };
258
- if (!isDeepStrictEqual(after, expected)) {
275
+ if (!equalTomlTables(after, expected)) {
259
276
  throw new Error('Could not safely update requirements.toml without changing unrelated policy. Existing configuration was not modified.');
260
277
  }
261
278
  return content;
@@ -344,7 +361,7 @@ export function managedBinding(source, launcher, hookPath) {
344
361
  const retainedConfig = parseToml(retained);
345
362
  const groups = original.hooks?.PreToolUse;
346
363
  const retainedGroups = retainedConfig.hooks?.PreToolUse || [];
347
- const owned = groups.filter(group => !retainedGroups.some(other => isDeepStrictEqual(group, other)));
364
+ const owned = groups.filter(group => !retainedGroups.some(other => equalTomlTables(group, other)));
348
365
  if (owned.length !== 1) return null;
349
366
  const group = owned[0];
350
367
  if (group.matcher !== '*' || !Array.isArray(group.hooks) || group.hooks.length !== 1) return null;
@@ -353,7 +370,7 @@ export function managedBinding(source, launcher, hookPath) {
353
370
  const command = parseManagedCommand(handler.command, hookPath);
354
371
  const windowsCommand = parseManagedCommand(handler.command_windows, hookPath);
355
372
  if (!command || !windowsCommand || normalizedPath(command.nodePath) !== normalizedPath(windowsCommand.nodePath)) return null;
356
- if (!isDeepStrictEqual(group, { matcher: '*', hooks: [{
373
+ if (!equalTomlTables(group, { matcher: '*', hooks: [{
357
374
  type: 'command', command: handler.command, command_windows: handler.command_windows,
358
375
  statusMessage: 'Checking EvolCore session policy',
359
376
  }] })) return null;
@@ -441,6 +458,87 @@ export function inspectManagedHookInstallation({ requirements, managedDir, packa
441
458
  }
442
459
  }
443
460
 
461
+ export function removeManagedHookInstallation(options, acl = windowsAcl) {
462
+ const { requirements, managedDir, packageRoot, nodePath = process.execPath } = options;
463
+ const canonicalRequirements = path.resolve(requirements);
464
+ const canonicalManagedDir = path.resolve(managedDir);
465
+ const hookPath = path.join(canonicalManagedDir, 'pre-tool-use.mjs');
466
+ if (!packageRoot || !path.isAbsolute(packageRoot)) throw new Error('An absolute --package-root is required for managed hook removal.');
467
+ for (const target of [path.dirname(canonicalRequirements), canonicalManagedDir]) {
468
+ for (let directory = target; ; directory = path.dirname(directory)) {
469
+ try {
470
+ const stat = fs.lstatSync(directory);
471
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Expected a real managed-hook directory: ${directory}`);
472
+ } catch (error) {
473
+ if (error?.code !== 'ENOENT') throw error;
474
+ }
475
+ if (directory === path.dirname(directory)) break;
476
+ }
477
+ }
478
+ const req = regularFile(canonicalRequirements);
479
+ const hook = regularFile(hookPath);
480
+ if (req.ok && !hook.ok && !hook.unsafe) {
481
+ const content = fs.readFileSync(canonicalRequirements, 'utf8');
482
+ const parsed = parseToml(content);
483
+ if (!sourceHasManagedMarker(content)
484
+ && !JSON.stringify(parsed.hooks?.PreToolUse || []).toLowerCase().includes('pre-tool-use.mjs')) {
485
+ return { status: 'absent', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath };
486
+ }
487
+ }
488
+ const state = inspectManagedHookInstallation({ requirements: canonicalRequirements, managedDir: canonicalManagedDir, packageRoot, nodePath });
489
+ if (state.status === 'missing') return { ...state, status: 'absent' };
490
+ if (state.status === 'stale' && !samePackageRoot(state.managedPackageRoot, packageRoot)) {
491
+ return { ...state, status: 'preserved', reason: 'managed-hook belongs to a different EvolCore installation' };
492
+ }
493
+ if (state.status !== 'installed') throw new Error(`Refusing managed-hook removal: ${state.reason}`);
494
+ const source = fs.readFileSync(canonicalRequirements, 'utf8');
495
+ const launcher = fs.readFileSync(hookPath, 'utf8');
496
+ if (createHash('sha256').update(source).update('\0').update(launcher).digest('hex') !== state.repairFingerprint) {
497
+ throw new Error('Managed-hook state changed during ownership verification; retry the uninstall.');
498
+ }
499
+ const retained = removeManagedBlock(source);
500
+ acl('preflight');
501
+ const lockPath = path.join(path.dirname(canonicalRequirements), '.evolcore-hooks.install.lock');
502
+ let lock;
503
+ try { lock = fs.openSync(lockPath, 'wx', 0o600); } catch (error) {
504
+ throw new Error(`Cannot acquire installer lock ${lockPath}: ${error.message}. Confirm the other installer has stopped before retrying.`, { cause: error });
505
+ }
506
+ const temporary = `${canonicalRequirements}.evolcore-${randomUUID()}.tmp`;
507
+ const warnings = [];
508
+ try {
509
+ fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, started: new Date().toISOString(), operation: 'uninstall' }));
510
+ fs.writeFileSync(temporary, retained, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
511
+ acl('prepare', { path: temporary, reference: canonicalRequirements });
512
+ acl('verify', { entries: [
513
+ { path: canonicalManagedDir, protected: true, execute: true },
514
+ { path: temporary, protected: true },
515
+ { path: hookPath, protected: true },
516
+ ] });
517
+ const unchanged = (file, expected) => () => {
518
+ existingFile(file, fs);
519
+ if (fs.readFileSync(file, 'utf8') !== expected) throw new Error(`Managed-hook file changed before removal: ${file}`);
520
+ };
521
+ warnings.push(...commitPreparedFiles([
522
+ { file: canonicalRequirements, temporary, validate: unchanged(canonicalRequirements, source) },
523
+ { file: hookPath, remove: true, validate: unchanged(hookPath, launcher) },
524
+ ], () => {
525
+ if (fs.readFileSync(canonicalRequirements, 'utf8') !== retained || fs.existsSync(hookPath)) {
526
+ throw new Error('Managed-hook removal could not be verified.');
527
+ }
528
+ acl('verify', { entries: [{ path: canonicalRequirements, protected: true }] });
529
+ }));
530
+ try { fs.rmdirSync(canonicalManagedDir); } catch (error) {
531
+ if (!['ENOTEMPTY', 'EEXIST', 'ENOENT'].includes(error?.code)) warnings.push(`Managed-hook directory was preserved: ${error.message}`);
532
+ }
533
+ } finally {
534
+ try { fs.rmSync(temporary, { force: true }); } catch (error) { warnings.push(`Could not remove staging file ${temporary}: ${error.message}`); }
535
+ fs.closeSync(lock);
536
+ try { fs.unlinkSync(lockPath); } catch (error) { warnings.push(`Could not remove installer lock ${lockPath}: ${error.message}`); }
537
+ }
538
+ warnings.push('Other Codex hooks and shared policy settings were preserved.');
539
+ return { status: 'removed', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, warnings };
540
+ }
541
+
444
542
  /** Idempotently repair a missing or stale canonical installation; unsafe edits fail closed. */
445
543
  export function repairManagedHookInstallation(options, acl = windowsAcl) {
446
544
  const { requirements, managedDir, packageRoot, nodePath = process.execPath } = options;
@@ -527,9 +625,13 @@ export function commitPreparedFiles(entries, verify, io = fs) {
527
625
  }
528
626
  records.push(record);
529
627
  }
628
+ for (const record of records) {
629
+ record.validate?.();
630
+ }
530
631
  for (const record of records) {
531
632
  makeReplaceable(record.file, io);
532
- io.renameSync(record.temporary, record.file);
633
+ if (record.remove) io.unlinkSync(record.file);
634
+ else io.renameSync(record.temporary, record.file);
533
635
  record.installed = true;
534
636
  if (record.backup) io.chmodSync(record.backup, record.mode);
535
637
  }
@@ -666,6 +768,26 @@ async function main() {
666
768
  await checkClaudeSandboxDependencies();
667
769
  return;
668
770
  }
771
+ if (hasArgument('--uninstall-managed-hook')) {
772
+ if (process.platform !== 'win32') fail('Codex managed hook removal is only supported on Windows.');
773
+ if (!argument('--package-root')) fail('--package-root is required for managed hook removal.');
774
+ const packageRoot = path.resolve(argument('--package-root'));
775
+ const nodePath = path.resolve(argument('--node-path') || process.execPath);
776
+ const requirements = path.resolve(argument('--requirements')
777
+ || path.join(process.env.ProgramData || path.join(os.homedir(), 'ProgramData'), 'OpenAI', 'Codex', 'requirements.toml'));
778
+ const targetDirectory = path.resolve(argument('--managed-dir') || path.join(path.dirname(requirements), 'EvolCore', 'hooks'));
779
+ if (argument('--runtime-root')) {
780
+ const { configureAutostart } = await import('../dist/utils/autostart.js');
781
+ const autostart = configureAutostart(false, path.resolve(argument('--runtime-root')));
782
+ if (!autostart.ok) throw new Error(`Login autostart removal failed: ${autostart.error || 'unknown error'}`);
783
+ if (autostart.warning) process.stderr.write(`[evolcore] ${autostart.warning}\n`);
784
+ }
785
+ const result = removeManagedHookInstallation({ requirements, managedDir: targetDirectory, packageRoot, nodePath });
786
+ for (const warning of result.warnings || []) process.stderr.write(`[evolcore] ${warning}\n`);
787
+ if (result.status === 'preserved') process.stderr.write(`[evolcore] ${result.reason}; existing configuration was not modified.\n`);
788
+ process.stdout.write(`${JSON.stringify(result)}\n`);
789
+ return;
790
+ }
669
791
  // An explicit package root selects provisioning, even if the elevated
670
792
  // child inherited npm lifecycle variables. Ordinary postinstall skips it.
671
793
  if (!argument('--package-root') && (lifecycleEvent() === 'postinstall' || isGlobalInstall())) {
@@ -573,6 +573,43 @@ export class AbilityApplicationService {
573
573
  abilityAssert(this.store.get('instance', instanceId)?.revision === instance.revision, 'LEASE_EXPIRED', 'Resource authorization changed', 403);
574
574
  if (method === 'host.status')
575
575
  return { ready: instance.runtimeState === 'ready' };
576
+ // Storage batch operations (Protocol v2)
577
+ if (method === 'storage.batch') {
578
+ abilityAssert(this.validGrant(instance, 'storage'), 'RESOURCE_DENIED', 'Storage is not granted', 403);
579
+ abilityAssert(Array.isArray(args.operations) && args.operations.length >= 1 && args.operations.length <= 50, 'INVALID_BATCH_SIZE', 'Batch operations must contain 1-50 items');
580
+ const results = await Promise.all(args.operations.map(async (op) => {
581
+ try {
582
+ abilityAssert(typeof op.key === 'string' && /^[A-Za-z0-9._-]{1,128}$/.test(op.key), 'KEY_INVALID', 'Invalid storage key');
583
+ const entry = this.store.kvAddress(instance, op.key);
584
+ if (op.op === 'get') {
585
+ const value = this.store.get(entry.kind, entry.id) ?? null;
586
+ return { success: true, value };
587
+ }
588
+ else if (op.op === 'set') {
589
+ abilityAssert(Buffer.byteLength(JSON.stringify(op.value) ?? '') <= 65536, 'VALUE_TOO_LARGE', 'Storage value exceeds 64 KiB');
590
+ this.store.transaction(() => {
591
+ this.store.audit('invocation:' + invocationId, instance.target.aid, 'storage.set', instanceId);
592
+ this.store.put(entry.kind, entry.id, instance.target.aid, op.value);
593
+ });
594
+ return { success: true };
595
+ }
596
+ else if (op.op === 'delete') {
597
+ this.store.transaction(() => {
598
+ this.store.audit('invocation:' + invocationId, instance.target.aid, 'storage.delete', instanceId);
599
+ this.store.put(entry.kind, entry.id, instance.target.aid, null);
600
+ });
601
+ return { success: true };
602
+ }
603
+ else {
604
+ return { success: false, error: 'UNKNOWN_OPERATION' };
605
+ }
606
+ }
607
+ catch (error) {
608
+ return { success: false, error: error instanceof AbilityError ? error.code : 'OPERATION_FAILED' };
609
+ }
610
+ }));
611
+ return { results };
612
+ }
576
613
  if (!method.startsWith('storage.')) {
577
614
  const check = () => {
578
615
  const current = this.store.get('instance', instanceId);
@@ -42,6 +42,34 @@ for (const [network, prefix] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0',
42
42
  privateNetworks.addSubnet(network, prefix, 'ipv4');
43
43
  function publicAddress(address) { return isIP(address) === 4 && !privateNetworks.check(address, 'ipv4'); }
44
44
  export async function resourceCall(instance, pkg, secrets, refs, method, args, checkLease) {
45
+ // Note: storage.batch is now handled directly in application-service.ts broker()
46
+ // to access the store instance. This keeps workspace batch operations here.
47
+ // Workspace batch read (Protocol v2)
48
+ if (method === 'workspace.readMany') {
49
+ const grant = activeGrants(instance, 'workspace')[0]?.value;
50
+ abilityAssert(grant, 'RESOURCE_DENIED', 'Workspace is not granted', 403);
51
+ abilityAssert(Array.isArray(args.files) &&
52
+ args.files.length >= 1 &&
53
+ args.files.length <= 10, 'INVALID_FILE_COUNT', 'Can read 1-10 files at once');
54
+ const files = {};
55
+ await Promise.all(args.files.map(async (file) => {
56
+ try {
57
+ const fullPath = workspacePath(grant.root, file, false);
58
+ checkLease();
59
+ const stat = fs.statSync(fullPath);
60
+ abilityAssert(stat.isFile() && stat.size <= 1024 * 1024, 'RESOURCE_TOO_LARGE', 'File exceeds 1 MiB');
61
+ const content = fs.readFileSync(fullPath, 'utf8');
62
+ files[file] = { success: true, content };
63
+ }
64
+ catch (error) {
65
+ files[file] = {
66
+ success: false,
67
+ error: error instanceof AbilityError ? error.code : 'FILE_READ_FAILED'
68
+ };
69
+ }
70
+ }));
71
+ return { files };
72
+ }
45
73
  if (method.startsWith('workspace.')) {
46
74
  const grant = activeGrants(instance, 'workspace')[0]?.value;
47
75
  abilityAssert(grant, 'RESOURCE_DENIED', 'Workspace is not granted', 403);
@@ -39,6 +39,7 @@ export class AbilityRunner {
39
39
  this.broker = broker;
40
40
  this.exited = exited;
41
41
  }
42
+ supportedCapabilities = [];
42
43
  async start(pkg, instance, migration) {
43
44
  abilityAssert(packageDigest(pkg.root) === pkg.digest, 'PACKAGE_CHANGED', 'Stored package changed');
44
45
  const command = runtimeCommand(pkg);
@@ -101,11 +102,15 @@ export class AbilityRunner {
101
102
  this.child.once('exit', ended);
102
103
  try {
103
104
  const health = await this.call('initialize', {
105
+ protocolVersion: 'evolcore.ability-runtime/2',
106
+ capabilities: ['batch-operations', 'heartbeat', 'prefetch'],
104
107
  ...(pkg.manifest.runtime.kind === 'node-subprocess' ? { entry: packageFile(pkg.root, pkg.manifest.runtime.entry) } : {}),
105
- config: instance.config, handlers: pkg.manifest.abilities.map(item => item.handler), ...(migration ? { migration } : {})
108
+ config: instance.config, handlers: pkg.manifest.abilities.map(item => item.handler), ...(migration ? { migration } : {}),
109
+ runtimeOptions: { heartbeatMode: false, batchingEnabled: true }
106
110
  }, 30000);
107
111
  abilityAssert(health?.ready === true, 'RUNTIME_NOT_READY', 'Runner did not report readiness', 503);
108
112
  abilityAssert(Array.isArray(health.handlers) && JSON.stringify([...health.handlers].sort()) === JSON.stringify(pkg.manifest.abilities.map(row => row.handler).sort()), 'RUNTIME_HANDLERS_MISMATCH', 'Runner handler set differs from Manifest', 503);
113
+ this.supportedCapabilities = health.supportedCapabilities || [];
109
114
  this.healthTimer = setInterval(() => {
110
115
  if (!this.closing)
111
116
  void this.call('health', {}, 5000).then(value => {
@@ -34,7 +34,8 @@ import { buildClaudeUnixSocketAllowlist } from '../core/permission/unix-socket-p
34
34
  import { auditToolInfrastructureFailure, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
35
35
  import { getManagedTaskTempDir, isManagedSessionRuntimeDir } from '../cli/task-context.js';
36
36
  import { unsettledInterruptError, withInterruptDeadline, hasTrustedFullAccessContext } from './runner-types.js';
37
- import { getGatewayPricing as getSharedGatewayPricing, resolveModelSpec } from '../stats/price-resolver.js';
37
+ import { getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
38
+ import { resolveModelCapabilities } from '../core/model/model-capabilities.js';
38
39
  import { contextTokensForUsage, usageForContext, realContextWindowForModel, autoCompactWindowForModel, sdkAutoCompactWindowForModel } from './runner-types.js';
39
40
  import { hasContextWindowSuffix, stripContextWindowSuffix } from '../core/model/context-window-suffix.js';
40
41
  const resolveModule = createRequire(import.meta.url);
@@ -463,12 +464,13 @@ function applyContextWindow(modelId, contextWindow, catalog) {
463
464
  return modelId;
464
465
  }
465
466
  function resolveClaudeModelContext(modelId, catalog) {
466
- const modelSpec = resolveModelSpec(resolvePaths().root, modelId, undefined, {
467
- context_window: realContextWindowForModel(modelId),
467
+ const capabilities = resolveModelCapabilities(resolvePaths().root, modelId, {
468
+ catalog,
469
+ fallbackContextWindow: realContextWindowForModel(modelId),
468
470
  });
469
471
  return {
470
- sdkModel: applyContextWindow(modelId, modelSpec.context_window, catalog),
471
- contextWindow: modelSpec.context_window,
472
+ sdkModel: applyContextWindow(capabilities.model, capabilities.contextWindow, catalog),
473
+ contextWindow: capabilities.contextWindow,
472
474
  };
473
475
  }
474
476
  class MessageStream {
@@ -268,18 +268,6 @@ export class CodexAppServerClient {
268
268
  await this.request('thread/compact/start', { threadId });
269
269
  return true;
270
270
  }
271
- /**
272
- * 直接往 thread 的模型可见历史里追加 Responses API item。
273
- *
274
- * 用于工具调用后的时间感知:Codex 的 turn loop 由 app-server 内部驱动,客户端拿不到
275
- * "下一批工具开始前"的钩子时机(PostToolUse 是独立进程,每次工具都要再起一个 node,
276
- * 且需要管理员安装托管钩子);inject_items 走同一条 app-server 连接,成本极低。
277
- */
278
- async threadInjectItems(threadId, items) {
279
- if (items.length === 0)
280
- return;
281
- await this.request('thread/inject_items', { threadId, items });
282
- }
283
271
  async threadTurnsList(threadId, limit, cursor) {
284
272
  return this.request('thread/turns/list', {
285
273
  threadId,
@@ -15,7 +15,6 @@ import { logger } from '../utils/logger.js';
15
15
  import { resolveProviderService } from '../config/providers.js';
16
16
  import { catalogHash } from '../core/model/catalog-service.js';
17
17
  import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
18
- import { renderToolTime } from './tool-time-context.js';
19
18
  import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolInfrastructureFailure, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
20
19
  import { classifyError, ErrorType, getToolResultErrorText, isOutputTokenLimitError, isRetryableError } from '../utils/error-utils.js';
21
20
  import { findModelSpec, getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
@@ -112,8 +111,9 @@ function parseCodexRetryProgress(message) {
112
111
  return undefined;
113
112
  return { count, limit };
114
113
  }
115
- function createCodexRetryMetadataError(message, state) {
114
+ function createCodexRetryMetadataError(message, state, executionOutcome) {
116
115
  const error = new Error(message);
116
+ error.codexExecutionOutcome = executionOutcome;
117
117
  if (state.modelRetryCount !== undefined)
118
118
  error.codexRetryCount = state.modelRetryCount;
119
119
  if (state.modelRetryLimit !== undefined)
@@ -335,22 +335,14 @@ function logCodexProbeFailure(args, startedAt, error, timeoutMs, launch) {
335
335
  })}`);
336
336
  }
337
337
  function probeCodexCli(args, executable) {
338
- return probeCliSync('codex', args, { executable, onFailure: logCodexProbeFailure });
338
+ return probeCliSync('codex', args, {
339
+ executable, onFailure: logCodexProbeFailure,
340
+ validateOutput: args[0] === '--version' ? output => parseCodexCliVersion(output) !== null : undefined,
341
+ });
339
342
  }
340
343
  export function getCodexCliVersion(executable) {
341
- const startedAt = Date.now();
342
344
  try {
343
- const output = probeCodexCli(['--version'], executable);
344
- const version = parseCodexCliVersion(output);
345
- if (!version) {
346
- logCodexProbeFailure(['--version'], startedAt, {
347
- code: 'INVALID_VERSION_OUTPUT',
348
- message: 'Codex CLI version output could not be parsed',
349
- status: 0,
350
- stdout: output,
351
- }, CODEX_CLI_PROBE_TIMEOUT_MS);
352
- }
353
- return version;
345
+ return parseCodexCliVersion(probeCodexCli(['--version'], executable));
354
346
  }
355
347
  catch {
356
348
  return null;
@@ -445,7 +437,9 @@ async function probeCodexAppServerAvailabilityAsync() {
445
437
  // version gate passes, so the decision order is unchanged.
446
438
  const appServerProbe = probeCli('codex', ['app-server', '--help'], options);
447
439
  appServerProbe.catch(() => { });
448
- version = parseCodexCliVersion(await probeCli('codex', ['--version'], options)) ?? undefined;
440
+ version = parseCodexCliVersion(await probeCli('codex', ['--version'], {
441
+ ...options, validateOutput: output => parseCodexCliVersion(output) !== null,
442
+ })) ?? undefined;
449
443
  if (!version)
450
444
  return { available: false, reason: '无法读取 Codex CLI 版本。' };
451
445
  if (!isCodexCliVersionSupported(version)) {
@@ -5639,7 +5633,7 @@ export class CodexRunner {
5639
5633
  lastReportedUsage: state.tokenUsage?.last,
5640
5634
  })}`);
5641
5635
  if (isRetryableError(new Error(turn.error.message))) {
5642
- throw createCodexRetryMetadataError(turn.error.message, state);
5636
+ throw createCodexRetryMetadataError(turn.error.message, state, 'failed');
5643
5637
  }
5644
5638
  yield { type: 'error', error: turn.error.message, errorType: toAgentErrorType(turn.error.message) };
5645
5639
  }
@@ -5675,7 +5669,7 @@ export class CodexRunner {
5675
5669
  break;
5676
5670
  }
5677
5671
  if (isRetryableError(new Error(message))) {
5678
- throw createCodexRetryMetadataError(message, state);
5672
+ throw createCodexRetryMetadataError(message, state, params.willRetry === false ? 'failed' : 'unknown');
5679
5673
  }
5680
5674
  yield { type: 'error', error: message, errorType: toAgentErrorType(message) };
5681
5675
  break;
@@ -5689,45 +5683,9 @@ export class CodexRunner {
5689
5683
  return;
5690
5684
  if (event.type === 'tool_use') {
5691
5685
  state.openToolCalls.set(event.callId, event.name);
5692
- // 批次起点:本批第一个工具开始执行时记一次,后续并行工具不覆盖。
5693
- if (state.toolBatchStartedAt === undefined)
5694
- state.toolBatchStartedAt = Date.now();
5695
5686
  }
5696
5687
  else if (event.type === 'tool_result') {
5697
5688
  state.openToolCalls.delete(event.callId);
5698
- if (state.openToolCalls.size === 0)
5699
- this.injectToolTime(state);
5700
- }
5701
- }
5702
- /**
5703
- * 工具批次结束后把时间行注入 Codex thread 的模型可见历史。
5704
- *
5705
- * Codex 的时间感知没有 Claude PostToolBatch 那种同步钩子:turn loop 在 app-server 内部,
5706
- * 客户端只能在收到 item/completed、且本批 openToolCalls 清空后主动追加一条 item。
5707
- * 用 Responses API 的 user message + input_text,模型下一次推理即可读到。
5708
- *
5709
- * 失败不影响主流程(注入是增值能力,不是正确性依赖),只记 debug 日志。
5710
- */
5711
- injectToolTime(state) {
5712
- state.toolBatchStartedAt = undefined;
5713
- if (!state.threadId)
5714
- return;
5715
- const items = [{
5716
- type: 'message',
5717
- role: 'user',
5718
- content: [{ type: 'input_text', text: renderToolTime() }],
5719
- }];
5720
- try {
5721
- const client = this.getAppServerClientForThread(state.threadId);
5722
- state.toolTimeInjectedBatches = (state.toolTimeInjectedBatches ?? 0) + 1;
5723
- void client.threadInjectItems(state.threadId, items).catch(error => {
5724
- logger.debug(`[CodexRunner] tool time injection failed: thread=${state.threadId} `
5725
- + `error=${error instanceof Error ? error.message : String(error)}`);
5726
- });
5727
- }
5728
- catch (error) {
5729
- logger.debug(`[CodexRunner] tool time injection skipped: thread=${state.threadId} `
5730
- + `error=${error instanceof Error ? error.message : String(error)}`);
5731
5689
  }
5732
5690
  }
5733
5691
  *reconcileOpenAppServerToolCalls(state, turnId) {