evolcore 0.0.41-test.0 → 0.0.41-test.2

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 (235) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/agents/baseagent-availability.js +1 -1
  3. package/dist/agents/baseagent.js +88 -49
  4. package/dist/agents/claude-runner.js +177 -92
  5. package/dist/agents/codex-runner.js +146 -71
  6. package/dist/agents/ecagent-runner.js +1 -1
  7. package/dist/agents/gemini-runner.js +1 -1
  8. package/dist/aun/aid/agentmd.js +98 -11
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +26 -2
  11. package/dist/aun/aid/identity.js +91 -0
  12. package/dist/aun/aid/index.js +1 -1
  13. package/dist/aun/aid/managed-operation.js +1 -1
  14. package/dist/aun/aid/ownership-operation.js +23 -22
  15. package/dist/aun/group/fs-download.js +39 -0
  16. package/dist/aun/group/identity.js +36 -21
  17. package/dist/aun/group/operations.js +5 -0
  18. package/dist/aun/menu/client.js +27 -0
  19. package/dist/aun/msg/managed-operation.js +68 -7
  20. package/dist/aun/msg/p2p.js +8 -8
  21. package/dist/aun/service-proxy.js +53 -12
  22. package/dist/channels/aun.js +633 -32
  23. package/dist/channels/daemon.js +15 -1
  24. package/dist/cli/agent-command.js +5 -2
  25. package/dist/cli/agent-create.js +991 -233
  26. package/dist/cli/agent.js +49 -10
  27. package/dist/cli/aid-bind-command.js +48 -19
  28. package/dist/cli/aun-commands.js +48 -36
  29. package/dist/cli/daemon-commands.js +679 -697
  30. package/dist/cli/fs-command.js +64 -2
  31. package/dist/cli/index.js +72 -5
  32. package/dist/cli/init-channel.js +1 -1
  33. package/dist/cli/init.js +75 -1
  34. package/dist/cli/managed-command-guard.js +17 -1
  35. package/dist/cli/model.js +40 -40
  36. package/dist/cli/provider-command.js +57 -0
  37. package/dist/cli/proxy-command.js +92 -0
  38. package/dist/cli/restart-monitor.js +4 -2
  39. package/dist/cli/role.js +85 -0
  40. package/dist/cli/stats.js +10 -3
  41. package/dist/cli/task-context.js +19 -0
  42. package/dist/config/access-policy.js +7 -2
  43. package/dist/config/boot-log.js +39 -1
  44. package/dist/config/config-field-policy.js +17 -39
  45. package/dist/config/config-manager.js +183 -44
  46. package/dist/config/config-operation-service.js +5 -19
  47. package/dist/config/contact-book-store.js +47 -21
  48. package/dist/config/contact-book.js +18 -12
  49. package/dist/config/contact-operation-service.js +3 -4
  50. package/dist/config/contact-request-service.js +11 -0
  51. package/dist/config/daemon-services.js +11 -0
  52. package/dist/config/gateway-config.js +88 -594
  53. package/dist/config/owner-config.js +2 -2
  54. package/dist/config/peer-role-resolver.js +15 -12
  55. package/dist/config/provider-ipc-service.js +132 -0
  56. package/dist/config/provider-menu-request.js +58 -0
  57. package/dist/config/providers-config.js +12 -7
  58. package/dist/config/providers-import.js +3 -21
  59. package/dist/config/providers-management.js +78 -5
  60. package/dist/config/resolved-config-op.js +11 -1
  61. package/dist/config/role-command-service.js +166 -0
  62. package/dist/config/role-request-service.js +193 -0
  63. package/dist/config/schema-migration.js +1000 -25
  64. package/dist/config-store.js +89 -4
  65. package/dist/contracts/ecweb-instance.js +41 -0
  66. package/dist/contracts/ecweb-service-protocol.js +4 -1
  67. package/dist/core/agent-application-service.js +60 -11
  68. package/dist/core/agent-create-status.js +203 -0
  69. package/dist/core/agent-creation-claim.js +177 -0
  70. package/dist/core/agent-ipc-registration.js +39 -18
  71. package/dist/core/agent-runtime.js +194 -24
  72. package/dist/core/auth/agent-delegation.js +6 -3
  73. package/dist/core/auth/auth-gateway.js +67 -2
  74. package/dist/core/auth/authorization-audit.js +58 -11
  75. package/dist/core/auth/delegation-authorization.js +5 -2
  76. package/dist/core/auth/operation-authorizer.js +43 -6
  77. package/dist/core/auth/operation-catalog.js +45 -7
  78. package/dist/core/channel-loader.js +2 -0
  79. package/dist/core/command/agent-control.js +260 -21
  80. package/dist/core/command/agent-storage-menu.js +5 -3
  81. package/dist/core/command/cli-intent-parser.js +8 -3
  82. package/dist/core/command/command-handler.js +112 -154
  83. package/dist/core/command/connect-menu.js +11 -3
  84. package/dist/core/command/data-root-resolver.js +5 -4
  85. package/dist/core/command/memory-slash.js +16 -8
  86. package/dist/core/command/menu-catalog.js +10 -6
  87. package/dist/core/command/menu-handler.js +106 -73
  88. package/dist/core/command/menu-protocol.js +15 -1
  89. package/dist/core/command/provider-menu.js +46 -0
  90. package/dist/core/command/role-menu.js +147 -30
  91. package/dist/core/command/slash-handler.js +125 -255
  92. package/dist/core/daemon-control.js +26 -27
  93. package/dist/core/event-catalog.js +10 -0
  94. package/dist/core/evolagent-registry.js +7 -5
  95. package/dist/core/evolagent.js +10 -8
  96. package/dist/core/file-integrity/store.js +11 -0
  97. package/dist/core/handoff/ipc-registration.js +3 -0
  98. package/dist/core/inference/text-inference.js +31 -40
  99. package/dist/core/initialization/service.js +491 -0
  100. package/dist/core/ipc-registration.js +40 -24
  101. package/dist/core/memory/consolidation-context.js +51 -5
  102. package/dist/core/memory/consolidation-ops-records.js +96 -1
  103. package/dist/core/memory/consolidation-trigger.js +208 -191
  104. package/dist/core/memory/consolidation.js +333 -35
  105. package/dist/core/memory/index-manager.js +27 -5
  106. package/dist/core/memory/memory-admin.js +45 -5
  107. package/dist/core/memory/memory-writer.js +163 -18
  108. package/dist/core/memory/relation-idle-monitor.js +119 -58
  109. package/dist/core/memory/relation-sweep.js +55 -45
  110. package/dist/core/message/aun-ipc-sender.js +81 -69
  111. package/dist/core/message/im-renderer.js +25 -4
  112. package/dist/core/message/message-admission.js +89 -4
  113. package/dist/core/message/message-bridge.js +66 -21
  114. package/dist/core/message/response-engine.js +108 -35
  115. package/dist/core/model/catalog-service.js +5 -3
  116. package/dist/core/model/config-scope.js +29 -71
  117. package/dist/core/model/field-scope.js +1 -1
  118. package/dist/core/model/model-catalog.js +30 -41
  119. package/dist/core/model/model-diagnostics.js +4 -3
  120. package/dist/core/model/model-fallback.js +10 -7
  121. package/dist/core/model/model-permission.js +3 -2
  122. package/dist/core/ownership/owner-resolver.js +772 -158
  123. package/dist/core/permission/approval-gateway.js +103 -403
  124. package/dist/core/permission/ec-command-parser.js +62 -6
  125. package/dist/core/permission/index.js +1 -0
  126. package/dist/core/permission/permission-result.js +78 -0
  127. package/dist/core/permission/sandbox-runtime.js +18 -1
  128. package/dist/core/permission/tool-policy.js +21 -46
  129. package/dist/core/relation/peer-identity.js +64 -1
  130. package/dist/core/role/runtime-policy.js +72 -13
  131. package/dist/core/session/session-capsule.js +1 -1
  132. package/dist/core/session/session-idle-monitor.js +1 -1
  133. package/dist/core/session/session-manager.js +20 -0
  134. package/dist/core/session/session-renew.js +3 -3
  135. package/dist/core/skill/index-generator.js +15 -5
  136. package/dist/core/system-session/memory.js +43 -8
  137. package/dist/core/thread/thread-service.js +19 -6
  138. package/dist/directory/owner-directory-admission.js +95 -0
  139. package/dist/directory/owner-directory-authorization.js +309 -0
  140. package/dist/directory/owner-directory-cache.js +635 -0
  141. package/dist/eck/kit-renderer.js +2 -2
  142. package/dist/ecweb/basic-settings-service.js +33 -40
  143. package/dist/ecweb/init-menu.js +32 -0
  144. package/dist/ecweb/message-context-service.js +110 -0
  145. package/dist/index.js +93 -19
  146. package/dist/ipc.js +247 -29
  147. package/dist/paths.js +7 -0
  148. package/dist/proxy/command.js +122 -0
  149. package/dist/proxy/ipc-service.js +68 -0
  150. package/dist/proxy/manager.js +484 -0
  151. package/dist/proxy/service-supervisor.js +603 -0
  152. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  153. package/dist/trigger/authorization.js +27 -17
  154. package/dist/trigger/feedback.js +2 -3
  155. package/dist/trigger/ipc-service.js +105 -78
  156. package/dist/trigger/local-files.js +2 -1
  157. package/dist/trigger/manager.js +5 -3
  158. package/dist/trigger/scheduler.js +88 -6
  159. package/dist/utils/atomic-write.js +28 -0
  160. package/dist/utils/cross-platform.js +14 -0
  161. package/dist/utils/ecweb-supervisor.js +258 -83
  162. package/dist/utils/error-utils.js +26 -2
  163. package/dist/utils/logger.js +92 -6
  164. package/dist/utils/package-version-info.js +4 -2
  165. package/dist/utils/welcome.js +1 -1
  166. package/kits/docs/INDEX.md +1 -0
  167. package/kits/docs/aun/SDK.md +4 -1
  168. package/kits/docs/channels/aun.md +9 -0
  169. package/kits/docs/evolcore/INDEX.md +1 -0
  170. package/kits/docs/evolcore/agent.md +8 -1
  171. package/kits/docs/evolcore/aid.md +67 -17
  172. package/kits/docs/evolcore/config.md +28 -7
  173. package/kits/docs/evolcore/contact.md +3 -0
  174. package/kits/docs/evolcore/fs.md +11 -0
  175. package/kits/docs/evolcore/group.md +1 -1
  176. package/kits/docs/evolcore/memory-architecture.md +2 -2
  177. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  178. package/kits/docs/evolcore/memory.md +1 -1
  179. package/kits/docs/evolcore/menu-protocol.md +4 -0
  180. package/kits/docs/evolcore/model.md +23 -20
  181. package/kits/docs/evolcore/msg.md +4 -7
  182. package/kits/docs/evolcore/provider.md +50 -0
  183. package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
  184. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  185. package/kits/rules/01-overview.md +3 -0
  186. package/kits/rules/04-relation.md +1 -1
  187. package/kits/schemas/_meta.json +37 -4
  188. package/kits/schemas/agent-config.schema.13.json +8 -3
  189. package/kits/schemas/agent-config.schema.16.json +891 -0
  190. package/kits/schemas/daemon.schema.9.json +366 -0
  191. package/kits/schemas/defaults.schema.5.json +406 -127
  192. package/kits/schemas/relation-config.schema.11.json +277 -0
  193. package/kits/schemas/role-config.schema.1.json +7 -7
  194. package/kits/skills/.switches.json +4 -0
  195. package/kits/skills/ec-agent-create/SKILL.md +3 -0
  196. package/kits/skills/ec-identity/SKILL.md +2 -2
  197. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  198. package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
  199. package/kits/skills/personal-assistant/SKILL.md +176 -0
  200. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  201. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  202. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  203. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  204. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  205. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  206. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  207. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  208. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  209. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  210. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  211. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  212. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  213. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  214. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  215. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  216. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  217. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  218. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  219. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  220. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  221. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  222. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  223. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  224. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  225. package/kits/skills/thread-ops/SKILL.md +5 -0
  226. package/kits/templates/memory-consolidation/forget.md +19 -6
  227. package/kits/templates/memory-consolidation/notes.md +1 -1
  228. package/kits/templates/memory-consolidation/profile.md +2 -2
  229. package/kits/templates/memory-consolidation/promote.md +20 -3
  230. package/kits/templates/roles/member.json +8 -1
  231. package/kits/templates/system-fragments/baseagent.md +2 -2
  232. package/kits/templates/system-fragments/memory.md +4 -4
  233. package/kits/templates/system-fragments/venue.md +1 -1
  234. package/package.json +7 -3
  235. package/dist/core/message/create-status.js +0 -96
