evolcore 0.0.43-test.5 → 0.0.43-test.6

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 (116) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bin/ecmsg.js +126 -43
  3. package/dist/agents/baseagent-availability.js +19 -4
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +14 -3
  7. package/dist/agents/codex-runner.js +6 -6
  8. package/dist/aun/group/invite-service.js +3 -2
  9. package/dist/aun/service-proxy.js +18 -6
  10. package/dist/channels/aun.js +73 -10
  11. package/dist/cli/agent-create.js +16 -6
  12. package/dist/cli/aun-commands.js +9 -1
  13. package/dist/cli/daemon-commands.js +30 -1
  14. package/dist/cli/ecmsg-gateway.js +3 -1
  15. package/dist/cli/init.js +75 -0
  16. package/dist/cli/provider-command.js +1 -1
  17. package/dist/cli/restart-monitor.js +24 -5
  18. package/dist/cli/task-context.js +38 -1
  19. package/dist/cli/watch-logs.js +6 -4
  20. package/dist/config/boot-log.js +6 -4
  21. package/dist/config/builtin-roles.js +2 -2
  22. package/dist/config/config-manager.js +1 -1
  23. package/dist/config/peer-role-resolver.js +1 -1
  24. package/dist/config/provider-identity-migration.js +92 -17
  25. package/dist/config/provider-local-sync.js +2 -0
  26. package/dist/config/providers-config.js +13 -0
  27. package/dist/config/providers-management.js +100 -10
  28. package/dist/config/role-service.js +8 -8
  29. package/dist/config/role-store.js +22 -22
  30. package/dist/config/schema-migration.js +80 -87
  31. package/dist/config/snapshot.js +70 -41
  32. package/dist/core/agent-runtime.js +44 -7
  33. package/dist/core/baseagent-loader.js +114 -11
  34. package/dist/core/channel-loader.js +36 -13
  35. package/dist/core/channel-runtime.js +112 -42
  36. package/dist/core/command/command-handler.js +5 -5
  37. package/dist/core/command/menu-handler.js +8 -3
  38. package/dist/core/command/menu-protocol.js +82 -11
  39. package/dist/core/command/role-menu.js +27 -15
  40. package/dist/core/daemon-control.js +42 -15
  41. package/dist/core/daemon-lifecycle.js +411 -67
  42. package/dist/core/handoff/dispatcher.js +9 -3
  43. package/dist/core/handoff/runtime.js +130 -42
  44. package/dist/core/handoff/store.js +190 -2
  45. package/dist/core/handoff/types.js +5 -0
  46. package/dist/core/initialization/service.js +4 -4
  47. package/dist/core/ipc-registration.js +5 -4
  48. package/dist/core/lifecycle-notice.js +10 -4
  49. package/dist/core/message/aun-ipc-sender.js +2 -2
  50. package/dist/core/message/message-bridge.js +53 -4
  51. package/dist/core/message/message-queue.js +46 -4
  52. package/dist/core/message/pending-hints.js +4 -10
  53. package/dist/core/message/response-engine.js +10 -2
  54. package/dist/core/message/send-routing.js +12 -2
  55. package/dist/core/ownership/owner-resolver.js +1 -0
  56. package/dist/core/permission/ec-command-parser.js +11 -1
  57. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  58. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  59. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  60. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  61. package/dist/core/session/session-fs-store.js +164 -3
  62. package/dist/core/session/session-idle-monitor.js +9 -1
  63. package/dist/core/session/session-manager.js +36 -2
  64. package/dist/directory/owner-directory-admission.js +26 -1
  65. package/dist/directory/owner-directory-cache.js +57 -16
  66. package/dist/directory/owner-directory-query-operation.js +4 -1
  67. package/dist/ecweb/runtime/lifecycle.js +9 -7
  68. package/dist/ecweb/runtime/supervisor.js +44 -27
  69. package/dist/index.js +548 -251
  70. package/dist/proxy/manager.js +38 -17
  71. package/dist/proxy/service-supervisor.js +65 -31
  72. package/dist/trigger/application-service.js +3 -1
  73. package/dist/trigger/audit.js +19 -4
  74. package/dist/trigger/authorization.js +14 -5
  75. package/dist/trigger/history.js +176 -7
  76. package/dist/trigger/manager.js +1 -3
  77. package/dist/trigger/scheduler.js +78 -5
  78. package/dist/utils/cross-platform.js +152 -4
  79. package/dist/utils/host-info.js +11 -8
  80. package/dist/utils/npm-ops.js +48 -0
  81. package/dist/utils/process-introspect.js +64 -1
  82. package/dist/utils/startup-trace.js +160 -19
  83. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  84. package/kits/docs/evolcore/INDEX.md +3 -2
  85. package/kits/docs/evolcore/ctl.md +2 -1
  86. package/kits/docs/evolcore/group.md +2 -2
  87. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  88. package/kits/docs/evolcore/msg.md +13 -6
  89. package/kits/docs/evolcore/provider.md +21 -3
  90. package/kits/docs/evolcore/response.md +1 -1
  91. package/kits/eck_manifest.json +19 -7
  92. package/kits/eck_message_manifest.json +3 -3
  93. package/kits/rules/06-channel.md +5 -6
  94. package/kits/schemas/daemon.schema.1.json +5 -0
  95. package/kits/schemas/daemon.schema.2.json +5 -0
  96. package/kits/schemas/daemon.schema.3.json +2 -1
  97. package/kits/schemas/daemon.schema.4.json +2 -1
  98. package/kits/schemas/daemon.schema.5.json +2 -1
  99. package/kits/schemas/daemon.schema.6.json +1 -1
  100. package/kits/schemas/daemon.schema.7.json +1 -1
  101. package/kits/schemas/daemon.schema.8.json +2 -1
  102. package/kits/schemas/daemon.schema.9.json +2 -1
  103. package/kits/schemas/role-registry.schema.1.json +2 -2
  104. package/kits/schemas/single-session.schema.1.json +1 -1
  105. package/kits/schemas/single-session.schema.2.json +1 -1
  106. package/kits/schemas/single-session.schema.3.json +1 -1
  107. package/kits/skills/aid-ability/SKILL.md +7 -7
  108. package/kits/skills/ec-group/SKILL.md +8 -5
  109. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  110. package/kits/skills/ec-trigger/SKILL.md +4 -4
  111. package/kits/skills/thread-ops/SKILL.md +10 -10
  112. package/kits/templates/system-fragments/commands.md +5 -5
  113. package/kits/templates/system-fragments/reply.md +2 -1
  114. package/kits/templates/system-fragments/session.md +1 -1
  115. package/kits/templates/system-fragments/thread.md +1 -1
  116. package/package.json +4 -3
