evolcore 0.0.39 → 0.0.41-test.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +31 -20
  3. package/bin/codex-managed-hook.mjs +11 -0
  4. package/bin/ec-safe-output.js +25 -3
  5. package/dist/agents/baseagent-availability.js +1 -0
  6. package/dist/agents/claude-runner.js +53 -152
  7. package/dist/agents/codex-runner.js +485 -241
  8. package/dist/agents/ecagent-runner.js +48 -18
  9. package/dist/agents/gemini-runner.js +27 -8
  10. package/dist/agents/runner-types.js +39 -9
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/aid/control-aid.js +23 -98
  14. package/dist/aun/aid/ownership-operation.js +1 -3
  15. package/dist/aun/group/identity.js +8 -0
  16. package/dist/aun/group/invite-service.js +6 -0
  17. package/dist/aun/msg/managed-operation.js +4 -4
  18. package/dist/aun/msg/p2p.js +28 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +99 -52
  22. package/dist/channels/daemon.js +24 -4
  23. package/dist/channels/dingtalk.js +8 -2
  24. package/dist/channels/feishu.js +6 -1
  25. package/dist/channels/wecom.js +7 -3
  26. package/dist/cli/agent-command.js +2 -0
  27. package/dist/cli/agent-create.js +121 -23
  28. package/dist/cli/agent.js +10 -3
  29. package/dist/cli/aid-bind-command.js +4 -1
  30. package/dist/cli/aun-commands.js +82 -22
  31. package/dist/cli/daemon-commands.js +260 -26
  32. package/dist/cli/index.js +25 -13
  33. package/dist/cli/memory-command.js +33 -14
  34. package/dist/cli/restart-monitor.js +52 -13
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/task-context.js +1 -0
  38. package/dist/cli/trigger-command.js +2 -2
  39. package/dist/config/access-policy.js +2 -0
  40. package/dist/config/config-field-policy.js +1 -0
  41. package/dist/config/config-operation-service.js +17 -6
  42. package/dist/config/gateway-config.js +1 -1
  43. package/dist/config/peer-role-resolver.js +10 -8
  44. package/dist/contracts/ecweb-service-protocol.js +44 -0
  45. package/dist/core/agent-application-service.js +11 -1
  46. package/dist/core/agent-ipc-registration.js +4 -0
  47. package/dist/core/agent-runtime.js +6 -0
  48. package/dist/core/auth/agent-delegation.js +87 -9
  49. package/dist/core/auth/auth-gateway.js +3 -1
  50. package/dist/core/auth/authorization-audit.js +25 -4
  51. package/dist/core/auth/debug-context.js +5 -1
  52. package/dist/core/auth/operation-catalog.js +24 -0
  53. package/dist/core/command/agent-control.js +91 -12
  54. package/dist/core/command/command-handler.js +64 -47
  55. package/dist/core/command/connect-menu.js +23 -2
  56. package/dist/core/command/menu-catalog.js +49 -12
  57. package/dist/core/command/menu-handler.js +110 -105
  58. package/dist/core/command/menu-protocol.js +29 -3
  59. package/dist/core/command/role-menu.js +7 -6
  60. package/dist/core/command/slash-gate.js +22 -5
  61. package/dist/core/command/slash-handler.js +121 -102
  62. package/dist/core/event-catalog.js +17 -0
  63. package/dist/core/interaction-router.js +2 -1
  64. package/dist/core/ipc-registration.js +44 -8
  65. package/dist/core/memory/batch-meta.js +2 -0
  66. package/dist/core/memory/consolidation-context.js +42 -51
  67. package/dist/core/memory/consolidation-ops-records.js +39 -7
  68. package/dist/core/memory/consolidation-trigger.js +72 -65
  69. package/dist/core/memory/consolidation.js +226 -20
  70. package/dist/core/memory/memory-writer.js +160 -34
  71. package/dist/core/memory/relation-idle-monitor.js +287 -0
  72. package/dist/core/memory/relation-sweep.js +206 -0
  73. package/dist/core/message/aun-ipc-sender.js +31 -5
  74. package/dist/core/message/aun-request-registry.js +97 -3
  75. package/dist/core/message/im-renderer.js +4 -0
  76. package/dist/core/message/message-admission.js +8 -4
  77. package/dist/core/message/message-bridge.js +96 -53
  78. package/dist/core/message/message-log.js +72 -0
  79. package/dist/core/message/message-queue.js +11 -5
  80. package/dist/core/message/outbound.js +70 -0
  81. package/dist/core/message/peer-mode.js +7 -2
  82. package/dist/core/message/response-engine.js +633 -191
  83. package/dist/core/model/model-catalog.js +7 -6
  84. package/dist/core/ownership/owner-resolver.js +384 -178
  85. package/dist/core/permission/ec-command-parser.js +129 -8
  86. package/dist/core/permission/tool-policy.js +35 -14
  87. package/dist/core/role/runtime-policy.js +64 -0
  88. package/dist/core/session/session-capsule.js +197 -0
  89. package/dist/core/session/session-manager.js +172 -18
  90. package/dist/core/session/session-mapper.js +2 -0
  91. package/dist/core/system-session/memory.js +3 -18
  92. package/dist/ecweb/basic-settings-service.js +709 -0
  93. package/dist/ecweb/providers-service.js +172 -0
  94. package/dist/index.js +95 -7
  95. package/dist/ipc.js +100 -19
  96. package/dist/stats/budget.js +1 -1
  97. package/dist/stats/db.js +48 -0
  98. package/dist/stats/index.js +3 -3
  99. package/dist/stats/price-resolver.js +304 -5
  100. package/dist/stats/query.js +328 -3
  101. package/dist/stats/writer.js +79 -6
  102. package/dist/trigger/application-service.js +12 -0
  103. package/dist/trigger/authorization.js +2 -2
  104. package/dist/trigger/feedback.js +18 -7
  105. package/dist/trigger/history.js +36 -0
  106. package/dist/trigger/manager.js +20 -3
  107. package/dist/trigger/parser.js +6 -3
  108. package/dist/trigger/patch.js +1 -1
  109. package/dist/trigger/scheduler.js +3 -0
  110. package/dist/trigger/system-definitions.js +43 -7
  111. package/dist/trigger/validation.js +13 -5
  112. package/dist/utils/ecweb-supervisor.js +31 -10
  113. package/dist/utils/error-utils.js +22 -4
  114. package/dist/utils/evolcore-version.js +3 -2
  115. package/dist/utils/host-info.js +52 -0
  116. package/dist/utils/npm-ops.js +2 -1
  117. package/dist/utils/package-version-info.js +1 -1
  118. package/dist/utils/upgrade-jobs.js +45 -5
  119. package/ecagent/dist/harness/agent-harness.js +4 -1
  120. package/kits/docs/INDEX.md +1 -1
  121. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  122. package/kits/docs/evolcore/INDEX.md +3 -2
  123. package/kits/docs/evolcore/agent-create.md +3 -2
  124. package/kits/docs/evolcore/agent.md +1 -1
  125. package/kits/docs/evolcore/aid.md +29 -12
  126. package/kits/docs/evolcore/config.md +9 -7
  127. package/kits/docs/evolcore/event.md +1 -0
  128. package/kits/docs/evolcore/fs.md +5 -0
  129. package/kits/docs/evolcore/memory-architecture.md +3 -4
  130. package/kits/docs/evolcore/memory-consolidation.md +28 -7
  131. package/kits/docs/evolcore/memory-tags.md +1 -1
  132. package/kits/docs/evolcore/memory.md +1 -1
  133. package/kits/docs/evolcore/menu-client.md +1 -1
  134. package/kits/docs/evolcore/menu-protocol.md +38 -0
  135. package/kits/docs/evolcore/msg.md +18 -2
  136. package/kits/docs/evolcore/session.md +14 -0
  137. package/kits/eck_manifest.json +3 -3
  138. package/kits/rules/04-relation.md +3 -2
  139. package/kits/schemas/agent-config.schema.13.json +20 -1
  140. package/kits/skills/aid-ability/SKILL.md +35 -6
  141. package/kits/templates/memory-consolidation/generalize.md +32 -4
  142. package/kits/templates/memory-consolidation/notes.md +2 -2
  143. package/kits/templates/memory-consolidation/promote.md +10 -2
  144. package/kits/templates/session-capsule/recovery.md +5 -0
  145. package/kits/templates/session-capsule/renew.md +5 -0
  146. package/kits/templates/system-fragments/baseagent.md +5 -0
  147. package/kits/templates/system-fragments/bootstrap.md +6 -6
  148. package/kits/templates/system-fragments/channel.md +1 -1
  149. package/kits/templates/system-fragments/memory.md +12 -3
  150. package/kits/templates/system-fragments/session.md +1 -1
  151. package/kits/{rules/07-memory-and-thread.md → templates/system-fragments/thread.md} +17 -80
  152. package/package.json +3 -3
  153. package/dist/stats/billing.js +0 -215
