@plurnk/plurnk-service 1.6.0 → 1.7.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 (164) hide show
  1. package/.env.defaults +7 -21
  2. package/INSTALL.md +18 -17
  3. package/README.md +1 -1
  4. package/SPEC.md +209 -136
  5. package/dist/build-info.json +1 -1
  6. package/dist/core/ChannelWrite.sql +3 -3
  7. package/dist/core/ClientInteractions.d.ts +19 -0
  8. package/dist/core/ClientInteractions.d.ts.map +1 -0
  9. package/dist/core/ClientInteractions.js +124 -0
  10. package/dist/core/ClientInteractions.js.map +1 -0
  11. package/dist/core/ClientInteractions.sql +34 -0
  12. package/dist/core/CoreSchemeServices.d.ts +9 -3
  13. package/dist/core/CoreSchemeServices.d.ts.map +1 -1
  14. package/dist/core/CoreSchemeServices.js +8 -2
  15. package/dist/core/CoreSchemeServices.js.map +1 -1
  16. package/dist/core/Dispatcher.d.ts +4 -2
  17. package/dist/core/Dispatcher.d.ts.map +1 -1
  18. package/dist/core/Dispatcher.js +116 -1149
  19. package/dist/core/Dispatcher.js.map +1 -1
  20. package/dist/core/Engine.d.ts +24 -34
  21. package/dist/core/Engine.d.ts.map +1 -1
  22. package/dist/core/Engine.js +137 -1672
  23. package/dist/core/Engine.js.map +1 -1
  24. package/dist/core/Engine.sql +46 -32
  25. package/dist/core/ExecutableTools.d.ts +1 -0
  26. package/dist/core/ExecutableTools.d.ts.map +1 -1
  27. package/dist/core/ExecutableTools.js +17 -9
  28. package/dist/core/ExecutableTools.js.map +1 -1
  29. package/dist/core/ExecutorRegistry.d.ts +11 -3
  30. package/dist/core/ExecutorRegistry.d.ts.map +1 -1
  31. package/dist/core/ExecutorRegistry.js +139 -16
  32. package/dist/core/ExecutorRegistry.js.map +1 -1
  33. package/dist/core/LogBody.d.ts +1 -0
  34. package/dist/core/LogBody.d.ts.map +1 -1
  35. package/dist/core/LogBody.js +4 -0
  36. package/dist/core/LogBody.js.map +1 -1
  37. package/dist/core/ModelCall.d.ts +2 -2
  38. package/dist/core/ModelCall.d.ts.map +1 -1
  39. package/dist/core/ModelCall.js +4 -2
  40. package/dist/core/ModelCall.js.map +1 -1
  41. package/dist/core/PacketBuilder.d.ts +11 -22
  42. package/dist/core/PacketBuilder.d.ts.map +1 -1
  43. package/dist/core/PacketBuilder.js +90 -180
  44. package/dist/core/PacketBuilder.js.map +1 -1
  45. package/dist/core/ProblemLog.d.ts +1 -1
  46. package/dist/core/ProblemLog.d.ts.map +1 -1
  47. package/dist/core/ProblemLog.js +14 -3
  48. package/dist/core/ProblemLog.js.map +1 -1
  49. package/dist/core/ProposalLifecycle.d.ts +4 -2
  50. package/dist/core/ProposalLifecycle.d.ts.map +1 -1
  51. package/dist/core/ProposalLifecycle.js +19 -7
  52. package/dist/core/ProposalLifecycle.js.map +1 -1
  53. package/dist/core/ProviderInstantiate.js +2 -2
  54. package/dist/core/ProviderInstantiate.js.map +1 -1
  55. package/dist/core/ResourceMutations.d.ts +73 -0
  56. package/dist/core/ResourceMutations.d.ts.map +1 -0
  57. package/dist/core/ResourceMutations.js +1142 -0
  58. package/dist/core/ResourceMutations.js.map +1 -0
  59. package/dist/core/SchemeRegistry.d.ts +18 -10
  60. package/dist/core/SchemeRegistry.d.ts.map +1 -1
  61. package/dist/core/SchemeRegistry.js +195 -43
  62. package/dist/core/SchemeRegistry.js.map +1 -1
  63. package/dist/core/StoredPacket.d.ts +2 -2
  64. package/dist/core/StoredPacket.js +7 -7
  65. package/dist/core/TurnRunner.d.ts +74 -0
  66. package/dist/core/TurnRunner.d.ts.map +1 -0
  67. package/dist/core/TurnRunner.js +1733 -0
  68. package/dist/core/TurnRunner.js.map +1 -0
  69. package/dist/core/WorkspaceGate.d.ts +1 -0
  70. package/dist/core/WorkspaceGate.d.ts.map +1 -1
  71. package/dist/core/WorkspaceGate.js +39 -0
  72. package/dist/core/WorkspaceGate.js.map +1 -1
  73. package/dist/core/caps/CoreInteractionCaps.d.ts +9 -0
  74. package/dist/core/caps/CoreInteractionCaps.d.ts.map +1 -0
  75. package/dist/core/caps/CoreInteractionCaps.js +14 -0
  76. package/dist/core/caps/CoreInteractionCaps.js.map +1 -0
  77. package/dist/core/caps/DbChannelCaps.js +4 -4
  78. package/dist/core/caps/DbChannelCaps.js.map +1 -1
  79. package/dist/core/caps/SchemeCtxImpl.d.ts +2 -1
  80. package/dist/core/caps/SchemeCtxImpl.d.ts.map +1 -1
  81. package/dist/core/caps/SchemeCtxImpl.js +3 -0
  82. package/dist/core/caps/SchemeCtxImpl.js.map +1 -1
  83. package/dist/core/content-hash.js +2 -2
  84. package/dist/core/content-hash.js.map +1 -1
  85. package/dist/core/content-weight.d.ts +2 -0
  86. package/dist/core/content-weight.d.ts.map +1 -0
  87. package/dist/core/content-weight.js +4 -0
  88. package/dist/core/content-weight.js.map +1 -0
  89. package/dist/core/content_weight.d.ts +4 -0
  90. package/dist/core/content_weight.d.ts.map +1 -0
  91. package/dist/core/content_weight.js +6 -0
  92. package/dist/core/content_weight.js.map +1 -0
  93. package/dist/core/fork.sql +5 -5
  94. package/dist/core/packet-wire.d.ts +4 -4
  95. package/dist/core/packet-wire.d.ts.map +1 -1
  96. package/dist/core/packet-wire.js +21 -21
  97. package/dist/core/packet-wire.js.map +1 -1
  98. package/dist/core/scheme-types.d.ts +3 -2
  99. package/dist/core/scheme-types.d.ts.map +1 -1
  100. package/dist/core/scheme-types.js.map +1 -1
  101. package/dist/digest/Digest.js +1 -1
  102. package/dist/digest/Digest.js.map +1 -1
  103. package/dist/schemes/Exec.d.ts.map +1 -1
  104. package/dist/schemes/Exec.js +53 -15
  105. package/dist/schemes/Exec.js.map +1 -1
  106. package/dist/schemes/ExecOutputScheme.js +1 -1
  107. package/dist/schemes/ExecOutputScheme.js.map +1 -1
  108. package/dist/schemes/File.d.ts.map +1 -1
  109. package/dist/schemes/File.js +1 -1
  110. package/dist/schemes/File.js.map +1 -1
  111. package/dist/schemes/Log.d.ts.map +1 -1
  112. package/dist/schemes/Log.js +2 -2
  113. package/dist/schemes/Log.sql +2 -2
  114. package/dist/schemes/Worker.js +2 -2
  115. package/dist/schemes/Worker.js.map +1 -1
  116. package/dist/schemes/_entry-crud.js +4 -4
  117. package/dist/schemes/_entry-crud.js.map +1 -1
  118. package/dist/schemes/_entry-crud.sql +2 -2
  119. package/dist/schemes/_entry-find.d.ts +5 -5
  120. package/dist/schemes/_entry-find.d.ts.map +1 -1
  121. package/dist/schemes/_entry-find.js +29 -28
  122. package/dist/schemes/_entry-find.js.map +1 -1
  123. package/dist/schemes/_entry-manifest.js +4 -4
  124. package/dist/schemes/_entry-manifest.js.map +1 -1
  125. package/dist/schemes/_entry-ops.d.ts.map +1 -1
  126. package/dist/schemes/_entry-ops.js +3 -3
  127. package/dist/schemes/_entry-ops.js.map +1 -1
  128. package/dist/schemes/_entry-ops.sql +3 -3
  129. package/dist/server/Daemon.d.ts +20 -49
  130. package/dist/server/Daemon.d.ts.map +1 -1
  131. package/dist/server/Daemon.js +311 -908
  132. package/dist/server/Daemon.js.map +1 -1
  133. package/dist/server/DaemonModule.d.ts +31 -3
  134. package/dist/server/DaemonModule.d.ts.map +1 -1
  135. package/dist/server/DrainSupervisor.d.ts +117 -0
  136. package/dist/server/DrainSupervisor.d.ts.map +1 -0
  137. package/dist/server/DrainSupervisor.js +802 -0
  138. package/dist/server/DrainSupervisor.js.map +1 -0
  139. package/dist/server/client-input.d.ts +2 -0
  140. package/dist/server/client-input.d.ts.map +1 -1
  141. package/dist/server/client-input.js +12 -0
  142. package/dist/server/client-input.js.map +1 -1
  143. package/dist/server/lifecycle-recovery.sql +9 -0
  144. package/dist/server/logEntry.d.ts +1 -1
  145. package/dist/server/logEntry.js +1 -1
  146. package/dist/server/loopDocs.d.ts +1 -0
  147. package/dist/server/loopDocs.d.ts.map +1 -1
  148. package/dist/server/loopDocs.js +37 -8
  149. package/dist/server/loopDocs.js.map +1 -1
  150. package/dist/server/loopDocs.sql +10 -0
  151. package/dist/server/seam-entry-read.sql +2 -2
  152. package/dist/server/workspace-capabilities.sql +19 -0
  153. package/dist/service.js +1 -1
  154. package/dist/service.js.map +1 -1
  155. package/migrations/001_schema.sql +51 -10
  156. package/package.json +34 -33
  157. package/dist/core/ruler_count.d.ts +0 -4
  158. package/dist/core/ruler_count.d.ts.map +0 -1
  159. package/dist/core/ruler_count.js +0 -7
  160. package/dist/core/ruler_count.js.map +0 -1
  161. package/dist/core/token-ruler.d.ts +0 -2
  162. package/dist/core/token-ruler.d.ts.map +0 -1
  163. package/dist/core/token-ruler.js +0 -5
  164. package/dist/core/token-ruler.js.map +0 -1