@@ -1,18 +1,110 @@
1
1
  import crypto from 'crypto';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
+ import { createInterface } from 'node:readline';
5
+ import { setImmediate as yieldToIo } from 'node:timers/promises';
4
6
  import { isManagedSessionRuntimeDir, SESSION_RUNTIME_DIR_ENV } from '../cli/task-context.js';
5
7
  import { findMessageLogOperationMessageId } from '../core/message/message-log.js';
6
8
  import { chatDirPath } from '../core/session/session-fs-store.js';
7
9
  import { resolvePaths } from '../paths.js';
8
10
  import { definitionRevision } from './validation.js';
9
11
  import * as aunOutbox from '../aun/outbox.js';
12
+ // Share streaming scans, without retaining the contents of the audit logs.
13
+ // Callers arriving after a pass starts join the next pass so no prefix is lost.
14
+ const sharedAuditScans = new Map();
15
+ function importSharedAuditLogs(logDir, agentAid, ready, accept) {
16
+ const directory = path.resolve(logDir);
17
+ const key = process.platform === 'win32' ? directory.toLowerCase() : directory;
18
+ const batch = sharedAuditScans.get(key) ?? { pending: [], running: false };
19
+ sharedAuditScans.set(key, batch);
20
+ const result = new Promise((resolve, reject) => {
21
+ const request = { agentAid, accept, resolve, reject, ready };
22
+ request.ready = ready.catch(error => { request.failed = true; reject(error); });
23
+ batch.pending.push(request);
24
+ });
25
+ const schedule = () => {
26
+ if (batch.running)
27
+ return;
28
+ batch.running = true;
29
+ setImmediate(() => {
30
+ const requests = batch.pending.splice(0);
31
+ void scanSharedAuditLogs(directory, requests).finally(() => {
32
+ batch.running = false;
33
+ if (batch.pending.length)
34
+ schedule();
35
+ else
36
+ sharedAuditScans.delete(key);
37
+ });
38
+ });
39
+ };
40
+ schedule();
41
+ return result;
42
+ }
43
+ async function scanSharedAuditLogs(logDir, requests) {
44
+ // Registration happens before local history I/O, so simultaneous startup
45
+ // callers share a pass even when their history callbacks arrive out of order.
46
+ await Promise.all(requests.map(request => request.ready));
47
+ const byAgent = new Map();
48
+ for (const request of requests) {
49
+ const matching = byAgent.get(request.agentAid) ?? [];
50
+ matching.push(request);
51
+ byAgent.set(request.agentAid, matching);
52
+ }
53
+ try {
54
+ let entries;
55
+ try {
56
+ entries = await fs.promises.readdir(logDir);
57
+ }
58
+ catch {
59
+ return;
60
+ }
61
+ for (const file of auditLogFiles(logDir, entries)) {
62
+ for await (const line of readLinesCooperatively(file)) {
63
+ let audit;
64
+ try {
65
+ audit = JSON.parse(line);
66
+ }
67
+ catch {
68
+ continue;
69
+ }
70
+ if (!audit?.runId || audit.status === 'dry-run')
71
+ continue;
72
+ for (const request of byAgent.get(audit.agentAid) ?? []) {
73
+ if (request.failed)
74
+ continue;
75
+ try {
76
+ request.accept(audit, path.basename(file));
77
+ }
78
+ catch (error) {
79
+ request.failed = true;
80
+ request.reject(error);
81
+ }
82
+ }
83
+ }
84
+ }
85
+ }
86
+ catch (error) {
87
+ for (const request of requests) {
88
+ if (!request.failed) {
89
+ request.failed = true;
90
+ request.reject(error);
91
+ }
92
+ }
93
+ }
94
+ finally {
95
+ for (const request of requests)
96
+ if (!request.failed)
97
+ request.resolve();
98
+ }
99
+ }
10
100
  export class TriggerHistoryStore {
11
101
  rootDir;
12
102
  agentAid;
13
103
  file;
14
104
  fallbackFile;
15
105
  runSummaryCache = null;
106
+ auditImport;
107
+ importingRunIds;
16
108
  constructor(rootDir, agentAid) {
17
109
  this.rootDir = rootDir;
18
110
  this.agentAid = agentAid;
@@ -58,6 +150,8 @@ export class TriggerHistoryStore {
58
150
  importedFrom,
59
151
  };
60
152
  this.append(event);
153
+ if (audit.agentAid === this.agentAid)
154
+ this.importingRunIds?.add(audit.runId);
61
155
  return event;
62
156
  }
63
157
  events(triggerId, limit = 100) {
@@ -226,17 +320,36 @@ export class TriggerHistoryStore {
226
320
  });
227
321
  }