@@ -2,18 +2,20 @@ import { getRunnerCatalog, catalogEfforts, assertCatalogSelectable } from '../co
2
2
  // Codex/OpenAI API 不认识 Claude Code SDK 的窗口后缀,必须传入基础模型 ID。
3
3
  import { parseModelId, stripContextWindowSuffix } from '../core/model/context-window-suffix.js';
4
4
  import { formatAsyncQuestionAnswer, hasTrustedFullAccessContext, parseAsyncUserQuestions, unsettledInterruptError, withInterruptDeadline } from './runner-types.js';
5
- import { requestDangerousCommandPermission } from '../core/permission/approval-gateway.js';
5
+ import { requestDangerousCommandPermissionResult } from '../core/permission/approval-gateway.js';
6
+ import { permissionFailureResult } from '../core/permission/permission-result.js';
6
7
  import { checkReadonly, checkDangerousCommand, evaluateToolPreflight } from '../core/permission/tool-policy.js';
7
8
  import { isShellToolName } from '../core/permission/tool-canonical.js';
8
9
  import { normalizeExecutionPermissionMode, normalizePermissionMode, resolvePhaseOneExecutionSandbox } from '../core/permission/mode.js';
9
10
  import { assertWindowsCodexFilesystemRuleBudget, buildCodexProtectedFilesystemRules, compactCodexLinuxFilesystemRules, getExistingRelationAttachmentDirs, isSameOrDescendant, resolveProtectedCandidate, } from '../core/permission/protected-paths.js';
