evolcore 0.0.42 → 0.0.43-test.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/bin/ec-safe-output.js +4 -1
  3. package/dist/ability/application-service.js +882 -0
  4. package/dist/ability/authorization.js +70 -0
  5. package/dist/ability/command-contract.js +105 -0
  6. package/dist/ability/daemon.js +137 -0
  7. package/dist/ability/development.js +450 -0
  8. package/dist/ability/environment.js +75 -0
  9. package/dist/ability/interop-v1.js +547 -0
  10. package/dist/ability/management.js +79 -0
  11. package/dist/ability/package.js +264 -0
  12. package/dist/ability/provider.js +73 -0
  13. package/dist/ability/publication.js +107 -0
  14. package/dist/ability/resources.js +106 -0
  15. package/dist/ability/runtime.js +212 -0
  16. package/dist/ability/secrets.js +47 -0
  17. package/dist/ability/store.js +112 -0
  18. package/dist/ability/toolchain.js +69 -0
  19. package/dist/ability/types.js +14 -0
  20. package/dist/ability/versions.js +32 -0
  21. package/dist/agents/baseagent.js +2 -2
  22. package/dist/agents/claude-runner.js +4 -0
  23. package/dist/agents/codex-runner.js +81 -17
  24. package/dist/agents/ecagent-plugin-lazy.js +41 -0
  25. package/dist/agents/ecagent-runner.js +18 -11
  26. package/dist/aun/ability-device-routing.js +12 -1
  27. package/dist/aun/aid/agentmd.js +2 -2
  28. package/dist/aun/aid/client.js +1 -1
  29. package/dist/aun/aid/identity.js +45 -0
  30. package/dist/aun/aid/index.js +1 -0
  31. package/dist/aun/aid/managed-operation.js +73 -2
  32. package/dist/channels/aun.js +64 -18
  33. package/dist/channels/builtin-plugins.js +14 -0
  34. package/dist/channels/dingtalk.js +78 -26
  35. package/dist/channels/feishu.js +89 -14
  36. package/dist/channels/qqbot.js +84 -19
  37. package/dist/channels/wechat.js +77 -19
  38. package/dist/channels/wecom.js +67 -22
  39. package/dist/cli/ability-command.js +92 -0
  40. package/dist/cli/aun-commands.js +124 -85
  41. package/dist/cli/daemon-commands.js +37 -85
  42. package/dist/cli/index.js +14 -0
  43. package/dist/cli/init.js +11 -13
  44. package/dist/cli/managed-command-guard.js +6 -0
  45. package/dist/cli/model.js +101 -104
  46. package/dist/cli/provider-command.js +6 -4
  47. package/dist/cli/restart-monitor.js +52 -11
  48. package/dist/cli/upgrade-command.js +102 -0
  49. package/dist/cli/version.js +1 -1
  50. package/dist/config/access-policy.js +4 -2
  51. package/dist/config/builtin-roles.js +1 -0
  52. package/dist/config/config-field-policy.js +4 -0
  53. package/dist/config/config-manager.js +7 -0
  54. package/dist/config/provider-ipc-service.js +10 -0
  55. package/dist/config/providers-config.js +12 -3
  56. package/dist/config/providers-management.js +45 -9
  57. package/dist/config/schema-migration.js +40 -22
  58. package/dist/contracts/ecweb-service-protocol.js +2 -1
  59. package/dist/core/agent-runtime.js +2 -1
  60. package/dist/core/auth/agent-delegation.js +21 -5
  61. package/dist/core/auth/auth-gateway.js +31 -9
  62. package/dist/core/auth/authorization-audit.js +52 -4
  63. package/dist/core/auth/delegation-authorization.js +140 -4
  64. package/dist/core/auth/operation-authorizer.js +114 -13
  65. package/dist/core/auth/operation-catalog.js +118 -4
  66. package/dist/core/baseagent-loader.js +14 -1
  67. package/dist/core/channel-loader.js +47 -9
  68. package/dist/core/channel-runtime.js +1 -1
  69. package/dist/core/command/agent-storage-menu.js +1 -1
  70. package/dist/core/command/cli-intent-parser.js +26 -13
  71. package/dist/core/command/command-handler.js +232 -76
  72. package/dist/core/command/connect-menu.js +10 -4
  73. package/dist/core/command/daemon-diagnostics.js +3 -3
  74. package/dist/core/command/data-root-resolver.js +2 -3
  75. package/dist/core/command/menu-catalog.js +10 -3
  76. package/dist/core/command/menu-handler.js +321 -46
  77. package/dist/core/command/menu-protocol.js +53 -7
  78. package/dist/core/command/pa-workspace-calendar.js +1 -2
  79. package/dist/core/command/pa-workspace-items.js +486 -0
  80. package/dist/core/command/pa-workspace-store.js +10 -1
  81. package/dist/core/command/slash-gate.js +2 -2
  82. package/dist/core/command/slash-handler.js +67 -25
  83. package/dist/core/contact-bind-registry.js +27 -0
  84. package/dist/core/daemon-control.js +3 -3
  85. package/dist/core/daemon-lifecycle.js +2 -1
  86. package/dist/core/event-bus.js +9 -2
  87. package/dist/core/handoff/ipc-registration.js +1 -0
  88. package/dist/core/host-snapshot.js +1 -2
  89. package/dist/core/initialization/service.js +32 -11
  90. package/dist/core/ipc-registration.js +18 -5
  91. package/dist/core/memory/consolidation-context.js +2 -2
  92. package/dist/core/message/aun-request-registry.js +99 -18
  93. package/dist/core/message/im-renderer.js +16 -11
  94. package/dist/core/message/message-admission.js +25 -20
  95. package/dist/core/message/message-bridge.js +21 -47
  96. package/dist/core/message/message-queue.js +3 -0
  97. package/dist/core/message/response-engine.js +7 -5
  98. package/dist/core/model/catalog-service.js +1 -1
  99. package/dist/core/permission/ec-command-parser.js +41 -9
  100. package/dist/core/permission/permission-result.js +1 -0
  101. package/dist/core/permission/protected-paths.js +25 -14
  102. package/dist/core/permission/tool-policy.js +108 -107
  103. package/dist/core/plugin-lifecycle.js +133 -0
  104. package/dist/core/runner-reload-transaction.js +4 -1
  105. package/dist/core/system-session/memory.js +16 -3
  106. package/dist/core/task/task-activity-store.js +50 -0
  107. package/dist/core/task/task-image-resources.js +140 -0
  108. package/dist/core/thread/ipc-operation.js +1 -1
  109. package/dist/core/thread/thread-service.js +0 -1
  110. package/dist/directory/canonical-digest.js +5 -3
  111. package/dist/directory/owner-directory-admission.js +22 -2
  112. package/dist/directory/owner-directory-cache.js +394 -60
  113. package/dist/directory/owner-directory-markdown.js +29 -2
  114. package/dist/directory/owner-directory-scope.js +35 -16
  115. package/dist/ecweb/basic-settings-service.js +4 -1
  116. package/dist/ecweb/pairing.js +41 -0
  117. package/dist/ecweb/providers-service.js +8 -1
  118. package/dist/{utils/ecweb-utils.js → ecweb/runtime/launch.js} +3 -27
  119. package/dist/ecweb/runtime/lifecycle.js +184 -0
  120. package/dist/{utils/ecweb-supervisor.js → ecweb/runtime/supervisor.js} +32 -27
  121. package/dist/index.js +34 -25
  122. package/dist/ipc.js +124 -7
  123. package/dist/response-system/engines/v1/proactive-flow.js +1 -1
  124. package/dist/trigger/authorization.js +2 -2
  125. package/dist/utils/atomic-write.js +24 -0
  126. package/dist/utils/avatar-upload.js +3 -1
  127. package/dist/utils/cross-platform.js +31 -2
  128. package/dist/utils/host-info.js +36 -0
  129. package/dist/utils/instance-registry.js +38 -11
  130. package/dist/utils/logger.js +9 -0
  131. package/dist/utils/{process-tree-stats.js → process-tree.js} +29 -0
  132. package/dist/utils/tool-summary.js +9 -1
  133. package/dist/utils/upgrade-jobs.js +96 -15
  134. package/dist/utils/windows-autostart.js +1 -1
  135. package/ecagent/README.md +19 -0
  136. package/ecagent/dist/harness/agent-harness.js +9 -0
  137. package/ecagent/dist/harness/env/nodejs.js +71 -11
  138. package/ecagent/dist/harness/env/windows-shell.d.ts +7 -0
  139. package/ecagent/dist/harness/env/windows-shell.js +132 -0
  140. package/kits/docs/aun/ABILITY_CALLING.md +38 -9
  141. package/kits/docs/evolcore/INDEX.md +5 -1
  142. package/kits/docs/evolcore/ability.md +181 -0
  143. package/kits/docs/evolcore/aid.md +20 -0
  144. package/kits/docs/evolcore/config.md +10 -6
  145. package/kits/docs/evolcore/menu-protocol.md +40 -1
  146. package/kits/docs/evolcore/provider.md +2 -2
  147. package/kits/docs/evolcore/tool-authorization.md +270 -0
  148. package/kits/runtime/ability-job.ps1 +41 -0
  149. package/kits/runtime/ability-runner.mjs +67 -0
  150. package/kits/runtime/ability-secret.ps1 +59 -0
  151. package/kits/runtime/ability-templates/go/main.go +59 -0
  152. package/kits/runtime/ability-templates/java/Json.java +67 -0
  153. package/kits/runtime/ability-templates/java/Runner.java +42 -0
  154. package/kits/runtime/ability-templates/python/runner.py +48 -0
  155. package/kits/runtime/ability-templates/rust/json.rs +87 -0
  156. package/kits/runtime/ability-templates/rust/runner.rs +35 -0
  157. package/kits/schemas/_meta.json +12 -1
  158. package/kits/schemas/ability-plugin.schema.1.json +107 -0
  159. package/kits/schemas/ability-project.schema.1.json +31 -0
  160. package/kits/schemas/agent-config.schema.16.json +20 -0
  161. package/kits/schemas/agent-config.schema.17.json +20 -0
  162. package/kits/schemas/agent-config.schema.18.json +917 -0
  163. package/kits/skills/.switches.json +4 -0
  164. package/kits/skills/aid-ability/SKILL.md +5 -4
  165. package/kits/skills/ec-ability/SKILL.md +67 -0
  166. package/kits/skills/ec-ability/references/contract-checklist.md +37 -0
  167. package/kits/skills/ec-ability/references/development.md +104 -0
  168. package/kits/skills/ec-ability/references/management.md +117 -0
  169. package/kits/skills/ec-ability/references/recovery.md +27 -0
  170. package/kits/skills/ec-ability/references/runtime-protocol.md +109 -0
  171. package/kits/skills/ec-ability/references/workflows.md +15 -0
  172. package/kits/skills/ec-service-proxy/SKILL.md +12 -0
  173. package/kits/skills/personal-assistant/SKILL.md +240 -6
  174. package/kits/skills/personal-assistant/references/02-bootstrap.md +78 -4
  175. package/kits/skills/personal-assistant/scripts/clean.mjs +397 -0
  176. package/kits/skills/personal-assistant/scripts/init.mjs +113 -25
  177. package/kits/skills/personal-assistant/scripts/lock.mjs +189 -0
  178. package/kits/skills/personal-assistant/scripts/migrate.mjs +35 -10
  179. package/kits/skills/personal-assistant/scripts/verify.mjs +2 -1
  180. package/kits/skills/personal-assistant/templates/persona-section.md +54 -0
  181. package/kits/skills/personal-assistant/triggers/ingest-daily.json +1 -1
  182. package/kits/templates/memory-consolidation/notes.md +1 -1
  183. package/kits/templates/system-fragments/channel.md +2 -1
  184. package/kits/templates/system-fragments/commands.md +1 -0
  185. package/package.json +5 -3
  186. package/dist/core/command/data-root-error.js +0 -10
  187. package/dist/utils/machine-info.js +0 -46
  188. package/dist/utils/process-tree-worker.js +0 -31
  189. package/dist/utils/windows-output.js +0 -36
