evolcore 0.0.43-test.7 → 0.0.45

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 (127) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bin/ecmsg.js +22 -9
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/claude-runner.js +1 -1
  9. package/dist/aun/aid/agentmd.js +56 -1
  10. package/dist/aun/aid/client.js +3 -1
  11. package/dist/aun/menu/client.js +3 -2
  12. package/dist/aun/msg/p2p.js +1 -1
  13. package/dist/channels/aun.js +47 -32
  14. package/dist/cli/agent-command.js +5 -0
  15. package/dist/cli/agent-create.js +5 -1
  16. package/dist/cli/agent-template.js +124 -0
  17. package/dist/cli/aun-commands.js +2 -2
  18. package/dist/cli/ctl-command.js +2 -1
  19. package/dist/cli/daemon-commands.js +5 -0
  20. package/dist/cli/ecmsg-gateway.js +2 -2
  21. package/dist/cli/events-command.js +45 -9
  22. package/dist/cli/index.js +29 -0
  23. package/dist/cli/net-check.js +1 -1
  24. package/dist/cli/restart-monitor.js +115 -36
  25. package/dist/cli/services-command.js +29 -3
  26. package/dist/cli/thread-command.js +97 -11
  27. package/dist/config/boot-log.js +8 -8
  28. package/dist/config/schema-migration.js +41 -16
  29. package/dist/core/agent-ipc-registration.js +25 -4
  30. package/dist/core/agent-runtime.js +2 -0
  31. package/dist/core/auth/operation-authorizer.js +2 -0
  32. package/dist/core/auth/operation-catalog.js +11 -2
  33. package/dist/core/channel-runtime.js +16 -9
  34. package/dist/core/command/agent-control.js +11 -1
  35. package/dist/core/command/agent-template-menu.js +147 -0
  36. package/dist/core/command/command-handler.js +27 -6
  37. package/dist/core/command/eventcenter-menu.js +158 -28
  38. package/dist/core/command/menu-catalog.js +8 -1
  39. package/dist/core/command/menu-handler.js +18 -6
  40. package/dist/core/command/menu-protocol.js +11 -2
  41. package/dist/core/daemon-control.js +14 -0
  42. package/dist/core/daemon-lifecycle.js +262 -189
  43. package/dist/core/handoff/runtime.js +42 -10
  44. package/dist/core/ipc-registration.js +5 -1
  45. package/dist/core/legacy-rename.js +41 -0
  46. package/dist/core/message/aun-ipc-sender.js +118 -13
  47. package/dist/core/message/im-renderer.js +88 -1
  48. package/dist/core/message/message-queue.js +66 -15
  49. package/dist/core/message/pending-hints.js +29 -5
  50. package/dist/core/message/response-engine.js +37 -7
  51. package/dist/core/message/send-routing.js +13 -6
  52. package/dist/core/pack-auth.js +94 -0
  53. package/dist/core/pack-install.js +194 -0
  54. package/dist/core/permission/ec-command-parser.js +49 -16
  55. package/dist/core/rate-window.js +48 -0
  56. package/dist/core/relation/peer-identity.js +28 -0
  57. package/dist/core/session/session-fs-store.js +66 -26
  58. package/dist/core/session/session-idle-monitor.js +59 -19
  59. package/dist/core/session/session-manager.js +13 -4
  60. package/dist/core/thread/thread-route.js +2 -2
  61. package/dist/core/thread/thread-service.js +52 -3
  62. package/dist/eck/kit-renderer.js +1 -1
  63. package/dist/eck/message-renderer.js +2 -0
  64. package/dist/event-center/admission-materializer.js +22 -12
  65. package/dist/event-center/bus-gate.js +20 -2
  66. package/dist/event-center/bus-host.js +46 -29
  67. package/dist/event-center/bus-resolver.js +1 -1
  68. package/dist/event-center/center-config.js +41 -14
  69. package/dist/event-center/daemon.js +1 -2
  70. package/dist/event-center/directory-source.js +3 -1
  71. package/dist/event-center/index-generator.js +12 -2
  72. package/dist/event-center/ipc-operation.js +140 -25
  73. package/dist/event-center/pack-loader.js +61 -56
  74. package/dist/event-center/pack-manager.js +2 -2
  75. package/dist/event-center/registry.js +242 -17
  76. package/dist/event-center/runtime.js +271 -75
  77. package/dist/event-center/types.js +20 -4
  78. package/dist/event-center/validation.js +34 -12
  79. package/dist/index.js +147 -44
  80. package/dist/ipc.js +44 -4
  81. package/dist/paths.js +2 -2
  82. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  83. package/dist/services/index.js +3 -3
  84. package/dist/services/ipc-operation.js +99 -7
  85. package/dist/services/pack-manager.js +17 -6
  86. package/dist/services/router.js +8 -5
  87. package/dist/services/validation.js +5 -5
  88. package/dist/trigger/scheduler.js +38 -0
  89. package/dist/trigger/script-sandbox.js +52 -2
  90. package/dist/utils/npm-ops.js +2 -1
  91. package/dist/utils/package-version-info.js +6 -3
  92. package/kits/docs/aun/ABILITY_CALLING.md +4 -3
  93. package/kits/docs/context-assembly.md +1 -1
  94. package/kits/docs/evolcore/INDEX.md +3 -3
  95. package/kits/docs/evolcore/agent.md +22 -1
  96. package/kits/docs/evolcore/event-center.md +30 -10
  97. package/kits/docs/evolcore/fs.md +4 -3
  98. package/kits/docs/evolcore/menu-protocol.md +7 -1
  99. package/kits/docs/evolcore/msg.md +8 -8
  100. package/kits/docs/evolcore/response.md +2 -2
  101. package/kits/docs/evolcore/services.md +27 -10
  102. package/kits/docs/evolcore/thread-chain.md +15 -3
  103. package/kits/rules/06-channel.md +1 -0
  104. package/kits/skills/ability/references/calling.md +2 -2
  105. package/kits/skills/ec-group/SKILL.md +5 -8
  106. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  107. package/kits/skills/ec-trigger/SKILL.md +4 -4
  108. package/kits/skills/thread-ops/SKILL.md +10 -10
  109. package/kits/templates/message-fragments/item.md +1 -1
  110. package/kits/templates/system-fragments/channel.md +1 -1
  111. package/kits/templates/system-fragments/commands.md +1 -1
  112. package/kits/templates/system-fragments/reply.md +1 -0
  113. package/kits/templates/system-fragments/thread.md +3 -2
  114. package/package.json +4 -3
  115. package/scripts/agent-template/index.mjs +40 -0
  116. package/scripts/agent-template/inspect.mjs +240 -0
  117. package/scripts/agent-template/overlay.mjs +71 -0
  118. package/scripts/agent-template/pack.mjs +169 -0
  119. package/scripts/agent-template/shared/common.mjs +235 -0
  120. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  121. package/scripts/agent-template/shared/plan.mjs +129 -0
  122. package/scripts/agent-template/shared/team-schema.json +70 -0
  123. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  124. package/scripts/agent-template/shared/template-package.mjs +265 -0
  125. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  126. package/scripts/agent-template/shared/template.mjs +142 -0
  127. package/dist/event-center/client-factory.js +0 -50
