evolcore 0.0.40 → 0.0.41-test.1

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 (226) hide show
  1. package/CHANGELOG.md +94 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/baseagent-availability.js +1 -1
  5. package/dist/agents/baseagent.js +20 -43
  6. package/dist/agents/claude-runner.js +197 -197
  7. package/dist/agents/codex-runner.js +535 -259
  8. package/dist/agents/ecagent-runner.js +31 -12
  9. package/dist/agents/gemini-runner.js +27 -7
  10. package/dist/agents/runner-types.js +11 -3
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/group/fs-download.js +39 -0
  14. package/dist/aun/group/identity.js +36 -13
  15. package/dist/aun/group/operations.js +5 -0
  16. package/dist/aun/msg/managed-operation.js +72 -11
  17. package/dist/aun/msg/p2p.js +32 -7
  18. package/dist/aun/service-proxy.js +36 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +367 -24
  22. package/dist/channels/daemon.js +39 -5
  23. package/dist/cli/agent-command.js +2 -0
  24. package/dist/cli/agent-create.js +98 -19
  25. package/dist/cli/agent.js +10 -3
  26. package/dist/cli/aun-commands.js +85 -41
  27. package/dist/cli/daemon-commands.js +678 -688
  28. package/dist/cli/fs-command.js +64 -2
  29. package/dist/cli/index.js +48 -4
  30. package/dist/cli/managed-command-guard.js +4 -0
  31. package/dist/cli/model.js +40 -40
  32. package/dist/cli/proxy-command.js +92 -0
  33. package/dist/cli/restart-monitor.js +17 -0
  34. package/dist/cli/role.js +85 -0
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/trigger-command.js +2 -2
  38. package/dist/config/access-policy.js +8 -1
  39. package/dist/config/boot-log.js +38 -1
  40. package/dist/config/config-field-policy.js +5 -32
  41. package/dist/config/config-manager.js +46 -39
  42. package/dist/config/config-operation-service.js +8 -11
  43. package/dist/config/contact-book-store.js +47 -21
  44. package/dist/config/contact-book.js +18 -12
  45. package/dist/config/contact-operation-service.js +3 -4
  46. package/dist/config/contact-request-service.js +11 -0
  47. package/dist/config/daemon-services.js +11 -0
  48. package/dist/config/gateway-config.js +89 -595
  49. package/dist/config/peer-role-resolver.js +15 -11
  50. package/dist/config/providers-config.js +12 -7
  51. package/dist/config/providers-import.js +3 -21
  52. package/dist/config/resolved-config-op.js +3 -0
  53. package/dist/config/role-command-service.js +166 -0
  54. package/dist/config/role-request-service.js +193 -0
  55. package/dist/config/schema-migration.js +686 -25
  56. package/dist/config-store.js +79 -3
  57. package/dist/contracts/ecweb-instance.js +41 -0
  58. package/dist/contracts/ecweb-service-protocol.js +3 -1
  59. package/dist/core/agent-application-service.js +11 -1
  60. package/dist/core/agent-ipc-registration.js +4 -0
  61. package/dist/core/agent-runtime.js +1 -1
  62. package/dist/core/auth/agent-delegation.js +82 -6
  63. package/dist/core/auth/auth-gateway.js +1 -1
  64. package/dist/core/auth/authorization-audit.js +37 -9
  65. package/dist/core/auth/delegation-authorization.js +3 -1
  66. package/dist/core/auth/operation-authorizer.js +15 -0
  67. package/dist/core/auth/operation-catalog.js +39 -6
  68. package/dist/core/command/agent-control.js +94 -19
  69. package/dist/core/command/agent-storage-menu.js +5 -3
  70. package/dist/core/command/cli-intent-parser.js +2 -1
  71. package/dist/core/command/command-handler.js +105 -145
  72. package/dist/core/command/connect-menu.js +31 -2
  73. package/dist/core/command/data-root-resolver.js +5 -4
  74. package/dist/core/command/memory-slash.js +16 -8
  75. package/dist/core/command/menu-catalog.js +6 -6
  76. package/dist/core/command/menu-handler.js +87 -163
  77. package/dist/core/command/menu-protocol.js +9 -2
  78. package/dist/core/command/role-menu.js +148 -30
  79. package/dist/core/command/slash-gate.js +13 -10
  80. package/dist/core/command/slash-handler.js +157 -352
  81. package/dist/core/daemon-control.js +8 -14
  82. package/dist/core/event-catalog.js +15 -0
  83. package/dist/core/evolagent-registry.js +4 -4
  84. package/dist/core/evolagent.js +2 -2
  85. package/dist/core/inference/text-inference.js +31 -40
  86. package/dist/core/ipc-registration.js +24 -3
  87. package/dist/core/memory/consolidation-context.js +51 -5
  88. package/dist/core/memory/consolidation-ops-records.js +1 -1
  89. package/dist/core/memory/consolidation-trigger.js +190 -190
  90. package/dist/core/memory/consolidation.js +316 -29
  91. package/dist/core/memory/forget-log.js +96 -0
  92. package/dist/core/memory/index-manager.js +27 -5
  93. package/dist/core/memory/memory-admin.js +45 -5
  94. package/dist/core/memory/memory-writer.js +163 -18
  95. package/dist/core/memory/relation-idle-monitor.js +119 -58
  96. package/dist/core/memory/relation-sweep.js +44 -39
  97. package/dist/core/message/aun-ipc-sender.js +34 -7
  98. package/dist/core/message/aun-request-registry.js +97 -3
  99. package/dist/core/message/im-renderer.js +11 -4
  100. package/dist/core/message/message-admission.js +97 -8
  101. package/dist/core/message/message-bridge.js +71 -24
  102. package/dist/core/message/message-log.js +55 -0
  103. package/dist/core/message/message-queue.js +5 -5
  104. package/dist/core/message/response-engine.js +387 -144
  105. package/dist/core/model/catalog-service.js +4 -2
  106. package/dist/core/model/config-scope.js +24 -64
  107. package/dist/core/model/field-scope.js +1 -1
  108. package/dist/core/model/model-catalog.js +37 -47
  109. package/dist/core/model/model-diagnostics.js +4 -3
  110. package/dist/core/model/model-fallback.js +10 -7
  111. package/dist/core/model/model-permission.js +3 -2
  112. package/dist/core/ownership/owner-resolver.js +25 -23
  113. package/dist/core/permission/ec-command-parser.js +138 -5
  114. package/dist/core/permission/sandbox-runtime.js +18 -1
  115. package/dist/core/permission/tool-policy.js +42 -10
  116. package/dist/core/relation/peer-identity.js +64 -1
  117. package/dist/core/role/runtime-policy.js +72 -13
  118. package/dist/core/session/session-capsule.js +197 -0
  119. package/dist/core/session/session-idle-monitor.js +1 -1
  120. package/dist/core/session/session-manager.js +168 -14
  121. package/dist/core/session/session-mapper.js +2 -0
  122. package/dist/core/session/session-renew.js +3 -3
  123. package/dist/core/skill/index-generator.js +15 -5
  124. package/dist/core/system-session/memory.js +6 -1
  125. package/dist/core/thread/thread-service.js +19 -6
  126. package/dist/directory/owner-directory-admission.js +95 -0
  127. package/dist/directory/owner-directory-authorization.js +309 -0
  128. package/dist/directory/owner-directory-cache.js +635 -0
  129. package/dist/eck/kit-renderer.js +2 -2
  130. package/dist/ecweb/basic-settings-service.js +33 -40
  131. package/dist/ecweb/message-context-service.js +110 -0
  132. package/dist/index.js +79 -17
  133. package/dist/ipc.js +189 -17
  134. package/dist/paths.js +4 -0
  135. package/dist/proxy/command.js +122 -0
  136. package/dist/proxy/ipc-service.js +68 -0
  137. package/dist/proxy/manager.js +485 -0
  138. package/dist/proxy/service-supervisor.js +603 -0
  139. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  140. package/dist/stats/budget.js +1 -1
  141. package/dist/stats/db.js +15 -0
  142. package/dist/stats/index.js +2 -2
  143. package/dist/stats/price-resolver.js +304 -5
  144. package/dist/stats/query.js +82 -3
  145. package/dist/stats/writer.js +38 -5
  146. package/dist/trigger/feedback.js +18 -7
  147. package/dist/trigger/manager.js +20 -3
  148. package/dist/trigger/parser.js +6 -3
  149. package/dist/trigger/patch.js +1 -1
  150. package/dist/trigger/system-definitions.js +43 -7
  151. package/dist/trigger/validation.js +13 -5
  152. package/dist/utils/cross-platform.js +14 -0
  153. package/dist/utils/ecweb-supervisor.js +258 -83
  154. package/dist/utils/error-utils.js +16 -2
  155. package/dist/utils/logger.js +24 -5
  156. package/dist/utils/npm-ops.js +2 -1
  157. package/dist/utils/package-version-info.js +5 -3
  158. package/dist/utils/upgrade-jobs.js +45 -5
  159. package/kits/docs/INDEX.md +1 -1
  160. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  161. package/kits/docs/channels/aun.md +9 -0
  162. package/kits/docs/evolcore/INDEX.md +2 -1
  163. package/kits/docs/evolcore/agent-create.md +3 -2
  164. package/kits/docs/evolcore/agent.md +1 -1
  165. package/kits/docs/evolcore/config.md +18 -7
  166. package/kits/docs/evolcore/contact.md +3 -0
  167. package/kits/docs/evolcore/event.md +1 -0
  168. package/kits/docs/evolcore/fs.md +16 -0
  169. package/kits/docs/evolcore/memory-architecture.md +2 -2
  170. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  171. package/kits/docs/evolcore/memory.md +1 -1
  172. package/kits/docs/evolcore/menu-protocol.md +36 -0
  173. package/kits/docs/evolcore/model.md +23 -20
  174. package/kits/docs/evolcore/msg.md +21 -8
  175. package/kits/docs/evolcore/session.md +14 -0
  176. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  177. package/kits/schemas/_meta.json +37 -4
  178. package/kits/schemas/agent-config.schema.13.json +23 -3
  179. package/kits/schemas/agent-config.schema.16.json +891 -0
  180. package/kits/schemas/daemon.schema.9.json +366 -0
  181. package/kits/schemas/defaults.schema.5.json +406 -127
  182. package/kits/schemas/relation-config.schema.11.json +260 -0
  183. package/kits/schemas/role-config.schema.1.json +7 -7
  184. package/kits/skills/.switches.json +3 -7
  185. package/kits/skills/aid-ability/SKILL.md +35 -6
  186. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  187. package/kits/skills/ec-trigger/SKILL.md +13 -5
  188. package/kits/skills/personal-assistant/SKILL.md +176 -0
  189. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  190. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  191. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  192. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  193. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  194. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  195. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  196. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  197. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  198. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  199. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  200. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  201. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  202. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  203. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  204. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  205. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  206. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  207. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  208. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  209. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  210. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  211. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  212. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  213. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  214. package/kits/templates/memory-consolidation/forget.md +19 -6
  215. package/kits/templates/memory-consolidation/notes.md +1 -1
  216. package/kits/templates/memory-consolidation/profile.md +2 -2
  217. package/kits/templates/memory-consolidation/promote.md +20 -3
  218. package/kits/templates/roles/member.json +8 -1
  219. package/kits/templates/session-capsule/recovery.md +5 -0
  220. package/kits/templates/session-capsule/renew.md +5 -0
  221. package/kits/templates/system-fragments/baseagent.md +2 -2
  222. package/kits/templates/system-fragments/bootstrap.md +6 -6
  223. package/kits/templates/system-fragments/channel.md +1 -1
  224. package/kits/templates/system-fragments/memory.md +4 -4
  225. package/package.json +7 -3
  226. package/dist/stats/billing.js +0 -215
