evolcore 0.0.40 → 0.0.41-test.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/claude-runner.js +21 -106
  5. package/dist/agents/codex-runner.js +451 -231
  6. package/dist/agents/ecagent-runner.js +30 -11
  7. package/dist/agents/gemini-runner.js +26 -6
  8. package/dist/agents/runner-types.js +11 -3
  9. package/dist/aun/ability-device-routing.js +26 -0
  10. package/dist/aun/aid/client.js +1 -1
  11. package/dist/aun/group/identity.js +8 -0
  12. package/dist/aun/msg/managed-operation.js +4 -4
  13. package/dist/aun/msg/p2p.js +27 -7
  14. package/dist/aun/storage/download.js +30 -0
  15. package/dist/aun/storage/index.js +14 -6
  16. package/dist/channels/aun.js +33 -4
  17. package/dist/channels/daemon.js +24 -4
  18. package/dist/cli/agent-command.js +2 -0
  19. package/dist/cli/agent-create.js +98 -19
  20. package/dist/cli/agent.js +10 -3
  21. package/dist/cli/aun-commands.js +82 -22
  22. package/dist/cli/daemon-commands.js +19 -10
  23. package/dist/cli/index.js +1 -1
  24. package/dist/cli/restart-monitor.js +17 -0
  25. package/dist/cli/session-command.js +128 -13
  26. package/dist/cli/stats.js +60 -4
  27. package/dist/cli/trigger-command.js +2 -2
  28. package/dist/config/access-policy.js +2 -0
  29. package/dist/config/config-operation-service.js +17 -6
  30. package/dist/config/gateway-config.js +1 -1
  31. package/dist/config/peer-role-resolver.js +10 -8
  32. package/dist/core/agent-application-service.js +11 -1
  33. package/dist/core/agent-ipc-registration.js +4 -0
  34. package/dist/core/auth/agent-delegation.js +80 -5
  35. package/dist/core/auth/authorization-audit.js +20 -3
  36. package/dist/core/auth/operation-catalog.js +8 -0
  37. package/dist/core/command/agent-control.js +91 -12
  38. package/dist/core/command/command-handler.js +57 -46
  39. package/dist/core/command/connect-menu.js +23 -2
  40. package/dist/core/command/menu-catalog.js +1 -0
  41. package/dist/core/command/menu-handler.js +38 -101
  42. package/dist/core/command/menu-protocol.js +9 -2
  43. package/dist/core/command/role-menu.js +7 -6
  44. package/dist/core/command/slash-gate.js +13 -10
  45. package/dist/core/command/slash-handler.js +34 -98
  46. package/dist/core/event-catalog.js +15 -0
  47. package/dist/core/ipc-registration.js +18 -1
  48. package/dist/core/memory/consolidation-trigger.js +1 -1
  49. package/dist/core/message/aun-ipc-sender.js +26 -5
  50. package/dist/core/message/aun-request-registry.js +97 -3
  51. package/dist/core/message/im-renderer.js +4 -0
  52. package/dist/core/message/message-admission.js +8 -4
  53. package/dist/core/message/message-bridge.js +40 -6
  54. package/dist/core/message/message-log.js +55 -0
  55. package/dist/core/message/message-queue.js +5 -5
  56. package/dist/core/message/response-engine.js +310 -136
  57. package/dist/core/model/model-catalog.js +7 -6
  58. package/dist/core/ownership/owner-resolver.js +2 -2
  59. package/dist/core/permission/ec-command-parser.js +110 -5
  60. package/dist/core/permission/tool-policy.js +28 -7
  61. package/dist/core/session/session-capsule.js +197 -0
  62. package/dist/core/session/session-manager.js +148 -14
  63. package/dist/core/session/session-mapper.js +2 -0
  64. package/dist/index.js +3 -3
  65. package/dist/ipc.js +22 -8
  66. package/dist/stats/budget.js +1 -1
  67. package/dist/stats/db.js +15 -0
  68. package/dist/stats/index.js +2 -2
  69. package/dist/stats/price-resolver.js +304 -5
  70. package/dist/stats/query.js +82 -3
  71. package/dist/stats/writer.js +38 -5
  72. package/dist/trigger/feedback.js +18 -7
  73. package/dist/trigger/manager.js +20 -3
  74. package/dist/trigger/parser.js +6 -3
  75. package/dist/trigger/patch.js +1 -1
  76. package/dist/trigger/system-definitions.js +43 -7
  77. package/dist/trigger/validation.js +13 -5
  78. package/dist/utils/error-utils.js +14 -0
  79. package/dist/utils/npm-ops.js +2 -1
  80. package/dist/utils/package-version-info.js +1 -1
  81. package/dist/utils/upgrade-jobs.js +45 -5
  82. package/kits/docs/INDEX.md +1 -1
  83. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  84. package/kits/docs/evolcore/INDEX.md +2 -1
  85. package/kits/docs/evolcore/agent-create.md +3 -2
  86. package/kits/docs/evolcore/agent.md +1 -1
  87. package/kits/docs/evolcore/config.md +1 -1
  88. package/kits/docs/evolcore/event.md +1 -0
  89. package/kits/docs/evolcore/fs.md +5 -0
  90. package/kits/docs/evolcore/menu-protocol.md +32 -0
  91. package/kits/docs/evolcore/msg.md +17 -1
  92. package/kits/docs/evolcore/session.md +14 -0
  93. package/kits/schemas/agent-config.schema.13.json +15 -0
  94. package/kits/skills/aid-ability/SKILL.md +35 -6
  95. package/kits/templates/session-capsule/recovery.md +5 -0
  96. package/kits/templates/session-capsule/renew.md +5 -0
  97. package/kits/templates/system-fragments/bootstrap.md +6 -6
  98. package/kits/templates/system-fragments/channel.md +1 -1
  99. package/package.json +3 -3
  100. package/dist/stats/billing.js +0 -215