@@ -12,10 +12,9 @@ import fs from 'fs';
12
12
  import path from 'path';
13
13
  import { spawnSync } from 'child_process';
14
14
  import { getPackageRoot, resolvePaths, isDevMode } from '../paths.js';
15
- import { isProcessRunning, killProcess, isWindows, findProcessesWithCommandLine } from './cross-platform.js';
15
+ import { isProcessRunning, killProcess, isWindows, findProcessesWithCommandLine, decodeWindowsOutput } from './cross-platform.js';
16
16
  import { getProcessSnapshot, getProcessStartTime, snapshotProcessState, startTimeMatches, } from './process-introspect.js';
17
17
  import { isConfirmedLeakedTestDaemon, runtimeHomeFromEnv } from './restart-safety.js';
18
- import { decodeWindowsOutput } from './windows-output.js';
19
18
  import { atomicWriteJson } from './atomic-write.js';
20
19
  // ── Helpers ──
21
20
  function instanceDir() {
@@ -34,25 +33,52 @@ function safeParseJson(filePath) {
34
33
  return null;
35
34
  }
36
35
  }
36
+ function lazySnapshot() {
37
+ let cached = null;
38
+ return {
39
+ get() {
40
+ cached ??= getProcessSnapshot();
41
+ return cached;
42
+ },
43
+ taken: () => cached !== null,
44
+ };
45
+ }
37
46
  /**
38
47
  * 判断一条实例记录是否仍在运行。
39
48
  *
40
- * 优先用进程快照:Windows 上逐个 pid 查启动时间要拉一次 PowerShell(约 0.4s),
41
- * 而启动路径上一次扫描就有十几条记录。快照不可用(macOS、CIM 失败)时回退到
42
- * 逐个查询——慢一些,但判定语义完全不变。
49
+ * 先做一次廉价的单 pid 存活探测:绝大多数启动场景下 instance 目录里只有本进程
50
+ * 刚写的记录,或者几条已经死掉的记录,此时完全不需要采集整张进程表(Windows 上
51
+ * 约 0.45s)。只有确认「它确实还活着」才需要创建时间来排除 PID 复用。
43
52
  */