@@ -0,0 +1,1733 @@
1
+ var _a;
2
+ import { PlurnkParser, PlurnkParseError, UNKNOWN_POSITION } from "@plurnk/plurnk-contracts";
3
+ import Owner from "./Owner.js";
4
+ const TERMINAL_SEND_SIGNALS = new Set([102, 200, 202, 300, 499]);
5
+ const comparePosition = (a, b) => a.line - b.line || a.column - b.column;
6
+ import Meta from "@plurnk/plurnk-meta";
7
+ import EntryCrud from "../schemes/_entry-crud.js";
8
+ import GitMembership from "./git-membership.js";
9
+ import GitState from "./git-state.js";
10
+ import WorkspaceSettings from "./workspace-settings.js";
11
+ import { editedSpan } from "../content/index.js";
12
+ import { promptPathname, promptLoopPrefix, renderTarget } from "./plurnk-uri.js";
13
+ import { readFile } from "node:fs/promises";
14
+ import { fileURLToPath } from "node:url";
15
+ import { randomUUID } from "node:crypto";
16
+ // Shared module imported by both Engine and bin/digest.ts, so wire
17
+ // projection and digest projection are structurally one function — no
18
+ // drift between wire and digest possible.
19
+ import PacketWire from "./packet-wire.js";
20
+ import Results, { OperationFailureError } from "./results.js";
21
+ import BranchReceipt from "./BranchReceipt.js";
22
+ import TerminalResult from "./TerminalResult.js";
23
+ import WorkerControlAddress from "./WorkerControlAddress.js";
24
+ import JournalTurn from "./JournalTurn.js";
25
+ import LogBody from "./LogBody.js";
26
+ import StrikeRail from "./StrikeRail.js";
27
+ import StoredPacket from "./StoredPacket.js";
28
+ import { observed, observedSync } from "../observe/spans.js";
29
+ import { OPS_DISPATCHED, PROVIDER_CALLS, recordCounter } from "../observe/metrics.js";
30
+ import { scheduleTurnOps } from "./turn-scheduler.js";
31
+ import { readOptimisticSettlementMs } from "./optimistic-settlement.js";
32
+ import ModelCall, { ModelCallPersistenceError, ProviderAccountingIntegrityError, } from "./ModelCall.js";
33
+ const RECORD_STREAM_MIMETYPES = new Set(["application/jsonl", "application/x-ndjson"]);
34
+ const baseMimetype = (mimetype) => mimetype.split(";", 1)[0].trim().toLowerCase();
35
+ // {§exec-stream} Active streams publish only independently meaningful units.
36
+ // Atomic documents wait for close; JSONL stops after its last complete record.
37
+ const streamPublicationEnd = (content, mimetype, cursor, closed) => {
38
+ const type = baseMimetype(mimetype);
39
+ if (closed || type.startsWith("text/"))
40
+ return content.length;
41
+ if (!RECORD_STREAM_MIMETYPES.has(type))
42
+ return cursor;
43
+ return Math.max(cursor, content.lastIndexOf("\n") + 1);
44
+ };
45
+ const ENGINE_PROBLEMS = Object.freeze({
46
+ max_commands_exceeded: {
47
+ status: 429,
48
+ code: "max-commands-exceeded",
49
+ detail: "Later operations were not executed because the turn exceeded its operation limit.",
50
+ },
51
+ idle_turn: {
52
+ status: 409,
53
+ code: "idle-turn",
54
+ detail: "`## SEND0 [102]` was emitted without an operation to continue from.",
55
+ },
56
+ });
57
+ // The prompt entry target - prompt:///<loop>/<N>, self-only ({§prompt-self-only}):
58
+ // the owner rides the owner_id column, the address carries only the loop coordinate.
59
+ const promptTarget = (loopSeq, turnSeq) => {
60
+ const storage = promptPathname(loopSeq, turnSeq);
61
+ return {
62
+ kind: "url", raw: `prompt://${storage}`,
63
+ scheme: "prompt", username: null, password: null,
64
+ hostname: null, port: null,
65
+ pathname: storage, query: null, fragment: null,
66
+ };
67
+ };
68
+ const assertOpenPaths = (value, source) => {
69
+ if (!Array.isArray(value) || value.some((path) => typeof path !== "string" || path.length === 0)) {
70
+ throw new TypeError(`${source}: expected an array of non-empty strings`);
71
+ }
72
+ return value;
73
+ };
74
+ const parsePromptAttributes = (encoded, source) => {
75
+ const attributes = JSON.parse(encoded);
76
+ if (attributes === null || typeof attributes !== "object" || Array.isArray(attributes)) {
77
+ throw new TypeError(`${source}: expected a JSON object`);
78
+ }
79
+ return attributes;
80
+ };
81
+ // Per-emission action ceiling — OFF by default. `-1` (or unset/non-positive) = no cap:
82
+ // every generated op dispatches. Runaway degeneration is a sampler concern (repetition penalty),
83
+ // not grounds to drop already-generated work. A positive value is an operator ceiling a
84
+ // workspace's maxCommands may tighten (min wins), never widen
85
+ // ({§operator-config-workspace-max-commands}).
86
+ const readMaxCommands = () => {
87
+ const raw = process.env.PLURNK_SERVICE_MAX_COMMANDS;
88
+ if (raw === undefined || raw.length === 0)
89
+ return Number.POSITIVE_INFINITY;
90
+ const n = Number.parseInt(raw, 10);
91
+ if (!Number.isFinite(n) || n < 1)
92
+ return Number.POSITIVE_INFINITY;
93
+ return n;
94
+ };
95
+ // PLURNK_SERVICE_FILES_ITEMS — the turn-0 catalog preview. null = off;
96
+ // -1 = the ordinary markerless page; positive N explicitly caps file rows. 0 / unset = off.
97
+ const normalizeFilesItems = (n) => (!Number.isFinite(n) || n === 0 ? null : n < 0 ? -1 : n);
98
+ const readFilesItems = () => {
99
+ const raw = process.env.PLURNK_SERVICE_FILES_ITEMS;
100
+ if (raw === undefined || raw.length === 0)
101
+ return null;
102
+ return normalizeFilesItems(Number.parseInt(raw, 10));
103
+ };
104
+ import { ProviderError, resolveActiveAlias, scopeEnvToAlias, } from "@plurnk/plurnk-providers";
105
+ import { validateGbnf } from "@plurnk/gbnf";
106
+ import ProviderInstantiate from "./ProviderInstantiate.js";
107
+ // A generated rail may constrain only the sampled continuation while the chat
108
+ // template contributes a prefix that llama-server preserves in its response.
109
+ // The artifact names the alternate root that composes those bytes for evidence
110
+ // grading; arbitrary grammars without the declaration retain their transport root.
111
+ const grammarConstraint = (grammar) => {
112
+ const declarations = [...grammar.matchAll(/^# @plurnk-response-root ([A-Za-z][A-Za-z0-9-]*)$/gm)];
113
+ if (declarations.length === 0)
114
+ return { transport: grammar, response: grammar };
115
+ if (declarations.length !== 1)
116
+ throw new Error("GBNF constraint declares multiple @plurnk-response-root values");
117
+ const responseRoot = declarations[0][1];
118
+ if (!grammar.split("\n").some((line) => line.startsWith(`${responseRoot} ::=`))) {
119
+ throw new Error(`GBNF constraint declares missing response root ${responseRoot}`);
120
+ }
121
+ const roots = [...grammar.matchAll(/^root ::= ([A-Za-z][A-Za-z0-9-]*)$/gm)];
122
+ if (roots.length !== 1)
123
+ throw new Error("GBNF constraint must declare exactly one simple root");
124
+ return {
125
+ transport: grammar,
126
+ response: grammar.replace(roots[0][0], `root ::= ${responseRoot}`),
127
+ };
128
+ };
129
+ const TOKEN_BUDGET_OVERFLOW_DETAIL = "Token Budget Overflow: Token Usage exceeded Token Ceiling. Newest log items were automatically FOLDed to fit within token budget. Curate the log and/or perform more conservatively scoped or chunked retrieval operations to recover.";
130
+ const curationOverflowFailure = (pressure) => Results.failure("engine:context", "token-budget-overflow", 413, TOKEN_BUDGET_OVERFLOW_DETAIL, {}, {
131
+ usage: pressure.weight,
132
+ ceiling: pressure.budget,
133
+ deficit: pressure.excess,
134
+ });
135
+ // Runtime normalization for a disposition the engine refuses or resolves as a
136
+ // continue after dispatch ({§send}). Every admitted emission itself ends in an
137
+ // explicit disposition SEND ({§emission-admission}).
138
+ const TURN_STATUS_IMPLICIT_CONTINUE = 102;
139
+ const INVALID_EMISSION_RECOVERY_MESSAGE = "Your previous response contained an unrecoverable syntax error. No operations were performed. Try again.";
140
+ const readEmissionAttempts = () => {
141
+ const raw = process.env.PLURNK_SERVICE_EMISSION_ATTEMPTS;
142
+ const value = Number.parseInt(raw ?? "", 10);
143
+ if (!Number.isInteger(value) || value < 1) {
144
+ throw new Error(`PLURNK_SERVICE_EMISSION_ATTEMPTS must be a positive integer; got ${raw}`);
145
+ }
146
+ return value;
147
+ };
148
+ // The wall's abort reason — runLoop branches a mid-turn teardown to the 504 terminal on it.
149
+ export const LOOP_TIMEOUT_REASON = "loop_timeout";
150
+ class TurnRunner {
151
+ #db;
152
+ #schemes;
153
+ #mimetypes;
154
+ #weighContent;
155
+ #notices;
156
+ #problems;
157
+ #strikes;
158
+ #packets;
159
+ #dispatcher;
160
+ #liveSubscriptions;
161
+ #streamEventNotify;
162
+ #wakeWorkerNotify;
163
+ #executors;
164
+ #loopSignal;
165
+ #interactions;
166
+ #warmWorkspace;
167
+ #dispatch;
168
+ #resolveWorkerProviderIdentity;
169
+ #gbnfCache = new Map();
170
+ constructor({ db, schemes, mimetypes, weigh, notices, problems, strikes, packets, dispatcher, liveSubscriptions, streamEventNotify, wakeWorkerNotify, executors, loopSignal, interactions, warmWorkspace, dispatch, resolveWorkerProviderIdentity, }) {
171
+ this.#db = db;
172
+ this.#schemes = schemes;
173
+ this.#mimetypes = mimetypes;
174
+ this.#weighContent = weigh;
175
+ this.#notices = notices;
176
+ this.#problems = problems;
177
+ this.#strikes = strikes;
178
+ this.#packets = packets;
179
+ this.#dispatcher = dispatcher;
180
+ this.#liveSubscriptions = liveSubscriptions;
181
+ this.#streamEventNotify = streamEventNotify;
182
+ this.#wakeWorkerNotify = wakeWorkerNotify;
183
+ this.#executors = executors;
184
+ this.#loopSignal = loopSignal;
185
+ this.#interactions = interactions;
186
+ this.#warmWorkspace = warmWorkspace;
187
+ this.#dispatch = dispatch;
188
+ this.#resolveWorkerProviderIdentity = resolveWorkerProviderIdentity;
189
+ }
190
+ // {§rail-truth-engine-verdict} — the verify GAP (a configured grammar @plurnk/gbnf can't
191
+ // parse): warn once per message, never per turn; the turn records railsVerdict "unverifiable".
192
+ static #railGapWarned = new Set();
193
+ static #warnRailVerdictGapOnce(message) {
194
+ if (_a.#railGapWarned.has(message))
195
+ return;
196
+ _a.#railGapWarned.add(message);
197
+ process.stderr.write(`plurnk-engine: rail verdict unavailable — the configured grammar did not parse in @plurnk/gbnf (${message})\n`);
198
+ }
199
+ static #requireGrammarEvidence(response) {
200
+ const evidence = response.grammarEvidence;
201
+ if (evidence === undefined) {
202
+ throw new Error("provider contract violation: configured GBNF response omitted grammar evidence");
203
+ }
204
+ const input = [...evidence.input];
205
+ if (!Number.isInteger(evidence.contentStart)
206
+ || evidence.contentStart < 0
207
+ || evidence.contentStart > input.length
208
+ || typeof evidence.transported !== "boolean"
209
+ || input.slice(evidence.contentStart).join("") !== response.assistant.content) {
210
+ throw new Error("provider contract violation: grammar evidence does not map exactly to assistant.content");
211
+ }
212
+ return evidence;
213
+ }
214
+ async #grammarConstraint(provider) {
215
+ // Resolve through the registered or active alias; ambiguity and load
216
+ // failures never degrade to unconstrained generation.
217
+ // {§grammar-enforcement-verified-at-boot}
218
+ const registered = ProviderInstantiate.aliasOf(provider);
219
+ const fallback = registered === undefined ? resolveActiveAlias(process.env)?.alias : undefined;
220
+ if (registered === undefined && fallback === undefined && Object.keys(process.env).some((k) => k.startsWith("PLURNK_PROVIDERS_GBNF_"))) {
221
+ throw new Error("GBNF constraint: provider has no registered alias and no active alias resolves, while per-alias PLURNK_PROVIDERS_GBNF_* constraints are configured");
222
+ }
223
+ const alias = registered ?? fallback ?? "";
224
+ const variant = scopeEnvToAlias(process.env, alias, ["PLURNK_PROVIDERS_GBNF"]).PLURNK_PROVIDERS_GBNF;
225
+ if (variant === undefined || variant === "" || variant === "0")
226
+ return undefined;
227
+ const hit = this.#gbnfCache.get(variant);
228
+ if (hit !== undefined)
229
+ return hit;
230
+ const path = variant.startsWith("/") || variant.startsWith(".")
231
+ ? variant
232
+ : fileURLToPath(import.meta.resolve(`@plurnk/plurnk-contracts/${variant}`));
233
+ const text = await readFile(path, "utf8"); // unresolvable/unreadable throws — a configured rail never silently degrades
234
+ const constraint = grammarConstraint(text);
235
+ this.#gbnfCache.set(variant, constraint);
236
+ process.stderr.write(`plurnk-engine: GBNF constraint: ${alias || "(bare)"} → ${variant} (${text.length} chars)\n`);
237
+ return constraint;
238
+ }
239
+ // A lineage's no-parent root; a root worker resolves to itself. Fail hard
240
+ // when corruption leaves a worker without one. {§worker-primary}
241
+ async #attemptAttributions(provider, context) {
242
+ const tags = Meta.composeAttributions(this.#schemes.attributions(context), this.#executors()?.attributions(context) ?? [], await this.#mimetypes.attributions(context), provider.attributions?.(context) ?? []);
243
+ return [...tags];
244
+ }
245
+ #providerAttributions(provider, context) {
246
+ return [...Meta.composeAttributions(provider.attributions?.(context) ?? [])];
247
+ }
248
+ static #providerFailure(error, signal) {
249
+ if (error instanceof ProviderError) {
250
+ return { status: error.problem.status, problem: error.problem };
251
+ }
252
+ if (signal?.aborted === true) {
253
+ const timedOut = signal.reason === LOOP_TIMEOUT_REASON;
254
+ return Results.failure("engine:provider", timedOut ? "provider-call-timeout" : "provider-call-cancelled", timedOut ? 504 : 499, timedOut
255
+ ? "The provider call was interrupted by the loop deadline."
256
+ : "The provider call was interrupted by loop cancellation.", {}, { stage: "provider-request", retryable: false });
257
+ }
258
+ console.error("Provider failed outside its Problem Details contract:", error);
259
+ return Results.failure("engine:provider", "provider-contract-violation", 502, "The provider failed without returning its required Problem Details.", {}, { stage: "provider-request", retryable: false });
260
+ }
261
+ async #runBareBatch({ statements, provider, turnId, modelCallSequenceStart, workspaceId, workerId, primaryWorkerId, loopSequence, turnSequence, signal, }) {
262
+ const prepared = [];
263
+ for (const [index, statement] of statements.entries()) {
264
+ const providerWorkerId = randomUUID();
265
+ const attributionContext = Object.freeze({
266
+ workspaceId: String(workspaceId),
267
+ workerId: providerWorkerId,
268
+ primaryWorkerId,
269
+ loop: loopSequence,
270
+ turn: turnSequence,
271
+ attempt: 1,
272
+ });
273
+ const attributions = this.#providerAttributions(provider, attributionContext);
274
+ const modelCall = await ModelCall.open(this.#db, {
275
+ turnId,
276
+ sequence: modelCallSequenceStart + index,
277
+ kind: "bare",
278
+ attributions,
279
+ model: provider.model,
280
+ });
281
+ prepared.push({ statement, modelCall, attributions, providerWorkerId });
282
+ }
283
+ const settlements = await Promise.allSettled(prepared.map(async ({ statement, modelCall, attributions, providerWorkerId }) => {
284
+ try {
285
+ const response = await observed("provider.generate", { model: provider.model, attempt: 1, kind: "bare" }, async (span) => {
286
+ try {
287
+ const generated = await provider.generate({
288
+ messages: [{ role: "user", content: statement.body }],
289
+ workerId: providerWorkerId,
290
+ primaryWorkerId,
291
+ signal,
292
+ attributions: attributions.length > 0 ? attributions : undefined,
293
+ workspaceId: String(workspaceId),
294
+ loop: loopSequence,
295
+ turn: turnSequence,
296
+ observeRequest: modelCall.observeRequest,
297
+ callKind: "bare",
298
+ });
299
+ modelCall.assertAccounting(generated.accounting);
300
+ recordCounter(PROVIDER_CALLS, {
301
+ model: provider.model,
302
+ attempt: 1,
303
+ status: "resolved",
304
+ });
305
+ span.setAttribute("status", "resolved");
306
+ return generated;
307
+ }
308
+ catch (error) {
309
+ if (error instanceof ProviderError) {
310
+ modelCall.assertAccounting(error.accounting);
311
+ }
312
+ throw error;
313
+ }
314
+ });
315
+ await modelCall.observeResponse(response);
316
+ return {
317
+ statement,
318
+ modelCallId: modelCall.id,
319
+ result: Results.assert({
320
+ status: 200,
321
+ content: response.assistant.content,
322
+ mimetype: "text/plain",
323
+ }),
324
+ };
325
+ }
326
+ catch (error) {
327
+ if (error instanceof ModelCallPersistenceError || error instanceof ProviderAccountingIntegrityError) {
328
+ throw error;
329
+ }
330
+ const failure = _a.#providerFailure(error, signal);
331
+ if (error instanceof ProviderError && error.attempt !== undefined) {
332
+ await modelCall.observeResponse(error.attempt, failure);
333
+ }
334
+ else {
335
+ await modelCall.fail(failure);
336
+ }
337
+ return { statement, modelCallId: modelCall.id, result: failure };
338
+ }
339
+ }));
340
+ const internalFailure = settlements.find((settlement) => settlement.status === "rejected");
341
+ if (internalFailure !== undefined)
342
+ throw internalFailure.reason;
343
+ signal?.throwIfAborted();
344
+ return settlements.map((settlement) => settlement.value);
345
+ }
346
+ // {§attribution} — reporting derives from exact provider-request evidence;
347
+ // malformed durable tags fail here instead of being silently filtered.
348
+ #offsetToLineColumn(content, offset) {
349
+ const cps = Array.from(content);
350
+ const clamped = Math.max(0, Math.min(offset, cps.length));
351
+ let line = 1;
352
+ let column = 0;
353
+ for (let i = 0; i < clamped; i++) {
354
+ if (cps[i] === "\n") {
355
+ line++;
356
+ column = 0;
357
+ }
358
+ else {
359
+ column++;
360
+ }
361
+ }
362
+ return { line, column };
363
+ }
364
+ async runTurn({ provider, childProvider = provider, messages, requirements = "", workspaceId, workerId, loopId, origin = "model", signal, onDispatch, turnNumber = 1, maxTurns = 50, invalidEmissionRecoveryEntryId, }) {
365
+ const allowInvalidEmissionRecovery = invalidEmissionRecoveryEntryId === null;
366
+ const transientOpenLogEntryId = typeof invalidEmissionRecoveryEntryId === "number"
367
+ ? invalidEmissionRecoveryEntryId
368
+ : null;
369
+ // === Turn-as-container model ===
370
+ //
371
+ // Turn rows are created at runTurn OPEN (status=102, placeholder
372
+ // packet) so things can be written into the turn before the model
373
+ // is called: the user prompt on turn 1; later, system signals or
374
+ // injected Notices on any turn. The turn is CLOSED at
375
+ // the end with the final packet + status + usage stats.
376
+ //
377
+ // sequence is "ordinal of stuff in this turn." Pre-model
378
+ // writes consume low indices; model ops continue from there.
379
+ const seqRow = await this.#db.engine_next_turn_sequence.get({ loop_id: loopId });
380
+ const seq = seqRow.next;
381
+ // loops.sequence is the loop's ordinal within the worker. Turn-0 foists that belong to the
382
+ // WORKER (manifest preview, AGENTS, operator docs) gate on the worker's first loop, not every loop's
383
+ // first turn ({§actor-boundary-catalog-preview}); per-loop foists such as
384
+ // {§prompt-entry} still fire each loop. Read once, turn-1 only.
385
+ const loopRow = seq === 1
386
+ ? await this.#db.engine_get_loop_prompt.get({ loop_id: loopId })
387
+ : undefined;
388
+ const workerFirstLoop = (loopRow?.sequence ?? 0) === 1;
389
+ const openRow = await this.#db.engine_open_turn.get({
390
+ loop_id: loopId, sequence: seq,
391
+ });
392
+ if (openRow === undefined)
393
+ throw new Error("Engine.runTurn: turn open returned no row");
394
+ const turnId = openRow.id;
395
+ // {§env-delta-log-pull} — establish a fresh worker's observation
396
+ // baseline immediately after its first turn opens. A fork already has
397
+ // its parent's cursor, so the NULL-guarded statement leaves it intact.
398
+ // Events committed after this statement belong to this or a later
399
+ // closed pull window; pre-existing state is read through the ordinary
400
+ // shared-world projections in this first packet.
401
+ await this.#db.engine_initialize_ambient_cursor.get({ workspace_id: workspaceId, worker_id: workerId });
402
+ // Threaded per turn, never engine state, so concurrent loops on
403
+ // different providers each read their own honest tokenizer values.
404
+ const systemCtx = {
405
+ db: this.#db, workspaceId, workerId, loopId, turnId,
406
+ writer: "plurnk",
407
+ signal: this.#loopSignal(loopId),
408
+ streamEventNotify: this.#streamEventNotify,
409
+ wakeWorkerNotify: this.#wakeWorkerNotify,
410
+ weigh: this.#weighContent,
411
+ mimetypes: this.#mimetypes,
412
+ defaultChannelFor: (s) => this.#schemes.defaultChannelFor(s, workspaceId),
413
+ pushNotice: (notice) => this.#notices.push(workspaceId, loopId, notice),
414
+ requestInteraction: (request) => this.#interactions.request(request, { workspaceId, workerId, loopId, turnId }, this.#loopSignal(loopId)),
415
+ };
416
+ // Pre-model writes. Each prompt the model has not seen yet becomes an
417
+ // actionless `prompt` log row whose target is its durable prompt:// entry:
418
+ // - Turn 1: loop.prompt is the initial user prompt.
419
+ // - Turn N>1: only if Engine.inject (or wake-on-completion via
420
+ // daemon.inject) wrote a prompt entry for this turn slot
421
+ // between turn N-1 and N. Inject writes directly to entries;
422
+ // we DON'T re-foist here for N>1.
423
+ // Model ops dispatch after these pre-model rows.
424
+ let nextActionIndex = 1;
425
+ const turnOpenPaths = [];
426
+ // {§worker-initialization-entry} — the worker's first turn opens with a kernel-authored initialization: a
427
+ // worked turn PLAN → the environment FINDs the foist ACTUALLY dispatches → SEND signal 102. Built
428
+ // from the real ops below (not a static print — we lean into the genuine echo paradigm) and
429
+ // written at sequence 1, so it reads first with the foisted results following.
430
+ const turnZeroMoves = [];
431
+ if (seq === 1) {
432
+ if (workerFirstLoop)
433
+ nextActionIndex = 2; // reserve sequence 1 for initialization
434
+ // Operator doc READs (PLURNK_SERVICE_MD_<ALIAS>, {§actor-boundary-doc-injection}). The docs were materialized
435
+ // as worker://plurnk/<entry> entries by the plurnk worker (LoopDocs, via the
436
+ // {§actor-boundary} keystone); foist a READ of each into THIS turn-0 so the model
437
+ // reads them inline. It sees only the READ — the materializing EDIT
438
+ // lives in the plurnk worker's log, never the model's.
439
+ // {§operator-config-workspace-md-docs} — env docs union the workspace's client docs; foist a READ of
440
+ // each materialized worker://plurnk/<alias>.md (LoopDocs materialized the same set).
441
+ const { mdDocs } = await WorkspaceSettings.read(this.#db, workspaceId);
442
+ // {§actor-boundary-doc-injection} — operator docs appear on the worker's first loop.
443
+ for (const doc of workerFirstLoop ? await WorkspaceSettings.resolveDocs(mdDocs) : []) {
444
+ const docTarget = {
445
+ kind: "url", raw: `worker://plurnk/${doc.entryName}`, scheme: "worker",
446
+ username: null, password: null, hostname: "plurnk", port: null,
447
+ pathname: `/${doc.entryName}`, query: null, fragment: null,
448
+ };
449
+ const docRead = {
450
+ op: "READ", suffix: "", signal: null, target: docTarget,
451
+ lineMarker: null, body: null, position: UNKNOWN_POSITION,
452
+ };
453
+ await this.#dispatch({
454
+ statement: docRead, workspaceId, workerId, loopId, turnId,
455
+ sequence: nextActionIndex, origin: "plurnk", onDispatch,
456
+ });
457
+ nextActionIndex++;
458
+ }
459
+ const promptRow = loopRow; // {§prompt-entry} — per-loop; fires every loop's turn 1
460
+ if (promptRow !== undefined && typeof promptRow.prompt === "string" && promptRow.prompt.length > 0) {
461
+ const openPaths = assertOpenPaths(JSON.parse(promptRow.open_paths), `Loop ${loopId} open_paths`);
462
+ const promptLoopSeq = promptRow.sequence; // the loop's per-worker sequence — model-facing, matching log coordinates (owner: the db id read as prompt/2/1)
463
+ const promptPath = promptTarget(promptLoopSeq, seq);
464
+ const entry = {
465
+ channels: { body: { content: promptRow.prompt, mimetype: "text/markdown" } },
466
+ attributes: { openPaths },
467
+ };
468
+ await EntryCrud.writeEntry(promptPath.pathname, entry, systemCtx, "prompt", workerId);
469
+ turnOpenPaths.push(...openPaths);
470
+ const promptLogId = await this.#writePromptLog({
471
+ workerId,
472
+ loopId,
473
+ turnId,
474
+ sequence: nextActionIndex,
475
+ target: promptPath,
476
+ content: promptRow.prompt,
477
+ });
478
+ onDispatch?.(promptLogId);
479
+ nextActionIndex++;
480
+ }
481
+ }
482
+ // {§prompt-loop-containment}: the loop contains every prompt that arrived
483
+ // while it ran. Publish each undelivered frame as a prompt row, oldest
484
+ // first, so rapid arrivals reach the model together exactly once.
485
+ {
486
+ const loopSeqRow = await this.#db.engine_loop_sequence.get({ loop_id: loopId });
487
+ const loopSeq = loopSeqRow?.sequence ?? loopId;
488
+ const prefix = promptLoopPrefix(loopSeq);
489
+ const undelivered = (await this.#db.drain_undelivered_prompts_for_loop.all({
490
+ owner_id: workerId,
491
+ pattern: `${prefix}%`,
492
+ prefix_len: prefix.length,
493
+ loop_id: loopId,
494
+ }))
495
+ .filter((r) => typeof r.content === "string" && r.content.length > 0);
496
+ for (const injectedRow of undelivered) {
497
+ const attributes = parsePromptAttributes(injectedRow.attributes, `Prompt ${injectedRow.pathname} attributes`);
498
+ const encodedOpenPaths = attributes.openPaths;
499
+ if (encodedOpenPaths !== undefined) {
500
+ turnOpenPaths.push(...assertOpenPaths(encodedOpenPaths, `Prompt ${injectedRow.pathname} openPaths`));
501
+ }
502
+ const ordinal = Number(injectedRow.pathname.split("/").filter(Boolean).at(-1));
503
+ const injTarget = promptTarget(loopSeq, ordinal);
504
+ const promptLogId = await this.#writePromptLog({
505
+ workerId,
506
+ loopId,
507
+ turnId,
508
+ sequence: nextActionIndex,
509
+ target: injTarget,
510
+ content: injectedRow.content,
511
+ });
512
+ onDispatch?.(promptLogId);
513
+ nextActionIndex++;
514
+ }
515
+ }
516
+ // The persistent search-index pass (_search-index.maintain) attaches
517
+ // every readable entry/log projection to complete graph/FTS/vector derivations.
518
+ // NOT an action: no log entry, no sequence slot,
519
+ // not dispatched. There is no materialized manifest entry — the catalog
520
+ // is served on demand by FIND: recursive when asked, shallow-mapped below.
521
+ // {§semantic-embed-dedup} — one pass-wide semantic plan binds every
522
+ // chunk counter to the derivation identity it produces.
523
+ // SPEC {§membership} D4/D5 — git-ls-files workspace membership, resolved at
524
+ // prompt-composition (EMI is eager + exhaustive — git is the only bound). When the
525
+ // workspace's project_root is a git working tree, tracked files are
526
+ // members without a client `add`; active members are materialized
527
+ // (disk → body channel) so they appear in the catalog. No-ops
528
+ // on headless / non-git workspaces. Runs BEFORE the derivation pump so
529
+ // this turn's packet reflects them.
530
+ // Workspace creation starts this eagerly. Joining here is the correctness
531
+ // boundary: the model never runs against partial graph/vector coverage.
532
+ await this.#warmWorkspace(systemCtx, false);
533
+ // The warm materialized membership before deriving. This second pass is the
534
+ // ordinary cheap change detector and captures any drift that landed meanwhile.
535
+ const fsDivergences = await GitMembership.indexGitMembership(systemCtx);
536
+ // {§packet-git-status} — one post-reconciliation snapshot supplies both
537
+ // the compact packet summary and each causal file event's exact XY state.
538
+ const gitStatus = await GitState.status(this.#db, workspaceId, this.#loopSignal(loopId));
539
+ await this.#logFsFictions(workspaceId, fsDivergences, gitStatus);
540
+ // The refresh above may have changed bodies (including model/client edits
541
+ // since the startup warm). Re-derive to completion before packet/model
542
+ // construction. Membership is already current, so this pass does not
543
+ // consume the filesystem divergences a second time.
544
+ await this.#warmWorkspace(systemCtx, true, false);
545
+ // Turn-0 catalog preview (PLURNK_SERVICE_FILES_ITEMS, {§actor-boundary-catalog-preview}):
546
+ // Four FIND surveys foisted into the worker's first model turn establish the project,
547
+ // commons, private, and documentation surfaces in that order. Their `init`
548
+ // classification lets the model curate this opening survey as one log set.
549
+ if (seq === 1) {
550
+ // {§operator-config-workspace-files-items} — workspace filesItems replaces the env default.
551
+ const { filesItems: workspaceMI } = await WorkspaceSettings.read(this.#db, workspaceId);
552
+ const filesItems = workspaceMI !== null ? normalizeFilesItems(workspaceMI) : readFilesItems();
553
+ if (filesItems !== null && workerFirstLoop) { // {§actor-boundary-catalog-preview} — once per worker
554
+ const catalogSchemes = await this.#db.engine_scheme_catalog_summary.all({ workspace_id: workspaceId });
555
+ const fileItems = catalogSchemes.find(({ scheme }) => scheme === "file")?.shallow_items ?? 0;
556
+ const fileCap = filesItems > 0 && fileItems > 0 ? Math.min(filesItems, fileItems) : null;
557
+ await Owner.kernelId(this.#db, workspaceId);
558
+ const surveys = [
559
+ {
560
+ statement: {
561
+ op: "FIND", suffix: "", signal: ["+init"],
562
+ target: { kind: "local", raw: "*" },
563
+ body: null,
564
+ lineMarker: fileCap === null ? null : { marks: [1, fileCap] },
565
+ position: UNKNOWN_POSITION,
566
+ },
567
+ exemplar: `## FIND0 [+init] (*)${fileCap === null ? "" : ` <1,${fileCap}>`}`,
568
+ },
569
+ {
570
+ statement: {
571
+ op: "FIND", suffix: "", signal: ["+init"],
572
+ target: { kind: "url", raw: "worker:///*", scheme: "worker", username: null, password: null, hostname: null, port: null, pathname: "/*", query: null, fragment: null },
573
+ body: null, lineMarker: null, position: UNKNOWN_POSITION,
574
+ },
575
+ exemplar: "## FIND0 [+init] (worker:///*)",
576
+ },
577
+ {
578
+ statement: {
579
+ op: "FIND", suffix: "", signal: ["+init"],
580
+ target: { kind: "url", raw: "worker://~/*", scheme: "worker", username: null, password: null, hostname: "~", port: null, pathname: "/*", query: null, fragment: null },
581
+ body: null, lineMarker: null, position: UNKNOWN_POSITION,
582
+ },
583
+ exemplar: "## FIND0 [+init] (worker://~/*)",
584
+ },
585
+ {
586
+ statement: {
587
+ op: "FIND", suffix: "", signal: ["+init", "+docs"],
588
+ target: { kind: "url", raw: "worker://plurnk/docs/**", scheme: "worker", username: null, password: null, hostname: "plurnk", port: null, pathname: "/docs/**", query: null, fragment: null },
589
+ body: null, lineMarker: { marks: [1, -1] }, position: UNKNOWN_POSITION,
590
+ },
591
+ exemplar: "## FIND0 [+init,+docs] (worker://plurnk/docs/**) <1,-1>",
592
+ },
593
+ ];
594
+ for (const { statement, exemplar } of surveys) {
595
+ await this.#dispatch({ statement, workspaceId, workerId, loopId, turnId, sequence: nextActionIndex, origin: "plurnk", onDispatch });
596
+ nextActionIndex++;
597
+ turnZeroMoves.push(exemplar);
598
+ }
599
+ }
600
+ // {§worker-initialization-entry} — write the kernel's turn-0 initialization OPEN at sequence 1: PLAN → the FINDs actually
601
+ // foisted above (real, their results already in the log) → SEND signal 102. Dynamic — it reflects
602
+ // the true survey, never a frozen print — and OPEN: the worked example the model orients on,
603
+ // so the grammar can stay thin.
604
+ if (workerFirstLoop) {
605
+ const initialization = [
606
+ "# PLAN0\n* Initialization complete.\n* Next: address the prompt.",
607
+ ...turnZeroMoves,
608
+ "## SEND0 [102]\nNext, address the prompt.",
609
+ ].join("\n\n");
610
+ await this.#dispatcher.writeInitializationEntry({ verbatim: initialization, workerId, loopId, turnId, sequence: 1 });
611
+ }
612
+ }
613
+ // {§methods-loop-run-open-paths}: selected workspace paths belong to
614
+ // the prompt frame. Publish the frame, then dispatch ordinary core READs
615
+ // in that same turn; missing/non-member paths retain their normal 4xx.
616
+ for (const raw of turnOpenPaths) {
617
+ const pathname = raw.startsWith("/") ? raw : `/${raw}`;
618
+ const fileRead = {
619
+ op: "READ", suffix: "", signal: null, lineMarker: null,
620
+ target: {
621
+ kind: "url", raw: `file://${pathname}`, scheme: "file",
622
+ username: null, password: null, hostname: null, port: null,
623
+ pathname, query: null, fragment: null,
624
+ },
625
+ body: null, position: UNKNOWN_POSITION,
626
+ };
627
+ await this.#dispatch({
628
+ statement: fileRead, workspaceId, workerId, loopId, turnId,
629
+ sequence: nextActionIndex, origin: "plurnk", onDispatch,
630
+ });
631
+ nextActionIndex++;
632
+ }
633
+ // {§env-delta-log-pull} — materialize ambient observations before packet
634
+ // composition and reserve their action indices. {§exec-stream} owns the
635
+ // distinct byte-cursor path for this worker's streams.
636
+ // {§exec-poll} — EXEC `<0>` is turn-scoped: reap the worker's open turn-scoped streams (necessarily
637
+ // from a prior turn — this runs before the turn's own spawns) so a `<0>` never survives into
638
+ // the subsequent turn. The terminal output then surfaces born-OPEN via the stream-delta path.
639
+ await this.#reapTurnScopedStreams(workerId);
640
+ nextActionIndex += await this.#materializeEnvironmentDeltas({ workspaceId, workerId, loopId, turnId, fromSequence: nextActionIndex });
641
+ nextActionIndex += await this.#materializeStreamDeltas({ workspaceId, workerId, loopId, turnId, fromSequence: nextActionIndex });
642
+ // The post-reconciliation Git snapshot above is threaded into the packet
643
+ // and every budget rebuild; overflow never shells again.
644
+ // Notices are non-terminal observations, never operation-failure truth.
645
+ // Drain once and thread the same set through every grinder rebuild.
646
+ const notices = this.#notices.drain(loopId)
647
+ .filter((event) => event.level !== "info");
648
+ // Build the model request packet ({§packet-stored-shape}). The log build
649
+ // queries log_entries scoped to the worker — the prompt entry just
650
+ // written (if turn 1) is part of that query result.
651
+ let promptProjection = "automatic";
652
+ const buildPacket = () => this.#packets.buildRequestPacket({
653
+ initialMessages: messages,
654
+ requirements,
655
+ workspaceId,
656
+ workerId,
657
+ loopId,
658
+ currentTurnSeq: seq,
659
+ provider,
660
+ gitStatus,
661
+ notices,
662
+ transientOpenLogEntryId,
663
+ promptProjection,
664
+ });
665
+ let requestPacket = await buildPacket();
666
+ // SPEC {§grinder} — budget grinder, pre-LLM: reclaim window on actual overflow.
667
+ const enforced = await this.#packets.enforceBudget({
668
+ packet: requestPacket, provider, loopId, turnId,
669
+ recordOverflow: async (pressure) => {
670
+ await this.#problems.record({
671
+ workerId,
672
+ loopId,
673
+ turnId,
674
+ sequence: nextActionIndex++,
675
+ origin: "plurnk",
676
+ source: "engine",
677
+ result: curationOverflowFailure(pressure),
678
+ });
679
+ },
680
+ rebuild: buildPacket,
681
+ });
682
+ requestPacket = enforced.packet;
683
+ let boundaryRolledBack = enforced.boundaryRolledBack;
684
+ let modelMessages = PacketWire.packetToWireMessages(requestPacket);
685
+ // Curation pressure and provider generation are independent. The
686
+ // provider owns its configured total output envelope.
687
+ let response;
688
+ let splitResponse;
689
+ let railGrammar;
690
+ let railResponseGrammar;
691
+ let railEvidence;
692
+ let emissionAttempts = 0;
693
+ let providerCallInFlight = false;
694
+ let modelCallSequence = 0;
695
+ let currentEmissionAttempt = 0;
696
+ let providerAttemptId = null;
697
+ let providerModelCall = null;
698
+ let providerAttemptAttributions = [];
699
+ const providerSignal = this.#loopSignal(loopId) ?? signal;
700
+ // {§client-metadata}
701
+ const { client } = await WorkspaceSettings.read(this.#db, workspaceId);
702
+ const loopSeq = (await this.#db.engine_loop_sequence.get({ loop_id: loopId }))?.sequence ?? loopId;
703
+ const providerIdentity = await this.#resolveWorkerProviderIdentity(workerId);
704
+ const { workerId: providerWorkerId, primaryWorkerId } = providerIdentity;
705
+ const classifyProviderAttempt = async (id, attemptSplit, emissionAttempt, accepted) => {
706
+ const result = await this.#db.engine_classify_turn_attempt_response.run({
707
+ id,
708
+ accepted: accepted ? 1 : 0,
709
+ parse_errors: JSON.stringify(attemptSplit.parseErrors),
710
+ });
711
+ if (result.changes !== 1) {
712
+ throw new Error(`emission attempt ${id} was not awaiting classification`);
713
+ }
714
+ emissionAttempts = emissionAttempt;
715
+ };
716
+ const recoverCapacityPacket = async () => {
717
+ let baselineMessages = modelMessages;
718
+ if (promptProjection === "automatic") {
719
+ promptProjection = "withheld";
720
+ const candidate = await buildPacket();
721
+ const candidateMessages = PacketWire.packetToWireMessages(candidate);
722
+ if (JSON.stringify(candidateMessages) !== JSON.stringify(baselineMessages)) {
723
+ requestPacket = candidate;
724
+ modelMessages = candidateMessages;
725
+ return true;
726
+ }
727
+ baselineMessages = candidateMessages;
728
+ }
729
+ if (!boundaryRolledBack) {
730
+ await this.#packets.rollbackNewestBoundary(loopId, turnId);
731
+ boundaryRolledBack = true;
732
+ const candidate = await buildPacket();
733
+ const candidateMessages = PacketWire.packetToWireMessages(candidate);
734
+ if (JSON.stringify(candidateMessages) !== JSON.stringify(baselineMessages)) {
735
+ requestPacket = candidate;
736
+ modelMessages = candidateMessages;
737
+ return true;
738
+ }
739
+ }
740
+ return false;
741
+ };
742
+ try {
743
+ // {§turn-lifecycle}: bracket the complete provider-attempt window with liveness notices.
744
+ if (!signal?.aborted)
745
+ this.#notices.push(workspaceId, loopId, { source: "engine:turn", kind: "turn_awaiting_model", level: "info", message: "awaiting model response" });
746
+ const railConstraint = await this.#grammarConstraint(provider);
747
+ railGrammar = railConstraint?.transport;
748
+ railResponseGrammar = railConstraint?.response;
749
+ const attemptLimit = readEmissionAttempts();
750
+ const strikeStreak = this.#strikes.streak(loopId);
751
+ for (let attempt = 1; attempt <= attemptLimit;) {
752
+ // Capacity recovery may rebuild and resend the request without
753
+ // consuming a grammar-emission attempt. Every logical provider
754
+ // call still receives its own durable sequence and accounting.
755
+ currentEmissionAttempt = attempt;
756
+ modelCallSequence++;
757
+ const attributionContext = Object.freeze({
758
+ workspaceId: String(workspaceId),
759
+ workerId: providerWorkerId,
760
+ primaryWorkerId,
761
+ loop: loopSeq,
762
+ turn: seq,
763
+ attempt: modelCallSequence,
764
+ });
765
+ providerAttemptAttributions = await this.#attemptAttributions(provider, attributionContext);
766
+ requestPacket = { ...requestPacket, attributions: providerAttemptAttributions };
767
+ providerModelCall = await ModelCall.open(this.#db, {
768
+ turnId,
769
+ sequence: modelCallSequence,
770
+ kind: "emission",
771
+ attributions: providerAttemptAttributions,
772
+ model: provider.model,
773
+ });
774
+ const attemptRow = await this.#db.engine_open_turn_attempt.get({
775
+ model_call_id: providerModelCall.id,
776
+ });
777
+ if (attemptRow === undefined) {
778
+ throw new Error(`Engine.runTurn: provider call ${modelCallSequence} did not open`);
779
+ }
780
+ providerAttemptId = attemptRow.id;
781
+ providerCallInFlight = true;
782
+ const currentModelCall = providerModelCall;
783
+ let completedResponse;
784
+ try {
785
+ completedResponse = await observed(// {§observability-boundary}
786
+ "provider.generate", { model: provider.model, attempt: modelCallSequence }, async (span) => {
787
+ try {
788
+ const generated = await provider.generate({
789
+ messages: modelMessages,
790
+ workerId: providerWorkerId,
791
+ primaryWorkerId,
792
+ signal: providerSignal,
793
+ grammar: railGrammar,
794
+ strikes: strikeStreak,
795
+ attributions: providerAttemptAttributions.length > 0
796
+ ? providerAttemptAttributions
797
+ : undefined,
798
+ client: client ?? undefined,
799
+ workspaceId: String(workspaceId),
800
+ loop: loopSeq,
801
+ turn: seq,
802
+ observeRequest: currentModelCall.observeRequest,
803
+ callKind: "emission",
804
+ }); // {§provider-surface-generate} {§provider-guarantees-signal-wired} {§provider-guarantees-serial-attempts} {§attribution} {§client-metadata}
805
+ currentModelCall.assertAccounting(generated.accounting);
806
+ providerCallInFlight = false;
807
+ recordCounter(PROVIDER_CALLS, {
808
+ model: provider.model,
809
+ attempt: modelCallSequence,
810
+ status: "resolved",
811
+ });
812
+ span.setAttribute("status", "resolved");
813
+ return generated;
814
+ }
815
+ catch (error) {
816
+ if (error instanceof ProviderError) {
817
+ currentModelCall.assertAccounting(error.accounting);
818
+ }
819
+ throw error;
820
+ }
821
+ });
822
+ }
823
+ catch (error) {
824
+ if (!(error instanceof ProviderError)
825
+ || error.kind !== "capacity_exceeded"
826
+ || providerSignal?.aborted === true
827
+ || !await recoverCapacityPacket()) {
828
+ throw error;
829
+ }
830
+ const failure = _a.#providerFailure(error, providerSignal);
831
+ await currentModelCall.fail(failure, error.capacity ?? null);
832
+ providerCallInFlight = false;
833
+ await this.#problems.record({
834
+ workerId,
835
+ loopId,
836
+ turnId,
837
+ sequence: nextActionIndex++,
838
+ origin: "plurnk",
839
+ source: "provider",
840
+ result: failure,
841
+ });
842
+ // Include the durable recovery signal in the replacement
843
+ // request while preserving the selected recovery posture.
844
+ requestPacket = await buildPacket();
845
+ modelMessages = PacketWire.packetToWireMessages(requestPacket);
846
+ continue;
847
+ }
848
+ response = completedResponse;
849
+ await currentModelCall.observeResponse(completedResponse);
850
+ railEvidence = railGrammar === undefined
851
+ ? undefined
852
+ : _a.#requireGrammarEvidence(completedResponse);
853
+ splitResponse = this.#splitResponse(completedResponse);
854
+ await classifyProviderAttempt(attemptRow.id, splitResponse, attempt, splitResponse.emissionValid);
855
+ if (splitResponse.emissionValid)
856
+ break;
857
+ attempt++;
858
+ }
859
+ if (!signal?.aborted)
860
+ this.#notices.push(workspaceId, loopId, { source: "engine:turn", kind: "turn_generated", level: "info", message: "parsing model response" });
861
+ }
862
+ catch (err) {
863
+ // This handler owns only provider-call failures. Parser, cost, SQL,
864
+ // and engine-contract failures retain their original source.
865
+ if (err instanceof ModelCallPersistenceError || err instanceof ProviderAccountingIntegrityError)
866
+ throw err;
867
+ if (!providerCallInFlight)
868
+ throw err;
869
+ providerCallInFlight = false;
870
+ if (providerAttemptId === null || providerModelCall === null) {
871
+ throw new Error("provider call failed without durable model-call and attempt identities", { cause: err });
872
+ }
873
+ const failure = _a.#providerFailure(err, providerSignal);
874
+ const capacityFailure = err instanceof ProviderError && err.kind === "capacity_exceeded";
875
+ // {§provider-interrupted-attempt} — a provider-declared interruption
876
+ // carries response evidence without becoming a completed exchange.
877
+ // Persist it as an unaccepted attempt before settling the failure.
878
+ if (err instanceof ProviderError && err.attempt !== undefined) {
879
+ response = err.attempt;
880
+ await providerModelCall.observeResponse(response, failure);
881
+ splitResponse = this.#splitResponse(response);
882
+ await classifyProviderAttempt(providerAttemptId, splitResponse, currentEmissionAttempt, false);
883
+ }
884
+ else {
885
+ await providerModelCall.fail(failure, err instanceof ProviderError ? err.capacity ?? null : null);
886
+ if (!capacityFailure)
887
+ emissionAttempts = currentEmissionAttempt;
888
+ }
889
+ // {§turn-never-blank} — a ProviderError means no completed exchange exists.
890
+ // Persist its exact RFC 9457 result before propagating it. Grammar evidence
891
+ // and its engine-owned verdict exist only on completed responses
892
+ // ({§rail-truth-engine-verdict}). Cancellation is lifecycle truth, not a
893
+ // provider failure. Close the
894
+ // attempted turn without inventing an assistant response, then let
895
+ // runLoop/Daemon settle the exact 504/499 loop result.
896
+ if (providerSignal?.aborted) {
897
+ await this.#db.engine_close_turn.run({
898
+ id: turnId,
899
+ status: providerSignal.reason === LOOP_TIMEOUT_REASON ? 504 : 499,
900
+ packet: StoredPacket.stringify(requestPacket),
901
+ usage_curation_budget: this.#packets.curationBudgetFor(provider),
902
+ finish_reason: splitResponse?.callMetadata.finishReason ?? null,
903
+ model: splitResponse?.callMetadata.model ?? provider.model,
904
+ meta: JSON.stringify(response?.meta ?? {}),
905
+ });
906
+ throw err;
907
+ }
908
+ const recorded = await this.#problems.record({
909
+ workerId,
910
+ loopId,
911
+ turnId,
912
+ sequence: nextActionIndex,
913
+ origin: "plurnk",
914
+ source: "provider",
915
+ result: failure,
916
+ });
917
+ // The provider call was attempted, but no completed exchange exists.
918
+ // Persist the exact request half and failure status; omitting assistant
919
+ // is materially different from fabricating an empty model turn.
920
+ await this.#db.engine_close_turn.run({
921
+ id: turnId,
922
+ status: recorded.result.status,
923
+ packet: StoredPacket.stringify(requestPacket),
924
+ usage_curation_budget: this.#packets.curationBudgetFor(provider),
925
+ finish_reason: splitResponse?.callMetadata.finishReason ?? null,
926
+ model: splitResponse?.callMetadata.model ?? provider.model,
927
+ meta: JSON.stringify(response?.meta ?? {}),
928
+ });
929
+ if (capacityFailure) {
930
+ return {
931
+ turnId,
932
+ status: recorded.result.status,
933
+ outcomes: [],
934
+ fingerprint: "",
935
+ capacityHardStop: true,
936
+ capacityFailure: recorded.result,
937
+ steerStruck: false,
938
+ emissionAttempts,
939
+ emissionExhausted: false,
940
+ };
941
+ }
942
+ throw new OperationFailureError(recorded.result, { cause: err });
943
+ }
944
+ if (response === undefined || splitResponse === undefined || providerModelCall === null) {
945
+ throw new Error("provider attempt loop completed without a response");
946
+ }
947
+ const emissionModelCallId = providerModelCall.id;
948
+ if (!splitResponse.emissionValid) {
949
+ // {§invalid-emission-attempts} The first consecutive exhaustion
950
+ // publishes only the raw final response and generic recovery fact.
951
+ let rejectedModelEntryId;
952
+ if (allowInvalidEmissionRecovery) {
953
+ rejectedModelEntryId = await this.#dispatcher.writeModelEntry({
954
+ verbatim: splitResponse.packetAssistant.content,
955
+ workerId,
956
+ loopId,
957
+ turnId,
958
+ sequence: nextActionIndex,
959
+ folded: true,
960
+ modelCallId: emissionModelCallId,
961
+ admission: "rejected",
962
+ });
963
+ this.#notices.push(workspaceId, loopId, {
964
+ source: "engine:grammar",
965
+ kind: "invalid_emission",
966
+ level: "error",
967
+ message: INVALID_EMISSION_RECOVERY_MESSAGE,
968
+ });
969
+ }
970
+ await this.#db.engine_close_turn.run({
971
+ id: turnId,
972
+ status: allowInvalidEmissionRecovery ? TURN_STATUS_IMPLICIT_CONTINUE : 500,
973
+ packet: StoredPacket.stringify(requestPacket),
974
+ usage_curation_budget: this.#packets.curationBudgetFor(provider),
975
+ finish_reason: splitResponse.callMetadata.finishReason,
976
+ model: splitResponse.callMetadata.model,
977
+ meta: JSON.stringify(response.meta ?? {}),
978
+ });
979
+ return {
980
+ turnId,
981
+ status: allowInvalidEmissionRecovery ? TURN_STATUS_IMPLICIT_CONTINUE : 500,
982
+ outcomes: [],
983
+ fingerprint: "",
984
+ capacityHardStop: false,
985
+ steerStruck: false,
986
+ emissionAttempts,
987
+ emissionExhausted: true,
988
+ ...(rejectedModelEntryId === undefined ? {} : { rejectedModelEntryId }),
989
+ };
990
+ }
991
+ // {§packet-stored-shape} — admitted emission data extends the packet;
992
+ // provider-call metadata remains on the Turn row.
993
+ const { packetAssistant, callMetadata, parseNotices, recoverableParseErrors, } = splitResponse; // raw assistant content is opaque — split, never interpreted — {§provider-guarantees-assistantraw-opaque}
994
+ for (const notice of parseNotices) {
995
+ this.#notices.push(workspaceId, loopId, notice);
996
+ }
997
+ // Non-fatal provider transport notices on an accepted turn. Forward each
998
+ // Notice with a content-offset `line:col`;
999
+ // the model resolves it against its own emission — READ the folded model-emission row at the
1000
+ // cited lines ({§model-entry}) — not an embedded snippet that would duplicate the emission.
1001
+ for (const notice of response.notices ?? []) {
1002
+ const located = typeof notice.position === "number"
1003
+ ? this.#offsetToLineColumn(packetAssistant.content, notice.position)
1004
+ : null;
1005
+ this.#notices.push(workspaceId, loopId, {
1006
+ source: notice.source,
1007
+ kind: notice.kind,
1008
+ message: notice.message ?? "",
1009
+ level: notice.level,
1010
+ ...(located !== null
1011
+ ? { position: { type: "content-offset", line: located.line, column: located.column } }
1012
+ : {}),
1013
+ });
1014
+ }
1015
+ // Grade configured local evidence independently. Endpoint-owned
1016
+ // constraints remain provider observations. {§rail-truth-engine-verdict}
1017
+ let railKeys;
1018
+ if (railGrammar !== undefined) {
1019
+ if (railEvidence === undefined)
1020
+ throw new Error("configured GBNF response has no final grammar evidence");
1021
+ if (railResponseGrammar === undefined)
1022
+ throw new Error("configured GBNF has no response grammar");
1023
+ let verdict = null;
1024
+ try {
1025
+ verdict = validateGbnf(railResponseGrammar, railEvidence.input);
1026
+ }
1027
+ catch (cause) {
1028
+ _a.#warnRailVerdictGapOnce(cause.message);
1029
+ }
1030
+ railKeys = {
1031
+ railsAttached: railEvidence.transported ? "client" : "withheld",
1032
+ railsVerdict: verdict?.status ?? "unverifiable",
1033
+ };
1034
+ if (verdict !== null && verdict.status !== "accept") {
1035
+ const contentPosition = verdict.pos >= railEvidence.contentStart
1036
+ ? verdict.pos - railEvidence.contentStart
1037
+ : null;
1038
+ const located = contentPosition === null
1039
+ ? null
1040
+ : this.#offsetToLineColumn(packetAssistant.content, contentPosition);
1041
+ this.#notices.push(workspaceId, loopId, {
1042
+ source: "engine:rails",
1043
+ kind: "grammar_unenforced",
1044
+ message: verdict.status === "reject"
1045
+ ? `emission rejects the grammar at raw code point ${verdict.pos}`
1046
+ : `emission is an incomplete grammar sentence (ends at raw code point ${verdict.pos})`,
1047
+ level: "warn",
1048
+ ...(located === null
1049
+ ? {}
1050
+ : { position: { type: "content-offset", line: located.line, column: located.column } }),
1051
+ });
1052
+ }
1053
+ }
1054
+ const opsCount = packetAssistant.ops.length;
1055
+ const finalOp = packetAssistant.ops.at(-1);
1056
+ if (finalOp?.op !== "SEND") {
1057
+ // Text emissions cannot reach this point without a disposition;
1058
+ // this fail-hard guard also keeps Mock's trusted pre-parsed seam
1059
+ // from creating runtime states that production admission forbids.
1060
+ throw new Error("an admitted emission must end in a disposition SEND");
1061
+ }
1062
+ const dispositionSignal = finalOp.signal;
1063
+ if (typeof dispositionSignal !== "number" || !TERMINAL_SEND_SIGNALS.has(dispositionSignal)) {
1064
+ throw new Error("an admitted emission must end in a disposition SEND");
1065
+ }
1066
+ const sendOp = finalOp;
1067
+ // {§send} the terminal contract — engine error states verify a terminal claim against loop
1068
+ // state, never trusting the model's code. They strike via turn.steerStruck
1069
+ // ({§engine-rails}): the loop continues, the model sees the steering hint not the strike
1070
+ // count, and a non-resolver spins out to the engine's 500.
1071
+ let steerStruck = false;
1072
+ // Engine errors raised this turn, minted as op='error' log rows after dispatch (they share the
1073
+ // post-dispatch sequence counter). {§operation-result-uniform-error-channel}
1074
+ const pendingEngineErrors = [];
1075
+ // Terminal adjudication moved to the DISPATCHER ({§send-premature-terminate}, the unified
1076
+ // pending set): the terminal SEND is judged AT ITS OWN DISPATCH — after the emission's
1077
+ // earlier ops executed — so a same-turn KILL+[200] repairs in one turn and a same-turn
1078
+ // WORK+[200] is caught. A refused final disposition (409) strikes via
1079
+ // the dispatch-loop check below.
1080
+ let turnStatus = dispositionSignal;
1081
+ // Idle turn: an implicit-continue (102) that did no WORK — its ops are only PLAN/SEND, no mid op.
1082
+ // The model continued with nothing to do.
1083
+ const midOpsCount = packetAssistant.ops.filter((op) => op.op !== "PLAN" && op.op !== "SEND").length
1084
+ + recoverableParseErrors.length;
1085
+ if (!steerStruck && turnStatus === TURN_STATUS_IMPLICIT_CONTINUE && midOpsCount === 0) {
1086
+ steerStruck = true;
1087
+ pendingEngineErrors.push("idle_turn");
1088
+ }
1089
+ // Close the turn with the final packet, status, and usage stats.
1090
+ const packet = StoredPacket.admit(requestPacket, packetAssistant, response.assistantRaw);
1091
+ await this.#db.engine_close_turn.run({
1092
+ id: turnId,
1093
+ status: turnStatus,
1094
+ packet: StoredPacket.stringify(packet),
1095
+ usage_curation_budget: this.#packets.curationBudgetFor(provider), // {§tokenomics-client-gauge}
1096
+ finish_reason: callMetadata.finishReason,
1097
+ model: callMetadata.model,
1098
+ // Opaque provider metadata plus engine-authored rail keys.
1099
+ // {§meta-passthrough}, {§rail-truth-engine-verdict}
1100
+ meta: JSON.stringify({ ...(response.meta ?? {}), ...(railKeys ?? {}) }),
1101
+ });
1102
+ // Dispatch model ops starting at nextActionIndex (continues the
1103
+ // turn's running counter after any pre-model writes).
1104
+ //
1105
+ // Max-commands ceiling: OFF by default (unlimited) — every generated op dispatches.
1106
+ // A degenerate op-loop is a sampler failure guarded at generation, not by dropping
1107
+ // already-generated work post-hoc. The ceiling is an OPT-IN operator/client bound:
1108
+ // when set, overflow ops drop without per-op log entries (no forensics flood) and the
1109
+ // model gets one notices signal next packet.
1110
+ // {§operator-config-workspace-max-commands} — workspace maxCommands min()s the env ceiling.
1111
+ const maxCommands = Math.min(readMaxCommands(), (await WorkspaceSettings.read(this.#db, workspaceId)).maxCommands ?? Number.POSITIVE_INFINITY);
1112
+ // PLAN (intended goals) and the final disposition SEND are not actions —
1113
+ // they always dispatch and never count against the cap. maxCommands
1114
+ // bounds real actions only; maxCommands:0 still admits a plan and a disposition
1115
+ // (the PLAN/SEND ops, zero actions), which is its only coherent meaning.
1116
+ let realCommands = 0;
1117
+ const admittedOps = packetAssistant.ops.filter((op) => {
1118
+ return op.op === "PLAN"
1119
+ || op === sendOp
1120
+ || realCommands++ < maxCommands;
1121
+ });
1122
+ const opsToDispatch = scheduleTurnOps(admittedOps);
1123
+ await this.#dispatcher.prepareEditBatches(opsToDispatch.filter((statement) => statement.op === "EDIT"), {
1124
+ workspaceId, workerId, loopId, turnId,
1125
+ origin, onDispatch,
1126
+ });
1127
+ const droppedCount = opsCount - opsToDispatch.length;
1128
+ const bareStatements = opsToDispatch.filter((statement) => statement.op === "BARE");
1129
+ let bareResults = null;
1130
+ const outcomes = [];
1131
+ // Running counter — a multi-file READ writes N rows from one statement (rowsWritten),
1132
+ // so the next op's sequence picks up after them. Collapses to nextActionIndex+i when
1133
+ // every op writes one row (the common case).
1134
+ let rowSeq = nextActionIndex;
1135
+ let parseErrorsRecorded = false;
1136
+ const recordRecoverableParseErrors = async () => {
1137
+ if (parseErrorsRecorded)
1138
+ return;
1139
+ parseErrorsRecorded = true;
1140
+ for (const error of recoverableParseErrors) {
1141
+ const recorded = await this.#problems.record({
1142
+ workerId,
1143
+ loopId,
1144
+ turnId,
1145
+ sequence: rowSeq++,
1146
+ origin: "model",
1147
+ source: "grammar",
1148
+ result: Results.failure("grammar:parser", "invalid-operation-syntax", 400, error.message, {}, {
1149
+ line: error.line,
1150
+ column: error.column,
1151
+ source: error.source,
1152
+ stage: "parse",
1153
+ recovery: "Correct only the failed operation; sibling operations were retained.",
1154
+ retryable: false,
1155
+ }),
1156
+ });
1157
+ outcomes.push({ op: null, status: recorded.result.status });
1158
+ onDispatch?.(recorded.id);
1159
+ }
1160
+ };
1161
+ for (const statement of opsToDispatch) {
1162
+ if (statement.op === "SEND"
1163
+ && typeof statement.signal === "number"
1164
+ && TERMINAL_SEND_SIGNALS.has(statement.signal)) {
1165
+ await recordRecoverableParseErrors();
1166
+ // {§worker-optimistic-settlement} — SEND judges the refreshed
1167
+ // lifecycle after this turn's own fast streams receive one
1168
+ // bounded opportunity to conclude. This is not a sleep and
1169
+ // does not delay a later turn for older monitored streams.
1170
+ const execHandler = this.#schemes.get("exec");
1171
+ await execHandler?.settleTurnSpawns?.(workerId, turnId, readOptimisticSettlementMs(), providerSignal);
1172
+ }
1173
+ const result = await observed(// {§observability-boundary}
1174
+ "op.dispatch", { op: statement.op }, async (span) => {
1175
+ let dispatchResult;
1176
+ if (statement.op === "BARE") {
1177
+ if (bareResults === null) {
1178
+ const batch = await this.#runBareBatch({
1179
+ statements: bareStatements,
1180
+ provider: childProvider,
1181
+ turnId,
1182
+ modelCallSequenceStart: modelCallSequence + 1,
1183
+ workspaceId,
1184
+ workerId,
1185
+ primaryWorkerId,
1186
+ loopSequence: loopSeq,
1187
+ turnSequence: seq,
1188
+ signal: providerSignal,
1189
+ });
1190
+ bareResults = new Map(batch.map((item) => [item.statement, item]));
1191
+ }
1192
+ const bare = bareResults.get(statement);
1193
+ if (bare === undefined) {
1194
+ throw new Error("BARE statement reached dispatch without its batch result");
1195
+ }
1196
+ dispatchResult = await this.#dispatcher.recordBareResult({
1197
+ statement,
1198
+ workspaceId,
1199
+ workerId,
1200
+ loopId,
1201
+ turnId,
1202
+ sequence: rowSeq,
1203
+ origin,
1204
+ onDispatch,
1205
+ }, bare.result, bare.modelCallId);
1206
+ }
1207
+ else {
1208
+ dispatchResult = await this.#dispatcher.dispatch({
1209
+ statement, workspaceId, workerId, loopId, turnId,
1210
+ sequence: rowSeq,
1211
+ origin, onDispatch,
1212
+ });
1213
+ }
1214
+ span.setAttribute("status", dispatchResult.status);
1215
+ recordCounter(OPS_DISPATCHED, { op: statement.op, status: dispatchResult.status });
1216
+ return dispatchResult;
1217
+ });
1218
+ outcomes.push({ op: statement.op, status: result.status });
1219
+ for (const normalization of result.scopeNormalizations ?? []) {
1220
+ this.#notices.push(workspaceId, loopId, {
1221
+ source: "engine:slicer",
1222
+ kind: "scope_normalized",
1223
+ level: "warn",
1224
+ message: `Scope <${normalization.requested.join(",")}> was normalized to <${normalization.canonical.join(",")}>.`,
1225
+ });
1226
+ }
1227
+ // {§engine-rails} — a refused final disposition leaves both loop
1228
+ // and turn continuing, and its 409 steering ruling strikes once.
1229
+ if (statement === sendOp && result.status === 409) {
1230
+ steerStruck = true;
1231
+ turnStatus = TURN_STATUS_IMPLICIT_CONTINUE;
1232
+ await this.#db.engine_reconcile_turn_status.run({ id: turnId, status: turnStatus });
1233
+ }
1234
+ // {§send-300-choices}: a question resolves through the proposal system; whatever the
1235
+ // resolution (answer/reject/timeout), the LOOP continues to the turn where the model
1236
+ // reads it; the turn record is a continue, never a 300 terminal.
1237
+ if (statement === sendOp && sendOp.signal === 300 && result.status !== 409) {
1238
+ turnStatus = TURN_STATUS_IMPLICIT_CONTINUE;
1239
+ await this.#db.engine_reconcile_turn_status.run({ id: turnId, status: turnStatus });
1240
+ }
1241
+ // A broadcast [202] is a conditional wait, not an unconditional turn status:
1242
+ // live work parks at 202; completed-but-unobserved work continues at 102; an
1243
+ // empty join completes at 200. Persist and return the dispatcher's actual ruling.
1244
+ if (statement === sendOp
1245
+ && result.status !== 409
1246
+ && sendOp.target === null
1247
+ && sendOp.signal === 202
1248
+ && result.status !== 202) {
1249
+ turnStatus = result.status;
1250
+ await this.#db.engine_reconcile_turn_status.run({ id: turnId, status: turnStatus });
1251
+ }
1252
+ rowSeq += result.rowsWritten ?? 1;
1253
+ }
1254
+ await recordRecoverableParseErrors();
1255
+ // Engine rail failures mint as op='error' log rows at the turn's next
1256
+ // free sequence. Bounded syntax failures were recorded in their
1257
+ // authored turn before its terminal disposition.
1258
+ let errSeq = rowSeq;
1259
+ // max_commands_exceeded IS model-facing: dropped ops the model emitted that didn't run.
1260
+ if (droppedCount > 0)
1261
+ pendingEngineErrors.push("max_commands_exceeded");
1262
+ for (const kind of pendingEngineErrors) {
1263
+ const problem = ENGINE_PROBLEMS[kind];
1264
+ const extensions = kind === "max_commands_exceeded"
1265
+ ? {
1266
+ operationLimit: maxCommands,
1267
+ omittedOperations: droppedCount,
1268
+ stage: "dispatch-admission",
1269
+ recovery: "Continue with no more than the configured operation limit.",
1270
+ retryable: false,
1271
+ }
1272
+ : {
1273
+ stage: "turn",
1274
+ recovery: "Perform an operation before continuing with `## SEND0 [102]`.",
1275
+ retryable: false,
1276
+ };
1277
+ await this.#problems.record({
1278
+ workerId,
1279
+ loopId,
1280
+ turnId,
1281
+ sequence: errSeq++,
1282
+ origin: "plurnk",
1283
+ source: "rail",
1284
+ result: Results.failure("engine:rail", problem.code, problem.status, problem.detail, {}, extensions),
1285
+ });
1286
+ }
1287
+ // {§log-row-self-explains} — model-operation failures remain on their
1288
+ // own rows; genuine engine faults fail hard and mint no substitute row.
1289
+ // {§model-entry} — mirror this turn's verbatim emission back as a `model` row, so the NEXT
1290
+ // packet shows the model exactly what it last produced. ALWAYS born FOLDED — the old
1291
+ // born-OPEN-on-error auto-trigger was conditional helpfulness that bred its own hazards
1292
+ // (a 24k-char ramble mirrored open re-injects itself into the next packet: cost,
1293
+ // contamination, pressure feedback).
1294
+ // {§encrypted-reasoning-carrier} — core relays every provider-normalized
1295
+ // item unchanged.
1296
+ const reasoningItems = response.assistant.reasoningEncrypted?.length
1297
+ ? response.assistant.reasoningEncrypted
1298
+ : undefined;
1299
+ if (packetAssistant.content.trim().length > 0 || reasoningItems !== undefined) {
1300
+ await this.#dispatcher.writeModelEntry({
1301
+ verbatim: packetAssistant.content,
1302
+ workerId,
1303
+ loopId,
1304
+ turnId,
1305
+ sequence: errSeq++,
1306
+ folded: true,
1307
+ modelCallId: emissionModelCallId,
1308
+ ...(reasoningItems !== undefined ? { reasoningItems } : {}),
1309
+ });
1310
+ }
1311
+ return {
1312
+ turnId,
1313
+ status: turnStatus,
1314
+ outcomes,
1315
+ fingerprint: StrikeRail.fingerprintTurn(packetAssistant.ops),
1316
+ capacityHardStop: false,
1317
+ steerStruck,
1318
+ emissionAttempts,
1319
+ emissionExhausted: false,
1320
+ };
1321
+ }
1322
+ // Split the wire-level ProviderResponse into the two destinations:
1323
+ // packet.assistant gets the model's emission (content, ops, reasoning);
1324
+ // Turn columns get accepted-call metadata (finishReason, model). Physical
1325
+ // request usage and cost have their own cardinal persistence path.
1326
+ // {§provider-surface} Text-fragment scraping policy lives
1327
+ // here — engine owns the parse and the scraping rule, providers stay
1328
+ // grammar-unaware.
1329
+ //
1330
+ // Test-fixture escape hatch: the Mock provider may pre-supply `ops` on
1331
+ // its assistant payload to skip the parse roundtrip. The wire Provider
1332
+ // contract has no `ops` field; only Mock exposes one. Real providers
1333
+ // always take the parse path because their `assistant.ops` is undefined.
1334
+ #splitResponse(response) {
1335
+ const { assistant } = response;
1336
+ const preParsedOps = assistant.ops;
1337
+ const ops = [];
1338
+ // PLAN is an ordinary op — emitted by the model, dispatched, and passed to the
1339
+ // client as a log entry. No special hoisting into the reasoning field. Only
1340
+ // structured operations are executable; interstitial text is not an operation.
1341
+ // Full PlurnkParseError context is preserved on rejected attempt evidence;
1342
+ // warnings remain admissible Notices. {§parse-diagnostics}
1343
+ const parseErrors = [];
1344
+ let hasUnparsedTail = false;
1345
+ const parseNotices = [];
1346
+ if (preParsedOps !== undefined) {
1347
+ ops.push(...preParsedOps);
1348
+ }
1349
+ else {
1350
+ // {§observability-boundary} — the parse is observed without its input;
1351
+ // only the resulting statement count is attributable.
1352
+ const parsed = observedSync("contracts.parse", {}, (span) => {
1353
+ const result = PlurnkParser.parse(assistant.content);
1354
+ span.setAttribute("statements", result.items.filter((item) => item.kind === "statement").length);
1355
+ return result;
1356
+ });
1357
+ for (const item of parsed.items) {
1358
+ if (item.kind === "statement") {
1359
+ ops.push(item.statement);
1360
+ }
1361
+ else if (item.kind === "error") {
1362
+ const err = item.error;
1363
+ if (err instanceof PlurnkParseError) {
1364
+ if (err.severity === "warning") {
1365
+ parseNotices.push({
1366
+ source: "grammar",
1367
+ kind: "parse_advisory",
1368
+ level: "warn",
1369
+ message: err.message,
1370
+ position: {
1371
+ type: "content-offset",
1372
+ line: err.line,
1373
+ column: err.column,
1374
+ },
1375
+ parserSource: err.source,
1376
+ });
1377
+ }
1378
+ else {
1379
+ parseErrors.push({ message: err.message, line: err.line, column: err.column, source: err.source });
1380
+ }
1381
+ }
1382
+ else {
1383
+ const msg = err?.message ?? "parse error";
1384
+ parseErrors.push({ message: msg, line: 0, column: 0, source: "parser" });
1385
+ }
1386
+ }
1387
+ }
1388
+ // Boundary loss is the parser's one public fact from `unparsedTail.from` onward;
1389
+ // preserve it with the rejected forensic attempt. {§unparsed-tail-boundary}
1390
+ const tail = parsed.unparsedTail;
1391
+ if (tail !== undefined) {
1392
+ hasUnparsedTail = true;
1393
+ parseErrors.push({ message: tail.reason, line: tail.from.line, column: tail.from.column, source: "grammar" });
1394
+ }
1395
+ }
1396
+ const plan = ops[0]?.op === "PLAN" ? ops[0] : undefined;
1397
+ const finalOp = ops.at(-1);
1398
+ const terminalSend = finalOp?.op === "SEND"
1399
+ && typeof finalOp.signal === "number"
1400
+ && TERMINAL_SEND_SIGNALS.has(finalOp.signal)
1401
+ ? finalOp
1402
+ : undefined;
1403
+ const recoverableParseErrors = plan !== undefined && terminalSend !== undefined && !hasUnparsedTail
1404
+ ? parseErrors.filter((error) => comparePosition(error, plan.position) > 0
1405
+ && comparePosition(error, terminalSend.position) < 0).toSorted(comparePosition)
1406
+ : [];
1407
+ const emissionValid = preParsedOps !== undefined
1408
+ || (plan !== undefined
1409
+ && terminalSend !== undefined
1410
+ && !hasUnparsedTail
1411
+ && recoverableParseErrors.length === parseErrors.length);
1412
+ const reasoning = assistant.reasoning ?? null;
1413
+ return {
1414
+ packetAssistant: { content: assistant.content, ops, reasoning },
1415
+ callMetadata: { finishReason: assistant.finishReason, model: assistant.model },
1416
+ parseErrors,
1417
+ recoverableParseErrors: emissionValid ? recoverableParseErrors : [],
1418
+ parseNotices,
1419
+ // The ANTLR model-turn parser is authoritative. A trustworthy
1420
+ // PLAN...SEND frame admits bounded interior statement failures so
1421
+ // they become durable operation results. Missing boundaries,
1422
+ // errors outside the frame, and an unparsed tail reject wholesale.
1423
+ // Pre-parsed ops are Mock's trusted test seam.
1424
+ emissionValid,
1425
+ };
1426
+ }
1427
+ // #note12 — the plugin-provided reference docs (schemes' + execs' `documentation`),
1428
+ // materialized at worker://plurnk/docs/<name>.md by LoopDocs (like operator docs).
1429
+ async #materializeEnvironmentDeltas(args) {
1430
+ const { workspaceId, workerId, loopId, turnId, fromSequence } = args;
1431
+ const rows = await this.#db.engine_pull_ambient_events.all({ workspace_id: workspaceId, worker_id: workerId });
1432
+ const window = rows[0];
1433
+ if (window === undefined)
1434
+ throw new Error(`ambient pull: worker ${workerId} has no observation window`);
1435
+ let written = 0;
1436
+ for (const r of rows) {
1437
+ if (r.event_id === null || r.producer_worker_id === null || r.producer_worker_name === null || r.kind === null
1438
+ || r.op === null || r.status_rx === null)
1439
+ continue;
1440
+ const termination = r.kind === "loop_termination";
1441
+ if (r.rx === null)
1442
+ throw new Error(`ambient event ${r.event_id} has no materializable result`);
1443
+ const terminal = termination
1444
+ ? TerminalResult.parse(r.rx, `ambient loop-termination event ${r.event_id}`)
1445
+ : null;
1446
+ if (terminal !== null && terminal.status !== r.status_rx) {
1447
+ throw new Error(`ambient loop-termination event ${r.event_id} status ${r.status_rx} does not match its terminal result status ${terminal.status}`);
1448
+ }
1449
+ let attrs = r.attrs ?? "{}";
1450
+ const parsedTags = JSON.parse(r.tags ?? "[]");
1451
+ if (!Array.isArray(parsedTags) || !parsedTags.every((tag) => typeof tag === "string" && tag.length > 0)) {
1452
+ throw new TypeError(`ambient event ${r.event_id} tags must be an array of nonempty strings`);
1453
+ }
1454
+ const tags = [...new Set(parsedTags)].toSorted();
1455
+ if (tags.length !== parsedTags.length || tags.some((tag, index) => tag !== parsedTags[index])) {
1456
+ throw new TypeError(`ambient event ${r.event_id} tags must be unique and sorted`);
1457
+ }
1458
+ if (terminal !== null) {
1459
+ const inherited = JSON.parse(attrs);
1460
+ if (inherited === null || typeof inherited !== "object" || Array.isArray(inherited)) {
1461
+ throw new TypeError(`ambient loop-termination event ${r.event_id} attrs must be an object`);
1462
+ }
1463
+ const receipt = await BranchReceipt.render(this.#db, r.producer_worker_id);
1464
+ attrs = JSON.stringify({
1465
+ ...inherited,
1466
+ kind: "loop_termination",
1467
+ ...(r.terminated_by === null ? {} : { terminatedBy: r.terminated_by }),
1468
+ ...(receipt === null ? {} : { receipt }),
1469
+ });
1470
+ }
1471
+ const inserted = await this.#db.engine_insert_ambient_delta.get({
1472
+ worker_id: workerId, loop_id: loopId, turn_id: turnId, sequence: fromSequence + written,
1473
+ event_id: r.event_id,
1474
+ source: r.source ?? WorkerControlAddress.render(r.producer_worker_name),
1475
+ op: r.op,
1476
+ scheme: r.scheme,
1477
+ hostname: r.hostname,
1478
+ pathname: r.pathname,
1479
+ rx: r.rx,
1480
+ mimetype_rx: "application/json",
1481
+ status: r.status_rx,
1482
+ weight: LogBody.weight({
1483
+ op: r.op,
1484
+ attrs,
1485
+ tx: "",
1486
+ rx: r.rx,
1487
+ mimetypeTx: "text/plain",
1488
+ mimetypeRx: "application/json",
1489
+ }, this.#weighContent),
1490
+ expanded: terminal !== null && terminal.status >= 200 && terminal.status < 300 ? 1 : 0,
1491
+ attrs,
1492
+ });
1493
+ const materialized = inserted ?? await this.#db.engine_ambient_delta_id.get({
1494
+ worker_id: workerId,
1495
+ event_id: r.event_id,
1496
+ });
1497
+ if (materialized === undefined)
1498
+ throw new Error(`ambient event ${r.event_id} has no observer log row after materialization`);
1499
+ for (const tag of tags) {
1500
+ await this.#db.log_write_tag.run({ log_entry_id: materialized.id, tag });
1501
+ }
1502
+ if (inserted !== undefined)
1503
+ written++;
1504
+ }
1505
+ await this.#db.engine_advance_ambient_cursor.get({
1506
+ workspace_id: workspaceId,
1507
+ worker_id: workerId,
1508
+ cursor: window.cursor,
1509
+ boundary: window.boundary,
1510
+ });
1511
+ return written;
1512
+ }
1513
+ // {§exec-poll} — EXEC `<0>` is turn-scoped: abort the worker's open turn-scoped streams via their
1514
+ // owning scheme (the same registry-routed abort the total reap uses). Called at each pre-turn
1515
+ // before the turn's own spawns, so every open turn-scoped sub here is from a prior turn — it
1516
+ // never survives into the subsequent turn. Fire-and-forget: the spawn finalizes async and its
1517
+ // terminal output surfaces born-OPEN through the stream-delta path ({§exec-stream}).
1518
+ async #reapTurnScopedStreams(workerId) {
1519
+ const open = await this.#db.find_open_turn_scoped_subscriptions_for_worker.all({ worker_id: workerId });
1520
+ await Promise.all(open.map(({ id }) => this.#liveSubscriptions.cancel(id)));
1521
+ }
1522
+ async #materializeStreamDeltas(args) {
1523
+ const { workspaceId, workerId, loopId, turnId, fromSequence } = args;
1524
+ const channels = await this.#db.engine_worker_stream_channels.all({ worker_id: workerId });
1525
+ let written = 0;
1526
+ for (const ch of channels) {
1527
+ // Default channels are an implementation detail. Preserve the
1528
+ // channel internally on the entry/subscription, but present the
1529
+ // ordinary address to the model; only an explicitly non-default
1530
+ // channel earns a fragment in the log.
1531
+ const visibleFragment = ch.published_channel !== null
1532
+ && ch.channel === this.#schemes.defaultChannelFor(ch.runtime, workspaceId)
1533
+ ? null
1534
+ : ch.channel;
1535
+ const prior = await this.#db.engine_stream_cursor.get({
1536
+ worker_id: workerId, scheme: ch.runtime, pathname: ch.coord, fragment: visibleFragment,
1537
+ });
1538
+ const priorAttrs = prior !== undefined ? JSON.parse(prior.attrs) : {};
1539
+ const cursor = priorAttrs.streamEnd ?? 0;
1540
+ const closed = ch.state === "closed" || ch.state === "errored";
1541
+ const terminal = closed
1542
+ ? Results.assert(JSON.parse(ch.close_result ?? "null"))
1543
+ : null;
1544
+ const terminalResult = async (fields, sequence) => {
1545
+ if (terminal === null)
1546
+ throw new Error(`closed subscription ${ch.subscription_id} has no terminal result`);
1547
+ const result = Results.assert({
1548
+ ...terminal,
1549
+ ...(terminal.problem === undefined ? {} : { problem: { ...terminal.problem } }),
1550
+ ...fields,
1551
+ });
1552
+ if (result.problem !== undefined) {
1553
+ const seqs = await this.#db.engine_loop_turn_seqs.get({
1554
+ loop_id: loopId,
1555
+ turn_id: turnId,
1556
+ });
1557
+ if (seqs === undefined)
1558
+ throw new Error(`stream delta has no log coordinate for loop=${loopId} turn=${turnId}`);
1559
+ Results.attachInstance(result, `log:///${seqs.loop_seq}/${seqs.turn_seq}/${sequence}/READ`);
1560
+ }
1561
+ return result;
1562
+ };
1563
+ const publishEnd = streamPublicationEnd(ch.content, ch.mimetype, cursor, closed);
1564
+ if (publishEnd <= cursor) {
1565
+ // The cursor-terminal race: a channel written in one final
1566
+ // burst gets fully shown FOLDED while still active; the close then has zero new
1567
+ // content and the auto-OPEN terminal observation never fired — the model was never shown
1568
+ // the conclusion of a stream whose result it already holds folded. The same
1569
+ // observation is required when the channel produced no publishable content:
1570
+ // completion is information independently of payload. Text streams retain their
1571
+ // terse marker; structured channels emit a bodyless typed conclusion.
1572
+ if (closed && priorAttrs.terminal !== true) {
1573
+ const streamTarget = renderTarget({
1574
+ scheme: ch.runtime,
1575
+ pathname: ch.coord,
1576
+ fragment: visibleFragment,
1577
+ });
1578
+ if (streamTarget === null)
1579
+ throw new Error(`stream ${ch.subscription_id} has no renderable address`);
1580
+ const pointer = cursor > 0
1581
+ ? `full output already delivered above; READ ${streamTarget} to revisit`
1582
+ : "stream produced no output";
1583
+ const sequence = fromSequence + written;
1584
+ const content = baseMimetype(ch.mimetype).startsWith("text/")
1585
+ ? `[ stream closed (${ch.close_status ?? 200}) - ${pointer} ]`
1586
+ : "";
1587
+ const rx = JSON.stringify(await terminalResult({
1588
+ content,
1589
+ mimetype: ch.mimetype,
1590
+ }, sequence));
1591
+ await this.#db.engine_insert_stream_delta.run({
1592
+ worker_id: workerId, loop_id: loopId, turn_id: turnId, sequence,
1593
+ scheme: ch.runtime, pathname: ch.coord, fragment: visibleFragment,
1594
+ rx,
1595
+ weight: LogBody.weight({
1596
+ op: "READ",
1597
+ attrs: {},
1598
+ tx: "",
1599
+ rx,
1600
+ mimetypeTx: "text/plain",
1601
+ mimetypeRx: "application/json",
1602
+ }, this.#weighContent),
1603
+ status: terminal?.status ?? 200,
1604
+ attrs: JSON.stringify({ streamEnd: ch.content.length, terminal: true }),
1605
+ expanded: 1,
1606
+ });
1607
+ written++;
1608
+ }
1609
+ continue;
1610
+ }
1611
+ // startLine continues the line count across turns: a multi-turn stream's deltas number
1612
+ // into one sequence (lines N..M, then M+1..), not N independent "1:" restarts. {§exec-stream}
1613
+ const startLine = (ch.content.slice(0, cursor).match(/\n/g)?.length ?? 0) + 1;
1614
+ const sequence = fromSequence + written;
1615
+ const content = ch.content.slice(cursor, publishEnd);
1616
+ const terminalDelivery = closed && publishEnd === ch.content.length;
1617
+ const fields = { content, mimetype: ch.mimetype, startLine };
1618
+ const result = terminalDelivery
1619
+ ? await terminalResult(fields, sequence)
1620
+ : { status: 200, ...fields };
1621
+ const rx = JSON.stringify(result);
1622
+ await this.#db.engine_insert_stream_delta.run({
1623
+ worker_id: workerId, loop_id: loopId, turn_id: turnId, sequence,
1624
+ scheme: ch.runtime, pathname: ch.coord, fragment: visibleFragment,
1625
+ rx,
1626
+ weight: LogBody.weight({
1627
+ op: "READ",
1628
+ attrs: {},
1629
+ tx: "",
1630
+ rx,
1631
+ mimetypeTx: "text/plain",
1632
+ mimetypeRx: "application/json",
1633
+ }, this.#weighContent),
1634
+ status: result.status,
1635
+ attrs: JSON.stringify({ streamEnd: publishEnd, terminal: terminalDelivery }),
1636
+ expanded: terminalDelivery ? 1 : 0, // {§exec-stream} — terminal observation auto-OPENs; ongoing folds
1637
+ });
1638
+ written++;
1639
+ }
1640
+ return written;
1641
+ }
1642
+ // {§env-delta-filesystem-narration} {§membership-emi-divergence-signal}
1643
+ // — journal project-file divergence once through the reserved actor.
1644
+ async #logFsFictions(workspaceId, divergences, gitStatus) {
1645
+ if (divergences.length === 0)
1646
+ return;
1647
+ const gitByPath = new Map(gitStatus?.files.map(({ path, status }) => [path, status]) ?? []);
1648
+ const worker = await this.#db.envelope_get_worker_by_name.get({ workspace_id: workspaceId, name: "plurnk" })
1649
+ ?? await this.#db.envelope_insert_worker.get({ workspace_id: workspaceId, name: "plurnk", origin: "plurnk" });
1650
+ if (worker === undefined)
1651
+ throw new Error("logFsFictions: plurnk worker resolution returned no row");
1652
+ const loop = await this.#db.envelope_insert_client_loop.get({ worker_id: worker.id });
1653
+ if (loop === undefined)
1654
+ throw new Error("logFsFictions: loop insert returned no row");
1655
+ const turn = await JournalTurn.insert(this.#db, loop.id);
1656
+ let sequence = 1;
1657
+ for (const d of divergences) {
1658
+ const span = editedSpan(d.before, d.after);
1659
+ const rx = JSON.stringify({ status: 200, entryId: d.entryId, channel: d.channel, span });
1660
+ const attrs = gitByPath.has(d.pathname)
1661
+ ? JSON.stringify({ git: gitByPath.get(d.pathname) })
1662
+ : "{}";
1663
+ await this.#db.engine_insert_log_entry.get({
1664
+ worker_id: worker.id, loop_id: loop.id, turn_id: turn.id, sequence: sequence++,
1665
+ origin: "plurnk", source: "file", model_call_id: null,
1666
+ op: "EDIT", suffix: "", signal: null,
1667
+ // Match Dispatcher.#extractTarget: a bare file address has NULL scheme
1668
+ // only in log target metadata; its entry identity remains `file`.
1669
+ scheme: null, username: null, password: null, hostname: null, port: null,
1670
+ pathname: d.pathname, query: null, fragment: null, lineMarker: null,
1671
+ tx: "", mimetype_tx: "text/plain",
1672
+ rx, mimetype_rx: "application/json",
1673
+ status_rx: 200,
1674
+ weight: LogBody.weight({
1675
+ op: "EDIT",
1676
+ attrs,
1677
+ tx: "",
1678
+ rx,
1679
+ mimetypeTx: "text/plain",
1680
+ mimetypeRx: "application/json",
1681
+ }, this.#weighContent),
1682
+ state: "resolved", outcome: null,
1683
+ attrs,
1684
+ });
1685
+ }
1686
+ }
1687
+ async #writePromptLog({ workerId, loopId, turnId, sequence, target, content, }) {
1688
+ const rx = JSON.stringify({ content, mimetype: "text/markdown" });
1689
+ const row = await this.#db.engine_insert_log_entry.get({
1690
+ worker_id: workerId,
1691
+ loop_id: loopId,
1692
+ turn_id: turnId,
1693
+ sequence,
1694
+ origin: "plurnk",
1695
+ source: null,
1696
+ model_call_id: null,
1697
+ op: "prompt",
1698
+ suffix: "",
1699
+ signal: null,
1700
+ scheme: target.scheme,
1701
+ username: target.username,
1702
+ password: target.password,
1703
+ hostname: target.hostname,
1704
+ port: target.port,
1705
+ pathname: target.pathname,
1706
+ query: target.query,
1707
+ fragment: target.fragment,
1708
+ lineMarker: null,
1709
+ tx: "",
1710
+ mimetype_tx: "text/plain",
1711
+ rx,
1712
+ mimetype_rx: "application/json",
1713
+ status_rx: 200,
1714
+ weight: LogBody.weight({
1715
+ op: "prompt",
1716
+ attrs: {},
1717
+ tx: "",
1718
+ rx,
1719
+ mimetypeTx: "text/plain",
1720
+ mimetypeRx: "application/json",
1721
+ }, this.#weighContent),
1722
+ state: "resolved",
1723
+ outcome: null,
1724
+ attrs: "{}",
1725
+ });
1726
+ if (row === undefined)
1727
+ throw new Error("TurnRunner.#writePromptLog: INSERT ... RETURNING produced no row");
1728
+ return row.id;
1729
+ }
1730
+ }
1731
+ _a = TurnRunner;
1732
+ export default TurnRunner;
1733
+ //# sourceMappingURL=TurnRunner.js.map