package/CHANGELOG.md CHANGED
@@ -5,6 +5,53 @@
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ ## 0.0.45 (2026-11-10)
9
+
10
+ ### 身份、Owner 与联系人
11
+
12
+ - Agent 常驻设定改用 personal/soul/ 分册,迁移旧 persona.md;显示名跟随签名名片刷新,支持关闭首次欢迎消息。
13
+ - 新增 App 联系人准入与同 Owner 内部联系人默认角色,完善黑名单、临时授权、名录范围和出站联系申请;敏感操作重新核验协议归属。
14
+ - 名录查询统一为 ec directory list/info,准入与查询使用本地快照,废弃本地授权凭据;明确撤权持久化,阻止共享缓存恢复已撤权快照。
15
+ - 上下文与记忆写入统一使用协议确认的 Owner;普通 Agent 绑定和转让要求目标为验签通过的 human,自动绑定仅限初始化阶段;修复 SDK 0.5.34 下绑定提交前连接中断的识别。
16
+
17
+ ### 对话、模型与自动化
18
+
19
+ - 移除 paactive 对话模式,仅保留 interactive/proactive,启动时自动迁移已知配置中的旧模式;个人助理与本人 Owner 的 AUN 私聊按已核验身份使用可靠 activity 投递。
20
+ - 统一模型容量解析,按当前 Provider 计算压缩阈值,更新模型与价格数据;修正压缩后用量,增加手动压缩进度通知。
21
+ - ecagent 支持只读访问入站附件并校验真实路径;非法工具参数转为可恢复错误,摘要失败不再自动重试。
22
+ - Trigger 跟随 Agent 当前基座,支持静默结果和自定义闲置提示;完善取消与子进程清理,输入已提交但结果不明时避免重复提交。
23
+
24
+ ### 消息、服务与事件
25
+
26
+ - 新增 ecmsg 统一发送入口,统一话题路由、复查和加密选项,支持非 AUN 既有会话;跨话题自派必须指定其他话题,并向该话题对端展示派发副本。
27
+ - AUN Menu 使用独立 control 消息流并强制加密响应;完善自动最终回复的结构化投递、话题摘要批量读取及空列表诊断。
28
+ - 新增 ec services 服务路由,支持准入、限流、幂等、脚本执行和结构化应答;新增 ec events 事件中心,提供 TTL 内在线通知、订阅及白名单管理。
29
+ - 服务包与事件包统一使用 pack.json,支持受控安装、卸载、日志归档和跨 Agent 管理授权;事件中心复用 AUN 渠道连接,完善订阅、重连和消费诊断。
30
+ - 完善 Fullaccess 委托核验、授权审计及跨 Shell 参数解析,允许直接执行 ecmsg 入口,过滤空消息占位输出。
31
+
32
+ ### 能力插件、团队与模板
33
+
34
+ - 新增按 Agent 或主机 AID 管理的能力插件平台,支持开发、构建、安装、授权、发布、升级及回滚;能力发现和管理技能合并为 ability。
35
+ - 完善多运行时、设备路由、请求关联、契约校验和重放保护,资源代理支持批量存储与工作区读取。
36
+ - 新增 ec team 团队工作区及成员、导航管理,使用稳定入口 ID 增量更新;每个 Agent 使用独立产物目录,迁移旧工作区文件与导航引用。
37
+ - 新增 Agent 模板检查、打包、分享及安装,支持将多成员模板映射到已有 Agent,逐成员选择 Provider、统一渲染资源占位符,并在失败时整包回滚。
38
+ - 支持导出不含主机凭据的便携模板包、校验后导入新目录,以及通过主机控制通道推送模板任务进度;兼容旧版团队模板字段布局并校验格式版本。
39
+
40
+ ### Provider、启动与运行管理
41
+
42
+ - Provider 使用域名稳定 ID,支持本机配置导入、引用迁移、接口风格保存和冲突诊断;EC Web 初始化导入冲突改用对话框处理。
43
+ - 修复 Codex 切换 Provider 后原会话续接,保留线程与历史;Runner 按需加载,合并首次并发加载,协调配置重载、中断与停机。
44
+ - 启动恢复按 Agent 和任务优先级调度,Handoff 后台恢复,会话空闲计时按近期与历史分批恢复;复用目录扫描并让出 I/O,减少就绪等待。
45
+ - EC Web 启动甘特图展示 Observer 提示、空闲计时及 Handoff 后台恢复阶段;修复初始化重试时项目路径尾分隔符误判。
46
+ - 完善受管服务与 EC Web 的实例身份、健康检查和优雅退出,以及异步进程探测、重启监控、并行停机和 Windows 安装诊断;移除内置 PA 看板导航入口。
47
+
48
+ ### 依赖与兼容性
49
+
50
+ - Node.js 要求 >=22.16.0,AUN SDK 最低兼容版本提升至 0.5.34,配套 ec-web@0.0.45。
51
+ - Agent、Relation、Role Schema 分别为 v20、v12、v2;内部联系人默认角色使用 internalContact,已知 Schema 中的旧 paactive 模式自动迁移为 proactive。
52
+ - 服务与事件配置采用 services-config.json、events-config.json,旧配置与包清单在兼容流程中迁移至新名称。
53
+ - Invoke 保留为未完成功能,本次按要求不执行相关测试,不作为可用功能验收。
54
+
8
55
  ## 0.0.43-test.7 (2026-11-09)
