evolcore 0.0.42 → 0.0.43-test.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/CHANGELOG.md +29 -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/identity.js +45 -0
  29. package/dist/aun/aid/index.js +1 -0
  30. package/dist/aun/aid/managed-operation.js +73 -2
  31. package/dist/channels/aun.js +64 -18
  32. package/dist/channels/builtin-plugins.js +14 -0
  33. package/dist/channels/dingtalk.js +78 -26
  34. package/dist/channels/feishu.js +89 -14
  35. package/dist/channels/qqbot.js +84 -19
  36. package/dist/channels/wechat.js +77 -19
  37. package/dist/channels/wecom.js +67 -22
  38. package/dist/cli/ability-command.js +92 -0
  39. package/dist/cli/aun-commands.js +124 -85
  40. package/dist/cli/daemon-commands.js +37 -85
  41. package/dist/cli/index.js +14 -0
  42. package/dist/cli/init.js +11 -13
  43. package/dist/cli/managed-command-guard.js +6 -0
  44. package/dist/cli/model.js +101 -104
  45. package/dist/cli/provider-command.js +6 -4
  46. package/dist/cli/restart-monitor.js +52 -11
  47. package/dist/cli/upgrade-command.js +102 -0
  48. package/dist/cli/version.js +1 -1
  49. package/dist/config/access-policy.js +4 -2
  50. package/dist/config/builtin-roles.js +1 -0
  51. package/dist/config/config-field-policy.js +4 -0
  52. package/dist/config/config-manager.js +7 -0
  53. package/dist/config/provider-ipc-service.js +10 -0
  54. package/dist/config/providers-config.js +12 -3
  55. package/dist/config/providers-management.js +45 -9
  56. package/dist/config/schema-migration.js +40 -22
  57. package/dist/contracts/ecweb-service-protocol.js +2 -1
  58. package/dist/core/auth/agent-delegation.js +21 -5
  59. package/dist/core/auth/auth-gateway.js +31 -9
  60. package/dist/core/auth/authorization-audit.js +52 -4
  61. package/dist/core/auth/delegation-authorization.js +140 -4
  62. package/dist/core/auth/operation-authorizer.js +114 -13
  63. package/dist/core/auth/operation-catalog.js +118 -4
  64. package/dist/core/baseagent-loader.js +14 -1
  65. package/dist/core/channel-loader.js +47 -9
  66. package/dist/core/channel-runtime.js +1 -1
  67. package/dist/core/command/agent-storage-menu.js +1 -1
  68. package/dist/core/command/cli-intent-parser.js +26 -13
  69. package/dist/core/command/command-handler.js +232 -76
  70. package/dist/core/command/connect-menu.js +10 -4
  71. package/dist/core/command/daemon-diagnostics.js +3 -3
  72. package/dist/core/command/data-root-resolver.js +2 -3
  73. package/dist/core/command/menu-catalog.js +10 -3
  74. package/dist/core/command/menu-handler.js +321 -46
  75. package/dist/core/command/menu-protocol.js +53 -7
  76. package/dist/core/command/pa-workspace-calendar.js +1 -2
  77. package/dist/core/command/pa-workspace-items.js +486 -0
  78. package/dist/core/command/pa-workspace-store.js +10 -1
  79. package/dist/core/command/slash-gate.js +2 -2
  80. package/dist/core/command/slash-handler.js +67 -25
  81. package/dist/core/contact-bind-registry.js +27 -0
  82. package/dist/core/daemon-control.js +3 -3
  83. package/dist/core/daemon-lifecycle.js +2 -1
  84. package/dist/core/event-bus.js +9 -2
  85. package/dist/core/handoff/ipc-registration.js +1 -0
  86. package/dist/core/host-snapshot.js +1 -2
  87. package/dist/core/initialization/service.js +32 -11
  88. package/dist/core/ipc-registration.js +18 -5
  89. package/dist/core/memory/consolidation-context.js +2 -2
  90. package/dist/core/message/aun-request-registry.js +99 -18
  91. package/dist/core/message/im-renderer.js +16 -11
  92. package/dist/core/message/message-admission.js +25 -20
  93. package/dist/core/message/message-bridge.js +21 -47
  94. package/dist/core/message/message-queue.js +3 -0
  95. package/dist/core/message/response-engine.js +7 -5
  96. package/dist/core/model/catalog-service.js +1 -1
  97. package/dist/core/permission/ec-command-parser.js +41 -9
  98. package/dist/core/permission/permission-result.js +1 -0
  99. package/dist/core/permission/protected-paths.js +25 -14
  100. package/dist/core/permission/tool-policy.js +108 -107
  101. package/dist/core/plugin-lifecycle.js +133 -0
  102. package/dist/core/runner-reload-transaction.js +4 -1
  103. package/dist/core/system-session/memory.js +16 -3
  104. package/dist/core/task/task-activity-store.js +50 -0
  105. package/dist/core/task/task-image-resources.js +140 -0
  106. package/dist/core/thread/ipc-operation.js +1 -1
  107. package/dist/core/thread/thread-service.js +0 -1
  108. package/dist/directory/canonical-digest.js +5 -3
  109. package/dist/directory/owner-directory-admission.js +22 -2
  110. package/dist/directory/owner-directory-cache.js +394 -60
  111. package/dist/directory/owner-directory-markdown.js +29 -2
  112. package/dist/directory/owner-directory-scope.js +35 -16
  113. package/dist/ecweb/basic-settings-service.js +4 -1
  114. package/dist/ecweb/pairing.js +41 -0
  115. package/dist/ecweb/providers-service.js +8 -1
  116. package/dist/{utils/ecweb-utils.js → ecweb/runtime/launch.js} +3 -27
  117. package/dist/ecweb/runtime/lifecycle.js +184 -0
  118. package/dist/{utils/ecweb-supervisor.js → ecweb/runtime/supervisor.js} +32 -27
  119. package/dist/index.js +34 -25
  120. package/dist/ipc.js +124 -7
  121. package/dist/response-system/engines/v1/proactive-flow.js +1 -1
  122. package/dist/trigger/authorization.js +2 -2
  123. package/dist/utils/atomic-write.js +24 -0
  124. package/dist/utils/avatar-upload.js +3 -1
  125. package/dist/utils/cross-platform.js +31 -2
  126. package/dist/utils/host-info.js +36 -0
  127. package/dist/utils/instance-registry.js +38 -11
  128. package/dist/utils/logger.js +9 -0
  129. package/dist/utils/{process-tree-stats.js → process-tree.js} +29 -0
  130. package/dist/utils/tool-summary.js +9 -1
  131. package/dist/utils/upgrade-jobs.js +96 -15
  132. package/dist/utils/windows-autostart.js +1 -1
  133. package/ecagent/README.md +19 -0
  134. package/ecagent/dist/harness/agent-harness.js +9 -0
  135. package/ecagent/dist/harness/env/nodejs.js +71 -11
  136. package/ecagent/dist/harness/env/windows-shell.d.ts +7 -0
  137. package/ecagent/dist/harness/env/windows-shell.js +132 -0
  138. package/kits/docs/aun/ABILITY_CALLING.md +38 -9
  139. package/kits/docs/evolcore/INDEX.md +5 -1
  140. package/kits/docs/evolcore/ability.md +181 -0
  141. package/kits/docs/evolcore/aid.md +20 -0
  142. package/kits/docs/evolcore/config.md +10 -6
  143. package/kits/docs/evolcore/menu-protocol.md +40 -1
  144. package/kits/docs/evolcore/provider.md +2 -2
  145. package/kits/docs/evolcore/tool-authorization.md +270 -0
  146. package/kits/runtime/ability-job.ps1 +41 -0
  147. package/kits/runtime/ability-runner.mjs +67 -0
  148. package/kits/runtime/ability-secret.ps1 +59 -0
  149. package/kits/runtime/ability-templates/go/main.go +59 -0
  150. package/kits/runtime/ability-templates/java/Json.java +67 -0
  151. package/kits/runtime/ability-templates/java/Runner.java +42 -0
  152. package/kits/runtime/ability-templates/python/runner.py +48 -0
  153. package/kits/runtime/ability-templates/rust/json.rs +87 -0
  154. package/kits/runtime/ability-templates/rust/runner.rs +35 -0
  155. package/kits/schemas/_meta.json +12 -1
  156. package/kits/schemas/ability-plugin.schema.1.json +107 -0
  157. package/kits/schemas/ability-project.schema.1.json +31 -0
  158. package/kits/schemas/agent-config.schema.16.json +20 -0
  159. package/kits/schemas/agent-config.schema.17.json +20 -0
  160. package/kits/schemas/agent-config.schema.18.json +917 -0
  161. package/kits/skills/.switches.json +4 -0
  162. package/kits/skills/aid-ability/SKILL.md +5 -4
  163. package/kits/skills/ec-ability/SKILL.md +67 -0
  164. package/kits/skills/ec-ability/references/contract-checklist.md +37 -0
  165. package/kits/skills/ec-ability/references/development.md +104 -0
  166. package/kits/skills/ec-ability/references/management.md +117 -0
  167. package/kits/skills/ec-ability/references/recovery.md +27 -0
  168. package/kits/skills/ec-ability/references/runtime-protocol.md +109 -0
  169. package/kits/skills/ec-ability/references/workflows.md +15 -0
  170. package/kits/skills/ec-service-proxy/SKILL.md +12 -0
  171. package/kits/skills/personal-assistant/SKILL.md +240 -6
  172. package/kits/skills/personal-assistant/references/02-bootstrap.md +78 -4
  173. package/kits/skills/personal-assistant/scripts/clean.mjs +397 -0
  174. package/kits/skills/personal-assistant/scripts/init.mjs +113 -25
  175. package/kits/skills/personal-assistant/scripts/lock.mjs +189 -0
  176. package/kits/skills/personal-assistant/scripts/migrate.mjs +35 -10
  177. package/kits/skills/personal-assistant/scripts/verify.mjs +2 -1
  178. package/kits/skills/personal-assistant/templates/persona-section.md +54 -0
  179. package/kits/skills/personal-assistant/triggers/ingest-daily.json +1 -1
  180. package/kits/templates/memory-consolidation/notes.md +1 -1
  181. package/kits/templates/system-fragments/channel.md +2 -1
  182. package/kits/templates/system-fragments/commands.md +1 -0
  183. package/package.json +4 -2
  184. package/dist/core/command/data-root-error.js +0 -10
  185. package/dist/utils/machine-info.js +0 -46
  186. package/dist/utils/process-tree-worker.js +0 -31
  187. package/dist/utils/windows-output.js +0 -36