@@ -24,6 +24,31 @@ export function parseJsonObjectArgument(raw, optionName = '--payload') {
24
24
  }
25
25
  return parsed;
26
26
  }
27
+ export function buildCanonicalEvolcoreExecutionSpec(input) {
28
+ const argv = normalizeEvolcoreCommandArgv(input.argv);
29
+ canonicalizeLocalFilePathFlags(argv);
30
+ const spec = {
31
+ version: 1,
32
+ dialect: input.dialect,
33
+ wrapper: input.wrapper,
34
+ argv,
35
+ };
36
+ if (input.cwd !== undefined)
37
+ spec.cwd = input.cwd;
38
+ if (input.command?.mergeStderr)
39
+ spec.mergeStderr = true;
40
+ if (input.command?.filterChain?.length)
41
+ spec.filterChain = input.command.filterChain.map(stage => [...stage]);
42
+ if (input.command?.suffixArgv?.length)
43
+ spec.suffixArgv = [...input.command.suffixArgv];
44
+ if (input.command?.outputPath)
45
+ spec.outputPath = input.command.outputPath;
46
+ return spec;
47
+ }
48
+ /** Stable JSON used in delegation metadata and diagnostics. */
49
+ export function serializeCanonicalEvolcoreExecutionSpec(spec) {
50
+ return JSON.stringify(spec);
51
+ }
27
52
  function parseApplyPatchCommand(command, options = {}) {
28
53
  const input = command.trim();
29
54
  let commandText = input;
@@ -312,7 +337,7 @@ const EVOLCORE_SUBCOMMANDS = new Set([
312
337
  'fs', 'gateway', 'group', 'handoff', 'init', 'link-rules', 'logs', 'menu-client',
313
338
  'mode', 'model', 'msg', 'mv', 'net', 'queue', 'response', 'restart',
314
339
  'restart-monitor', 'rpc', 'start', 'stats', 'status', 'stop', 'storage', 'task',
315
- 'trigger', 'version', 'watch',
340
+ 'trigger', 'proxy', 'version', 'watch', 'session',
316
341
  ]);
317
342
  // Development/install entrypoints that are part of this repository's CLI.
318
343
  // Only these exact relative paths are canonicalized; arbitrary Node scripts
@@ -746,7 +771,7 @@ const INLINE_TEXT_FLAGS = {
746
771
  triggerUpdate: new Set(['--prompt', '--description']),
747
772
  };
748
773
  const MESSAGE_POSITIONAL_FLAGS = new Set([
749
- '--file', '--payload', '--as', '--content-type', '--text', '--transcript',
774
+ '--file', '--payload', '--payload-file', '--as', '--content-type', '--text', '--transcript',
750
775
  '--thread', '--title', '--description', '--text-from-file',
751
776
  '--handoff-context', '--aun-path', '--app', '--format', '--encrypt', '--no-encrypt',
752
777
  '--return', '--timeout',
@@ -891,6 +916,27 @@ function canonicalizeHandoffText(argv) {
891
916
  argv[index] = decodeEvolcoreInlineText(argv[index]);
892
917
  }
893
918
  }
919
+ const LOCAL_FILE_VALUE_FLAGS = new Set(['--file', '--text-from-file', '--payload-file']);
920
+ function normalizeWindowsFilePath(value) {
921
+ if (process.platform !== 'win32' || !/^[A-Za-z]:[\\/]/u.test(value))
922
+ return value;
923
+ return value.replace(/\\{2,}/gu, '\\').replace(/\/{2,}/gu, '/');
924
+ }
925
+ function canonicalizeLocalFilePathFlags(argv) {
926
+ for (let index = 2; index < argv.length; index++) {
927
+ if (argv[index] === '--')
928
+ break;
929
+ const inline = argv[index].match(/^(--(?:file|text-from-file|payload-file))=(.*)$/u);
930
+ if (inline) {
931
+ argv[index] = `${inline[1]}=${normalizeWindowsFilePath(inline[2])}`;
932
+ continue;
933
+ }
934
+ if (!LOCAL_FILE_VALUE_FLAGS.has(argv[index]) || argv[index + 1] === undefined)
935
+ continue;
936
+ argv[index + 1] = normalizeWindowsFilePath(argv[index + 1]);
937
+ index++;
938
+ }
939
+ }
894
940
  /**
895
941
  * Convert an EC invocation to the one argv representation shared by approval,
896
942
  * delegation hashing, IPC, and command execution. Shell syntax is already
@@ -903,6 +949,7 @@ export function canonicalizeEvolcoreCommandArgv(argv) {
903
949
  if (canonical[0] !== 'ec')
904
950
  return canonical;
905
951
  const result = [...canonical];
952
+ canonicalizeLocalFilePathFlags(result);
906
953
  const command = result[1];
907
954
  const subcommand = result[2];
908
955
  if (command === 'agent') {
@@ -2522,6 +2569,10 @@ export function parseCodexExecToolCommand(input) {
2522
2569
  function classifyCompositeProactiveSend(commandText, options) {
2523
2570
  const classified = classifyEvolcoreShellCommand(commandText, options);
2524
2571
  if (classified.kind === 'cd-prefixed' || classified.kind === 'bounded-output') {
2572
+ // 带尾部命令(suffixArgv)的结构不允许作为 proactive send 放行:
2573
+ // 尾部段可以是任意 echo/pwd,拼接意图不可证。
2574
+ if (classified.command.suffixArgv?.length)
2575
+ return null;
2525
2576
  const argv = normalizeEvolcoreCommandArgv(classified.command.argv);
2526
2577
  if (argv[0] === 'ec')
2527
2578
  return { ok: true, argv };
@@ -2987,6 +3038,72 @@ export function classifyEvolcoreShellCommand(command, options = {}) {
2987
3038
  ? { kind: 'composite', issue: literal.issue }
2988
3039
  : { kind: 'none' };
2989
3040
  }
3041
+ /**
3042
+ * Resolve a Codex Bash input through the same shell-boundary classifier used
3043
+ * by preflight, then produce one canonical EC execution spec for approval and
3044
+ * delegation. This intentionally recognizes EC by executable, not subcommand.
3045
+ */
3046
+ export function resolveCanonicalEvolcoreToolInput(input, options = {}) {
3047
+ const explicitArgv = Array.isArray(input.commandArgv)
3048
+ && input.commandArgv.every(value => typeof value === 'string')
3049
+ ? input.commandArgv
3050
+ : undefined;
3051
+ if (explicitArgv) {
3052
+ const nulIndex = explicitArgv.findIndex(value => value.includes('\0'));
3053
+ if (nulIndex >= 0)
3054
+ return {
3055
+ kind: 'invalid',
3056
+ failure: parseFailure('invalid-control-char', '', 0, nulIndex, options.dialect ?? 'posix'),
3057
+ };
3058
+ if (normalizeEvolcoreCommandArgv(explicitArgv)[0] === 'ec') {
3059
+ const spec = buildCanonicalEvolcoreExecutionSpec({
3060
+ argv: explicitArgv,
3061
+ dialect: options.dialect ?? 'posix',
3062
+ wrapper: 'literal',
3063
+ });
3064
+ return { kind: 'ec', spec };
3065
+ }
3066
+ }
3067
+ const rawCommand = typeof input.command === 'string' ? input.command : '';
3068
+ const carrier = explicitArgv
3069
+ ? resolveCodexShellCarrierArgv(explicitArgv)
3070
+ : resolveCodexShellCarrierString(rawCommand);
3071
+ const command = carrier?.command ?? rawCommand;
3072
+ const dialect = carrier?.dialect ?? options.dialect;
3073
+ const parseOptions = { ...options, ...(dialect ? { dialect } : {}) };
3074
+ const classification = classifyEvolcoreShellCommand(command, parseOptions);
3075
+ if (classification.kind === 'bounded-output' || classification.kind === 'cd-prefixed') {
3076
+ if (normalizeEvolcoreCommandArgv(classification.command.argv)[0] !== 'ec')
3077
+ return { kind: 'not-ec' };
3078
+ const spec = buildCanonicalEvolcoreExecutionSpec({
3079
+ argv: classification.command.argv,
3080
+ dialect: dialect ?? 'posix',
3081
+ wrapper: classification.kind,
3082
+ ...(classification.kind === 'cd-prefixed' && classification.cwd ? { cwd: classification.cwd } : {}),
3083
+ command: classification.command,
3084
+ });
3085
+ return { kind: 'ec', spec };
3086
+ }
3087
+ const parsed = carrier
3088
+ ? parseCodexCarrierCommand(carrier, parseOptions)
3089
+ : parseCodexToolCommand(input, parseOptions);
3090
+ if (parsed.ok && normalizeEvolcoreCommandArgv(parsed.argv)[0] === 'ec') {
3091
+ const spec = buildCanonicalEvolcoreExecutionSpec({
3092
+ argv: parsed.argv,
3093
+ dialect: dialect ?? 'posix',
3094
+ wrapper: 'literal',
3095
+ });
3096
+ return {
3097
+ kind: 'ec', spec,
3098
+ ...(parsed.credentialToken ? { credentialToken: parsed.credentialToken } : {}),
3099
+ };
3100
+ }
3101
+ if (classification.kind === 'composite')
3102
+ return { kind: 'invalid', ...(!parsed.ok ? { failure: parsed } : {}) };
3103
+ if (!parsed.ok && hasEcCommandPrefix(command))
3104
+ return { kind: 'invalid', failure: parsed };
3105
+ return { kind: 'not-ec' };
3106
+ }
2990
3107
  function isDeterministicFilePath(value) {
2991
3108
  return !!value
2992
3109
  && value === value.trim()
@@ -2994,6 +3111,15 @@ function isDeterministicFilePath(value) {
2994
3111
  && !value.startsWith('~')
2995
3112
  && !AMBIGUOUS_FILE_PATH_RE.test(value);
2996
3113
  }
3114
+ /** `$TMPDIR` is expanded by the managed shell; the daemon validates its final path. */
3115
+ function isManagedPayloadFilePath(value) {
3116
+ if (!value || value !== value.trim() || value.startsWith('--') || value.startsWith('~'))
3117
+ return false;
3118
+ if (!AMBIGUOUS_FILE_PATH_RE.test(value))
3119
+ return true;
3120
+ return /^(?:\$TMPDIR|\$\{TMPDIR\})(?:[\\/]|$)/i.test(value)
3121
+ && !/[\0\r\n`*?\[\]{}<>|;&]/.test(value);
3122
+ }
2997
3123
  function findSingleFileOption(argv, startIndex) {
2998
3124
  const matches = [];
2999
3125
  for (let index = startIndex; index < argv.length; index++) {
@@ -3012,7 +3138,7 @@ function findSingleFileOption(argv, startIndex) {
3012
3138
  : { invalid: true };
3013
3139
  }
3014
3140
  const PROACTIVE_SEND_VALUE_FLAGS = new Set([
3015
- '--format', '--app', '--file', '--text-from-file', '--link', '--payload',
3141
+ '--format', '--app', '--file', '--text-from-file', '--link', '--payload', '--payload-file',
3016
3142
  '--title', '--description', '--text', '--transcript', '--as',
3017
3143
  '--content-type', '--mention', '--aun-path', '--thread', '--handoff-context',
3018
3144
  '--check-every', '--trigger-prompt', '--return', '--timeout',
@@ -3132,8 +3258,13 @@ function hasExecutableProactiveSendPayload(argv, scope) {
3132
3258
  return false;
3133
3259
  modes.set('payload', operand);
3134
3260
  }
3261
+ if (value === '--payload-file') {
3262
+ if (scope !== 'msg' || modes.has('payload-file') || !isManagedPayloadFilePath(operand))
3263
+ return false;
3264
+ modes.set('payload-file', operand);
3265
+ }
3135
3266
  }
3136
- if (modes.size > 1)
3267
+ if (modes.size > 1 || (modes.size > 0 && positionals.length > 0))
3137
3268
  return false;
3138
3269
  if (modes.has('link')) {
3139
3270
  try {
@@ -3153,6 +3284,8 @@ function hasExecutableProactiveSendPayload(argv, scope) {
3153
3284
  return false;
3154
3285
  }
3155
3286
  }
3287
+ if (modes.has('payload-file'))
3288
+ return true;
3156
3289
  return positionals.join(' ').length > 0;
3157
3290
  }
3158
3291
  function parseEvolcoreSendArgv(argv) {
@@ -3297,7 +3430,7 @@ export function describeProactiveSendCommandFailure(toolName, input, session) {
3297
3430
  + `要联系其他对象请走 --thread 跨话题发送(ec thread list <对方AID> 选中话题后加 --check-every)。`;
3298
3431
  }
3299
3432
  return `${prefix}发送者与目标正确,但正文或参数无效——正文不能为空;--file/--text-from-file 属于文件发送,`
3300
- + '不在普通回复放行范围;--link 的值必须是 http(s) URL;--payload 的值必须是 JSON 对象。';
3433
+ + '不在普通回复放行范围;--link 的值必须是 http(s) URL;--payload 的值必须是 JSON 对象;--payload-file 的值必须是确定的文件路径。';
3301
3434
  }
3302
3435
  /** 与 CLI `isValidAid` 同一规则;parser 不依赖 AID 模块,避免引入身份存储副作用。 */
3303
3436
  function looksLikeAid(value) {
@@ -115,6 +115,22 @@ export function isSandboxInitializationFailure(error, stderr = []) {
115
115
  || /(?:^|\n)\s*bwrap:\s*(?:can't|cannot) create (?:file|directory) at [^\n]+: read-only file system/.test(text)
116
116
  || /(?:^|\n)\s*bwrap:\s*(?:can't|cannot) mkdir parents for [^\n]+: read-only file system/.test(text);
117
117
  }
118
+ /**
119
+ * Recognize failures from a task runner's nested sandbox. The outer EvolCore
120
+ * H-class guard is already running when this is used, so generic outer guard
121
+ * launch failures must not be treated as safe fallback candidates.
122
+ */
123
+ export function isNestedSandboxInitializationFailure(error, stderr = []) {
124
+ const text = [error instanceof Error ? error.message : String(error ?? ''), ...stderr]
125
+ .join('\n')
126
+ .toLowerCase();
127
+ return text.includes(CODEX_SANDBOX_USER_NAMESPACE_UNAVAILABLE)
128
+ || text.includes(CODEX_SANDBOX_USER_NAMESPACE_DISABLED_BY_APPARMOR)
129
+ || /fs sandbox helper failed/.test(text)
130
+ || /failed to initialize session[\s\S]*sandbox/.test(text)
131
+ || /(?:apply-seccomp|seccomp)[\s\S]*(?:uid_map|gid_map|operation not permitted|permission denied)/.test(text)
132
+ || /(?:uid_map|gid_map)[\s\S]*(?:operation not permitted|permission denied)/.test(text);
133
+ }
118
134
  export function isCodexSandboxUserNamespaceFailure(error) {
119
135
  const record = error && typeof error === 'object'
120
136
  ? error
@@ -318,7 +334,8 @@ export function formatCodexSandboxAvailability(check) {
318
334
  return `Codex Linux sandbox check not applicable on ${check.platform}`;
319
335
  if (check.status === 'missing') {
320
336
  return 'Codex Linux sandbox is unavailable: bubblewrap (bwrap) was not found; '
321
- + 'install or provision the Codex sandbox runtime. EvolCore will not disable the sandbox automatically.';
337
+ + 'install or provision the Codex nested sandbox runtime. Managed Linux sessions may retry '
338
+ + 'behind the EvolCore H-class guard; direct app-server callers remain fail-closed.';
322
339
  }
323
340
  const apparmor = check.apparmorRestrictsUnprivilegedUserns === true
324
341
  ? ' AppArmor restricts unprivileged user namespaces on this host; the probe below confirms whether the active profile permits Codex.'
@@ -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. */
@@ -2107,7 +2107,7 @@ export function checkLClassWrite(toolName, input, context) {
2107
2107
  behavior: 'deny',
2108
2108
  message: context?.permissionMode === 'readonly'
2109
2109
  ? '🔒 只读模式:visitor 最低权限不允许读取 L-class 路径'
2110
- : '🔒 L-class 路径允许读取,但当前 Bash 复合命令无法证明为只读,已拒绝执行。请改用受控的 EvolCore 读取命令或白名单只读命令',
2110
+ : `🔒 L-class 路径允许读取,但当前 Bash 命令无法证明为只读${protectedOperands.analysis.kind === 'unproven' ? `(原因码:${protectedOperands.analysis.reason})` : ''},已拒绝执行。请改用受控的 EvolCore 读取命令或白名单只读命令`,
2111
2111
  matchedPath: protectedOperands.lClassPath,
2112
2112
  };
2113
2113
  }
@@ -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(['低', '中', '高']);
@@ -2348,6 +2369,7 @@ export function checkBashDescription(toolName, input) {
2348
2369
  /** Shared fail-closed preflight used before runner-specific mode and approval handling. */
2349
2370
  export function evaluateToolPreflight(toolName, input, context) {
2350
2371
  let applyPatchFileChanges;
2372
+ let protectedPolicyCommand;
2351
2373
  const managedPathCheck = checkManagedTempToolPaths(toolName, input, managedTempOptions(context));
2352
2374
  if (managedPathCheck.kind === 'deny') {
2353
2375
  const currentTmpDir = resolveManagedTempDir(managedTempOptions(context).env);
@@ -2397,6 +2419,13 @@ export function evaluateToolPreflight(toolName, input, context) {
2397
2419
  ?? (explicitCommandArgv ? undefined : resolveCodexShellCarrierString(command));
2398
2420
  const wrappedCommand = stringShellCarrier?.parseFailure ? undefined : stringShellCarrier?.command;
2399
2421
  const policyCommand = wrappedCommand ?? commandForPolicy;
2422
+ // The class checks must inspect the same inner command used by command
2423
+ // classification. Otherwise Codex's outer `bash -lc` carrier makes a
2424
+ // valid single read look like an unsupported composite shell command.
2425
+ protectedPolicyCommand = wrappedCommand
2426
+ ?? (!shellCarrier && explicitCommandArgv
2427
+ ? explicitCommandArgv.map(quotePosixShellArg).join(' ')
2428
+ : undefined);
2400
2429
  if (context.sessionId && /^\s*(?:command\s+-v|which|type)\s+ec\s*$/i.test(policyCommand)) {
2401
2430
  return {
2402
2431
  behavior: 'deny',
@@ -2672,7 +2701,10 @@ export function evaluateToolPreflight(toolName, input, context) {
2672
2701
  ? { ...checkedInput, fileChanges: applyPatchFileChanges }
2673
2702
  : checkedInput;
2674
2703
  const policyToolName = applyPatchFileChanges ? 'FileChange' : toolName;
2675
- const hClass = checkHClassWrite(policyToolName, policyInput, {
2704
+ const protectedPolicyInput = policyToolName === 'Bash' && protectedPolicyCommand
2705
+ ? { ...policyInput, command: protectedPolicyCommand }
2706
+ : policyInput;
2707
+ const hClass = checkHClassWrite(policyToolName, protectedPolicyInput, {
2676
2708
  sessionId: context.sessionId,
2677
2709
  channel: context.channel,
2678
2710
  peerId: context.userId,
@@ -2689,7 +2721,7 @@ export function evaluateToolPreflight(toolName, input, context) {
2689
2721
  if (hClass.behavior === 'deny') {
2690
2722
  return { behavior: 'deny', input: checkedInput, message: hClass.message, policyCode: 'h_class_protection', matchedPath: hClass.matchedPath };
2691
2723
  }
2692
- const lClass = checkLClassWrite(policyToolName, policyInput, {
2724
+ const lClass = checkLClassWrite(policyToolName, protectedPolicyInput, {
2693
2725
  sessionId: context.sessionId,
2694
2726
  channel: context.channel,
2695
2727
  peerId: context.userId,
@@ -66,7 +66,10 @@ import * as path from 'path';
66
66
  import * as crypto from 'crypto';
67
67
  import { parse as parseYaml } from 'yaml';
68
68
  import { logger } from '../../utils/logger.js';
69
- import { agentMdPath } from '../../paths.js';
69
+ import { agentDir as resolveAgentDir, agentMdPath } from '../../paths.js';
70
+ import { ConfigTarget, mutateConfig, read } from '../../config/config-manager.js';
71
+ import { isValidAid } from '../../aun/aid/validation.js';
72
+ import { resolveAunTargetKind, verifiedPeerType, } from '../../aun/group/identity.js';
70
73
  /**
71
74
  * peerKey: 关系层路由键,格式 `<channelType>#<urlEncode(channelId)>`。
72
75
  * 群聊场景下 channelId = groupId,所有发言者共用同一个 peerKey。
@@ -83,6 +86,58 @@ export function parsePeerKey(key) {
83
86
  channelId: decodeURIComponent(key.slice(idx + 1)),
84
87
  };
85
88
  }
89
+ /** Read type evidence without network access or any AID-shape fallback. */
90
+ export function readAunPeerKind(selfAid, peerAid, options = {}) {
91
+ if (!isValidAid(selfAid) || !isValidAid(peerAid)) {
92
+ return { kind: 'unknown', reason: 'invalid', sources: [] };
93
+ }
94
+ try {
95
+ const relation = options.relation !== undefined ? options.relation
96
+ : read(ConfigTarget.Relation, { self: selfAid, peerKey: formatPeerKey('aun', peerAid) });
97
+ return resolveAunTargetKind({
98
+ routeKind: options.routeKind,
99
+ targetKind: relation?.targetKind,
100
+ verifiedType: verifiedPeerType(peerAid, PeerIdentityCache.get('aun', peerAid, resolveAgentDir(selfAid))),
101
+ });
102
+ }
103
+ catch {
104
+ return { kind: 'unknown', reason: 'unavailable', sources: [] };
105
+ }
106
+ }
107
+ /** Fetch and cache a verified card only when local evidence is missing. Never resolve a conflict by guessing. */
108
+ export async function resolveAunPeerKind(selfAid, peerAid, options = {}) {
109
+ const current = readAunPeerKind(selfAid, peerAid, options);
110
+ if (current.reason !== 'missing')
111
+ return current;
112
+ try {
113
+ const { agentmdGet } = await import('../../aun/aid/agentmd.js');
114
+ const result = await agentmdGet(peerAid, { withVerification: true });
115
+ if (result.verification.status !== 'verified')
116
+ return { ...current, reason: 'unavailable' };
117
+ const metadata = parseAgentMdFrontmatter(result.content);
118
+ if (metadata.aid !== peerAid || typeof metadata.type !== 'string' || !metadata.type.trim()) {
119
+ return { kind: 'unknown', reason: 'invalid', sources: [] };
120
+ }
121
+ PeerIdentityCache.cacheVerifiedAgentMd('aun', peerAid, resolveAgentDir(selfAid), result.content);
122
+ // Re-read relation metadata because it may have changed during the remote lookup.
123
+ return readAunPeerKind(selfAid, peerAid, options);
124
+ }
125
+ catch {
126
+ return { ...current, reason: 'unavailable' };
127
+ }
128
+ }
129
+ /** Persist a trusted runtime kind, without overwriting conflicting evidence. */
130
+ export function recordAunPeerRoute(selfAid, peerAid, routeKind) {
131
+ const current = readAunPeerKind(selfAid, peerAid, { routeKind });
132
+ if (current.kind !== routeKind)
133
+ return current;
134
+ return mutateConfig(ConfigTarget.Relation, { self: selfAid, peerKey: formatPeerKey('aun', peerAid) }, relation => {
135
+ const resolution = readAunPeerKind(selfAid, peerAid, { routeKind, relation });
136
+ if (resolution.kind === routeKind)
137
+ relation.targetKind = routeKind;
138
+ return resolution;
139
+ }).value;
140
+ }
86
141
  /**
87
142
  * 对端身份缓存管理器
88
143
  */
@@ -114,6 +169,14 @@ export class PeerIdentityCache {
114
169
  return null;
115
170
  }
116
171
  }
172
+ /** Internal callers must pass bytes returned by agentmdGet with verification.status=verified. */
173
+ static cacheVerifiedAgentMd(channelType, peerId, agentDir, content) {
174
+ const metadata = parseAgentMdFrontmatter(content);
175
+ if (metadata.aid !== peerId || typeof metadata.type !== 'string' || !metadata.type.trim()) {
176
+ throw new Error('Verified agent.md must declare the requested AID and its type');
177
+ }
178
+ return this.updateFromAgentMd(channelType, peerId, agentDir, content, Date.now(), 'agentmd');
179
+ }
117
180
  /** Expire only the freshness check; retain the last snapshot and its trust level. */
118
181
  static invalidate(channelType, peerId, agentDir) {
119
182
  const cached = this.get(channelType, peerId, agentDir);
@@ -1,10 +1,12 @@
1
1
  import { getRoleDefinition } from '../../config/roles.js';
2
2
  import { PUBLIC_PERMISSION_MODES } from '../permission/mode.js';
3
- import { ConfigTarget, read } from '../../config/config-manager.js';
3
+ import { ConfigTarget, mutateConfig, read } from '../../config/config-manager.js';
4
4
  import { resolvePrincipal } from '../../config/contact-book.js';
5
5
  import { getDaemonOwners, ownerResolver } from '../ownership/owner-resolver.js';
6
6
  import { hasTrustedPrincipal } from '../auth/authenticated-actor.js';
7
7
  import { isTopicSession } from '../thread/topic-id.js';
8
+ import { formatPeerKey } from '../relation/peer-identity.js';
9
+ import { logger } from '../../utils/logger.js';
8
10
  const PERMISSION_MODE_AUTHORITY = {
9
11
  readonly: 0,
10
12
  auto: 1,
@@ -161,30 +163,85 @@ export function agentFullAccessStatus(agentAid, principalId) {
161
163
  return { enabled, eligible, effective: enabled && eligible };
162
164
  }
163
165
  export function sessionFullAccessStatus(session, principalId) {
164
- const override = session.metadata?.sessionFullAccess;
165
166
  const agentStatus = session.selfAID ? agentFullAccessStatus(session.selfAID, principalId) : {
166
167
  enabled: false, eligible: false, effective: false,
167
168
  };
168
- if (isTopicSession(session) && !override) {
169
- return { enabled: false, eligible: agentStatus.eligible, effective: false, inherited: false };
169
+ // Agent policy is the global switch. Once enabled for an eligible owner it
170
+ // takes precedence over any per-main-session or per-topic /fa state.
171
+ const override = readSessionFullAccessOverride(session);
172
+ const localEnabled = override?.enabled === true;
173
+ const scope = isTopicSession(session) ? 'session' : 'relation';
174
+ if (agentStatus.enabled) {
175
+ return {
176
+ ...agentStatus, effective: agentStatus.effective && session.chatType === 'private',
177
+ inherited: true, globalEnabled: true, localEnabled, scope, source: 'agent', mutable: false,
178
+ };
170
179
  }
171
- if (!override || typeof override !== 'object') {
172
- return { ...agentStatus, inherited: true };
180
+ if (!override) {
181
+ return {
182
+ enabled: false, eligible: agentStatus.eligible, effective: false,
183
+ inherited: false, globalEnabled: false, localEnabled: false, scope, source: scope, mutable: true,
184
+ };
173
185
  }
174
186
  const eligible = !!session.selfAID && isAgentFullAccessOwner(session.selfAID, principalId);
175
187
  return {
176
188
  enabled: override.enabled === true,
177
189
  eligible,
178
- effective: override.enabled === true && eligible && principalId === override.authorizedBy,
190
+ effective: override.enabled === true && eligible && principalId === override.authorizedBy
191
+ && session.chatType === 'private',
179
192
  inherited: false,
193
+ globalEnabled: false,
194
+ localEnabled,
195
+ scope,
196
+ source: scope,
197
+ mutable: true,
180
198
  authorizedBy: override.authorizedBy,
181
199
  };
182
200
  }
183
- export function hasSessionFullAccessOverride(session) {
184
- return !!session.metadata && Object.prototype.hasOwnProperty.call(session.metadata, 'sessionFullAccess');
201
+ /** Read the local /fa switch without applying the Agent-level global switch. */
202
+ export function readSessionFullAccessOverride(session) {
203
+ let value = session.metadata?.sessionFullAccess;
204
+ if (!isTopicSession(session)) {
205
+ const selector = mainSessionFullAccessSelector(session);
206
+ if (!selector)
207
+ return undefined;
208
+ try {
209
+ value = read(ConfigTarget.Relation, selector, { cache: false })?.sessionFullAccess;
210
+ }
211
+ catch (error) {
212
+ logger.warn(`[FullAccess] Cannot read main-session policy for ${session.id}: ${error instanceof Error ? error.message : String(error)}`);
213
+ return undefined;
214
+ }
215
+ }
216
+ if (!value || typeof value !== 'object' || Array.isArray(value))
217
+ return undefined;
218
+ const config = value;
219
+ return typeof config.enabled === 'boolean'
220
+ && typeof config.authorizedBy === 'string' && !!config.authorizedBy.trim()
221
+ ? { enabled: config.enabled, authorizedBy: config.authorizedBy }
222
+ : undefined;
223
+ }
224
+ function mainSessionFullAccessSelector(session) {
225
+ const peerId = session.channelId;
226
+ if (isTopicSession(session) || session.chatType !== 'private' || !session.selfAID || !peerId)
227
+ return undefined;
228
+ return { self: session.selfAID, peerKey: formatPeerKey(session.channelType || session.channel, peerId) };
229
+ }
230
+ /** Persist the main-session /fa switch at relation scope (backend independent). */
231
+ export function updateRelationSessionFullAccess(session, config) {
232
+ const selector = mainSessionFullAccessSelector(session);
233
+ if (!selector) {
234
+ throw Object.assign(new Error('fullaccess main session requires a private relation'), { code: 'INVALID_CONTEXT' });
235
+ }
236
+ if (typeof config.enabled !== 'boolean' || !config.authorizedBy.trim()) {
237
+ throw Object.assign(new Error('invalid session fullaccess configuration'), { code: 'INVALID_ARGUMENT' });
238
+ }
239
+ mutateConfig(ConfigTarget.Relation, selector, current => {
240
+ current.sessionFullAccess = { ...config };
241
+ });
185
242
  }
186
243
  export function createSessionFullAccessAuthorization(input) {
187
- const config = input.session.metadata?.sessionFullAccess;
244
+ const config = readSessionFullAccessOverride(input.session);
188
245
  if (!config?.enabled
189
246
  || input.session.chatType !== 'private'
190
247
  || (input.source !== undefined && input.source !== 'user')
@@ -209,16 +266,18 @@ export function assertSessionFullAccessAuthorization(authorization, session) {
209
266
  if (authorization.source !== 'session-policy'
210
267
  || !session
211
268
  || authorization.sessionId !== session.id
212
- || !authorization.agentAid
269
+ || !authorization.agentAid || authorization.agentAid !== session.selfAID
270
+ || session.chatType !== 'private'
213
271
  || !authorization.policyActor
214
272
  || !hasTrustedPrincipal(authorization.policyActor)) {
215
273
  throw new Error('session fullaccess authorization is missing or malformed');
216
274
  }
217
275
  const current = resolvePrincipal(authorization.agentAid, authorization.policyActor.operatorChannelType, authorization.policyActor.operatorId, authorization.policyActor.operatorChannelKey);
276
+ const config = readSessionFullAccessOverride(session);
218
277
  if (!hasTrustedPrincipal({ ...authorization.policyActor, ...current })
219
278
  || current.principalId !== authorization.authorizedBy
220
- || session.metadata?.sessionFullAccess?.enabled !== true
221
- || session.metadata.sessionFullAccess.authorizedBy !== authorization.authorizedBy
279
+ || config?.enabled !== true
280
+ || config.authorizedBy !== authorization.authorizedBy
222
281
  || !isAgentFullAccessOwner(authorization.agentAid, authorization.authorizedBy)) {
223
282
  throw new Error('session fullaccess authorization is no longer active');
224
283
  }