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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/LICENSE-APACHE +201 -0
  3. package/LICENSE-MIT +19 -0
  4. package/README.md +55 -2
  5. package/README_EN.md +56 -0
  6. package/cordis.patch.yml +29 -0
  7. package/docs/acn-compat.md +33 -0
  8. package/docs/architecture.md +129 -0
  9. package/docs/assets/activity-view.png +0 -0
  10. package/docs/assets/install-package.png +0 -0
  11. package/docs/assets/knowledge-model.png +0 -0
  12. package/docs/assets/knowledge-view.png +0 -0
  13. package/docs/assets/personal-configuration.png +0 -0
  14. package/docs/assets/session-upstream.png +0 -0
  15. package/docs/assets/upstream-settings.png +0 -0
  16. package/docs/assets/upstream-team.png +0 -0
  17. package/docs/command-reference.md +201 -0
  18. package/docs/config.md +243 -0
  19. package/docs/development.md +197 -0
  20. package/docs/dsh-compat.md +59 -0
  21. package/docs/index.md +16 -0
  22. package/docs/outstanding-issues.md +61 -0
  23. package/docs/user_guide.md +183 -0
  24. package/icon.svg +8 -0
  25. package/lib/activities-LRoCwpzw.js +327 -0
  26. package/lib/alignment-CwH0nBf-.js +80 -0
  27. package/lib/auth-DFI9yowX.js +71 -0
  28. package/lib/checkpoint-Bmt8q2vB.js +188 -0
  29. package/lib/checkpoint-RgcdqifN.js +318 -0
  30. package/lib/claim-DOAGe8ZK.js +168 -0
  31. package/lib/client.js +18420 -0
  32. package/lib/deliver-BuYQaPRW.js +168 -0
  33. package/lib/delivery-status-D5m3178s.js +87 -0
  34. package/lib/dispute-CtrInHzf.js +20 -0
  35. package/lib/disputes-ByEmi43j.js +51 -0
  36. package/lib/dream-agent-DBszTHXY.js +249 -0
  37. package/lib/dream.js +4 -0
  38. package/lib/effects-DJ4Xa7Tx.js +268 -0
  39. package/lib/errors-Bp_2WXBr.js +19 -0
  40. package/lib/errors-pPumDOGD.js +18 -0
  41. package/lib/evidence-store-DLFvSuNa.js +1030 -0
  42. package/lib/formation-D4LO31WW.js +187 -0
  43. package/lib/formation-replay-CEOy5FkI.js +87 -0
  44. package/lib/formation.js +9 -0
  45. package/lib/inbox-2CugZZQm.js +188 -0
  46. package/lib/inbox-DFtE2fOp.js +71 -0
  47. package/lib/inbox.js +3 -0
  48. package/lib/index.js +1377 -0
  49. package/lib/lock-DbmlKOoX.js +332 -0
  50. package/lib/pages-BEWC3kmZ.js +51 -0
  51. package/lib/paths-CDYV5UH9.js +154 -0
  52. package/lib/plugins/commands.js +590 -0
  53. package/lib/plugins/dream.js +66 -0
  54. package/lib/plugins/formation.js +66 -0
  55. package/lib/plugins/inbox.js +53 -0
  56. package/lib/plugins/knowledge.js +1111 -0
  57. package/lib/plugins/prompt.js +102 -0
  58. package/lib/plugins/tools.js +280 -0
  59. package/lib/policy-DnyHh7Bl.js +16 -0
  60. package/lib/prepare-DwHZudbA.js +134 -0
  61. package/lib/presentation-BlLjgDjP.js +47 -0
  62. package/lib/protocol.js +8 -0
  63. package/lib/queue-M917xHPS.js +153 -0
  64. package/lib/regular-file-BFpqMoub.js +136 -0
  65. package/lib/render-CJaVcKKC.js +48 -0
  66. package/lib/reported-sets-DdEKdeVb.js +122 -0
  67. package/lib/revision-DeoL_IUN.js +11 -0
  68. package/lib/scheduler-MaUEbXr3.js +64 -0
  69. package/lib/service-B7AI5jds.js +344 -0
  70. package/lib/service-BcHV5mc7.js +305 -0
  71. package/lib/service-CNjqHCBR.js +505 -0
  72. package/lib/service-C_i3BzdP.js +1106 -0
  73. package/lib/session-binding-BQrOGhZI.js +151 -0
  74. package/lib/session-state-CYqUhC95.js +38 -0
  75. package/lib/sessions-C2xuPFQv.js +218 -0
  76. package/lib/store.js +16 -0
  77. package/lib/structured-lyQCK-Zk.js +452 -0
  78. package/lib/subagent-yJsFxHmH.js +9 -0
  79. package/lib/team-credentials-C9xHrPIi.js +579 -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 +71 -0
  85. package/lib/types/advanced-configuration.d.ts +11 -0
  86. package/lib/types/client/ActivityDetails.d.ts +18 -0
  87. package/lib/types/client/AdvancedPreferences.d.ts +8 -0
  88. package/lib/types/client/BlankCommandFeedback.d.ts +10 -0
  89. package/lib/types/client/ComposerMenu.d.ts +24 -0
  90. package/lib/types/client/ConfigurationPage.d.ts +11 -0
  91. package/lib/types/client/ConnectionCheckDialog.d.ts +12 -0
  92. package/lib/types/client/KnowledgeDetail.d.ts +6 -0
  93. package/lib/types/client/KnowledgeDirectoryField.d.ts +11 -0
  94. package/lib/types/client/KnowledgePanel.d.ts +12 -0
  95. package/lib/types/client/KnowledgeReference.d.ts +13 -0
  96. package/lib/types/client/SessionToolbar.d.ts +16 -0
  97. package/lib/types/client/SettingsToast.d.ts +3 -0
  98. package/lib/types/client/SourceSessionLink.d.ts +15 -0
  99. package/lib/types/client/TeamCredentialField.d.ts +16 -0
  100. package/lib/types/client/TeamSettingsPage.d.ts +30 -0
  101. package/lib/types/client/configuration-errors.d.ts +2 -0
  102. package/lib/types/client/interaction-styles.d.ts +1 -0
  103. package/lib/types/client/interaction-ui.d.ts +30 -0
  104. package/lib/types/client/knowledge-labels.d.ts +5 -0
  105. package/lib/types/client/locales.d.ts +51 -0
  106. package/lib/types/commands/claim.d.ts +4 -0
  107. package/lib/types/commands/import.d.ts +10 -0
  108. package/lib/types/commands/status.d.ts +5 -0
  109. package/lib/types/config.d.ts +122 -0
  110. package/lib/types/configuration.d.ts +259 -0
  111. package/lib/types/credentials.d.ts +65 -0
  112. package/lib/types/dream/audit.d.ts +4 -0
  113. package/lib/types/dream/autonomous.d.ts +185 -0
  114. package/lib/types/dream/candidates.d.ts +34 -0
  115. package/lib/types/dream/checkpoint.d.ts +35 -0
  116. package/lib/types/dream/evidence-files.d.ts +10 -0
  117. package/lib/types/dream/evidence-store.d.ts +103 -0
  118. package/lib/types/dream/evidence.d.ts +30 -0
  119. package/lib/types/dream/index.d.ts +10 -0
  120. package/lib/types/dream/plan.d.ts +18 -0
  121. package/lib/types/dream/preservation.d.ts +6 -0
  122. package/lib/types/dream/review.d.ts +10 -0
  123. package/lib/types/dream/schema.d.ts +1475 -0
  124. package/lib/types/dream/service.d.ts +56 -0
  125. package/lib/types/dream/sync.d.ts +147 -0
  126. package/lib/types/dsh-adapter/configuration-remote.d.ts +1 -0
  127. package/lib/types/dsh-adapter/configuration-service.d.ts +28 -0
  128. package/lib/types/dsh-adapter/dream-agent.d.ts +4 -0
  129. package/lib/types/dsh-adapter/dream-evidence.d.ts +3 -0
  130. package/lib/types/dsh-adapter/formation-archive.d.ts +3 -0
  131. package/lib/types/dsh-adapter/formation-replay.d.ts +5 -0
  132. package/lib/types/dsh-adapter/formation.d.ts +4 -0
  133. package/lib/types/dsh-adapter/interaction-service.d.ts +13 -0
  134. package/lib/types/dsh-adapter/knowledge-paths.d.ts +3 -0
  135. package/lib/types/dsh-adapter/llm.d.ts +10 -0
  136. package/lib/types/dsh-adapter/project-upstream.d.ts +4 -0
  137. package/lib/types/dsh-adapter/runtime-pool.d.ts +110 -0
  138. package/lib/types/dsh-adapter/session-binding.d.ts +43 -0
  139. package/lib/types/dsh-adapter/source-sessions.d.ts +3 -0
  140. package/lib/types/dsh-adapter/team-credentials.d.ts +5 -0
  141. package/lib/types/dsh-adapter/tool-schema.d.ts +4 -0
  142. package/lib/types/dsh-adapter/tools.d.ts +5 -0
  143. package/lib/types/formation/capture.d.ts +19 -0
  144. package/lib/types/formation/checkpoint.d.ts +136 -0
  145. package/lib/types/formation/index.d.ts +10 -0
  146. package/lib/types/formation/prepare.d.ts +16 -0
  147. package/lib/types/formation/schema.d.ts +45 -0
  148. package/lib/types/formation/service.d.ts +58 -0
  149. package/lib/types/formation/transcript.d.ts +75 -0
  150. package/lib/types/formation/triggers.d.ts +3 -0
  151. package/lib/types/inbox/cascade.d.ts +3 -0
  152. package/lib/types/inbox/effects.d.ts +275 -0
  153. package/lib/types/inbox/index.d.ts +5 -0
  154. package/lib/types/inbox/prepare.d.ts +380 -0
  155. package/lib/types/inbox/service.d.ts +26 -0
  156. package/lib/types/inbox/sync.d.ts +9 -0
  157. package/lib/types/index.d.ts +1 -0
  158. package/lib/types/interaction-messages.d.ts +69 -0
  159. package/lib/types/interaction.d.ts +550 -0
  160. package/lib/types/knowledge/alignment.d.ts +49 -0
  161. package/lib/types/knowledge/catalog.d.ts +5 -0
  162. package/lib/types/knowledge/changes.d.ts +32 -0
  163. package/lib/types/knowledge/disputes.d.ts +3 -0
  164. package/lib/types/knowledge/errors.d.ts +9 -0
  165. package/lib/types/knowledge/ordering.d.ts +7 -0
  166. package/lib/types/knowledge/pages.d.ts +7 -0
  167. package/lib/types/knowledge/safety.d.ts +2 -0
  168. package/lib/types/knowledge/service.d.ts +52 -0
  169. package/lib/types/knowledge/sessions.d.ts +59 -0
  170. package/lib/types/knowledge/sources.d.ts +2 -0
  171. package/lib/types/knowledge/timestamps.d.ts +1 -0
  172. package/lib/types/knowledge/types.d.ts +84 -0
  173. package/lib/types/llm/response.d.ts +1 -0
  174. package/lib/types/llm/structured.d.ts +27 -0
  175. package/lib/types/local-name.d.ts +1 -0
  176. package/lib/types/plugins/client.d.ts +9 -0
  177. package/lib/types/plugins/commands.d.ts +11 -0
  178. package/lib/types/plugins/configuration.d.ts +8 -0
  179. package/lib/types/plugins/dream.d.ts +16 -0
  180. package/lib/types/plugins/formation.d.ts +16 -0
  181. package/lib/types/plugins/inbox.d.ts +16 -0
  182. package/lib/types/plugins/knowledge.d.ts +19 -0
  183. package/lib/types/plugins/prompt.d.ts +17 -0
  184. package/lib/types/plugins/tools.d.ts +10 -0
  185. package/lib/types/prompt/render.d.ts +2 -0
  186. package/lib/types/protocol/arbitration.d.ts +154 -0
  187. package/lib/types/protocol/auth.d.ts +31 -0
  188. package/lib/types/protocol/claim.d.ts +36 -0
  189. package/lib/types/protocol/dispute.d.ts +17 -0
  190. package/lib/types/protocol/ids.d.ts +20 -0
  191. package/lib/types/protocol/inbox.d.ts +141 -0
  192. package/lib/types/protocol/index.d.ts +11 -0
  193. package/lib/types/protocol/policy.d.ts +21 -0
  194. package/lib/types/protocol/revision.d.ts +2 -0
  195. package/lib/types/protocol/router.d.ts +114 -0
  196. package/lib/types/protocol/schema.d.ts +4 -0
  197. package/lib/types/protocol/time.d.ts +5 -0
  198. package/lib/types/protocol/trace.d.ts +11 -0
  199. package/lib/types/store/atomic.d.ts +8 -0
  200. package/lib/types/store/claim-edits.d.ts +33 -0
  201. package/lib/types/store/claims.d.ts +7 -0
  202. package/lib/types/store/context.d.ts +13 -0
  203. package/lib/types/store/delivery-status.d.ts +47 -0
  204. package/lib/types/store/disputes.d.ts +6 -0
  205. package/lib/types/store/entities.d.ts +16 -0
  206. package/lib/types/store/errors.d.ts +8 -0
  207. package/lib/types/store/inbox.d.ts +27 -0
  208. package/lib/types/store/index.d.ts +16 -0
  209. package/lib/types/store/jobs.d.ts +5 -0
  210. package/lib/types/store/lock.d.ts +11 -0
  211. package/lib/types/store/path-names.d.ts +2 -0
  212. package/lib/types/store/paths.d.ts +45 -0
  213. package/lib/types/store/presentation.d.ts +13 -0
  214. package/lib/types/store/regular-file.d.ts +2 -0
  215. package/lib/types/store/rejected-disputes.d.ts +18 -0
  216. package/lib/types/store/rename.d.ts +1 -0
  217. package/lib/types/store/reported-sets.d.ts +24 -0
  218. package/lib/types/store/session-state.d.ts +17 -0
  219. package/lib/types/store/traces.d.ts +6 -0
  220. package/lib/types/store/uploads.d.ts +312 -0
  221. package/lib/types/store/yaml.d.ts +8 -0
  222. package/lib/types/team/errors.d.ts +10 -0
  223. package/lib/types/team/http.d.ts +20 -0
  224. package/lib/types/team/index.d.ts +5 -0
  225. package/lib/types/team/maintainer-client.d.ts +18 -0
  226. package/lib/types/team/router-client.d.ts +14 -0
  227. package/lib/types/team/service.d.ts +28 -0
  228. package/lib/types/team/system-proxy.d.ts +9 -0
  229. package/lib/types/tools/claim.d.ts +63 -0
  230. package/lib/types/tools/consult-router.d.ts +11 -0
  231. package/lib/types/tools/subagent.d.ts +8 -0
  232. package/lib/types/tools/validation.d.ts +2 -0
  233. package/lib/types/upload/consolidation.d.ts +63 -0
  234. package/lib/types/upload/deliver.d.ts +15 -0
  235. package/lib/types/upload/index.d.ts +2 -0
  236. package/lib/types/upload/scheduler.d.ts +19 -0
  237. package/lib/types/upstreams.d.ts +5 -0
  238. package/lib/types/worker/queue.d.ts +17 -0
  239. package/lib/types/worker/types.d.ts +51 -0
  240. package/lib/types/worker/worker.d.ts +39 -0
  241. package/lib/types-C2ST2Zdg.js +17 -0
  242. package/lib/upload.js +3 -0
  243. package/lib/uploads-BCA2p92b.js +210 -0
  244. package/lib/worker-BBTYP2RE.js +185 -0
  245. package/locale/commands/en.json +1 -0
  246. package/locale/commands/zh.json +1 -0
  247. package/locale/dream/en.json +1 -0
  248. package/locale/dream/zh.json +1 -0
  249. package/locale/en.json +7 -0
  250. package/locale/formation/en.json +1 -0
  251. package/locale/formation/zh.json +1 -0
  252. package/locale/inbox/en.json +1 -0
  253. package/locale/inbox/zh.json +1 -0
  254. package/locale/knowledge/en.json +1 -0
  255. package/locale/knowledge/zh.json +1 -0
  256. package/locale/prompt/en.json +1 -0
  257. package/locale/prompt/zh.json +1 -0
  258. package/locale/tools/en.json +1 -0
  259. package/locale/tools/zh.json +1 -0
  260. package/locale/zh.json +7 -0
  261. package/package.json +262 -3
  262. package/prompts/claim_dream.j2 +77 -0
  263. package/prompts/claim_dream_legacy.j2 +63 -0
  264. package/prompts/dream_compaction.j2 +11 -0
  265. package/prompts/dream_evidence.j2 +5 -0
  266. package/prompts/inbox_claim_attribute_update_internalize.j2 +112 -0
  267. package/prompts/inbox_policy_update_internalize.j2 +87 -0
  268. package/prompts/knowledge.j2 +38 -0
  269. package/prompts/session_recap.j2 +113 -0
  270. package/prompts/what_is_claim.j2 +51 -0
  271. package/prompts/what_is_dispute.j2 +21 -0
  272. package/prompts/what_is_policy.j2 +22 -0