228
322
  ensureDefinitionSnapshot(definition) {
229
- const revision = definitionRevision(definition);
230
- for (const event of this.events(definition.id, Number.MAX_SAFE_INTEGER)) {
231
- if (isDefinitionEvent(event) && event.revision === revision)
323
+ this.ensureDefinitionSnapshots([definition]);
324
+ }
325
+ ensureDefinitionSnapshots(definitions) {
326
+ const pending = new Map(definitions.map(definition => [definition.id, {
327
+ definition, revision: definitionRevision(definition),
328
+ }]));
329
+ if (pending.size === 0)
330
+ return;
331
+ // Snapshot migration needs revisions only, never delivery hydration. Read
332
+ // history once for the entire Agent instead of once per definition.
333
+ for (const line of this.readLines()) {
334
+ const event = parseHistoryEvent(line, this.agentAid);
335
+ if (!event || event.agentAid !== this.agentAid || !isDefinitionEvent(event))
336
+ continue;
337
+ if (pending.get(event.triggerId)?.revision === event.revision)
338
+ pending.delete(event.triggerId);
339
+ if (pending.size === 0)
232
340
  return;
233
341
  }
234
- this.recordDefinition('trigger.created', definition, { reason: 'migration_snapshot' });
342
+ for (const { definition } of pending.values()) {
343
+ this.recordDefinition('trigger.created', definition, { reason: 'migration_snapshot' });
344
+ }
235
345
  }
236
346
  importAuditLogs(logDir) {
237
- const knownRuns = new Set(this.events(undefined, Number.MAX_SAFE_INTEGER)
238
- .filter(isRunEvent)
239
- .map(event => event.audit.runId));
347
+ const knownRuns = new Set();
348
+ for (const line of this.readLines()) {
349
+ const event = parseHistoryEvent(line, this.agentAid);
350
+ if (event && event.agentAid === this.agentAid && isRunEvent(event))
351
+ knownRuns.add(event.audit.runId);
352
+ }
240
353
  let imported = 0;
241
354
  for (const file of listAuditLogFiles(logDir)) {
242
355
  let lines;
@@ -267,6 +380,39 @@ export class TriggerHistoryStore {
267
380
  }
268
381
  return imported;
269
382
  }
383
+ /** Daemon startup imports yield during both history and legacy audit scans. */
384
+ importAuditLogsAsync(logDir) {
385
+ if (this.auditImport)
386
+ return this.auditImport;
387
+ const knownRuns = new Set();
388
+ // A live audit written while scanning must not be imported a second time.
389
+ this.importingRunIds = knownRuns;
390
+ this.auditImport = this.importAuditLogsCooperatively(logDir, knownRuns).finally(() => {
391
+ this.auditImport = undefined;
392
+ this.importingRunIds = undefined;
393
+ });
394
+ return this.auditImport;
395
+ }
396
+ async importAuditLogsCooperatively(logDir, knownRuns) {
397
+ const ready = (async () => {
398
+ for (const file of [this.file, this.fallbackFile].filter((value) => !!value)) {
399
+ for await (const line of readLinesCooperatively(file)) {
400
+ const event = parseHistoryEvent(line, this.agentAid);
401
+ if (event && event.agentAid === this.agentAid && isRunEvent(event))
402
+ knownRuns.add(event.audit.runId);
403
+ }
404
+ }
405
+ })();
406
+ let imported = 0;
407
+ await importSharedAuditLogs(logDir, this.agentAid, ready, (audit, file) => {
408
+ if (knownRuns.has(audit.runId))
409
+ return;
410
+ this.recordRun(audit, file);
411
+ knownRuns.add(audit.runId);
412
+ imported++;
413
+ });
414
+ return imported;
415
+ }
270
416
  append(event) {
271
417
  const line = `${JSON.stringify(event)}\n`;
272
418
  try {
@@ -453,8 +599,31 @@ function listAuditLogFiles(logDir) {
453
599
  catch {
454
600
  return [];
455
601
  }
602
+ return auditLogFiles(logDir, entries);
603
+ }
604
+ function auditLogFiles(logDir, entries) {
456
605
  return entries
457
606
  .filter(file => file === 'trigger-runs.log' || /^trigger-runs-\d{8}\.log$/.test(file))
458
607
  .sort()
459
608
  .map(file => path.join(logDir, file));
460
609
  }
610
+ async function* readLinesCooperatively(file) {
611
+ const input = fs.createReadStream(file, { encoding: 'utf8' });
612
+ const lines = createInterface({ input, crlfDelay: Infinity });
613
+ let count = 0;
614
+ try {
615
+ for await (const line of lines) {
616
+ if (line)
617
+ yield line;
618
+ if (++count % 128 === 0)
619
+ await yieldToIo();
620
+ }
621
+ }
622
+ catch {
623
+ // Preserve the synchronous import's tolerance of missing/inaccessible logs.
624
+ }
625
+ finally {
626
+ lines.close();
627
+ input.destroy();
628
+ }
629
+ }
@@ -15,9 +15,7 @@ export class TriggerDefinitionManager {
15
15
  fs.mkdirSync(this.rootDir, { recursive: true });
16
16
  assertRealDirectory(this.rootDir, 'Trigger root');
17
17
  this.history = new TriggerHistoryStore(rootDir, agentAid);
18
- for (const definition of this.list({ all: true })) {
19
- this.history.ensureDefinitionSnapshot(definition);
20
- }
18
+ this.history.ensureDefinitionSnapshots(this.list({ all: true }));
21
19
  }
22
20
  list(opts = {}) {
23
21
  const definitions = [];
@@ -33,12 +33,14 @@ export class TriggerRuntimeScheduler {
33
33
  eventBus;
34
34
  targetSessionLocks;
35
35
  timers = new Map();
36
+ authorizationRetries = new Map();
36
37
  running = new Map();
37
38
  runStartLocks = new Map();
38
39
  recoveredOneShotIds = new Set();
39
40
  eventSource;
40
41
  initialized = false;
41
42
  stopping = false;
43
+ lifecycleGeneration = 0;
42
44
  constructor(manager, state, audit, scriptExecutor, feedback, daemonChannel, runtime, eventBus, targetSessionLocks = new TargetSessionLockRegistry()) {
43
45
  this.manager = manager;
44
46
  this.state = state;
@@ -56,10 +58,19 @@ export class TriggerRuntimeScheduler {
56
58
  }
57
59
  }
58
60
  async init() {
59
- await this.stop();
61
+ const stopped = this.stop();
62
+ const generation = this.lifecycleGeneration;
63
+ await stopped;
64
+ if (generation !== this.lifecycleGeneration)
65
+ return;
60
66
  this.stopping = false;
61
67
  this.recoveredOneShotIds.clear();
68
+ await this.audit.initializeHistory?.();
69
+ if (this.stopping || generation !== this.lifecycleGeneration)
70
+ return;
62
71
  await this.recoverOpenRuns();
72
+ if (this.stopping || generation !== this.lifecycleGeneration)
73
+ return;
63
74
  for (const definition of this.manager.list()) {
64
75
  if (this.recoveredOneShotIds.has(definition.id))
65
76
  continue;
@@ -70,7 +81,9 @@ export class TriggerRuntimeScheduler {
70
81
  logger.info(`[Trigger] scheduler initialized for ${this.manager.agentAid}`);
71
82
  }
72
83
  async stop() {
84
+ this.lifecycleGeneration++;
73
85
  this.stopping = true;
86
+ this.clearAuthorizationRetries();
74
87
  for (const timer of this.timers.values())
75
88
  clearTimeout(timer);
76
89
  this.timers.clear();
@@ -93,7 +106,9 @@ export class TriggerRuntimeScheduler {
93
106
  * Explicit scheduler replacement/unload must continue to use stop().
94
107
  */
95
108
  async suspendForDaemonExit() {
109
+ this.lifecycleGeneration++;
96
110
  this.stopping = true;
111
+ this.clearAuthorizationRetries();
97
112
  for (const timer of this.timers.values())
98
113
  clearTimeout(timer);
99
114
  this.timers.clear();
@@ -431,7 +446,8 @@ export class TriggerRuntimeScheduler {
431
446
  return;
432
447
  }
433
448
  const result = await runPromise;
434
- if (result.status === 'running' && result.reason === 'daemon_restart_resume_pending')
449
+ if (result.reason === 'authorization_unavailable'
450
+ || (result.status === 'running' && result.reason === 'daemon_restart_resume_pending'))
435
451
  return;
436
452
  const fresh = this.manager.get(triggerId);
437
453
  if (fresh?.enabled && definitionRevision(fresh) === firedRevision) {
@@ -471,6 +487,24 @@ export class TriggerRuntimeScheduler {
471
487
  return { ok: false, runId, triggerId: definition.id, status: 'failed', reason: 'invalid_execution_configuration', audit, error: message };
472
488
  }
473
489
  const executionAuthorization = await this.runtime.authorizeExecution?.(definition);
490
+ if (executionAuthorization?.retryable && !executionAuthorization.allowed) {
491
+ if (!payload.dryRun)
492
+ this.deferAuthorization(definition, definition.id, async (current) => {
493
+ const result = await this.startRun(current, payload);
494
+ if (payload.scheduledAt !== undefined && this.isOneShot(current.source) && result.reason !== 'authorization_unavailable'
495
+ && result.reason !== 'stopped' && this.manager.get(current.id)?.enabled
496
+ && definitionRevision(this.manager.get(current.id)) === definitionRevision(current)) {
497
+ this.setEnabled(current.id, false);
498
+ }
499
+ });
500
+ return { ok: false, runId, triggerId: definition.id, status: 'skipped', reason: 'authorization_unavailable' };
501
+ }
502
+ if (!payload.dryRun) {
503
+ const pending = this.authorizationRetries.get(definition.id);
504
+ if (pending)
505
+ clearTimeout(pending);
506
+ this.authorizationRetries.delete(definition.id);
507
+ }
474
508
  if (executionAuthorization && !executionAuthorization.allowed) {
475
509
  const reason = executionAuthorization.reason || 'execution_authorization_denied';
476
510
  const failureNotice = payload.dryRun
@@ -843,9 +877,17 @@ export class TriggerRuntimeScheduler {
843
877
  }
844
878
  async runRecordedExecutionAttempt(definition, runId, firedAt, sourcePayload, signal, dryRun, causation, attempt, previousAttempt) {
845
879
  const attemptId = `${runId}:attempt:${attempt}`;
846
- const executionAuthorization = await this.runtime.authorizeExecution?.(definition);
880
+ let executionAuthorization = await this.runtime.authorizeExecution?.(definition);
881
+ while (executionAuthorization?.retryable && !executionAuthorization.allowed && !dryRun) {
882
+ if (!await sleep(5_000, signal))
883
+ throw new Error('Trigger authorization wait cancelled');
884
+ executionAuthorization = await this.runtime.authorizeExecution?.(definition);
885
+ }
886
+ if (signal.aborted)
887
+ throw new Error('Trigger execution cancelled');
847
888
  if (executionAuthorization && !executionAuthorization.allowed) {
848
- const reply = errorReply(runId, 0, 'authorization_denied', executionAuthorization.reason || 'Trigger execution authorization denied');
889
+ const reason = executionAuthorization.retryable ? 'authorization_unavailable' : 'authorization_denied';
890
+ const reply = errorReply(runId, 0, reason, executionAuthorization.reason || 'Trigger execution authorization denied');
849
891
  const execution = {
850
892
  script: null,
851
893
  processing: { mode: definition.execution.type },
@@ -859,7 +901,7 @@ export class TriggerRuntimeScheduler {
859
901
  });
860
902
  this.state.completeExecutionAttempt?.(definition.id, runId, attemptId, {
861
903
  status: 'failed',
862
- error: { code: 'authorization_denied', message: reply.error?.text || 'Trigger execution authorization denied' },
904
+ error: { code: reason, message: reply.error?.text || 'Trigger execution authorization denied' },
863
905
  });
864
906
  }
865
907
  return execution;
@@ -1161,10 +1203,41 @@ export class TriggerRuntimeScheduler {
1161
1203
  }
1162
1204
  }
1163
1205
  }
1206
+ clearAuthorizationRetries() {
1207
+ for (const timer of this.authorizationRetries.values())
1208
+ clearTimeout(timer);
1209
+ this.authorizationRetries.clear();
1210
+ }
1211
+ deferAuthorization(definition, key, retry) {
1212
+ if (this.stopping || this.authorizationRetries.has(key))
1213
+ return;
1214
+ const revision = definitionRevision(definition);
1215
+ logger.info(`[Trigger] waiting for authorization evidence: trigger=${definition.id}`);
1216
+ const timer = setTimeout(() => {
1217
+ this.authorizationRetries.delete(key);
1218
+ const current = this.manager.get(definition.id);
1219
+ if (this.stopping || !current?.enabled || definitionRevision(current) !== revision)
1220
+ return;
1221
+ void retry(current).catch(error => logger.warn(`[Trigger] deferred authorization failed: ${definition.id}: ${error}`));
1222
+ }, 5_000);
1223
+ timer.unref?.();
1224
+ this.authorizationRetries.set(key, timer);
1225
+ }
1164
1226
  async reclaimOpenRun(definition, run) {
1165
1227
  if (!definition.enabled || !this.isResumableCheckpoint(definition, run))
1166
1228
  return false;
1167
1229
  const executionAuthorization = await this.runtime.authorizeExecution?.(definition);
1230
+ if (executionAuthorization?.retryable && !executionAuthorization.allowed) {
1231
+ this.deferAuthorization(definition, run.runId, async (current) => {
1232
+ if (!this.state.list(current.id).some(active => active.runId === run.runId))
1233
+ return;
1234
+ if (!await this.reclaimOpenRun(current, run))
1235
+ await this.closeOpenRunAfterRestart(current, run);
1236
+ });
1237
+ if (this.isOneShot(definition.source))
1238
+ this.recoveredOneShotIds.add(definition.id);
1239
+ return true;
1240
+ }
1168
1241
  if (executionAuthorization && !executionAuthorization.allowed) {
1169
1242
  const reason = executionAuthorization.reason || 'Trigger execution authorization denied';
1170
1243
  const notice = await this.disableAndNotifyAuthorizationDenied(definition, run.runId, run.source?.firedAt ?? Date.now(), reason, createRootCausation());
@@ -8,6 +8,8 @@ import { getProcessStartTime, parseCimDate } from './process-introspect.js';
8
8
  import { resolveTrustedWindowsCmdPath } from './windows-shell-trust.js';
9
9
  const execFileAsync = promisify(execFile);
10
10
  const CLI_PROBE_FAILURE_BACKOFF_MS = 5_000;
11
+ export const CODEX_CLI_PROBE_TIMEOUT_MS = 9_000;
12
+ export const CODEX_CLI_PROBE_RETRY_TIMEOUT_MS = 15_000;
11
13
  const CLI_PROBE_PACKAGES = {
12
14
  codex: '@openai/codex',
13
15
  claude: '@anthropic-ai/claude-code',
@@ -184,13 +186,51 @@ export function invalidateCliProbes() {
184
186
  cliProbeCache.clear();
185
187
  }
186
188
  function cliProbeTimeouts(command, options) {
187
- return options.timeouts?.length ? options.timeouts : command === 'codex' ? [3_000, 15_000] : [3_000];
189
+ return options.timeouts?.length ? options.timeouts : command === 'codex'
190
+ ? [CODEX_CLI_PROBE_TIMEOUT_MS, CODEX_CLI_PROBE_RETRY_TIMEOUT_MS] : [3_000];
191
+ }
192
+ /** The stock npm shim adds cmd + node before Codex, outside a reliable Windows timeout. */
193
+ function codexProbeExecutable(executable) {
194
+ if (!isWindows || !/\.(?:cmd|bat)$/i.test(executable))
195
+ return executable;
196
+ try {
197
+ const shim = fs.readFileSync(executable, 'utf8');
198
+ // Preserve custom launchers. Only the stock npm entry for this installation
199
+ // may be shortened for read-only --version/app-server --help probes.
200
+ if (!/^@ECHO off\r?\nGOTO start\r?\n/i.test(shim)
201
+ || !shim.includes('%dp0%\\node_modules\\@openai\\codex\\bin\\codex.js'))
202
+ return executable;
203
+ const packageFile = path.join(path.dirname(executable), 'node_modules', '@openai', 'codex', 'package.json');
204
+ const manifest = JSON.parse(fs.readFileSync(packageFile, 'utf8'));
205
+ if (manifest.name !== '@openai/codex' || manifest.bin?.codex !== 'bin/codex.js')
206
+ return executable;
207
+ const arch = process.arch === 'x64' ? 'x86_64' : process.arch === 'arm64' ? 'aarch64' : null;
208
+ if (!arch)
209
+ return executable;
210
+ let vendorRoot;
211
+ try {
212
+ const platformFile = createRequire(packageFile).resolve(`@openai/codex-win32-${process.arch}/package.json`);
213
+ vendorRoot = path.join(path.dirname(platformFile), 'vendor');
214
+ }
215
+ catch {
216
+ vendorRoot = path.join(path.dirname(packageFile), 'vendor');
217
+ }
218
+ const binary = path.join(vendorRoot, `${arch}-pc-windows-msvc`, 'bin', 'codex.exe');
219
+ if (fs.statSync(binary).isFile())
220
+ return binary;
221
+ }
222
+ catch { /* Incomplete or non-npm installations retain their configured entrypoint. */ }
223
+ return executable;
188
224
  }
189
225
  function prepareCliProbe(command, args, options = {}) {
190
226
  const executable = options.executable ?? resolveProbePath(command);
191
227
  if (!executable)
192
228
  throw Object.assign(new Error(`${command} CLI not found`), { code: 'ENOENT' });
193
- const launchCommand = buildCliLaunchCommand(executable, args);
229
+ const probeExecutable = command === 'codex'
230
+ && (args.length === 1 && args[0] === '--version'
231
+ || args.length === 2 && args[0] === 'app-server' && args[1] === '--help')
232
+ ? codexProbeExecutable(executable) : executable;
233
+ const launchCommand = buildCliLaunchCommand(probeExecutable, args);
194
234
  const launch = launchCommand;
195
235
  const identity = `${probeInstallationIdentity(command, executable)}|${cliFileIdentity(launch.launcherPath)}`;
196
236
  const key = JSON.stringify([command, args]);
@@ -731,6 +771,42 @@ export function isProcessRunning(pid) {
731
771
  return e.code === 'EPERM';
732
772
  }
733
773
  }
774
+ const processLivenessQueries = new Map();
775
+ /** Share concurrent Windows probes, but never cache liveness across checks. */
776
+ export async function isProcessRunningAsync(pid) {
777
+ if (!Number.isInteger(pid) || pid <= 0)
778
+ return false;
779
+ if (!isWindows)
780
+ return isProcessRunning(pid);
781
+ const pending = processLivenessQueries.get(pid);
782
+ if (pending)
783
+ return pending;
784
+ const query = (async () => {
785
+ try {
786
+ const { stdout } = await execFileAsync('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], {
787
+ encoding: 'utf8', timeout: 3000, windowsHide: true,
788
+ });
789
+ if (new RegExp(`,"${pid}",`, 'i').test(stdout))
790
+ return true;
791
+ }
792
+ catch { /* Retain the conservative native fallback on query failure. */ }
793
+ try {
794
+ process.kill(pid, 0);
795
+ return true;
796
+ }
797
+ catch (error) {
798
+ return error.code === 'EPERM';
799
+ }
800
+ })();
801
+ processLivenessQueries.set(pid, query);
802
+ try {
803
+ return await query;
804
+ }
805
+ finally {
806
+ if (processLivenessQueries.get(pid) === query)
807
+ processLivenessQueries.delete(pid);
808
+ }
809
+ }
734
810
  function isWindowsProcessRunning(pid) {
735
811
  try {
736
812
  const result = spawnSync('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], { encoding: 'utf-8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
@@ -909,7 +985,7 @@ export function findProcessByPort(port) {
909
985
  const pids = new Set();
910
986
  try {
911
987
  if (isWindows) {
912
- const result = spawnSync('netstat', ['-ano', '-p', 'TCP'], { encoding: 'utf-8', windowsHide: true });
988
+ const result = spawnSync('netstat', ['-ano', '-p', 'TCP'], { encoding: 'utf-8', windowsHide: true, timeout: 3000 });
913
989
  const output = result.stdout || '';
914
990
  for (const line of output.split('\n')) {
915
991
  // 形如: TCP 0.0.0.0:42705 0.0.0.0:0 LISTENING 23004
@@ -924,7 +1000,7 @@ export function findProcessByPort(port) {
924
1000
  }
925
1001
  }
926
1002
  else {
927
- const output = execFileSync('lsof', ['-ti', `tcp:${port}`, '-sTCP:LISTEN'], { encoding: 'utf-8' }).trim();
1003
+ const output = execFileSync('lsof', ['-ti', `tcp:${port}`, '-sTCP:LISTEN'], { encoding: 'utf-8', timeout: 3000 }).trim();
928
1004
  for (const line of output.split('\n')) {
929
1005
  const pid = parseInt(line.trim(), 10);
930
1006
  if (pid && pid !== process.pid)
@@ -935,6 +1011,55 @@ export function findProcessByPort(port) {
935
1011
  catch { /* netstat/lsof missing or no match */ }
936
1012
  return [...pids];
937
1013
  }
1014
+ let tcpListenersQuery;
1015
+ /**
1016
+ * Share concurrent Windows port scans, without retaining stale ownership data.
1017
+ * Missing optional lsof yields no known PIDs; callers must still bind/probe the service.
1018
+ */
1019
+ export async function findProcessByPortAsync(port) {
1020
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
1021
+ throw new Error('Invalid TCP port');
1022
+ let output;
1023
+ if (isWindows) {
1024
+ const query = tcpListenersQuery ??= execFileAsync('netstat', ['-ano', '-p', 'TCP'], {
1025
+ encoding: 'utf8', windowsHide: true, timeout: 3000, maxBuffer: 4 * 1024 * 1024,
1026
+ }).then(result => result.stdout);
1027
+ try {
1028
+ output = (await query) ?? '';
1029
+ }
1030
+ finally {
1031
+ if (tcpListenersQuery === query)
1032
+ tcpListenersQuery = undefined;
1033
+ }
1034
+ }
1035
+ else {
1036
+ try {
1037
+ output = ((await execFileAsync('lsof', ['-ti', `tcp:${port}`, '-sTCP:LISTEN'], {
1038
+ encoding: 'utf8', timeout: 3000,
1039
+ })).stdout ?? '');
1040
+ }
1041
+ catch (error) {
1042
+ const detail = error;
1043
+ // lsof is optional on Unix, as in the synchronous port lookup.
1044
+ if (detail.code === 'ENOENT')
1045
+ return [];
1046
+ // lsof uses exit 1, with no output, to report an empty selection.
1047
+ if (detail.code === 1 && !detail.stdout?.trim() && !detail.stderr?.trim())
1048
+ return [];
1049
+ throw error;
1050
+ }
1051
+ }
1052
+ const pids = new Set();
1053
+ for (const line of output.split('\n')) {
1054
+ const match = isWindows ? line.match(/:(\d+)\s+\S+\s+LISTENING\s+(\d+)/i) : null;
1055
+ if (isWindows && (!match || Number(match[1]) !== port))
1056
+ continue;
1057
+ const pid = Number(isWindows ? match[2] : line.trim());
1058
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid)
1059
+ pids.add(pid);
1060
+ }
1061
+ return [...pids];
1062
+ }
938
1063
  export function getProcessInfo(pid) {
939
1064
  try {
940
1065
  if (isWindows) {
@@ -1014,6 +1139,29 @@ function parseDateString(value) {
1014
1139
  * Cross-platform command existence check.
1015
1140
  */
1016
1141
  const _commandExistsCache = new Map();
1142
+ const commandExistsPending = new Map();
1143
+ /** Daemon inventory probes must not block IPC on where/which. */
1144
+ export async function commandExistsAsync(cmd) {
1145
+ const cached = _commandExistsCache.get(cmd);
1146
+ if (cached !== undefined)
1147
+ return cached;
1148
+ const existing = commandExistsPending.get(cmd);
1149
+ if (existing)
1150
+ return existing;
1151
+ const pending = execFileAsync(isWindows ? 'where.exe' : 'which', [cmd], {
1152
+ encoding: 'utf8', windowsHide: true, timeout: 3_000,
1153
+ }).then(() => true, () => false);
1154
+ commandExistsPending.set(cmd, pending);
1155
+ try {
1156
+ const exists = await pending;
1157
+ _commandExistsCache.set(cmd, exists);
1158
+ return exists;
1159
+ }
1160
+ finally {
1161
+ if (commandExistsPending.get(cmd) === pending)
1162
+ commandExistsPending.delete(cmd);
1163
+ }
1164
+ }
1017
1165
  export function commandExists(cmd) {
1018
1166
  const cached = _commandExistsCache.get(cmd);
1019
1167
  if (cached !== undefined)
@@ -17,7 +17,7 @@ import { execFile } from 'node:child_process';
17
17
  import { readSystemMemoryUsage } from './system-memory.js';
18
18
  import { getPackageRoot } from '../paths.js';
19
19
  import { WEB_PACKAGE_NAME } from '../product.js';
20
- import { buildCliLaunchCommand, resolveProbePath } from './cross-platform.js';
20
+ import { probeCli, resolveProbePath } from './cross-platform.js';
21
21
  function readJsonVersion(filePath) {
22
22
  try {
23
23
  const pkg = JSON.parse(fs.readFileSync(filePath, 'utf8'));
@@ -195,8 +195,8 @@ function runExec(command, args, timeoutMs, windowsVerbatimArguments = false) {
195
195
  * 按 PATH 探测一个 CLI 的版本。
196
196
  *
197
197
  * 不能直接 execFile('claude'):Windows 上 npm 装的是 claude.cmd,Node 25 对 .cmd
198
- * 直接 spawn 会报 EINVAL。走 resolveProbePath + buildCliLaunchCommand,与
199
- * baseagent 探测同一套启动规则(.cmd 经受信任的 cmd.exe 转发)。
198
+ * 直接 spawn 会报 EINVAL。复用 baseagent 的探测缓存和在途请求,保留原生
199
+ * Codex 入口探测及 .cmd 经受信任 cmd.exe 转发的规则。
200
200
  */
201
201
  async function probeCliVersion(command, args, timeoutMs) {
202
202
  try {
@@ -207,9 +207,10 @@ async function probeCliVersion(command, args, timeoutMs) {
207
207
  const raw = await runExec(command, args, timeoutMs);
208
208
  return raw.ok ? firstVersionLine(raw.stdout) : null;
209
209
  }
210
- const launch = buildCliLaunchCommand(executable, args);
211
- const result = await runExec(launch.command, launch.args, timeoutMs, launch.windowsVerbatimArguments);
212
- return result.ok ? firstVersionLine(result.stdout) : null;
210
+ const output = await probeCli(command, args, {
211
+ executable, timeouts: [timeoutMs], validateOutput: value => firstVersionLine(value) !== null,
212
+ });
213
+ return firstVersionLine(output);
213
214
  }
214
215
  catch {
215
216
  return null;
@@ -299,8 +300,10 @@ async function probeBundledClaudeVersion() {
299
300
  const executable = resolveBundledClaudeExecutable();
300
301
  if (!executable)
301
302
  return null;
302
- const result = await runExec(executable, ['--version'], 8000);
303
- return result.ok ? firstVersionLine(result.stdout) : null;
303
+ const output = await probeCli('bundled-claude', ['--version'], {
304
+ executable, timeouts: [8000], validateOutput: value => firstVersionLine(value) !== null,
305
+ });
306
+ return firstVersionLine(output);
304
307
  }
305
308
  catch {
306
309
  return null;