@@ -0,0 +1,547 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** The wire profile currently implemented by EvolApp's ability host. */
3
+ export const ABILITY_SPEC_VERSION = 'aid-ability/2';
4
+ export const ABILITY_INDEX_SCHEMA = 'aun.ability.index.v1';
5
+ export const ABILITY_RELEASE_SCHEMA = 'aun.ability.release.v1';
6
+ export const ABILITY_USAGE_SCHEMA = 'aun.ability.usage.v1';
7
+ const PATH_RE = /^[a-z][a-z0-9_-]*(\/[a-z][a-z0-9_-]*)+$/;
8
+ const DEFINITION_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
9
+ const RELEASE_ID_RE = /^[a-f0-9]{64}$/;
10
+ const SEMVER_RE = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
11
+ // This is the same deliberately small schema profile checked by EvolApp's
12
+ // `checkSchemaProfile`. Keeping the allow-list here prevents Core from
13
+ // accepting a definition which the Flutter host would reject at registration.
14
+ const SCHEMA_KEYWORDS = new Set([
15
+ 'type', 'properties', 'required', 'additionalProperties', 'items', 'enum',
16
+ 'const', 'minimum', 'maximum', 'minLength', 'maxLength', 'minItems',
17
+ 'maxItems', 'description', 'default', 'untrusted_text',
18
+ ]);
19
+ const TRANSPORT_FIELDS = new Set([
20
+ 'device_id', 'slot_id', 'runtime_ref', 'target_runtime_ref',
21
+ 'sender_slot_id', 'to_device_id',
22
+ ]);
23
+ export const ABILITY_EFFECTS = new Set([
24
+ 'sensor.read',
25
+ 'sensor.read.camera',
26
+ 'sensor.read.location',
27
+ 'sensor.read.biometric',
28
+ 'sensor.read.identity',
29
+ 'state.read',
30
+ 'state.write',
31
+ 'actuator.control',
32
+ 'physical.output',
33
+ 'physical.irreversible',
34
+ 'data.egress',
35
+ 'data.local_write',
36
+ 'credential.access',
37
+ 'payment',
38
+ 'code.execute',
39
+ 'system.interact',
40
+ ]);
41
+ export class AbilityProtocolError extends Error {
42
+ code;
43
+ path;
44
+ constructor(message, options = {}) {
45
+ super(message);
46
+ this.name = 'AbilityProtocolError';
47
+ this.code = options.code ?? 'params_invalid';
48
+ this.path = options.path;
49
+ }
50
+ }
51
+ function fail(message, code = 'params_invalid', path) {
52
+ throw new AbilityProtocolError(message, { code, path });
53
+ }
54
+ export function isJsonObject(value) {
55
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
56
+ }
57
+ function requiredString(value, field, max = 256) {
58
+ if (typeof value !== 'string' || value.length === 0 || value.length > max) {
59
+ fail(`invalid ${field}`, 'params_invalid', field);
60
+ }
61
+ return value;
62
+ }
63
+ function requiredPath(value, field) {
64
+ const path = requiredString(value, field);
65
+ if (!PATH_RE.test(path) || path.startsWith('definitions/')) {
66
+ fail(`invalid ability path`, 'params_invalid', field);
67
+ }
68
+ return path;
69
+ }
70
+ function requiredDefinitionId(value, field = 'definition_id') {
71
+ const id = requiredString(value, field);
72
+ if (!DEFINITION_ID_RE.test(id))
73
+ fail(`invalid definition_id`, 'params_invalid', field);
74
+ return id;
75
+ }
76
+ function requiredRecord(value, field) {
77
+ if (!isJsonObject(value))
78
+ fail(`${field} must be an object`, 'params_invalid', field);
79
+ return value;
80
+ }
81
+ function requiredInteger(value, field) {
82
+ if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
83
+ fail(`invalid ${field}`, 'params_invalid', field);
84
+ }
85
+ return value;
86
+ }
87
+ function requiredAid(value, field) {
88
+ return requiredString(value, field, 512).trim() || fail(`invalid ${field}`, 'params_invalid', field);
89
+ }
90
+ function checkNoTransportFields(value) {
91
+ for (const field of TRANSPORT_FIELDS) {
92
+ if (Object.prototype.hasOwnProperty.call(value, field)) {
93
+ fail(`ability payload must not contain ${field}`, 'params_invalid', field);
94
+ }
95
+ }
96
+ }
97
+ /** Validate and normalize an EvolApp-compatible Ability call. */
98
+ export function parseAbilityCall(value, now = Date.now()) {
99
+ const payload = requiredRecord(value, 'payload');
100
+ if (payload.type !== 'ability' || payload.role !== 'call') {
101
+ fail('payload must be an ability call');
102
+ }
103
+ const callId = requiredString(payload.call_id, 'call_id');
104
+ const operationId = requiredString(payload.operation_id, 'operation_id');
105
+ const abilityPath = requiredPath(payload.ability_path, 'ability_path');
106
+ const sentAt = requiredInteger(payload.sent_at, 'sent_at');
107
+ const ttl = requiredInteger(payload.ttl, 'ttl');
108
+ if (sentAt < 0 || sentAt > now + 30_000 || ttl < 1 || ttl > 86_400) {
109
+ fail('invalid sent_at or ttl', 'params_invalid');
110
+ }
111
+ if (now >= sentAt + ttl * 1_000)
112
+ fail('ability call expired', 'message_expired');
113
+ if (payload.async !== undefined && typeof payload.async !== 'boolean') {
114
+ fail('async must be a boolean', 'params_invalid', 'async');
115
+ }
116
+ if (Object.prototype.hasOwnProperty.call(payload, 'credential') || payload.credential_present === true) {
117
+ fail('credential is not supported by the v1 profile', 'permission_denied', 'credential');
118
+ }
119
+ checkNoTransportFields(payload);
120
+ const params = payload.params === undefined ? {} : requiredRecord(payload.params, 'params');
121
+ const threadId = payload.thread_id === undefined ? undefined : requiredString(payload.thread_id, 'thread_id');
122
+ const async = payload.async === true;
123
+ if (abilityPath === 'protocol/discover') {
124
+ if (payload.definition_id !== undefined) {
125
+ fail('discover must not carry definition_id', 'params_invalid', 'definition_id');
126
+ }
127
+ const keys = Object.keys(params);
128
+ const windowSeconds = params.window_seconds;
129
+ if (params.spec_version !== ABILITY_SPEC_VERSION
130
+ || !Number.isSafeInteger(windowSeconds)
131
+ || windowSeconds < 1 || windowSeconds > 30
132
+ || ttl !== windowSeconds
133
+ || async
134
+ || keys.some(key => key !== 'spec_version' && key !== 'window_seconds')) {
135
+ fail('invalid protocol/discover parameters', 'params_invalid', 'params');
136
+ }
137
+ }
138
+ else {
139
+ requiredDefinitionId(payload.definition_id);
140
+ }
141
+ return {
142
+ type: 'ability', role: 'call', call_id: callId, operation_id: operationId,
143
+ ability_path: abilityPath,
144
+ ...(payload.definition_id !== undefined ? { definition_id: payload.definition_id } : {}),
145
+ params, sent_at: sentAt, ttl, async,
146
+ ...(threadId !== undefined ? { thread_id: threadId } : {}),
147
+ };
148
+ }
149
+ export function buildAbilityCall(input) {
150
+ const call = {
151
+ type: 'ability', role: 'call', call_id: input.callId,
152
+ operation_id: input.operationId, ability_path: input.path,
153
+ definition_id: input.definitionId, params: input.params ?? {},
154
+ sent_at: input.sentAt ?? Date.now(), ttl: input.ttlSeconds ?? 60,
155
+ async: input.async ?? false,
156
+ ...(input.threadId !== undefined ? { thread_id: input.threadId } : {}),
157
+ };
158
+ return parseAbilityCall(call, call.sent_at);
159
+ }
160
+ export function buildDiscoverCall(input) {
161
+ const windowSeconds = input.windowSeconds ?? 5;
162
+ const sentAt = input.sentAt ?? Date.now();
163
+ return parseAbilityCall({
164
+ type: 'ability', role: 'call', call_id: input.callId,
165
+ operation_id: input.operationId, ability_path: 'protocol/discover',
166
+ params: { spec_version: ABILITY_SPEC_VERSION, window_seconds: windowSeconds },
167
+ sent_at: sentAt, ttl: windowSeconds, async: false,
168
+ }, sentAt);
169
+ }
170
+ function validateReference(ref, prefix, expected, field) {
171
+ const value = requiredString(ref, field, 2_048);
172
+ if (value !== `${prefix}:/${expected}`)
173
+ fail(`invalid ${field}`, 'contract_invalid', field);
174
+ return value;
175
+ }
176
+ function validateReleaseId(value) {
177
+ const id = requiredString(value, 'release_id', 128);
178
+ if (!RELEASE_ID_RE.test(id))
179
+ fail('invalid release_id', 'contract_invalid', 'release_id');
180
+ return id;
181
+ }
182
+ function validateEffects(value) {
183
+ if (!Array.isArray(value) || value.length === 0 || value.some(effect => typeof effect !== 'string' || !ABILITY_EFFECTS.has(effect))) {
184
+ fail('invalid effects', 'contract_invalid', 'effects');
185
+ }
186
+ const effects = value;
187
+ if (new Set(effects).size !== effects.length)
188
+ fail('duplicate effects', 'contract_invalid', 'effects');
189
+ return effects;
190
+ }
191
+ function validateSchemaProfile(value, path = 'schema') {
192
+ const schema = requiredRecord(value, path);
193
+ const allowedTypes = new Set(['object', 'array', 'string', 'integer', 'boolean', 'null']);
194
+ if (Object.keys(schema).some(key => !SCHEMA_KEYWORDS.has(key))) {
195
+ fail('unsupported schema keyword', 'contract_invalid', path);
196
+ }
197
+ if (typeof schema.type !== 'string' || !allowedTypes.has(schema.type)) {
198
+ fail('unsupported schema type', 'contract_invalid', `${path}.type`);
199
+ }
200
+ if (schema.additionalProperties !== undefined && typeof schema.additionalProperties !== 'boolean') {
201
+ fail('additionalProperties must be boolean', 'contract_invalid', `${path}.additionalProperties`);
202
+ }
203
+ if (schema.properties !== undefined && !isJsonObject(schema.properties)) {
204
+ fail('properties must be an object', 'contract_invalid', `${path}.properties`);
205
+ }
206
+ if (schema.required !== undefined && (!Array.isArray(schema.required)
207
+ || schema.required.some(item => typeof item !== 'string'))) {
208
+ fail('required must be an array of strings', 'contract_invalid', `${path}.required`);
209
+ }
210
+ for (const keyword of ['enum', 'required']) {
211
+ if (schema[keyword] !== undefined && !Array.isArray(schema[keyword])) {
212
+ fail(`${keyword} must be an array`, 'contract_invalid', `${path}.${keyword}`);
213
+ }
214
+ }
215
+ for (const keyword of ['minimum', 'maximum', 'minLength', 'maxLength', 'minItems', 'maxItems']) {
216
+ if (schema[keyword] !== undefined && (typeof schema[keyword] !== 'number' || !Number.isSafeInteger(schema[keyword]))) {
217
+ fail(`${keyword} must be an integer`, 'contract_invalid', `${path}.${keyword}`);
218
+ }
219
+ }
220
+ if (schema.properties !== undefined) {
221
+ const properties = requiredRecord(schema.properties, `${path}.properties`);
222
+ for (const [key, child] of Object.entries(properties))
223
+ validateSchemaProfile(child, `${path}.properties.${key}`);
224
+ }
225
+ if (schema.items !== undefined)
226
+ validateSchemaProfile(schema.items, `${path}.items`);
227
+ return schema;
228
+ }
229
+ /** Validate an EvolApp definition object read from the public L3 path. */
230
+ export function parseAbilityDefinition(value, expected) {
231
+ const d = requiredRecord(value, 'definition');
232
+ const path = requiredPath(d.path, 'path');
233
+ if (path.startsWith('protocol/'))
234
+ fail('ability definitions cannot use protocol paths', 'contract_invalid', 'path');
235
+ const definitionId = requiredDefinitionId(d.definition_id);
236
+ if (expected?.path !== undefined && path !== expected.path)
237
+ fail('definition path mismatch', 'contract_changed', 'path');
238
+ if (expected?.definitionId !== undefined && definitionId !== expected.definitionId)
239
+ fail('definition_id mismatch', 'contract_changed', 'definition_id');
240
+ const effects = validateEffects(d.effects);
241
+ if (d.require_confirm !== true || d.auth_required !== true || d.idempotency !== 'keyed'
242
+ || JSON.stringify(d.allowed_modes) !== '["explicit"]' || d.aggregation !== 'none') {
243
+ fail('definition is not compatible with the EvolApp v1 profile', 'contract_invalid');
244
+ }
245
+ const retention = requiredInteger(d.dedupe_retention_seconds, 'dedupe_retention_seconds');
246
+ if (retention < 1)
247
+ fail('invalid dedupe retention', 'contract_invalid', 'dedupe_retention_seconds');
248
+ const paramsSchema = validateSchemaProfile(d.params_schema, 'params_schema');
249
+ const resultSchema = validateSchemaProfile(d.result_schema, 'result_schema');
250
+ return {
251
+ ...d, path, definition_id: definitionId, params_schema: paramsSchema,
252
+ result_schema: resultSchema, effects, require_confirm: true,
253
+ auth_required: true, idempotency: 'keyed', allowed_modes: ['explicit'],
254
+ aggregation: 'none', dedupe_retention_seconds: retention,
255
+ };
256
+ }
257
+ function validateSchemaValue(schema, value, path) {
258
+ const type = schema.type;
259
+ const valid = type === 'object' ? isJsonObject(value)
260
+ : type === 'array' ? Array.isArray(value)
261
+ : type === 'string' ? typeof value === 'string'
262
+ : type === 'integer' ? typeof value === 'number' && Number.isSafeInteger(value)
263
+ : type === 'boolean' ? typeof value === 'boolean'
264
+ : type === 'null' ? value === null : false;
265
+ if (!valid)
266
+ fail(`example does not match ${path}`, 'contract_invalid', path);
267
+ if (schema.const !== undefined && canonicalJson(schema.const) !== canonicalJson(value)) {
268
+ fail(`example does not match ${path}.const`, 'contract_invalid', path);
269
+ }
270
+ if (Array.isArray(schema.enum) && !schema.enum.some(item => canonicalJson(item) === canonicalJson(value))) {
271
+ fail(`example does not match ${path}.enum`, 'contract_invalid', path);
272
+ }
273
+ if (type === 'object') {
274
+ const object = value;
275
+ const properties = isJsonObject(schema.properties) ? schema.properties : {};
276
+ if (Array.isArray(schema.required)) {
277
+ for (const key of schema.required)
278
+ if (typeof key === 'string' && !Object.prototype.hasOwnProperty.call(object, key)) {
279
+ fail(`example is missing ${path}.${key}`, 'contract_invalid', path);
280
+ }
281
+ }
282
+ for (const [key, child] of Object.entries(object)) {
283
+ if (isJsonObject(properties[key]))
284
+ validateSchemaValue(properties[key], child, `${path}.${key}`);
285
+ else if (schema.additionalProperties === false)
286
+ fail(`example has unknown ${path}.${key}`, 'contract_invalid', path);
287
+ }
288
+ }
289
+ else if (type === 'array') {
290
+ const array = value;
291
+ if (typeof schema.minItems === 'number' && array.length < schema.minItems)
292
+ fail(`example array is too short`, 'contract_invalid', path);
293
+ if (typeof schema.maxItems === 'number' && array.length > schema.maxItems)
294
+ fail(`example array is too long`, 'contract_invalid', path);
295
+ if (isJsonObject(schema.items))
296
+ array.forEach((item, index) => validateSchemaValue(schema.items, item, `${path}[${index}]`));
297
+ }
298
+ else if (type === 'string') {
299
+ const length = [...value].length;
300
+ if (typeof schema.minLength === 'number' && length < schema.minLength)
301
+ fail(`example string is too short`, 'contract_invalid', path);
302
+ if (typeof schema.maxLength === 'number' && length > schema.maxLength)
303
+ fail(`example string is too long`, 'contract_invalid', path);
304
+ }
305
+ else if (type === 'integer') {
306
+ if (typeof schema.minimum === 'number' && value < schema.minimum)
307
+ fail(`example is below minimum`, 'contract_invalid', path);
308
+ if (typeof schema.maximum === 'number' && value > schema.maximum)
309
+ fail(`example is above maximum`, 'contract_invalid', path);
310
+ }
311
+ }
312
+ function canonicalJson(value) {
313
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
314
+ return JSON.stringify(value);
315
+ if (typeof value === 'number') {
316
+ if (!Number.isSafeInteger(value))
317
+ fail('unsupported JSON number', 'contract_invalid');
318
+ return String(value);
319
+ }
320
+ if (Array.isArray(value))
321
+ return `[${value.map(canonicalJson).join(',')}]`;
322
+ if (isJsonObject(value)) {
323
+ return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
324
+ }
325
+ fail('unsupported JSON value', 'contract_invalid');
326
+ }
327
+ export function canonicalizeAbilityJson(value) {
328
+ return canonicalJson(value);
329
+ }
330
+ export function sha256Hex(value) {
331
+ return createHash('sha256').update(value, 'utf8').digest('hex');
332
+ }
333
+ /** Match AbilityRelease.id from EvolApp (SHA-256 over canonical release content). */
334
+ export function abilityReleaseId(pluginVersion, definition, usage) {
335
+ return sha256Hex(canonicalJson({ plugin_version: pluginVersion, definition, usage }));
336
+ }
337
+ export function parseAbilityRelease(value, expected) {
338
+ const snapshot = requiredRecord(value, 'release');
339
+ if (snapshot.schema !== ABILITY_RELEASE_SCHEMA || typeof snapshot.plugin_version !== 'string' || !SEMVER_RE.test(snapshot.plugin_version)) {
340
+ fail('invalid release snapshot', 'contract_invalid');
341
+ }
342
+ const definition = parseAbilityDefinition(snapshot.definition, expected);
343
+ const usage = requiredRecord(snapshot.usage, 'usage');
344
+ if (usage.schema !== ABILITY_USAGE_SCHEMA || usage.path !== definition.path || usage.definition_id !== definition.definition_id
345
+ || !Array.isArray(usage.examples) || usage.examples.length === 0
346
+ || usage.examples.some(example => !isJsonObject(example) || !isJsonObject(example.params))
347
+ || !Array.isArray(usage.result_processing) || usage.result_processing.length === 0
348
+ || usage.result_processing.some(item => typeof item !== 'string')) {
349
+ fail('release usage does not match definition', 'contract_invalid', 'usage');
350
+ }
351
+ for (const [index, example] of usage.examples.entries()) {
352
+ validateSchemaValue(definition.params_schema, example.params, `usage.examples[${index}].params`);
353
+ }
354
+ const releaseId = validateReleaseId(snapshot.release_id);
355
+ const calculated = abilityReleaseId(snapshot.plugin_version, definition, usage);
356
+ if (releaseId !== calculated)
357
+ fail('release_id does not match snapshot content', 'contract_invalid', 'release_id');
358
+ return {
359
+ schema: ABILITY_RELEASE_SCHEMA, plugin_version: snapshot.plugin_version,
360
+ release_id: releaseId, definition, usage,
361
+ };
362
+ }
363
+ export function parseAbilityIndex(value, expectedPublisher) {
364
+ const index = requiredRecord(value, 'ability index');
365
+ const publisher = requiredAid(index.publisher, 'publisher');
366
+ if (expectedPublisher !== undefined && publisher !== expectedPublisher)
367
+ fail('index publisher mismatch', 'contract_invalid', 'publisher');
368
+ if (index.schema !== ABILITY_INDEX_SCHEMA || !Array.isArray(index.capabilities))
369
+ fail('invalid ability index', 'contract_invalid');
370
+ const capabilities = [];
371
+ const keys = new Set();
372
+ for (const raw of index.capabilities) {
373
+ const entry = requiredRecord(raw, 'capability');
374
+ const path = requiredPath(entry.path, 'capability.path');
375
+ const definitionId = requiredDefinitionId(entry.definition_id, 'capability.definition_id');
376
+ const releaseId = validateReleaseId(entry.release_id);
377
+ const key = `${path}\0${definitionId}\0${releaseId}`;
378
+ if (keys.has(key))
379
+ fail('duplicate ability index entry', 'contract_invalid', 'capabilities');
380
+ keys.add(key);
381
+ const detailRef = validateReference(entry.detail_ref, publisher, `ability/definitions/${definitionId}/${path}.json`, 'detail_ref');
382
+ const usageRef = entry.usage_ref === undefined ? undefined
383
+ : validateReference(entry.usage_ref, publisher, `ability/releases/${releaseId}/${path}.usage.json`, 'usage_ref');
384
+ let devices;
385
+ if (entry.devices !== undefined) {
386
+ if (!Array.isArray(entry.devices) || entry.devices.length === 0 || entry.devices.some(device => typeof device !== 'string' || !device.trim())) {
387
+ fail('invalid capability devices', 'contract_invalid', 'devices');
388
+ }
389
+ devices = [...new Set(entry.devices.map(device => device.trim()))].sort();
390
+ }
391
+ capabilities.push({
392
+ ...entry, path, definition_id: definitionId, release_id: releaseId,
393
+ detail_ref: detailRef, ...(usageRef ? { usage_ref: usageRef } : {}),
394
+ ...(devices ? { devices } : {}),
395
+ });
396
+ }
397
+ return { ...index, schema: ABILITY_INDEX_SCHEMA, publisher, capabilities };
398
+ }
399
+ export function abilitySummary(definition, publisherAid, releaseId, pluginVersion) {
400
+ requiredAid(publisherAid, 'publisher');
401
+ validateReleaseId(releaseId);
402
+ return {
403
+ path: definition.path, name: definition.name, effects: definition.effects,
404
+ require_confirm: definition.require_confirm, auth_required: definition.auth_required,
405
+ allowed_modes: definition.allowed_modes, idempotency: definition.idempotency,
406
+ dedupe_retention_seconds: definition.dedupe_retention_seconds,
407
+ aggregation: definition.aggregation, definition_id: definition.definition_id,
408
+ summary: definition.description, ...(pluginVersion ? { plugin_version: pluginVersion } : {}),
409
+ release_id: releaseId,
410
+ detail_ref: `${publisherAid}:/ability/definitions/${definition.definition_id}/${definition.path}.json`,
411
+ usage_ref: `${publisherAid}:/ability/releases/${releaseId}/${definition.path}.usage.json`,
412
+ };
413
+ }
414
+ export function buildAbilityIndex(input) {
415
+ const publisher = requiredAid(input.publisherAid, 'publisherAid');
416
+ const value = {
417
+ schema: ABILITY_INDEX_SCHEMA, publisher, version: input.version ?? '1.0.0',
418
+ ...(input.catalogRevision !== undefined ? { catalog_revision: input.catalogRevision } : {}),
419
+ ...(input.skillRef ? { skill_ref: input.skillRef } : {}),
420
+ ...(input.skillVersion ? { skill_version: input.skillVersion } : {}),
421
+ capabilities: input.capabilities,
422
+ updated_at: input.updatedAt ?? new Date().toISOString(),
423
+ };
424
+ return parseAbilityIndex(value, publisher);
425
+ }
426
+ /** Caller-side L2 accumulator, matching EvolApp's per-device aggregation. */
427
+ export class AbilityDiscoveryAccumulator {
428
+ expected;
429
+ protocol;
430
+ devices = new Set();
431
+ capabilities = new Map();
432
+ capabilityDevices = new Map();
433
+ constructor(expected) {
434
+ this.expected = expected;
435
+ }
436
+ add(response, metadata) {
437
+ if (metadata.senderAid !== this.expected.publisherAid || metadata.encrypted !== true || !metadata.senderDeviceId?.trim())
438
+ return false;
439
+ const payload = response;
440
+ if (!isJsonObject(payload) || payload.type !== 'ability' || payload.role !== 'result'
441
+ || payload.call_id !== this.expected.callId || payload.operation_id !== this.expected.operationId
442
+ || payload.ability_path !== 'protocol/discover')
443
+ return false;
444
+ try {
445
+ validateAbilityResult(payload, {
446
+ callId: this.expected.callId, operationId: this.expected.operationId,
447
+ abilityPath: 'protocol/discover',
448
+ });
449
+ if (payload.ok !== true)
450
+ return false;
451
+ const result = requiredRecord(payload.result, 'discover.result');
452
+ const protocol = requiredRecord(result.protocol, 'discover.protocol');
453
+ if (protocol.spec_version !== ABILITY_SPEC_VERSION || !Array.isArray(result.capabilities))
454
+ return false;
455
+ if (this.protocol && canonicalJson(this.protocol) !== canonicalJson(protocol))
456
+ return false;
457
+ this.protocol ??= protocol;
458
+ const deviceId = metadata.senderDeviceId.trim();
459
+ this.devices.add(deviceId);
460
+ for (const raw of result.capabilities) {
461
+ if (!isJsonObject(raw))
462
+ continue;
463
+ try {
464
+ const capability = parsePublishedCapability(raw, metadata.senderAid);
465
+ const key = `${capability.path}\0${capability.definition_id}\0${capability.release_id}`;
466
+ const { devices: _ignored, ...withoutDevices } = capability;
467
+ this.capabilities.set(key, withoutDevices);
468
+ const devices = this.capabilityDevices.get(key) ?? new Set();
469
+ devices.add(deviceId);
470
+ this.capabilityDevices.set(key, devices);
471
+ }
472
+ catch {
473
+ // EvolApp skips malformed capability rows while retaining the response.
474
+ }
475
+ }
476
+ return true;
477
+ }
478
+ catch {
479
+ // A malformed response is ignored by the Flutter accumulator.
480
+ return false;
481
+ }
482
+ }
483
+ get result() {
484
+ if (!this.protocol)
485
+ return undefined;
486
+ const capabilities = [...this.capabilities.keys()].sort().map(key => ({
487
+ ...this.capabilities.get(key),
488
+ devices: [...(this.capabilityDevices.get(key) ?? [])].sort(),
489
+ }));
490
+ return { protocol: this.protocol, devices: [...this.devices].sort(), capabilities };
491
+ }
492
+ }
493
+ function parsePublishedCapability(value, publisherAid) {
494
+ const row = requiredRecord(value, 'capability');
495
+ const path = requiredPath(row.path, 'path');
496
+ const definitionId = requiredDefinitionId(row.definition_id);
497
+ const releaseId = validateReleaseId(row.release_id);
498
+ const detailRef = validateReference(row.detail_ref, publisherAid, `ability/definitions/${definitionId}/${path}.json`, 'detail_ref');
499
+ const usageRef = row.usage_ref === undefined ? undefined
500
+ : validateReference(row.usage_ref, publisherAid, `ability/releases/${releaseId}/${path}.usage.json`, 'usage_ref');
501
+ return { ...row, path, definition_id: definitionId, release_id: releaseId, detail_ref: detailRef, ...(usageRef ? { usage_ref: usageRef } : {}) };
502
+ }
503
+ export function validateAbilityResult(value, expected) {
504
+ const payload = requiredRecord(value, 'result');
505
+ if (payload.type !== 'ability' || !['ack', 'result'].includes(String(payload.role)))
506
+ fail('invalid ability response');
507
+ if (payload.call_id !== expected.callId || payload.operation_id !== expected.operationId)
508
+ fail('ability response correlation mismatch', 'contract_changed');
509
+ checkNoTransportFields(payload);
510
+ if (payload.role === 'ack') {
511
+ // EvolApp's pending replay ACK omits ability_path. Fields which are
512
+ // present still have to match this attempt; ACK never completes it.
513
+ if ((payload.ability_path !== undefined && payload.ability_path !== expected.abilityPath)
514
+ || (payload.definition_id !== undefined && expected.definitionId !== undefined && payload.definition_id !== expected.definitionId)) {
515
+ fail('ability response contract mismatch', 'contract_changed');
516
+ }
517
+ if (payload.execution_state !== 'pending' || 'ok' in payload || 'result' in payload || 'error' in payload) {
518
+ fail('invalid ability ack', 'contract_invalid');
519
+ }
520
+ return payload;
521
+ }
522
+ if (payload.ability_path !== expected.abilityPath || (expected.definitionId !== undefined && payload.definition_id !== expected.definitionId)) {
523
+ fail('ability response contract mismatch', 'contract_changed');
524
+ }
525
+ if (typeof payload.ok !== 'boolean' || !['completed', 'not_executed', 'unknown'].includes(String(payload.execution_state)))
526
+ fail('invalid ability result', 'contract_invalid');
527
+ if (payload.ok === true) {
528
+ if (!Object.prototype.hasOwnProperty.call(payload, 'result') || Object.prototype.hasOwnProperty.call(payload, 'error')
529
+ || payload.execution_state !== 'completed')
530
+ fail('successful result must contain a completed result only', 'contract_invalid');
531
+ }
532
+ else {
533
+ if (!isJsonObject(payload.error) || typeof payload.error.code !== 'string' || !payload.error.code
534
+ || typeof payload.error.message !== 'string' || Object.prototype.hasOwnProperty.call(payload, 'result')) {
535
+ fail('failed result must contain only error', 'contract_invalid');
536
+ }
537
+ // EvolApp can withhold an already completed result after its delivery
538
+ // authorization expires. Preserve the state: this error is not retry-safe.
539
+ }
540
+ return payload;
541
+ }
542
+ export function operationKey(callerAid, providerAid, operationId) {
543
+ return sha256Hex(canonicalJson([callerAid, providerAid, operationId]));
544
+ }
545
+ export function operationFingerprint(call) {
546
+ return sha256Hex(canonicalJson({ path: call.ability_path, definition_id: call.definition_id ?? null, params: call.params, async: call.async ?? false }));
547
+ }
@@ -0,0 +1,79 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { abilityAssert, AbilityError } from './types.js';
4
+ import { isHClassPath, isLClassPath, isSameOrDescendant } from '../core/permission/protected-paths.js';
5
+ import { ABILITY_COMMANDS, parseAbilityOptions, parseAbilityWait, abilityCapabilities, abilityCommandSchema } from './command-contract.js';
6
+ /** Parse again in the daemon so the delegated argv is the operation authority. */
7
+ export function parseAbilityArgv(argv, context = {}) {
8
+ abilityAssert(Array.isArray(argv) && argv[0] === 'ability', 'ARGUMENT_INVALID', 'Expected ability command');
9
+ const [, operation, ...args] = argv;
10
+ abilityAssert(Object.hasOwn(ABILITY_COMMANDS, operation), 'ACTION_UNSUPPORTED', 'Unknown ability command');
11
+ const { values, positional } = parseAbilityOptions(args, ABILITY_COMMANDS[operation]);
12
+ let input = {};
13
+ if (values.file) {
14
+ const file = fs.realpathSync(path.resolve(context.baseDirectory ?? process.cwd(), values.file));
15
+ if (context.roots)
16
+ abilityAssert(context.roots.some(root => isSameOrDescendant(file, fs.realpathSync(root))), 'FILE_DENIED', 'Input must be inside the delegated project or session TMPDIR', 403);
17
+ abilityAssert(!isHClassPath(file) && !isLClassPath(file), 'FILE_DENIED', 'Management input must be outside protected configuration and credential paths', 403);
18
+ abilityAssert(fs.statSync(file).isFile() && fs.statSync(file).size <= 1024 * 1024, 'INPUT_TOO_LARGE', 'Input file must be JSON under 1 MiB');
19
+ input = JSON.parse(fs.readFileSync(file, 'utf8'));
20
+ abilityAssert(input && typeof input === 'object' && !Array.isArray(input), 'ARGUMENT_INVALID', 'Input must be an object');
21
+ }
22
+ if (operation === 'secret' || operation === 'secrets')
23
+ abilityAssert(values.stdin === 'true' && !values.file && values.slot && values.revision, 'SECRET_STDIN_REQUIRED', 'Secrets require --slot, --revision and --stdin; no plaintext input file');
24
+ else
25
+ abilityAssert(!values.stdin, 'ARGUMENT_INVALID', '--stdin is supported only for secrets');
26
+ if (values.revision)
27
+ abilityAssert(Number.isSafeInteger(Number(values.revision)) && Number(values.revision) > 0, 'ARGUMENT_INVALID', 'Revision must be a positive integer');
28
+ return { operation, aid: values.aid, self: values.self === 'true', ...(operation === 'preview' ? { source: positional[0], instanceId: input.instanceId } : { instanceId: positional[0], id: positional[0] }),
29
+ ...(values.wait || values['wait-publication'] ? { waitMs: parseAbilityWait(values.wait ?? values['wait-publication']) } : {}),
30
+ commandId: values['command-id'], input: { ...input, ...(values['acknowledge-external-data'] ? { acknowledgeExternalData: true } : {}), ...(values.slot ? { slot: values.slot } : {}), ...(values.revision ? { expectedRevision: Number(values.revision) } : {}), ...(values['command-id'] ? { commandId: values['command-id'] } : {}) } };
31
+ }
32
+ export async function executeAbilityManagement(service, actor, request, context) {
33
+ abilityAssert(request && typeof request.operation === 'string', 'REQUEST_INVALID', 'Operation required');
34
+ if (request.operation === 'capabilities')
35
+ return abilityCapabilities();
36
+ if (request.operation === 'schema')
37
+ return abilityCommandSchema(request.id);
38
+ if (request.operation === 'targets')
39
+ return service.targets(actor);
40
+ abilityAssert(!(request.self && request.aid), 'ARGUMENT_INVALID', '--aid and --self are mutually exclusive');
41
+ if (request.self) {
42
+ abilityAssert(context?.selfAid, 'SELF_UNAVAILABLE', 'No authenticated self AID is available');
43
+ request = { ...request, aid: context.selfAid };
44
+ }
45
+ abilityAssert(typeof request.aid === 'string' && request.aid.length <= 512, 'AID_REQUIRED', 'Select a managed AID');
46
+ const aid = request.aid;
47
+ if (request.operation === 'context')
48
+ return { ...await service.context(actor, aid), selfAid: context?.selfAid, authentication: context?.authentication ?? 'unspecified' };
49
+ if (request.operation === 'status')
50
+ return service.status(actor, aid, request.instanceId);
51
+ if (request.operation === 'doctor')
52
+ return service.doctor(actor, aid, request.instanceId);
53
+ if (request.operation === 'list')
54
+ return service.list(actor, aid);
55
+ if (request.operation === 'show')
56
+ return service.show(actor, aid, request.instanceId);
57
+ if (request.operation === 'history')
58
+ return service.history(actor, aid, request.instanceId);
59
+ if (request.operation === 'approvals')
60
+ return service.approvals(actor, aid);
61
+ if (request.operation === 'job')
62
+ return service.job(actor, aid, request.id, request.commandId);
63
+ if (request.operation === 'invocation')
64
+ return service.invocation(actor, aid, request.id);
65
+ if (request.operation === 'preview')
66
+ return service.preview(actor, aid, request.source, request.instanceId);
67
+ const input = request.input ?? {};
68
+ if (request.operation === 'unpublish') {
69
+ abilityAssert(input.paths === undefined || Array.isArray(input.paths) && input.paths.length === 0, 'ARGUMENT_INVALID', 'unpublish withdraws all paths; use publish for partial selection');
70
+ return service.submit(actor, aid, 'publish', { ...input, paths: [], instanceId: request.instanceId });
71
+ }
72
+ if (request.operation === 'secret' || request.operation === 'secrets')
73
+ return service.submit(actor, aid, 'configure', { commandId: input.commandId, expectedRevision: input.expectedRevision, instanceId: request.instanceId, acknowledgeExternalData: input.acknowledgeExternalData, secret: { slot: input.slot, value: input.value } });
74
+ return service.submit(actor, aid, request.operation, { ...input, ...(request.instanceId ? { instanceId: request.instanceId } : {}) });
75
+ }
76
+ export function abilityFailure(error) {
77
+ return error instanceof AbilityError ? { ok: false, status: error.status, code: error.code, error: error.message }
78
+ : { ok: false, status: 400, code: 'ABILITY_FAILED', error: 'Ability operation failed; check package, input and daemon diagnostics' };
79
+ }