@ftai/dsh-plugin-acn 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/LICENSE-APACHE +201 -0
  3. package/LICENSE-MIT +19 -0
  4. package/README.md +82 -2
  5. package/README_EN.md +83 -0
  6. package/cordis.patch.yml +29 -0
  7. package/docs/acn-compat.md +33 -0
  8. package/docs/architecture.md +130 -0
  9. package/docs/assets/acn-claim-reuse.png +0 -0
  10. package/docs/assets/activity-view.png +0 -0
  11. package/docs/assets/install-package.png +0 -0
  12. package/docs/assets/knowledge-model.png +0 -0
  13. package/docs/assets/knowledge-view.png +0 -0
  14. package/docs/assets/personal-configuration.png +0 -0
  15. package/docs/assets/session-upstream.png +0 -0
  16. package/docs/assets/upstream-settings.png +0 -0
  17. package/docs/assets/upstream-team.png +0 -0
  18. package/docs/command-reference.md +201 -0
  19. package/docs/config.md +253 -0
  20. package/docs/development.md +197 -0
  21. package/docs/dsh-compat.md +59 -0
  22. package/docs/index.md +16 -0
  23. package/docs/outstanding-issues.md +61 -0
  24. package/docs/user_guide.md +185 -0
  25. package/icon.svg +8 -0
  26. package/lib/activities-B8U-iW4-.js +407 -0
  27. package/lib/alignment-CwH0nBf-.js +80 -0
  28. package/lib/auth-DFI9yowX.js +71 -0
  29. package/lib/checkpoint-CPFPOxBM.js +188 -0
  30. package/lib/checkpoint-c7aI4D-X.js +318 -0
  31. package/lib/claim-DOAGe8ZK.js +168 -0
  32. package/lib/client.js +18417 -0
  33. package/lib/deliver-C-dmhkfm.js +168 -0
  34. package/lib/delivery-status-M7-Rwoyj.js +89 -0
  35. package/lib/dispute-CtrInHzf.js +20 -0
  36. package/lib/disputes-ByEmi43j.js +51 -0
  37. package/lib/dream-agent-BVqxbKFc.js +249 -0
  38. package/lib/dream.js +4 -0
  39. package/lib/effects-DX1iy6FM.js +268 -0
  40. package/lib/errors-Bp_2WXBr.js +19 -0
  41. package/lib/errors-pPumDOGD.js +18 -0
  42. package/lib/evidence-store-DW7kj20i.js +1030 -0
  43. package/lib/formation-D4LO31WW.js +187 -0
  44. package/lib/formation-replay-Bf4TSBiz.js +87 -0
  45. package/lib/formation.js +9 -0
  46. package/lib/history-DPMHX3ZE.js +214 -0
  47. package/lib/inbox-2CugZZQm.js +188 -0
  48. package/lib/inbox-DFtE2fOp.js +71 -0
  49. package/lib/inbox.js +3 -0
  50. package/lib/index.js +1373 -0
  51. package/lib/lock-DbmlKOoX.js +332 -0
  52. package/lib/pages-BEWC3kmZ.js +51 -0
  53. package/lib/paths-B7NI9Ano.js +157 -0
  54. package/lib/plugins/commands.js +590 -0
  55. package/lib/plugins/dream.js +66 -0
  56. package/lib/plugins/formation.js +66 -0
  57. package/lib/plugins/inbox.js +53 -0
  58. package/lib/plugins/knowledge.js +1109 -0
  59. package/lib/plugins/prompt.js +102 -0
  60. package/lib/plugins/tools.js +280 -0
  61. package/lib/policy-DnyHh7Bl.js +16 -0
  62. package/lib/prepare-CGXwBEcu.js +134 -0
  63. package/lib/protocol.js +8 -0
  64. package/lib/queue-M917xHPS.js +153 -0
  65. package/lib/regular-file-BFpqMoub.js +136 -0
  66. package/lib/render-CJaVcKKC.js +48 -0
  67. package/lib/reported-sets-DdEKdeVb.js +122 -0
  68. package/lib/revision-DeoL_IUN.js +11 -0
  69. package/lib/scheduler-BfJSY1eq.js +64 -0
  70. package/lib/service-BPwaZzFF.js +1106 -0
  71. package/lib/service-BQaszW_v.js +344 -0
  72. package/lib/service-BhniAHLo.js +305 -0
  73. package/lib/service-C2lXoygJ.js +505 -0
  74. package/lib/session-binding-zCSuizHs.js +342 -0
  75. package/lib/session-state-CYqUhC95.js +38 -0
  76. package/lib/sessions-C2xuPFQv.js +218 -0
  77. package/lib/store.js +16 -0
  78. package/lib/structured-C9byFuzm.js +453 -0
  79. package/lib/subagent-yJsFxHmH.js +9 -0
  80. package/lib/team.js +3 -0
  81. package/lib/tool-schema-3b4gH1zf.js +28 -0
  82. package/lib/trace-Da0RnL5R.js +14 -0
  83. package/lib/traces-CHBo8y1z.js +11 -0
  84. package/lib/types/activities.d.ts +73 -0
  85. package/lib/types/advanced-configuration.d.ts +11 -0
  86. package/lib/types/client/ActivityCard.d.ts +14 -0
  87. package/lib/types/client/ActivityDetails.d.ts +18 -0
  88. package/lib/types/client/AdvancedPreferences.d.ts +8 -0
  89. package/lib/types/client/BlankCommandFeedback.d.ts +10 -0
  90. package/lib/types/client/ComposerMenu.d.ts +24 -0
  91. package/lib/types/client/ConfigurationPage.d.ts +11 -0
  92. package/lib/types/client/ConnectionCheckDialog.d.ts +12 -0
  93. package/lib/types/client/KnowledgeDetail.d.ts +6 -0
  94. package/lib/types/client/KnowledgeDirectoryField.d.ts +11 -0
  95. package/lib/types/client/KnowledgePanel.d.ts +12 -0
  96. package/lib/types/client/KnowledgeReference.d.ts +13 -0
  97. package/lib/types/client/SessionToolbar.d.ts +16 -0
  98. package/lib/types/client/SettingsToast.d.ts +3 -0
  99. package/lib/types/client/SourceSessionLink.d.ts +16 -0
  100. package/lib/types/client/TeamCredentialField.d.ts +16 -0
  101. package/lib/types/client/TeamSettingsPage.d.ts +28 -0
  102. package/lib/types/client/configuration-errors.d.ts +2 -0
  103. package/lib/types/client/interaction-styles.d.ts +1 -0
  104. package/lib/types/client/interaction-ui.d.ts +30 -0
  105. package/lib/types/client/knowledge-labels.d.ts +5 -0
  106. package/lib/types/client/locales.d.ts +51 -0
  107. package/lib/types/commands/claim.d.ts +4 -0
  108. package/lib/types/commands/import.d.ts +10 -0
  109. package/lib/types/commands/status.d.ts +5 -0
  110. package/lib/types/config.d.ts +111 -0
  111. package/lib/types/configuration.d.ts +235 -0
  112. package/lib/types/credentials.d.ts +59 -0
  113. package/lib/types/dream/audit.d.ts +4 -0
  114. package/lib/types/dream/autonomous.d.ts +185 -0
  115. package/lib/types/dream/candidates.d.ts +34 -0
  116. package/lib/types/dream/checkpoint.d.ts +35 -0
  117. package/lib/types/dream/evidence-files.d.ts +10 -0
  118. package/lib/types/dream/evidence-store.d.ts +103 -0
  119. package/lib/types/dream/evidence.d.ts +30 -0
  120. package/lib/types/dream/index.d.ts +10 -0
  121. package/lib/types/dream/plan.d.ts +18 -0
  122. package/lib/types/dream/preservation.d.ts +6 -0
  123. package/lib/types/dream/review.d.ts +10 -0
  124. package/lib/types/dream/schema.d.ts +1475 -0
  125. package/lib/types/dream/service.d.ts +56 -0
  126. package/lib/types/dream/sync.d.ts +147 -0
  127. package/lib/types/dsh-adapter/configuration-remote.d.ts +1 -0
  128. package/lib/types/dsh-adapter/configuration-service.d.ts +28 -0
  129. package/lib/types/dsh-adapter/dream-agent.d.ts +4 -0
  130. package/lib/types/dsh-adapter/dream-evidence.d.ts +3 -0
  131. package/lib/types/dsh-adapter/formation-archive.d.ts +3 -0
  132. package/lib/types/dsh-adapter/formation-replay.d.ts +5 -0
  133. package/lib/types/dsh-adapter/formation.d.ts +4 -0
  134. package/lib/types/dsh-adapter/interaction-service.d.ts +13 -0
  135. package/lib/types/dsh-adapter/knowledge-paths.d.ts +3 -0
  136. package/lib/types/dsh-adapter/llm.d.ts +10 -0
  137. package/lib/types/dsh-adapter/project-upstream.d.ts +4 -0
  138. package/lib/types/dsh-adapter/runtime-pool.d.ts +110 -0
  139. package/lib/types/dsh-adapter/session-binding.d.ts +43 -0
  140. package/lib/types/dsh-adapter/source-sessions.d.ts +3 -0
  141. package/lib/types/dsh-adapter/team-credentials.d.ts +5 -0
  142. package/lib/types/dsh-adapter/tool-schema.d.ts +4 -0
  143. package/lib/types/dsh-adapter/tools.d.ts +5 -0
  144. package/lib/types/formation/capture.d.ts +19 -0
  145. package/lib/types/formation/checkpoint.d.ts +136 -0
  146. package/lib/types/formation/index.d.ts +10 -0
  147. package/lib/types/formation/prepare.d.ts +16 -0
  148. package/lib/types/formation/schema.d.ts +45 -0
  149. package/lib/types/formation/service.d.ts +58 -0
  150. package/lib/types/formation/transcript.d.ts +75 -0
  151. package/lib/types/formation/triggers.d.ts +3 -0
  152. package/lib/types/inbox/cascade.d.ts +3 -0
  153. package/lib/types/inbox/effects.d.ts +275 -0
  154. package/lib/types/inbox/index.d.ts +5 -0
  155. package/lib/types/inbox/prepare.d.ts +380 -0
  156. package/lib/types/inbox/service.d.ts +26 -0
  157. package/lib/types/inbox/sync.d.ts +9 -0
  158. package/lib/types/index.d.ts +1 -0
  159. package/lib/types/interaction-messages.d.ts +69 -0
  160. package/lib/types/interaction.d.ts +541 -0
  161. package/lib/types/knowledge/alignment.d.ts +49 -0
  162. package/lib/types/knowledge/catalog.d.ts +5 -0
  163. package/lib/types/knowledge/changes.d.ts +32 -0
  164. package/lib/types/knowledge/disputes.d.ts +3 -0
  165. package/lib/types/knowledge/errors.d.ts +9 -0
  166. package/lib/types/knowledge/ordering.d.ts +7 -0
  167. package/lib/types/knowledge/pages.d.ts +7 -0
  168. package/lib/types/knowledge/safety.d.ts +2 -0
  169. package/lib/types/knowledge/service.d.ts +52 -0
  170. package/lib/types/knowledge/sessions.d.ts +59 -0
  171. package/lib/types/knowledge/sources.d.ts +2 -0
  172. package/lib/types/knowledge/timestamps.d.ts +1 -0
  173. package/lib/types/knowledge/types.d.ts +84 -0
  174. package/lib/types/llm/response.d.ts +1 -0
  175. package/lib/types/llm/structured.d.ts +27 -0
  176. package/lib/types/local-name.d.ts +1 -0
  177. package/lib/types/plugins/client.d.ts +9 -0
  178. package/lib/types/plugins/commands.d.ts +11 -0
  179. package/lib/types/plugins/configuration.d.ts +8 -0
  180. package/lib/types/plugins/dream.d.ts +16 -0
  181. package/lib/types/plugins/formation.d.ts +16 -0
  182. package/lib/types/plugins/inbox.d.ts +16 -0
  183. package/lib/types/plugins/knowledge.d.ts +19 -0
  184. package/lib/types/plugins/prompt.d.ts +17 -0
  185. package/lib/types/plugins/tools.d.ts +10 -0
  186. package/lib/types/prompt/render.d.ts +2 -0
  187. package/lib/types/protocol/arbitration.d.ts +154 -0
  188. package/lib/types/protocol/auth.d.ts +31 -0
  189. package/lib/types/protocol/claim.d.ts +36 -0
  190. package/lib/types/protocol/dispute.d.ts +17 -0
  191. package/lib/types/protocol/ids.d.ts +20 -0
  192. package/lib/types/protocol/inbox.d.ts +141 -0
  193. package/lib/types/protocol/index.d.ts +11 -0
  194. package/lib/types/protocol/policy.d.ts +21 -0
  195. package/lib/types/protocol/revision.d.ts +2 -0
  196. package/lib/types/protocol/router.d.ts +114 -0
  197. package/lib/types/protocol/schema.d.ts +4 -0
  198. package/lib/types/protocol/time.d.ts +5 -0
  199. package/lib/types/protocol/trace.d.ts +11 -0
  200. package/lib/types/store/atomic.d.ts +8 -0
  201. package/lib/types/store/claim-edits.d.ts +33 -0
  202. package/lib/types/store/claims.d.ts +7 -0
  203. package/lib/types/store/context.d.ts +13 -0
  204. package/lib/types/store/delivery-status.d.ts +48 -0
  205. package/lib/types/store/disputes.d.ts +6 -0
  206. package/lib/types/store/entities.d.ts +16 -0
  207. package/lib/types/store/errors.d.ts +8 -0
  208. package/lib/types/store/history.d.ts +65 -0
  209. package/lib/types/store/inbox.d.ts +27 -0
  210. package/lib/types/store/index.d.ts +16 -0
  211. package/lib/types/store/jobs.d.ts +5 -0
  212. package/lib/types/store/library-directory.d.ts +4 -0
  213. package/lib/types/store/lock.d.ts +11 -0
  214. package/lib/types/store/path-names.d.ts +2 -0
  215. package/lib/types/store/paths.d.ts +45 -0
  216. package/lib/types/store/presentation.d.ts +13 -0
  217. package/lib/types/store/regular-file.d.ts +2 -0
  218. package/lib/types/store/rejected-disputes.d.ts +18 -0
  219. package/lib/types/store/rename.d.ts +1 -0
  220. package/lib/types/store/reported-sets.d.ts +24 -0
  221. package/lib/types/store/session-state.d.ts +17 -0
  222. package/lib/types/store/traces.d.ts +6 -0
  223. package/lib/types/store/uploads.d.ts +312 -0
  224. package/lib/types/store/yaml.d.ts +8 -0
  225. package/lib/types/team/errors.d.ts +10 -0
  226. package/lib/types/team/http.d.ts +20 -0
  227. package/lib/types/team/index.d.ts +5 -0
  228. package/lib/types/team/maintainer-client.d.ts +18 -0
  229. package/lib/types/team/router-client.d.ts +14 -0
  230. package/lib/types/team/service.d.ts +28 -0
  231. package/lib/types/team/system-proxy.d.ts +9 -0
  232. package/lib/types/tools/claim.d.ts +63 -0
  233. package/lib/types/tools/consult-router.d.ts +11 -0
  234. package/lib/types/tools/subagent.d.ts +8 -0
  235. package/lib/types/tools/validation.d.ts +2 -0
  236. package/lib/types/upload/consolidation.d.ts +63 -0
  237. package/lib/types/upload/deliver.d.ts +15 -0
  238. package/lib/types/upload/index.d.ts +2 -0
  239. package/lib/types/upload/scheduler.d.ts +19 -0
  240. package/lib/types/upstreams.d.ts +5 -0
  241. package/lib/types/worker/queue.d.ts +17 -0
  242. package/lib/types/worker/types.d.ts +51 -0
  243. package/lib/types/worker/worker.d.ts +39 -0
  244. package/lib/types-C2ST2Zdg.js +17 -0
  245. package/lib/upload.js +3 -0
  246. package/lib/uploads-BCA2p92b.js +210 -0
  247. package/lib/upstreams-DEi-56tD.js +495 -0
  248. package/lib/worker-HMGzJFWd.js +185 -0
  249. package/locale/commands/en.json +1 -0
  250. package/locale/commands/zh.json +1 -0
  251. package/locale/dream/en.json +1 -0
  252. package/locale/dream/zh.json +1 -0
  253. package/locale/en.json +7 -0
  254. package/locale/formation/en.json +1 -0
  255. package/locale/formation/zh.json +1 -0
  256. package/locale/inbox/en.json +1 -0
  257. package/locale/inbox/zh.json +1 -0
  258. package/locale/knowledge/en.json +1 -0
  259. package/locale/knowledge/zh.json +1 -0
  260. package/locale/prompt/en.json +1 -0
  261. package/locale/prompt/zh.json +1 -0
  262. package/locale/tools/en.json +1 -0
  263. package/locale/tools/zh.json +1 -0
  264. package/locale/zh.json +7 -0
  265. package/package.json +262 -3
  266. package/prompts/claim_dream.j2 +77 -0
  267. package/prompts/claim_dream_legacy.j2 +63 -0
  268. package/prompts/dream_compaction.j2 +11 -0
  269. package/prompts/dream_evidence.j2 +5 -0
  270. package/prompts/inbox_claim_attribute_update_internalize.j2 +112 -0
  271. package/prompts/inbox_policy_update_internalize.j2 +87 -0
  272. package/prompts/knowledge.j2 +38 -0
  273. package/prompts/session_recap.j2 +113 -0
  274. package/prompts/what_is_claim.j2 +51 -0
  275. package/prompts/what_is_dispute.j2 +21 -0
  276. package/prompts/what_is_policy.j2 +22 -0