44
- function isAlive(pid, recordedStartedAt, snapshot = getProcessSnapshot()) {
45
- const verdict = snapshotProcessState(snapshot, pid, recordedStartedAt);
46
- if (verdict !== 'unknown')
47
- return verdict === 'alive';
53
+ function isAlive(pid, recordedStartedAt, snapshot) {
54
+ if (pid === process.pid) {
55
+ // 自身直接比对(内部走 uptime 近似,不需要外部进程)。
56
+ const actual = getProcessStartTime(pid);
57
+ return actual === null ? true : startTimeMatches(recordedStartedAt, actual);
58
+ }
59
+ // 廉价前置探测:不存在就直接判定为死,省掉整张进程表。
48
60
  if (!isProcessRunning(pid))
49
61
  return false;
62
+ // 还活着才需要创建时间来排除 PID 复用。
63
+ const snap = snapshot.get();
64
+ const verdict = snapshotProcessState(snap, pid, recordedStartedAt);
65
+ if (verdict !== 'unknown') {
66
+ if (verdict === 'alive')
67
+ return true;
68
+ // 快照说「不在表里」,但单 pid 探测说还活着:以更保守的探测为准再确认一次。
69
+ if (!snapshotAvailable(snap))
70
+ return true;
71
+ }
50
72
  const actual = getProcessStartTime(pid);
51
73
  // 拿不到启动时间时保守认为是我们的进程(宁可误判活着,不误杀)
52
74
  if (actual === null)
53
75
  return true;
54
76
  return startTimeMatches(recordedStartedAt, actual);
55
77
  }
78
+ /** 快照是否可信到可以否定存活结论。 */
79
+ function snapshotAvailable(snapshot) {
80
+ return snapshot.complete;
81
+ }
56
82
  // ── Main record ──
57
83
  function mainFileName(pid) {
58
84
  return `main-${pid}.json`;
@@ -218,8 +244,9 @@ export function readAidLastActivity(pid) {
218
244
  * 损坏的 JSON 文件直接删除。aid-*.jsonl 在 scan 时不解析,由调用方按需读取。
219
245
  */
220
246
  export function scanInstances() {
221
- // 整个扫描共用一份进程快照:Windows 上每条记录单独查存活要各拉一次外部进程。
222
- const snapshot = getProcessSnapshot();
247
+ // 惰性快照:每条记录先做廉价的单 pid 存活探测,只有确实活着才需要整张进程表。
248
+ // 启动路径上绝大多数时候目录里只有本进程的记录或已死记录,这样可省掉约 0.45s。
249
+ const snapshot = lazySnapshot();
223
250
  const status = {
224
251
  mains: [],
225
252
  restartMonitors: [],
@@ -331,6 +331,15 @@ export function setLogLevel(level) {
331
331
  export function getLogLevel() {
332
332
  return currentLevel;
333
333
  }
334
+ /** Report daemon-owned stream gates without exposing its environment. */
335
+ export function getLogStreamStates() {
336
+ return {
337
+ messages: config.messageLog,
338
+ events: config.eventLog,
339
+ 'channel-in': config.channelLogs,
340
+ 'channel-out': config.channelLogs,
341
+ };
342
+ }
334
343
  /** Enable or disable channel boundary audit streams at runtime. */
335
344
  export function setChannelLogsEnabled(enabled) {
336
345
  const next = enabled === true;
@@ -1,5 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import { spawnSync } from 'child_process';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { isMainThread, parentPort, workerData } from 'node:worker_threads';
3
5
  import { parseCimDate } from './process-introspect.js';
4
6
  function runnerKind(name) {
5
7
  const normalized = name.toLowerCase();
@@ -289,3 +291,30 @@ export class ProcessTreeSampler {
289
291
  };
290
292
  }
291
293
  }
294
+ const port = parentPort;
295
+ if (!isMainThread && workerData === 'process-tree-sampler' && port) {
296
+ port.on('message', (message) => {
297
+ if (message?.type !== 'sample')
298
+ return;
299
+ const startedAt = performance.now();
300
+ try {
301
+ const metrics = readProcessMetrics();
302
+ if (metrics.length === 0)
303
+ throw new Error('process enumeration returned no metrics');
304
+ port.postMessage({
305
+ type: 'sample',
306
+ requestId: message.requestId,
307
+ metrics,
308
+ durationMs: round1(performance.now() - startedAt),
309
+ });
310
+ }
311
+ catch (error) {
312
+ port.postMessage({
313
+ type: 'sample-error',
314
+ requestId: message.requestId,
315
+ error: error instanceof Error ? error.message : String(error),
316
+ durationMs: round1(performance.now() - startedAt),
317
+ });
318
+ }
319
+ });
320
+ }
@@ -183,7 +183,15 @@ export function summarizeToolInput(toolName, input) {
183
183
  * credentials commonly embedded in shell commands or tool arguments.
184
184
  */
185
185
  export function summarizeToolInputForAudit(toolName, input) {
186
- return summarizeToolInput(toolName, input)
186
+ // The display summary intentionally stays short, but authorization audit
187
+ // needs enough command context to distinguish a real EC invocation from a
188
+ // search pattern that merely contains the token `ec`.
189
+ const summary = toolName === 'Bash' && typeof input?.command === 'string'
190
+ ? input.command.slice(0, 512)
191
+ + (typeof input.description === 'string' && input.description
192
+ ? ` | ${input.description}` : '')
193
+ : summarizeToolInput(toolName, input);
194
+ return summary
187
195
  .replace(/\b([A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL)[A-Z0-9_]*)\s*=\s*(?:"[^"]*"|'[^']*'|\S+)/gi, '$1=[REDACTED]')
188
196
  .replace(/\b(authorization\s*:\s*Bearer\s+)[^\s"',;]+/gi, '$1[REDACTED]')
189
197
  .replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|authorization|cookie)\s*([=:])\s*(?:"[^"]*"|'[^']*'|\S+)/gi, '$1$2[REDACTED]')
@@ -48,6 +48,17 @@ export function readUpgradeJob(jobId) {
48
48
  return null;
49
49
  }
50
50
  }
51
+ /** All authenticated management surfaces query the same current/last task. */
52
+ export async function readCurrentUpgradeJob() {
53
+ if (!fs.existsSync(directory()))
54
+ return null;
55
+ return withFileLock(path.join(directory(), 'active.lock'), async () => {
56
+ const existing = jobs();
57
+ const active = reconcileUpgradeJobs(existing);
58
+ const latest = existing.sort((left, right) => right.updatedAt - left.updatedAt)[0];
59
+ return active ? readUpgradeJob(active.jobId) ?? active : latest ? readUpgradeJob(latest.jobId) ?? latest : null;
60
+ });
61
+ }
51
62
  function save(job) {
52
63
  atomicWriteJson(jobPath(job.jobId), job);
53
64
  }
@@ -111,6 +122,62 @@ export function upgradeJobView(job) {
111
122
  const { target: _target, npmConfig: _npmConfig, requestKey: _requestKey, scopeKey: _scopeKey, ownerPid: _ownerPid, monitorPid: _monitorPid, launcherPid: _launcherPid, ...view } = job;
112
123
  return view;
113
124
  }
125
+ export function parseUpgradeMode(args) {
126
+ if (args !== undefined && (!args || typeof args !== 'object' || Array.isArray(args))) {
127
+ throw Object.assign(new Error('无效的更新参数'), { code: 'INVALID_ARGUMENT' });
128
+ }
129
+ const value = (args ?? {});
130
+ const mode = value.mode ?? 'check';
131
+ if (!['check', 'update', 'status'].includes(String(mode)) || typeof mode !== 'string'
132
+ || Object.keys(value).some(key => !['mode', 'context'].includes(key))) {
133
+ throw Object.assign(new Error('更新仅接受 mode=check/update/status,不接受 jobId'), { code: 'INVALID_ARGUMENT' });
134
+ }
135
+ return mode;
136
+ }
137
+ /** One business service for Menu, slash, local CLI and ECWeb. Authorize first. */
138
+ export async function executeUpgradeAction(mode, requestId, scope) {
139
+ if (mode === 'check') {
140
+ const distTag = resolveUpgradeDistTag();
141
+ const results = await refreshManagedPackageVersions(VERSION_INFO_PACKAGES, {
142
+ source: 'upgrade-check', distTag, includeUninstalled: true,
143
+ });
144
+ return structuredUpgradeCheck(results, distTag);
145
+ }
146
+ if (mode === 'status') {
147
+ const job = await readCurrentUpgradeJob();
148
+ if (!job)
149
+ throw Object.assign(new Error('当前没有升级任务'), { code: 'NO_ACTIVE_UPDATE' });
150
+ return upgradeJobView(job);
151
+ }
152
+ const result = await startUpgradeJob(requestId, scope);
153
+ return { ...upgradeJobView(result.job), reused: result.reused };
154
+ }
155
+ /** Only presentation differs between text commands and Menu/ECWeb JSON. */
156
+ export function formatUpgradeResult(data) {
157
+ if ('jobId' in data) {
158
+ const event = data.events.at(-1);
159
+ const lines = [`${data.phase} · ${data.status}`, `任务:${data.jobId}`];
160
+ if (data.lifecycle)
161
+ lines.push(`重启结果:${data.lifecycle.status}${data.lifecycle.reason ? ` · ${data.lifecycle.reason}` : ''}`);
162
+ else if (data.reason || event?.message)
163
+ lines.push(data.reason ?? event.message);
164
+ if (data.status === 'restart-started' && !data.lifecycle)
165
+ lines.push('已进入重启执行,尚不代表新进程已就绪');
166
+ if (data.status === 'accepted')
167
+ lines.push(data.reused ? '已有升级任务,复用当前任务' : '升级任务已受理');
168
+ return lines.join('\n');
169
+ }
170
+ const lines = Object.entries(data.packages).map(([name, value]) => value.error
171
+ ? `⚠ ${name}:${value.error}`
172
+ : `${name}:当前 ${value.currentVersion ?? '未安装'},目标 ${value.targetVersion ?? '未知'}`);
173
+ if (data.devMode)
174
+ lines.push('开发模式:可检查版本,不能通过 npm 升级');
175
+ if (data.hasUpdate)
176
+ lines.push('发现 EvolCore 更新,请执行 update');
177
+ else if (data.hasUpdate === false)
178
+ lines.push('当前 EvolCore 无可升级版本');
179
+ return lines.join('\n');
180
+ }
114
181
  export function subscribeUpgradeJob(jobId, send, key) {
115
182
  if (key)
116
183
  subscriptions.get(key)?.();
@@ -167,6 +234,29 @@ function jobs() {
167
234
  return [];
168
235
  }
169
236
  }
237
+ /** Called under active.lock; never start another job during monitor handoff. */
238
+ function reconcileUpgradeJobs(existing) {
239
+ const monitors = scanInstances().restartMonitors.filter(item => item.alive);
240
+ for (const job of existing.sort((left, right) => right.createdAt - left.createdAt)) {
241
+ const liveMonitor = !!job.monitorPid && isProcessRunning(job.monitorPid);
242
+ const liveLauncher = !!job.launcherPid && isProcessRunning(job.launcherPid);
243
+ if (job.released && !liveMonitor && !liveLauncher)
244
+ continue;
245
+ const workerAlive = !job.restartRequestId && isProcessRunning(job.ownerPid) && job.deadline > Date.now();
246
+ if (liveMonitor || liveLauncher || workerAlive
247
+ || monitors.some(item => item.record.requestId === job.restartRequestId))
248
+ return job;
249
+ const reason = 'Update worker exited or expired before completing the transaction';
250
+ updateUpgradeJob(job.jobId, {
251
+ ...(!terminal(job.status) ? {
252
+ status: job.deadline <= Date.now() ? 'timeout' : 'failed',
253
+ success: false, code: 'UPGRADE_INTERRUPTED', reason,
254
+ } : !job.lifecycle ? { lifecycle: { status: 'failed', reason, at: new Date().toISOString() } } : {}),
255
+ released: true,
256
+ }, '更新进程已退出或超时,可重新发起');
257
+ }
258
+ return null;
259
+ }
170
260
  function assertStableUpgradeEnabled() {
171
261
  if (loadDaemonConfig().upgrade?.autoOnStart === false) {
172
262
  throw Object.assign(new Error('Automatic stable upgrades disabled by autoOnStart'), { code: 'AUTO_UPGRADE_DISABLED' });
@@ -186,25 +276,16 @@ export async function startUpgradeJob(requestId, scope, options = {}) {
186
276
  return withFileLock(path.join(directory(), 'active.lock'), async () => {
187
277
  const existing = jobs();
188
278
  const requestKey = crypto.createHash('sha256').update(JSON.stringify([scope, requestId])).digest('hex');
189
- const scopeKey = crypto.createHash('sha256').update(scope).digest('hex');
279
+ const scopeKey = crypto.createHash('sha256').update('system-upgrade-singleton').digest('hex');
190
280
  const replay = existing.find(job => job.requestKey === requestKey);
191
281
  if (replay)
192
282
  return { job: replay, reused: true };
193
- const monitors = scanInstances().restartMonitors.filter(item => item.alive);
194
- for (const job of existing) {
195
- const liveMonitor = !!job.monitorPid && isProcessRunning(job.monitorPid);
196
- const liveLauncher = !!job.launcherPid && isProcessRunning(job.launcherPid);
197
- if (!job.released || liveMonitor || liveLauncher) {
198
- if (liveMonitor || liveLauncher || (!job.released && !job.restartRequestId && isProcessRunning(job.ownerPid)) || monitors.length) {
199
- if (job.scopeKey !== scopeKey)
200
- throw Object.assign(new Error('An update is already running for another requester'), { code: 'CONFLICT' });
201
- return { job, reused: true };
202
- }
203
- updateUpgradeJob(job.jobId, { status: 'failed', success: false, released: true, code: 'UPGRADE_INTERRUPTED', reason: 'Update worker exited before completing the transaction' }, '更新进程已退出,可重新发起');
204
- }
205
- }
206
- if (monitors.length)
283
+ const active = reconcileUpgradeJobs(existing);
284
+ if (active)
285
+ return { job: active, reused: true };
286
+ if (scanInstances().restartMonitors.some(item => item.alive)) {
207
287
  throw Object.assign(new Error('A restart transaction is still running'), { code: 'CONFLICT' });
288
+ }
208
289
  const now = Date.now();
209
290
  const job = {
210
291
  ...blankCheck(stableTarget ? 'stable' : resolveUpgradeDistTag()),
@@ -3,7 +3,7 @@ import path from 'path';
3
3
  import { spawnSync } from 'child_process';
4
4
  import { getPackageRoot, resolvePaths } from '../paths.js';
5
5
  import { atomicReadJson, atomicWriteJson } from './atomic-write.js';
6
- import { decodeWindowsOutput } from './windows-output.js';
6
+ import { decodeWindowsOutput } from './cross-platform.js';
7
7
  export const WINDOWS_AUTOSTART_TASK_NAME = 'EvolCore';
8
8
  export const WINDOWS_AUTOSTART_RUN_VALUE_NAME = 'EvolCore';
9
9
  export const WINDOWS_AUTOSTART_STATE_VERSION = 1;
package/ecagent/README.md CHANGED
@@ -41,6 +41,25 @@ import { AssistantMessageEventStream } from "ecagent/runtime";
41
41
  EvolCore uses this boundary to connect its own credentials, gateway, streaming,
42
42
  and abort handling.
43
43
 
44
+ ## Shell execution and cancellation
45
+
46
+ `NodeExecutionEnv.exec()` takes a timeout in **seconds**. EvolCore's `Bash` tool
47
+ instead exposes milliseconds (120000 by default, at most 600000) and converts at
48
+ the adapter boundary.
49
+
50
+ On Windows, shell commands run under a hidden Windows PowerShell supervisor and
51
+ a per-command Job Object. Aborting or timing out terminates the supervisor and
52
+ its job, including descendants whose original Bash parent has already exited.
53
+ Execution settles only after the supervisor exits, not when cancellation is
54
+ merely requested. Both output streams are forwarded as UTF-8 bytes; internal
55
+ completion markers are removed before tool results and streaming callbacks.
56
+
57
+ A command that completes normally can leave an intentionally backgrounded
58
+ service alive if that service redirects its output. While an execution is still
59
+ pending, interruption terminates all processes in its job. Long-running managed
60
+ services should use EvolCore's service manager rather than rely on an open Bash
61
+ tool call. The supervisor fails closed if job assignment is unavailable.
62
+
44
63
  ## Build from source
45
64
 
46
65
  ```bash
@@ -336,6 +336,15 @@ export class AgentHarness {
336
336
  toolName: toolCall.name,
337
337
  input: args,
338
338
  }, signal);
339
+ if (signal?.aborted) {
340
+ if (result?.block)
341
+ return result;
342
+ return {
343
+ block: true,
344
+ reason: 'Operation aborted',
345
+ details: { cancelled: true },
346
+ };
347
+ }
339
348
  return result;
340
349
  },
341
350
  afterToolCall: async ({ toolCall, args, result, isError }) => {
@@ -5,6 +5,7 @@ import { access, appendFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath,
5
5
  import { tmpdir } from "node:os";
6
6
  import { isAbsolute, join, resolve } from "node:path";
7
7
  import { createInterface } from "node:readline";
8
+ import { windowsShellSupervisor } from "./windows-shell.js";
8
9
  import { ExecutionError, err, FileError, ok, toError, } from "../types.js";
9
10
  const MAX_TIMEOUT_MS = 2_147_483_647;
10
11
  const MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;
@@ -20,6 +21,16 @@ function resolveTimeoutMs(timeout) {
20
21
  }
21
22
  return ok(timeoutMs);
22
23
  }
24
+ function consumeSupervisorOutput(buffer, marker) {
25
+ const markerIndex = buffer.indexOf(marker);
26
+ if (markerIndex >= 0)
27
+ return { output: buffer.slice(0, markerIndex), pending: "", finished: true };
28
+ let prefixLength = Math.min(buffer.length, marker.length - 1);
29
+ while (prefixLength > 0 && !marker.startsWith(buffer.slice(-prefixLength)))
30
+ prefixLength--;
31
+ const safeLength = buffer.length - prefixLength;
32
+ return { output: buffer.slice(0, safeLength), pending: buffer.slice(safeLength), finished: false };
33
+ }
23
34
  function resolvePath(cwd, path) {
24
35
  return isAbsolute(path) ? path : resolve(cwd, path);
25
36
  }
@@ -222,17 +233,30 @@ export class NodeExecutionEnv {
222
233
  const shellConfig = await getShellConfig(this.shellPath);
223
234
  if (!shellConfig.ok)
224
235
  return shellConfig;
236
+ if (options?.abortSignal?.aborted)
237
+ return err(new ExecutionError("aborted", "aborted"));
225
238
  return await new Promise((resolvePromise) => {
226
239
  let stdout = "";
227
240
  let stderr = "";
228
241
  let settled = false;
229
242
  let timedOut = false;
230
243
  let callbackError;
244
+ let interrupted = false;
245
+ let supervisorMarker;
246
+ let stdoutFinished = false;
247
+ let stderrFinished = false;
248
+ let processExited = false;
249
+ let pendingStdout = "";
250
+ let pendingStderr = "";
231
251
  let child;
232
252
  let timeoutId;
233
253
  const onAbort = () => {
234
254
  if (child?.pid) {
235
- killProcessTree(child.pid);
255
+ interrupted = true;
256
+ if (process.platform === "win32")
257
+ child.kill("SIGKILL");
258
+ else
259
+ killProcessTree(child.pid);
236
260
  }
237
261
  };
238
262
  const settle = (result) => {
@@ -245,18 +269,34 @@ export class NodeExecutionEnv {
245
269
  settled = true;
246
270
  resolvePromise(result);
247
271
  };
272
+ const releaseOutput = () => {
273
+ if (!processExited || (!interrupted && !(stdoutFinished && stderrFinished)))
274
+ return;
275
+ child?.stdout?.destroy();
276
+ child?.stderr?.destroy();
277
+ };
248
278
  try {
249
279
  const commandFromStdin = shellConfig.value.commandTransport === "stdin";
250
- child = spawn(shellConfig.value.shell, commandFromStdin ? shellConfig.value.args : [...shellConfig.value.args, command], {
280
+ const args = commandFromStdin ? shellConfig.value.args : [...shellConfig.value.args, command];
281
+ const supervisor = process.platform === "win32"
282
+ ? windowsShellSupervisor(shellConfig.value.shell, args, commandFromStdin ? command : undefined)
283
+ : undefined;
284
+ supervisorMarker = supervisor?.completionMarker;
285
+ const env = getShellEnv(this.shellEnv, options?.env);
286
+ if (supervisor && env.TMPDIR) {
287
+ env.TEMP = env.TMPDIR;
288
+ env.TMP = env.TMPDIR;
289
+ }
290
+ child = spawn(supervisor?.command ?? shellConfig.value.shell, supervisor?.args ?? args, {
251
291
  cwd,
252
292
  detached: process.platform !== "win32",
253
- env: getShellEnv(this.shellEnv, options?.env),
254
- stdio: [commandFromStdin ? "pipe" : "ignore", "pipe", "pipe"],
293
+ env,
294
+ stdio: [supervisor || commandFromStdin ? "pipe" : "ignore", "pipe", "pipe"],
255
295
  windowsHide: true,
256
296
  });
257
- if (commandFromStdin) {
297
+ if (supervisor || commandFromStdin) {
258
298
  child.stdin?.on("error", () => { });
259
- child.stdin?.end(command);
299
+ child.stdin?.end(supervisor?.input ?? command);
260
300
  }
261
301
  }
262
302
  catch (error) {
@@ -268,9 +308,7 @@ export class NodeExecutionEnv {
268
308
  timeoutMs !== undefined
269
309
  ? setTimeout(() => {
270
310
  timedOut = true;
271
- if (child?.pid) {
272
- killProcessTree(child.pid);
273
- }
311
+ onAbort();
274
312
  }, timeoutMs)
275
313
  : undefined;
276
314
  if (options?.abortSignal) {
@@ -284,31 +322,53 @@ export class NodeExecutionEnv {
284
322
  child.stdout?.setEncoding("utf8");
285
323
  child.stderr?.setEncoding("utf8");
286
324
  child.stdout?.on("data", (chunk) => {
325
+ if (supervisorMarker) {
326
+ const parsed = consumeSupervisorOutput(pendingStdout + chunk, supervisorMarker);
327
+ chunk = parsed.output;
328
+ pendingStdout = parsed.pending;
329
+ stdoutFinished ||= parsed.finished;
330
+ }
287
331
  stdout += chunk;
288
332
  try {
289
- options?.onStdout?.(chunk);
333
+ if (chunk)
334
+ options?.onStdout?.(chunk);
290
335
  }
291
336
  catch (error) {
292
337
  const cause = toError(error);
293
338
  callbackError = new ExecutionError("callback_error", cause.message, cause);
294
339
  onAbort();
295
340
  }
341
+ releaseOutput();
296
342
  });
297
343
  child.stderr?.on("data", (chunk) => {
344
+ if (supervisorMarker) {
345
+ const parsed = consumeSupervisorOutput(pendingStderr + chunk, supervisorMarker);
346
+ chunk = parsed.output;
347
+ pendingStderr = parsed.pending;
348
+ stderrFinished ||= parsed.finished;
349
+ }
298
350
  stderr += chunk;
299
351
  try {
300
- options?.onStderr?.(chunk);
352
+ if (chunk)
353
+ options?.onStderr?.(chunk);
301
354
  }
302
355
  catch (error) {
303
356
  const cause = toError(error);
304
357
  callbackError = new ExecutionError("callback_error", cause.message, cause);
305
358
  onAbort();
306
359
  }
360
+ releaseOutput();
307
361
  });
308
362
  child.on("error", (error) => {
309
363
  settle(err(new ExecutionError("spawn_error", error.message, error)));
310
364
  });
365
+ child.on("exit", () => {
366
+ processExited = true;
367
+ releaseOutput();
368
+ });
311
369
  child.on("close", (code) => {
370
+ stdout += pendingStdout;
371
+ stderr += pendingStderr;
312
372
  if (callbackError) {
313
373
  settle(err(callbackError));
314
374
  return;
@@ -0,0 +1,7 @@
1
+ export declare function windowsShellSupervisor(shell: string, args: string[], input?: string): {
2
+ command: string;
3
+ args: string[];
4
+ input: string;
5
+ completionMarker: string;
6
+ };
7
+ //# sourceMappingURL=windows-shell.d.ts.map
@@ -0,0 +1,132 @@
1
+ import { join } from "node:path";
2
+ import { randomUUID } from "node:crypto";
3
+ const supervisorSource = String.raw `
4
+ using System;
5
+ using System.ComponentModel;
6
+ using System.Diagnostics;
7
+ using System.Runtime.InteropServices;
8
+ using System.Text;
9
+ using System.Threading.Tasks;
10
+
11
+ public static class EcagentShellJob {
12
+ [StructLayout(LayoutKind.Sequential)]
13
+ private struct BasicLimits {
14
+ public long ProcessTime, JobTime;
15
+ public uint Flags;
16
+ public UIntPtr MinWorkingSet, MaxWorkingSet;
17
+ public uint ActiveProcesses;
18
+ public UIntPtr Affinity;
19
+ public uint Priority, Scheduling;
20
+ }
21
+ [StructLayout(LayoutKind.Sequential)]
22
+ private struct IoCounters {
23
+ public ulong ReadOperations, WriteOperations, OtherOperations;
24
+ public ulong ReadBytes, WriteBytes, OtherBytes;
25
+ }
26
+ [StructLayout(LayoutKind.Sequential)]
27
+ private struct ExtendedLimits {
28
+ public BasicLimits Basic;
29
+ public IoCounters Io;
30
+ public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
31
+ }
32
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
33
+ private static extern IntPtr CreateJobObject(IntPtr attributes, string name);
34
+ [DllImport("kernel32.dll", SetLastError = true)]
35
+ private static extern bool SetInformationJobObject(IntPtr job, int informationClass, ref ExtendedLimits limits, uint length);
36
+ [DllImport("kernel32.dll", SetLastError = true)]
37
+ private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
38
+ [DllImport("kernel32.dll")]
39
+ private static extern bool CloseHandle(IntPtr handle);
40
+ [DllImport("kernel32.dll")]
41
+ private static extern IntPtr GetStdHandle(int identifier);
42
+ [DllImport("kernel32.dll", SetLastError = true)]
43
+ private static extern bool SetHandleInformation(IntPtr handle, uint mask, uint flags);
44
+
45
+ private static void SetLimits(IntPtr job, uint flags) {
46
+ var limits = new ExtendedLimits();
47
+ limits.Basic.Flags = flags;
48
+ if (!SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(ExtendedLimits))))
49
+ throw new Win32Exception(Marshal.GetLastWin32Error());
50
+ }
51
+
52
+ private static string Quote(string argument) {
53
+ var result = new StringBuilder("\"");
54
+ int slashes = 0;
55
+ foreach (char character in argument) {
56
+ if (character == '\\') { slashes++; continue; }
57
+ if (character == '"') result.Append('\\', slashes * 2 + 1).Append('"');
58
+ else result.Append('\\', slashes).Append(character);
59
+ slashes = 0;
60
+ }
61
+ return result.Append('\\', slashes * 2).Append('"').ToString();
62
+ }
63
+
64
+ public static int Run(string shell, string[] arguments, string input, string completionMarker) {
65
+ IntPtr job = CreateJobObject(IntPtr.Zero, null);
66
+ if (job == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error());
67
+ SetLimits(job, 0x2000);
68
+ using (var self = Process.GetCurrentProcess()) {
69
+ if (!AssignProcessToJobObject(job, self.Handle))
70
+ throw new Win32Exception(Marshal.GetLastWin32Error());
71
+ }
72
+ foreach (int identifier in new[] { -10, -11, -12 }) {
73
+ IntPtr handle = GetStdHandle(identifier);
74
+ if (handle != IntPtr.Zero && handle != new IntPtr(-1) && !SetHandleInformation(handle, 1, 0))
75
+ throw new Win32Exception(Marshal.GetLastWin32Error());
76
+ }
77
+ var commandLine = new StringBuilder();
78
+ foreach (string argument in arguments) {
79
+ if (commandLine.Length > 0) commandLine.Append(' ');
80
+ commandLine.Append(Quote(argument));
81
+ }
82
+ using (var child = new Process()) {
83
+ child.StartInfo = new ProcessStartInfo(shell, commandLine.ToString()) {
84
+ UseShellExecute = false, CreateNoWindow = true,
85
+ RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true
86
+ };
87
+ child.Start();
88
+ Task stdout = child.StandardOutput.BaseStream.CopyToAsync(Console.OpenStandardOutput());
89
+ Task stderr = child.StandardError.BaseStream.CopyToAsync(Console.OpenStandardError());
90
+ if (input != null) {
91
+ byte[] bytes = Encoding.UTF8.GetBytes(input);
92
+ child.StandardInput.BaseStream.Write(bytes, 0, bytes.Length);
93
+ }
94
+ child.StandardInput.Close();
95
+ child.WaitForExit();
96
+ Task.WaitAll(stdout, stderr);
97
+ int exitCode = child.ExitCode;
98
+ byte[] marker = Encoding.UTF8.GetBytes(completionMarker);
99
+ Console.OpenStandardOutput().Write(marker, 0, marker.Length);
100
+ Console.OpenStandardError().Write(marker, 0, marker.Length);
101
+ SetLimits(job, 0);
102
+ CloseHandle(job);
103
+ return exitCode;
104
+ }
105
+ }
106
+ }
107
+ `;
108
+ const supervisorScript = `
109
+ $ErrorActionPreference = 'Stop'
110
+ $ProgressPreference = 'SilentlyContinue'
111
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
112
+ try {
113
+ Add-Type -TypeDefinition @'
114
+ ${supervisorSource}
115
+ '@
116
+ $request = [Console]::In.ReadToEnd() | ConvertFrom-Json
117
+ exit [EcagentShellJob]::Run($request.shell, [string[]]$request.arguments, $request.input, $request.completionMarker)
118
+ } catch {
119
+ [Console]::Error.WriteLine($_.Exception.ToString())
120
+ exit 1
121
+ }
122
+ `;
123
+ export function windowsShellSupervisor(shell, args, input) {
124
+ const completionMarker = `\0ecagent-shell-${randomUUID()}\0`;
125
+ return {
126
+ command: join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
127
+ args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-InputFormat", "Text", "-OutputFormat", "Text", "-EncodedCommand", Buffer.from(supervisorScript, "utf16le").toString("base64")],
128
+ input: JSON.stringify({ shell, arguments: args, input: input ?? null, completionMarker }),
129
+ completionMarker,
130
+ };
131
+ }
132
+ //# sourceMappingURL=windows-shell.js.map