evolcore 0.0.42 → 0.0.43-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 (189) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/bin/ec-safe-output.js +4 -1
  3. package/dist/ability/application-service.js +882 -0
  4. package/dist/ability/authorization.js +70 -0
  5. package/dist/ability/command-contract.js +105 -0
  6. package/dist/ability/daemon.js +137 -0
  7. package/dist/ability/development.js +450 -0
  8. package/dist/ability/environment.js +75 -0
  9. package/dist/ability/interop-v1.js +547 -0
  10. package/dist/ability/management.js +79 -0
  11. package/dist/ability/package.js +264 -0
  12. package/dist/ability/provider.js +73 -0
  13. package/dist/ability/publication.js +107 -0
  14. package/dist/ability/resources.js +106 -0
  15. package/dist/ability/runtime.js +212 -0
  16. package/dist/ability/secrets.js +47 -0
  17. package/dist/ability/store.js +112 -0
  18. package/dist/ability/toolchain.js +69 -0
  19. package/dist/ability/types.js +14 -0
  20. package/dist/ability/versions.js +32 -0
  21. package/dist/agents/baseagent.js +2 -2
  22. package/dist/agents/claude-runner.js +4 -0
  23. package/dist/agents/codex-runner.js +81 -17
  24. package/dist/agents/ecagent-plugin-lazy.js +41 -0
  25. package/dist/agents/ecagent-runner.js +18 -11
  26. package/dist/aun/ability-device-routing.js +12 -1
  27. package/dist/aun/aid/agentmd.js +2 -2
  28. package/dist/aun/aid/client.js +1 -1
  29. package/dist/aun/aid/identity.js +45 -0
  30. package/dist/aun/aid/index.js +1 -0
  31. package/dist/aun/aid/managed-operation.js +73 -2
  32. package/dist/channels/aun.js +64 -18
  33. package/dist/channels/builtin-plugins.js +14 -0
  34. package/dist/channels/dingtalk.js +78 -26
  35. package/dist/channels/feishu.js +89 -14
  36. package/dist/channels/qqbot.js +84 -19
  37. package/dist/channels/wechat.js +77 -19
  38. package/dist/channels/wecom.js +67 -22
  39. package/dist/cli/ability-command.js +92 -0
  40. package/dist/cli/aun-commands.js +124 -85
  41. package/dist/cli/daemon-commands.js +37 -85
  42. package/dist/cli/index.js +14 -0
  43. package/dist/cli/init.js +11 -13
  44. package/dist/cli/managed-command-guard.js +6 -0
  45. package/dist/cli/model.js +101 -104
  46. package/dist/cli/provider-command.js +6 -4
  47. package/dist/cli/restart-monitor.js +52 -11
  48. package/dist/cli/upgrade-command.js +102 -0
  49. package/dist/cli/version.js +1 -1
  50. package/dist/config/access-policy.js +4 -2
  51. package/dist/config/builtin-roles.js +1 -0
  52. package/dist/config/config-field-policy.js +4 -0
  53. package/dist/config/config-manager.js +7 -0
  54. package/dist/config/provider-ipc-service.js +10 -0
  55. package/dist/config/providers-config.js +12 -3
  56. package/dist/config/providers-management.js +45 -9
  57. package/dist/config/schema-migration.js +40 -22
  58. package/dist/contracts/ecweb-service-protocol.js +2 -1
  59. package/dist/core/agent-runtime.js +2 -1
  60. package/dist/core/auth/agent-delegation.js +21 -5
  61. package/dist/core/auth/auth-gateway.js +31 -9
  62. package/dist/core/auth/authorization-audit.js +52 -4
  63. package/dist/core/auth/delegation-authorization.js +140 -4
  64. package/dist/core/auth/operation-authorizer.js +114 -13
  65. package/dist/core/auth/operation-catalog.js +118 -4
  66. package/dist/core/baseagent-loader.js +14 -1
  67. package/dist/core/channel-loader.js +47 -9
  68. package/dist/core/channel-runtime.js +1 -1
  69. package/dist/core/command/agent-storage-menu.js +1 -1
  70. package/dist/core/command/cli-intent-parser.js +26 -13
  71. package/dist/core/command/command-handler.js +232 -76
  72. package/dist/core/command/connect-menu.js +10 -4
  73. package/dist/core/command/daemon-diagnostics.js +3 -3
  74. package/dist/core/command/data-root-resolver.js +2 -3
  75. package/dist/core/command/menu-catalog.js +10 -3
  76. package/dist/core/command/menu-handler.js +321 -46
  77. package/dist/core/command/menu-protocol.js +53 -7
  78. package/dist/core/command/pa-workspace-calendar.js +1 -2
  79. package/dist/core/command/pa-workspace-items.js +486 -0
  80. package/dist/core/command/pa-workspace-store.js +10 -1
  81. package/dist/core/command/slash-gate.js +2 -2
  82. package/dist/core/command/slash-handler.js +67 -25
  83. package/dist/core/contact-bind-registry.js +27 -0
  84. package/dist/core/daemon-control.js +3 -3
  85. package/dist/core/daemon-lifecycle.js +2 -1
  86. package/dist/core/event-bus.js +9 -2
  87. package/dist/core/handoff/ipc-registration.js +1 -0
  88. package/dist/core/host-snapshot.js +1 -2
  89. package/dist/core/initialization/service.js +32 -11
  90. package/dist/core/ipc-registration.js +18 -5
  91. package/dist/core/memory/consolidation-context.js +2 -2
  92. package/dist/core/message/aun-request-registry.js +99 -18
  93. package/dist/core/message/im-renderer.js +16 -11
  94. package/dist/core/message/message-admission.js +25 -20
  95. package/dist/core/message/message-bridge.js +21 -47
  96. package/dist/core/message/message-queue.js +3 -0
  97. package/dist/core/message/response-engine.js +7 -5
  98. package/dist/core/model/catalog-service.js +1 -1
  99. package/dist/core/permission/ec-command-parser.js +41 -9
  100. package/dist/core/permission/permission-result.js +1 -0
  101. package/dist/core/permission/protected-paths.js +25 -14
  102. package/dist/core/permission/tool-policy.js +108 -107
  103. package/dist/core/plugin-lifecycle.js +133 -0
  104. package/dist/core/runner-reload-transaction.js +4 -1
  105. package/dist/core/system-session/memory.js +16 -3
  106. package/dist/core/task/task-activity-store.js +50 -0
  107. package/dist/core/task/task-image-resources.js +140 -0
  108. package/dist/core/thread/ipc-operation.js +1 -1
  109. package/dist/core/thread/thread-service.js +0 -1
  110. package/dist/directory/canonical-digest.js +5 -3
  111. package/dist/directory/owner-directory-admission.js +22 -2
  112. package/dist/directory/owner-directory-cache.js +394 -60
  113. package/dist/directory/owner-directory-markdown.js +29 -2
  114. package/dist/directory/owner-directory-scope.js +35 -16
  115. package/dist/ecweb/basic-settings-service.js +4 -1
  116. package/dist/ecweb/pairing.js +41 -0
  117. package/dist/ecweb/providers-service.js +8 -1
  118. package/dist/{utils/ecweb-utils.js → ecweb/runtime/launch.js} +3 -27
  119. package/dist/ecweb/runtime/lifecycle.js +184 -0
  120. package/dist/{utils/ecweb-supervisor.js → ecweb/runtime/supervisor.js} +32 -27
  121. package/dist/index.js +34 -25
  122. package/dist/ipc.js +124 -7
  123. package/dist/response-system/engines/v1/proactive-flow.js +1 -1
  124. package/dist/trigger/authorization.js +2 -2
  125. package/dist/utils/atomic-write.js +24 -0
  126. package/dist/utils/avatar-upload.js +3 -1
  127. package/dist/utils/cross-platform.js +31 -2
  128. package/dist/utils/host-info.js +36 -0
  129. package/dist/utils/instance-registry.js +38 -11
  130. package/dist/utils/logger.js +9 -0
  131. package/dist/utils/{process-tree-stats.js → process-tree.js} +29 -0
  132. package/dist/utils/tool-summary.js +9 -1
  133. package/dist/utils/upgrade-jobs.js +96 -15
  134. package/dist/utils/windows-autostart.js +1 -1
  135. package/ecagent/README.md +19 -0
  136. package/ecagent/dist/harness/agent-harness.js +9 -0
  137. package/ecagent/dist/harness/env/nodejs.js +71 -11
  138. package/ecagent/dist/harness/env/windows-shell.d.ts +7 -0
  139. package/ecagent/dist/harness/env/windows-shell.js +132 -0
  140. package/kits/docs/aun/ABILITY_CALLING.md +38 -9
  141. package/kits/docs/evolcore/INDEX.md +5 -1
  142. package/kits/docs/evolcore/ability.md +181 -0
  143. package/kits/docs/evolcore/aid.md +20 -0
  144. package/kits/docs/evolcore/config.md +10 -6
  145. package/kits/docs/evolcore/menu-protocol.md +40 -1
  146. package/kits/docs/evolcore/provider.md +2 -2
  147. package/kits/docs/evolcore/tool-authorization.md +270 -0
  148. package/kits/runtime/ability-job.ps1 +41 -0
  149. package/kits/runtime/ability-runner.mjs +67 -0
  150. package/kits/runtime/ability-secret.ps1 +59 -0
  151. package/kits/runtime/ability-templates/go/main.go +59 -0
  152. package/kits/runtime/ability-templates/java/Json.java +67 -0
  153. package/kits/runtime/ability-templates/java/Runner.java +42 -0
  154. package/kits/runtime/ability-templates/python/runner.py +48 -0
  155. package/kits/runtime/ability-templates/rust/json.rs +87 -0
  156. package/kits/runtime/ability-templates/rust/runner.rs +35 -0
  157. package/kits/schemas/_meta.json +12 -1
  158. package/kits/schemas/ability-plugin.schema.1.json +107 -0
  159. package/kits/schemas/ability-project.schema.1.json +31 -0
  160. package/kits/schemas/agent-config.schema.16.json +20 -0
  161. package/kits/schemas/agent-config.schema.17.json +20 -0
  162. package/kits/schemas/agent-config.schema.18.json +917 -0
  163. package/kits/skills/.switches.json +4 -0
  164. package/kits/skills/aid-ability/SKILL.md +5 -4
  165. package/kits/skills/ec-ability/SKILL.md +67 -0
  166. package/kits/skills/ec-ability/references/contract-checklist.md +37 -0
  167. package/kits/skills/ec-ability/references/development.md +104 -0
  168. package/kits/skills/ec-ability/references/management.md +117 -0
  169. package/kits/skills/ec-ability/references/recovery.md +27 -0
  170. package/kits/skills/ec-ability/references/runtime-protocol.md +109 -0
  171. package/kits/skills/ec-ability/references/workflows.md +15 -0
  172. package/kits/skills/ec-service-proxy/SKILL.md +12 -0
  173. package/kits/skills/personal-assistant/SKILL.md +240 -6
  174. package/kits/skills/personal-assistant/references/02-bootstrap.md +78 -4
  175. package/kits/skills/personal-assistant/scripts/clean.mjs +397 -0
  176. package/kits/skills/personal-assistant/scripts/init.mjs +113 -25
  177. package/kits/skills/personal-assistant/scripts/lock.mjs +189 -0
  178. package/kits/skills/personal-assistant/scripts/migrate.mjs +35 -10
  179. package/kits/skills/personal-assistant/scripts/verify.mjs +2 -1
  180. package/kits/skills/personal-assistant/templates/persona-section.md +54 -0
  181. package/kits/skills/personal-assistant/triggers/ingest-daily.json +1 -1
  182. package/kits/templates/memory-consolidation/notes.md +1 -1
  183. package/kits/templates/system-fragments/channel.md +2 -1
  184. package/kits/templates/system-fragments/commands.md +1 -0
  185. package/package.json +5 -3
  186. package/dist/core/command/data-root-error.js +0 -10
  187. package/dist/utils/machine-info.js +0 -46
  188. package/dist/utils/process-tree-worker.js +0 -31
  189. package/dist/utils/windows-output.js +0 -36
