evolcore 0.0.47 → 0.0.49

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 (266) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +143 -40
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +34 -17
  8. package/dist/agents/codex-runner.js +36 -17
  9. package/dist/agents/ecagent-runner.js +7 -4
  10. package/dist/agents/gemini-runner.js +5 -2
  11. package/dist/agents/runner-types.js +5 -21
  12. package/dist/aun/aid/agentmd.js +5 -1
  13. package/dist/aun/msg/p2p.js +2 -1
  14. package/dist/aun/service-proxy.js +4 -2
  15. package/dist/build-identity.json +1 -0
  16. package/dist/channels/aun.js +722 -295
  17. package/dist/channels/daemon.js +9 -25
  18. package/dist/cli/aun-commands.js +86 -51
  19. package/dist/cli/code-stats.js +19 -8
  20. package/dist/cli/command-log.js +1 -1
  21. package/dist/cli/daemon-commands.js +44 -43
  22. package/dist/cli/directory.js +13 -2
  23. package/dist/cli/ecmsg-gateway.js +5 -2
  24. package/dist/cli/index.js +9 -9
  25. package/dist/cli/init-channel.js +4 -6
  26. package/dist/cli/init.js +72 -50
  27. package/dist/cli/invoke-command.js +1 -1
  28. package/dist/cli/managed-command-guard.js +2 -0
  29. package/dist/cli/model.js +20 -5
  30. package/dist/cli/provider-command.js +74 -13
  31. package/dist/cli/quota.js +89 -0
  32. package/dist/cli/role.js +62 -17
  33. package/dist/cli/services-command.js +1 -0
  34. package/dist/cli/stats.js +3 -3
  35. package/dist/cli/team-workspace-command.js +56 -2
  36. package/dist/cli/thread-command.js +16 -51
  37. package/dist/config/boot-log.js +3 -9
  38. package/dist/config/builtin-roles.js +5 -7
  39. package/dist/config/config-field-policy.js +71 -1
  40. package/dist/config/config-manager.js +13 -7
  41. package/dist/config/daemon-services.js +30 -3
  42. package/dist/config/gateway-config.js +2 -2
  43. package/dist/config/invoke-ipc-service.js +6 -4
  44. package/dist/config/peer-bind-code.js +3 -4
  45. package/dist/config/peer-book-store.js +62 -229
  46. package/dist/config/peer-book.js +26 -27
  47. package/dist/config/peer-role-resolver.js +16 -1
  48. package/dist/config/provider-identity-migration.js +4 -1
  49. package/dist/config/provider-ipc-service.js +56 -11
  50. package/dist/config/provider-menu-request.js +24 -5
  51. package/dist/config/provider-templates.js +127 -0
  52. package/dist/config/providers-config.js +67 -12
  53. package/dist/config/providers-management.js +477 -51
  54. package/dist/config/resolved-config-op.js +3 -2
  55. package/dist/config/role-command-service.js +248 -1
  56. package/dist/config/schema-migration.js +105 -4
  57. package/dist/core/agent-application-service.js +6 -1
  58. package/dist/core/agent-runtime.js +4 -0
  59. package/dist/core/auth/agent-delegation.js +2 -1
  60. package/dist/core/auth/auth-gateway.js +2 -1
  61. package/dist/core/auth/delegation-authorization.js +36 -26
  62. package/dist/core/auth/operation-authorizer.js +25 -0
  63. package/dist/core/auth/operation-catalog.js +37 -64
  64. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  65. package/dist/core/channel-loader.js +18 -0
  66. package/dist/core/command/agent-control.js +32 -0
  67. package/dist/core/command/cli-intent-parser.js +13 -0
  68. package/dist/core/command/command-handler.js +126 -87
  69. package/dist/core/command/menu-catalog.js +1 -0
  70. package/dist/core/command/menu-handler.js +67 -150
  71. package/dist/core/command/menu-protocol.js +31 -1
  72. package/dist/core/command/provider-menu.js +13 -3
  73. package/dist/core/command/remote-shell.js +565 -0
  74. package/dist/core/command/role-menu.js +47 -23
  75. package/dist/core/command/slash-handler.js +26 -43
  76. package/dist/core/command/team-workspace-items.js +81 -12
  77. package/dist/core/command/team-workspace-team.js +9 -71
  78. package/dist/core/command/topic-slash.js +9 -30
  79. package/dist/core/daemon-bootstrap.js +8 -1
  80. package/dist/core/daemon-control.js +64 -8
  81. package/dist/core/daemon-lifecycle.js +16 -2
  82. package/dist/core/evolagent-registry.js +20 -3
  83. package/dist/core/file-integrity/store.js +2 -0
  84. package/dist/core/handoff/runtime.js +37 -1
  85. package/dist/core/inference/text-inference.js +3 -1
  86. package/dist/core/initialization/service.js +11 -6
  87. package/dist/core/interaction-router.js +3 -0
  88. package/dist/core/invoke/executors/text.js +72 -19
  89. package/dist/core/ipc-registration.js +3 -1
  90. package/dist/core/message/aun-ipc-sender.js +279 -107
  91. package/dist/core/message/contact-admission.js +91 -6
  92. package/dist/core/message/contact-pending-inbound.js +113 -0
  93. package/dist/core/message/contact-thread-approval.js +212 -0
  94. package/dist/core/message/im-renderer.js +41 -2
  95. package/dist/core/message/message-admission.js +5 -39
  96. package/dist/core/message/message-bridge.js +140 -370
  97. package/dist/core/message/message-log.js +29 -0
  98. package/dist/core/message/message-queue.js +119 -15
  99. package/dist/core/message/message-utils.js +8 -0
  100. package/dist/core/message/response-engine.js +580 -134
  101. package/dist/core/message/send-routing.js +5 -1
  102. package/dist/core/model/catalog-service.js +31 -11
  103. package/dist/core/model/config-scope.js +6 -14
  104. package/dist/core/model/model-capabilities.js +22 -4
  105. package/dist/core/model/model-catalog.js +1 -0
  106. package/dist/core/model/model-diagnostics.js +19 -0
  107. package/dist/core/model/model-fallback.js +13 -2
  108. package/dist/core/ownership/owner-resolver.js +328 -50
  109. package/dist/core/pack-auth.js +3 -0
  110. package/dist/core/pack-install.js +1 -1
  111. package/dist/core/permission/ec-command-parser.js +106 -19
  112. package/dist/core/permission/protected-paths.js +6 -6
  113. package/dist/core/permission/services-path-acl.js +451 -0
  114. package/dist/core/permission/tool-policy.js +5 -1
  115. package/dist/core/relation/peer-identity.js +36 -1
  116. package/dist/core/relation/same-owner-proof.js +81 -112
  117. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  118. package/dist/core/session/session-file-health.js +13 -7
  119. package/dist/core/session/session-fs-store.js +91 -35
  120. package/dist/core/session/session-manager.js +68 -24
  121. package/dist/core/session/session-mapper.js +14 -34
  122. package/dist/core/session/session-transcript.js +5 -1
  123. package/dist/core/task/task-activity-store.js +84 -0
  124. package/dist/core/task/task-recovery-service.js +13 -0
  125. package/dist/core/thread/command-parser.js +7 -12
  126. package/dist/core/thread/thread-context-storage.js +3 -2
  127. package/dist/core/thread/thread-operation.js +2 -13
  128. package/dist/core/thread/thread-service.js +15 -46
  129. package/dist/core/thread/topic-id.js +15 -0
  130. package/dist/directory/owner-directory-admission.js +12 -9
  131. package/dist/directory/owner-directory-cache.js +64 -28
  132. package/dist/directory/owner-directory-markdown.js +14 -2
  133. package/dist/directory/owner-directory-policy.js +5 -30
  134. package/dist/directory/owner-directory-query-operation.js +29 -3
  135. package/dist/directory/owner-directory-remarks.js +11 -3
  136. package/dist/directory/owner-directory-request-operation.js +5 -2
  137. package/dist/eck/kit-renderer.js +1 -1
  138. package/dist/eck/message-renderer.js +112 -29
  139. package/dist/ecweb/basic-settings-service.js +3 -1
  140. package/dist/ecweb/message-context-service.js +1 -1
  141. package/dist/ecweb/pairing.js +4 -3
  142. package/dist/ecweb/providers-service.js +26 -1
  143. package/dist/ecweb/runtime/lifecycle.js +18 -8
  144. package/dist/ecweb/runtime/proxy-access.js +74 -0
  145. package/dist/ecweb/runtime/supervisor.js +36 -6
  146. package/dist/event-center/center-config.js +9 -5
  147. package/dist/event-center/dispatcher.js +10 -1
  148. package/dist/event-center/ipc-operation.js +19 -0
  149. package/dist/event-center/registry.js +29 -3
  150. package/dist/event-center/runtime.js +106 -11
  151. package/dist/event-center/script-runner.js +5 -5
  152. package/dist/index.js +96 -59
  153. package/dist/ipc.js +38 -3
  154. package/dist/outputs/authorization.js +16 -0
  155. package/dist/outputs/cards.js +336 -0
  156. package/dist/outputs/events.js +63 -0
  157. package/dist/outputs/protocol.js +103 -0
  158. package/dist/outputs/service.js +266 -0
  159. package/dist/paths.js +3 -0
  160. package/dist/proxy/manager.js +43 -13
  161. package/dist/services/index.js +114 -5
  162. package/dist/services/ipc-operation.js +88 -15
  163. package/dist/services/pack-manager.js +13 -1
  164. package/dist/services/router.js +21 -6
  165. package/dist/services/script-runner.js +5 -4
  166. package/dist/services/service-payload.js +13 -7
  167. package/dist/services/validation.js +1 -1
  168. package/dist/stats/budget.js +2 -2
  169. package/dist/stats/db.js +19 -0
  170. package/dist/stats/index.js +1 -1
  171. package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
  172. package/dist/stats/normalizer.js +2 -0
  173. package/dist/stats/query.js +35 -27
  174. package/dist/stats/quota-query.js +95 -0
  175. package/dist/stats/role-budget.js +5 -2
  176. package/dist/stats/writer.js +10 -6
  177. package/dist/trigger/audit.js +7 -0
  178. package/dist/trigger/authorization.js +105 -11
  179. package/dist/trigger/feedback.js +10 -0
  180. package/dist/trigger/history.js +37 -11
  181. package/dist/trigger/ipc-service.js +12 -1
  182. package/dist/trigger/manager.js +1 -0
  183. package/dist/trigger/scheduler.js +7 -5
  184. package/dist/trigger/script-executor.js +2 -1
  185. package/dist/trigger/script-sandbox.js +21 -3
  186. package/dist/trigger/validation.js +22 -0
  187. package/dist/utils/atomic-write.js +22 -8
  188. package/dist/utils/cross-platform.js +73 -26
  189. package/dist/utils/error-dict.json +94 -4
  190. package/dist/utils/error-utils.js +27 -4
  191. package/dist/utils/evolcore-version.js +36 -65
  192. package/dist/utils/host-info.js +100 -1
  193. package/dist/utils/msg-diag.js +1 -0
  194. package/dist/utils/npm-ops.js +43 -8
  195. package/dist/utils/process-introspect.js +12 -7
  196. package/dist/utils/process-tree.js +50 -2
  197. package/dist/utils/windows-shell-trust.js +2 -0
  198. package/dist/workbench/protocol.js +80 -0
  199. package/dist/workbench/service.js +359 -0
  200. package/ecagent/dist/types.d.ts +6 -2
  201. package/kits/docs/context-assembly.md +1 -1
  202. package/kits/docs/evolcore/INDEX.md +4 -2
  203. package/kits/docs/evolcore/aid.md +25 -0
  204. package/kits/docs/evolcore/config.md +16 -1
  205. package/kits/docs/evolcore/directory.md +30 -12
  206. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  207. package/kits/docs/evolcore/model.md +10 -0
  208. package/kits/docs/evolcore/msg.md +9 -0
  209. package/kits/docs/evolcore/peer.md +19 -65
  210. package/kits/docs/evolcore/provider.md +124 -4
  211. package/kits/docs/evolcore/quota.md +54 -0
  212. package/kits/docs/evolcore/role.md +83 -0
  213. package/kits/docs/evolcore/services.md +6 -6
  214. package/kits/docs/evolcore/stats.md +2 -0
  215. package/kits/docs/evolcore/team-workspace.md +1 -1
  216. package/kits/docs/evolcore/thread-chain.md +14 -15
  217. package/kits/docs/evolcore/tool-authorization.md +5 -0
  218. package/kits/docs/evolcore/trigger.md +12 -0
  219. package/kits/eck_message_manifest.json +12 -0
  220. package/kits/provider-templates.json +1213 -0
  221. package/kits/rules/04-relation.md +3 -3
  222. package/kits/schemas/_meta.json +14 -2
  223. package/kits/schemas/agent-config.schema.20.json +24 -0
  224. package/kits/schemas/contact-book.schema.4.json +52 -0
  225. package/kits/schemas/providers.schema.3.json +200 -0
  226. package/kits/skills/.switches.json +8 -0
  227. package/kits/skills/ability/references/calling.md +1 -1
  228. package/kits/skills/agent-output-cards/SKILL.md +57 -0
  229. package/kits/skills/ec-group/SKILL.md +2 -2
  230. package/kits/skills/ec-identity/SKILL.md +19 -72
  231. package/kits/skills/ec-provider/SKILL.md +270 -0
  232. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  233. package/kits/skills/ec-trigger/SKILL.md +1 -1
  234. package/kits/skills/thread-ops/SKILL.md +34 -21
  235. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  236. package/kits/templates/message-fragments/group-batch.md +1 -1
  237. package/kits/templates/message-fragments/inject-default.md +1 -1
  238. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  239. package/kits/templates/message-fragments/item-group.md +1 -1
  240. package/kits/templates/message-fragments/item-private.md +1 -1
  241. package/kits/templates/message-fragments/thread-context.md +1 -1
  242. package/kits/templates/message-fragments/trigger-session.md +1 -1
  243. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  244. package/kits/templates/roles/admin.json +2 -19
  245. package/kits/templates/roles/member.json +0 -3
  246. package/kits/templates/roles/visitor.json +1 -0
  247. package/kits/templates/system-fragments/baseagent.md +6 -0
  248. package/kits/templates/system-fragments/commands.md +4 -3
  249. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  250. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  251. package/kits/templates/system-fragments/relation.md +1 -1
  252. package/kits/templates/system-fragments/thread.md +7 -5
  253. package/kits/templates/system-fragments/venue.md +11 -0
  254. package/package.json +6 -4
  255. package/scripts/agent-template/inspect.mjs +50 -11
  256. package/scripts/agent-template/shared/common.mjs +11 -6
  257. package/scripts/agent-template/shared/team-schema.json +6 -4
  258. package/scripts/agent-template/shared/template-contract.mjs +62 -11
  259. package/scripts/agent-template/shared/template-package.mjs +189 -21
  260. package/scripts/agent-template/shared/template-runtime.mjs +54 -6
  261. package/scripts/agent-template/shared/template.mjs +2 -2
  262. package/scripts/agent-template/team-pack.mjs +52 -14
  263. package/dist/cli/peer.js +0 -127
  264. package/dist/config/peer-operation-service.js +0 -132
  265. package/dist/config/peer-request-service.js +0 -532
  266. package/dist/core/command/connect-menu.js +0 -624