10
11
  import { CODEX_THREAD_ACTIVE_WRITER, CodexAppServerClient, } from './codex/app-server-client.js';
12
+ import { getSandboxInitializationFailureCounters, isNestedSandboxInitializationFailure, recordSandboxInitializationFailure, SANDBOX_INITIALIZATION_FAILED, } from '../core/permission/sandbox-runtime.js';
11
13
  import { resolveOpenaiConfig, resolveCodexCliPath, resolveCodexPowerShellShimPath, } from './baseagent.js';
12
14
  import { logger } from '../utils/logger.js';
13
15
  import { resolveProviderService } from '../config/providers.js';
14
16
  import { catalogHash } from '../core/model/catalog-service.js';
15
17
  import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
16
- import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
18
+ import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolInfrastructureFailure, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
17
19
  import { classifyError, ErrorType, getToolResultErrorText, isOutputTokenLimitError, isRetryableError } from '../utils/error-utils.js';
18
20
  import { findModelSpec, getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
19
21
  import { renderActionAsText } from '../core/interaction-router.js';
@@ -21,7 +23,7 @@ import { buildEnvelope, isInteractionSendAccepted, sendInteractionPayload } from
21
23
  import { resolveCodexCapabilityThreadConfigForProject } from '../core/capability/capability-manager.js';
22
24
  import { AGENT_DELEGATION_TOKEN_ENV, CODEX_SESSION_TOKEN_ENV, hashDelegatedCommandArgv, hashDelegatedCommandSpec, parseDelegatedExecutionSpec, } from '../core/auth/agent-delegation.js';
23
25
  import { sanitizeShellExecutionEnvironment } from '../core/permission/shell-environment.js';
24
- import { classifyEvolcoreShellCommand, containsLiteralManagedTmpDirOutsideSendContent, containsUnresolvedManagedTmpDirReference, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseLiteralShellArgv, resolveCodexShellCarrierArgv, parseShellApplyPatchInvocation, resolveCanonicalEvolcoreToolInput, serializeCanonicalEvolcoreExecutionSpec, } from '../core/permission/ec-command-parser.js';
26
+ import { classifyEvolcoreShellCommand, literalShellParseRemedy, containsLiteralManagedTmpDirOutsideSendContent, containsUnresolvedManagedTmpDirReference, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseLiteralShellArgv, resolveCodexShellCarrierArgv, parseShellApplyPatchInvocation, resolveCanonicalEvolcoreToolInput, serializeCanonicalEvolcoreExecutionSpec, } from '../core/permission/ec-command-parser.js';
25
27
  import { compareVersions } from '../utils/npm-ops.js';
26
28
  import { agentCodexTokenPath, getPackageRoot, resolvePaths, resolveRoot } from '../paths.js';
27
29
  import { MAIN_CLI_BIN } from '../product.js';
@@ -123,6 +125,8 @@ function fallbackErrorCodeForToolDenial(decisionSource, policyCode) {
123
125
  return 'POLICY_DENIED';
124
126
  if (decisionSource === 'approval')
125
127
  return 'USER_DENIED';
128
+ if (policyCode === 'approval_expired' || policyCode === 'approval_timeout')
129
+ return 'APPROVAL_TIMEOUT';
126
130
  if (policyCode && /delegation|carrier/i.test(policyCode))
127
131
  return 'DELEGATION_FAILED';
128
132
  if (policyCode && /argument|canonical|quote|shell/i.test(policyCode))
@@ -2138,35 +2142,41 @@ export class CodexRunner {
2138
2142
  const persistentRuntimeEnv = runtimeEnv
2139
2143
  ? Object.fromEntries(Object.entries(runtimeEnv).filter(([name]) => callMode === 'fullaccess' || name.toUpperCase() !== AGENT_DELEGATION_TOKEN_ENV))
2140
2144
  : undefined;
2141
- let threadOptions = {
2145
+ let innerSandboxFallback = false;
2146
+ const canFallbackFromInnerSandbox = process.platform === 'linux'
2147
+ && executionSandbox.decision.state === 'active';
2148
+ const buildThreadOptions = (fallback = false) => ({
2142
2149
  model: callModel,
2143
2150
  effort: callEffort,
2144
2151
  approvalPolicy: effectiveApprovalPolicy,
2145
2152
  approvalsReviewer: 'user',
2146
- ...(executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
2147
- config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, persistentRuntimeEnv ? { shell_environment_policy: { set: persistentRuntimeEnv } } : undefined, capabilityConfig, userInputConfig, externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionId, threadSessionToken, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined), this.buildLifecycleLockdownConfig(callMode)), callMode, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined),
2153
+ ...(fallback
2154
+ ? { sandbox: 'danger-full-access' }
2155
+ : executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
2156
+ config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(fallback ? undefined : executionSandbox.permissionProfileConfig, persistentRuntimeEnv ? { shell_environment_policy: { set: persistentRuntimeEnv } } : undefined, capabilityConfig, userInputConfig, externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionId, threadSessionToken, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined), this.buildLifecycleLockdownConfig(callMode)), callMode, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined),
2148
2157
  ...(developerInstructions ? { developerInstructions } : {}),
2149
- };
2158
+ });
2159
+ let threadOptions = buildThreadOptions();
2150
2160
  logger.info(`[CodexRunner] runQuery permMode=${requestedPermissionMode}->${callMode} ` +
2151
2161
  `role=${executionSandbox.decision.role ?? 'none'} sandbox=${executionSandbox.decision.state}`);
2152
2162
  let threadResponse;
2153
2163
  let previousAppServer;