9
56
 
10
57
  ### 身份、Owner 与联系人
package/bin/ecmsg.js CHANGED
@@ -7,8 +7,7 @@
7
7
  * 职责边界(第一期):
8
8
  * - 只做**路由**:解析目标三元组、判跨话题、决定复查与加密,然后分派给
9
9
  * 现有的内部发送通道。
10
- * - 不改写任何内部通道的实现。`ec msg send` / `ec group send` / `ec ctl send`
11
- * 全部保持原状可用。
10
+ * - 不改写任何内部通道的实现,旧命令全部保持原状可用。
12
11
  *
13
12
  * 为什么必须有这一层:
14
13
  * 模型面对三种写法时必须先判断"用哪种",判断错就失败。网关把判断收敛为一
@@ -49,7 +48,7 @@ const HELP = `用法: ecmsg send '<正文>' [选项]
49
48
  --thread <话题id> 发到指定话题;只接受 thread-… 或 main:<aidA>:<aidB>
50
49
  --to <对端ID> 发到指定对端(群 AID 或对方 AID,按本地关系判定类型)
51
50
  --from <本端AID> 托管会话可省略(恒等于会话本端);非托管必填
52
- --to <本端AID> 话题内投给自己(self-address):本机直接入队处理
51
+ --to <本端AID> 跨话题自派(self-dispatch):必须配合 --thread,换话题给自己派活
53
52
 
54
53
  复查:
55
54
  跨话题(对端或话题与会话不同)自动创建复查 Trigger,默认 20m;
@@ -196,6 +195,8 @@ async function resolveTargetPeerKind(runtime, targetId, selfAidOverride) {
196
195
  const normalize = value => String(value ?? '').trim().replace(/^@/, '').toLowerCase();
197
196
  const currentPeerId = runtime ? currentPeerIdOf(runtime) : '';
198
197
  if (currentPeerId && normalize(targetId) === normalize(currentPeerId)) return currentKind;
198
+ // 目标是本端自己:类型就是当前会话类型,不必拉自己的 agent.md / 网关。
199
+ if (selfAid && normalize(targetId) === normalize(selfAid)) return currentKind;
199
200
 
200
201
  const peerIdentity = await loadDist('core/relation/peer-identity.js');
201
202
  try {
@@ -275,6 +276,11 @@ async function main() {
275
276
  { hint: sub === 'history' ? '查看历史请用 ec msg history' : '用 --help 查看发送用法' });
276
277
  }
277
278
 
279
+ // 与 aid/msg/group 等命令一致:先关掉 SDK 的 [aun_core] 日志,
280
+ // 否则解析对端类型时的 debug 行会糊住真正的回执/错误。
281
+ const aidModule = await loadDist('aun/aid/index.js');
282
+ aidModule?.suppressSdkLogs?.();
283
+
278
284
  const routing = await loadDist('core/message/send-routing.js');
279
285
  const gateway = await loadDist('cli/ecmsg-gateway.js');
280
286
  if (!routing || !gateway) fail(BUILD_HINT, 'BUILD_REQUIRED');
@@ -299,7 +305,7 @@ async function main() {
299
305
  }
300
306
  if (!routeOpts.thread || !String(routeOpts.thread).trim()) {
301
307
  fail('非托管使用需要 --thread <话题id> 定位会话', 'THREAD_REQUIRED',
302
- { hint: "ec msg send '<正文>' --self <本端AID> --thread <话题id> 也可以" });
308
+ { hint: "ecmsg send '<正文>' --from <本端AID> --thread <话题id> --to <对端或本端AID>" });
303
309
  }
304
310
  if (passthrough.length > 0) {
305
311
  fail(`非托管发送目前只支持纯文本,不支持的选项:${passthrough.join(' ')}`, 'UNSUPPORTED_OPTION');
@@ -576,8 +582,11 @@ function renderReceipt(route, result, routing, gateway) {
576
582
  encryptResolved: route.encryptResolved,
577
583
  message_id: result.message_id,
578
584
  seq: result.seq,
579
- status: result.status,
580
- ...(selfAddressed ? {
585
+ // status 是「本地已受理」的稳定口径;传输层的原始状态单独放在 aun_status,
586
+ // 它随消息类型在 sent/delivered/accepted 之间变化,不适合当判据。
587
+ status: 'accepted',
588
+ ...(result.status !== undefined ? { aun_status: result.status } : {}),
589
+ ...(selfAddressed || result.self_session_id !== undefined || result.self_delivery_error !== undefined ? {
581
590
  self_session_id: result.self_session_id,
582
591
  self_delivery_error: result.self_delivery_error,
583
592
  } : { trigger_id: result.trigger_id }),
@@ -594,18 +603,22 @@ function renderReceipt(route, result, routing, gateway) {
594
603
  }
595
604
 
596
605
  const seq = result.seq ?? result.message?.seq ?? '-';
606
+ // 稳定口径:status 恒为 accepted(本地已受理);传输层原始状态放 aun_status。
607
+ const aunStatus = result.status !== undefined ? ` aun_status=${result.status}` : '';
597
608
  process.stdout.write(
598
- `✓ 已发送 ${routeLine} message_id=${result.message_id ?? '-'} seq=${seq} status=${result.status ?? '-'}\n`,
609
+ `✓ 已发送 ${routeLine} message_id=${result.message_id ?? '-'} seq=${seq} status=accepted${aunStatus}\n`,
599
610
  );
600
611
 
601
- if (selfAddressed) {
612
+ // 只要 daemon 报了本地投递失败就必须说出来:会话内回复会被路由成「发给会话对端」,
613
+ // 目标恰好是本端时 recipient 是 peer 而不是 self,只看 route 会把这个失败吞掉。
614
+ if (selfAddressed || result.self_delivery_error !== undefined || result.self_session_id !== undefined) {
602
615
  // 自发不建复查(D13),也不该按跨话题的口径提示「已建复查」。
603
616
  if (result.self_delivery_error) {
604
617
  process.stderr.write(`⚠ 本地投递未完成: ${result.self_delivery_error}\n`);
605
618
  process.stderr.write(' AUN 消息已发出(其它设备可见),但本机队列没拿到这条任务。\n');
606
619
  } else if (result.self_session_id) {
607
620
  process.stdout.write(`✓ 已投给本端队列 session=${result.self_session_id}\n`);
608
- } else {
621
+ } else if (selfAddressed) {
609
622
  process.stderr.write('⚠ 未返回本地投递结果(self_session_id 缺失)\n');
610
623
  }
611
624
  return;
@@ -0,0 +1,62 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { atomicWriteJson } from '../core/session/session-fs-store.js';
5
+ import { templateError } from './types.js';
6
+ function stable(value) {
7
+ return JSON.stringify(value, (_key, v) => v && typeof v === 'object' && !Array.isArray(v)
8
+ ? Object.fromEntries(Object.keys(v).sort().map(k => [k, v[k]])) : v);
9
+ }
10
+ export function templateFingerprint(value) { return createHash('sha256').update(stable(value)).digest('hex'); }
11
+ export class TemplateJobs {
12
+ root;
13
+ constructor(root) {
14
+ this.root = root;
15
+ fs.mkdirSync(root, { recursive: true });
16
+ }
17
+ file(id) {
18
+ if (!/^job_[a-f0-9-]{36}$/.test(id))
19
+ throw templateError('INVALID_ARGUMENT', 'Invalid jobId');
20
+ return path.join(this.root, id + '.json');
21
+ }
22
+ list() {
23
+ return fs.readdirSync(this.root).filter(f => /^job_[a-f0-9-]{36}\.json$/.test(f)).map(f => {
24
+ const value = JSON.parse(fs.readFileSync(path.join(this.root, f), 'utf8'));
25
+ if (!value.jobId || !value.event)
26
+ throw templateError('INSTALL_BROKEN', 'Invalid persisted template job');
27
+ return value;
28
+ });
29
+ }
30
+ save(job) { atomicWriteJson(this.file(job.jobId), job); }
31
+ get(actor, query) {
32
+ const job = query.jobId ? this.list().find(j => j.jobId === query.jobId && j.actor === actor)
33
+ : this.list().find(j => j.requestId === query.requestId && j.actor === actor);
34
+ if (!job || job.event.status !== 'running' && job.updatedAt < Date.now() - 86400_000) {
35
+ throw templateError('NOT_FOUND', 'Template task not found or expired');
36
+ }
37
+ return job;
38
+ }
39
+ accept(actor, aid, requestId, action, args, phase, aids) {
40
+ const fingerprint = templateFingerprint({ action, args });
41
+ const jobs = this.list();
42
+ const original = jobs.find(j => j.actor === actor && (j.requestId === requestId
43
+ || action === 'deploy' && j.action === action && j.args.pullId === args.pullId
44
+ || action === 'push' && j.action === action && j.args.buildId === args.buildId && j.event.status === 'running'));
45
+ if (original) {
46
+ if (original.fingerprint !== fingerprint)
47
+ throw templateError('CONFLICT', 'Request or pullId already has different parameters');
48
+ return { job: original, reused: true };
49
+ }
50
+ const jobId = 'job_' + randomUUID();
51
+ const now = Date.now();
52
+ const job = { jobId, actor, aid, ...(aids ? { aids } : {}), action, args, requestId, fingerprint, createdAt: now, updatedAt: now,
53
+ event: { type: 'menu.event', event: 'template.progress', requestId, jobId, seq: 1, phase, status: 'running', message: 'Task accepted' } };
54
+ this.save(job);
55
+ return { job, reused: false };
56
+ }
57
+ update(job, patch) {
58
+ job.updatedAt = Date.now();
59
+ job.event = { ...job.event, ...patch, seq: job.event.seq + 1 };
60
+ this.save(job);
61
+ }
62
+ }
@@ -0,0 +1,214 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { stringify } from 'yaml';
5
+ import { validateAgentMdDocument } from '@agentunion/fastaun';
6
+ import { ownerResolver, getDaemonOwners } from '../core/ownership/owner-resolver.js';
7
+ import { resolvePaths, getPackageRoot } from '../paths.js';
8
+ import { loadAgent, loadDaemonConfig } from '../config-store.js';
9
+ import { resolveEffective, notifyConfigWrite, ConfigTarget } from '../config/config-manager.js';
10
+ import { readProvidersSnapshot } from '../config/providers-management.js';
11
+ import { resolveProviderId } from '../config/providers-config.js';
12
+ import { resolveAllSkillStates } from '../core/skill/switch-resolver.js';
13
+ import { agentmdGet, agentmdUpdate } from '../aun/aid/agentmd.js';
14
+ import { getProviderCatalog, assertCatalogSelectable, resolveCatalogModel, catalogEfforts } from '../core/model/model-catalog.js';
15
+ import { AgentTemplateService } from './service.js';
16
+ import { templateError, templateJobAids } from './types.js';
17
+ import { refreshSkillIndex } from '../core/skill/startup.js';
18
+ import { TemplateJobs } from './jobs.js';
19
+ import { runTemplateTool } from './tool-runner.js';
20
+ /** Restore disk state before registry/runner loading. Network profile compensation follows after Control connects. */
21
+ export async function restoreTemplatesBeforeStartup(root) {
22
+ const blocked = new Set();
23
+ const pending = new Set();
24
+ const directory = path.join(root, 'data', 'template-cache', 'jobs');
25
+ if (!fs.existsSync(directory))
26
+ return { blocked, pending };
27
+ const jobs = new TemplateJobs(directory);
28
+ for (const job of jobs.list()) {
29
+ if (job.event.code === 'INSTALL_BROKEN') {
30
+ for (const aid of templateJobAids(job))
31
+ blocked.add(aid);
32
+ continue;
33
+ }
34
+ if (job.event.status !== 'running' || job.action !== 'deploy')
35
+ continue;
36
+ try {
37
+ if (job.backupDir && fs.existsSync(path.join(job.backupDir, 'journal.json'))) {
38
+ await runTemplateTool('overlay', { operation: 'restore', backupDir: job.backupDir });
39
+ }
40
+ job.localRecoveryComplete = true;
41
+ if (job.profileAttempted) {
42
+ for (const aid of templateJobAids(job))
43
+ pending.add(aid);
44
+ jobs.save(job);
45
+ }
46
+ else
47
+ jobs.update(job, { event: 'template.result', status: 'failed', code: 'TASK_INTERRUPTED',
48
+ message: 'Interrupted install restored before Agent startup', data: { rolledBack: true } });
49
+ }
50
+ catch {
51
+ for (const aid of templateJobAids(job))
52
+ blocked.add(aid);
53
+ jobs.update(job, { event: 'template.result', status: 'failed', code: 'INSTALL_BROKEN',
54
+ message: 'Local template recovery failed before startup', data: { rolledBack: false } });
55
+ }
56
+ }
57
+ return { blocked, pending };
58
+ }
59
+ const FIELDS = ['name', 'description', 'avatar', 'tags', 'exttype'];
60
+ export async function authorizeTemplateOwner(actor, aid) {
61
+ if (!getDaemonOwners().includes(actor))
62
+ throw templateError('NOT_ALLOWED', 'DaemonOwner required', { reason: 'DAEMON_OWNER_REQUIRED' });
63
+ const owner = await ownerResolver.refresh(aid, { force: true, allowTransient: false, source: 'agent-template' });
64
+ if (owner.refreshFailure || owner.consensusStatus !== 'consensus' || owner.ownerAid !== actor) {
65
+ throw templateError('NOT_ALLOWED', 'Agent Owner required', { reason: 'AGENT_OWNER_REQUIRED' });
66
+ }
67
+ }
68
+ export function createAgentTemplateRuntime(options) {
69
+ const paths = resolvePaths();
70
+ const requireHost = () => {
71
+ const channel = options.getControl();
72
+ if (!channel?.getClient())
73
+ throw templateError('AUN_DISCONNECTED', 'Host Control AID is not connected');
74
+ return channel;
75
+ };
76
+ const profile = async (aid) => {
77
+ await options.waitForControl?.();
78
+ const card = await agentmdGet(aid, { withVerification: true, remoteOnly: true });
79
+ if (card.verification.status !== 'verified' || !card.remoteVersion?.etag)
80
+ throw templateError('PROFILE_UNAVAILABLE', 'Verified remote profile unavailable');
81
+ const parsed = validateAgentMdDocument(card.content, { expectedAid: aid, validateOwnership: false });
82
+ return { profile: Object.fromEntries([...FIELDS, 'type'].filter(k => parsed.frontmatter[k] !== undefined).map(k => [k, parsed.frontmatter[k]])),
83
+ profileVersion: card.remoteVersion.etag };
84
+ };
85
+ const context = async (aid, actor) => {
86
+ const agent = options.registry.get(aid);
87
+ const raw = loadAgent(aid);
88
+ if (!agent || !raw)
89
+ throw templateError('NOT_FOUND', 'Agent must exist on this host');
90
+ const card = await profile(aid);
91
+ const effective = resolveEffective({ self: aid }, {});
92
+ const providers = readProvidersSnapshot();
93
+ const config = structuredClone(effective);
94
+ for (const block of Object.values(config.baseagents ?? {}))
95
+ if (block.provider)
96
+ block.provider = resolveProviderId(block.provider, providers);
97
+ return { home: paths.root, packageRoot: getPackageRoot(), agentDir: path.join(paths.agentsDir, aid), agentAid: aid, targetAid: aid,
98
+ ownerAid: actor, hostAid: requireHost().getAid(), ...card, targetConfig: raw, effectiveConfig: config,
99
+ projectPath: effective.projects?.defaultPath, providers: providers.providers,
100
+ publisher: { aid: actor }, skills: resolveAllSkillStates(path.join(paths.agentsDir, aid)).map(s => ({ name: s.name, type: s.source, enabled: s.enabled })) };
101
+ };
102
+ return new AgentTemplateService({
103
+ root: paths.root, hostAid: loadDaemonConfig().aid ?? '', authorize: authorizeTemplateOwner,
104
+ source: context, target: context, exclusive: (aid, work) => options.coordinator.runExclusive(aid, work),
105
+ pause: async (aid) => {
106
+ const scheduler = options.getScheduler(aid);
107
+ return scheduler ? await scheduler.pauseForMutation() : async () => { };
108
+ },
109
+ reload: async (aid) => {
110
+ notifyConfigWrite(ConfigTarget.Agent, { self: aid });
111
+ refreshSkillIndex(path.join(paths.agentsDir, aid), aid);
112
+ await options.reloadInsideGate(aid);
113
+ },
114
+ block: options.block, recoveryComplete: options.recoveryComplete, readProfile: profile,
115
+ validateModels: async (config, refs) => {
116
+ for (const ref of refs) {
117
+ if (!ref.provider)
118
+ throw templateError('PROVIDER_NOT_FOUND', 'Choose a Provider for ' + ref.baseagent);
119
+ const block = config.baseagents[ref.baseagent];
120
+ const catalog = await getProviderCatalog(block.provider, undefined, false, false, ref.baseagent);
121
+ assertCatalogSelectable(catalog);
122
+ if (block.model && !catalog.models.some(m => m.id === resolveCatalogModel(catalog, block.model))) {
123
+ throw templateError('INVALID_ARGUMENT', 'Model is unavailable for ' + ref.baseagent);
124
+ }
125
+ if (block.effort && (!block.model || !catalogEfforts(catalog, block.model, ref.baseagent).includes(block.effort))) {
126
+ throw templateError('INVALID_ARGUMENT', 'Effort is unavailable for ' + ref.baseagent);
127
+ }
128
+ }
129
+ },
130
+ publishProfile: async (aid, values, expected) => {
131
+ await agentmdUpdate(aid, async (current) => {
132
+ if (expected && current.remoteVersion?.etag !== expected)
133
+ throw templateError('CONFLICT', 'Profile changed');
134
+ const parsed = validateAgentMdDocument(current.content, { expectedAid: aid, validateOwnership: false });
135
+ const fields = { ...parsed.frontmatter };
136
+ for (const key of FIELDS) {
137
+ if (values?.[key] !== undefined)
138
+ fields[key] = values[key];
139
+ else
140
+ delete fields[key];
141
+ }
142
+ const body = parsed.payload.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '');
143
+ return '---\n' + stringify(fields) + '---\n' + body;
144
+ });
145
+ const actual = await profile(aid);
146
+ for (const key of FIELDS)
147
+ if (JSON.stringify(actual.profile[key]) !== JSON.stringify(values?.[key])) {
148
+ throw templateError('PROFILE_NOT_CONFIRMED', 'Published profile was not confirmed');
149
+ }
150
+ },
151
+ upload: async (owner, remote, local, recoverExisting = false) => {
152
+ try {
153
+ if (recoverExisting) {
154
+ try {
155
+ const existing = await requireHost().callClient('storage.head_object', {
156
+ owner_aid: owner, bucket: 'default', object_key: remote.replace(/^\/+/, ''), consistency: 'authoritative',
157
+ });
158
+ const digest = createHash('sha256').update(fs.readFileSync(local)).digest('hex');
159
+ if (existing.exists !== false && existing.sha256 === digest && existing.size_bytes === fs.statSync(local).size)
160
+ return;
161
+ }
162
+ catch (error) {
163
+ if (!/not.?found|32008/i.test(String(error.code) + error.message))
164
+ throw error;
165
+ }
166
+ }
167
+ await requireHost().getClient().storage.uploadFile(local, remote, { owner, overwrite: false });
168
+ }
169
+ catch (error) {
170
+ const code = String(error.code ?? '');
171
+ throw templateError(/exist|conflict|32009/i.test(code + error.message) ? 'VERSION_EXISTS'
172
+ : /access|denied|32004/i.test(code + error.message) ? 'ACCESS_DENIED' : 'UPLOAD_FAILED', 'Template upload failed: ' + error.message);
173
+ }
174
+ },
175
+ download: async (shareId, file, location) => {
176
+ try {
177
+ const channel = requireHost();
178
+ // A share code is local to its storage issuer; owner_aid routes cross-issuer reads.
179
+ const value = await channel.callClient('storage.get_by_share', { share_id: shareId, owner_aid: location.aid });
180
+ const key = String(value.object_key ?? value.path ?? '').replace(/^\/+/, '');
181
+ if (key !== location.path.replace(/^\/+/, '') || value.owner_aid && value.owner_aid !== location.aid) {
182
+ throw templateError('INTEGRITY_FAILED', 'Share points to another package');
183
+ }
184
+ if (typeof value.content === 'string')
185
+ fs.writeFileSync(file, Buffer.from(value.content, 'base64'));
186
+ else if (typeof value.download_url === 'string') {
187
+ const response = await fetch(value.download_url, { signal: AbortSignal.timeout(120_000) });
188
+ if (!response.ok || !response.body)
189
+ throw new Error('Download HTTP ' + response.status);
190
+ const handle = fs.openSync(file, 'wx', 0o600);
191
+ let size = 0;
192
+ try {
193
+ for await (const bytes of response.body) {
194
+ size += bytes.length;
195
+ if (size > 200 * 1024 * 1024)
196
+ throw new Error('Package exceeds 200 MiB');
197
+ fs.writeSync(handle, bytes);
198
+ }
199
+ }
200
+ finally {
201
+ fs.closeSync(handle);
202
+ }
203
+ }
204
+ else
205
+ throw new Error('Share response has no content/download_url');
206
+ }
207
+ catch (error) {
208
+ if (error.code === 'INTEGRITY_FAILED')
209
+ throw error;
210
+ throw templateError(/access|denied|expired|32004/i.test(String(error.code) + error.message) ? 'ACCESS_DENIED' : 'DOWNLOAD_FAILED', error.message);
211
+ }
212
+ },
213
+ });
214
+ }