@@ -0,0 +1,153 @@
1
+ import { C as StoreError, _ as JobError, c as readYamlOr, l as writeYamlAtomic, n as withFileLock, w as hasCode, x as jobPriority, y as JobSchema } from "./lock-DbmlKOoX.js";
2
+ import { z } from "zod";
3
+ import { randomUUID } from "node:crypto";
4
+ import fs from "node:fs/promises";
5
+ //#region src/worker/queue.ts
6
+ function runnableJob(job, kinds, now = Date.now()) {
7
+ return job.state === "queued" && job.payload["paused"] !== true && kinds.has(job.kind) && (job.nextRunAt ?? 0) <= now;
8
+ }
9
+ var JobQueue = class {
10
+ context;
11
+ constructor(context) {
12
+ this.context = context;
13
+ }
14
+ async list() {
15
+ let entries;
16
+ try {
17
+ entries = await fs.readdir(this.context.paths.jobs, { withFileTypes: true });
18
+ } catch (error) {
19
+ if (hasCode(error, "ENOENT")) return [];
20
+ throw error;
21
+ }
22
+ return (await Promise.all(entries.filter((entry) => entry.isFile() && /^[a-zA-Z0-9_-]+\.yaml$/.test(entry.name)).map((entry) => this.read(entry.name.slice(0, -5))))).filter((value) => value !== null);
23
+ }
24
+ async read(id) {
25
+ const value = await readYamlOr(this.context.paths.job(id), z.preprocess((value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "memory_review" ? null : value, JobSchema.nullable()), () => null);
26
+ if (value !== null && value.id !== id) throw new StoreError("decode", "Job ID differs from its filename.");
27
+ return value;
28
+ }
29
+ write(job) {
30
+ return writeYamlAtomic(this.context.paths.job(job.id), job, JobSchema, this.context.logger);
31
+ }
32
+ locked(action) {
33
+ return withFileLock(this.context.paths.jobQueueLock, action, { timeoutMs: this.context.lockTimeoutMs });
34
+ }
35
+ enqueue(kind, payload, sessionId) {
36
+ return this.locked(async () => {
37
+ const jobs = await this.list();
38
+ if (kind === "dream") {
39
+ const pending = jobs.find((job) => job.kind === kind && (job.state === "queued" || job.state === "running"));
40
+ if (pending !== void 0) return pending;
41
+ }
42
+ const same = jobs.find((job) => job.kind === kind && job.sessionId === sessionId && job.state === "queued" && JSON.stringify(job.payload) === JSON.stringify(payload));
43
+ if (same !== void 0) return same;
44
+ if (kind === "finalize") {
45
+ for (const job of jobs) if (job.kind === "recap" && job.sessionId === sessionId && job.state === "queued") await this.write({
46
+ ...job,
47
+ state: "succeeded",
48
+ updatedAt: Date.now(),
49
+ result: { skipped: "superseded" }
50
+ });
51
+ }
52
+ const now = Date.now();
53
+ const job = JobSchema.parse({
54
+ schemaVersion: 1,
55
+ id: randomUUID(),
56
+ kind,
57
+ ...sessionId === void 0 ? {} : { sessionId },
58
+ payload,
59
+ state: "queued",
60
+ attempts: 0,
61
+ createdAt: now,
62
+ updatedAt: now,
63
+ ordinal: Math.max(0, ...jobs.map((job) => job.ordinal ?? 0)) + 1
64
+ });
65
+ await this.write(job);
66
+ return job;
67
+ });
68
+ }
69
+ recoverRunning() {
70
+ return this.locked(async () => {
71
+ for (const job of await this.list()) if (job.state === "running") await this.write({
72
+ ...job,
73
+ state: "queued",
74
+ updatedAt: Date.now()
75
+ });
76
+ });
77
+ }
78
+ claim(kinds) {
79
+ return this.locked(async () => {
80
+ const now = Date.now();
81
+ const jobs = (await this.list()).filter((job) => runnableJob(job, kinds, now));
82
+ jobs.sort((a, b) => jobPriority[a.kind] - jobPriority[b.kind] || (a.ordinal !== void 0 && b.ordinal !== void 0 ? a.ordinal - b.ordinal : a.createdAt - b.createdAt) || a.id.localeCompare(b.id));
83
+ const first = jobs[0];
84
+ if (first === void 0) return null;
85
+ const job = {
86
+ ...first,
87
+ state: "running",
88
+ attempts: first.attempts + 1,
89
+ updatedAt: Date.now()
90
+ };
91
+ await this.write(job);
92
+ return job;
93
+ });
94
+ }
95
+ settle(job, state, details = {}) {
96
+ return this.locked(async () => {
97
+ const current = await this.read(job.id);
98
+ const next = {
99
+ ...job,
100
+ payload: current?.payload ?? job.payload,
101
+ state,
102
+ updatedAt: Date.now()
103
+ };
104
+ delete next.lastError;
105
+ delete next.lastErrorKind;
106
+ delete next.nextRunAt;
107
+ delete next.result;
108
+ await this.write({
109
+ ...next,
110
+ ...details
111
+ });
112
+ });
113
+ }
114
+ pauseDream(paused) {
115
+ return this.locked(async () => {
116
+ const result = [];
117
+ for (const job of await this.list()) if (job.kind === "dream" && (job.state === "queued" || job.state === "running")) {
118
+ const next = {
119
+ ...job,
120
+ payload: {
121
+ ...job.payload,
122
+ paused
123
+ },
124
+ updatedAt: Date.now()
125
+ };
126
+ delete next.payload["budget_exhausted"];
127
+ delete next.payload["budget_epoch"];
128
+ await this.write(next);
129
+ result.push(next);
130
+ }
131
+ return result;
132
+ });
133
+ }
134
+ retry(id) {
135
+ return this.locked(async () => {
136
+ const job = await this.read(id);
137
+ if (job === null || job.state !== "failed") throw new JobError("validation", "只能重试已失败的任务;请从 /acn-status 复制任务 ID。");
138
+ const next = {
139
+ ...job,
140
+ state: "queued",
141
+ attempts: 0,
142
+ updatedAt: Date.now()
143
+ };
144
+ delete next.lastError;
145
+ delete next.lastErrorKind;
146
+ delete next.nextRunAt;
147
+ await this.write(next);
148
+ return next;
149
+ });
150
+ }
151
+ };
152
+ //#endregion
153
+ export { runnableJob as n, JobQueue as t };
@@ -0,0 +1,136 @@
1
+ import { t as KnowledgeError } from "./errors-Bp_2WXBr.js";
2
+ import fs from "node:fs/promises";
3
+ import { constants } from "node:fs";
4
+ //#region src/knowledge/safety.ts
5
+ const invisibleRanges = [
6
+ [0, 31],
7
+ [127, 159],
8
+ [173, 173],
9
+ [847, 847],
10
+ [1564, 1564],
11
+ [1757, 1757],
12
+ [1807, 1807],
13
+ [2192, 2193],
14
+ [2274, 2274],
15
+ [6158, 6158],
16
+ [7114, 7117],
17
+ [119155, 119162],
18
+ [8203, 8207],
19
+ [8234, 8238],
20
+ [8288, 8303],
21
+ [65024, 65039],
22
+ [65279, 65279],
23
+ [65529, 65531],
24
+ [917760, 917999]
25
+ ];
26
+ function invisible(value) {
27
+ return Array.from(value).some((char) => {
28
+ if ([
29
+ " ",
30
+ "\n",
31
+ "\r"
32
+ ].includes(char)) return false;
33
+ const point = char.codePointAt(0);
34
+ return point !== void 0 && invisibleRanges.some(([first, last]) => point >= first && point <= last);
35
+ });
36
+ }
37
+ const patterns = [
38
+ ["ignore", "instructions"],
39
+ ["you are now"],
40
+ ["do not tell", "user"],
41
+ ["system prompt", "override"],
42
+ [
43
+ "override",
44
+ "previous",
45
+ "rules"
46
+ ],
47
+ ["disregard", "instructions"],
48
+ ["disregard", "rules"],
49
+ [
50
+ "act as if",
51
+ "no",
52
+ "restrictions"
53
+ ],
54
+ [
55
+ "act as though",
56
+ "no",
57
+ "rules"
58
+ ],
59
+ ...[
60
+ "key",
61
+ "token",
62
+ "secret",
63
+ "password",
64
+ "credential"
65
+ ].map((term) => [
66
+ "curl",
67
+ "$",
68
+ term
69
+ ]),
70
+ ["curl", "api_key"],
71
+ ["curl", "token="],
72
+ ...[
73
+ "key",
74
+ "token",
75
+ "secret"
76
+ ].map((term) => [
77
+ "wget",
78
+ "$",
79
+ term
80
+ ]),
81
+ ...[
82
+ ".env",
83
+ "credentials",
84
+ "id_rsa",
85
+ ".netrc",
86
+ ".npmrc",
87
+ ".pypirc"
88
+ ].map((term) => ["curl", term]),
89
+ ...[
90
+ ".env",
91
+ "credentials",
92
+ "id_rsa"
93
+ ].map((term) => ["wget", term]),
94
+ ...[
95
+ ".env",
96
+ "credentials",
97
+ ".netrc",
98
+ ".pgpass",
99
+ ".npmrc",
100
+ ".pypirc",
101
+ "id_rsa",
102
+ ".aws/config"
103
+ ].map((term) => ["cat", term]),
104
+ ["authorized_keys"],
105
+ ["$home/.ssh"],
106
+ ["~/.ssh"]
107
+ ];
108
+ function validateClaimText(fields) {
109
+ for (const [field, value] of Object.entries(fields)) {
110
+ if (value.trim() === "") throw new KnowledgeError("validation", `Claim ${field} must not be empty.`);
111
+ if (textSafetyIssue(value) !== null) throw new KnowledgeError("safety", `Claim ${field} failed the safety scan.`);
112
+ }
113
+ }
114
+ function textSafetyIssue(value) {
115
+ if (invisible(value)) return "invisible_unicode";
116
+ const normalized = value.toLowerCase().replace(/\s/gu, " ").replace(/ +/g, " ");
117
+ return patterns.some((terms) => terms.every((term) => normalized.includes(term))) ? "threat_pattern" : null;
118
+ }
119
+ //#endregion
120
+ //#region src/store/regular-file.ts
121
+ async function openSingleFile(path, invalid) {
122
+ const before = await fs.lstat(path);
123
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1) throw invalid();
124
+ const file = await fs.open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
125
+ try {
126
+ const opened = await file.stat();
127
+ const current = await fs.lstat(path);
128
+ if (!opened.isFile() || opened.nlink !== 1 || current.isSymbolicLink() || before.dev !== opened.dev || before.ino !== opened.ino || current.dev !== opened.dev || current.ino !== opened.ino) throw invalid();
129
+ return file;
130
+ } catch (error) {
131
+ await file.close();
132
+ throw error;
133
+ }
134
+ }
135
+ //#endregion
136
+ export { validateClaimText as n, openSingleFile as t };
@@ -0,0 +1,48 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import nunjucks from "nunjucks";
5
+ //#region src/prompt/render.ts
6
+ const templateNames = [
7
+ "claim_dream.j2",
8
+ "claim_dream_legacy.j2",
9
+ "dream_compaction.j2",
10
+ "dream_evidence.j2",
11
+ "knowledge.j2",
12
+ "session_recap.j2",
13
+ "inbox_policy_update_internalize.j2",
14
+ "inbox_claim_attribute_update_internalize.j2",
15
+ "what_is_claim.j2",
16
+ "what_is_dispute.j2",
17
+ "what_is_policy.j2"
18
+ ];
19
+ var TemplateLoader = class extends nunjucks.Loader {
20
+ sources;
21
+ constructor(sources) {
22
+ super();
23
+ this.sources = sources;
24
+ }
25
+ getSource(name) {
26
+ const src = this.sources[name];
27
+ if (src === void 0) throw new Error("Unknown knowledge template.");
28
+ return {
29
+ src: src.endsWith("\n") ? src.slice(0, -1) : src,
30
+ path: name,
31
+ noCache: false
32
+ };
33
+ }
34
+ };
35
+ function promptRenderer(sources) {
36
+ const environment = new nunjucks.Environment(new TemplateLoader(sources), {
37
+ autoescape: false,
38
+ throwOnUndefined: true
39
+ });
40
+ return (name, context) => environment.render(name, context);
41
+ }
42
+ async function loadPromptRenderer() {
43
+ const root = dirname(fileURLToPath(import.meta.resolve("@ftai/dsh-plugin-acn/package.json")));
44
+ const sources = await Promise.all(templateNames.map(async (name) => [name, await readFile(join(root, "prompts", name), "utf8")]));
45
+ return promptRenderer(Object.fromEntries(sources));
46
+ }
47
+ //#endregion
48
+ export { loadPromptRenderer as t };
@@ -0,0 +1,122 @@
1
+ import { l as ClaimIdSchema, t as ClaimSchema, u as DisputeIdSchema, y as TimestampSchema } from "./claim-DOAGe8ZK.js";
2
+ import { C as StoreError, c as readYamlOr, d as removeFile, l as writeYamlAtomic, n as withFileLock, s as readYaml, w as hasCode } from "./lock-DbmlKOoX.js";
3
+ import { z } from "zod";
4
+ import fs from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ //#region src/store/entities.ts
7
+ var EntityStore = class {
8
+ context;
9
+ directory;
10
+ schema;
11
+ idSchema;
12
+ constructor(context, directory, schema, idSchema) {
13
+ this.context = context;
14
+ this.directory = directory;
15
+ this.schema = schema;
16
+ this.idSchema = idSchema;
17
+ }
18
+ path(id) {
19
+ return join(this.directory, `${this.idSchema.parse(id)}.yaml`);
20
+ }
21
+ async read(id) {
22
+ const value = await readYaml(this.path(id), this.schema);
23
+ if (value.id !== id) throw new StoreError("decode", `Entity ID differs from its filename: ${id}`);
24
+ return value;
25
+ }
26
+ async write(value) {
27
+ const parsed = this.schema.parse(value);
28
+ await writeYamlAtomic(this.path(parsed.id), parsed, this.schema, this.context.logger);
29
+ return parsed;
30
+ }
31
+ async list() {
32
+ let entries;
33
+ try {
34
+ entries = await fs.readdir(this.directory, { withFileTypes: true });
35
+ } catch (error) {
36
+ if (hasCode(error, "ENOENT")) return [];
37
+ throw error;
38
+ }
39
+ const values = [];
40
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
41
+ if (!entry.isFile() || !entry.name.endsWith(".yaml") || entry.name.includes(".tmp.")) continue;
42
+ const id = entry.name.slice(0, -5);
43
+ if (!this.idSchema.safeParse(id).success) continue;
44
+ try {
45
+ values.push(await this.read(id));
46
+ } catch (error) {
47
+ if (error instanceof StoreError && error.kind === "decode") this.context.logger.warn(`Skipped invalid entity file: ${entry.name}`);
48
+ else throw error;
49
+ }
50
+ }
51
+ return values;
52
+ }
53
+ async create(makeId, makeValue) {
54
+ await fs.mkdir(this.directory, { recursive: true });
55
+ for (let attempt = 0; attempt < 8; attempt += 1) {
56
+ const id = this.idSchema.parse(makeId());
57
+ const path = this.path(id);
58
+ try {
59
+ await (await fs.open(path, "wx", 384)).close();
60
+ } catch (error) {
61
+ if (hasCode(error, "EEXIST")) continue;
62
+ throw error;
63
+ }
64
+ try {
65
+ const value = makeValue(id);
66
+ if (value.id !== id) throw new StoreError("conflict", "Reserved entity ID differs from the value.");
67
+ return await this.write(value);
68
+ } catch (error) {
69
+ await removeFile(path, this.context.logger);
70
+ throw error;
71
+ }
72
+ }
73
+ throw new StoreError("conflict", "Entity ID collisions exceeded eight attempts.");
74
+ }
75
+ };
76
+ //#endregion
77
+ //#region src/store/claims.ts
78
+ var ClaimStore = class extends EntityStore {
79
+ constructor(context) {
80
+ super(context, context.paths.claims, ClaimSchema, ClaimIdSchema);
81
+ }
82
+ async write(value) {
83
+ const claim = ClaimSchema.parse(value);
84
+ if (claim.holder !== this.context.agentId) throw new StoreError("ownership", "Cannot write a Claim held by another agent.");
85
+ return super.write(claim);
86
+ }
87
+ };
88
+ //#endregion
89
+ //#region src/store/reported-sets.ts
90
+ const ReportedSetsSchema = z.object({ reported_claim_sets: z.record(z.string(), z.object({
91
+ first_dispute_id: DisputeIdSchema,
92
+ reported_at: TimestampSchema
93
+ })).default({}).transform((records) => Object.fromEntries(Object.entries(records).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))) });
94
+ function reportedClaimSetKey(claims) {
95
+ return [...new Set(claims.map((id) => ClaimIdSchema.parse(id)))].sort().join(" | ");
96
+ }
97
+ var ReportedSetStore = class {
98
+ context;
99
+ constructor(context) {
100
+ this.context = context;
101
+ }
102
+ read() {
103
+ return readYamlOr(this.context.paths.reportedSets, ReportedSetsSchema, () => ReportedSetsSchema.parse({}));
104
+ }
105
+ async contains(claims) {
106
+ return Object.hasOwn((await this.read()).reported_claim_sets, reportedClaimSetKey(claims));
107
+ }
108
+ async record(claims, disputeId, reportedAt) {
109
+ await withFileLock(`${this.context.paths.reportedSets}.lock`, async () => {
110
+ const value = await this.read();
111
+ const key = reportedClaimSetKey(claims);
112
+ if (Object.hasOwn(value.reported_claim_sets, key)) return;
113
+ value.reported_claim_sets[key] = {
114
+ first_dispute_id: DisputeIdSchema.parse(disputeId),
115
+ reported_at: TimestampSchema.parse(reportedAt)
116
+ };
117
+ await writeYamlAtomic(this.context.paths.reportedSets, value, ReportedSetsSchema, this.context.logger);
118
+ }, { timeoutMs: this.context.lockTimeoutMs });
119
+ }
120
+ };
121
+ //#endregion
122
+ export { EntityStore as a, ClaimStore as i, ReportedSetsSchema as n, reportedClaimSetKey as r, ReportedSetStore as t };
@@ -0,0 +1,11 @@
1
+ import { t as ClaimSchema } from "./claim-DOAGe8ZK.js";
2
+ import { createHash } from "node:crypto";
3
+ //#region src/protocol/revision.ts
4
+ function canonicalJson(value) {
5
+ return JSON.stringify(ClaimSchema.parse(value));
6
+ }
7
+ function claimRevision(value) {
8
+ return `sha256-v1:${createHash("sha256").update(canonicalJson(value)).digest("hex")}`;
9
+ }
10
+ //#endregion
11
+ export { claimRevision as n, canonicalJson as t };
@@ -0,0 +1,64 @@
1
+ import { r as UploadStore } from "./uploads-BCA2p92b.js";
2
+ import { t as UploadDelivery } from "./deliver-BuYQaPRW.js";
3
+ //#region src/upload/scheduler.ts
4
+ var UploadScheduler = class {
5
+ knowledge;
6
+ intervalMs;
7
+ pending;
8
+ requested = false;
9
+ closed = false;
10
+ abort = new AbortController();
11
+ timer;
12
+ unsubscribe;
13
+ delivery;
14
+ constructor(knowledge, intervalMs = 10 * 6e4) {
15
+ this.knowledge = knowledge;
16
+ this.intervalMs = intervalMs;
17
+ this.delivery = new UploadDelivery(knowledge.context(), knowledge.team);
18
+ }
19
+ start() {
20
+ if (this.knowledge.team === null) return;
21
+ this.unsubscribe = this.knowledge.onClaimsChanged(() => {
22
+ this.kick();
23
+ });
24
+ this.timer = setInterval(() => {
25
+ this.kick();
26
+ }, this.intervalMs);
27
+ this.timer.unref();
28
+ this.kick();
29
+ }
30
+ kick() {
31
+ if (this.closed || this.knowledge.team === null) return;
32
+ this.requested = true;
33
+ if (this.pending !== void 0) return;
34
+ const work = this.run().catch(() => {
35
+ if (!this.closed) this.knowledge.logger.warn("Could not finish local upload bookkeeping; pending delivery is retained.");
36
+ });
37
+ this.pending = work;
38
+ work.finally(() => {
39
+ if (this.pending === work) {
40
+ this.pending = void 0;
41
+ if (this.requested && !this.closed) this.kick();
42
+ }
43
+ });
44
+ }
45
+ async run() {
46
+ while (this.requested && !this.closed) {
47
+ this.requested = false;
48
+ const queue = await new UploadStore(this.knowledge.context()).read();
49
+ if (queue.claims.length > 0 || queue.disputes.length > 0) await this.delivery.deliver(this.abort.signal);
50
+ }
51
+ }
52
+ async flush() {
53
+ await this.pending;
54
+ }
55
+ async close() {
56
+ this.closed = true;
57
+ this.unsubscribe?.();
58
+ if (this.timer !== void 0) clearInterval(this.timer);
59
+ this.abort.abort();
60
+ await this.pending;
61
+ }
62
+ };
63
+ //#endregion
64
+ export { UploadScheduler as t };