@@ -194,7 +194,14 @@ async function canSudoNonInteractively() {
194
194
  export async function npmInstallGlobal(pkg, options = {}) {
195
195
  const npm = resolveNpmInvocation();
196
196
  const registry = options.registry ? normalizeRegistry(options.registry) : undefined;
197
- const npmArgs = ['install', '-g', pkg, ...(registry ? ['--registry', registry] : []), ...npmConfigArgs(options.npmConfig), ...(options.preferOffline ? ['--prefer-offline'] : [])];
197
+ // Override inherited npmrc/env cache modes when recovering from stale metadata.
198
+ const cacheArgs = options.preferOnline
199
+ ? ['--prefer-online', '--prefer-offline=false', '--offline=false']
200
+ : options.preferOffline ? ['--prefer-offline'] : [];
201
+ const npmArgs = [
202
+ 'install', '-g', pkg, ...(registry ? ['--registry', registry] : []),
203
+ ...npmConfigArgs(options.npmConfig), ...cacheArgs,
204
+ ];
198
205
  try {
199
206
  await execFileAsync(npm.command, [...npm.argsPrefix, ...npmArgs], {
200
207
  timeout: options.timeoutMs ?? 180000,
@@ -492,7 +499,30 @@ export async function queryPackageVersion(pkg, selection, signal, distTag = 'lat
492
499
  : await fetchLatestVersion(pkg, 10000, signal, registry, distTag);
493
500
  return isPackageVersion(version) ? { version, registry, npmConfig: selection.npmConfig } : null;
494
501
  }
495
- /** No registry lookup: callers must validate cache freshness before each install. */
502
+ function npmFailureCode(error) {
503
+ const failure = error;
504
+ if (typeof failure?.code === 'string' && /^[A-Z][A-Z0-9_]+$/.test(failure.code))
505
+ return failure.code;
506
+ // execFile reports the numeric exit status; npm's own error code is in stderr.
507
+ const output = [failure?.stderr, failure?.message].filter(value => typeof value === 'string').join('\n');
508
+ return output.match(/(?:^|\n)npm (?:error|ERR!) code ([A-Z][A-Z0-9_]+)\b/)?.[1];
509
+ }
510
+ function formatPackageInstallFailure(error, phase) {
511
+ const failure = error;
512
+ const stderr = typeof failure?.stderr === 'string' ? failure.stderr.trim() : '';
513
+ const errorLines = stderr.split('\n').filter(line => /^npm (?:error|ERR!)\s/.test(line));
514
+ const detail = (errorLines.length ? errorLines.join('\n') : stderr
515
+ || (typeof failure?.message === 'string' ? failure.message : String(error)))
516
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
517
+ .replace(/https?:\/\/[^\s"'<>]+/gi, '[registry]')
518
+ .replace(/(\b[\w-]*(?:token|password|secret|api[_-]?key|credential|authorization|_auth)[\w-]*["']?\s*[:=]\s*)(?:(?:Bearer|Basic)\s+)?(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1[redacted]')
519
+ .replace(/\b(?:Bearer|Basic)\s+[^\s,;]+/gi, '[redacted]')
520
+ .replace(/\bnpm_[a-z0-9]+\b/gi, '[redacted]')
521
+ .replace(/\s+/g, ' ').trim().slice(0, 1_000);
522
+ const code = npmFailureCode(error);
523
+ return `Package ${phase} failed${code ? ` (${code})` : ''}${detail ? `: ${detail}` : ''}`;
524
+ }
525
+ /** No target version lookup: callers validate the cached target; ETARGET retries refresh dependency metadata. */
496
526
  export async function installExactPackageVersion(pkg, target, registry, resolveInstalled, npmConfig, beforeInstall) {
497
527
  if (![MAIN_PACKAGE_NAME, WEB_PACKAGE_NAME].includes(pkg)
498
528
  || !isPackageVersion(target) || normalizeVersionRegistry(registry) !== registry) {
@@ -511,20 +541,25 @@ export async function installExactPackageVersion(pkg, target, registry, resolveI
511
541
  return;
512
542
  }
513
543
  await beforeInstall?.();
544
+ let preferOnline = false;
514
545
  for (let attempt = 0; attempt < 2; attempt++) {
546
+ let phase = 'installation';
515
547
  try {
516
- await npmInstallGlobal(`${pkg}@${target}`, { registry, preferOffline: true, npmConfig });
548
+ await npmInstallGlobal(`${pkg}@${target}`, {
549
+ registry, preferOffline: !preferOnline, preferOnline, npmConfig,
550
+ });
551
+ phase = 'version verification';
517
552
  const actual = resolveInstalled()?.version;
518
553
  if (!actual || !isPackageVersion(actual) || comparePackageVersions(actual, target) < 0) {
519
- throw new Error('Installed version did not reach the cached target');
554
+ throw new Error(`Installed ${pkg} version is ${actual ?? 'unavailable'} (target ${target})`);
520
555
  }
521
556
  result = { status: 'upgraded', from, to: actual };
522
557
  return;
523
558
  }
524
- catch {
525
- // npm stderr can contain private registry credentials. Persist a safe
526
- // diagnostic; npm's existing permission/transport behavior is retained.
527
- result = { status: 'failed', from, to: target, error: 'Exact package installation or version verification failed' };
559
+ catch (error) {
560
+ if (phase === 'installation' && npmFailureCode(error) === 'ETARGET')
561
+ preferOnline = true;
562
+ result = { status: 'failed', from, to: target, error: formatPackageInstallFailure(error, phase) };
528
563
  }
529
564
  }
530
565
  });
@@ -236,7 +236,7 @@ function getStartTimeMacOS(pid) {
236
236
  }
237
237
  // ── Windows ──
238
238
  function getStartTimeWindows(pid) {
239
- const query = createWindowsSnapshotQuery(pid);
239
+ const query = createWindowsProcessQuery(WINDOWS_WMI_SNAPSHOT_SCRIPT, pid);
240
240
  if (query) {
241
241
  try {
242
242
  const result = spawnSync(query.command, query.args, {
@@ -305,6 +305,8 @@ const SNAPSHOT_TTL_MS = 5000;
305
305
  * 传 `{ fresh: true }` 可强制重新采集(例如清理前需要最新状态)。
306
306
  */
307
307
  export function getProcessSnapshot(options = {}) {
308
+ if (options.fresh)
309
+ invalidateProcessSnapshot();
308
310
  const now = Date.now();
309
311
  if (!options.fresh && snapshotCache && now - snapshotCache.at < SNAPSHOT_TTL_MS) {
310
312
  return snapshotCache.snapshot;
@@ -313,8 +315,10 @@ export function getProcessSnapshot(options = {}) {
313
315
  snapshotCache = { at: now, snapshot };
314
316
  return snapshot;
315
317
  }
316
- /** The restart monitor shares one snapshot per phase without blocking IPC/timers. */
318
+ /** Fresh requests start a new generation; ordinary callers share current work. */
317
319
  export async function getProcessSnapshotAsync(options = {}) {
320
+ if (options.fresh)
321
+ invalidateProcessSnapshot();
318
322
  if (!options.fresh && snapshotCache && Date.now() - snapshotCache.at < SNAPSHOT_TTL_MS) {
319
323
  return snapshotCache.snapshot;
320
324
  }
@@ -380,7 +384,8 @@ for (; !processes.atEnd(); processes.moveNext()) {
380
384
  WScript.Echo('[' + rows.join(',') + ']');
381
385
  `;
382
386
  let windowsWmiScriptAvailable = true;
383
- function createWindowsSnapshotQuery(pid) {
387
+ /** Prepare a private WMI script; callers must dispose it after the query. */
388
+ export function createWindowsProcessQuery(script, pid) {
384
389
  if (!windowsWmiScriptAvailable)
385
390
  return null;
386
391
  let directory;
@@ -408,7 +413,7 @@ function createWindowsSnapshotQuery(pid) {
408
413
  }
409
414
  directory = fs.mkdtempSync(path.join(os.tmpdir(), 'evolcore-process-snapshot-'));
410
415
  file = path.join(directory, 'snapshot.js');
411
- fs.writeFileSync(file, WINDOWS_WMI_SNAPSHOT_SCRIPT, { flag: 'wx', mode: 0o600 });
416
+ fs.writeFileSync(file, script, { flag: 'wx', mode: 0o600 });
412
417
  return { command, args: ['//Nologo', '//E:JScript', file, ...(pid === undefined ? [] : [String(pid)])], dispose };
413
418
  }
414
419
  catch {
@@ -419,7 +424,7 @@ function createWindowsSnapshotQuery(pid) {
419
424
  }
420
425
  /** Query the same creation-time provider without starting PowerShell for every PID. */
421
426
  async function readWindowsStartTimeAsync(pid) {
422
- const query = createWindowsSnapshotQuery(pid);
427
+ const query = createWindowsProcessQuery(WINDOWS_WMI_SNAPSHOT_SCRIPT, pid);
423
428
  if (!query)
424
429
  return null;
425
430
  try {
@@ -449,7 +454,7 @@ function parseWindowsWmiSnapshot(output) {
449
454
  return null;
450
455
  }
451
456
  async function readWindowsSnapshotAsync() {
452
- const query = createWindowsSnapshotQuery();
457
+ const query = createWindowsProcessQuery(WINDOWS_WMI_SNAPSHOT_SCRIPT);
453
458
  if (query) {
454
459
  try {
455
460
  const snapshot = parseWindowsWmiSnapshot(await processQuery(query.command, query.args, 2000));
@@ -463,7 +468,7 @@ async function readWindowsSnapshotAsync() {
463
468
  return parseWindowsSnapshot(await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], 8000));
464
469
  }
465
470
  function readWindowsSnapshot() {
466
- const query = createWindowsSnapshotQuery();
471
+ const query = createWindowsProcessQuery(WINDOWS_WMI_SNAPSHOT_SCRIPT);
467
472
  if (query) {
468
473
  try {
469
474
  const result = spawnSync(query.command, query.args, { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
@@ -2,7 +2,7 @@ import fs from 'fs';
2
2
  import { spawnSync } from 'child_process';
3
3
  import { performance } from 'node:perf_hooks';
4
4
  import { isMainThread, parentPort, workerData } from 'node:worker_threads';
5
- import { parseCimDate } from './process-introspect.js';
5
+ import { createWindowsProcessQuery, parseCimDate } from './process-introspect.js';
6
6
  function runnerKind(name) {
7
7
  const normalized = name.toLowerCase();
8
8
  if (normalized.includes('codex'))
@@ -164,7 +164,52 @@ function readUnixPsMetrics() {
164
164
  }
165
165
  return metrics;
166
166
  }
167
+ // Read the same counters as CIM without loading PowerShell on every sample.
168
+ // Escape non-ASCII names so cscript's console code page cannot corrupt JSON.
169
+ const WINDOWS_WMI_METRICS_SCRIPT = String.raw `
170
+ function text(value) {
171
+ return '"' + String(value).replace(/[\\"\u0000-\u001f\u007f-\uffff]/g, function (ch) {
172
+ return '\\u' + ('0000' + ch.charCodeAt(0).toString(16)).slice(-4);
173
+ }) + '"';
174
+ }
175
+ var service = GetObject('winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2');
176
+ var processes = new Enumerator(service.ExecQuery('SELECT ProcessId,ParentProcessId,Name,WorkingSetSize,KernelModeTime,UserModeTime,CreationDate FROM Win32_Process'));
177
+ var rows = [];
178
+ for (; !processes.atEnd(); processes.moveNext()) {
179
+ var item = processes.item();
180
+ rows.push('{"ProcessId":' + Number(item.ProcessId)
181
+ + ',"ParentProcessId":' + Number(item.ParentProcessId)
182
+ + ',"Name":' + text(item.Name)
183
+ + ',"WorkingSetSize":' + text(item.WorkingSetSize)
184
+ + ',"KernelModeTime":' + text(item.KernelModeTime)
185
+ + ',"UserModeTime":' + text(item.UserModeTime)
186
+ + ',"CreationDate":' + (item.CreationDate == null ? 'null' : text(item.CreationDate)) + '}');
187
+ }
188
+ WScript.Echo('[' + rows.join(',') + ']');
189
+ `;
190
+ let windowsWmiMetricsAvailable = true;
167
191
  function readWindowsMetrics() {
192
+ const query = windowsWmiMetricsAvailable ? createWindowsProcessQuery(WINDOWS_WMI_METRICS_SCRIPT) : null;
193
+ if (query) {
194
+ try {
195
+ const result = spawnSync(query.command, query.args, {
196
+ encoding: 'utf8', timeout: 2000, windowsHide: true,
197
+ stdio: ['ignore', 'pipe', 'ignore'],
198
+ });
199
+ if (result.status === 0) {
200
+ const metrics = parseWindowsMetrics(result.stdout || '');
201
+ // Empty or incomplete output must not replace a working sample.
202
+ if (metrics.some(metric => metric.pid === process.pid && typeof metric.startId === 'number'))
203
+ return metrics;
204
+ }
205
+ }
206
+ catch { /* Keep the CIM fallback for blocked or unavailable script hosts. */ }
207
+ finally {
208
+ query.dispose();
209
+ }
210
+ // Do not add a failed script-host timeout to every subsequent sample.
211
+ windowsWmiMetricsAvailable = false;
212
+ }
168
213
  const command = [
169
214
  'Get-CimInstance Win32_Process',
170
215
  "Select-Object ProcessId,ParentProcessId,Name,WorkingSetSize,KernelModeTime,UserModeTime,@{Name='CreationDate';Expression={if ($_.CreationDate) {$_.CreationDate.ToUniversalTime().ToString('o')}}}",
@@ -178,8 +223,11 @@ function readWindowsMetrics() {
178
223
  });
179
224
  if (result.status !== 0 || !result.stdout?.trim())
180
225
  return [];
226
+ return parseWindowsMetrics(result.stdout);
227
+ }
228
+ function parseWindowsMetrics(output) {
181
229
  try {
182
- const parsed = JSON.parse(result.stdout);
230
+ const parsed = JSON.parse(output.replace(/^\uFEFF/, ''));
183
231
  const rows = Array.isArray(parsed) ? parsed : [parsed];
184
232
  return rows.map((row) => ({
185
233
  pid: Number(row.ProcessId),
@@ -223,6 +223,8 @@ function fileAccessFailure(filePath, cause) {
223
223
  }, cause);
224
224
  }
225
225
  function rememberSignature(key, stat, error) {
226
+ if (error && ['SIGNATURE_PROBE_TIMEOUT', 'POWERSHELL_START_FAILED', 'SIGNATURE_PROBE_FAILED'].includes(error.reason))
227
+ return;
226
228
  signatureCache.set(key, { size: stat.size, mtimeMs: stat.mtimeMs, error });
227
229
  while (signatureCache.size > MAX_CACHE_ENTRIES) {
228
230
  const oldest = signatureCache.keys().next().value;
@@ -0,0 +1,80 @@
1
+ export const WORKBENCH_EVENT = 'team.workbench.changed';
2
+ export const WORKBENCH_TYPES = ['snapshot', 'history', 'changes'].map(action => `services.workbench.${action}`);
3
+ export const WORKBENCH_MODULES = ['runtime', 'currentTasks', 'recentExecutions', 'history'];
4
+ export const isWorkbenchType = (type) => WORKBENCH_TYPES.includes(type);
5
+ export function workbenchRequestSchema(type) {
6
+ const action = type.split('.').at(-1);
7
+ const properties = { protocolVersion: { const: 1 } };
8
+ const required = ['protocolVersion'];
9
+ if (action === 'snapshot')
10
+ Object.assign(properties, {
11
+ limit: { type: 'integer', minimum: 1, maximum: 12 }, waitForIndex: { type: 'boolean' },
12
+ });
13
+ if (action === 'history')
14
+ Object.assign(properties, {
15
+ from: { type: 'integer', minimum: 0 }, to: { type: 'integer', minimum: 0 },
16
+ limit: { type: 'integer', minimum: 1, maximum: 20 }, pageCursor: { type: 'string', maxLength: 512 },
17
+ });
18
+ if (action === 'changes') {
19
+ properties.cursor = { type: 'string', maxLength: 128 };
20
+ required.push('cursor');
21
+ }
22
+ return { type: 'object', additionalProperties: false, required: ['type', 'request_id', 'data'], properties: {
23
+ type: { const: type }, request_id: { type: 'string', minLength: 1, maxLength: 128 },
24
+ data: { type: 'object', additionalProperties: false, required, properties },
25
+ } };
26
+ }
27
+ export function workbenchResponseSchema(type) {
28
+ const timestamp = { type: 'integer', minimum: 0 };
29
+ const state = { enum: ['starting', 'running', 'waiting', 'paused', 'interrupting', 'completed', 'interrupted', 'error', 'timeout', 'unknown'] };
30
+ const availability = { enum: ['ready', 'building', 'unsupported', 'unavailable'] };
31
+ const coverage = { enum: ['complete', 'partial', 'retained'] };
32
+ const task = { type: 'object', additionalProperties: false,
33
+ required: ['id', 'title', 'state', 'startedAt', 'updatedAt', 'detailAvailable'], properties: {
34
+ id: { type: 'string', maxLength: 256 }, title: { type: 'string', maxLength: 200 }, state,
35
+ startedAt: timestamp, updatedAt: timestamp, completedAt: timestamp,
36
+ detailAvailable: { type: 'boolean' }, threadId: { type: 'string', maxLength: 512 },
37
+ } };
38
+ const historyEntry = { type: 'object', additionalProperties: false,
39
+ required: ['id', 'taskId', 'title', 'state', 'at', 'detailAvailable'], properties: {
40
+ id: { type: 'string', maxLength: 256 }, taskId: { type: 'string', maxLength: 256 },
41
+ title: { type: 'string', maxLength: 200 }, state, at: timestamp,
42
+ detailAvailable: { type: 'boolean' }, threadId: { type: 'string', maxLength: 512 },
43
+ } };
44
+ const taskModule = { type: 'object', additionalProperties: false,
45
+ required: ['availability', 'coverage', 'items', 'truncated'], properties: {
46
+ availability, coverage, items: { type: 'array', maxItems: 12, items: task }, truncated: { type: 'boolean' },
47
+ } };
48
+ const properties = {
49
+ protocol: { const: 'evol.workbench' }, protocolVersion: { const: 1 },
50
+ sourceAid: { type: 'string', minLength: 3, maxLength: 256 }, generatedAt: timestamp,
51
+ revision: { type: 'string', pattern: '^[a-f0-9]{24}$' },
52
+ cursor: { type: 'string', pattern: '^[a-f0-9]{24}\\.\\d+$', maxLength: 128 },
53
+ notifications: { anyOf: [{ type: 'null' }, { type: 'object', additionalProperties: false,
54
+ required: ['busAid', 'event'], properties: { busAid: { type: 'string' }, event: { const: WORKBENCH_EVENT } } }] },
55
+ };
56
+ const required = Object.keys(properties);
57
+ if (type.endsWith('.changes')) {
58
+ properties.changedModules = { type: 'array', uniqueItems: true, maxItems: 4, items: { enum: WORKBENCH_MODULES } };
59
+ properties.reset = { type: 'boolean' };
60
+ required.push('changedModules', 'reset');
61
+ }
62
+ else {
63
+ properties.modules = { type: 'object', additionalProperties: false, required: WORKBENCH_MODULES, properties: {
64
+ runtime: { type: 'object', additionalProperties: false,
65
+ required: ['availability', 'coverage', 'status', 'workState', 'activeTaskCount'], properties: {
66
+ availability, coverage, status: { enum: ['running', 'stopped', 'disabled', 'error', 'unknown'] },
67
+ workState: { enum: ['working', 'idle', 'unknown'] }, activeTaskCount: { type: 'integer', minimum: 0 },
68
+ } },
69
+ currentTasks: taskModule, recentExecutions: taskModule,
70
+ history: { type: 'object', additionalProperties: false,
71
+ required: ['availability', 'coverage', 'items', 'nextCursor', 'from', 'to', 'oldestRetainedAt', 'truncated'], properties: {
72
+ availability, coverage, items: { type: 'array', maxItems: 20, items: historyEntry },
73
+ nextCursor: { anyOf: [{ type: 'null' }, { type: 'string', maxLength: 512 }] },
74
+ from: timestamp, to: timestamp, oldestRetainedAt: { anyOf: [{ type: 'null' }, timestamp] }, truncated: { type: 'boolean' },
75
+ } },
76
+ } };
77
+ required.push('modules');
78
+ }
79
+ return { type: 'object', additionalProperties: false, required, properties };
80
+ }