@@ -0,0 +1,1106 @@
1
+ import { h as TraceIdSchema, l as ClaimIdSchema, t as ClaimSchema, x as nowSeconds } from "./claim-DOAGe8ZK.js";
2
+ import { n as resolveRoute, r as structuredCall } from "./structured-C9byFuzm.js";
3
+ import { A as valueHash, B as CandidateSchema, C as expandDraft, D as sameIds, E as reviewInput, G as DraftResponseSchema, M as validateEvidenceSummaryPreservation, O as validateCandidates, U as DiscoverySchema, W as DraftGroupSchema, X as KeepReasonSchema, Y as HashSchema, Z as KeySchema, _ as dreamEligible, a as GlobArgs, b as validateSelfReview, ct as ReviewSummarySchema, g as conservativeTokens, h as claimInput, j as validateEvidencePreservation, k as validateConsolidationSources, o as GrepArgs, pt as requireDream, q as DreamValidationError, r as EvidenceStore, rt as ProgressSchema, s as ReadArgs, st as ReviewResponseSchema, ut as SemanticReviewSchema, w as prepareGroup, x as validateSemanticReview } from "./evidence-store-DW7kj20i.js";
4
+ import { C as StoreError, S as LockTimeoutError, _ as JobError, c as readYamlOr, g as DreamYield, h as DreamStopped, l as writeYamlAtomic, n as withFileLock, s as readYaml, w as hasCode, x as jobPriority } from "./lock-DbmlKOoX.js";
5
+ import { l as sameClaim, r as KnowledgeBusy, s as ensureKnowledgeReady } from "./alignment-CwH0nBf-.js";
6
+ import { i as ClaimStore } from "./reported-sets-DdEKdeVb.js";
7
+ import { t as TraceStore } from "./traces-CHBo8y1z.js";
8
+ import { r as UploadStore, t as ConsolidationDeliverySchema } from "./uploads-BCA2p92b.js";
9
+ import { t as UploadDelivery } from "./deliver-C-dmhkfm.js";
10
+ import { z } from "zod";
11
+ import fs from "node:fs/promises";
12
+ import { join } from "node:path";
13
+ //#region src/dream/sync.ts
14
+ const SyncValidationSchema = z.strictObject({
15
+ validation_id: HashSchema,
16
+ input: z.strictObject({
17
+ before: ClaimSchema,
18
+ carriers: z.array(ClaimSchema),
19
+ previous_dependency: ConsolidationDeliverySchema,
20
+ current_source: ClaimSchema
21
+ })
22
+ });
23
+ const SyncRecordSchema = z.strictObject({
24
+ validation: SyncValidationSchema,
25
+ review: SemanticReviewSchema,
26
+ applied: z.boolean(),
27
+ abandoned: z.boolean().default(false)
28
+ });
29
+ var DreamSync = class {
30
+ context;
31
+ semanticReview;
32
+ constructor(context, semanticReview = false) {
33
+ this.context = context;
34
+ this.semanticReview = semanticReview;
35
+ }
36
+ async resume(jobId, sourceId, signal) {
37
+ const root = join(this.context.paths.dreamJob(jobId), "sync_reviews");
38
+ let files;
39
+ try {
40
+ files = await fs.readdir(root);
41
+ } catch (error) {
42
+ if (hasCode(error, "ENOENT")) return false;
43
+ throw error;
44
+ }
45
+ for (const file of files.filter((name) => /^[0-9a-f]{64}\.yaml$/.test(name)).sort()) {
46
+ const path = join(root, file);
47
+ const record = await readYaml(path, SyncRecordSchema);
48
+ if (record.validation.input.before.id !== sourceId || record.abandoned) continue;
49
+ if (record.applied) return true;
50
+ try {
51
+ await this.apply(jobId, record.validation, record.review, signal);
52
+ return true;
53
+ } catch (error) {
54
+ if (!(error instanceof DreamValidationError || error instanceof StoreError && error.kind === "conflict")) throw error;
55
+ await writeYamlAtomic(path, {
56
+ ...record,
57
+ abandoned: true
58
+ }, SyncRecordSchema, this.context.logger);
59
+ }
60
+ }
61
+ return false;
62
+ }
63
+ async prepare(sourceId, carrierIds, signal) {
64
+ return withFileLock(this.context.paths.knowledgeLock, async () => {
65
+ await ensureKnowledgeReady(this.context.paths.root);
66
+ return this.prepareLocked(sourceId, carrierIds);
67
+ }, { signal });
68
+ }
69
+ async prepareLocked(sourceId, carrierIds) {
70
+ requireDream(this.context.mode === "team", "单人模式没有整合交付依赖。");
71
+ const previous = (await new UploadStore(this.context).read()).consolidations?.find((group) => group.retired.id === sourceId);
72
+ requireDream(previous !== void 0, "没有对应的待交付整合来源。");
73
+ const current = await new ClaimStore(this.context).list();
74
+ const source = current.find((claim) => claim.id === sourceId);
75
+ requireDream(source !== void 0 && sameClaim(source, previous.retired) && source.holder === this.context.agentId, "来源已变化,旧弃用请求不能重绑。");
76
+ const carriers = carrierIds.map((id) => current.find((claim) => claim.id === id));
77
+ requireDream(carriers.length > 0 && new Set(carrierIds).size === carrierIds.length && carriers.every((claim) => claim !== void 0 && claim.holder === this.context.agentId && claim.status !== "deprecated"), "承接必须是当前完整、唯一、存续的自身 Claim。");
78
+ const input = {
79
+ before: previous.before,
80
+ carriers: carriers.filter((claim) => claim !== void 0),
81
+ previous_dependency: previous,
82
+ current_source: source
83
+ };
84
+ if (!this.semanticReview) validateEvidenceSummaryPreservation(input.before, input.carriers);
85
+ return SyncValidationSchema.parse({
86
+ validation_id: valueHash(input),
87
+ input
88
+ });
89
+ }
90
+ async apply(jobId, validation, review, signal) {
91
+ const input = validation.input;
92
+ const carrierIds = input.carriers.map((claim) => claim.id);
93
+ requireDream(valueHash(input) === validation.validation_id, "同步复核哈希必须绑定完整输入。");
94
+ requireDream(review.claims.length === 1 && review.claims[0]?.claim_id === input.before.id, "同步复核只描述原整合来源。");
95
+ const item = review.claims[0];
96
+ requireDream(item !== void 0 && item.final_name === input.current_source.name && item.name_reason.trim() !== "" && !item.factual_correction && item.evidence_ids.length === 0 && sameIds(item.output_ids, carrierIds), "同步复核只能确认当前承接完整保留信息,不能纠正事实或省略承接项。");
97
+ validateConsolidationSources(input.before, input.carriers, carrierIds);
98
+ await withFileLock(this.context.paths.knowledgeLock, async () => {
99
+ await ensureKnowledgeReady(this.context.paths.root);
100
+ const path = join(this.context.paths.dreamJob(KeySchema.parse(jobId)), "sync_reviews", `${validation.validation_id}.yaml`);
101
+ if ((await readYamlOr(path, SyncRecordSchema, () => null))?.applied) return;
102
+ const current = await this.prepareLocked(input.before.id, carrierIds);
103
+ const revised = {
104
+ ...input.previous_dependency,
105
+ carriers: input.carriers
106
+ };
107
+ const rebound = valueHash(current.input.previous_dependency) === valueHash(revised) && current.input.carriers.every((claim, index) => input.carriers[index] !== void 0 && sameClaim(claim, input.carriers[index]));
108
+ requireDream(current.validation_id === validation.validation_id || rebound, "同步输入版本已变化,必须重新读取和复核。");
109
+ signal.throwIfAborted();
110
+ await writeYamlAtomic(path, {
111
+ validation,
112
+ review,
113
+ applied: false
114
+ }, SyncRecordSchema, this.context.logger);
115
+ await new UploadStore(this.context).rebind(input.previous_dependency, revised);
116
+ await writeYamlAtomic(path, {
117
+ validation,
118
+ review,
119
+ applied: true
120
+ }, SyncRecordSchema, this.context.logger);
121
+ }, { signal });
122
+ }
123
+ };
124
+ //#endregion
125
+ //#region src/dream/autonomous.ts
126
+ const groupId = { group_id: KeySchema };
127
+ const DreamTools = {
128
+ dream_record_candidates: z.strictObject({ candidates: z.array(CandidateSchema).min(1) }),
129
+ dream_stage_group: z.strictObject({
130
+ ...groupId,
131
+ group: DraftGroupSchema.nullable()
132
+ }),
133
+ dream_validate: z.strictObject(groupId),
134
+ dream_apply_group: z.strictObject({
135
+ ...groupId,
136
+ validation_id: HashSchema,
137
+ review: SemanticReviewSchema
138
+ }),
139
+ dream_keep_candidate: z.strictObject({
140
+ ...groupId,
141
+ reason_kind: KeepReasonSchema,
142
+ reason: z.string().min(1)
143
+ }),
144
+ dream_read_draft: z.strictObject({ group_id: KeySchema.optional() }),
145
+ dream_read_history: z.strictObject({
146
+ offset: z.number().int().nonnegative().default(0),
147
+ limit: z.number().int().min(1).max(10).default(5)
148
+ }),
149
+ dream_review_sync: z.strictObject({
150
+ source_id: ClaimIdSchema,
151
+ carrier_ids: z.array(ClaimIdSchema).min(1),
152
+ validation_id: HashSchema.optional(),
153
+ review: SemanticReviewSchema.optional()
154
+ }),
155
+ dream_finish: z.strictObject({ review: ReviewSummarySchema }),
156
+ read_claim: z.strictObject({ id: ClaimIdSchema }),
157
+ read_trace: z.strictObject({
158
+ claim_id: ClaimIdSchema.optional(),
159
+ trace_id: TraceIdSchema.optional(),
160
+ id: TraceIdSchema.optional(),
161
+ offset: z.number().int().nonnegative().default(0),
162
+ limit: z.number().int().min(1).max(8e3).optional()
163
+ }).refine((value) => value.id === void 0 ? value.claim_id !== void 0 : value.claim_id === void 0 && value.trace_id === void 0, "提供 claim_id,按需提供 trace_id;旧 id 入口不能混用其它 ID 字段。"),
164
+ file_read: ReadArgs,
165
+ file_glob: GlobArgs,
166
+ file_grep: GrepArgs
167
+ };
168
+ const isDreamTool = (name) => Object.hasOwn(DreamTools, name);
169
+ var DreamSession = class DreamSession {
170
+ knowledge;
171
+ job;
172
+ control;
173
+ progress;
174
+ claims;
175
+ originalHigh;
176
+ workspace;
177
+ boundary;
178
+ pending = Promise.resolve();
179
+ constructor(knowledge, job, control, progress, claims, originalHigh, workspace, boundary) {
180
+ this.knowledge = knowledge;
181
+ this.job = job;
182
+ this.control = control;
183
+ this.progress = progress;
184
+ this.claims = claims;
185
+ this.originalHigh = originalHigh;
186
+ this.workspace = workspace;
187
+ this.boundary = boundary;
188
+ }
189
+ static async create(knowledge, job, control, boundary) {
190
+ const store = knowledge.dreamStore();
191
+ const origin = await store.origin(job.id);
192
+ requireDream(origin?.workspace_root !== void 0, "缺少 Dream 工作区快照。");
193
+ const progress = await store.progress(job.id) ?? ProgressSchema.parse({
194
+ schemaVersion: 1,
195
+ discovery: {
196
+ review: {
197
+ quality: "尚未检查",
198
+ evidence: "尚未探索",
199
+ consolidation: "尚未检查"
200
+ },
201
+ candidates: [],
202
+ sync_candidates: []
203
+ },
204
+ entries: [],
205
+ syncCompleted: [],
206
+ finished: false,
207
+ summary: null
208
+ });
209
+ const input = claimInput(origin.claims.filter((claim) => claim.status !== "deprecated"));
210
+ if (progress.autonomy === void 0) progress.autonomy = {
211
+ steps: 0,
212
+ epoch: 0,
213
+ limit: knowledge.config.dream.maxModelSteps,
214
+ read_ids: input.loaded.map((claim) => claim.id)
215
+ };
216
+ const claims = [...origin.claims];
217
+ for (const { checkpoint } of await store.records(job.id)) for (const group of checkpoint.groups.filter((item) => item.completed && !item.skipped)) for (const after of group.after) {
218
+ const index = claims.findIndex((claim) => claim.id === after.id);
219
+ const previous = claims[index];
220
+ if (index >= 0 && previous !== void 0 && Date.parse(after.updated_at ?? after.created_at) >= Date.parse(previous.updated_at ?? previous.created_at)) claims[index] = after;
221
+ }
222
+ for (const entry of progress.entries.filter((item) => item.status === "pending")) {
223
+ const record = (await store.records(job.id)).find(({ checkpoint }) => entry.validation !== null && checkpoint.operation?.group_id === entry.candidate.group_id && checkpoint.operation.validation_id === entry.validation.validation_id && checkpoint.applied);
224
+ if (record !== void 0) {
225
+ entry.status = record.checkpoint.groups.some((group) => group.skipped) ? "skipped" : "executed";
226
+ entry.reason = "从持久执行回执恢复。";
227
+ }
228
+ }
229
+ if ((await store.final(job.id))?.applied) progress.finished = true;
230
+ await store.saveProgress(job.id, progress);
231
+ return new DreamSession(knowledge, job, control, progress, claims, new Set(origin.claims.filter((claim) => claim.confidence === "high").map((claim) => claim.id)), origin.workspace_root, boundary);
232
+ }
233
+ get finished() {
234
+ return this.progress.finished;
235
+ }
236
+ get exhausted() {
237
+ const budget = this.progress.autonomy;
238
+ return budget !== void 0 && budget.steps >= budget.limit;
239
+ }
240
+ get wrappingUp() {
241
+ return this.progress.autonomy?.wrap_up !== void 0;
242
+ }
243
+ budgetNotice() {
244
+ const budget = this.progress.autonomy;
245
+ if (budget === void 0) return "";
246
+ return `Dream 运行额度:\n${JSON.stringify({
247
+ budget,
248
+ phase: this.wrappingUp ? "wrap_up" : "exploration",
249
+ instruction: this.wrappingUp ? "探索额度已用尽,现在进行本次 Dream 的有限收尾。禁止发现新候选、读取新证据或启动同步复核;只可完成已登记项的草稿、校验与提交,或保留原样。立即用 dream_finish 总结真实覆盖和未完成事项,剩余 pending 将记为未完成并丢弃未提交草稿。本次结束后不会再次续做;不为赶结束跳过校验。" : "按剩余额度安排探索;完成时调用 dream_finish,不把未执行事项写成已完成。"
250
+ })}`;
251
+ }
252
+ async admitStep(signal) {
253
+ this.control.signal.throwIfAborted();
254
+ signal?.throwIfAborted();
255
+ await this.boundary();
256
+ requireDream(!this.finished, "Dream 已结束。");
257
+ const budget = this.progress.autonomy;
258
+ requireDream(budget !== void 0, "缺少持久轮数预算。");
259
+ if (this.exhausted) {
260
+ budget.wrap_up ??= {
261
+ steps: 0,
262
+ limit: this.knowledge.config.dream.maxWrapUpSteps
263
+ };
264
+ if (budget.wrap_up.steps >= budget.wrap_up.limit) {
265
+ await this.finishBudget(signal);
266
+ throw new JobError("dream_finished", "Dream 已按额度收尾结束。");
267
+ }
268
+ budget.wrap_up.steps += 1;
269
+ } else budget.steps += 1;
270
+ await this.save();
271
+ signal?.throwIfAborted();
272
+ }
273
+ async finishBudget(signal) {
274
+ if (this.finished) return;
275
+ requireDream(this.exhausted, "尚未耗尽探索额度。");
276
+ const control = {
277
+ ...this.control,
278
+ signal: signal === void 0 ? this.control.signal : AbortSignal.any([this.control.signal, signal])
279
+ };
280
+ control.signal.throwIfAborted();
281
+ const review = Object.fromEntries([
282
+ "quality",
283
+ "evidence",
284
+ "consolidation"
285
+ ].map((kind) => {
286
+ const entries = this.progress.entries.filter((entry) => entry.candidate.kind === kind);
287
+ return [kind, `模型未提交收尾总结,插件按持久记录终结本次:${entries.filter((entry) => entry.status === "executed").length} 项已执行,${entries.filter((entry) => entry.status === "kept").length} 项明确保留,${entries.filter((entry) => entry.status === "pending" || entry.status === "skipped").length} 项未完成或跳过。未检查范围不能视作已验证;详见逐项回执。`];
288
+ }));
289
+ await this.finish(ReviewSummarySchema.parse(review), control);
290
+ }
291
+ async finish(review, control) {
292
+ if (this.exhausted) for (const entry of this.progress.entries.filter((item) => item.status === "pending")) {
293
+ entry.status = "skipped";
294
+ entry.reason = "本次额度已用尽,收尾时仍未完成;丢弃未提交草稿,不代表知识无效。";
295
+ entry.draft = null;
296
+ entry.validation = null;
297
+ entry.review = null;
298
+ }
299
+ requireDream(this.progress.entries.every((entry) => entry.status !== "pending"), "仍有候选待处理。");
300
+ if (!this.exhausted && this.readable().length > 0 && !this.progress.finish_reminder_sent && !this.progress.proposal_attempted && this.progress.entries.length === 0 && this.progress.exploration_receipts === 0 && (await this.knowledge.dreamStore().records(this.job.id)).length === 0) {
301
+ this.progress.finish_reminder_sent = true;
302
+ await this.save();
303
+ return {
304
+ accepted: false,
305
+ finished: false,
306
+ confirmation_required: true,
307
+ activity: {
308
+ exploration_receipts: 0,
309
+ proposal_attempted: false,
310
+ executed_groups: 0
311
+ },
312
+ note: "本轮尚无探索回执或修改提案。这是一次结束前提醒,不要求增加工具调用或修改数量。请检查:A 判断记忆层级,high 也可清理纯工作记录;B 才受 medium/low 门槛限制;C 可以保留分开的知识。尚未暂存/受理不是不能提出候选的理由。可以继续探索或暂存草稿;若仍决定全部保留,请在 ABC 总结中简述代表 Claim 的保留依据、B 未选候选的原因(未探索不等于查证后缺证据),再调用 dream_finish 即可结束,不会重复此提醒。"
313
+ };
314
+ }
315
+ this.progress.discovery.review = review;
316
+ await this.save();
317
+ const checkpoint = await this.knowledge.dreamStore().finish(this.job.id, this.progress, control);
318
+ control.committed?.();
319
+ this.progress.finished = true;
320
+ await this.save();
321
+ return {
322
+ finished: true,
323
+ updatedClaimIds: Object.keys(checkpoint.self_versions),
324
+ budget_limited: this.exhausted
325
+ };
326
+ }
327
+ save() {
328
+ return this.knowledge.dreamStore().saveProgress(this.job.id, this.progress);
329
+ }
330
+ current(groupId) {
331
+ const entry = this.progress.entries.find((item) => item.status === "pending");
332
+ requireDream(entry !== void 0 && (groupId === void 0 || entry.candidate.group_id === groupId), "请先处理 candidate_progress.current;不能跳过当前候选或重放已执行组。");
333
+ return entry;
334
+ }
335
+ readable() {
336
+ return this.claims.filter((claim) => this.progress.autonomy?.read_ids.includes(claim.id));
337
+ }
338
+ candidateProgress() {
339
+ return {
340
+ current: this.progress.entries.find((entry) => entry.status === "pending")?.candidate ?? null,
341
+ entries: this.progress.entries.map(({ candidate, status, reason }) => ({
342
+ ...candidate,
343
+ status,
344
+ reason
345
+ }))
346
+ };
347
+ }
348
+ async input() {
349
+ const store = this.knowledge.dreamStore();
350
+ const origin = await store.origin(this.job.id);
351
+ return {
352
+ workspace_root: this.workspace,
353
+ dream_context: {
354
+ agent_id: this.knowledge.agentId,
355
+ snapshot_at: origin?.snapshot_at,
356
+ eligibility: this.claims.map((claim) => ({
357
+ id: claim.id,
358
+ owned: true,
359
+ evidence_eligible: origin?.claims.some((original) => original.id === claim.id && original.confidence !== "high") && claim.status !== "deprecated"
360
+ }))
361
+ },
362
+ claims: this.readable(),
363
+ coverage: origin?.coverage,
364
+ claim_catalog: this.claims.filter((claim) => !this.progress.autonomy?.read_ids.includes(claim.id)).map(({ id, name, scope, status }) => ({
365
+ id,
366
+ name,
367
+ scope,
368
+ status
369
+ })),
370
+ policy_context: {
371
+ available: false,
372
+ complete: false
373
+ },
374
+ pending_consolidation_sync: (await new UploadStore(this.knowledge.context()).read()).consolidations ?? [],
375
+ capabilities: {
376
+ evidence_calibration: this.knowledge.config.dream.evidenceCalibration,
377
+ shell: false,
378
+ evidence_limits: {
379
+ calls_per_group: this.knowledge.config.dream.evidenceMaxCalls,
380
+ bytes_per_group: this.knowledge.config.dream.evidenceMaxBytes
381
+ }
382
+ },
383
+ budget: this.progress.autonomy,
384
+ authoritative_state: {
385
+ candidate_progress: this.candidateProgress(),
386
+ drafts: this.progress.entries.filter((entry) => entry.status === "pending"),
387
+ executions: (await store.records(this.job.id)).map(({ checkpoint }) => ({
388
+ operation: checkpoint.operation,
389
+ groups: checkpoint.groups
390
+ })),
391
+ evidence: await this.evidenceState()
392
+ }
393
+ };
394
+ }
395
+ async evidenceState() {
396
+ return Object.fromEntries(await Promise.all(this.progress.entries.filter((entry) => entry.status === "pending").map(async (entry) => [entry.candidate.group_id, await new EvidenceStore(this.knowledge.context(), this.job.id, entry.candidate.group_id).read()])));
397
+ }
398
+ register(candidates) {
399
+ const next = structuredClone(this.progress.entries);
400
+ const groups = /* @__PURE__ */ new Set();
401
+ for (const candidate of candidates) {
402
+ requireDream(candidate.group_id !== "_discovery", "该组名为宿主只读探索保留,请使用其他 group_id。");
403
+ requireDream(!groups.has(candidate.group_id), "同一批不能重复登记 group_id。");
404
+ groups.add(candidate.group_id);
405
+ validateCandidates([candidate], this.readable(), this.knowledge.context().agentId, this.knowledge.config.dream.evidenceCalibration);
406
+ requireDream(candidate.kind !== "evidence" || candidate.claim_ids.every((id) => !this.originalHigh.has(id)), "high Claim 不进入证据校准;资格以本轮原始版本为准。");
407
+ const prior = next.find((entry) => entry.status === "pending" && entry.candidate.group_id === candidate.group_id);
408
+ for (const entry of next.filter((item) => item.status === "pending")) if (entry === prior) requireDream(entry.candidate.claim_ids.every((id) => candidate.claim_ids.includes(id)), "不能静默删除当前候选的 Claim;先处理或明确保留。");
409
+ else requireDream(!entry.candidate.claim_ids.some((id) => candidate.claim_ids.includes(id)), "待处理候选不能重叠;请在已有组内细化。");
410
+ if (prior !== void 0) {
411
+ if (prior.candidate.kind !== candidate.kind || !sameIds(prior.candidate.claim_ids, candidate.claim_ids)) {
412
+ prior.validation = null;
413
+ prior.review = null;
414
+ }
415
+ prior.candidate = candidate;
416
+ } else next.push({
417
+ candidate,
418
+ status: "pending",
419
+ reason: "",
420
+ draft: null,
421
+ validation: null,
422
+ review: null
423
+ });
424
+ }
425
+ this.progress.entries = next;
426
+ this.progress.discovery.candidates = next.map((entry) => entry.candidate);
427
+ }
428
+ execute(name, args, signal) {
429
+ const control = {
430
+ ...this.control,
431
+ signal: signal === void 0 ? this.control.signal : AbortSignal.any([this.control.signal, signal])
432
+ };
433
+ const result = this.pending.then(async () => {
434
+ control.signal.throwIfAborted();
435
+ await this.boundary();
436
+ control.signal.throwIfAborted();
437
+ requireDream(!this.finished, "Dream 已结束。");
438
+ const value = await this.dispatch(name, args, control);
439
+ if ([
440
+ "read_claim",
441
+ "read_trace",
442
+ "file_read",
443
+ "file_glob",
444
+ "file_grep"
445
+ ].includes(name)) {
446
+ this.progress.exploration_receipts += 1;
447
+ await this.save();
448
+ }
449
+ return value;
450
+ });
451
+ this.pending = result.catch(() => {});
452
+ return result;
453
+ }
454
+ async dispatch(name, args, control) {
455
+ if (this.wrappingUp) requireDream(![
456
+ "dream_record_candidates",
457
+ "file_read",
458
+ "file_glob",
459
+ "file_grep",
460
+ "read_trace",
461
+ "dream_review_sync"
462
+ ].includes(name), "已进入有限收尾;不能展开新探索,请处理已有候选或调用 dream_finish。");
463
+ if (name === "dream_record_candidates") {
464
+ const input = DreamTools[name].parse(args);
465
+ this.register(input.candidates);
466
+ await this.save();
467
+ } else if (name === "read_claim") {
468
+ const { id } = DreamTools[name].parse(args);
469
+ const claim = this.claims.find((claim) => claim.id === id);
470
+ requireDream(claim !== void 0, "只可读取本轮冻结的自有 Claim。");
471
+ const current = (await this.knowledge.snapshot()).claims.find((value) => value.id === id);
472
+ requireDream(current !== void 0 && sameClaim(current, claim), "Claim 已被外部修改,本轮请保留该项。");
473
+ if (!this.progress.autonomy?.read_ids.includes(id)) this.progress.autonomy?.read_ids.push(id);
474
+ await this.save();
475
+ return claim;
476
+ } else if (name === "read_trace") {
477
+ const input = DreamTools[name].parse(args);
478
+ if (input.claim_id !== void 0) requireDream(this.readable().some((claim) => claim.id === input.claim_id), "请先 read_claim 读取本轮自有 Claim,再查询其 Trace。");
479
+ if (input.claim_id !== void 0 && input.trace_id === void 0) return {
480
+ ...await this.knowledge.listTraces({
481
+ claimId: input.claim_id,
482
+ offset: input.offset,
483
+ limit: Math.min(input.limit ?? 20, 100)
484
+ }),
485
+ independent_evidence: false
486
+ };
487
+ const id = input.trace_id ?? input.id;
488
+ requireDream(id !== void 0, "读取 Trace 正文需要 trace_id。");
489
+ const trace = await new TraceStore(this.knowledge.context()).read(id);
490
+ requireDream(trace !== null && trace.agent === this.knowledge.agentId && [...trace.input_claims, ...trace.output_claims].some((id) => input.claim_id === void 0 ? this.readable().some((claim) => claim.id === id) : id === input.claim_id), "只可读取本轮已读 Claim 关联的本地自身 Trace。");
491
+ const limit = input.limit ?? 4e3;
492
+ const chars = Array.from(JSON.stringify(trace));
493
+ const end = Math.min(chars.length, input.offset + limit);
494
+ return {
495
+ content: chars.slice(input.offset, end).join(""),
496
+ total_chars: chars.length,
497
+ truncated: input.offset > 0 || end < chars.length,
498
+ next_offset: end < chars.length ? end : null,
499
+ independent_evidence: false
500
+ };
501
+ } else if (name === "file_read" || name === "file_glob" || name === "file_grep") {
502
+ const entry = name === "file_read" ? this.current() : void 0;
503
+ const original = await this.knowledge.dreamStore().origin(this.job.id);
504
+ const eligible = entry === void 0 ? (original?.claims ?? []).filter((claim) => claim.confidence !== "high" && claim.status !== "deprecated") : this.readable().filter((claim) => entry.candidate.claim_ids.includes(claim.id) && original?.claims.some((input) => input.id === claim.id && input.confidence !== "high") && claim.status !== "deprecated");
505
+ const evidence = new EvidenceStore(this.knowledge.context(), this.job.id, entry?.candidate.group_id ?? "_discovery");
506
+ await evidence.initialize(this.workspace, eligible, this.knowledge.config.dream, control.signal);
507
+ await evidence.reopen(control.signal);
508
+ return evidence.execute(name === "file_read" ? "read" : name === "file_glob" ? "glob" : "grep", DreamTools[name].parse(args), eligible, control.signal);
509
+ } else if (name === "dream_stage_group") {
510
+ const input = DreamTools[name].parse(args);
511
+ if (input.group !== null) {
512
+ this.progress.proposal_attempted = true;
513
+ await this.save();
514
+ }
515
+ if (input.group === null) {
516
+ const entry = this.current(input.group_id);
517
+ entry.draft = null;
518
+ entry.validation = null;
519
+ entry.review = null;
520
+ await this.save();
521
+ } else {
522
+ const group = expandDraft(input.group, this.readable());
523
+ const receipts = z.record(z.string(), z.json()).parse((await new EvidenceStore(this.knowledge.context(), this.job.id, input.group_id).read())?.receipts ?? {});
524
+ prepareGroup(group, this.readable(), this.knowledge.context().agentId, void 0, {
525
+ enabled: this.knowledge.config.dream.evidenceCalibration,
526
+ receipts,
527
+ semanticReview: true
528
+ });
529
+ if (!this.progress.entries.some((entry) => entry.status === "pending" && entry.candidate.group_id === input.group_id)) {
530
+ requireDream(!this.wrappingUp, "收尾阶段不能新增候选。");
531
+ requireDream(!this.progress.entries.some((entry) => entry.status === "pending"), "先处理当前候选。");
532
+ this.register([{
533
+ group_id: input.group_id,
534
+ claim_ids: input.group.operations.map((op) => op.id),
535
+ kind: input.group.kind,
536
+ reason: input.group.reason
537
+ }]);
538
+ }
539
+ const entry = this.current(input.group_id);
540
+ requireDream(input.group.kind === entry.candidate.kind && sameIds(input.group.operations.map((op) => op.id), entry.candidate.claim_ids), "草稿必须包含当前候选全部且仅这些 ID 与 kind。");
541
+ entry.draft = group;
542
+ entry.validation = null;
543
+ entry.review = null;
544
+ await this.save();
545
+ }
546
+ } else if (name === "dream_validate") {
547
+ const input = DreamTools[name].parse(args);
548
+ const entry = this.current(input.group_id);
549
+ requireDream(entry.draft !== null, "请先暂存完整草稿。");
550
+ requireDream(entry.draft.kind === entry.candidate.kind && sameIds(entry.draft.updates.map((claim) => claim.id), entry.candidate.claim_ids), "候选已细化,请保留原编辑并补齐当前候选的完整草稿后再 validate。");
551
+ const receipts = z.record(z.string(), z.json()).parse((await new EvidenceStore(this.knowledge.context(), this.job.id, input.group_id).read())?.receipts ?? {});
552
+ prepareGroup(entry.draft, this.readable(), this.knowledge.context().agentId, void 0, {
553
+ enabled: this.knowledge.config.dream.evidenceCalibration,
554
+ receipts,
555
+ semanticReview: true
556
+ });
557
+ entry.validation = reviewInput(input.group_id, entry.draft, this.readable(), receipts);
558
+ await this.save();
559
+ return entry.validation;
560
+ } else if (name === "dream_apply_group") {
561
+ const input = DreamTools[name].parse(args);
562
+ const entry = this.current(input.group_id);
563
+ requireDream(entry.draft !== null && entry.validation !== null && input.validation_id === entry.validation.validation_id, "缺少当前草稿版本的 validate,请重新校验。");
564
+ const evidence = new EvidenceStore(this.knowledge.context(), this.job.id, input.group_id);
565
+ if (await evidence.read() !== null) await evidence.complete(control.signal);
566
+ const checkpoint = await this.knowledge.applyDreamGroup(this.job.id, input.group_id, entry.draft, entry.validation, input.review, null, control);
567
+ control.committed?.();
568
+ entry.status = checkpoint.groups.some((group) => group.skipped) ? "skipped" : "executed";
569
+ entry.reason = entry.status === "executed" ? "已按逐 Claim 语义复核提交。" : "外部版本或证据变化,未继续旧修改。";
570
+ entry.review = {
571
+ decision: "apply",
572
+ reason: entry.reason,
573
+ reason_kind: "useful_knowledge",
574
+ semantic: input.review,
575
+ self_review: null
576
+ };
577
+ if (entry.status === "executed") for (const after of checkpoint.groups.flatMap((group) => group.after)) {
578
+ const index = this.claims.findIndex((claim) => claim.id === after.id);
579
+ if (index >= 0) this.claims[index] = after;
580
+ }
581
+ await this.save();
582
+ return {
583
+ executed: entry.status === "executed",
584
+ candidate_progress: this.candidateProgress(),
585
+ changes: checkpoint.groups
586
+ };
587
+ } else if (name === "dream_keep_candidate") {
588
+ const input = DreamTools[name].parse(args);
589
+ const entry = this.current(input.group_id);
590
+ requireDream(input.reason_kind !== "no_consolidation_benefit" || entry.candidate.kind === "consolidation", "no_consolidation_benefit 仅适用于 C。");
591
+ entry.status = "kept";
592
+ entry.reason = `${input.reason_kind}: ${input.reason}`;
593
+ entry.draft = null;
594
+ entry.validation = null;
595
+ await this.save();
596
+ } else if (name === "dream_read_draft") {
597
+ const input = DreamTools[name].parse(args);
598
+ return {
599
+ candidate_progress: this.candidateProgress(),
600
+ drafts: this.progress.entries.filter((entry) => input.group_id === void 0 ? entry.status === "pending" : entry.candidate.group_id === input.group_id),
601
+ budget: this.progress.autonomy
602
+ };
603
+ } else if (name === "dream_read_history") {
604
+ const input = DreamTools[name].parse(args);
605
+ const records = await this.knowledge.dreamStore().records(this.job.id);
606
+ return {
607
+ records: records.slice(input.offset, input.offset + input.limit).map(({ checkpoint }) => checkpoint),
608
+ total: records.length
609
+ };
610
+ } else if (name === "dream_review_sync") {
611
+ const input = DreamTools[name].parse(args);
612
+ const sync = new DreamSync(this.knowledge.context(), true);
613
+ const validation = await sync.prepare(input.source_id, input.carrier_ids, control.signal);
614
+ if (input.review === void 0) return validation;
615
+ requireDream(input.validation_id === validation.validation_id, "同步依赖版本已变化,请重新读取并复核。");
616
+ await sync.apply(this.job.id, validation, input.review, control.signal);
617
+ return { synchronized: input.source_id };
618
+ } else if (name === "dream_finish") return this.finish(DreamTools[name].parse(args).review, control);
619
+ return {
620
+ candidate_progress: this.candidateProgress(),
621
+ budget: this.progress.autonomy
622
+ };
623
+ }
624
+ };
625
+ //#endregion
626
+ //#region src/dream/service.ts
627
+ const SummarySchema = z.strictObject({
628
+ checked: z.string(),
629
+ findings: z.string(),
630
+ uncertainties: z.string(),
631
+ next_steps: z.string()
632
+ });
633
+ var AcnDream = class {
634
+ knowledge;
635
+ backend;
636
+ render;
637
+ beforeCall;
638
+ options;
639
+ unregister;
640
+ timers = /* @__PURE__ */ new Set();
641
+ eligibilityRetry;
642
+ pending = Promise.resolve();
643
+ stopped = false;
644
+ closed = false;
645
+ active;
646
+ constructor(knowledge, backend, render, beforeCall, options = {}) {
647
+ this.knowledge = knowledge;
648
+ this.backend = backend;
649
+ this.render = render;
650
+ this.beforeCall = beforeCall;
651
+ this.options = options;
652
+ const worker = knowledge.jobs;
653
+ if (worker === null) throw new JobError("unconfigured", "请先配置 agentId。");
654
+ this.unregister = knowledge.config.dream.enabled ? worker.register("dream", async (job, control) => {
655
+ const run = this.run(job, control);
656
+ this.active = run;
657
+ try {
658
+ return await run;
659
+ } finally {
660
+ if (this.active === run) this.active = void 0;
661
+ }
662
+ }) : () => {};
663
+ }
664
+ async start() {
665
+ const worker = this.knowledge.jobs;
666
+ if (worker === null) return;
667
+ if (!this.knowledge.config.dream.enabled) {
668
+ await worker.queue.pauseDream(true);
669
+ return;
670
+ }
671
+ await worker.queue.pauseDream(false);
672
+ worker.wake(true);
673
+ await this.check();
674
+ this.schedule();
675
+ }
676
+ schedule() {
677
+ const deadline = Date.now() + this.knowledge.config.dream.checkIntervalHours * 36e5;
678
+ const wait = () => {
679
+ if (this.closed) return;
680
+ const remaining = deadline - Date.now();
681
+ if (remaining > 0) {
682
+ const timer = setTimeout(() => {
683
+ this.timers.delete(timer);
684
+ wait();
685
+ }, Math.min(remaining, 2147483647));
686
+ timer.unref();
687
+ this.timers.add(timer);
688
+ } else {
689
+ this.trigger();
690
+ this.schedule();
691
+ }
692
+ };
693
+ wait();
694
+ }
695
+ trigger() {
696
+ this.pending = this.pending.then(() => this.check()).catch(() => {
697
+ this.knowledge.logger.warn("Dream eligibility check could not complete; the next trigger will retry.");
698
+ });
699
+ }
700
+ async flush() {
701
+ await this.pending;
702
+ }
703
+ async check() {
704
+ if (this.closed || this.stopped || !this.knowledge.config.dream.enabled) return;
705
+ const worker = this.knowledge.jobs;
706
+ if (worker === null || (await worker.queue.list()).some((job) => job.kind === "dream" && (job.state === "queued" || job.state === "running"))) return;
707
+ const eligible = await this.eligible(false);
708
+ if (this.closed || this.stopped) return;
709
+ if (eligible === null) {
710
+ if (this.eligibilityRetry === void 0) {
711
+ const timer = setTimeout(() => {
712
+ this.timers.delete(timer);
713
+ this.eligibilityRetry = void 0;
714
+ this.trigger();
715
+ }, 1e3);
716
+ timer.unref();
717
+ this.timers.add(timer);
718
+ this.eligibilityRetry = timer;
719
+ }
720
+ } else if (eligible) await worker.enqueue("dream", {
721
+ manual: false,
722
+ workspace_root: await this.workspace()
723
+ });
724
+ }
725
+ async eligible(manual) {
726
+ try {
727
+ const snapshot = await this.knowledge.snapshot(void 0, 0);
728
+ return dreamEligible(this.knowledge.config.dream, await this.knowledge.dreamStore().state(), snapshot.claims, this.knowledge.context().agentId, manual);
729
+ } catch (error) {
730
+ if (error instanceof KnowledgeBusy || error instanceof LockTimeoutError) return null;
731
+ throw error;
732
+ }
733
+ }
734
+ async workspace(input) {
735
+ return fs.realpath(input ?? await this.options.workspace?.() ?? process.cwd());
736
+ }
737
+ async request(workspace, sessionId) {
738
+ if (!this.knowledge.config.dream.enabled) throw new JobError("disabled", "Dream 已关闭,请先启用 dream.enabled。");
739
+ const worker = this.knowledge.jobs;
740
+ if (worker === null) throw new JobError("unconfigured", "请先配置 agentId。");
741
+ this.stopped = false;
742
+ const pending = await worker.queue.pauseDream(false);
743
+ worker.wake(true);
744
+ if (pending[0] !== void 0) return pending[0];
745
+ if (await this.eligible(true) === false) throw new JobError("empty", "没有可整理的自身 active/stale Claim。");
746
+ return worker.enqueue("dream", {
747
+ manual: true,
748
+ workspace_root: await this.workspace(workspace)
749
+ }, sessionId);
750
+ }
751
+ async stop() {
752
+ this.stopped = true;
753
+ if (this.eligibilityRetry !== void 0) {
754
+ clearTimeout(this.eligibilityRetry);
755
+ this.timers.delete(this.eligibilityRetry);
756
+ this.eligibilityRetry = void 0;
757
+ }
758
+ const worker = this.knowledge.jobs;
759
+ if (worker === null) return 0;
760
+ const jobs = await worker.queue.pauseDream(true);
761
+ worker.cancelDream(new DreamStopped());
762
+ return jobs.length;
763
+ }
764
+ async boundary(job, control) {
765
+ control.signal.throwIfAborted();
766
+ const jobs = await this.knowledge.jobs?.queue.list() ?? [];
767
+ if (jobs.some((current) => current.id === job.id && current.payload["paused"] === true)) throw new DreamStopped();
768
+ if (jobs.some((job) => this.knowledge.jobs?.canRun(job) && jobPriority[job.kind] < jobPriority.dream)) throw new DreamYield();
769
+ }
770
+ async call(job, control, phase, data, schema, parse = (value) => value, systemName = "claim_dream_legacy.j2") {
771
+ await this.boundary(job, control);
772
+ await this.beforeCall?.();
773
+ const route = await resolveRoute(this.knowledge.config.llm, this.knowledge.context());
774
+ return structuredCall({
775
+ backend: this.backend,
776
+ context: this.knowledge.context(),
777
+ config: this.knowledge.config.llm,
778
+ route,
779
+ jobId: job.id,
780
+ phase,
781
+ system: this.render(systemName, {}),
782
+ input: JSON.stringify({
783
+ phase,
784
+ ...data
785
+ }),
786
+ schema,
787
+ parse: (value) => parse(schema.parse(value)),
788
+ signal: control.signal
789
+ });
790
+ }
791
+ async run(job, control) {
792
+ const store = this.knowledge.dreamStore();
793
+ await store.recover();
794
+ await this.boundary(job, control);
795
+ let origin = await store.origin(job.id);
796
+ if (origin === null) {
797
+ const claims = (await this.knowledge.dreamSnapshot(control.signal)).filter((claim) => claim.holder === this.knowledge.agentId);
798
+ if (!dreamEligible(this.knowledge.config.dream, await store.state(), claims, this.knowledge.context().agentId, job.payload["manual"] === true)) return { skipped: "not_eligible" };
799
+ const input = claimInput(claims.filter((claim) => claim.status !== "deprecated"));
800
+ origin = {
801
+ snapshot_at: nowSeconds(),
802
+ claims,
803
+ coverage: input.coverage,
804
+ workspace_root: await this.workspace(typeof job.payload["workspace_root"] === "string" ? job.payload["workspace_root"] : void 0)
805
+ };
806
+ await store.saveOrigin(job.id, origin);
807
+ }
808
+ if (this.options.run !== void 0) {
809
+ const session = await DreamSession.create(this.knowledge, job, control, () => this.boundary(job, control));
810
+ if (!session.finished) {
811
+ await this.beforeCall?.();
812
+ await this.options.run({
813
+ session,
814
+ route: await resolveRoute(this.knowledge.config.llm, this.knowledge.context()),
815
+ config: this.knowledge.config.llm,
816
+ system: this.render("claim_dream.j2", {}),
817
+ signal: control.signal
818
+ });
819
+ requireDream(session.finished, "自主 Dream 尚未完成。");
820
+ }
821
+ await new UploadDelivery(this.knowledge.context(), this.knowledge.team).deliver(control.signal);
822
+ return {
823
+ updatedClaimIds: [...new Set((await store.records(job.id)).flatMap(({ checkpoint }) => Object.keys(checkpoint.self_versions)))],
824
+ modelSteps: session.progress.autonomy?.steps ?? 0,
825
+ wrapUpSteps: session.progress.autonomy?.wrap_up?.steps ?? 0,
826
+ budgetLimited: session.exhausted,
827
+ incompleteCandidates: session.progress.entries.filter((entry) => entry.status === "skipped").map((entry) => ({
828
+ groupId: entry.candidate.group_id,
829
+ claimIds: entry.candidate.claim_ids,
830
+ reason: entry.reason ?? ""
831
+ })),
832
+ report: "Dream report.md 已保存。"
833
+ };
834
+ }
835
+ const loaded = claimInput(origin.claims.filter((claim) => claim.status !== "deprecated")).loaded;
836
+ const evidenceEnabled = this.knowledge.config.dream.evidenceCalibration && this.options.explore !== void 0 && origin.workspace_root !== void 0;
837
+ let progress = await store.progress(job.id);
838
+ if (progress === null) {
839
+ const discovery = await this.call(job, control, "candidates", {
840
+ dream_context: {
841
+ agent_id: this.knowledge.agentId,
842
+ snapshot_at: origin.snapshot_at,
843
+ trigger: job.payload["manual"] === true ? "manual" : "automatic"
844
+ },
845
+ claims: loaded,
846
+ coverage: origin.coverage,
847
+ policy_context: {
848
+ available: false,
849
+ complete: false
850
+ },
851
+ pending_consolidation_sync: (await new UploadStore(this.knowledge.context()).read()).consolidations ?? [],
852
+ evidence_calibration: {
853
+ available: evidenceEnabled,
854
+ tools: evidenceEnabled ? [
855
+ "read",
856
+ "grep",
857
+ "glob",
858
+ "claim(list/read)"
859
+ ] : [],
860
+ high_excluded: true
861
+ }
862
+ }, DiscoverySchema, (value) => {
863
+ validateCandidates(value.candidates, loaded, this.knowledge.context().agentId, evidenceEnabled);
864
+ requireDream(new Set(value.sync_candidates.map((item) => item.source_id)).size === value.sync_candidates.length, "同步候选来源不能重复。");
865
+ return value;
866
+ });
867
+ progress = ProgressSchema.parse({
868
+ schemaVersion: 1,
869
+ discovery,
870
+ entries: discovery.candidates.map((candidate) => ({
871
+ candidate,
872
+ status: "pending",
873
+ reason: "",
874
+ draft: null,
875
+ validation: null,
876
+ review: null
877
+ })),
878
+ syncCompleted: [],
879
+ finished: false,
880
+ summary: null
881
+ });
882
+ await store.saveProgress(job.id, progress);
883
+ }
884
+ await this.compact(job, control, progress);
885
+ for (const entry of progress.entries) {
886
+ if (entry.status !== "pending") continue;
887
+ await this.boundary(job, control);
888
+ const previous = (await store.records(job.id)).find((record) => record.checkpoint.operation?.group_id === entry.candidate.group_id);
889
+ if (previous?.checkpoint.applied) {
890
+ entry.status = previous.checkpoint.groups.some((group) => group.skipped) ? "skipped" : "executed";
891
+ entry.reason = entry.status === "skipped" ? "外部版本变化,旧方案未继续。" : "从已持久执行回执恢复,未重放模型。";
892
+ await store.saveProgress(job.id, progress);
893
+ continue;
894
+ }
895
+ const before = loaded.filter((claim) => entry.candidate.claim_ids.includes(claim.id));
896
+ const current = (await this.knowledge.snapshot()).claims;
897
+ if (!before.every((claim) => current.some((value) => sameClaim(value, claim)))) {
898
+ entry.status = "skipped";
899
+ entry.reason = "分析后 Claim 已被外部修改,本候选保留当前版本。";
900
+ await store.saveProgress(job.id, progress);
901
+ continue;
902
+ }
903
+ let receipts = {};
904
+ let evidenceStore;
905
+ if (entry.candidate.kind === "evidence") {
906
+ if (!evidenceEnabled || origin.workspace_root === void 0 || this.options.explore === void 0) {
907
+ entry.status = "kept";
908
+ entry.reason = "证据校准已关闭或受限子会话不可用,保持原样。";
909
+ await store.saveProgress(job.id, progress);
910
+ continue;
911
+ }
912
+ const evidence = new EvidenceStore(this.knowledge.context(), job.id, entry.candidate.group_id);
913
+ evidenceStore = evidence;
914
+ let manifest = await evidence.initialize(origin.workspace_root, before, this.knowledge.config.dream, control.signal);
915
+ if (!await evidence.current(manifest)) {
916
+ entry.status = "skipped";
917
+ entry.reason = "查证文件版本已变化,本组保持原样;不会重用旧证据授权。";
918
+ await store.saveProgress(job.id, progress);
919
+ continue;
920
+ }
921
+ if (!manifest.completed) {
922
+ await this.boundary(job, control);
923
+ await this.beforeCall?.();
924
+ await this.options.explore({
925
+ store: evidence,
926
+ claims: before,
927
+ route: await resolveRoute(this.knowledge.config.llm, this.knowledge.context()),
928
+ config: this.knowledge.config.llm,
929
+ signal: control.signal
930
+ });
931
+ await this.boundary(job, control);
932
+ await evidence.complete(control.signal);
933
+ manifest = await evidence.read() ?? manifest;
934
+ }
935
+ receipts = z.record(z.string(), z.json()).parse(manifest.receipts);
936
+ if (manifest.model_steps >= manifest.limits.steps && Object.keys(receipts).length === 0) {
937
+ entry.status = "kept";
938
+ entry.reason = "查证模型轮数已耗尽且未取得直接证据,保持原样。";
939
+ await store.saveProgress(job.id, progress);
940
+ continue;
941
+ }
942
+ }
943
+ let repairs = 0;
944
+ while (entry.status === "pending") {
945
+ await this.boundary(job, control);
946
+ if (entry.validation !== null) try {
947
+ validateEvidencePreservation(entry.validation.input);
948
+ } catch (error) {
949
+ if (!(error instanceof DreamValidationError)) throw error;
950
+ entry.reason = error.message;
951
+ entry.draft = null;
952
+ entry.validation = null;
953
+ entry.review = null;
954
+ await store.saveProgress(job.id, progress);
955
+ }
956
+ if (evidenceStore !== void 0) {
957
+ const manifest = await evidenceStore.read();
958
+ requireDream(manifest !== null, "查证清单丢失。");
959
+ if (!await evidenceStore.current(manifest)) {
960
+ entry.status = "skipped";
961
+ entry.reason = "查证材料已改变;不复用旧验证或复核授权。";
962
+ await store.saveProgress(job.id, progress);
963
+ break;
964
+ }
965
+ }
966
+ if (entry.draft === null || entry.validation === null) {
967
+ const proposed = await this.call(job, control, "draft", {
968
+ candidate: entry.candidate,
969
+ before,
970
+ evidence: receipts,
971
+ coverage: origin.coverage,
972
+ review_summary: progress.discovery.review,
973
+ prior_feedback: entry.reason,
974
+ prior_summary: progress.summary
975
+ }, DraftResponseSchema, (value) => {
976
+ if (value.action === "keep") {
977
+ requireDream(value.reason_kind !== "no_consolidation_benefit" || entry.candidate.kind === "consolidation", "no_consolidation_benefit 仅用于整合。");
978
+ return value;
979
+ }
980
+ requireDream(value.group.kind === entry.candidate.kind && sameIds(value.group.operations.map((operation) => operation.id), entry.candidate.claim_ids), "草稿必须处理当前候选的全部且仅这些 ID 与 kind。");
981
+ prepareGroup(expandDraft(value.group, before), loaded, this.knowledge.context().agentId, nowSeconds(), {
982
+ enabled: evidenceEnabled,
983
+ receipts
984
+ });
985
+ return value;
986
+ });
987
+ await store.archive(job.id, `${entry.candidate.group_id}-draft-${repairs}`, proposed);
988
+ if (proposed.action === "keep") {
989
+ entry.status = "kept";
990
+ entry.reason = `${proposed.reason_kind}: ${proposed.reason}`;
991
+ await store.saveProgress(job.id, progress);
992
+ break;
993
+ }
994
+ entry.draft = expandDraft(proposed.group, before);
995
+ entry.validation = reviewInput(entry.candidate.group_id, entry.draft, before, receipts);
996
+ entry.review = null;
997
+ await store.saveProgress(job.id, progress);
998
+ }
999
+ const validation = entry.validation;
1000
+ const reviewed = await this.call(job, control, "review", {
1001
+ candidate: entry.candidate,
1002
+ validation,
1003
+ draft: entry.draft,
1004
+ before,
1005
+ review_summary: progress.discovery.review,
1006
+ prior_feedback: entry.reason,
1007
+ prior_summary: progress.summary
1008
+ }, ReviewResponseSchema, (value) => {
1009
+ if (value.decision !== "apply") return value;
1010
+ requireDream(value.semantic !== null && value.self_review !== null, "执行前必须同时给出逐 Claim 语义复核与双向全文引用复核。");
1011
+ validateSelfReview(validation, value.self_review);
1012
+ validateSemanticReview(validation, value.semantic);
1013
+ return value;
1014
+ });
1015
+ entry.review = reviewed;
1016
+ await store.saveProgress(job.id, progress);
1017
+ if (reviewed.decision === "keep") {
1018
+ entry.status = "kept";
1019
+ entry.reason = `${reviewed.reason_kind}: ${reviewed.reason}`;
1020
+ await store.saveProgress(job.id, progress);
1021
+ break;
1022
+ }
1023
+ if (reviewed.decision === "repair") {
1024
+ repairs += 1;
1025
+ entry.reason = reviewed.reason;
1026
+ entry.draft = null;
1027
+ entry.validation = null;
1028
+ await store.saveProgress(job.id, progress);
1029
+ if (repairs >= this.knowledge.config.llm.structuredRetries) throw new JobError("dream_repair", "本组多次复核要求修复,已保留候选与草稿反馈;请检查报告后重试。");
1030
+ continue;
1031
+ }
1032
+ requireDream(reviewed.semantic !== null && reviewed.self_review !== null, "缺少复核。");
1033
+ await this.boundary(job, control);
1034
+ const record = await this.knowledge.applyDreamGroup(job.id, entry.candidate.group_id, entry.draft, validation, reviewed.semantic, reviewed.self_review, control);
1035
+ control.committed?.();
1036
+ entry.status = record.groups.some((group) => group.skipped) ? "skipped" : "executed";
1037
+ entry.reason = entry.status === "skipped" ? "外部版本或证据版本变化,或来源环冲突;已生效结果保留。" : reviewed.reason;
1038
+ await store.saveProgress(job.id, progress);
1039
+ }
1040
+ await this.compact(job, control, progress);
1041
+ }
1042
+ for (const candidate of progress.discovery.sync_candidates) if (!progress.syncCompleted.includes(candidate.source_id)) {
1043
+ await this.boundary(job, control);
1044
+ const sync = new DreamSync(this.knowledge.context());
1045
+ if (await sync.resume(job.id, candidate.source_id, control.signal)) {
1046
+ progress.syncCompleted.push(candidate.source_id);
1047
+ await store.saveProgress(job.id, progress);
1048
+ continue;
1049
+ }
1050
+ const validation = await sync.prepare(candidate.source_id, candidate.carrier_ids);
1051
+ const review = await this.call(job, control, "sync_review", {
1052
+ validation,
1053
+ reason: candidate.reason,
1054
+ note: "只确认完整信息承接,不修改 Claim,不纠正事实。"
1055
+ }, SemanticReviewSchema);
1056
+ await sync.apply(job.id, validation, review, control.signal);
1057
+ progress.syncCompleted.push(candidate.source_id);
1058
+ await store.saveProgress(job.id, progress);
1059
+ }
1060
+ await this.boundary(job, control);
1061
+ const final = await store.finish(job.id, progress, control);
1062
+ control.committed?.();
1063
+ progress.finished = true;
1064
+ await store.saveProgress(job.id, progress);
1065
+ await new UploadDelivery(this.knowledge.context(), this.knowledge.team).deliver(control.signal);
1066
+ return {
1067
+ updatedClaimIds: Object.keys(final.self_versions),
1068
+ report: "Dream report.md 已保存。",
1069
+ skipped: progress.entries.filter((entry) => entry.status === "skipped").map((entry) => entry.candidate.group_id),
1070
+ kept: progress.entries.filter((entry) => entry.status === "kept").map((entry) => entry.candidate.group_id)
1071
+ };
1072
+ }
1073
+ async compact(job, control, progress) {
1074
+ const handled = progress.entries.filter((entry) => entry.status !== "pending");
1075
+ const history = handled.slice(progress.compactedThrough);
1076
+ if (conservativeTokens(JSON.stringify(history)) < 64e3 / 2) return;
1077
+ await this.knowledge.dreamStore().archive(job.id, `context-${history.length}`, history);
1078
+ const previews = history.map((entry) => ({
1079
+ group_id: entry.candidate.group_id,
1080
+ status: entry.status,
1081
+ validation_id: entry.validation?.validation_id,
1082
+ preview: Array.from(entry.reason).slice(0, 400).join(""),
1083
+ preview_truncated: Array.from(entry.reason).length > 400
1084
+ }));
1085
+ progress.summary = await this.call(job, control, "compaction", {
1086
+ prior_summary: progress.summary,
1087
+ history: previews
1088
+ }, SummarySchema, (value) => {
1089
+ requireDream(Object.values(value).reduce((sum, value) => sum + Array.from(value).length, 0) <= 12e3, "压缩摘要超过 12000 字符。");
1090
+ return value;
1091
+ }, "dream_compaction.j2");
1092
+ progress.compactedThrough = handled.length;
1093
+ await this.knowledge.dreamStore().saveProgress(job.id, progress);
1094
+ }
1095
+ async close() {
1096
+ this.closed = true;
1097
+ this.unregister();
1098
+ this.knowledge.jobs?.cancelDream();
1099
+ for (const timer of this.timers) clearTimeout(timer);
1100
+ this.timers.clear();
1101
+ await this.pending;
1102
+ await this.active?.catch(() => {});
1103
+ }
1104
+ };
1105
+ //#endregion
1106
+ export { SyncValidationSchema as a, DreamSync as i, DreamTools as n, isDreamTool as r, AcnDream as t };