@@ -87,6 +87,11 @@ function resolveProviderCatalogBaseagent(serviceType, requested) {
87
87
  }
88
88
  return baseagent;
89
89
  }
90
+ function adaptProviderCatalogModels(models, provider, baseagent) {
91
+ return baseagent
92
+ ? adaptCatalogModels(models, baseagent)
93
+ : adaptServiceCatalogModels(models, provider.serviceType, provider.style);
94
+ }
90
95
  export async function getProviderCatalog(providerId, serviceType, refresh = false, management = false, requestedBaseagent) {
91
96
  const selected = requestedBaseagent
92
97
  ? resolveProviderServiceForBaseagent(providerId, requestedBaseagent, serviceType)
@@ -97,9 +102,7 @@ export async function getProviderCatalog(providerId, serviceType, refresh = fals
97
102
  if (management)
98
103
  return snapshot;
99
104
  const overridden = applyProviderModelOverrides(snapshot, selected.modelOverrides);
100
- return { ...overridden, models: baseagent
101
- ? adaptCatalogModels(overridden.models, baseagent)
102
- : adaptServiceCatalogModels(overridden.models, effectiveServiceType, selected.style) };
105
+ return { ...overridden, models: adaptProviderCatalogModels(overridden.models, selected, baseagent) };
103
106
  };
104
107
  if (!daemonOwner) {
105
108
  const snapshot = await queryDaemonCatalog(undefined, undefined, refresh, { providerId, serviceType: effectiveServiceType });
@@ -117,9 +120,7 @@ export async function getLocalProviderCatalog(providerId, serviceType, refresh =
117
120
  export function previewProviderCatalog(provider, requestedBaseagent) {
118
121
  const baseagent = resolveProviderCatalogBaseagent(provider.serviceType, requestedBaseagent);
119
122
  return new ModelCatalogService().get({ ...provider, scope: '<provider-preview>', baseagent: '' }, true)
120
- .then(snapshot => ({ ...snapshot, models: baseagent
121
- ? adaptCatalogModels(snapshot.models, baseagent)
122
- : adaptServiceCatalogModels(snapshot.models, provider.serviceType, provider.style) }));
123
+ .then(snapshot => ({ ...snapshot, models: adaptProviderCatalogModels(snapshot.models, provider, baseagent) }));
123
124
  }
124
125
  export function resolveCatalogContext(self, ba) {
125
126
  const baseagent = ba || activeBaseagent(self);
@@ -675,11 +675,11 @@ export class OwnerResolver {
675
675
  return undefined;
676
676
  ownerClient = await sdkStore.loadClient(store, ownerAid);
677
677
  subClient = await sdkStore.loadClient(store, subjectAid);
678
- if (typeof ownerClient.bindLocalSubaid !== 'function'
678
+ if (typeof ownerClient.bindSubaid !== 'function'
679
679
  || ownerClient.getType() !== 'agent' || subClient.getType() !== 'agent')
680
680
  return undefined;
681
681
  invoked = true;
682
- const task = this.task(await ownerClient.bindLocalSubaid(subClient));
682
+ const task = this.task(await ownerClient.bindSubaid(subjectAid));
683
683
  if (!task || task.operation !== 'bind' || task.sub_aid !== subjectAid || task.owner_aid !== ownerAid
684
684
  || task.status !== 'completed') {
685
685
  throw Object.assign(new OwnershipError(task?.code ?? 'LOCAL_BIND_FAILED', task?.reason ?? 'Local binding did not complete'), { retryable: task?.retryable });
@@ -24,6 +24,29 @@ export function parseJsonObjectArgument(raw, optionName = '--payload') {
24
24
  }
25
25
  return parsed;
26
26
  }
27
+ export function buildCanonicalEvolcoreExecutionSpec(input) {
28
+ const spec = {
29
+ version: 1,
30
+ dialect: input.dialect,
31
+ wrapper: input.wrapper,
32
+ argv: normalizeEvolcoreCommandArgv(input.argv),
33
+ };
34
+ if (input.cwd !== undefined)
35
+ spec.cwd = input.cwd;
36
+ if (input.command?.mergeStderr)
37
+ spec.mergeStderr = true;
38
+ if (input.command?.filterChain?.length)
39
+ spec.filterChain = input.command.filterChain.map(stage => [...stage]);
40
+ if (input.command?.suffixArgv?.length)
41
+ spec.suffixArgv = [...input.command.suffixArgv];
42
+ if (input.command?.outputPath)
43
+ spec.outputPath = input.command.outputPath;
44
+ return spec;
45
+ }
46
+ /** Stable JSON used in delegation metadata and diagnostics. */
47
+ export function serializeCanonicalEvolcoreExecutionSpec(spec) {
48
+ return JSON.stringify(spec);
49
+ }
27
50
  function parseApplyPatchCommand(command, options = {}) {
28
51
  const input = command.trim();
29
52
  let commandText = input;
@@ -312,7 +335,7 @@ const EVOLCORE_SUBCOMMANDS = new Set([
312
335
  'fs', 'gateway', 'group', 'handoff', 'init', 'link-rules', 'logs', 'menu-client',
313
336
  'mode', 'model', 'msg', 'mv', 'net', 'queue', 'response', 'restart',
314
337
  'restart-monitor', 'rpc', 'start', 'stats', 'status', 'stop', 'storage', 'task',
315
- 'trigger', 'version', 'watch',
338
+ 'trigger', 'version', 'watch', 'session',
316
339
  ]);
317
340
  // Development/install entrypoints that are part of this repository's CLI.
318
341
  // Only these exact relative paths are canonicalized; arbitrary Node scripts
@@ -746,7 +769,7 @@ const INLINE_TEXT_FLAGS = {
746
769
  triggerUpdate: new Set(['--prompt', '--description']),
747
770
  };
748
771
  const MESSAGE_POSITIONAL_FLAGS = new Set([
749
- '--file', '--payload', '--as', '--content-type', '--text', '--transcript',
772
+ '--file', '--payload', '--payload-file', '--as', '--content-type', '--text', '--transcript',
750
773
  '--thread', '--title', '--description', '--text-from-file',
751
774
  '--handoff-context', '--aun-path', '--app', '--format', '--encrypt', '--no-encrypt',
752
775
  '--return', '--timeout',
@@ -2987,6 +3010,72 @@ export function classifyEvolcoreShellCommand(command, options = {}) {
2987
3010
  ? { kind: 'composite', issue: literal.issue }
2988
3011
  : { kind: 'none' };
2989
3012
  }
3013
+ /**
3014
+ * Resolve a Codex Bash input through the same shell-boundary classifier used
3015
+ * by preflight, then produce one canonical EC execution spec for approval and
3016
+ * delegation. This intentionally recognizes EC by executable, not subcommand.
3017
+ */
3018
+ export function resolveCanonicalEvolcoreToolInput(input, options = {}) {
3019
+ const explicitArgv = Array.isArray(input.commandArgv)
3020
+ && input.commandArgv.every(value => typeof value === 'string')
3021
+ ? input.commandArgv
3022
+ : undefined;
3023
+ if (explicitArgv) {
3024
+ const nulIndex = explicitArgv.findIndex(value => value.includes('\0'));
3025
+ if (nulIndex >= 0)
3026
+ return {
3027
+ kind: 'invalid',
3028
+ failure: parseFailure('invalid-control-char', '', 0, nulIndex, options.dialect ?? 'posix'),
3029
+ };
3030
+ if (normalizeEvolcoreCommandArgv(explicitArgv)[0] === 'ec') {
3031
+ const spec = buildCanonicalEvolcoreExecutionSpec({
3032
+ argv: explicitArgv,
3033
+ dialect: options.dialect ?? 'posix',
3034
+ wrapper: 'literal',
3035
+ });
3036
+ return { kind: 'ec', spec };
3037
+ }
3038
+ }
3039
+ const rawCommand = typeof input.command === 'string' ? input.command : '';
3040
+ const carrier = explicitArgv
3041
+ ? resolveCodexShellCarrierArgv(explicitArgv)
3042
+ : resolveCodexShellCarrierString(rawCommand);
3043
+ const command = carrier?.command ?? rawCommand;
3044
+ const dialect = carrier?.dialect ?? options.dialect;
3045
+ const parseOptions = { ...options, ...(dialect ? { dialect } : {}) };
3046
+ const classification = classifyEvolcoreShellCommand(command, parseOptions);
3047
+ if (classification.kind === 'bounded-output' || classification.kind === 'cd-prefixed') {
3048
+ if (normalizeEvolcoreCommandArgv(classification.command.argv)[0] !== 'ec')
3049
+ return { kind: 'not-ec' };
3050
+ const spec = buildCanonicalEvolcoreExecutionSpec({
3051
+ argv: classification.command.argv,
3052
+ dialect: dialect ?? 'posix',
3053
+ wrapper: classification.kind,
3054
+ ...(classification.kind === 'cd-prefixed' && classification.cwd ? { cwd: classification.cwd } : {}),
3055
+ command: classification.command,
3056
+ });
3057
+ return { kind: 'ec', spec };
3058
+ }
3059
+ const parsed = carrier
3060
+ ? parseCodexCarrierCommand(carrier, parseOptions)
3061
+ : parseCodexToolCommand(input, parseOptions);
3062
+ if (parsed.ok && normalizeEvolcoreCommandArgv(parsed.argv)[0] === 'ec') {
3063
+ const spec = buildCanonicalEvolcoreExecutionSpec({
3064
+ argv: parsed.argv,
3065
+ dialect: dialect ?? 'posix',
3066
+ wrapper: 'literal',
3067
+ });
3068
+ return {
3069
+ kind: 'ec', spec,
3070
+ ...(parsed.credentialToken ? { credentialToken: parsed.credentialToken } : {}),
3071
+ };
3072
+ }
3073
+ if (classification.kind === 'composite')
3074
+ return { kind: 'invalid', ...(!parsed.ok ? { failure: parsed } : {}) };
3075
+ if (!parsed.ok && hasEcCommandPrefix(command))
3076
+ return { kind: 'invalid', failure: parsed };
3077
+ return { kind: 'not-ec' };
3078
+ }
2990
3079
  function isDeterministicFilePath(value) {
2991
3080
  return !!value
2992
3081
  && value === value.trim()
@@ -2994,6 +3083,15 @@ function isDeterministicFilePath(value) {
2994
3083
  && !value.startsWith('~')
2995
3084
  && !AMBIGUOUS_FILE_PATH_RE.test(value);
2996
3085
  }
3086
+ /** `$TMPDIR` is expanded by the managed shell; the daemon validates its final path. */
3087
+ function isManagedPayloadFilePath(value) {
3088
+ if (!value || value !== value.trim() || value.startsWith('--') || value.startsWith('~'))
3089
+ return false;
3090
+ if (!AMBIGUOUS_FILE_PATH_RE.test(value))
3091
+ return true;
3092
+ return /^(?:\$TMPDIR|\$\{TMPDIR\})(?:[\\/]|$)/i.test(value)
3093
+ && !/[\0\r\n`*?\[\]{}<>|;&]/.test(value);
3094
+ }
2997
3095
  function findSingleFileOption(argv, startIndex) {
2998
3096
  const matches = [];
2999
3097
  for (let index = startIndex; index < argv.length; index++) {
@@ -3012,7 +3110,7 @@ function findSingleFileOption(argv, startIndex) {
3012
3110
  : { invalid: true };
3013
3111
  }
3014
3112
  const PROACTIVE_SEND_VALUE_FLAGS = new Set([
3015
- '--format', '--app', '--file', '--text-from-file', '--link', '--payload',
3113
+ '--format', '--app', '--file', '--text-from-file', '--link', '--payload', '--payload-file',
3016
3114
  '--title', '--description', '--text', '--transcript', '--as',
3017
3115
  '--content-type', '--mention', '--aun-path', '--thread', '--handoff-context',
3018
3116
  '--check-every', '--trigger-prompt', '--return', '--timeout',
@@ -3132,8 +3230,13 @@ function hasExecutableProactiveSendPayload(argv, scope) {
3132
3230
  return false;
3133
3231
  modes.set('payload', operand);
3134
3232
  }
3233
+ if (value === '--payload-file') {
3234
+ if (scope !== 'msg' || modes.has('payload-file') || !isManagedPayloadFilePath(operand))
3235
+ return false;
3236
+ modes.set('payload-file', operand);
3237
+ }
3135
3238
  }
3136
- if (modes.size > 1)
3239
+ if (modes.size > 1 || (modes.size > 0 && positionals.length > 0))
3137
3240
  return false;
3138
3241
  if (modes.has('link')) {
3139
3242
  try {
@@ -3153,6 +3256,8 @@ function hasExecutableProactiveSendPayload(argv, scope) {
3153
3256
  return false;
3154
3257
  }
3155
3258
  }
3259
+ if (modes.has('payload-file'))
3260
+ return true;
3156
3261
  return positionals.join(' ').length > 0;
3157
3262
  }
3158
3263
  function parseEvolcoreSendArgv(argv) {
@@ -3297,7 +3402,7 @@ export function describeProactiveSendCommandFailure(toolName, input, session) {
3297
3402
  + `要联系其他对象请走 --thread 跨话题发送(ec thread list <对方AID> 选中话题后加 --check-every)。`;
3298
3403
  }
3299
3404
  return `${prefix}发送者与目标正确,但正文或参数无效——正文不能为空;--file/--text-from-file 属于文件发送,`
3300
- + '不在普通回复放行范围;--link 的值必须是 http(s) URL;--payload 的值必须是 JSON 对象。';
3405
+ + '不在普通回复放行范围;--link 的值必须是 http(s) URL;--payload 的值必须是 JSON 对象;--payload-file 的值必须是确定的文件路径。';
3301
3406
  }
3302
3407
  /** 与 CLI `isValidAid` 同一规则;parser 不依赖 AID 模块,避免引入身份存储副作用。 */
3303
3408
  function looksLikeAid(value) {
@@ -6,7 +6,7 @@ import { randomUUID } from 'crypto';
6
6
  import { logger } from '../../utils/logger.js';
7
7
  import { resolveRoot } from '../../paths.js';
8
8
  import { containsHClassReference, containsAgentScopeReference, containsLClassReference, checkProtectedPathAccess, getExistingHClassMaskTargets, hClassGrantIncludesProtectedPath, isHClassPath, isSameOrDescendant, isLClassPath, lClassGrantIncludesProtectedPath, resolveProtectedCandidate, resolveProtectedCandidateWithoutFinalSymlink, } from './protected-paths.js';
9
- import { classifyEvolcoreShellCommand, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseCodexToolCommand, parseBoundedOutputShellCommand, parseShellApplyPatchInvocation, parseLiteralShellArgv, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from './ec-command-parser.js';
9
+ import { classifyEvolcoreShellCommand, canonicalizeEvolcoreCommandArgv, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseCodexToolCommand, parseBoundedOutputShellCommand, buildCanonicalEvolcoreExecutionSpec, serializeCanonicalEvolcoreExecutionSpec, parseShellApplyPatchInvocation, parseLiteralShellArgv, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from './ec-command-parser.js';
10
10
  import { analyzeReadonlyShellQuery, } from './readonly-shell-query.js';
11
11
  import { applyPatchChangePaths, collectFileChangePaths } from './tool-canonical.js';
12
12
  /** Resolve the session-owned temporary root supplied by the execution host. */
@@ -2291,6 +2291,23 @@ function prepareBoundedOutputInput(input, command, kind, context) {
2291
2291
  catch {
2292
2292
  return { behavior: 'deny', input, message: '🔒 安全输出 helper 不可用,命令已拒绝', policyCode: 'bounded_output_helper_unavailable' };
2293
2293
  }
2294
+ const executionArgv = kind === 'ec' ? canonicalizeEvolcoreCommandArgv(command.argv) : command.argv;
2295
+ const executionCwd = path.resolve(context.projectPath, command.cwd ?? '.');
2296
+ const executionOutputPath = command.outputPath
2297
+ ? expandManagedTempPath(command.outputPath, managedTempOptions(context))
2298
+ : undefined;
2299
+ const canonicalExecutionSpec = kind === 'ec'
2300
+ ? buildCanonicalEvolcoreExecutionSpec({
2301
+ argv: executionArgv,
2302
+ dialect: 'posix',
2303
+ wrapper: command.cwd ? 'cd-prefixed' : 'bounded-output',
2304
+ cwd: executionCwd,
2305
+ command: {
2306
+ ...command,
2307
+ ...(executionOutputPath ? { outputPath: executionOutputPath } : {}),
2308
+ },
2309
+ })
2310
+ : undefined;
2294
2311
  const payload = Buffer.from(JSON.stringify({
2295
2312
  // v3 carries a chain of stdin-only filters; v1 named only the filter's
2296
2313
  // arguments and v2 carried a single filter argv, so both are rejected
@@ -2299,20 +2316,24 @@ function prepareBoundedOutputInput(input, command, kind, context) {
2299
2316
  nonce: randomUUID(),
2300
2317
  kind,
2301
2318
  workspace: path.resolve(context.workspacePath ?? context.projectPath),
2302
- cwd: command.cwd ? path.resolve(command.cwd) : path.resolve(context.projectPath),
2303
- argv: command.argv,
2319
+ cwd: executionCwd,
2320
+ argv: executionArgv,
2304
2321
  mergeStderr: command.mergeStderr,
2305
2322
  ...(command.filterChain?.length ? { filterChain: command.filterChain } : {}),
2306
2323
  ...(command.suffixArgv?.length ? { suffixArgv: command.suffixArgv } : {}),
2307
- ...(command.outputPath
2308
- ? { outputPath: expandManagedTempPath(command.outputPath, managedTempOptions(context)) }
2309
- : {}),
2324
+ ...(executionOutputPath ? { outputPath: executionOutputPath } : {}),
2325
+ ...(canonicalExecutionSpec ? { executionSpec: serializeCanonicalEvolcoreExecutionSpec(canonicalExecutionSpec) } : {}),
2310
2326
  }), 'utf8').toString('base64url');
2311
2327
  const rewrittenCommand = `${quotePosixShellArg(process.execPath)} ${quotePosixShellArg(helperPath)} ${quotePosixShellArg(payload)}`;
2328
+ const updatedInput = { ...input, command: rewrittenCommand };
2329
+ delete updatedInput.commandArgv;
2312
2330
  return {
2313
2331
  behavior: 'allow',
2314
- input: { ...input, command: rewrittenCommand },
2332
+ input: updatedInput,
2315
2333
  reason: kind === 'ec' ? 'ec-command' : 'host-process-command',
2334
+ ...(canonicalExecutionSpec
2335
+ ? { executionSpec: serializeCanonicalEvolcoreExecutionSpec(canonicalExecutionSpec) }
2336
+ : {}),
2316
2337
  };
2317
2338
  }
2318
2339
  const BASH_RISK_LEVELS = new Set(['低', '中', '高']);
@@ -0,0 +1,197 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { resolveEffective } from '../../config/config-manager.js';
5
+ import { getPackageRoot } from '../../paths.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { createTextInferenceProvider } from '../inference/text-inference.js';
8
+ import { formatPeerKey } from '../relation/peer-identity.js';
9
+ import { isTransientProtocolMessage, messageLogPath } from '../message/message-log.js';
10
+ import { appendJsonlDurable, readAllJsonlLines } from './session-fs-store.js';
11
+ export function sessionCapsulePath(chatDir) {
12
+ return path.join(chatDir, 'session-capsules.jsonl');
13
+ }
14
+ export function generateCapsuleId(now = Date.now()) {
15
+ return `cap_${now}_${crypto.randomBytes(6).toString('hex')}`;
16
+ }
17
+ export function appendSessionCapsuleEvent(chatDir, event) {
18
+ fs.mkdirSync(chatDir, { recursive: true });
19
+ appendJsonlDurable(sessionCapsulePath(chatDir), event);
20
+ }
21
+ export function readSessionCapsuleEvents(chatDir) {
22
+ let content;
23
+ try {
24
+ content = fs.readFileSync(sessionCapsulePath(chatDir), 'utf8');
25
+ }
26
+ catch (error) {
27
+ if (error.code === 'ENOENT')
28
+ return [];
29
+ throw error;
30
+ }
31
+ const lines = content.split('\n');
32
+ return lines.flatMap((line, index) => {
33
+ if (!line.trim())
34
+ return [];
35
+ let event;
36
+ try {
37
+ event = JSON.parse(line);
38
+ }
39
+ catch {
40
+ // Only an unterminated tail can be an interrupted append.
41
+ if (index === lines.length - 1)
42
+ return [];
43
+ throw new Error(`Corrupt session capsule record at line ${index + 1}`);
44
+ }
45
+ if (!event || !/^cap_[A-Za-z0-9_-]+$/u.test(event.capsuleId)
46
+ || typeof event.sessionId !== 'string' || !event.sessionId
47
+ || !['created', 'bound', 'consumed'].includes(event.kind)
48
+ || !['session-renew', 'topic-renew', 'backend-recovery'].includes(event.cause)
49
+ || !Number.isFinite(event.createdAt)
50
+ || (event.kind === 'created' && typeof event.content !== 'string')
51
+ || (event.kind !== 'created' && (typeof event.agentSessionId !== 'string' || !event.agentSessionId))) {
52
+ throw new Error(`Invalid session capsule record at line ${index + 1}`);
53
+ }
54
+ return [event];
55
+ });
56
+ }
57
+ export function materializeSessionCapsules(chatDir) {
58
+ const capsules = new Map();
59
+ for (const event of readSessionCapsuleEvents(chatDir)) {
60
+ const current = capsules.get(event.capsuleId);
61
+ if (event.kind === 'created') {
62
+ if (current)
63
+ throw new Error(`Duplicate session capsule: ${event.capsuleId}`);
64
+ capsules.set(event.capsuleId, {
65
+ capsuleId: event.capsuleId,
66
+ sessionId: event.sessionId,
67
+ sourceSessionId: event.sourceSessionId,
68
+ cause: event.cause,
69
+ sourceAgentSessionId: event.sourceAgentSessionId,
70
+ agentSessionId: event.agentSessionId,
71
+ content: event.content ?? '',
72
+ createdAt: event.createdAt,
73
+ });
74
+ continue;
75
+ }
76
+ if (!current || current.sessionId !== event.sessionId || current.cause !== event.cause
77
+ || current.sourceSessionId !== event.sourceSessionId || current.sourceAgentSessionId !== event.sourceAgentSessionId) {
78
+ throw new Error(`Session capsule lifecycle is inconsistent: ${event.capsuleId}`);
79
+ }
80
+ if (event.kind === 'bound') {
81
+ if (current.agentSessionId && current.agentSessionId !== event.agentSessionId) {
82
+ throw new Error(`Session capsule has conflicting backend bindings: ${event.capsuleId}`);
83
+ }
84
+ current.agentSessionId = event.agentSessionId;
85
+ if (event.sourceAgentSessionId)
86
+ current.sourceAgentSessionId = event.sourceAgentSessionId;
87
+ }
88
+ else if (event.kind === 'consumed') {
89
+ if (current.agentSessionId !== event.agentSessionId)
90
+ throw new Error(`Unbound session capsule consumed: ${event.capsuleId}`);
91
+ current.consumedAt = event.consumedAt ?? event.createdAt;
92
+ current.messageId = event.messageId;
93
+ }
94
+ }
95
+ return [...capsules.values()].sort((a, b) => a.createdAt - b.createdAt);
96
+ }
97
+ export function findSessionCapsule(chatDir, capsuleId) {
98
+ return materializeSessionCapsules(chatDir).find(capsule => capsule.capsuleId === capsuleId);
99
+ }
100
+ const MAX_INPUT_CHARS = 24_000;
101
+ const MAX_CONTENT_CHARS = 5_000;
102
+ const NON_DIALOGUE = new Set(['command', 'thought', 'status', 'event', 'tool_call', 'tool_result']);
103
+ function bounded(text, limit) {
104
+ if (text.length <= limit)
105
+ return text;
106
+ const head = Math.floor((limit - 24) / 3);
107
+ return `${text.slice(0, head)}\n[中间历史已省略]\n${text.slice(-(limit - head - 24))}`;
108
+ }
109
+ function safeHistory(text) {
110
+ return text.replace(/<session-capsule\b[^>]*>[\s\S]*?<\/session-capsule>/gu, '')
111
+ .replace(/\b(?:sk|sk-ant)-[a-zA-Z0-9_-]{12,}/gu, '[凭据已省略]')
112
+ .replace(/((?:api[_-]?key|appSecret|authorization|password|access[_-]?token)\s*[=:]\s*)[^\s,}\n]+/giu, '$1[已省略]');
113
+ }
114
+ function transcriptText(message) {
115
+ if (!message || typeof message !== 'object')
116
+ return '';
117
+ const content = message.content;
118
+ if (typeof content === 'string')
119
+ return content;
120
+ if (!Array.isArray(content))
121
+ return '';
122
+ return content.flatMap(block => block?.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n');
123
+ }
124
+ export function capsuleHistory(chatDir, source) {
125
+ const capsules = materializeSessionCapsules(chatDir);
126
+ const previous = capsules.filter(capsule => capsule.sessionId === source.id).at(-1);
127
+ const allEntries = readAllJsonlLines(messageLogPath(chatDir))
128
+ .filter(entry => entry.sessionId === source.id && !isTransientProtocolMessage(entry)
129
+ && !NON_DIALOGUE.has(entry.msgType) && entry.content?.trim()
130
+ && !/^\/(?:renew|new)(?:\s|$)/u.test(entry.content.trim()));
131
+ const boundary = previous ? allEntries.findIndex(entry => entry.capsuleId === previous.capsuleId) : -1;
132
+ const entries = boundary >= 0 ? allEntries.slice(boundary)
133
+ : allEntries.filter(entry => !previous || entry.ts >= previous.createdAt);
134
+ const history = entries.map(entry => `${entry.dir === 'in' ? '用户' : '助手'}:${bounded(entry.content, 2400)}`);
135
+ return bounded(safeHistory([
136
+ `话题:${source.name ?? ''}`,
137
+ previous ? `此前摘要:\n${previous.content}` : '',
138
+ ...history,
139
+ ].filter(Boolean).join('\n\n')), MAX_INPUT_CHARS);
140
+ }
141
+ export function fallbackCapsuleContent(history, cause) {
142
+ const introduction = cause === 'backend-recovery'
143
+ ? '原底层会话无法恢复。以下为可获取的历史摘录;助手计划不等于已执行结果,涉及副作用必须先核实。'
144
+ : '以下为精简后的历史摘录;当前用户指令优先,已完成或取消的任务不要重复执行。';
145
+ return `${introduction}\n\n${bounded(history || '没有可恢复的对话记录,请根据当前用户消息继续。', MAX_CONTENT_CHARS - 150)}`;
146
+ }
147
+ export async function generateCapsuleContent(chatDir, source, cause, reader) {
148
+ let history = capsuleHistory(chatDir, source);
149
+ if (source.agentSessionId && reader) {
150
+ try {
151
+ const messages = await reader(source);
152
+ const transcript = messages.filter(item => item.type === 'user' || item.type === 'assistant')
153
+ .map(item => ({ type: item.type, text: transcriptText(item.message) }))
154
+ .filter(item => item.text.trim() && !item.text.includes('--- [SYSTEM_PROMPT_END] ---'))
155
+ .map(item => `${item.type === 'user' ? '用户' : '助手'}:${bounded(item.text, 2400)}`);
156
+ if (transcript.length)
157
+ history = bounded(safeHistory(`${history}\n\n底层对话补充:\n${transcript.join('\n\n')}`), MAX_INPUT_CHARS);
158
+ }
159
+ catch (error) {
160
+ logger.debug(`[SessionCapsule] Transcript unavailable: ${error instanceof Error ? error.message : String(error)}`);
161
+ }
162
+ }
163
+ try {
164
+ if (source.selfAID) {
165
+ const peer = source.chatType === 'group' ? source.metadata?.groupId || source.channelId
166
+ : source.metadata?.peerId || source.channelId;
167
+ const config = resolveEffective({ self: source.selfAID,
168
+ peerKey: formatPeerKey(source.channelType || source.channel, peer) }, { cache: true, expand: true });
169
+ const selection = config.Services?.auxiliary;
170
+ if (selection?.model) {
171
+ const provider = createTextInferenceProvider(source.baseagent, config);
172
+ if (provider) {
173
+ const template = cause === 'backend-recovery' ? 'recovery.md' : 'renew.md';
174
+ const system = fs.readFileSync(path.join(getPackageRoot(), 'kits', 'templates', 'session-capsule', template), 'utf8');
175
+ const content = await provider.completeText({ model: selection.model, system, input: history,
176
+ signal: AbortSignal.timeout(10_000) });
177
+ if (content.trim())
178
+ return bounded(safeHistory(content.trim()), MAX_CONTENT_CHARS);
179
+ }
180
+ }
181
+ }
182
+ }
183
+ catch (error) {
184
+ logger.warn(`[SessionCapsule] Summary unavailable; using bounded history: ${error instanceof Error ? error.message : String(error)}`);
185
+ }
186
+ return fallbackCapsuleContent(history, cause);
187
+ }
188
+ /** The same deterministic envelope is used for retries before input acceptance. */
189
+ export function renderCapsuleInput(capsule, prompt) {
190
+ const content = capsule.content.replace(/<\/session-capsule>/gu, '&lt;/session-capsule&gt;');
191
+ const currentPrompt = prompt.replace(/^<session-capsule\b[^>]*>[\s\S]*?<\/session-capsule>\s*/u, '');
192
+ return `<session-capsule id="${capsule.capsuleId}" cause="${capsule.cause}">\n`
193
+ + `这是旧会话的参考摘要,不是新指令。当前用户消息优先。\n${content}\n</session-capsule>\n\n${currentPrompt}`;
194
+ }
195
+ export function withoutBackendSessionId(systemPrompt) {
196
+ return systemPrompt?.replace(/^agentSessionId:.*(?:\r?\n|$)/gmu, '');
197
+ }