@@ -0,0 +1,70 @@
1
+ import Ajv from 'ajv';
2
+ import { abilityAssert } from './types.js';
3
+ const ajv = new Ajv({ strict: false, allErrors: true, addUsedSchema: false });
4
+ const reservedNames = new Set(['__proto__', 'constructor', 'prototype']);
5
+ export function grantState(instance, grant, store) {
6
+ if (grant.revokedAt)
7
+ return 'revoked';
8
+ if (!grant.expiresAt || grant.expiresAt <= Date.now())
9
+ return 'expired';
10
+ if (grant.issuedByAid !== instance.approvedByAid)
11
+ return 'issuer_changed';
12
+ if (grant.permission === 'remote-call') {
13
+ const scope = grant.value;
14
+ const usage = store.get('grant-usage', grant.id);
15
+ const maxCalls = scope.mode === 'once' ? 1 : scope.maxCalls;
16
+ if (maxCalls !== undefined && (usage?.calls ?? 0) >= maxCalls)
17
+ return 'exhausted';
18
+ }
19
+ return 'active';
20
+ }
21
+ export function validateRemoteGrant(value, pkg, currentDefinitions) {
22
+ const scope = value;
23
+ abilityAssert(scope && typeof scope.callerAid === 'string' && /^[a-z0-9][a-z0-9.-]{1,510}$/i.test(scope.callerAid)
24
+ && currentDefinitions.some(row => row.path === scope.path && row.definition_id === scope.definitionId), 'GRANT_INVALID', 'Select a caller and a current ability contract');
25
+ abilityAssert(!scope.mode || ['persistent', 'once', 'approval'].includes(scope.mode), 'GRANT_INVALID', 'Unsupported grant mode');
26
+ abilityAssert(scope.maxCalls === undefined || Number.isSafeInteger(scope.maxCalls) && scope.maxCalls > 0 && scope.maxCalls <= 1000000, 'GRANT_INVALID', 'maxCalls must be a positive integer up to one million');
27
+ if (scope.paramsSchema !== undefined) {
28
+ abilityAssert(scope.paramsSchema && typeof scope.paramsSchema === 'object' && !Array.isArray(scope.paramsSchema)
29
+ && Buffer.byteLength(JSON.stringify(scope.paramsSchema)) <= 16384, 'GRANT_INVALID', 'Parameter scope must be a schema under 16 KiB');
30
+ const check = (input, depth) => {
31
+ abilityAssert(depth <= 16, 'GRANT_INVALID', 'Parameter scope is too deep');
32
+ if (!input || typeof input !== 'object')
33
+ return;
34
+ for (const [key, child] of Object.entries(input)) {
35
+ abilityAssert(!['$ref', '$dynamicRef', '$recursiveRef', '$id', '$schema'].includes(key), 'GRANT_INVALID', 'Schema references are not supported in grants');
36
+ check(child, depth + 1);
37
+ }
38
+ };
39
+ check(scope.paramsSchema, 0);
40
+ abilityAssert(ajv.validateSchema(scope.paramsSchema), 'GRANT_INVALID', 'Parameter scope schema is invalid');
41
+ ajv.compile(scope.paramsSchema);
42
+ }
43
+ if (scope.budgets !== undefined) {
44
+ abilityAssert(scope.budgets && typeof scope.budgets === 'object' && !Array.isArray(scope.budgets) && Object.keys(scope.budgets).length <= 16, 'GRANT_INVALID', 'Budgets must map up to 16 numeric parameter names to totals');
45
+ const definition = pkg.definitions.find(row => row.definition.path === scope.path).definition;
46
+ const properties = definition.params_schema.properties;
47
+ for (const [key, total] of Object.entries(scope.budgets)) {
48
+ abilityAssert(!reservedNames.has(key) && properties && Object.hasOwn(properties, key) && properties[key]?.type === 'integer'
49
+ && Number.isSafeInteger(total) && total >= 0, 'GRANT_INVALID', 'Budgets require declared integer parameters and nonnegative integer totals');
50
+ }
51
+ }
52
+ }
53
+ export function executionGrant(instance, caller, definition, params, store) {
54
+ return instance.grants.find(grant => {
55
+ const scope = grant.value;
56
+ if (grant.permission !== 'remote-call' || grantState(instance, grant, store) !== 'active' || scope.callerAid !== caller || scope.path !== definition.path || scope.definitionId !== definition.definition_id)
57
+ return false;
58
+ if (scope.paramsSchema && !ajv.compile(scope.paramsSchema)(params))
59
+ return false;
60
+ const usage = store.get('grant-usage', grant.id) ?? { calls: 0, totals: Object.create(null) };
61
+ return Object.entries(scope.budgets ?? {}).every(([key, total]) => Number.isSafeInteger(params[key]) && params[key] >= 0 && (usage.totals[key] ?? 0) <= total - params[key]);
62
+ });
63
+ }
64
+ export function consumeGrant(grant, params, aid, store) {
65
+ const usage = store.get('grant-usage', grant.id) ?? { calls: 0, totals: Object.create(null) };
66
+ usage.calls++;
67
+ for (const key of Object.keys(grant.value.budgets ?? {}))
68
+ usage.totals[key] = (usage.totals[key] ?? 0) + params[key];
69
+ store.put('grant-usage', grant.id, aid, usage);
70
+ }
@@ -0,0 +1,105 @@
1
+ import { abilityAssert } from './types.js';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { getPackageRoot } from '../paths.js';
5
+ export const ABILITY_COMMAND_VERSION = 'evolcore.ability-cli/v1';
6
+ export const ABILITY_COMMANDS = {
7
+ capabilities: { description: '查询 daemon 实际支持的命令' },
8
+ schema: { description: '查询命令或 manifest/project JSON Schema', positional: 'required' },
9
+ targets: { description: '列出有权读取的 Agent/host AID' },
10
+ context: { description: '解析可信自身、目标与当前操作权限', target: true },
11
+ list: { description: '列出目标实例', target: true },
12
+ show: { description: '查看实例和当前契约', target: true, positional: 'required' },
13
+ status: { description: '查看运行和发布状态', target: true, positional: 'optional', options: ['--wait-publication'] },
14
+ doctor: { description: '只读诊断与修复建议', target: true, positional: 'optional' },
15
+ history: { description: '查看回滚点', target: true, positional: 'optional' },
16
+ approvals: { description: '查看调用审批队列', target: true },
17
+ preview: { description: '预览预构建目录、tgz 或固定 GitHub release', target: true, positional: 'required', options: ['--file'] },
18
+ job: { description: '查询原作业,可有界等待', target: true, positional: 'optional', options: ['--command-id', '--wait'] },
19
+ invocation: { description: '查询原调用结果', target: true, positional: 'required' },
20
+ ...Object.fromEntries(['install', 'configure', 'enable', 'disable', 'grant', 'invoke', 'publish', 'unpublish', 'upgrade', 'rollback', 'retire', 'uninstall'].map(action => [action, {
21
+ description: action === 'unpublish' ? '撤销实例全部能力发布,保留本地运行' : '提交 ' + action + ' 持久作业',
22
+ target: true, positional: action === 'install' ? undefined : 'required', action: action === 'unpublish' ? 'publish' : action,
23
+ options: ['--file', '--command-id'],
24
+ }])),
25
+ secrets: { description: '从非交互标准输入写秘密', target: true, positional: 'required', action: 'configure', options: ['--slot', '--revision', '--command-id', '--stdin', '--acknowledge-external-data'] },
26
+ };
27
+ ABILITY_COMMANDS.secret = ABILITY_COMMANDS.secrets;
28
+ export const ABILITY_DEV_COMMANDS = {
29
+ init: { description: '生成 readiness 插件项目', positional: 'required', options: ['--id', '--name', '--target', '--template', '--language'] },
30
+ 'add-ability': { description: '添加契约、用法和待实现 handler', positional: 'required', options: ['--project', '--handler', '--name'] },
31
+ 'remove-ability': { description: '移除项目能力声明,保留源码供审查', positional: 'required', options: ['--project'] },
32
+ check: { description: '静态校验预构建包,不执行代码', positional: 'required' },
33
+ doctor: { description: '检测已有语言运行时和构建工具,不自动配置环境', options: ['--project', '--language'] },
34
+ build: { description: '使用已配置工具链构建并按白名单组装插件包', options: ['--project', '--out'] },
35
+ pack: { description: '校验发行目录并生成确定性 tgz', options: ['--project', '--out'] },
36
+ version: { description: '修改开发 Manifest 的精确版本', positional: 'required', options: ['--project'] },
37
+ };
38
+ /** Shared by the CLI and daemon; flags never change authenticated identity. */
39
+ export function parseAbilityOptions(args, command) {
40
+ const allowed = new Set(['--format', ...(command.options ?? []), ...(command.target ? ['--aid', '--self'] : [])]);
41
+ const flags = new Set(['--self', '--stdin', '--acknowledge-external-data']);
42
+ const values = {};
43
+ const positional = [];
44
+ for (let i = 0; i < args.length; i++) {
45
+ const arg = args[i];
46
+ if (!arg.startsWith('-')) {
47
+ positional.push(arg);
48
+ continue;
49
+ }
50
+ abilityAssert(allowed.has(arg) && !(arg.slice(2) in values), 'ARGUMENT_INVALID', 'Unknown or duplicate option: ' + arg);
51
+ if (flags.has(arg))
52
+ values[arg.slice(2)] = 'true';
53
+ else {
54
+ abilityAssert(!!args[i + 1] && !args[i + 1].startsWith('--'), 'ARGUMENT_INVALID', 'Missing value: ' + arg);
55
+ values[arg.slice(2)] = args[++i];
56
+ }
57
+ }
58
+ abilityAssert(!values.format || values.format === 'json', 'ARGUMENT_INVALID', 'Only --format json is supported');
59
+ abilityAssert(!(values.aid && values.self), 'ARGUMENT_INVALID', '--aid and --self are mutually exclusive');
60
+ abilityAssert(positional.length <= (command.positional ? 1 : 0) && (command.positional !== 'required' || positional.length === 1), 'ARGUMENT_INVALID', 'Invalid number of positional arguments');
61
+ return { values, positional };
62
+ }
63
+ export function abilityCapabilities() {
64
+ return { schemaVersion: ABILITY_COMMAND_VERSION, commands: ABILITY_COMMANDS, development: ABILITY_DEV_COMMANDS,
65
+ features: { selfSelection: true, localArchive: true, runtimeDefaultCommands: true, buildAdapters: ['java', 'go', 'rust', 'command'], environmentAutoInstall: false,
66
+ ownerSelfManagementPolicy: false, separateCodeApprovalQueue: false, isolatedDevTest: false, persistedLogs: false },
67
+ output: { success: '{ok:true,data}', failure: '{ok:false,status,code,error}', jobSubmissionIsCompletion: false } };
68
+ }
69
+ export function abilityCommandSchema(operation) {
70
+ if (operation === 'manifest' || operation === 'project') {
71
+ const filename = operation === 'manifest' ? 'ability-plugin.schema.1.json' : 'ability-project.schema.1.json';
72
+ return { schemaVersion: ABILITY_COMMAND_VERSION, operation, input: JSON.parse(fs.readFileSync(path.join(getPackageRoot(), 'kits/schemas', filename), 'utf8')) };
73
+ }
74
+ abilityAssert(Object.hasOwn(ABILITY_COMMANDS, operation), 'ACTION_UNSUPPORTED', 'Unknown management command');
75
+ const command = ABILITY_COMMANDS[operation];
76
+ if (operation === 'secrets' || operation === 'secret')
77
+ return { schemaVersion: ABILITY_COMMAND_VERSION, operation, command, inputTransport: 'non-tty-stdin', maxSecretBytes: 16384, jsonFileAccepted: false };
78
+ const string = { type: 'string', minLength: 1 };
79
+ const object = { type: 'object' };
80
+ const common = { commandId: { type: 'string', pattern: '^[A-Za-z0-9_-]{8,128}$' }, expectedRevision: { type: 'integer', minimum: 1 } };
81
+ const fields = {
82
+ install: { previewId: string, name: { type: 'string', pattern: '^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$' }, config: object, approveTrustedCode: { type: 'boolean' } },
83
+ configure: { config: object, acknowledgeExternalData: { type: 'boolean' } },
84
+ enable: { approveTrustedCode: { type: 'boolean' } },
85
+ publish: { paths: { type: 'array', uniqueItems: true, items: string } },
86
+ unpublish: { paths: { type: 'array', maxItems: 0 } },
87
+ invoke: { confirmed: { const: true }, path: string, definitionId: string, params: object, operationId: string },
88
+ upgrade: { previewId: string, config: object, approveTrustedCode: { const: true }, approveCompatibilityChange: { type: 'boolean' }, approveSourceChange: { type: 'boolean' }, approveDowngrade: { type: 'boolean' }, acknowledgeExternalData: { type: 'boolean' } },
89
+ rollback: { generation: string, acknowledgeExternalData: { type: 'boolean' } }, retire: { generation: string },
90
+ grant: { permission: { enum: ['storage', 'workspace', 'http', 'remote-call'] }, value: object, expiresAt: { type: 'integer' }, confirmed: { type: 'boolean' }, revokeId: string, approvalId: string, decision: { enum: ['approved', 'denied'] } },
91
+ preview: { instanceId: string },
92
+ };
93
+ const required = { install: ['previewId', 'name'], configure: ['config'], publish: ['paths'], invoke: ['confirmed', 'path', 'definitionId', 'params', 'operationId'], upgrade: ['previewId', 'approveTrustedCode'], rollback: ['generation'], retire: ['generation'] };
94
+ return { schemaVersion: ABILITY_COMMAND_VERSION, operation, command,
95
+ input: { $schema: 'http://json-schema.org/draft-07/schema#', type: 'object', additionalProperties: true,
96
+ description: 'JSON body for --file; commandId may also be supplied by --command-id. Resource grants and configuration receive further service validation. Secrets use stdin only.',
97
+ properties: { ...(command.action ? common : {}), ...(fields[operation] ?? {}) },
98
+ required: [...(command.action ? ['commandId', ...(operation === 'install' ? [] : ['expectedRevision'])] : []), ...(required[operation] ?? [])] } };
99
+ }
100
+ export function parseAbilityWait(value) {
101
+ const match = /^(\d+)(ms|s|m)?$/.exec(value);
102
+ const duration = match ? Number(match[1]) * ({ ms: 1, s: 1000, m: 60000 }[match[2] || 's']) : NaN;
103
+ abilityAssert(Number.isSafeInteger(duration) && duration >= 1 && duration <= 60_000, 'ARGUMENT_INVALID', 'Wait must be between 1ms and 60s');
104
+ return duration;
105
+ }
@@ -0,0 +1,137 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AbilityApplicationService } from './application-service.js';
3
+ import { executeAbilityManagement, parseAbilityArgv, abilityFailure } from './management.js';
4
+ import { installAbilityProvider } from './provider.js';
5
+ import { abilityAssert } from './types.js';
6
+ import { ownerResolver, OWNERSHIP_AUTHORIZATION_MAX_AGE_MS } from '../core/ownership/owner-resolver.js';
7
+ import { remoteAccessService } from '../core/auth/remote-access-store.js';
8
+ import { createDelegationAuthorizer } from '../core/auth/delegation-authorization.js';
9
+ import { AUNChannel } from '../channels/aun.js';
10
+ import { logger } from '../utils/logger.js';
11
+ import { resolveEffective } from '../config/config-manager.js';
12
+ export function registerAbilityPlatform(root, deps) {
13
+ const delegated = createDelegationAuthorizer(deps);
14
+ const channels = () => [deps.getControlChannel?.(), ...deps.channelInstances.map(item => item.channel)].filter((item) => item instanceof AUNChannel);
15
+ const codeApprovalPolicy = (target) => {
16
+ if (target.kind === 'host')
17
+ return { enabled: true, source: 'host-default' };
18
+ try {
19
+ return { enabled: resolveEffective({ self: target.aid }, { cache: false }).ability?.codeApproval?.enabled ?? true, source: 'agent-config' };
20
+ }
21
+ catch {
22
+ // A malformed or unavailable Agent config must not open a code-execution gate.
23
+ return { enabled: false, source: 'agent-config' };
24
+ }
25
+ };
26
+ const authorizeAbility = async (actor, target, action) => {
27
+ if (target.kind === 'host')
28
+ return actor.daemonOwner;
29
+ if (action === 'read' && actor.daemonOwner)
30
+ return true;
31
+ if (actor.delegated) {
32
+ if (actor.delegated.scopeAid !== target.aid)
33
+ return false;
34
+ const decision = await delegated({ ...actor.delegated, targetAid: target.aid,
35
+ ...(actor.delegated.cachedGrant ? { delegationGrant: actor.delegated.cachedGrant } : {}) }, 'ability.' + action);
36
+ if (!decision.ok)
37
+ return false;
38
+ actor.delegated.cachedGrant = decision.grant;
39
+ if (action === 'read')
40
+ return true;
41
+ }
42
+ if (!actor.aid)
43
+ return false;
44
+ const view = await ownerResolver.refresh(target.aid, { maxAgeMs: OWNERSHIP_AUTHORIZATION_MAX_AGE_MS, allowTransient: false, source: 'ability.' + action });
45
+ return view.authorizationStatus === 'verified' && view.ownerAid === actor.aid;
46
+ };
47
+ const service = new AbilityApplicationService(root, {
48
+ targets: () => [...new Map([...deps.agentRegistry.list().map(agent => ({ aid: agent.aid, name: agent.displayName || agent.name, kind: 'agent' })),
49
+ ...(deps.daemonAid ? [{ aid: deps.daemonAid, name: 'Host', kind: 'host' }] : [])].map(target => [target.aid, target])).values()],
50
+ authorize: authorizeAbility,
51
+ runtimeAuthorized: async (instance) => {
52
+ if (instance.target.kind === 'host')
53
+ return true;
54
+ if (!instance.approvedByAid)
55
+ return false;
56
+ const view = await ownerResolver.refresh(instance.target.aid, { maxAgeMs: OWNERSHIP_AUTHORIZATION_MAX_AGE_MS, allowTransient: false, source: 'ability.runtime' });
57
+ return view.authorizationStatus === 'verified' && view.ownerAid === instance.approvedByAid;
58
+ },
59
+ approveCode: async (actor) => {
60
+ if (actor.daemonOwner)
61
+ return true;
62
+ if (!actor.aid || !deps.daemonAid)
63
+ return false;
64
+ const view = await ownerResolver.refresh(deps.daemonAid, { maxAgeMs: OWNERSHIP_AUTHORIZATION_MAX_AGE_MS, allowTransient: false, source: 'ability.code-approval' });
65
+ return view.authorizationStatus === 'verified' && view.ownerAid === actor.aid;
66
+ },
67
+ canApproveCode: async (actor, targetAid) => {
68
+ const target = deps.agentRegistry.get(targetAid);
69
+ if (!target || !codeApprovalPolicy({ aid: targetAid, kind: 'agent' }).enabled)
70
+ return false;
71
+ return authorizeAbility(actor, { aid: targetAid, kind: 'agent', name: target.name }, 'install');
72
+ },
73
+ codeApprovalPolicy,
74
+ publish: async (aid, documents, expectedIndexes) => {
75
+ const channel = channels().find(item => item.abilityPublisherAid === aid);
76
+ abilityAssert(channel, 'AUN_NOT_CONNECTED', 'Target AID has no AUN channel', 503);
77
+ await channel.publishAbilityDocuments(documents, expectedIndexes);
78
+ },
79
+ });
80
+ deps.ipcServer.setAbilityExecutor(async (command) => {
81
+ try {
82
+ let actor;
83
+ let context = { authentication: 'ecweb' };
84
+ let inputContext = {};
85
+ if (command.type === 'ecweb.ability') {
86
+ const token = command.remoteToken;
87
+ const valid = remoteAccessService.validateToken(token);
88
+ abilityAssert(valid.valid && typeof token === 'string', 'AUTHENTICATION_REQUIRED', 'ECWeb bearer authentication is required', 401);
89
+ actor = { key: 'ecweb:' + createHash('sha256').update(token).digest('hex'), aid: valid.authorizedBy, daemonOwner: true };
90
+ }
91
+ else if (command.sessionId || command.delegationToken) {
92
+ const validation = deps.agentDelegationRegistry.validateForContext(command.delegationToken, command.sessionId, command.delegationCommandHash);
93
+ abilityAssert(validation.ok, 'INVALID_DELEGATION', 'A current task delegation is required', 403);
94
+ const grant = validation.grant;
95
+ const session = await deps.sessionManager.getSessionById(grant.sessionId);
96
+ abilityAssert(session?.selfAID === grant.selfAid, 'INVALID_DELEGATION', 'Delegation does not match session', 403);
97
+ actor = { key: grant.channelType + ':' + grant.actorId, aid: grant.channelType === 'aun' ? grant.actorId : undefined, daemonOwner: false,
98
+ delegated: { sessionId: grant.sessionId, delegationToken: command.delegationToken, delegationCommandHash: command.delegationCommandHash, scopeAid: grant.selfAid } };
99
+ context = { selfAid: grant.selfAid, authentication: 'delegated-agent' };
100
+ inputContext = { baseDirectory: session.projectPath, roots: [session.projectPath, grant.sessionRuntimeDir].filter((root) => !!root) };
101
+ }
102
+ else {
103
+ actor = { key: 'local-control', daemonOwner: true };
104
+ context = { selfAid: deps.daemonAid, authentication: 'local-control' };
105
+ }
106
+ const request = command.type === 'ability.op' ? parseAbilityArgv(command.argv, inputContext) : command.request;
107
+ if (command.type === 'ability.op' && ['secret', 'secrets'].includes(request.operation))
108
+ request.input = { ...request.input, value: command.stdinSecret };
109
+ return { ok: true, data: await executeAbilityManagement(service, actor, request, context) };
110
+ }
111
+ catch (error) {
112
+ return abilityFailure(error);
113
+ }
114
+ });
115
+ const removeProvider = installAbilityProvider(service);
116
+ let closing = false;
117
+ let reconcile;
118
+ const reconcilePublication = () => {
119
+ if (closing || reconcile)
120
+ return;
121
+ reconcile = (async () => {
122
+ await service.recover();
123
+ for (const target of service.host.targets()) {
124
+ const state = service.store.get('publication', target.aid);
125
+ if (state?.state === 'pending')
126
+ try {
127
+ await service.syncPublication(target.aid);
128
+ }
129
+ catch { /* next pass retries */ }
130
+ }
131
+ })().catch(() => logger.warn('[ability] Publication reconciliation failed')).finally(() => { reconcile = undefined; });
132
+ };
133
+ const recovery = service.recover().catch(() => logger.warn('[ability] Recovery incomplete; inspect AID plugin state'));
134
+ const timer = setInterval(reconcilePublication, 30000);
135
+ timer.unref();
136
+ return { async close() { closing = true; clearInterval(timer); removeProvider(); await recovery; await reconcile; await service.close(); } };
137
+ }