evolcore 0.0.42-test.0 → 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 +31 -2
  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,450 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { gzipSync } from 'node:zlib';
5
+ import Ajv from 'ajv';
6
+ import { getPackageRoot } from '../paths.js';
7
+ import { isHClassPath, isLClassPath, isSameOrDescendant } from '../core/permission/protected-paths.js';
8
+ import { abilityTemp, packageFile, abilityPackageFiles, packageDigest, validateAbilityPackage, materializeDefinition, abilityExecutableEntry } from './package.js';
9
+ import { processRuntimeCommand, checkEnvironment } from './environment.js';
10
+ import { buildProcessRpcArtifact, toolchainReport } from './toolchain.js';
11
+ import { ABILITY_DEV_COMMANDS, parseAbilityOptions } from './command-contract.js';
12
+ import { abilityAssert, AbilityError } from './types.js';
13
+ const PROJECT = 'ability-project.json';
14
+ const RECEIPT = '.ability-build.json';
15
+ const MAX_BYTES = 32 * 1024 * 1024;
16
+ const ajv = new Ajv({ allErrors: true, strict: false, addUsedSchema: false });
17
+ function writeJson(file, value) { fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n'); }
18
+ function json(file) {
19
+ abilityAssert(fs.existsSync(file), 'PROJECT_FILE_MISSING', 'Required file is missing: ' + file);
20
+ abilityAssert(fs.statSync(file).isFile() && fs.statSync(file).size <= 1024 * 1024, 'PROJECT_INVALID', 'Expected a JSON file under 1 MiB: ' + file);
21
+ try {
22
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
23
+ }
24
+ catch {
25
+ throw new AbilityError('PROJECT_JSON_INVALID', 'Invalid JSON file: ' + file);
26
+ }
27
+ }
28
+ function unprotected(file) {
29
+ abilityAssert(!isHClassPath(file) && !isLClassPath(file), 'FILE_DENIED', 'Development files must be outside protected configuration and credential paths', 403);
30
+ }
31
+ function sourceFile(root, ref) {
32
+ const file = packageFile(root, ref);
33
+ unprotected(file);
34
+ let cursor = file;
35
+ while (cursor !== root) {
36
+ if (fs.existsSync(cursor))
37
+ abilityAssert(!fs.lstatSync(cursor).isSymbolicLink(), 'PROJECT_INVALID', 'Project references must not use symbolic links');
38
+ cursor = path.dirname(cursor);
39
+ }
40
+ return file;
41
+ }
42
+ function projectAt(directory) {
43
+ const root = fs.realpathSync(path.resolve(directory));
44
+ unprotected(root);
45
+ const project = json(sourceFile(root, PROJECT));
46
+ const validate = ajv.compile(json(path.join(getPackageRoot(), 'kits/schemas/ability-project.schema.1.json')));
47
+ abilityAssert(validate(project), 'PROJECT_INVALID', 'ability-project.json: ' + ajv.errorsText(validate.errors));
48
+ const manifest = json(sourceFile(root, 'ability-plugin.json'));
49
+ const validateManifest = ajv.compile(json(path.join(getPackageRoot(), 'kits/schemas/ability-plugin.schema.1.json')));
50
+ abilityAssert(validateManifest(manifest), 'MANIFEST_INVALID', ajv.errorsText(validateManifest.errors));
51
+ abilityAssert(Array.isArray(manifest.abilities) && manifest.runtime, 'PROJECT_INVALID', 'Development project requires a runtime manifest');
52
+ const language = project.language ?? (manifest.runtime.kind === 'node-subprocess' ? 'node' : manifest.runtime.language);
53
+ abilityAssert(language === (manifest.runtime.kind === 'node-subprocess' ? 'node' : manifest.runtime.language), 'PROJECT_INVALID', 'Project language must match manifest runtime');
54
+ if (manifest.runtime.kind === 'node-subprocess')
55
+ abilityAssert(manifest.runtime.entry === 'dist/main.mjs', 'PROJECT_INVALID', 'Node development projects require runtime.entry dist/main.mjs');
56
+ else {
57
+ const refs = processRuntimeCommand(manifest.runtime).filter(value => value.startsWith('package:')).map(value => value.slice('package:'.length));
58
+ abilityAssert(refs.length > 0 && refs.includes(project.build?.output ?? project.entry), 'PROJECT_INVALID', 'Runtime must reference the build output or prebuilt project entry');
59
+ abilityAssert(fs.existsSync(sourceFile(root, project.entry)), 'PROJECT_FILE_MISSING', 'Runtime entry is missing: ' + project.entry);
60
+ if (project.build) {
61
+ abilityAssert(project.build.kind === 'command' || project.build.kind === language, 'PROJECT_INVALID', 'Build kind must match runtime language');
62
+ abilityAssert(project.build.sources.includes(project.entry), 'PROJECT_INVALID', 'Build sources must include project.entry');
63
+ for (const ref of project.build.sources)
64
+ sourceFile(root, ref);
65
+ packageFile(root, project.build.output);
66
+ allowedReleaseName(project.build.output);
67
+ abilityAssert(!project.build.command?.some(arg => arg.includes('\0')), 'PROJECT_INVALID', 'Build command cannot contain a NUL byte');
68
+ }
69
+ }
70
+ return { root, project, manifest };
71
+ }
72
+ function definition(abilityPath, name, readiness = false) {
73
+ return { path: abilityPath, name, summary: readiness ? 'Returns service readiness without account or process details.' : 'TODO: describe the implemented behavior.',
74
+ params_schema: { type: 'object', properties: {}, additionalProperties: false },
75
+ result_schema: readiness ? { type: 'object', properties: { ready: { type: 'boolean' } }, required: ['ready'], additionalProperties: false } : { type: 'object' },
76
+ effects: ['state.read'], auth_required: true, require_confirm: true, idempotency: 'keyed', allowed_modes: ['explicit'], aggregation: 'none', dedupe_retention_seconds: 3600 };
77
+ }
78
+ function usage(abilityPath) {
79
+ return { schema: 'aun.ability.usage.v1', path: abilityPath, examples: [{ params: {} }], result_processing: ['Interpret the result according to the current result_schema.'] };
80
+ }
81
+ function safeDestination(output, root) {
82
+ const absolute = path.resolve(output);
83
+ unprotected(absolute);
84
+ abilityAssert(path.dirname(absolute) !== absolute && !isSameOrDescendant(root, absolute), 'OUTPUT_INVALID', 'Output must not replace the project or an ancestor');
85
+ let cursor = absolute;
86
+ while (!fs.existsSync(cursor))
87
+ cursor = path.dirname(cursor);
88
+ abilityAssert(fs.realpathSync(cursor) === cursor && !fs.lstatSync(cursor).isSymbolicLink(), 'OUTPUT_INVALID', 'Output must use a physical path');
89
+ return absolute;
90
+ }
91
+ function allowedReleaseName(ref) {
92
+ abilityAssert(!ref.split('/').some(part => part.startsWith('.') || /^(?:node_modules|tests?|credentials?|secrets?|delegation)(?:[._-]|$)/i.test(part)) &&
93
+ !/\.(?:pem|key|pfx|p12)$/i.test(ref) && ![PROJECT, RECEIPT].includes(ref), 'RELEASE_FILE_DENIED', 'Private, development or credential files cannot be included: ' + ref);
94
+ }
95
+ export function initAbilityProject(directory, options) {
96
+ abilityAssert(/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/.test(options.id ?? '') && options.id.length <= 128, 'PROJECT_INVALID', 'Use --id @publisher/plugin');
97
+ abilityAssert(typeof options.name === 'string' && options.name.length > 0 && options.name.length <= 120, 'PROJECT_INVALID', 'Use --name with 1–120 characters');
98
+ abilityAssert(['agent', 'host', 'both'].includes(options.target), 'PROJECT_INVALID', 'Use --target agent, host or both');
99
+ abilityAssert(!options.template || options.template === 'readiness', 'PROJECT_INVALID', 'Only the readiness template is available');
100
+ const language = options.language ?? 'node';
101
+ abilityAssert(['node', 'python', 'java', 'go', 'rust', 'custom'].includes(language), 'PROJECT_INVALID', 'Use --language node, python, java, go, rust or custom');
102
+ const root = path.resolve(directory);
103
+ unprotected(root);
104
+ abilityAssert(!fs.existsSync(root) || fs.lstatSync(root).isDirectory() && !fs.lstatSync(root).isSymbolicLink() && fs.readdirSync(root).length === 0, 'OUTPUT_EXISTS', 'Project destination must be empty');
105
+ fs.mkdirSync(path.join(root, 'src/handlers'), { recursive: true });
106
+ fs.mkdirSync(path.join(root, 'definitions'));
107
+ fs.mkdirSync(path.join(root, 'usages'));
108
+ const nativeEntry = 'bin/runner' + (process.platform === 'win32' ? '.exe' : '');
109
+ const runtimeEntry = language === 'java' ? 'bin/runner.jar' : language === 'python' ? 'runner.py' : nativeEntry;
110
+ const runtime = language === 'node'
111
+ ? { kind: 'node-subprocess', apiVersion: '1', entry: 'dist/main.mjs' }
112
+ : { kind: 'process-rpc', apiVersion: '1', language, entry: runtimeEntry };
113
+ const engineRange = { node: '>=22.16.0 <27.0.0', python: '>=3.9.0 <4.0.0', java: '>=17.0.0', go: '>=1.20.0', rust: '>=1.70.0', custom: '*' }[language];
114
+ const engines = { evolcore: '>=0.0.41 <1.0.0', [language]: engineRange };
115
+ const manifest = { schemaVersion: 'evolcore.ability-plugin/v1', id: options.id, version: '0.1.0', name: options.name,
116
+ description: 'Returns service readiness without account or process details.', license: 'MIT',
117
+ engines, runtime,
118
+ targets: options.target === 'both' ? ['agent', 'host'] : [options.target],
119
+ platforms: language === 'custom' ? [process.platform] : ['win32', 'linux', 'darwin'],
120
+ ...(language === 'custom' ? { architectures: [process.arch] } : {}), configSchema: 'config.schema.json',
121
+ permissions: { networkOrigins: [], workspace: 'none', secretSlots: [] },
122
+ limits: { executionTimeoutMs: 5000, maxConcurrency: 1, maxParamsBytes: 16384, maxResultBytes: 16384, maxLogBytesPerMinute: 32768 },
123
+ abilities: [{ handler: 'getReadiness', definition: 'definitions/status.json', usage: 'usages/status.json' }] };
124
+ writeJson(path.join(root, 'ability-plugin.json'), manifest);
125
+ const entry = { node: 'src/main.mjs', python: 'runner.py', java: 'src/Runner.java', go: 'src/main.go', rust: 'src/runner.rs', custom: runtimeEntry }[language];
126
+ const sources = language === 'java' ? [entry, 'src/Json.java'] : language === 'rust' ? [entry, 'src/json.rs'] : [entry];
127
+ const build = language === 'java' || language === 'go' || language === 'rust' ? { kind: language, sources, output: runtimeEntry } : undefined;
128
+ const pendingHandlers = language === 'custom' ? ['getReadiness'] : [];
129
+ writeJson(path.join(root, PROJECT), { schemaVersion: 'evolcore.ability-project/v1', language, entry, ...(build ? { build } : {}), handlers: { getReadiness: language === 'node' ? 'src/handlers/getReadiness.mjs' : entry }, pendingHandlers, files: ['README.md', 'LICENSE'] });
130
+ writeJson(path.join(root, 'config.schema.json'), { type: 'object', properties: {}, additionalProperties: false });
131
+ writeJson(path.join(root, 'definitions/status.json'), definition('self/status', 'Service readiness', true));
132
+ writeJson(path.join(root, 'usages/status.json'), usage('self/status'));
133
+ if (language === 'node') {
134
+ fs.writeFileSync(path.join(root, 'src/main.mjs'), "import handlers from './handlers.mjs';\nexport default { apiVersion: '1', handlers, async health() { return { ready: true }; } };\n");
135
+ fs.writeFileSync(path.join(root, 'src/handlers/getReadiness.mjs'), 'export default async function getReadiness(_params, ctx) {\n const status = await ctx.host.status();\n return { ready: status.ready };\n}\n');
136
+ }
137
+ else if (language !== 'custom') {
138
+ for (const ref of sources) {
139
+ fs.mkdirSync(path.dirname(path.join(root, ref)), { recursive: true });
140
+ fs.copyFileSync(path.join(getPackageRoot(), 'kits/runtime/ability-templates', language, path.basename(ref)), path.join(root, ref));
141
+ }
142
+ }
143
+ else {
144
+ fs.mkdirSync(path.dirname(path.join(root, entry)), { recursive: true });
145
+ fs.writeFileSync(path.join(root, entry), '# Provide an executable process-rpc entry, or configure a build.command argv and declared sources.\n');
146
+ }
147
+ fs.copyFileSync(path.join(getPackageRoot(), 'LICENSE'), path.join(root, 'LICENSE'));
148
+ fs.writeFileSync(path.join(root, 'README.md'), '# ' + options.name + '\n\nDevelopment project for ' + options.id + '.\n\nRuntime language: ' + language + '. RPC uses JSON lines on stdin/stdout; write logs to stderr.\nRun ec ability dev doctor --project <project>, then dev build, dev check <release> and dev pack.\nJava/Go/Rust use configured local compilers; missing environments fail clearly. EvolCore does not install runtimes, compilers or dependencies.\nBuild sources must be declared in ability-project.json. Custom builders use argv (no shell), with {project} and {output} as whole-argument placeholders.\nBuild commands and compilers are trusted local code, not an OS sandbox. Installation/enable/publish remain separately authorized.\n');
149
+ return { project: root, pluginId: manifest.id, version: manifest.version, language, runtime: manifest.runtime, targets: manifest.targets, pendingHandlers, next: 'ec ability dev doctor --project <project>' };
150
+ }
151
+ export function addProjectAbility(directory, abilityPath, handler, name) {
152
+ const { root, project, manifest } = projectAt(directory);
153
+ const template = definition(abilityPath, name);
154
+ materializeDefinition(template, 'development');
155
+ const ref = { handler, definition: 'definitions/' + handler + '.json', usage: 'usages/' + handler + '.json' };
156
+ abilityAssert(/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(handler ?? '') && !Object.hasOwn(project.handlers, handler), 'HANDLER_INVALID', 'Choose a unique --handler');
157
+ for (const row of manifest.abilities)
158
+ abilityAssert(json(sourceFile(root, row.definition)).path !== abilityPath, 'PATH_CONFLICT', 'Ability path is already declared');
159
+ // Validate the handler against the actual Manifest Schema, including reserved names.
160
+ const schema = json(path.join(getPackageRoot(), 'kits/schemas/ability-plugin.schema.1.json'));
161
+ abilityAssert(!schema.properties.abilities.items.properties.handler.not.enum.includes(handler), 'HANDLER_INVALID', 'Reserved handler name');
162
+ const node = manifest.runtime.kind === 'node-subprocess';
163
+ const module = node ? 'src/handlers/' + handler + '.mjs' : project.entry;
164
+ const addedFiles = [ref.definition, ref.usage, ...(node ? [module] : [])];
165
+ for (const file of addedFiles)
166
+ abilityAssert(!fs.existsSync(sourceFile(root, file)), 'OUTPUT_EXISTS', 'Refusing to replace existing project file: ' + file);
167
+ for (const file of addedFiles)
168
+ fs.mkdirSync(path.dirname(sourceFile(root, file)), { recursive: true });
169
+ writeJson(sourceFile(root, ref.definition), template);
170
+ writeJson(sourceFile(root, ref.usage), usage(abilityPath));
171
+ if (node)
172
+ fs.writeFileSync(sourceFile(root, module), 'export default async function ' + handler + '(_params, _ctx) {\n throw new Error("NOT_IMPLEMENTED");\n}\n');
173
+ manifest.abilities.push(ref);
174
+ project.handlers[handler] = module;
175
+ project.pendingHandlers.push(handler);
176
+ writeJson(sourceFile(root, 'ability-plugin.json'), manifest);
177
+ writeJson(sourceFile(root, PROJECT), project);
178
+ return { path: abilityPath, handler, module, pendingHandlers: project.pendingHandlers, implemented: false };
179
+ }
180
+ export function removeProjectAbility(directory, abilityPath) {
181
+ const { root, project, manifest } = projectAt(directory);
182
+ const index = manifest.abilities.findIndex(row => json(sourceFile(root, row.definition)).path === abilityPath);
183
+ abilityAssert(index >= 0 && manifest.abilities.length > 1, 'PROJECT_INVALID', 'Select a declared ability; at least one ability must remain');
184
+ const [removed] = manifest.abilities.splice(index, 1);
185
+ const module = project.handlers[removed.handler];
186
+ delete project.handlers[removed.handler];
187
+ project.pendingHandlers = project.pendingHandlers.filter(handler => handler !== removed.handler);
188
+ writeJson(sourceFile(root, 'ability-plugin.json'), manifest);
189
+ writeJson(sourceFile(root, PROJECT), project);
190
+ return { path: abilityPath, removedHandler: removed.handler, retainedFiles: [removed.definition, removed.usage, module].filter(Boolean),
191
+ publicationImpact: 'Future upgrades remove this path and invalidate its old contract grants; installed instances were not changed.' };
192
+ }
193
+ export function checkAbilityRelease(directory) {
194
+ const root = fs.realpathSync(path.resolve(directory));
195
+ unprotected(root);
196
+ const pkg = validateAbilityPackage(root, { kind: 'local', locator: root });
197
+ return { directory: root, valid: true, packageDigest: pkg.digest, pluginId: pkg.manifest.id, version: pkg.manifest.version, targets: pkg.manifest.targets,
198
+ files: abilityPackageFiles(root), abilities: pkg.definitions.map(row => ({ path: row.definition.path, handler: row.handler })), codeExecuted: false, businessBehaviorVerified: false };
199
+ }
200
+ export function buildAbilityProject(directory, output) {
201
+ const { root, project, manifest } = projectAt(directory);
202
+ abilityAssert(project.pendingHandlers.length === 0, 'HANDLERS_PENDING', 'Implement and review pending handlers before building: ' + project.pendingHandlers.join(', '));
203
+ abilityAssert(manifest.runtime.kind !== 'node-subprocess' || /\.(?:mjs|js)$/.test(project.entry), 'BUILD_UNSUPPORTED', 'Node projects require a JavaScript entry');
204
+ const destination = safeDestination(output ?? path.join(root, 'release'), root);
205
+ const receiptFile = sourceFile(root, RECEIPT);
206
+ let priorDigest;
207
+ if (fs.existsSync(destination)) {
208
+ const receipt = fs.existsSync(receiptFile) ? json(receiptFile) : undefined;
209
+ abilityAssert(receipt?.directory === destination && packageDigest(destination) === receipt.packageDigest, 'OUTPUT_CHANGED', 'Output must be absent or an unchanged previous build from this project');
210
+ priorDigest = receipt.packageDigest;
211
+ }
212
+ const stage = abilityTemp('ability-build-');
213
+ try {
214
+ const names = new Set();
215
+ const sources = new Set();
216
+ let bytes = 0;
217
+ const inputDigests = { [PROJECT]: createHash('sha256').update(fs.readFileSync(sourceFile(root, PROJECT))).digest('hex') };
218
+ const reserve = (name) => {
219
+ packageFile(stage, name);
220
+ allowedReleaseName(name);
221
+ abilityAssert(!names.has(name.toLowerCase()) && names.size < 4096, 'BUILD_CONFLICT', 'Duplicate or excessive release files: ' + name);
222
+ names.add(name.toLowerCase());
223
+ };
224
+ const input = (from) => {
225
+ const source = sourceFile(root, from);
226
+ sources.add(source);
227
+ const stat = fs.statSync(source);
228
+ bytes += stat.size;
229
+ abilityAssert(stat.isFile() && bytes <= MAX_BYTES, 'PACKAGE_TOO_LARGE', 'Build requires regular files totaling at most 32 MiB');
230
+ const content = fs.readFileSync(source);
231
+ inputDigests[from] = createHash('sha256').update(content).digest('hex');
232
+ return content;
233
+ };
234
+ const copy = (from, to = from) => {
235
+ reserve(to);
236
+ const content = input(from);
237
+ const target = packageFile(stage, to);
238
+ fs.mkdirSync(path.dirname(target), { recursive: true });
239
+ fs.writeFileSync(target, content);
240
+ };
241
+ copy('ability-plugin.json');
242
+ copy(manifest.configSchema);
243
+ if (manifest.runtime.kind === 'node-subprocess') {
244
+ copy(project.entry, manifest.runtime.entry);
245
+ const handlers = [];
246
+ for (const [index, row] of manifest.abilities.entries()) {
247
+ copy(row.definition);
248
+ copy(row.usage);
249
+ const module = project.handlers[row.handler];
250
+ abilityAssert(typeof module === 'string' && /\.(?:mjs|js)$/.test(module), 'HANDLER_INVALID', 'Missing prebuilt handler module: ' + row.handler);
251
+ copy(module, 'dist/handlers/' + row.handler + '.mjs');
252
+ handlers.push('import handler' + index + ' from ' + JSON.stringify('./handlers/' + row.handler + '.mjs') + ';');
253
+ }
254
+ reserve('dist/handlers.mjs');
255
+ fs.writeFileSync(path.join(stage, 'dist/handlers.mjs'), handlers.join('\n') + '\nexport default { ' + manifest.abilities.map((row, index) => JSON.stringify(row.handler) + ': handler' + index).join(', ') + ' };\n');
256
+ }
257
+ else {
258
+ for (const row of manifest.abilities) {
259
+ copy(row.definition);
260
+ copy(row.usage);
261
+ }
262
+ if (project.build) {
263
+ reserve(project.build.output);
264
+ const compilation = abilityTemp('ability-compile-');
265
+ try {
266
+ const snapshot = path.join(compilation, 'sources');
267
+ fs.mkdirSync(snapshot);
268
+ for (const ref of project.build.sources) {
269
+ const target = packageFile(snapshot, ref);
270
+ fs.mkdirSync(path.dirname(target), { recursive: true });
271
+ fs.writeFileSync(target, input(ref));
272
+ }
273
+ const artifact = packageFile(path.join(compilation, 'output'), project.build.output);
274
+ buildProcessRpcArtifact(project.build, snapshot, artifact, manifest);
275
+ const target = packageFile(stage, project.build.output);
276
+ fs.mkdirSync(path.dirname(target), { recursive: true });
277
+ fs.copyFileSync(artifact, target);
278
+ }
279
+ finally {
280
+ fs.rmSync(compilation, { recursive: true, force: true });
281
+ }
282
+ if (project.build.kind === 'go' || project.build.kind === 'rust' || abilityExecutableEntry(manifest)) {
283
+ manifest.platforms = [process.platform];
284
+ manifest.architectures = [process.arch];
285
+ }
286
+ writeJson(packageFile(stage, 'ability-plugin.json'), manifest);
287
+ }
288
+ const refs = new Set(processRuntimeCommand(manifest.runtime).filter(value => value.startsWith('package:')).map(value => value.slice('package:'.length)));
289
+ if (manifest.runtime.entry)
290
+ refs.add(manifest.runtime.entry);
291
+ for (const ref of refs)
292
+ if (ref !== project.build?.output)
293
+ copy(ref);
294
+ const executableEntry = abilityExecutableEntry(manifest);
295
+ if (executableEntry && process.platform !== 'win32')
296
+ fs.chmodSync(packageFile(stage, executableEntry), 0o755);
297
+ }
298
+ for (const file of project.files)
299
+ copy(file);
300
+ abilityAssert(![...sources].some(file => isSameOrDescendant(file, destination)), 'OUTPUT_INVALID', 'Output must not contain any build input');
301
+ const result = checkAbilityRelease(stage);
302
+ abilityAssert(result.files.length === names.size && result.files.every(file => names.has(file.toLowerCase())), 'BUILD_CONFLICT', 'Release files must match declared build outputs');
303
+ abilityAssert(Object.entries(inputDigests).every(([ref, digest]) => createHash('sha256').update(fs.readFileSync(sourceFile(root, ref))).digest('hex') === digest), 'PROJECT_CHANGED', 'Project changed during build; run build again');
304
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
305
+ const backupRoot = abilityTemp('ability-build-backup-');
306
+ const backup = path.join(backupRoot, 'release');
307
+ const hadOutput = fs.existsSync(destination);
308
+ let preserveBackup = false;
309
+ try {
310
+ abilityAssert(hadOutput === !!priorDigest, 'OUTPUT_CHANGED', 'Output appeared or disappeared during build');
311
+ if (hadOutput) {
312
+ fs.cpSync(destination, backup, { recursive: true, errorOnExist: true, force: false });
313
+ abilityAssert(packageDigest(backup) === priorDigest && packageDigest(destination) === priorDigest, 'OUTPUT_CHANGED', 'Output changed during backup');
314
+ }
315
+ // Only an unchanged, receipt-bound generated tree can reach replacement.
316
+ // Staging and backup stay in TMPDIR, including on a different volume.
317
+ try {
318
+ fs.rmSync(destination, { recursive: true, force: true });
319
+ fs.cpSync(stage, destination, { recursive: true, errorOnExist: true, force: false });
320
+ abilityAssert(packageDigest(destination) === result.packageDigest, 'OUTPUT_CHANGED', 'Release copy changed');
321
+ writeJson(receiptFile, { directory: destination, packageDigest: result.packageDigest, inputDigests });
322
+ }
323
+ catch (error) {
324
+ try {
325
+ fs.rmSync(destination, { recursive: true, force: true });
326
+ if (hadOutput)
327
+ fs.cpSync(backup, destination, { recursive: true, errorOnExist: true, force: false });
328
+ }
329
+ catch {
330
+ preserveBackup = true;
331
+ throw new AbilityError('OUTPUT_RESTORE_FAILED', 'Build failed; the previous release backup remains at ' + backup);
332
+ }
333
+ throw error;
334
+ }
335
+ }
336
+ finally {
337
+ if (!preserveBackup)
338
+ fs.rmSync(backupRoot, { recursive: true, force: true });
339
+ }
340
+ return { ...result, directory: destination, project: root, builder: project.build?.kind ?? 'declared-file-copy', pendingHandlers: [] };
341
+ }
342
+ finally {
343
+ fs.rmSync(stage, { recursive: true, force: true });
344
+ }
345
+ }
346
+ /** Deterministic USTAR regular-file archive, compatible with the production loader. */
347
+ function archive(root, files) {
348
+ const blocks = [];
349
+ let total = 1024;
350
+ const manifest = json(path.join(root, 'ability-plugin.json'));
351
+ const executable = abilityExecutableEntry(manifest);
352
+ for (const file of files) {
353
+ const content = fs.readFileSync(packageFile(root, file));
354
+ const header = Buffer.alloc(512);
355
+ const slash = file.lastIndexOf('/');
356
+ const short = file.length > 100 && slash > 0 ? file.slice(slash + 1) : file;
357
+ const prefix = short === file ? '' : file.slice(0, slash);
358
+ abilityAssert(Buffer.byteLength(short) <= 100 && Buffer.byteLength(prefix) <= 155, 'ARCHIVE_UNSUPPORTED', 'Package path exceeds USTAR name limits: ' + file);
359
+ const octal = (value, offset, length) => header.write(value.toString(8).padStart(length - 1, '0') + '\0', offset, length, 'ascii');
360
+ header.write(short, 0, 100, 'utf8');
361
+ octal(file === executable ? 0o755 : 0o644, 100, 8);
362
+ octal(0, 108, 8);
363
+ octal(0, 116, 8);
364
+ octal(content.length, 124, 12);
365
+ octal(0, 136, 12);
366
+ header.fill(32, 148, 156);
367
+ header.write('0', 156);
368
+ header.write('ustar\0', 257);
369
+ header.write('00', 263);
370
+ header.write(prefix, 345, 155, 'utf8');
371
+ header.write(header.reduce((sum, byte) => sum + byte, 0).toString(8).padStart(6, '0') + '\0 ', 148, 8, 'ascii');
372
+ const padding = Buffer.alloc((512 - content.length % 512) % 512);
373
+ total += 512 + content.length + padding.length;
374
+ abilityAssert(total <= MAX_BYTES, 'PACKAGE_TOO_LARGE', 'Archive including headers exceeds 32 MiB');
375
+ blocks.push(header, content, padding);
376
+ }
377
+ blocks.push(Buffer.alloc(1024));
378
+ return gzipSync(Buffer.concat(blocks), { level: 9 });
379
+ }
380
+ export function packAbilityProject(directory, output) {
381
+ const { root, project } = projectAt(directory);
382
+ abilityAssert(project.pendingHandlers.length === 0, 'HANDLERS_PENDING', 'Complete pending handlers before packing');
383
+ const receipt = json(sourceFile(root, RECEIPT));
384
+ abilityAssert(receipt.inputDigests && Object.entries(receipt.inputDigests).every(([ref, digest]) => createHash('sha256').update(fs.readFileSync(sourceFile(root, ref))).digest('hex') === digest), 'BUILD_STALE', 'Project inputs changed; rebuild before packing');
385
+ const result = checkAbilityRelease(receipt.directory);
386
+ abilityAssert(result.packageDigest === receipt.packageDigest, 'OUTPUT_CHANGED', 'Release changed after build; rebuild before packing');
387
+ for (const file of result.files)
388
+ allowedReleaseName(file);
389
+ const bytes = archive(result.directory, result.files);
390
+ abilityAssert(bytes.length <= MAX_BYTES, 'PACKAGE_TOO_LARGE', 'Compressed archive exceeds the 32 MiB loader limit');
391
+ const artifactDigest = createHash('sha256').update(bytes).digest('hex');
392
+ const destination = safeDestination(output ?? path.join(root, 'artifacts'), root);
393
+ abilityAssert(!isSameOrDescendant(destination, result.directory), 'OUTPUT_INVALID', 'Artifacts must be outside the release directory');
394
+ fs.mkdirSync(destination, { recursive: true });
395
+ const file = path.join(destination, result.pluginId.slice(1).replace('/', '-') + '-' + result.version + '-' + result.packageDigest.slice(0, 12) + '.tgz');
396
+ if (fs.existsSync(file))
397
+ abilityAssert(fs.readFileSync(file).equals(bytes), 'OUTPUT_CHANGED', 'Artifact filename already has different bytes');
398
+ else
399
+ fs.writeFileSync(file, bytes, { flag: 'wx' });
400
+ return { artifact: file, artifactDigest, packageDigest: result.packageDigest, bytes: bytes.length, files: result.files, uploaded: false };
401
+ }
402
+ export function versionAbilityProject(directory, version) {
403
+ abilityAssert(/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(version), 'VERSION_INVALID', 'Use an exact major.minor.patch version');
404
+ const { root, manifest } = projectAt(directory);
405
+ const previousVersion = manifest.version;
406
+ manifest.version = version;
407
+ writeJson(sourceFile(root, 'ability-plugin.json'), manifest);
408
+ return { pluginId: manifest.id, previousVersion, version, rebuildRequired: true, installedInstancesChanged: false };
409
+ }
410
+ export function doctorAbilityDevelopment(directory, language) {
411
+ abilityAssert(!language || ['node', 'python', 'java', 'go', 'rust', 'custom'].includes(language), 'ARGUMENT_INVALID', 'Unknown runtime language');
412
+ const current = directory || !language ? projectAt(directory ?? process.cwd()) : undefined;
413
+ const projectLanguage = current?.project.language ?? (current?.manifest.runtime.kind === 'node-subprocess' ? 'node' : current?.manifest.runtime.language);
414
+ abilityAssert(!current || !language || language === projectLanguage, 'ARGUMENT_INVALID', '--language must match the selected project; omit --project for a standalone language check');
415
+ const selected = (language ?? projectLanguage);
416
+ const build = current?.project.build;
417
+ const checks = !current ? toolchainReport(selected, { evolcore: '*' })
418
+ : build && build.kind !== 'command' ? toolchainReport(build.kind, current.manifest.engines) : [];
419
+ if (build?.kind === 'command')
420
+ checks.push(checkEnvironment(build.command[0]));
421
+ if (current) {
422
+ const command = current.manifest.runtime.kind === 'node-subprocess' ? [process.execPath] : processRuntimeCommand(current.manifest.runtime);
423
+ if (!command[0].startsWith('package:')) {
424
+ const args = selected === 'node' || selected === 'python' ? ['--version'] : selected === 'java' ? ['-version'] : undefined;
425
+ if (!checks.some(check => check.command === command[0]))
426
+ checks.push(checkEnvironment(command[0], args, current.manifest.engines[selected]));
427
+ }
428
+ else if (!build)
429
+ checks.push(checkEnvironment(sourceFile(current.root, command[0].slice('package:'.length))));
430
+ }
431
+ return { project: current?.root, language: selected, build: current?.project.build?.kind ?? 'declared-file-copy',
432
+ available: checks.every(check => check.available), checks, automaticallyInstallsEnvironment: false,
433
+ note: 'Only existing toolchains are inspected. No plugin code is executed, no dependencies are installed, and PATH is not modified.' };
434
+ }
435
+ export function executeAbilityDevelopment(args) {
436
+ const [operation, ...rest] = args;
437
+ abilityAssert(Object.hasOwn(ABILITY_DEV_COMMANDS, operation), 'ACTION_UNSUPPORTED', 'Unknown ability dev command');
438
+ const { values, positional } = parseAbilityOptions(rest, ABILITY_DEV_COMMANDS[operation]);
439
+ const project = values.project ?? process.cwd();
440
+ switch (operation) {
441
+ case 'init': return initAbilityProject(positional[0], { id: values.id, name: values.name, target: values.target, template: values.template, language: values.language });
442
+ case 'add-ability': return addProjectAbility(project, positional[0], values.handler, values.name ?? positional[0]);
443
+ case 'remove-ability': return removeProjectAbility(project, positional[0]);
444
+ case 'check': return checkAbilityRelease(positional[0]);
445
+ case 'doctor': return doctorAbilityDevelopment(values.project, values.language);
446
+ case 'build': return buildAbilityProject(project, values.out);
447
+ case 'pack': return packAbilityProject(project, values.out);
448
+ case 'version': return versionAbilityProject(project, positional[0]);
449
+ }
450
+ }
@@ -0,0 +1,75 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { execFile, spawnSync } from 'node:child_process';
5
+ import { abilityAssert } from './types.js';
6
+ const semver = createRequire(import.meta.url)('semver');
7
+ function isRelativeExecutablePath(command) {
8
+ return !path.isAbsolute(command) && /[\\/]/.test(command);
9
+ }
10
+ /** Locate an executable without a shell or a change to PATH. */
11
+ export function resolveExecutable(command, env = process.env) {
12
+ if (isRelativeExecutablePath(command))
13
+ return undefined;
14
+ const envPath = Object.entries(env).find(([key]) => key.toUpperCase() === 'PATH')?.[1] ?? '';
15
+ const dirs = path.isAbsolute(command) ? [''] : envPath.split(path.delimiter).map(dir => dir.trim().replace(/^"|"$/g, '')).filter(dir => dir && path.isAbsolute(dir));
16
+ const extensions = process.platform === 'win32' && !path.extname(command) ? ['', '.exe', '.com'] : [''];
17
+ for (const dir of dirs)
18
+ for (const ext of extensions) {
19
+ const file = dir ? path.join(dir, command + ext) : command + ext;
20
+ try {
21
+ if (!fs.statSync(file).isFile())
22
+ continue;
23
+ fs.accessSync(file, process.platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);
24
+ return file;
25
+ }
26
+ catch { /* check the next existing PATH entry */ }
27
+ }
28
+ return undefined;
29
+ }
30
+ export function processRuntimeCommand(runtime) {
31
+ if (runtime.command)
32
+ return [...runtime.command];
33
+ abilityAssert(runtime.entry, 'RUNTIME_COMMAND_INVALID', 'process-rpc requires entry or command');
34
+ const entry = 'package:' + runtime.entry;
35
+ switch (runtime.language) {
36
+ case 'node': return [process.execPath, entry];
37
+ case 'python': return [process.platform === 'win32' ? 'python' : 'python3', '-u', entry];
38
+ case 'java': return ['java', '-jar', entry];
39
+ default: return [entry];
40
+ }
41
+ }
42
+ export function checkEnvironment(command, args, required, env = process.env) {
43
+ if (isRelativeExecutablePath(command))
44
+ return { command, required, available: false, code: 'RUNTIME_COMMAND_INVALID', message: 'Use an executable name on PATH or an absolute executable path; relative executable paths are not supported.' };
45
+ const executable = resolveExecutable(command, env);
46
+ if (!executable)
47
+ return { command, required, available: false, code: 'RUNTIME_EXECUTABLE_MISSING', message: `Command '${command}' is not configured. Configure it externally; EvolCore does not install runtimes or change PATH.` };
48
+ if (!args)
49
+ return { command, executable, required, available: true };
50
+ const result = spawnSync(executable, args, { env: { ...env, RUSTUP_AUTO_INSTALL: '0', RUSTUP_NO_UPDATE_CHECK: '1' }, cwd: process.env.TMPDIR,
51
+ shell: false, windowsHide: true, encoding: 'utf8', timeout: 5000, maxBuffer: 65536 });
52
+ return versionCheck(command, executable, String(result.stdout ?? '') + '\n' + String(result.stderr ?? ''), !result.error && result.status === 0, required);
53
+ }
54
+ function versionCheck(command, executable, output, succeeded, required) {
55
+ const match = /(?:version\s+"?|Python\s+|(?:javac|jar)\s+|rustc\s+|go version go|\bv)(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(output);
56
+ const version = match ? `${Number(match[1])}.${Number(match[2] ?? 0)}.${Number(match[3] ?? 0)}` : undefined;
57
+ if (!succeeded || !version)
58
+ return { command, executable, required, available: false, code: 'RUNTIME_VERSION_UNAVAILABLE', message: `Unable to verify '${command}'. Configure a working runtime/toolchain externally.` };
59
+ if (required && (!semver.validRange(required) || !semver.satisfies(version, required)))
60
+ return { command, executable, version, required, available: false, code: 'ENGINE_UNSUPPORTED', message: `${command} ${version} does not satisfy ${required}.` };
61
+ return { command, executable, version, required, available: true };
62
+ }
63
+ /** Runtime activation must not block the daemon while an interpreter reports its version. */
64
+ export async function checkRuntimeEnvironment(command, args, required) {
65
+ const check = checkEnvironment(command);
66
+ if (!check.available || !args)
67
+ return check;
68
+ return new Promise(resolve => {
69
+ execFile(check.executable, args, { env: { ...process.env, RUSTUP_AUTO_INSTALL: '0', RUSTUP_NO_UPDATE_CHECK: '1' },
70
+ cwd: process.env.TMPDIR, windowsHide: true, timeout: 5000, maxBuffer: 65536, encoding: 'utf8' }, (error, stdout, stderr) => resolve(versionCheck(command, check.executable, stdout + '\n' + stderr, !error, required)));
71
+ });
72
+ }
73
+ export function assertEnvironment(check) {
74
+ abilityAssert(check.available && check.executable, check.code ?? 'RUNTIME_UNAVAILABLE', check.message ?? 'Runtime is unavailable', 503);
75
+ }