2154
- if (agentSessionId) {
2155
- // A thread may have been loaded by the other permission-mode client.
2156
- // Release that one thread before asking this client to resume it.
2157
- previousAppServer = await this.prepareThreadSubscription(appServer, agentSessionId);
2158
- try {
2159
- threadResponse = await this.resumeThreadAllowingWriterRelease(appServer, agentSessionId, projectPath, threadOptions, previousAppServer);
2160
- }
2161
- catch (error) {
2162
- if (isCodexActiveWriterError(error) && previousAppServer && previousAppServer !== appServer) {
2163
- // Some Codex builds acknowledge unsubscribe before unloading the
2164
- // runtime. Archive/unarchive is a synchronous per-thread teardown
2165
- // and preserves the same persisted thread id for the retry.
2166
- await this.archiveThreadForHandoff(previousAppServer, appServer, agentSessionId);
2167
- threadResponse = await appServer.threadResume(agentSessionId, projectPath, threadOptions);
2164
+ const openThread = async () => {
2165
+ if (agentSessionId) {
2166
+ // A thread may have been loaded by the other permission-mode client.
2167
+ // Release that one thread before asking this client to resume it.
2168
+ previousAppServer = await this.prepareThreadSubscription(appServer, agentSessionId);
2169
+ try {
2170
+ return await this.resumeThreadAllowingWriterRelease(appServer, agentSessionId, projectPath, threadOptions, previousAppServer);
2168
2171
  }
2169
- else {
2172
+ catch (error) {
2173
+ if (isCodexActiveWriterError(error) && previousAppServer && previousAppServer !== appServer) {
2174
+ // Some Codex builds acknowledge unsubscribe before unloading the
2175
+ // runtime. Archive/unarchive is a synchronous per-thread teardown
2176
+ // and preserves the same persisted thread id for the retry.
2177
+ await this.archiveThreadForHandoff(previousAppServer, appServer, agentSessionId);
2178
+ return appServer.threadResume(agentSessionId, projectPath, threadOptions);
2179
+ }
2170
2180
  // A legacy main session can retain a provider ID after its rollout was
2171
2181
  // removed externally. It is safe to recover before input submission;
2172
2182
  // topic bindings remain authoritative and fail closed.
@@ -2198,17 +2208,64 @@ export class CodexRunner {
2198
2208
  agentSessionId = undefined;
2199
2209
  resumingThread = false;
2200
2210
  threadSessionToken = this.createThreadCredential();
2201
- threadOptions = {
2202
- ...threadOptions,
2203
- config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, persistentRuntimeEnv ? { shell_environment_policy: { set: persistentRuntimeEnv } } : undefined, capabilityConfig, userInputConfig, externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionId, threadSessionToken, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined), this.buildLifecycleLockdownConfig(callMode)), callMode, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined),
2204
- };
2211
+ threadOptions = buildThreadOptions(innerSandboxFallback);
2205
2212
  logger.warn(`[CodexRunner] recovered missing rollout before input submission: session=${sessionId} thread=${missingThreadId}`);
2206
- threadResponse = await appServer.threadStart(projectPath, threadOptions);
2213
+ return appServer.threadStart(projectPath, threadOptions);
2207
2214
  }
2208
2215
  }
2216
+ return appServer.threadStart(projectPath, threadOptions);
2217
+ };
2218
+ try {
2219
+ threadResponse = await openThread();
2209
2220
  }
2210
- else {
2211
- threadResponse = await appServer.threadStart(projectPath, threadOptions);
2221
+ catch (error) {
2222
+ if (!canFallbackFromInnerSandbox || !isNestedSandboxInitializationFailure(error))
2223
+ throw error;
2224
+ innerSandboxFallback = true;
2225
+ const circuit = recordSandboxInitializationFailure(error, [], Date.now(), sessionId);
2226
+ const context = this.permissionContexts.get(sessionId);
2227
+ const fallbackRequestId = modelOverride?.turn?.inputId ?? `codex-sandbox-fallback-${Date.now()}`;
2228
+ const detail = error instanceof Error ? error.message : String(error);
2229
+ auditToolInfrastructureFailure({
2230
+ toolName: 'Bash',
2231
+ policyCode: SANDBOX_INITIALIZATION_FAILED,
2232
+ reason: detail.slice(0, 512),
2233
+ sessionId,
2234
+ agentAid: context?.selfAid,
2235
+ agentName: context?.agentName,
2236
+ permissionMode: callMode,
2237
+ role: context?.role,
2238
+ callId: fallbackRequestId,
2239
+ taskId: context?.taskId,
2240
+ occurrences: circuit.occurrences,
2241
+ fallback: true,
2242
+ sandboxFailure: {
2243
+ kind: circuit.kind,
2244
+ observation: 'fallback',
2245
+ counters: getSandboxInitializationFailureCounters(),
2246
+ },
2247
+ });
2248
+ await context?.recordExecutionAnomaly?.({
2249
+ code: 'capability_unavailable',
2250
+ severity: 'warning',
2251
+ phase: 'execution',
2252
+ occurredAt: Date.now(),
2253
+ correlationId: fallbackRequestId,
2254
+ requestId: fallbackRequestId,
2255
+ sessionId,
2256
+ toolName: 'Bash',
2257
+ policyCode: SANDBOX_INITIALIZATION_FAILED,
2258
+ decisionSource: 'infrastructure',
2259
+ agentAid: context?.selfAid,
2260
+ agentName: context?.agentName,
2261
+ permissionMode: callMode,
2262
+ summary: `Codex inner sandbox unavailable; retrying with outer EvolCore guard: ${detail}`.slice(0, 512),
2263
+ effect: 'fallback_used',
2264
+ });
2265
+ logger.warn(`[CodexSandbox] inner sandbox initialization failed; retrying with outer H-class guard ` +
2266
+ `session=${sessionId} occurrences=${circuit.occurrences}: ${detail}`);
2267
+ threadOptions = buildThreadOptions(true);
2268
+ threadResponse = await openThread();
2212
2269
  }
2213
2270
  let threadId = threadResponse.thread?.id || agentSessionId;
2214
2271
  if (!threadId)
@@ -2401,7 +2458,9 @@ export class CodexRunner {
2401
2458
  model: callModel,
2402
2459
  effort: callEffort,
2403
2460
  approvalPolicy: effectiveApprovalPolicy,
2404
- ...(executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
2461
+ ...(innerSandboxFallback
2462
+ ? { sandbox: 'danger-full-access' }
2463
+ : executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
2405
2464
  });
2406
2465
  if (!resumingThread) {
2407
2466
  let confirmationInFlight;
@@ -3714,9 +3773,7 @@ export class CodexRunner {
3714
3773
  }
3715
3774
  return await denyInfrastructure('ec_command_not_canonical', canonicalEcApproval?.parseFailure
3716
3775
  ? `EC command approval denied because canonical argv parsing failed (${canonicalEcApproval.parseFailure.issue})`
3717
- + (canonicalEcApproval.parseFailure.dialect === 'powershell' && canonicalEcApproval.parseFailure.issue === 'invalid-quote'
3718
- ? '. PowerShell treats U+2018/U+2019/U+201A/U+201B as quote delimiters too. An EC inline text argument must be ASCII single-quoted; replace any character inside it that looks like a quote with U+02BC or U+FF07, or write the text to the session TMPDIR and pass it with --text-from-file.'
3719
- : '')
3776
+ + `。${literalShellParseRemedy(canonicalEcApproval.parseFailure) ?? ''}`
3720
3777
  : 'EC command approval denied because no canonical argv could be derived', canonicalEcApproval?.parseFailure?.issue === 'invalid-quote' ? 'INVALID_QUOTE' : undefined);
3721
3778
  }
3722
3779
  try {
@@ -3751,25 +3808,31 @@ export class CodexRunner {
3751
3808
  }
3752
3809
  const response = this.toAppServerApprovalResponse(request.method, decision, toolInput, unattended);
3753
3810
  const decisionSource = resolutionMeta?.decisionSource
3754
- ?? (sessionMode === 'auto' || sessionMode === 'readonly' ? 'policy' : 'approval');
3811
+ ?? (sessionMode === 'auto' || sessionMode === 'readonly' ? 'policy' : 'infrastructure');
3755
3812
  const policyCode = resolutionMeta?.policyCode
3756
- ?? (decisionSource === 'policy' ? 'permission_mode_denied' : undefined);
3757
- const denialReason = resolutionMeta?.reason || reason || (policyCode
3813
+ ?? (decisionSource === 'policy' ? 'permission_mode_denied' : decision === 'deny' ? 'approval_failure_unknown' : undefined);
3814
+ const errorDetailCode = resolutionMeta?.errorDetailCode
3815
+ ?? (decision === 'deny' && policyCode === 'approval_failure_unknown' ? 'APPROVAL_FAILURE_UNKNOWN' : undefined);
3816
+ const denialReason = resolutionMeta?.reason || (decisionSource === 'policy'
3758
3817
  ? `permission mode ${sessionMode} denied approval`
3759
- : 'user approval denied');
3818
+ : '审批失败,具体原因未知;操作未执行。');
3760
3819
  if (decision === 'deny') {
3761
3820
  this.rememberToolDenial(request, params, {
3762
3821
  decision: 'deny',
3763
3822
  decisionSource,
3764
3823
  ...(policyCode ? { policyCode } : {}),
3765
- ...(resolutionMeta?.errorDetailCode ? { errorDetailCode: resolutionMeta.errorDetailCode } : {}),
3824
+ ...(errorDetailCode ? { errorDetailCode } : {}),
3825
+ approvalRequestId: resolutionMeta?.requestId,
3826
+ approverOperatorId: resolutionMeta?.approverOperatorId,
3827
+ approverChannelKey: resolutionMeta?.approverChannelKey,
3828
+ approverPrincipalId: resolutionMeta?.approverPrincipalId,
3766
3829
  reason: denialReason,
3767
3830
  });
3768
3831
  setImmediate(() => this.steerPolicyReason(sessionKey, policyCode, denialReason));
3769
3832
  }
3770
3833
  this.logAppServerApprovalAudit(request, sessionKey, toolName, decision === 'deny' ? 'deny' : 'allow', decision === 'deny' ? decisionSource : 'approval', decision === 'deny' ? policyCode : undefined, decision === 'deny'
3771
3834
  ? denialReason
3772
- : 'approval accepted');
3835
+ : 'approval accepted', undefined, { ...resolutionMeta, errorDetailCode });
3773
3836
  logger.info(`[CodexRunner] app-server approval response id=${request.id} method=${request.method} decision=${decision} response=${JSON.stringify(response)}`);
3774
3837
  return response;
3775
3838
  }
@@ -3779,7 +3842,14 @@ export class CodexRunner {
3779
3842
  throw error;
3780
3843
  }
3781
3844
  }
3782
- logAppServerApprovalAudit(request, sessionKey, toolName, decision, decisionSource, policyCode, reason, parseFailure) {
3845
+ logAppServerApprovalAudit(request, sessionKey, toolName, decision, decisionSource, policyCode, reason, parseFailure, resolution) {
3846
+ const approvalMetadata = {
3847
+ approvalRequestId: resolution?.requestId,
3848
+ errorDetailCode: resolution?.errorDetailCode,
3849
+ approverOperatorId: resolution?.approverOperatorId,
3850
+ approverChannelKey: resolution?.approverChannelKey,
3851
+ approverPrincipalId: resolution?.approverPrincipalId,
3852
+ };
3783
3853
  const context = this.permissionContexts.get(sessionKey);
3784
3854
  const params = (request.params || {});
3785
3855
  const rawCallId = params.itemId ?? params.item_id ?? params.callId ?? params.call_id;
@@ -3795,6 +3865,7 @@ export class CodexRunner {
3795
3865
  ? params.cwd
3796
3866
  : undefined;
3797
3867
  auditCodexApprovalDecision({
3868
+ ...approvalMetadata,
3798
3869
  requestId: request.id !== undefined ? String(request.id) : undefined,
3799
3870
  callId,
3800
3871
  correlationId: callId,
@@ -3823,6 +3894,7 @@ export class CodexRunner {
3823
3894
  ?? `codex-approval-${crypto.randomUUID()}`;
3824
3895
  auditPermissionLifecycle({
3825
3896
  phase: 'response',
3897
+ ...approvalMetadata,
3826
3898
  requestId: lifecycleRequestId,
3827
3899
  callId,
3828
3900
  correlationId: callId,
@@ -3842,6 +3914,7 @@ export class CodexRunner {
3842
3914
  });
3843
3915
  auditPermissionLifecycle({
3844
3916
  phase: 'final',
3917
+ ...approvalMetadata,
3845
3918
  requestId: lifecycleRequestId,
3846
3919
  callId,
3847
3920
  correlationId: callId,
@@ -3860,6 +3933,7 @@ export class CodexRunner {
3860
3933
  approvalMethod: request.method,
3861
3934
  });
3862
3935
  logger.info(`[CodexRunner] app-server approval audit ${JSON.stringify({
3936
+ ...approvalMetadata,
3863
3937
  requestId: request.id !== undefined ? String(request.id) : undefined,
3864
3938
  ...(callId ? { callId, correlationId: callId } : {}),
3865
3939
  method: request.method,
@@ -4428,11 +4502,12 @@ export class CodexRunner {
4428
4502
  }
4429
4503
  async resolvePermissionDecision(sessionKey, toolName, toolInput, summary, reason, workspacePath = process.cwd(), operationCwd = workspacePath, requestId, callId) {
4430
4504
  const permissionContext = this.permissionContexts.get(sessionKey);
4505
+ const resolutionRequestId = requestId !== undefined ? String(requestId) : `codex-approval-${crypto.randomUUID()}`;
4431
4506
  try {
4432
4507
  await assertOwnershipAuthorization(permissionContext);
4433
4508
  }
4434
4509
  catch {
4435
- return 'deny';
4510
+ return permissionFailureResult(resolutionRequestId, 'ownership_authorization_failed');
4436
4511
  }
4437
4512
  // 系统会话:审批路径同样只看模块判定(FileChange / PermissionGrant 一律被模块拒绝)
4438
4513
  if (permissionContext?.systemSessionCheck) {
@@ -4464,7 +4539,7 @@ export class CodexRunner {
4464
4539
  const mode = normalizeExecutionPermissionMode(rawMode);
4465
4540
  if (rawMode === 'fullaccess') {
4466
4541
  if (!this.isTrustedFullAccessSession(sessionKey)) {
4467
- return 'deny';
4542
+ return { decision: 'deny', decisionSource: 'policy', policyCode: 'fullaccess_untrusted', reason: '当前会话未通过完整访问授权校验。' };
4468
4543
  }
4469
4544
  return 'allow';
4470
4545
  }
@@ -4509,6 +4584,7 @@ export class CodexRunner {
4509
4584
  catch (error) {
4510
4585
  logger.warn(`[CodexRunner] failed to record blocked operation: session=${sessionKey} tool=${toolName} code=${policyCode} error=${error instanceof Error ? error.message : String(error)}`);
4511
4586
  }
4587
+ return { decision: 'deny', decisionSource: 'policy', requestId: resolutionRequestId, policyCode, reason: denialReason };
4512
4588
  };
4513
4589
  const preflight = evaluateToolPreflight(toolName, toolInput, {
4514
4590
  sessionId: sessionKey,
@@ -4554,23 +4630,31 @@ export class CodexRunner {
4554
4630
  const hasConcreteChanges = this.normalizeFileChanges(checkedInput.fileChanges)
4555
4631
  .some(change => typeof change?.path === 'string' && change.path.length > 0);
4556
4632
  if (!hasGrantRoot && !hasConcreteChanges)
4557
- return 'deny';
4633
+ return {
4634
+ decision: 'deny', decisionSource: 'infrastructure', policyCode: 'approval_file_changes_missing',
4635
+ errorDetailCode: 'FILE_CHANGE_INPUT_MISSING', reason: '无法审批文件编辑:审批请求缺少目标文件信息;操作未执行。',
4636
+ };
4558
4637
  }
4559
4638
  if (toolName === 'Bash' && !hasPermissionExpansion) {
4560
4639
  const command = typeof checkedInput.command === 'string'
4561
4640
  ? checkedInput.command.trim()
4562
4641
  : '';
4563
4642
  if (!command)
4564
- return 'deny';
4643
+ return {
4644
+ decision: 'deny', decisionSource: 'infrastructure', policyCode: 'approval_command_missing',
4645
+ errorDetailCode: 'COMMAND_INPUT_MISSING', reason: '无法审批命令:审批请求缺少命令信息;操作未执行。',
4646
+ };
4565
4647
  }
4566
4648
  if (toolName === 'PermissionGrant' && !hasPermissionExpansion)
4567
- return 'deny';
4649
+ return {
4650
+ decision: 'deny', decisionSource: 'infrastructure', policyCode: 'approval_permissions_missing',
4651
+ errorDetailCode: 'PERMISSION_INPUT_MISSING', reason: '无法审批权限申请:请求缺少可识别的权限范围;操作未执行。',
4652
+ };
4568
4653
  const grantScope = `codex:${this.permissionProfileName(sessionKey)}:${mode}`;
4569
4654
  if (mode === 'readonly') {
4570
4655
  const readonly = this.checkCodexReadonly(policyToolName, policyInput, operationCwd, sessionKey);
4571
4656
  if (readonly.behavior === 'deny') {
4572
- await recordBlockedOperation(readonly.policyCode ?? 'readonly_mode', policyInput, readonly.message);
4573
- return 'deny';
4657
+ return recordBlockedOperation(readonly.policyCode ?? 'readonly_mode', policyInput, readonly.message);
4574
4658
  }
4575
4659
  return 'allow';
4576
4660
  }
@@ -4580,49 +4664,36 @@ export class CodexRunner {
4580
4664
  // auto 模式下检查危险命令,危险命令自动拒绝
4581
4665
  if (mode === 'auto') {
4582
4666
  if (hasFileChangeExpansion || hasFilesystemPermissions || hasUnknownPermissions) {
4583
- await recordBlockedOperation('auto_permission_expansion', policyInput);
4584
- return 'deny';
4667
+ return recordBlockedOperation('auto_permission_expansion', policyInput, 'auto 权限模式不允许扩大文件系统权限;操作未执行。');
4585
4668
  }
4586
4669
  if (toolName === 'PermissionGrant' && !hasNetworkPermissions) {
4587
- await recordBlockedOperation('auto_permission_expansion', checkedInput);
4588
- return 'deny';
4670
+ return recordBlockedOperation('auto_permission_expansion', checkedInput, 'auto 权限模式不允许此权限扩展;操作未执行。');
4589
4671
  }
4590
4672
  const dangerous = checkDangerousCommand(toolName, checkedInput);
4591
4673
  if (dangerous.isDangerous) {
4592
- await recordBlockedOperation('auto_dangerous_command', checkedInput);
4593
- return 'deny';
4674
+ return recordBlockedOperation('auto_dangerous_command', checkedInput, 'auto 权限模式不允许执行此危险操作;操作未执行。');
4594
4675
  }
4595
4676
  return 'allow';
4596
4677
  }
4597
4678
  const requiresSandboxExpansionApproval = hasFileChangeExpansion
4598
4679
  || hasFilesystemPermissions
4599
4680
  || hasUnknownPermissions;
4600
- const resolveRuntimeApproval = (decision) => {
4601
- if (decision === 'deny' && permissionContext?.approvalInteractionPolicy === 'deny') {
4602
- return {
4603
- decision: 'deny',
4604
- decisionSource: 'policy',
4605
- policyCode: 'permission_mode_denied',
4606
- reason: 'permission mode denied runtime approval',
4607
- };
4608
- }
4609
- return decision;
4610
- };
4611
4681
  if (requiresSandboxExpansionApproval) {
4682
+ if (permissionContext?.approvalInteractionPolicy === 'deny') {
4683
+ return permissionFailureResult(resolutionRequestId, 'permission_mode_denied', {}, 'permission_mode_denied');
4684
+ }
4612
4685
  if (!this.permissionGateway || !permissionPrompt) {
4613
- return permissionContext?.approvalInteractionPolicy === 'deny'
4614
- ? resolveRuntimeApproval('deny')
4615
- : 'deny';
4686
+ return permissionFailureResult(resolutionRequestId, !this.permissionGateway ? 'approval_gateway_unavailable' : 'approval_prompt_unavailable', {}, 'approval_channel_unavailable');
4616
4687
  }
4617
4688
  if (policyToolName === 'FileChange') {
4618
- return resolveRuntimeApproval(await this.permissionGateway.requestPermission(sessionKey, policyToolName, policyInput, permissionPrompt, this.permissionContexts.get(sessionKey), summary, reason || 'Codex 请求扩大当前命令或 turn 的文件系统权限', grantScope, undefined, { fileChangeCwd: workspacePath }));
4689
+ return this.permissionGateway.requestPermissionResult(sessionKey, policyToolName, policyInput, permissionPrompt, { ...permissionContext, permissionMode: mode }, summary, reason || 'Codex 请求扩大当前命令或 turn 的文件系统权限', grantScope, undefined, { fileChangeCwd: workspacePath });
4619
4690
  }
4620
- return resolveRuntimeApproval(await this.permissionGateway.requestPermission(sessionKey, toolName, checkedInput, permissionPrompt, this.permissionContexts.get(sessionKey), summary, reason || 'Codex 请求扩大当前命令或 turn 的文件系统权限', grantScope, undefined, toolName === 'PermissionGrant' ? { filesystemCwd: operationCwd, workspacePath } : undefined));
4691
+ return this.permissionGateway.requestPermissionResult(sessionKey, toolName, checkedInput, permissionPrompt, { ...permissionContext, permissionMode: mode }, summary, reason || 'Codex 请求扩大当前命令或 turn 的文件系统权限', grantScope, undefined, toolName === 'PermissionGrant' ? { filesystemCwd: operationCwd, workspacePath } : undefined);
4621
4692
  }
4622
4693
  if (mode === 'request' || mode === 'bypass') {
4623
- const dangerous = await requestDangerousCommandPermission(this.permissionGateway, sessionKey, toolName, checkedInput, permissionPrompt, this.permissionContexts.get(sessionKey), grantScope, mode);
4694
+ const dangerous = await requestDangerousCommandPermissionResult(this.permissionGateway, sessionKey, toolName, checkedInput, permissionPrompt, this.permissionContexts.get(sessionKey), grantScope, mode);
4624
4695
  if (dangerous.matched)
4625
- return resolveRuntimeApproval(dangerous.decision);
4696
+ return dangerous.result;
4626
4697
  return 'allow';
4627
4698
  }
4628
4699
  // Network is already part of every profile, so a defensive
@@ -5542,6 +5613,10 @@ export class CodexRunner {
5542
5613
  policyCode: denial.policyCode,
5543
5614
  reason: denial.reason,
5544
5615
  requestId: denial.requestId,
5616
+ approvalRequestId: denial.approvalRequestId,
5617
+ approverOperatorId: denial.approverOperatorId,
5618
+ approverChannelKey: denial.approverChannelKey,
5619
+ approverPrincipalId: denial.approverPrincipalId,
5545
5620
  executed: false,
5546
5621
  executionState: 'blocked',
5547
5622
  }
@@ -805,7 +805,7 @@ export class EcagentRunner {
805
805
  const providerId = providerOverride ?? this.config.providerId;
806
806
  if (!providerId)
807
807
  return this.config;
808
- const provider = resolveProviderServiceForBaseagent(providerId, 'ecagent', this.config.providerServiceType);
808
+ const provider = resolveProviderServiceForBaseagent(providerId, 'ecagent');
809
809
  if (provider.style !== 'openai-compatible') {
810
810
  throw new Error(`Provider ${providerId} uses unsupported ecagent style: ${provider.style}`);
811
811
  }
@@ -369,7 +369,7 @@ export class GeminiRunner {
369
369
  }
370
370
  currentProviderConfig(providerOverride) {
371
371
  const config = this.agentAid
372
- ? { agents: { gemini: resolveEffective({ self: this.agentAid }, { cache: true, expand: false }).baseagents?.gemini ?? this.config.agents?.gemini } }
372
+ ? { agents: { gemini: resolveEffective({ self: this.agentAid }, { cache: true }).baseagents?.gemini ?? this.config.agents?.gemini } }
373
373
  : this.config;
374
374
  return resolveGoogleConfig(config, providerOverride ? { provider: providerOverride } : undefined);
375
375
  }
@@ -2,19 +2,21 @@ import crypto from 'crypto';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { parseDocument } from 'yaml';
5
+ import { validateAgentMdDocument } from '@agentunion/fastaun';
5
6
  import { getAidStore, loadAid, SLOT } from './store.js';
6
7
  import { agentMdPath, aidLocalDir, resolveRoot } from '../../paths.js';
7
8
  export const DEFAULT_AGENT_DESCRIPTION = 'EvolCore AI agent.';
8
9
  /**
9
- * AUN 主体类型白名单。没有 `ai` / `codeagent` 这类取值:使用大模型且没有
10
- * 专用主体类型的服务程序默认归为 `agent`。新建 AID 未指定类型时使用 DEFAULT_AGENT_TYPE。
10
+ * AUN 主体类型已知预设值列表。`type` 是可扩展字符串,协议允许应用自定义值;
11
+ * 此列表用于 CLI 创建/set 时的归一化,未知类型原样透传(协议层不拦截)。
12
+ * 新建 AID 未指定类型时使用 DEFAULT_AGENT_TYPE。
11
13
  */
12
- export const AGENT_TYPES = ['human', 'agent', 'group', 'service', 'device', 'org', 'host'];
14
+ export const AGENT_TYPES = ['human', 'agent', 'group', 'service', 'device', 'org', 'host', 'custom'];
13
15
  export const DEFAULT_AGENT_TYPE = 'agent';
14
16
  /**
15
- * 归一化主体类型:大小写不敏感,统一收敛为白名单里的小写形式。
16
- * `--type AGENT` / `Agent` 都接受,最终写进 agent.md 的一律是小写 `agent`。
17
- * 返回 undefined 表示输入不是可识别的类型(交由 validateAgentType 报错)。
17
+ * 归一化主体类型:大小写不敏感,对已知预设值统一收敛为小写形式。
18
+ * `--type AGENT` / `Agent` 都接受,最终写进 agent.md 的预设值一律是小写。
19
+ * 未知的扩展类型返回 undefined——由调用方决定是否透传或报错。
18
20
  */
19
21
  export function normalizeAgentType(type) {
20
22
  if (typeof type !== 'string')
@@ -26,8 +28,6 @@ export function normalizeAgentType(type) {
26
28
  export function validateAgentType(type) {
27
29
  if (typeof type !== 'string' || !type.trim())
28
30
  return 'must be a non-empty string';
29
- if (!normalizeAgentType(type))
30
- return `must be one of ${AGENT_TYPES.join(', ')}`;
31
31
  return null;
32
32
  }
33
33
  /**
@@ -42,8 +42,6 @@ export const AGENT_AVATAR_MAX_LENGTH = 256;
42
42
  function codePointLength(value) {
43
43
  return Array.from(value).length;
44
44
  }
45
- export const AGENT_TAG_MIN_COUNT = 3;
46
- export const AGENT_TAG_MAX_COUNT = 6;
47
45
  export const AGENT_TAG_MAX_LENGTH = 50;
48
46
  const AGENT_TAG_PATTERN = /^[\p{L}\p{N}-]+$/u;
49
47
  /** Return a human-readable validation error for one tag, or null when valid. */
@@ -500,7 +498,7 @@ export function updateAgentMdFrontmatterFieldValue(content, field, value) {
500
498
  const error = validateAgentType(normalized);
501
499
  if (error)
502
500
  throw new Error(`agent.md type ${error}`);
503
- return updateAgentMdFrontmatterField(content, field, normalizeAgentType(normalized), 'aid');
501
+ return updateAgentMdFrontmatterField(content, field, normalizeAgentType(normalized) ?? normalized, 'aid');
504
502
  }
505
503
  if (field === 'version' && !/^\d+\.\d+\.\d+$/.test(normalized)) {
506
504
  throw new Error('agent.md version must use major.minor.patch format');
@@ -615,6 +613,37 @@ export async function agentmdGet(aid, opts) {
615
613
  catch { /* ignore */ }
616
614
  }
617
615
  }
616
+ /** Check an existing identity before Agent creation can overwrite its signed card. */
617
+ export async function assertAgentIdentityReusable(aid, opts = {}) {
618
+ let card;
619
+ try {
620
+ card = await agentmdGet(aid, { ...opts, withVerification: true, remoteOnly: true });
621
+ }
622
+ catch (error) {
623
+ if (error.code === 'AGENTMD_NOT_FOUND')
624
+ return;
625
+ throw error;
626
+ }
627
+ assertAgentCardReusable(aid, card);
628
+ }
629
+ /** The caller supplies a card whose verification came from the SDK, never raw YAML alone. */
630
+ export function assertAgentCardReusable(aid, card) {
631
+ if (card.verification.status !== 'verified') {
632
+ throw Object.assign(new Error(`Cannot verify the existing identity for ${aid}`), { code: 'AGENT_IDENTITY_UNVERIFIED' });
633
+ }
634
+ const frontmatter = card.content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
635
+ const document = parseDocument(frontmatter ?? '');
636
+ const fields = document.toJS();
637
+ if (document.errors.length > 0 || !fields || typeof fields !== 'object' || Array.isArray(fields)
638
+ || typeof fields.aid !== 'string' || fields.aid.toLowerCase() !== aid.toLowerCase()) {
639
+ throw Object.assign(new Error(`Invalid existing identity for ${aid}`), { code: 'AGENT_IDENTITY_UNVERIFIED' });
640
+ }
641
+ if (typeof fields.type === 'string' && fields.type.trim().toLowerCase() === 'host') {
642
+ throw Object.assign(new Error(`AID "${aid}" belongs to a host and cannot be reused as an Agent`), {
643
+ code: 'HOST_AID_RESERVED',
644
+ });
645
+ }
646
+ }
618
647
  /**
619
648
  * Validate and upload agent.md. The SDK signs the payload and persists its
620
649
  * signed local cache only after the remote upload succeeds.
@@ -687,6 +716,64 @@ export async function agentmdPut(content, opts) {
687
716
  const lockKey = `${path.resolve(aunPath)}\u0000${opts.aid.toLowerCase()}`;
688
717
  return withAgentMdWriteLock(lockKey, () => publishAgentMd(content, opts));
689
718
  }
719
+ /**
720
+ * Apply the creation form's profile to the card produced by the SDK's initial
721
+ * Owner binding. Ownership declarations are SDK output: never reconstruct them
722
+ * from the form or replace the owned card with an unowned initial template.
723
+ */
724
+ export async function agentmdPutInitializationProfile(content, opts) {
725
+ const validation = validateAgentMdFrontmatter(content, opts.aid);
726
+ if (!validation.valid) {
727
+ throw new Error(`invalid agent.md frontmatter: ${validation.errors.join('; ')}`);
728
+ }
729
+ const profileFrontmatter = stripAgentMdSignature(content).match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)[1];
730
+ const profile = parseDocument(profileFrontmatter).toJS();
731
+ const aunPath = resolveAgentMdAunPath(opts);
732
+ const lockKey = `${path.resolve(aunPath)}\u0000${opts.aid.toLowerCase()}`;
733
+ return withAgentMdWriteLock(lockKey, async () => {
734
+ const store = opts.store ?? await getAidStore({ slotId: SLOT.cli, aunPath });
735
+ const ownStore = !opts.store;
736
+ try {
737
+ const current = await agentmdGet(opts.aid, { store, aunPath, withVerification: true, remoteOnly: true });
738
+ if (current.source !== 'remote' || current.verification.status !== 'verified') {
739
+ throw Object.assign(new Error('Initial owned agent.md must be verified remotely'), { code: 'INITIALIZE_REMOTE_UNVERIFIED' });
740
+ }
741
+ const payload = stripAgentMdSignature(current.content);
742
+ // Use the SDK's upload schema as well as signature verification. Download
743
+ // compatibility alone also accepts historical cards without Ownership 2.1.
744
+ const { frontmatter } = validateAgentMdDocument(payload, { expectedAid: opts.aid, forUpload: true });
745
+ const ownership = frontmatter.ownership;
746
+ const statement = ownership?.statement;
747
+ if (frontmatter.owner !== opts.ownerAid || statement?.owner_aid !== opts.ownerAid
748
+ || statement.sub_aid !== opts.aid || statement.relation_version !== 1) {
749
+ throw Object.assign(new Error('Initial agent.md ownership no longer matches the creation'), { code: 'INITIALIZE_OWNER_CONFLICT' });
750
+ }
751
+ const version = current.remoteVersion;
752
+ if (!version?.etag && !version?.lastModified) {
753
+ throw new AgentMdVersionUnavailableError('初始归属名片缺少远端版本,已拒绝覆盖发布');
754
+ }
755
+ if (opts.expectedRemoteVersion && !remoteVersionsEqual(opts.expectedRemoteVersion, version)) {
756
+ throw new AgentMdVersionConflictError(opts.expectedRemoteVersion, version);
757
+ }
758
+ const match = payload.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
759
+ const document = parseDocument(match[1]);
760
+ for (const field of ['name', 'type', 'description', 'tags']) {
761
+ if (Object.hasOwn(profile, field))
762
+ document.set(field, profile[field]);
763
+ }
764
+ const updated = `---\n${document.toString({ lineWidth: 0 })}---\n${payload.slice(match[0].length)}`;
765
+ validateAgentMdDocument(updated, { expectedAid: opts.aid, forUpload: true });
766
+ return await publishAgentMd(updated, { ...opts, store, aunPath, expectedRemoteVersion: version });
767
+ }
768
+ finally {
769
+ if (ownStore)
770
+ try {
771
+ store.close();
772
+ }
773
+ catch { /* ignore */ }
774
+ }
775
+ });
776
+ }
690
777
  export async function agentmdSet(aid, field, value, opts = {}) {
691
778
  const aunPath = resolveAgentMdAunPath(opts);
692
779
  const lockKey = `${path.resolve(aunPath)}\u0000${aid.toLowerCase()}`;
@@ -39,7 +39,7 @@ export function suppressSdkLogs() {
39
39
  };
40
40
  }
41
41
  // ==================== SDK package ====================
42
- export const MIN_AUN_CORE_SDK = [0, 5, 26];
42
+ export const MIN_AUN_CORE_SDK = [0, 5, 28];
43
43
  export const AUN_CORE_SDK_PKG = '@agentunion/fastaun';
44
44
  function compareVersion(a, min) {
45
45
  const parts = a.split('.').map(n => parseInt(n, 10));