@@ -127,7 +127,21 @@ export function insertContextBreakdown(evolcoreHome, bd) {
127
127
  import('../utils/logger.js').then(({ logger }) => logger.warn(`[StatsWriter] insertContextBreakdown failed: ${e}`));
128
128
  }
129
129
  }
130
- export function initializeStatsPersistence(evolcoreHome, collector) {
130
+ export function insertActivityEvent(evolcoreHome, event) {
131
+ const db = getDb(evolcoreHome);
132
+ if (!db)
133
+ return;
134
+ try {
135
+ db.prepare(`
136
+ INSERT INTO activity_events (ts, agent_aid, type, duration_ms, error_type)
137
+ VALUES (?, ?, ?, ?, ?)
138
+ `).run(event.ts, event.agent_aid ?? '', event.type, event.duration_ms ?? null, event.error_type ?? null);
139
+ }
140
+ catch (error) {
141
+ logger.warn(`[StatsWriter] insertActivityEvent failed: ${error}`);
142
+ }
143
+ }
144
+ export function initializeStatsPersistence(evolcoreHome, collector, eventBus) {
131
145
  const previousOnMessage = collector.onMessage;
132
146
  const onMessage = (event) => {
133
147
  void Promise.resolve()
@@ -135,6 +149,28 @@ export function initializeStatsPersistence(evolcoreHome, collector) {
135
149
  .catch(() => { });
136
150
  };
137
151
  collector.onMessage = onMessage;
152
+ const activityHandlers = [];
153
+ const subscribeActivity = (type, handler) => {
154
+ if (!eventBus)
155
+ return;
156
+ eventBus.subscribe(type, handler);
157
+ activityHandlers.push([type, handler]);
158
+ };
159
+ subscribeActivity('task:completed', event => {
160
+ void Promise.resolve().then(() => insertActivityEvent(evolcoreHome, {
161
+ ts: event.timestamp ?? Date.now(), agent_aid: event.agentAid, type: 'completed', duration_ms: event.durationMs,
162
+ })).catch(() => { });
163
+ });
164
+ subscribeActivity('task:error', event => {
165
+ void Promise.resolve().then(() => insertActivityEvent(evolcoreHome, {
166
+ ts: event.timestamp ?? Date.now(), agent_aid: event.agentAid, type: 'error', error_type: event.errorType,
167
+ })).catch(() => { });
168
+ });
169
+ subscribeActivity('task:interrupted', event => {
170
+ void Promise.resolve().then(() => insertActivityEvent(evolcoreHome, {
171
+ ts: event.timestamp ?? Date.now(), agent_aid: event.agentAid, type: 'interrupted',
172
+ })).catch(() => { });
173
+ });
138
174
  let stopped = false;
139
175
  let maintenanceTimer;
140
176
  void Promise.resolve()
@@ -147,6 +183,10 @@ export function initializeStatsPersistence(evolcoreHome, collector) {
147
183
  stopped = true;
148
184
  if (collector.onMessage === onMessage)
149
185
  collector.onMessage = previousOnMessage;
186
+ if (eventBus) {
187
+ for (const [type, handler] of activityHandlers)
188
+ eventBus.unsubscribe(type, handler);
189
+ }
150
190
  if (maintenanceTimer)
151
191
  clearInterval(maintenanceTimer);
152
192
  };
@@ -166,8 +206,29 @@ export function insertMessageEvent(evolcoreHome, event) {
166
206
  import('../utils/logger.js').then(({ logger }) => logger.warn(`[StatsWriter] insertMessageEvent failed: ${e}`));
167
207
  }
168
208
  }
209
+ /**
210
+ * 为单次大模型调用算价。
211
+ * 复用 usage_events 的同一套口径(normalizeUsage 推断 billing_fn + resolvePrices 取价),
212
+ * 保证明细行的金额与同轮 usage_events 的费用可对账。
213
+ */
214
+ function resolveCallPrices(evolcoreHome, r, gatewayPricing) {
215
+ const event = normalizeUsage({
216
+ input_tokens: r.input_tokens,
217
+ output_tokens: r.output_tokens,
218
+ cache_creation_input_tokens: r.cache_creation_tokens,
219
+ cache_read_input_tokens: r.cache_read_tokens,
220
+ }, {
221
+ ts: r.ts,
222
+ agent_aid: r.agent_aid,
223
+ peer_key: r.peer_key,
224
+ session_id: r.session_id,
225
+ model: r.model || 'unknown',
226
+ turns: 1,
227
+ });
228
+ return resolvePrices(evolcoreHome, event, gatewayPricing);
229
+ }
169
230
  /** 批量写入大模型调用明细。单事务;失败不影响主流程。 */
170
- export function insertModelCalls(evolcoreHome, rows) {
231
+ export function insertModelCalls(evolcoreHome, rows, gatewayPricing) {
171
232
  if (!rows.length)
172
233
  return;
173
234
  const db = getDb(evolcoreHome);
@@ -178,12 +239,24 @@ export function insertModelCalls(evolcoreHome, rows) {
178
239
  INSERT INTO model_calls
179
240
  (ts, task_id, session_id, agent_session_id, agent_aid, peer_key, call_index, model,
180
241
  source, provider_thread_id, request_id, message_id, input_tokens, output_tokens, cache_creation_tokens,
181
- cache_read_tokens, context_tokens, max_tokens, auto_compact_tokens, degraded)
182
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
242
+ cache_read_tokens, context_tokens, max_tokens, auto_compact_tokens, degraded,
243
+ cost_official_usd, cost_official_cny, cost_gateway_usd, cost_gateway_cny)
244
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
183
245
  `);
246
+ // 价格解析在读事务外算好:resolvePrices 可能读价格表文件,避免拖长写锁。
247
+ const priced = rows.map(r => {
248
+ let prices = { official: null, gateway: null };
249
+ try {
250
+ prices = resolveCallPrices(evolcoreHome, r, gatewayPricing);
251
+ }
252
+ catch {
253
+ // 单行算价失败不影响其它行落库,金额留空
254
+ }
255
+ return { r, prices };
256
+ });
184
257
  db.exec('BEGIN');
185
- for (const r of rows) {
186
- stmt.run(r.ts, r.task_id, r.session_id ?? null, r.agent_session_id ?? null, r.agent_aid, r.peer_key, r.call_index, r.model, r.source ?? 'request', r.provider_thread_id ?? null, r.request_id ?? null, r.message_id ?? null, r.input_tokens, r.output_tokens, r.cache_creation_tokens, r.cache_read_tokens, r.context_tokens ?? null, r.max_tokens ?? null, r.auto_compact_tokens ?? null, r.degraded);
258
+ for (const { r, prices } of priced) {
259
+ stmt.run(r.ts, r.task_id, r.session_id ?? null, r.agent_session_id ?? null, r.agent_aid, r.peer_key, r.call_index, r.model, r.source ?? 'request', r.provider_thread_id ?? null, r.request_id ?? null, r.message_id ?? null, r.input_tokens, r.output_tokens, r.cache_creation_tokens, r.cache_read_tokens, r.context_tokens ?? null, r.max_tokens ?? null, r.auto_compact_tokens ?? null, r.degraded, prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null);
187
260
  }
188
261
  db.exec('COMMIT');
189
262
  }
@@ -15,6 +15,18 @@ export class TriggerSchedulerRegistry {
15
15
  values() {
16
16
  return this.schedulers.values();
17
17
  }
18
+ statusSummary(fromTs, toTs) {
19
+ let enabled = 0;
20
+ let calls = 0;
21
+ let failures = 0;
22
+ for (const scheduler of this.schedulers.values()) {
23
+ enabled += scheduler.list({ all: true }).filter(definition => definition.enabled).length;
24
+ const summary = scheduler.runSummary(fromTs, toTs);
25
+ calls += summary.calls;
26
+ failures += summary.failures;
27
+ }
28
+ return { enabled, today: { calls, failures } };
29
+ }
18
30
  async replace(agentAid, createScheduler) {
19
31
  await this.schedulers.get(agentAid)?.stop();
20
32
  const scheduler = createScheduler();
@@ -212,7 +212,7 @@ export function isTriggerOperator(definition, actorConversationPeerId) {
212
212
  return triggerOperatorPeerIds(definition).includes(actorConversationPeerId);
213
213
  }
214
214
  export async function authorizeTriggerExecution(definition, dependencies) {
215
- await refreshOwnershipForAuthorization(definition.agentAid);
215
+ await refreshOwnershipForAuthorization(definition.agentAid, { allowTransient: true });
216
216
  if (definition.execution.permissionMode === 'fullaccess') {
217
217
  if (!definition.authorizedBy) {
218
218
  return { allowed: false, reason: 'fullaccess Trigger approval provenance is missing' };
@@ -386,7 +386,7 @@ export async function authenticatedTriggerActor(dependencies, agentAid, actorSes
386
386
  throw new Error('trigger delegation actor does not match session peer');
387
387
  }
388
388
  const actorChatType = triggerOriginChatType(actorOrigin);
389
- await refreshOwnershipForAuthorization(agentAid);
389
+ await refreshOwnershipForAuthorization(agentAid, { allowTransient: true });
390
390
  const actorConversationId = actorChatType === 'group' ? actorOrigin.channelId : actorOrigin.peerId;
391
391
  const roleDetail = resolvePeerRoleDetail({
392
392
  selfAid: agentAid,
@@ -543,7 +543,10 @@ export class TriggerFeedbackDispatcher {
543
543
  try {
544
544
  if (cancellation.signal.aborted)
545
545
  return { effects, error: cancellation.error() };
546
- if (this.deps.tryHandoff) {
546
+ // Successful feedback may use the cross-session handoff path. Final
547
+ // failures must stay on the structured adapter path so the receiver
548
+ // gets one `result.error` payload instead of a plain text handoff.
549
+ if (this.deps.tryHandoff && (input.reply.outcome === 'success' || input.reply.outcome === 'noop')) {
547
550
  const startedAt = Date.now();
548
551
  try {
549
552
  const routed = await raceWithAbort(this.deps.tryHandoff({ ...input, signal: cancellation.signal }, text, target, binding), cancellation.signal);
@@ -597,12 +600,7 @@ export class TriggerFeedbackDispatcher {
597
600
  ? replyContextWithCausation(target, input.causation)
598
601
  : replyContextFromTarget(target),
599
602
  causation: isAunTarget ? input.causation : undefined,
600
- }), {
601
- kind: 'result.text',
602
- text,
603
- isFinal: true,
604
- format: 'plain',
605
- }), cancellation.signal);
603
+ }), feedbackPayload(input.reply, text)), cancellation.signal);
606
604
  const common = {
607
605
  type: 'message.send',
608
606
  channelKey: target.channelKey,
@@ -865,6 +863,19 @@ function errorFromReply(reply) {
865
863
  ...(reply.error?.recoverable !== undefined ? { recoverable: reply.error.recoverable } : {}),
866
864
  };
867
865
  }
866
+ function feedbackPayload(reply, text) {
867
+ if (reply.outcome === 'success' || reply.outcome === 'noop') {
868
+ return { kind: 'result.text', text, isFinal: true, format: 'plain' };
869
+ }
870
+ return {
871
+ kind: 'result.error',
872
+ text,
873
+ reason: reply.error?.reason ?? reply.outcome,
874
+ subtype: reply.error?.subtype ?? reply.error?.reason ?? reply.outcome,
875
+ ...(reply.error?.raw ? { raw: reply.error.raw } : {}),
876
+ ...(reply.error?.recoverable !== undefined ? { recoverable: reply.error.recoverable } : {}),
877
+ };
878
+ }
868
879
  function originAsTarget(origin) {
869
880
  return {
870
881
  channelKey: origin.channelKey,
@@ -12,6 +12,7 @@ export class TriggerHistoryStore {
12
12
  agentAid;
13
13
  file;
14
14
  fallbackFile;
15
+ runSummaryCache = null;
15
16
  constructor(rootDir, agentAid) {
16
17
  this.rootDir = rootDir;
17
18
  this.agentAid = agentAid;
@@ -74,6 +75,41 @@ export class TriggerHistoryStore {
74
75
  }
75
76
  return out;
76
77
  }
78
+ runSummary(fromTs, toTs) {
79
+ const files = [this.file, this.fallbackFile].filter((value) => !!value);
80
+ const signature = files.map(file => {
81
+ try {
82
+ const stat = fs.statSync(file);
83
+ return `${file}:${stat.size}:${stat.mtimeMs}`;
84
+ }
85
+ catch {
86
+ return `${file}:missing`;
87
+ }
88
+ }).join('|');
89
+ if (this.runSummaryCache
90
+ && this.runSummaryCache.signature === signature
91
+ && this.runSummaryCache.fromTs === fromTs
92
+ && this.runSummaryCache.toTs === toTs) {
93
+ return { calls: this.runSummaryCache.calls, failures: this.runSummaryCache.failures };
94
+ }
95
+ let calls = 0;
96
+ let failures = 0;
97
+ for (const line of this.readLines()) {
98
+ const event = parseHistoryEvent(line, this.agentAid);
99
+ if (!event || !isRunEvent(event))
100
+ continue;
101
+ const finishedAt = event.audit.finishedAt;
102
+ if (finishedAt < fromTs || finishedAt >= toTs)
103
+ continue;
104
+ if (!['completed', 'degraded', 'noop', 'failed'].includes(event.audit.status))
105
+ continue;
106
+ calls++;
107
+ if (event.audit.status === 'failed')
108
+ failures++;
109
+ }
110
+ this.runSummaryCache = { signature, fromTs, toTs, calls, failures };
111
+ return { calls, failures };
112
+ }
77
113
  recentRuns(triggerId, limit = 20) {
78
114
  if (limit <= 0)
79
115
  return [];
@@ -36,12 +36,19 @@ export class TriggerDefinitionManager {
36
36
  if (!fs.existsSync(file))
37
37
  return undefined;
38
38
  const raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
39
- const definition = normalizeTriggerDefinition(raw);
39
+ const definition = normalizeTriggerDefinition(raw, { allowLegacyZeroRetryAttempts: true });
40
+ const migrations = [];
40
41
  if (legacyFeedbackTargetNeedsMigration(raw, definition)) {
41
42
  definition.feedback.target.chatType ??= 'private';
43
+ migrations.push('legacy-aun-target-chat-type');
44
+ }
45
+ if (legacyRetryAttemptsNeedMigration(raw)) {
46
+ migrations.push('legacy-retry-attempts-default-one');
47
+ }
48
+ if (migrations.length > 0) {
42
49
  definition.updatedAt = Date.now();
43
50
  this.writeDefinition(definition);
44
- this.history.recordDefinition('trigger.updated', definition, { reason: 'legacy-aun-target-chat-type' });
51
+ this.history.recordDefinition('trigger.updated', definition, { reason: migrations.join(',') });
45
52
  }
46
53
  return definition;
47
54
  }
@@ -186,7 +193,7 @@ export class TriggerDefinitionManager {
186
193
  const sourceDir = stat.isDirectory() ? inputPath : path.dirname(inputPath);
187
194
  const triggerJson = stat.isDirectory() ? path.join(inputPath, 'trigger.json') : inputPath;
188
195
  const definitionRaw = JSON.parse(fs.readFileSync(triggerJson, 'utf-8'));
189
- const definition = normalizeTriggerDefinition(definitionRaw);
196
+ const definition = normalizeTriggerDefinition(definitionRaw, { allowLegacyZeroRetryAttempts: true });
190
197
  const files = [];
191
198
  if (definition.execution.type === 'script') {
192
199
  const scriptAbs = resolveScriptPath(sourceDir, definition.execution.script.path);
@@ -495,6 +502,16 @@ function legacyFeedbackTargetNeedsMigration(raw, definition) {
495
502
  const channelKey = optionalString(target.channelKey);
496
503
  return !!channelKey && (channelKey === 'aun' || channelKey.startsWith('aun#'));
497
504
  }
505
+ function legacyRetryAttemptsNeedMigration(raw) {
506
+ if (!isRecord(raw))
507
+ return false;
508
+ const reliability = isRecord(raw.reliability) ? raw.reliability : undefined;
509
+ const retry = reliability && isRecord(reliability.retry) ? reliability.retry : undefined;
510
+ if (retry?.maxAttempts === 0)
511
+ return true;
512
+ const execution = isRecord(raw.execution) ? raw.execution : undefined;
513
+ return execution?.onError === 'retry' && retry?.maxAttempts === undefined;
514
+ }
498
515
  function mergeOrigin(existing, incoming) {
499
516
  if (existing?.channelKey && existing.channelId)
500
517
  return existing;
@@ -810,9 +810,12 @@ function parseTriggerUpdateFlags(nameOrId, flags, opts = {}) {
810
810
  if ('error' in retryAttempts)
811
811
  return { ok: false, error: retryAttempts.error };
812
812
  if (retryAttempts.value !== undefined) {
813
- if (!/^\d+$/.test(retryAttempts.value))
814
- return { ok: false, error: '--retry-attempts 必须是非负整数' };
815
- update.retryAttempts = Number(retryAttempts.value);
813
+ if (!/^[1-9]\d*$/.test(retryAttempts.value))
814
+ return { ok: false, error: '--retry-attempts 必须是正整数(1 到 20)' };
815
+ const parsedAttempts = Number(retryAttempts.value);
816
+ if (parsedAttempts > 20)
817
+ return { ok: false, error: '--retry-attempts 必须是 1 到 20 的整数' };
818
+ update.retryAttempts = parsedAttempts;
816
819
  }
817
820
  const retryBackoff = optionalFlagString(flags, 'retry-backoff');
818
821
  if ('error' in retryBackoff)
@@ -146,7 +146,7 @@ export function applyTriggerPatch(definition, input, opts = {}) {
146
146
  if (patch.retryAttempts !== undefined || patch.retryBackoff !== undefined) {
147
147
  const retry = { ...updated.reliability.retry };
148
148
  if (patch.retryAttempts !== undefined)
149
- retry.maxAttempts = patch.retryAttempts ?? 0;
149
+ retry.maxAttempts = patch.retryAttempts ?? 1;
150
150
  if (patch.retryBackoff !== undefined)
151
151
  retry.backoffMs = patch.retryBackoff ?? 30_000;
152
152
  updated.reliability = { ...updated.reliability, retry };
@@ -194,6 +194,9 @@ export class TriggerRuntimeScheduler {
194
194
  history(triggerId, limit = 100) {
195
195
  return this.manager.history.events(triggerId, limit);
196
196
  }
197
+ runSummary(fromTs, toTs) {
198
+ return this.manager.history.runSummary(fromTs, toTs);
199
+ }
197
200
  recentRuns(triggerId, limit = 50) {
198
201
  return this.audit.recent(triggerId, limit).map(run => ({
199
202
  runId: run.runId,
@@ -34,7 +34,7 @@ export function seedUpgradeCheckTrigger(manager, owner) {
34
34
  script: {
35
35
  path: scriptName,
36
36
  runtime: 'node',
37
- timeoutMs: 60_000,
37
+ timeoutMs: 6 * 60_000,
38
38
  },
39
39
  permissionMode: 'bypass',
40
40
  onError: 'fail',
@@ -47,7 +47,7 @@ export function seedUpgradeCheckTrigger(manager, owner) {
47
47
  concurrency: 'forbid',
48
48
  missedPolicy: 'run_once',
49
49
  retry: {
50
- maxAttempts: 0,
50
+ maxAttempts: 1,
51
51
  backoffMs: 30_000,
52
52
  },
53
53
  },
@@ -58,15 +58,51 @@ export function seedUpgradeCheckTrigger(manager, owner) {
58
58
  const packageRoot = getPackageRoot();
59
59
  fs.writeFileSync(scriptPath, `#!/usr/bin/env node
60
60
  const { pathToFileURL } = require('node:url');
61
- const entry = ${JSON.stringify(path.join(packageRoot, 'dist', 'utils', 'package-version-info.js'))};
61
+ const { randomUUID } = require('node:crypto');
62
+ const packageRoot = ${JSON.stringify(packageRoot)};
63
+ const load = file => import(pathToFileURL(require('node:path').join(packageRoot, 'dist', file)).href);
62
64
  async function main() {
63
- const { refreshManagedPackageVersions } = await import(pathToFileURL(entry).href);
64
- const results = await refreshManagedPackageVersions(undefined, { source: 'daily-check' });
65
- const failed = results.some(result => result.status === 'unavailable');
65
+ const [versions, npm, config, upgrades, product] = await Promise.all([
66
+ load('utils/package-version-info.js'), load('utils/npm-ops.js'), load('config-store.js'),
67
+ load('utils/upgrade-jobs.js'), load('product.js'),
68
+ ]);
69
+ const selection = await npm.resolveUpgradeRegistry();
70
+ const results = await versions.refreshManagedPackageVersions(undefined, { source: 'daily-check', selection });
71
+ const checkedAt = new Date().toISOString();
72
+ // Query stable separately so it never replaces the latest/test cache.
73
+ const linked = npm.isLinkedInstall();
74
+ const stable = linked ? null : await npm.queryPackageVersion(product.MAIN_PACKAGE_NAME, selection, undefined, 'stable');
75
+ let upgrade;
76
+ if (stable && config.loadDaemonConfig().upgrade?.autoOnStart !== false) {
77
+ const currentVersion = npm.getLocalVersion();
78
+ if (npm.comparePackageVersions(currentVersion, stable.version) < 0) {
79
+ const target = {
80
+ packageName: product.MAIN_PACKAGE_NAME, currentVersion, currentVersionObservedAt: checkedAt,
81
+ latestVersion: stable.version, checkedAt, registry: stable.registry, distTag: 'stable',
82
+ npmConfig: stable.npmConfig, lastAttemptStatus: 'ok', lastAttemptAt: checkedAt,
83
+ };
84
+ const started = await upgrades.startUpgradeJob(randomUUID(), '__upgrade-check', { stableTarget: target });
85
+ upgrade = started.job;
86
+ // Wait for the watchdog handoff before the script exits. The watchdog
87
+ // allows the result to be recorded before it shuts down the daemon.
88
+ while (['accepted', 'running'].includes(upgrade.status)) {
89
+ await new Promise(resolve => setTimeout(resolve, 100));
90
+ upgrade = upgrades.readUpgradeJob(upgrade.jobId);
91
+ if (!upgrade) throw new Error('Stable upgrade job disappeared');
92
+ }
93
+ }
94
+ }
95
+ const failed = results.some(result => result.status === 'unavailable') || (!linked && !stable)
96
+ || (upgrade && ['failed', 'timeout'].includes(upgrade.status));
66
97
  process.stdout.write(JSON.stringify({
67
98
  outcome: failed ? 'error' : 'success',
68
- text: results.map(result => result.packageName + ': ' + result.status).join('; '),
99
+ text: [
100
+ ...results.map(result => result.packageName + ': ' + result.status),
101
+ product.MAIN_PACKAGE_NAME + '@stable: ' + (stable?.version || (linked ? 'skipped (development install)' : 'unavailable')),
102
+ ...(upgrade ? ['stable upgrade: ' + upgrade.status + ' (' + upgrade.jobId + ')'] : []),
103
+ ].join('; '),
69
104
  files: [],
105
+ meta: { stableVersion: stable?.version || null, ...(upgrade ? { upgradeJobId: upgrade.jobId } : {}) },
70
106
  }));
71
107
  }
72
108
  main().catch(() => {
@@ -252,7 +252,9 @@ function normalizeV3Phase2(raw, opts) {
252
252
  source: normalizeSource(raw.source),
253
253
  execution: normalizeExecution(raw.execution, { id }),
254
254
  feedback: normalizeFeedback(raw.feedback, agentAid),
255
- reliability: normalizeReliability(raw.reliability),
255
+ reliability: normalizeReliability(raw.reliability, {
256
+ allowLegacyZeroRetryAttempts: opts.allowLegacyZeroRetryAttempts === true,
257
+ }),
256
258
  limits: normalizeLimits(raw.limits),
257
259
  };
258
260
  // T10: labels 字典原样保留,只做类型校验(如果存在必须是 Record<string, string>)
@@ -650,9 +652,9 @@ function inferSessionKind(threadId, rawSession, label) {
650
652
  }
651
653
  return inferred;
652
654
  }
653
- function normalizeReliability(value) {
655
+ function normalizeReliability(value, opts = {}) {
654
656
  if (value === undefined) {
655
- return { concurrency: 'forbid', missedPolicy: 'run_once', retry: { maxAttempts: 0, backoffMs: 30_000 } };
657
+ return { concurrency: 'forbid', missedPolicy: 'run_once', retry: { maxAttempts: 1, backoffMs: 30_000 } };
656
658
  }
657
659
  if (!isObject(value))
658
660
  throw new Error('reliability must be an object');
@@ -666,10 +668,16 @@ function normalizeReliability(value) {
666
668
  throw new Error('reliability.missedPolicy is invalid');
667
669
  }
668
670
  const retryRaw = isObject(raw.retry) ? raw.retry : {};
669
- const maxAttempts = optionalNumber(retryRaw.maxAttempts) ?? 0;
671
+ let maxAttempts = optionalNumber(retryRaw.maxAttempts) ?? 1;
670
672
  const backoffMs = optionalNumber(retryRaw.backoffMs) ?? 30_000;
671
673
  if (!Number.isInteger(maxAttempts) || maxAttempts < 0 || maxAttempts > 20) {
672
- throw new Error('reliability.retry.maxAttempts must be an integer between 0 and 20');
674
+ throw new Error('reliability.retry.maxAttempts must be an integer between 1 and 20');
675
+ }
676
+ if (maxAttempts === 0) {
677
+ if (!opts.allowLegacyZeroRetryAttempts) {
678
+ throw new Error('reliability.retry.maxAttempts must be at least 1');
679
+ }
680
+ maxAttempts = 1;
673
681
  }
674
682
  if (!Number.isFinite(backoffMs) || backoffMs < 0) {
675
683
  throw new Error('reliability.retry.backoffMs must be a non-negative number');
@@ -1,7 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { spawn } from 'child_process';
4
- import { getPackageRoot, resolvePaths } from '../paths.js';
4
+ import { getPackageRoot, isDevMode, resolvePaths } from '../paths.js';
5
5
  import { WEB_PACKAGE_NAME } from '../product.js';
6
6
  import { resolveGlobalPkg } from './npm-ops.js';
7
7
  import { ecwebVersionRequirementError, resolveEcwebLaunchCommand } from './ecweb-utils.js';
@@ -69,10 +69,15 @@ function removeEntriesForPid(pid) {
69
69
  }
70
70
  async function probe(port) {
71
71
  try {
72
- const response = await fetch(`http://127.0.0.1:${port}/`, {
72
+ const response = await fetch(`http://127.0.0.1:${port}/api/health`, {
73
73
  signal: AbortSignal.timeout(1500),
74
74
  });
75
- return response.ok;
75
+ if (!response.ok)
76
+ return false;
77
+ const health = await response.json();
78
+ return health.ok === true
79
+ && health.service === 'ecweb'
80
+ && health.daemonProtocolCompatible === true;
76
81
  }
77
82
  catch {
78
83
  return false;
@@ -95,6 +100,7 @@ export function createEcwebSupervisor(options) {
95
100
  let timer = null;
96
101
  let failureCount = 0;
97
102
  let startInFlight = null;
103
+ let childStartedAt = 0;
98
104
  let stopping = false;
99
105
  const logFile = path.join(resolvePaths().logs, 'ecweb-daemon.log');
100
106
  const setActiveFromEntry = (entry, owned) => {
@@ -182,7 +188,10 @@ export function createEcwebSupervisor(options) {
182
188
  });
183
189
  let cwd = root;
184
190
  let version = globalPkg?.version;
185
- if (!launch && fs.existsSync(localEntry)) {
191
+ // The repository fallback is deliberately development-only. Installed
192
+ // daemons must resolve the separately packaged ec-web entry; otherwise a
193
+ // stale source-tree build could silently replace the installed service.
194
+ if (!launch && isDevMode() && fs.existsSync(localEntry)) {
186
195
  launch = {
187
196
  command: process.execPath,
188
197
  args: [localEntry, '--home', root, '--port', String(options.port)],
@@ -218,15 +227,15 @@ export function createEcwebSupervisor(options) {
218
227
  detached: true,
219
228
  stdio: ['ignore', childLogFd, childLogFd],
220
229
  windowsHide: platform.isWindows,
221
- // ECWeb dynamically imports EvolCore's dist modules for config,
222
- // roles, authorization and session compatibility. Pin that lookup
223
- // to the same package root as this daemon; otherwise a separately
224
- // installed ECWeb can resolve its peer dependency and silently load
225
- // a different (possibly stale) EvolCore copy from node_modules.
230
+ // Keep the runtime home and package root aligned with this daemon.
231
+ // The service protocol is the runtime boundary; package-root pinning
232
+ // remains useful for development-only compatibility code and static
233
+ // asset resolution.
226
234
  env: {
227
235
  ...process.env,
228
236
  EVOLCORE_HOME: root,
229
237
  EVOLCORE_PACKAGE_ROOT: getPackageRoot(),
238
+ EVOLCORE_ECWEB_SUPERVISED: '1',
230
239
  },
231
240
  });
232
241
  }
@@ -237,13 +246,16 @@ export function createEcwebSupervisor(options) {
237
246
  }
238
247
  closeLogStream();
239
248
  child = spawned;
249
+ childStartedAt = Date.now();
240
250
  spawned.once('error', (error) => {
241
251
  options.logger.error(`ECWeb 子进程创建失败: ${error.message}`);
242
252
  });
243
253
  spawned.once('exit', (code, signal) => {
244
254
  options.logger.warn(`ECWeb 进程退出 (PID: ${spawned.pid ?? 'unknown'}, code=${code ?? 'null'}, signal=${signal ?? 'null'})`);
245
- if (child === spawned)
255
+ if (child === spawned) {
246
256
  child = null;
257
+ childStartedAt = 0;
258
+ }
247
259
  if (!stopping) {
248
260
  active = null;
249
261
  failureCount = failureThreshold;
@@ -265,6 +277,14 @@ export function createEcwebSupervisor(options) {
265
277
  const ensureRunning = async () => {
266
278
  if (stopping || startInFlight)
267
279
  return;
280
+ // A supervised ECWeb waits for daemon IPC before it binds and writes its
281
+ // instance record. Do not mistake that startup window for a crashed
282
+ // service and spawn a second child. The child is still subject to a hard
283
+ // timeout so a permanently stuck handshake is eventually replaced.
284
+ if (child?.pid && platform.isProcessRunning(child.pid)) {
285
+ if (Date.now() - childStartedAt < 45_000)
286
+ return;
287
+ }
268
288
  const healthy = await findHealthyInstance();
269
289
  if (healthy) {
270
290
  const changed = !active || active.pid !== healthy.record.pid || active.port !== healthy.record.port;
@@ -334,6 +354,7 @@ export function createEcwebSupervisor(options) {
334
354
  }
335
355
  catch { }
336
356
  child = null;
357
+ childStartedAt = 0;
337
358
  }
338
359
  closeLogStream();
339
360
  },
@@ -91,12 +91,16 @@ export var ErrorType;
91
91
  ErrorType["CODEX_SANDBOX_USER_NAMESPACE_UNAVAILABLE"] = "codex_sandbox_userns_unavailable";
92
92
  ErrorType["CLAUDE_STARTUP_ARGUMENTS_TOO_LONG"] = "claude_startup_arguments_too_long";
93
93
  ErrorType["CLAUDE_CODE_STARTUP_FAILED"] = "claude_code_startup_failed";
94
+ ErrorType["POLICY_REJECTED"] = "policy_rejected";
94
95
  ErrorType["UNKNOWN"] = "unknown";
95
96
  })(ErrorType || (ErrorType = {}));
97
+ const POLICY_REJECTION_PATTERN = /invalid prompt[\s\S]{0,240}flagged as potentially violating our usage policy|prompt was flagged as potentially violating our usage policy/i;
98
+ export function isPolicyRejectedError(error) {
99
+ return POLICY_REJECTION_PATTERN.test(getErrorRawText(error) ?? '');
100
+ }
96
101
  export function getErrorRawText(error, seen = new Set()) {
97
102
  if (typeof error === 'string') {
98
- const text = error.trim();
99
- return text || undefined;
103
+ return error.trim() ? error : undefined;
100
104
  }
101
105
  if (error === null || error === undefined)
102
106
  return undefined;
@@ -108,7 +112,7 @@ export function getErrorRawText(error, seen = new Set()) {
108
112
  if ('raw' in record) {
109
113
  const raw = record.raw;
110
114
  if (typeof raw === 'string' && raw.trim())
111
- return raw.trim();
115
+ return raw;
112
116
  }
113
117
  const causeText = getErrorRawText(record.cause, seen);
114
118
  if (causeText)
@@ -116,7 +120,7 @@ export function getErrorRawText(error, seen = new Set()) {
116
120
  for (const key of ['message', 'error', 'reason']) {
117
121
  const value = record[key];
118
122
  if (typeof value === 'string' && value.trim())
119
- return value.trim();
123
+ return value;
120
124
  if (value && typeof value === 'object') {
121
125
  const nestedText = getErrorRawText(value, seen);
122
126
  if (nestedText)
@@ -236,6 +240,7 @@ const NON_INFRA_SUBTYPES = new Set([
236
240
  'end_turn',
237
241
  'max_turns',
238
242
  'permission_denied',
243
+ 'policy_rejected',
239
244
  'stop',
240
245
  ]);
241
246
  const NON_INFRA_TERMINAL_REASONS = new Set([
@@ -462,6 +467,8 @@ export function classifyError(error) {
462
467
  // The broad dictionary rule for "stream" must not hide a provider budget limit.
463
468
  if (isOutputTokenLimitError(error))
464
469
  return ErrorType.MAX_OUTPUT_TOKENS;
470
+ if (isPolicyRejectedError(error))
471
+ return ErrorType.POLICY_REJECTED;
465
472
  if (error?.code === 'TOPIC_BACKEND_UNAVAILABLE') {
466
473
  return ErrorType.SESSION_UNAVAILABLE;
467
474
  }
@@ -523,10 +530,17 @@ export function isRetryableError(error) {
523
530
  // Replaying the same request does not increase its output budget.
524
531
  if (isOutputTokenLimitError(error))
525
532
  return false;
533
+ if (isPolicyRejectedError(error))
534
+ return false;
526
535
  const msg = error?.message || String(error);
527
536
  const lower = msg.toLowerCase();
528
537
  if (lower.includes('invalid jsonl session file') || lower.includes('invalid session file'))
529
538
  return false;
539
+ // The idle watchdog emits this exact terminal error when a runner stops
540
+ // producing events. The provider session remains resumable, so the task
541
+ // recovery trigger must be allowed to continue the original session.
542
+ if (lower === 'sdk_timeout')
543
+ return true;
530
544
  // 字典优先 — 命中则直接返回
531
545
  const rule = matchErrorRule(lower);
532
546
  if (rule)
@@ -571,6 +585,10 @@ export function getErrorMessage(error, terminalReason, includeEmoji = true) {
571
585
  return `${prefix}模型响应达到输出上限(max_output_tokens),本轮未完成。`
572
586
  + '请降低推理强度或提高模型服务的输出预算,然后在原会话发送“继续,先核对已完成操作,只完成剩余工作”;无需重发原任务。';
573
587
  }
588
+ if (isPolicyRejectedError(error)) {
589
+ const prefix = includeEmoji ? '⚠️ ' : '';
590
+ return `${prefix}上游安全策略拒绝处理本次请求,本轮未完成。请改写请求或新开话题后重试;不会自动重放原请求。`;
591
+ }
574
592
  if (isClaudeStartupArgumentsTooLong(error)) {
575
593
  const prefix = includeEmoji ? '⚠️ ' : '';
576
594
  return `${prefix}当前 Claude 启动参数过长,任务未执行`;