engine-artifacts.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /**
  2. * engine.ts 顶到 oxlint max-lines 上限(400 行),把**用户面产物**(`artifact.*`)的
  3. * 发布 / 声明 / 准入 / 结算 / resume 恢复拆到本文件;公开面仍从 engine.ts 导出。
  4. *
  5. * ⚠ 术语:以下一律指**用户面产物**(脚本发布给用户看的产出),不是 RunSettlement.artifact。
  6. * 自由函数经 {@link EngineState} 接缝读写引擎状态;WorkflowEngine 上的同名方法只是薄委托。
  7. */
  8. import { canonicalJson, inputHash } from "./hash.js";
  9. import { ARTIFACT_CAPS } from "../facade/artifact-caps.js";
  10. import {
  11. isArtifactPresetOp,
  12. type ArtifactContentOp,
  13. type ArtifactPresetOp,
  14. } from "../facade/registry.js";
  15. import { heldResolution } from "./replay-order.js";
  16. import {
  17. primaryArtifactId,
  18. primaryConflict,
  19. primaryConflictMessage,
  20. } from "./engine-artifacts-primary.js";
  21. import { validateArtifactSpec } from "./artifact-spec.js";
  22. import { hashMismatch } from "./hash-mismatch.js";
  23. import type { EngineState } from "./engine-state.js";
  24. import type {
  25. ArtifactPublishRequest,
  26. ArtifactRef,
  27. ArtifactVersionRecord,
  28. InstanceRef,
  29. } from "./types.js";
  30. import { refToString, WorkflowError } from "./types.js";
  31. /**
  32. * 发布一个**内容产物**(`artifact.file` / `artifact.markdown`)。效应族:经 driver 拷字节进
  33. * store,成功兑现 {@link ArtifactRef},失败**可 catch 地拒绝**——脚本的门控习语是
  34. * `try { await artifact.file(...) } catch { …让子代理补写… }`。
  35. *
  36. * 顺序:
  37. * 1. `nextOrdinal` → journal 命中?命中即短路:比 inputHash,成功记录返回它的 ArtifactRef,
  38. * **失败记录按记录重新拒绝**(resume 是崩溃恢复,不是复验:一次失败的发布在恢复后仍然
  39. * 是那次失败,重跑它会让脚本的 catch 分支走两次不同的路)。命中一律**不重发事件**(同 report)。
  40. * 2. 未命中:种类归属 → id 数上限 → 版本数上限,三条都是节点级拒绝(有 promise 可拒)。
  41. * 3. 版本号在 dispatch **之前**算好并传给 driver(store 的 toolCallId 里要带它,每版一份字节)。
  42. * 4. `putNode(running)` → driver → 成功 `putNode(completed)` + `artifact-published`;
  43. * 失败 `putNode(failed)` + `artifact-failed` → reject。
  44. *
  45. * 两条路都**不发任何节点生命周期事件**(node-queued / dispatched / settled):产物站点在两张
  46. * 图里都不是节点,一条 node-settled 落在这样的站点上会被投影归约进 `nodes[]`,在 run 面板里
  47. * 变成一个无从解释的未知节点。
  48. */
  49. export function publishContentArtifact(
  50. state: EngineState,
  51. siteId: string,
  52. op: ArtifactContentOp,
  53. args: unknown[],
  54. ): Promise<ArtifactRef> {
  55. if (state.isRunSettled()) return Promise.reject(state.runError());
  56. const ordinal = state.nextOrdinal(siteId);
  57. const instance: InstanceRef = { siteId, ordinal };
  58. const id = args[0];
  59. const payload = args[1];
  60. // 实参形状的运行期护栏(编译期的字面量 id 诊断与 facade 类型是正门):走到这里的非字符串
  61. // 只可能是有东西绕过了编译。用 DriverError 而不是某个 Artifact* 码——让那些码只表示它们
  62. // 各自的那件事(同 probeReportItem 对「item 不是 JSON」的取码论证)。
  63. //
  64. // 这两条**不落 journal 行、不发事件**,与下面所有失败路径不同。理由是它们是**确定性**的:
  65. // 结论只由 args 决定,没有 driver 往返,resume 重跑同一个调用必然得到同一个拒绝,所以
  66. // 不需要一行记录把它钉住(「settled failure 落库」那条要求针对的是 driver 执行过的、
  67. // 下次未必再失败的那种)。何况这里根本没有 id 可写进 `artifact_id` 或事件——编一个出来
  68. // 只会让读者以为真有那么一个产物。
  69. if (typeof id !== "string" || id === "") {
  70. return Promise.reject(
  71. new WorkflowError(
  72. "DriverError",
  73. `artifact.${op}: id must be a non-empty string (at ${refToString(instance)}).`,
  74. ),
  75. );
  76. }
  77. if (typeof payload !== "string") {
  78. return Promise.reject(
  79. new WorkflowError(
  80. "DriverError",
  81. op === "file"
  82. ? `artifact.file: path must be a string (at ${refToString(instance)}).`
  83. : `artifact.markdown: content must be a string (at ${refToString(instance)}).`,
  84. ),
  85. );
  86. }
  87. // `opts.primary` 由**引擎**读:driver 对不认识的
  88. // opts 键一律放行,而「全 run 至多一个 primary」是 run 级事实,只有引擎知道。非布尔值与上面
  89. // 两条同属确定性护栏——不落行、不发事件。
  90. const primaryOption = (args[2] as { primary?: unknown } | undefined)?.primary;
  91. if (primaryOption !== undefined && typeof primaryOption !== "boolean") {
  92. return Promise.reject(
  93. new WorkflowError(
  94. "DriverError",
  95. `artifact.${op}: opts.primary must be a boolean (at ${refToString(instance)}).`,
  96. ),
  97. );
  98. }
  99. const hash = inputHash({ args, id, op });
  100. const recorded = state.journal.getNode(state.runId, siteId, ordinal);
  101. if (recorded !== undefined) {
  102. if (recorded.inputHash !== hash) {
  103. const err = hashMismatch(instance, recorded.inputHash, hash);
  104. state.failRun(err);
  105. return Promise.reject(err);
  106. }
  107. // 与 ask / world 命中同规:释放点过 replay 次序闸(docs/execution-engine.md
  108. // 「Replaying the settle order」)。发布是效应、脚本要 await 它,所以它也是一个能决定
  109. // 后续续体次序的释放点;预置声明是同步 void,从不走这条路,也就从不占闸。
  110. if (recorded.status === "completed") {
  111. const record = recorded.result as ArtifactVersionRecord;
  112. return heldResolution(state.holdForReplay, instance, () => ({
  113. id: record.id,
  114. version: record.version,
  115. }));
  116. }
  117. if (recorded.status === "failed") {
  118. return heldResolution(state.holdForReplay, instance, () => {
  119. throw WorkflowError.fromJSON(recorded.error!);
  120. });
  121. }
  122. // status === "running":崩溃于执行中,落到下面重新 live 执行(字节的拷贝是幂等的,
  123. // 而版本号从**已 completed 的行数**派生,所以重跑不会跳号)。
  124. }
  125. // 粘着:这个 id 已经是 primary,则这一版也是,不管本次有没有再写 `primary`。
  126. const idState = state.artifacts.get(id);
  127. const primary = primaryOption === true || idState?.primary === true;
  128. const admission = admitArtifact(state, id, op, primary);
  129. if (admission !== undefined) {
  130. return Promise.reject(settleArtifactFailure(state, instance, hash, { id, op }, admission));
  131. }
  132. const version = (idState?.versions ?? 0) + 1;
  133. const publish = state.driver.executeArtifactPublish;
  134. if (publish === undefined) {
  135. // 装配没有 driver 侧的发布能力(纯 replay / 没接 store 的 fake)。**大声的一条命名失败**,
  136. // 不是静默降级成「发布了一个空产物」——脚本看得见、节点以 failed 落库。
  137. return Promise.reject(
  138. settleArtifactFailure(
  139. state,
  140. instance,
  141. hash,
  142. { id, op },
  143. new WorkflowError(
  144. "ArtifactStoreUnavailable",
  145. `Cannot publish "${id}": this host has no artifact store (at ${refToString(instance)}).`,
  146. ),
  147. ),
  148. );
  149. }
  150. state.journal.putNode({
  151. runId: state.runId,
  152. siteId,
  153. ordinal,
  154. kind: "artifact",
  155. inputHash: hash,
  156. status: "running",
  157. artifactId: id,
  158. });
  159. const request: ArtifactPublishRequest = {
  160. runId: state.runId,
  161. siteId,
  162. ordinal,
  163. op,
  164. id,
  165. version,
  166. ...(op === "file" ? { path: payload } : { content: payload }),
  167. ...(args[2] === undefined ? {} : { opts: args[2] }),
  168. };
  169. return publish.call(state.driver, request).then(
  170. (record) => settleArtifactPublish(state, instance, hash, { id, op, version, primary }, record),
  171. (cause: unknown) => {
  172. const err =
  173. cause instanceof WorkflowError
  174. ? cause
  175. : new WorkflowError("DriverError", `Artifact publish failed: ${op} "${id}".`, {
  176. cause,
  177. });
  178. throw settleArtifactFailure(state, instance, hash, { id, op }, err);
  179. },
  180. );
  181. }
  182. /**
  183. * 声明一个**预置产物**(`artifact.chart` / `table` / `metrics` / `board`)。声明族:同步、
  184. * 无返回值、**不经 driver**——一个声明没有可等的东西。
  185. *
  186. * 顺序:`nextOrdinal` → 命中即返回 → spec 形状校验
  187. * → 同 id 既有声明?相同 canonical ⇒ 幂等 no-op(不落新行、不发事件);不同 ⇒ failRun
  188. * → 上限 → `putNode(completed)` + `artifact-published`。
  189. *
  190. * 三种失败(spec 非法 / 同 id 异 spec / 超上限)全是 failRun 而不是拒绝:void 返回没有拒绝
  191. * 通道,与 `report` 的两个上限同一条论证。
  192. */
  193. export function declarePresetArtifact(
  194. state: EngineState,
  195. siteId: string,
  196. op: ArtifactPresetOp,
  197. args: unknown[],
  198. ): void {
  199. if (state.isRunSettled()) return; // 与 report / log 同
  200. const ordinal = state.nextOrdinal(siteId);
  201. const instance: InstanceRef = { siteId, ordinal };
  202. const id = args[0];
  203. if (typeof id !== "string" || id === "") {
  204. state.failRun(
  205. new WorkflowError(
  206. "DriverError",
  207. `artifact.${op}: id must be a non-empty string (at ${refToString(instance)}).`,
  208. ),
  209. );
  210. return;
  211. }
  212. const spec = args[1];
  213. const hash = inputHash({ args, id, op });
  214. const recorded = state.journal.getNode(state.runId, siteId, ordinal);
  215. if (recorded !== undefined) {
  216. if (recorded.inputHash !== hash) {
  217. state.failRun(hashMismatch(instance, recorded.inputHash, hash));
  218. return;
  219. }
  220. return; // replay 去重:静默跳过(同 report)
  221. }
  222. const problem = validateArtifactSpec(op, spec);
  223. if (problem !== undefined) {
  224. state.failRun(
  225. new WorkflowError(
  226. "ArtifactSpecInvalid",
  227. `Artifact "${id}" has an invalid spec (at ${refToString(instance)}): ${problem}`,
  228. ),
  229. );
  230. return;
  231. }
  232. const canonical = canonicalJson(spec);
  233. const idState = state.artifacts.get(id);
  234. if (idState !== undefined) {
  235. if (idState.kind !== op) {
  236. state.failRun(
  237. new WorkflowError(
  238. "ArtifactKindMismatch",
  239. `Artifact id "${id}" is already a ${idState.kind} and cannot be declared as a ${op} ` +
  240. `(at ${refToString(instance)}). An id belongs to one artifact kind for the whole run; ` +
  241. `use a different id.`,
  242. ),
  243. );
  244. return;
  245. }
  246. if (idState.spec === canonical) return; // 幂等 no-op:不落新行、不发事件
  247. state.failRun(
  248. new WorkflowError(
  249. "ArtifactRedeclared",
  250. `Artifact "${id}" was already declared with a different spec (at ${refToString(instance)}). ` +
  251. `The spec for one id must stay identical (an identical re-declaration is a no-op); ` +
  252. `declare it once at the top of the script.`,
  253. ),
  254. );
  255. return;
  256. }
  257. // `primary` 进 canonical spec,所以同 id 改旗子是 ArtifactRedeclared(上面已经拒了);这里只剩
  258. // **新** id 想当 primary 而别的 id 已经是——预置族没有拒绝通道,failRun。
  259. const wantsPrimary = (spec as { primary?: unknown }).primary === true;
  260. const holder = wantsPrimary ? primaryArtifactId(state) : undefined;
  261. if (holder !== undefined && holder !== id) {
  262. state.failRun(
  263. new WorkflowError(
  264. "ArtifactPrimaryConflict",
  265. primaryConflictMessage(id, holder, `declare "${id}" without primary`, instance),
  266. ),
  267. );
  268. return;
  269. }
  270. if (state.artifacts.size >= ARTIFACT_CAPS.maxArtifactsPerRun) {
  271. state.failRun(
  272. new WorkflowError(
  273. "ArtifactCapExceeded",
  274. `Cannot declare "${id}": this run already has ${ARTIFACT_CAPS.maxArtifactsPerRun} artifact ` +
  275. `ids, the maximum. Reuse an existing id or publish fewer artifacts.`,
  276. ),
  277. );
  278. return;
  279. }
  280. // 声明是**一次写**(同 report):准入与结算之间没有 driver 调用,没有什么能在中间失败。
  281. const record = presetRecord(id, op, spec);
  282. state.artifacts.set(id, {
  283. kind: op,
  284. spec: canonical,
  285. versions: 1,
  286. ...(wantsPrimary ? { primary: true as const } : {}),
  287. });
  288. state.journal.putNode({
  289. runId: state.runId,
  290. siteId,
  291. ordinal,
  292. kind: "artifact",
  293. inputHash: hash,
  294. status: "completed",
  295. result: record,
  296. artifactId: id,
  297. });
  298. state.record({ type: "artifact-published", instance, artifact: record });
  299. }
  300. /**
  301. * 内容产物的准入:种类归属 → id 数上限 → 版本数上限。返回拒绝理由,`undefined` 即放行。
  302. *
  303. * 三条全是**节点级**拒绝(内容成员有 promise 可拒),与预置族里同名的三条形成对照——
  304. * 那一族只能 failRun。同一个事实、两个通道,差别在返回类型而不是严重程度。
  305. */
  306. function admitArtifact(
  307. state: EngineState,
  308. id: string,
  309. op: ArtifactContentOp,
  310. primary: boolean,
  311. ): WorkflowError | undefined {
  312. const idState = state.artifacts.get(id);
  313. if (idState !== undefined && idState.kind !== op) {
  314. return new WorkflowError(
  315. "ArtifactKindMismatch",
  316. `Artifact id "${id}" is already a ${idState.kind} and cannot be published as a ${op}. An id ` +
  317. `belongs to one artifact kind for the whole run (publishing the same id again creates a ` +
  318. `new version, and a version cannot change what it is); use a different id.`,
  319. );
  320. }
  321. // primary 冲突排在上限之前:一个想当交付物的 id 被拒,理由该是「已经有交付物了」,不是「满了」。
  322. const holder = primaryConflict(state, id, primary);
  323. if (holder !== undefined) {
  324. return new WorkflowError(
  325. "ArtifactPrimaryConflict",
  326. primaryConflictMessage(id, holder, `publish "${id}" without primary`, undefined),
  327. );
  328. }
  329. if (idState === undefined && state.artifacts.size >= ARTIFACT_CAPS.maxArtifactsPerRun) {
  330. return new WorkflowError(
  331. "ArtifactCapExceeded",
  332. `Cannot publish "${id}": this run already has ${ARTIFACT_CAPS.maxArtifactsPerRun} artifact ` +
  333. `ids, the maximum. Publish a new version of an existing id instead.`,
  334. );
  335. }
  336. if (idState !== undefined && idState.versions >= ARTIFACT_CAPS.maxVersionsPerArtifact) {
  337. return new WorkflowError(
  338. "ArtifactVersionCapExceeded",
  339. `Artifact "${id}" already has ${idState.versions} versions, the maximum of ` +
  340. `${ARTIFACT_CAPS.maxVersionsPerArtifact}. Publish the final content in fewer versions.`,
  341. );
  342. }
  343. return undefined;
  344. }
  345. /**
  346. * 内容产物发布成功:落 completed 行 + 记账 + 发 `artifact-published`,返回脚本要的 ref。
  347. *
  348. * 身份(id / 种类 / 版本号)一律取**引擎自己算的那份**(`issued`),而不是 driver 回来的
  349. * 记录里的同名字段:版本号是引擎按 journal 派生并下发的,让它绕 driver 走一圈再读回来,
  350. * 只会多出一个可以不一致的地方。driver 的记录负责它真正拥有的东西——uri / bytes /
  351. * contentType / sourcePath——那些整条原样落 journal。
  352. */
  353. function settleArtifactPublish(
  354. state: EngineState,
  355. instance: InstanceRef,
  356. hash: string,
  357. issued: { id: string; op: ArtifactContentOp; version: number; primary: boolean },
  358. record: ArtifactVersionRecord,
  359. ): ArtifactRef {
  360. if (state.isRunSettled()) throw state.runError();
  361. // 准入与结算之间隔着一次 driver 往返:两个并发的 primary 发布都能过准入。结算时再查一次,
  362. // 输的那个走失败路径——failed 行不认领旗子,所以 journal 里永远不会有两个 completed 的 primary。
  363. const holder = primaryConflict(state, issued.id, issued.primary);
  364. if (holder !== undefined) {
  365. throw settleArtifactFailure(
  366. state,
  367. instance,
  368. hash,
  369. issued,
  370. new WorkflowError(
  371. "ArtifactPrimaryConflict",
  372. primaryConflictMessage(issued.id, holder, `publish "${issued.id}" without primary`, instance),
  373. ),
  374. );
  375. }
  376. // 旗子由引擎盖章:driver 的记录只负责它真正拥有的东西(uri / bytes / contentType / sourcePath)。
  377. const stored: ArtifactVersionRecord = issued.primary ? { ...record, primary: true } : record;
  378. state.journal.putNode({
  379. runId: state.runId,
  380. siteId: instance.siteId,
  381. ordinal: instance.ordinal,
  382. kind: "artifact",
  383. inputHash: hash,
  384. status: "completed",
  385. result: stored,
  386. artifactId: issued.id,
  387. });
  388. state.artifacts.set(issued.id, {
  389. kind: issued.op,
  390. versions: issued.version,
  391. ...(issued.primary ? { primary: true as const } : {}),
  392. });
  393. state.record({ type: "artifact-published", instance, artifact: stored });
  394. return { id: issued.id, version: issued.version };
  395. }
  396. /**
  397. * 内容产物发布失败:落 failed 行 + 发 `artifact-failed`,返回要抛出的错误。
  398. *
  399. * 落库是重放健全性的既有要求(settled failure 必须在 journal 里),否则 resume 会把一次
  400. * 已经被脚本 catch 过的失败重跑一遍——那正是「resume 是崩溃恢复不是复验」要防的。
  401. *
  402. * node-settled 的读者
  403. * 会把它归约进 `nodes[]` 并按 site id 去图里找对应节点,而产物站点不进任何图——那会在 run
  404. * 面板上变成一个无从解释的未知节点。`artifact-failed` 带着渲染一张失败卡需要的东西
  405. * (id / 种类 / 结构化错误),不冒充一步工作。成功那侧同理只发 `artifact-published`。
  406. */
  407. function settleArtifactFailure(
  408. state: EngineState,
  409. instance: InstanceRef,
  410. hash: string,
  411. issued: { id: string; op: ArtifactContentOp },
  412. error: WorkflowError,
  413. ): WorkflowError {
  414. const json = error.toJSON();
  415. state.journal.putNode({
  416. runId: state.runId,
  417. siteId: instance.siteId,
  418. ordinal: instance.ordinal,
  419. kind: "artifact",
  420. inputHash: hash,
  421. status: "failed",
  422. error: json,
  423. artifactId: issued.id,
  424. });
  425. state.record({
  426. type: "artifact-failed",
  427. instance,
  428. id: issued.id,
  429. op: issued.op,
  430. error: json,
  431. });
  432. return error;
  433. }
  434. /**
  435. * resume 恢复:把 journal 里一行**已完成**的产物记录并进内存状态。
  436. *
  437. * **只有 completed 行才认领 id**:失败的发布不占 id、不占种类、不占版本。这不只是图简洁——
  438. * 失败行的 `result` 是空的,种类无从恢复,若让 live 那一侧认领而 resume 那一侧认领不了,
  439. * 同一个脚本在崩溃前后就会得到两套上限账。种类冲突另有编译期诊断把守,运行期这条
  440. * (`ArtifactKindMismatch`)管的是真正发布成功过的那些 id。
  441. */
  442. export function rememberArtifactRow(
  443. state: EngineState,
  444. id: string | undefined,
  445. result: unknown,
  446. ): void {
  447. if (id === undefined || id === "") return;
  448. const record = (result ?? undefined) as ArtifactVersionRecord | undefined;
  449. if (record?.kind === undefined) return;
  450. const existing = state.artifacts.get(id);
  451. const spec = record.spec === undefined ? existing?.spec : canonicalJson(record.spec);
  452. const primary = record.primary === true || existing?.primary === true;
  453. state.artifacts.set(id, {
  454. kind: record.kind,
  455. ...(spec === undefined ? {} : { spec }),
  456. versions: (existing?.versions ?? 0) + 1,
  457. ...(primary ? { primary: true as const } : {}),
  458. });
  459. }
  460. /** 该 id 是否已被声明为**预置**产物(`report` 标签的合法目标)。 */
  461. export function isDeclaredPreset(state: EngineState, id: string): boolean {
  462. const idState = state.artifacts.get(id);
  463. return idState !== undefined && isArtifactPresetOp(idState.kind);
  464. }
  465. /** 已声明的预置 id(字典序)——只用于把 `ArtifactUndeclared` 的消息写得能照做。 */
  466. export function declaredPresetIds(state: EngineState): string[] {
  467. return [...state.artifacts.entries()]
  468. .filter(([, idState]) => isArtifactPresetOp(idState.kind))
  469. .map(([id]) => id)
  470. .sort();
  471. }
  472. /**
  473. * 预置声明的落库记录。`title` / `description` 从 spec 里**提上来**:卡片的读者(run 侧板、
  474. * 通知、中枢)只拿到这条记录,不该为了显示一个标题去解 spec;spec 仍原样保留,渲染器要
  475. * 完整形状。版本恒为 1——声明没有版本,它只有一次。
  476. */
  477. function presetRecord(id: string, op: ArtifactPresetOp, spec: unknown): ArtifactVersionRecord {
  478. const options = (spec ?? {}) as { title?: unknown; description?: unknown; primary?: unknown };
  479. return {
  480. id,
  481. kind: op,
  482. version: 1,
  483. ...(typeof options.title === "string" ? { title: options.title } : {}),
  484. ...(typeof options.description === "string" ? { description: options.description } : {}),
  485. spec,
  486. ...(options.primary === true ? { primary: true as const } : {}),
  487. };
  488. }