@opengeni/worker-bundle 0.16.29 → 0.20.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 (188) hide show
  1. package/dist/activities/agent-run-admission.d.ts +12 -0
  2. package/dist/activities/agent-turn.d.ts +110 -19
  3. package/dist/activities/api-integrations.d.ts +21 -0
  4. package/dist/activities/browser-state-artifact-reaper.d.ts +29 -0
  5. package/dist/activities/capabilities.d.ts +6 -0
  6. package/dist/activities/codemode-dispatcher.d.ts +35 -0
  7. package/dist/activities/codemode-token-renewal.d.ts +23 -0
  8. package/dist/activities/codex-capacity.d.ts +6 -5
  9. package/dist/activities/codex-image-generation.d.ts +21 -0
  10. package/dist/activities/context-compaction.d.ts +1 -0
  11. package/dist/activities/documents.d.ts +3 -2
  12. package/dist/activities/environment.d.ts +17 -8
  13. package/dist/activities/expiring-material-renewal.d.ts +1 -1
  14. package/dist/activities/file-upload-reaper.d.ts +7 -2
  15. package/dist/activities/gateway-image-generation.d.ts +39 -0
  16. package/dist/activities/gateway-video-generation.d.ts +53 -0
  17. package/dist/activities/generated-images.d.ts +112 -0
  18. package/dist/activities/git-credential-renewal.d.ts +1 -1
  19. package/dist/activities/goals.d.ts +2 -2
  20. package/dist/activities/google-drive-changes.d.ts +99 -0
  21. package/dist/activities/image-generation-operation.d.ts +74 -0
  22. package/dist/activities/image-generation-references.d.ts +25 -0
  23. package/dist/activities/knowledge-source-sync-driver.d.ts +23 -0
  24. package/dist/activities/knowledge-source-sync.d.ts +75 -0
  25. package/dist/activities/packs.d.ts +21 -36
  26. package/dist/activities/parent-wake.d.ts +1 -1
  27. package/dist/activities/retained-screenshot-reaper.d.ts +2 -2
  28. package/dist/activities/retained-screenshots.d.ts +36 -0
  29. package/dist/activities/rig-verification.d.ts +82 -5
  30. package/dist/activities/run-credential-renewal.d.ts +1 -1
  31. package/dist/activities/run-input.d.ts +3 -1
  32. package/dist/activities/sandbox-images.d.ts +14 -0
  33. package/dist/activities/sandbox-lease.d.ts +47 -9
  34. package/dist/activities/scheduled-tasks.d.ts +2 -2
  35. package/dist/activities/session-state.d.ts +7 -5
  36. package/dist/activities/site-auth-maintenance.d.ts +27 -0
  37. package/dist/activities/streaming.d.ts +1 -1
  38. package/dist/activities/types.d.ts +87 -5
  39. package/dist/activities/video-generation-admission.d.ts +43 -0
  40. package/dist/activities/video-generation-credential.d.ts +24 -0
  41. package/dist/activities/video-generation-reconciliation.d.ts +13 -0
  42. package/dist/activities/video-media-validation.d.ts +34 -0
  43. package/dist/activities/video-output-retention.d.ts +36 -0
  44. package/dist/activities/video-reference-staging.d.ts +55 -0
  45. package/dist/activities/workflow-wake.d.ts +2 -2
  46. package/dist/activities/workspace-capture.d.ts +10 -1
  47. package/dist/activities/xai-auth.d.ts +23 -0
  48. package/dist/activities/xai-image-generation.d.ts +26 -0
  49. package/dist/activities/xai-video-generation.d.ts +18 -0
  50. package/dist/activities-control-XURE4VKN.js +7221 -0
  51. package/dist/activities-control-XURE4VKN.js.map +1 -0
  52. package/dist/activities-control.d.ts +297 -0
  53. package/dist/activities-turn-6EBXGGLS.js +16036 -0
  54. package/dist/activities-turn-6EBXGGLS.js.map +1 -0
  55. package/dist/activities-turn.d.ts +17 -0
  56. package/dist/activities.d.ts +138 -150
  57. package/dist/activity-services.d.ts +10 -0
  58. package/dist/artifact-materializer-entry.d.ts +6 -0
  59. package/dist/artifact-materializer-entry.js +2662 -0
  60. package/dist/artifact-materializer-entry.js.map +1 -0
  61. package/dist/artifact-outbox-entry.d.ts +2 -0
  62. package/dist/artifact-outbox-entry.js +681 -0
  63. package/dist/artifact-outbox-entry.js.map +1 -0
  64. package/dist/chunk-5GRJIP5H.js +3092 -0
  65. package/dist/chunk-5GRJIP5H.js.map +1 -0
  66. package/dist/chunk-GRFQTTSQ.js +448 -0
  67. package/dist/chunk-GRFQTTSQ.js.map +1 -0
  68. package/dist/chunk-TYNPCG4U.js +906 -0
  69. package/dist/chunk-TYNPCG4U.js.map +1 -0
  70. package/dist/concurrency.d.ts +108 -5
  71. package/dist/editable-artifact-hint-broker.d.ts +49 -0
  72. package/dist/editable-artifact-materializer-launcher.d.ts +49 -0
  73. package/dist/editable-artifact-materializer-service.d.ts +108 -0
  74. package/dist/editable-artifact-materializer-storage.d.ts +12 -0
  75. package/dist/editable-artifact-materializer-subprocess.d.ts +50 -0
  76. package/dist/editable-artifact-materializer.d.ts +262 -0
  77. package/dist/editable-artifact-outbox-dispatcher.d.ts +44 -0
  78. package/dist/editable-artifact-outbox-service.d.ts +70 -0
  79. package/dist/host-export.d.ts +1 -1
  80. package/dist/index.d.ts +189 -10
  81. package/dist/index.js +715 -17380
  82. package/dist/index.js.map +1 -1
  83. package/dist/memory-pressure-guard.d.ts +57 -0
  84. package/dist/model-checkpoint-memory-collector.d.ts +23 -0
  85. package/dist/model-context-contributions.d.ts +40 -0
  86. package/dist/observability-metrics.d.ts +53 -1
  87. package/dist/sandbox-reaper-contract.d.ts +40 -0
  88. package/dist/sandbox-reaper-timeout.d.ts +14 -0
  89. package/dist/sandbox-resume.d.ts +34 -7
  90. package/dist/sandbox-routing.d.ts +6 -0
  91. package/dist/worker-service-lifecycle.d.ts +6 -2
  92. package/dist/workflow-bundle.js +1094 -370
  93. package/dist/workflows/activities.d.ts +8 -2
  94. package/dist/workflows/document-index.d.ts +1 -1
  95. package/dist/workflows/knowledge-source-sync.d.ts +13 -0
  96. package/dist/workflows/rig-verification.d.ts +1 -1
  97. package/dist/workflows/sandbox-reaper.d.ts +8 -0
  98. package/dist/workflows/scheduled-tasks.d.ts +1 -1
  99. package/dist/workflows/session.d.ts +2 -2
  100. package/dist/workflows/site-auth-maintenance.d.ts +2 -0
  101. package/dist/workflows/video-generation.d.ts +10 -0
  102. package/dist/workflows/workflow-wake.d.ts +1 -1
  103. package/dist/workflows.d.ts +10 -7
  104. package/package.json +35 -15
  105. package/src/activities/agent-run-admission.ts +76 -0
  106. package/src/activities/agent-turn.ts +2600 -340
  107. package/src/activities/api-integrations.ts +138 -0
  108. package/src/activities/browser-state-artifact-reaper.ts +120 -0
  109. package/src/activities/capabilities.ts +10 -0
  110. package/src/activities/codemode-dispatcher.ts +335 -0
  111. package/src/activities/codemode-token-renewal.ts +64 -0
  112. package/src/activities/codex-capacity.ts +54 -7
  113. package/src/activities/codex-image-generation.ts +56 -0
  114. package/src/activities/context-compaction.ts +38 -3
  115. package/src/activities/documents.ts +14 -4
  116. package/src/activities/environment.ts +54 -45
  117. package/src/activities/expiring-material-renewal.ts +1 -1
  118. package/src/activities/file-upload-reaper.ts +34 -3
  119. package/src/activities/gateway-image-generation.ts +146 -0
  120. package/src/activities/gateway-video-generation.ts +298 -0
  121. package/src/activities/generated-images.ts +860 -0
  122. package/src/activities/goals.ts +8 -3
  123. package/src/activities/google-drive-changes.ts +454 -0
  124. package/src/activities/image-generation-operation.ts +333 -0
  125. package/src/activities/image-generation-references.ts +118 -0
  126. package/src/activities/knowledge-source-sync-driver.ts +27 -0
  127. package/src/activities/knowledge-source-sync.ts +2840 -0
  128. package/src/activities/mcp-credentials.ts +1 -0
  129. package/src/activities/packs.ts +75 -152
  130. package/src/activities/parent-wake.ts +13 -1
  131. package/src/activities/retained-screenshot-reaper.ts +2 -2
  132. package/src/activities/retained-screenshots.ts +453 -28
  133. package/src/activities/rig-verification.ts +554 -43
  134. package/src/activities/run-input.ts +22 -6
  135. package/src/activities/sandbox-images.ts +167 -0
  136. package/src/activities/sandbox-lease.ts +1065 -483
  137. package/src/activities/scheduled-tasks.ts +104 -74
  138. package/src/activities/session-state.ts +22 -4
  139. package/src/activities/site-auth-maintenance.ts +269 -0
  140. package/src/activities/streaming.ts +42 -3
  141. package/src/activities/types.ts +104 -5
  142. package/src/activities/video-generation-admission.ts +303 -0
  143. package/src/activities/video-generation-credential.ts +112 -0
  144. package/src/activities/video-generation-reconciliation.ts +771 -0
  145. package/src/activities/video-media-validation.ts +332 -0
  146. package/src/activities/video-output-retention.ts +314 -0
  147. package/src/activities/video-reference-staging.ts +350 -0
  148. package/src/activities/workflow-wake.ts +2 -2
  149. package/src/activities/workspace-capture.ts +44 -10
  150. package/src/activities/xai-auth.ts +122 -0
  151. package/src/activities/xai-image-generation.ts +86 -0
  152. package/src/activities/xai-video-generation.ts +69 -0
  153. package/src/activities-control.ts +58 -0
  154. package/src/activities-turn.ts +40 -0
  155. package/src/activities.ts +53 -124
  156. package/src/activity-services.ts +62 -0
  157. package/src/artifact-materializer-entry.ts +35 -0
  158. package/src/artifact-outbox-entry.ts +29 -0
  159. package/src/concurrency.ts +484 -6
  160. package/src/editable-artifact-hint-broker.ts +235 -0
  161. package/src/editable-artifact-materializer-launcher.ts +515 -0
  162. package/src/editable-artifact-materializer-service.ts +787 -0
  163. package/src/editable-artifact-materializer-storage.ts +413 -0
  164. package/src/editable-artifact-materializer-subprocess.ts +956 -0
  165. package/src/editable-artifact-materializer.ts +1289 -0
  166. package/src/editable-artifact-outbox-dispatcher.ts +244 -0
  167. package/src/editable-artifact-outbox-service.ts +438 -0
  168. package/src/index.ts +328 -72
  169. package/src/memory-pressure-guard.ts +489 -0
  170. package/src/model-checkpoint-memory-collector.ts +123 -0
  171. package/src/model-context-contributions.ts +159 -0
  172. package/src/observability-metrics.ts +297 -13
  173. package/src/sandbox-reaper-contract.ts +73 -0
  174. package/src/sandbox-reaper-timeout.ts +79 -0
  175. package/src/sandbox-resume.ts +294 -153
  176. package/src/sandbox-routing.ts +32 -24
  177. package/src/worker-service-lifecycle.ts +80 -14
  178. package/src/workflows/activities.ts +31 -0
  179. package/src/workflows/file-upload-reaper.ts +9 -1
  180. package/src/workflows/knowledge-source-sync.ts +83 -0
  181. package/src/workflows/sandbox-reaper.ts +183 -21
  182. package/src/workflows/scheduled-tasks.ts +42 -6
  183. package/src/workflows/session.ts +20 -6
  184. package/src/workflows/site-auth-maintenance.ts +14 -0
  185. package/src/workflows/video-generation.ts +36 -0
  186. package/src/workflows.ts +18 -1
  187. package/dist/activities/toolspace-token-renewal.d.ts +0 -23
  188. package/src/activities/toolspace-token-renewal.ts +0 -64
@@ -0,0 +1,906 @@
1
+ // src/observability-metrics.ts
2
+ import { createHash } from "crypto";
3
+ import { errorCodeToJSON } from "@opengeni/agent-proto";
4
+ import { SandboxBackend } from "@opengeni/contracts";
5
+ import {
6
+ SELFHOSTED_INFRASTRUCTURE_FAULT_CLASSES,
7
+ modelUsageTokenCountOrNull
8
+ } from "@opengeni/runtime";
9
+ var turnTrackers = /* @__PURE__ */ new WeakMap();
10
+ var creditBalanceGaugeAccounts = /* @__PURE__ */ new WeakMap();
11
+ var modelCacheCounterTotals = /* @__PURE__ */ new WeakMap();
12
+ var MAX_MODEL_CACHE_COUNTER_TOTAL = 1e12;
13
+ function observabilityEventLogger(observability) {
14
+ return {
15
+ debug: (message, attributes) => observability.debug(message, eventAttributes(attributes)),
16
+ warn: (message, attributes) => observability.warn(message, eventAttributes(attributes))
17
+ };
18
+ }
19
+ function eventAttributes(attributes) {
20
+ if (!attributes) {
21
+ return void 0;
22
+ }
23
+ const projected = {};
24
+ for (const [key, value] of Object.entries(attributes)) {
25
+ projected[key] = eventAttributeValue(value);
26
+ }
27
+ return projected;
28
+ }
29
+ function eventAttributeValue(value) {
30
+ if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
31
+ return value;
32
+ }
33
+ try {
34
+ return JSON.stringify(value);
35
+ } catch {
36
+ return String(value);
37
+ }
38
+ }
39
+ function runtimeMetricsHooksForObservability(observability) {
40
+ return {
41
+ onModelCall: ({ provider, outcome, durationSeconds }) => {
42
+ observability.incrementCounter({
43
+ name: "opengeni_model_calls_total",
44
+ help: "Total model calls by provider and outcome.",
45
+ labels: { provider, outcome }
46
+ });
47
+ observability.observeHistogram({
48
+ name: "opengeni_model_call_duration_seconds",
49
+ help: "Model call duration in seconds by provider.",
50
+ labels: { provider },
51
+ value: durationSeconds
52
+ });
53
+ },
54
+ onSandboxCreate: ({ backend, imageSource, outcome, durationSeconds }) => {
55
+ observability.incrementCounter({
56
+ name: "opengeni_sandbox_creates_total",
57
+ help: "Total sandbox create attempts by backend and outcome.",
58
+ labels: { backend, image_source: imageSource, outcome }
59
+ });
60
+ observability.observeHistogram({
61
+ name: "opengeni_sandbox_create_duration_seconds",
62
+ help: "Sandbox create duration in seconds by backend.",
63
+ labels: { backend, image_source: imageSource },
64
+ value: durationSeconds
65
+ });
66
+ },
67
+ onSandboxWarmingTimeout: ({ backend, stage }) => {
68
+ observability.incrementCounter({
69
+ name: "opengeni_sandbox_warming_timeouts_total",
70
+ help: "Total sandbox warming timeouts.",
71
+ labels: { backend, stage }
72
+ });
73
+ },
74
+ onSandboxOp: ({ backend, op, outcome, code, healed, durationSeconds, replyBytes }) => {
75
+ observability.incrementCounter({
76
+ name: "opengeni_machine_op_total",
77
+ help: "Total Connected Machine control ops by op, outcome, and typed fault code.",
78
+ labels: { backend, op, outcome, code: code ?? "" }
79
+ });
80
+ observability.observeHistogram({
81
+ name: "opengeni_machine_op_duration_seconds",
82
+ help: "Connected Machine control-op duration in seconds by op.",
83
+ labels: { backend, op },
84
+ value: durationSeconds
85
+ });
86
+ if (healed) {
87
+ observability.incrementCounter({
88
+ name: "opengeni_machine_op_healed_total",
89
+ help: "Connected Machine ops that succeeded only after \u22651 in-call retry.",
90
+ labels: { backend, op }
91
+ });
92
+ }
93
+ if (replyBytes !== void 0) {
94
+ observability.observeHistogram({
95
+ name: "opengeni_machine_op_reply_bytes",
96
+ help: "Connected Machine control-op reply size in bytes (payload-wall indicator).",
97
+ labels: { backend, op },
98
+ value: replyBytes
99
+ });
100
+ }
101
+ }
102
+ };
103
+ }
104
+ function selfhostedOpObserverForMetrics(hooks) {
105
+ return (o) => {
106
+ hooks.onSandboxOp?.({
107
+ backend: "selfhosted",
108
+ op: o.op,
109
+ outcome: o.outcome,
110
+ healed: o.healed,
111
+ retries: o.retries,
112
+ durationSeconds: o.durationMs / 1e3,
113
+ ...o.code !== void 0 ? { code: errorCodeToJSON(o.code) } : {},
114
+ ...o.replyBytes !== void 0 ? { replyBytes: o.replyBytes } : {}
115
+ });
116
+ };
117
+ }
118
+ function machineOpSessionEventFor(o) {
119
+ if (o.outcome === "failed" && o.faultClass && SELFHOSTED_INFRASTRUCTURE_FAULT_CLASSES.has(o.faultClass)) {
120
+ return {
121
+ type: "machine.op.failed",
122
+ payload: {
123
+ op: o.op,
124
+ faultClass: o.faultClass,
125
+ attempts: o.retries,
126
+ ...o.machineId ? { machineId: o.machineId } : {}
127
+ }
128
+ };
129
+ }
130
+ if (o.outcome === "ok" && o.healed) {
131
+ return {
132
+ type: "machine.op.recovered",
133
+ payload: {
134
+ op: o.op,
135
+ faultClass: o.faultClass ?? "unknown",
136
+ attempts: o.retries,
137
+ ...o.machineId ? { machineId: o.machineId } : {}
138
+ }
139
+ };
140
+ }
141
+ return null;
142
+ }
143
+ function makeMachineOpObserver(hooks) {
144
+ const meter = selfhostedOpObserverForMetrics(hooks);
145
+ const buffered = [];
146
+ return {
147
+ observer: (o) => {
148
+ meter(o);
149
+ const event = machineOpSessionEventFor(o);
150
+ if (event) {
151
+ buffered.push(event);
152
+ }
153
+ },
154
+ drainEvents: () => buffered.splice(0, buffered.length)
155
+ };
156
+ }
157
+ function turnLifecycleMetricsFor(observability) {
158
+ const existing = turnTrackers.get(observability);
159
+ if (existing) {
160
+ return existing;
161
+ }
162
+ const tracker = new TurnLifecycleMetrics(observability);
163
+ turnTrackers.set(observability, tracker);
164
+ return tracker;
165
+ }
166
+ var TurnLifecycleMetrics = class {
167
+ constructor(observability, options = {}) {
168
+ this.observability = observability;
169
+ this.options = options;
170
+ }
171
+ turns = /* @__PURE__ */ new Map();
172
+ timer = null;
173
+ start(turnId) {
174
+ const now = this.now();
175
+ this.turns.set(turnId, { startedAt: now, lastProgressAt: now });
176
+ this.ensureTimer();
177
+ this.refreshGauges();
178
+ }
179
+ progress(turnId) {
180
+ const turn = this.turns.get(turnId);
181
+ if (!turn) return;
182
+ turn.lastProgressAt = this.now();
183
+ }
184
+ finish(turnId, outcome, durationSeconds) {
185
+ const startedAt = this.turns.get(turnId)?.startedAt;
186
+ if (startedAt !== void 0) {
187
+ this.turns.delete(turnId);
188
+ }
189
+ if (outcome) {
190
+ const observedDuration = durationSeconds ?? (startedAt === void 0 ? 0 : Math.max(0, (this.now() - startedAt) / 1e3));
191
+ this.observability.incrementCounter({
192
+ name: "opengeni_turns_total",
193
+ help: "Total agent turns by terminal outcome.",
194
+ labels: { outcome }
195
+ });
196
+ this.observability.observeHistogram({
197
+ name: "opengeni_turn_duration_seconds",
198
+ help: "Agent turn duration in seconds by terminal outcome.",
199
+ labels: { outcome },
200
+ value: observedDuration
201
+ });
202
+ }
203
+ this.refreshGauges();
204
+ if (this.turns.size === 0) {
205
+ this.stopTimer();
206
+ }
207
+ }
208
+ refreshGauges() {
209
+ this.observability.setGauge({
210
+ name: "opengeni_turns_inflight",
211
+ help: "Current number of in-flight agent turns in this worker process.",
212
+ value: this.turns.size
213
+ });
214
+ this.observability.setGauge({
215
+ name: "opengeni_turn_oldest_inflight_age_seconds",
216
+ help: "Age in seconds of the oldest in-flight agent turn in this worker process.",
217
+ value: this.oldestInflightAgeSeconds()
218
+ });
219
+ this.observability.setGauge({
220
+ name: "opengeni_turn_oldest_no_progress_age_seconds",
221
+ help: "Seconds since durable progress for the least recently progressing in-flight turn.",
222
+ value: this.oldestNoProgressAgeSeconds()
223
+ });
224
+ }
225
+ stop() {
226
+ this.turns.clear();
227
+ this.refreshGauges();
228
+ this.stopTimer();
229
+ }
230
+ oldestInflightAgeSeconds() {
231
+ if (this.turns.size === 0) {
232
+ return 0;
233
+ }
234
+ let oldest = Number.POSITIVE_INFINITY;
235
+ for (const { startedAt } of this.turns.values()) {
236
+ oldest = Math.min(oldest, startedAt);
237
+ }
238
+ return Math.max(0, (this.now() - oldest) / 1e3);
239
+ }
240
+ oldestNoProgressAgeSeconds() {
241
+ if (this.turns.size === 0) return 0;
242
+ let leastRecentProgress = Number.POSITIVE_INFINITY;
243
+ for (const { lastProgressAt } of this.turns.values()) {
244
+ leastRecentProgress = Math.min(leastRecentProgress, lastProgressAt);
245
+ }
246
+ return Math.max(0, (this.now() - leastRecentProgress) / 1e3);
247
+ }
248
+ ensureTimer() {
249
+ if (this.timer) {
250
+ return;
251
+ }
252
+ this.timer = setInterval(() => this.refreshGauges(), this.options.refreshIntervalMs ?? 15e3);
253
+ this.timer.unref?.();
254
+ }
255
+ stopTimer() {
256
+ if (!this.timer) {
257
+ return;
258
+ }
259
+ clearInterval(this.timer);
260
+ this.timer = null;
261
+ }
262
+ now() {
263
+ return this.options.now?.() ?? Date.now();
264
+ }
265
+ };
266
+ function recordTurnsQueuedGauge(observability, value) {
267
+ observability.setGauge({
268
+ name: "opengeni_turns_queued",
269
+ help: "Current number of queued session turns.",
270
+ value
271
+ });
272
+ }
273
+ function recordTurnTaskQueueStats(observability, stats) {
274
+ observability.setGauge({
275
+ name: "opengeni_turn_eligible_backlog",
276
+ help: "Temporal runAgentTurn activity tasks eligible for immediate worker admission.",
277
+ value: nonnegativeFinite(stats.eligibleBacklog)
278
+ });
279
+ observability.setGauge({
280
+ name: "opengeni_turn_eligible_backlog_oldest_age_seconds",
281
+ help: "Approximate age of the oldest eligible runAgentTurn activity task.",
282
+ value: nonnegativeFinite(stats.oldestBacklogAgeSeconds)
283
+ });
284
+ observability.setGauge({
285
+ name: "opengeni_turn_eligible_tasks_add_rate",
286
+ help: "Temporal runAgentTurn tasks added per second over its rolling window.",
287
+ value: nonnegativeFinite(stats.tasksAddRate)
288
+ });
289
+ observability.setGauge({
290
+ name: "opengeni_turn_eligible_tasks_dispatch_rate",
291
+ help: "Temporal runAgentTurn tasks dispatched per second over its rolling window.",
292
+ value: nonnegativeFinite(stats.tasksDispatchRate)
293
+ });
294
+ }
295
+ function normalizeTurnTaskQueueStats(stats) {
296
+ if (!stats) {
297
+ throw new Error("Temporal DescribeTaskQueue response omitted required stats");
298
+ }
299
+ const eligibleBacklog = requiredTemporalNumber(
300
+ stats.approximateBacklogCount,
301
+ "approximateBacklogCount",
302
+ { integer: true }
303
+ );
304
+ let oldestBacklogAgeSeconds = 0;
305
+ if (stats.approximateBacklogAge) {
306
+ const seconds = optionalTemporalNumber(
307
+ stats.approximateBacklogAge.seconds,
308
+ "approximateBacklogAge.seconds",
309
+ { integer: true }
310
+ );
311
+ const nanos = optionalTemporalNumber(
312
+ stats.approximateBacklogAge.nanos,
313
+ "approximateBacklogAge.nanos",
314
+ { integer: true }
315
+ );
316
+ if (nanos >= 1e9) {
317
+ throw new Error("Temporal approximateBacklogAge.nanos must be less than one second");
318
+ }
319
+ oldestBacklogAgeSeconds = seconds + nanos / 1e9;
320
+ } else if (eligibleBacklog > 0) {
321
+ throw new Error("Temporal stats omitted approximateBacklogAge for a nonzero backlog");
322
+ }
323
+ return {
324
+ eligibleBacklog,
325
+ oldestBacklogAgeSeconds,
326
+ tasksAddRate: optionalTemporalNumber(stats.tasksAddRate, "tasksAddRate"),
327
+ tasksDispatchRate: optionalTemporalNumber(stats.tasksDispatchRate, "tasksDispatchRate")
328
+ };
329
+ }
330
+ function startTurnCapacityMonitor(input) {
331
+ const intervalMs = input.intervalMs ?? 15e3;
332
+ const now = input.now ?? Date.now;
333
+ const startedAt = now();
334
+ let lastSuccessAt = null;
335
+ let lastReadSucceeded = false;
336
+ let stopped = false;
337
+ let running = null;
338
+ const recordStatus = () => {
339
+ const observedAt = now();
340
+ const successAgeMs = observedAt - (lastSuccessAt ?? startedAt);
341
+ const set = (name, help, value) => input.observability.setGauge({ name, help, value });
342
+ set(
343
+ "opengeni_turn_capacity_monitor_last_read_success",
344
+ "Whether the latest Temporal turn-queue capacity read completed successfully.",
345
+ lastReadSucceeded ? 1 : 0
346
+ );
347
+ set(
348
+ "opengeni_turn_capacity_monitor_last_success_timestamp_seconds",
349
+ "Unix timestamp of the latest successful Temporal turn-queue capacity read, or zero before one succeeds.",
350
+ lastSuccessAt === null ? 0 : lastSuccessAt / 1e3
351
+ );
352
+ set(
353
+ "opengeni_turn_capacity_monitor_last_success_age_seconds",
354
+ "Age of the latest successful Temporal turn-queue capacity read, or monitor age before one succeeds.",
355
+ Math.max(0, successAgeMs / 1e3)
356
+ );
357
+ set(
358
+ "opengeni_turn_capacity_monitor_fresh",
359
+ "Whether eligible-backlog gauges have a successful Temporal read within three monitor intervals.",
360
+ lastReadSucceeded && lastSuccessAt !== null && successAgeMs <= intervalMs * 3 ? 1 : 0
361
+ );
362
+ };
363
+ const refresh = () => {
364
+ recordStatus();
365
+ if (stopped || running) return;
366
+ running = input.read().then((stats) => {
367
+ recordTurnTaskQueueStats(input.observability, stats);
368
+ lastSuccessAt = now();
369
+ lastReadSucceeded = true;
370
+ recordStatus();
371
+ }).catch((error) => {
372
+ lastReadSucceeded = false;
373
+ recordStatus();
374
+ input.observability.warn("turn capacity monitor: Temporal task-queue stats failed", {
375
+ error: error instanceof Error ? error.message : String(error)
376
+ });
377
+ }).finally(() => {
378
+ running = null;
379
+ });
380
+ };
381
+ refresh();
382
+ const timer = setInterval(refresh, intervalMs);
383
+ timer.unref?.();
384
+ return {
385
+ close: async () => {
386
+ stopped = true;
387
+ clearInterval(timer);
388
+ await running;
389
+ }
390
+ };
391
+ }
392
+ function recordSandboxLeaseGauges(observability, counts) {
393
+ for (const liveness of ["cold", "warming", "warm", "draining"]) {
394
+ observability.setGauge({
395
+ name: "opengeni_sandbox_leases",
396
+ help: "Current sandbox leases by liveness state.",
397
+ labels: { liveness },
398
+ value: counts[liveness] ?? 0
399
+ });
400
+ }
401
+ }
402
+ function recordSandboxInventoryProjectionSuccess(observability, domain, timestampSeconds = Date.now() / 1e3) {
403
+ observability.setGauge({
404
+ name: "opengeni_sandbox_inventory_refresh_timestamp_seconds",
405
+ help: "Unix timestamp of the last complete successful sandbox inventory projection by domain.",
406
+ labels: { domain },
407
+ value: timestampSeconds
408
+ });
409
+ }
410
+ function recordSandboxInventoryProjectionFailure(observability, domain) {
411
+ observability.incrementCounter({
412
+ name: "opengeni_sandbox_inventory_refresh_failures_total",
413
+ help: "Failed sandbox inventory projection refreshes by domain.",
414
+ labels: { domain }
415
+ });
416
+ }
417
+ function recordCreditBalanceGauges(observability, balances) {
418
+ const previous = creditBalanceGaugeAccounts.get(observability) ?? /* @__PURE__ */ new Set();
419
+ const current = /* @__PURE__ */ new Set();
420
+ for (const balance of balances) {
421
+ current.add(balance.accountId);
422
+ observability.setGauge({
423
+ name: "opengeni_credit_balance_micros",
424
+ help: "Current credit balance in micros by account.",
425
+ labels: { account_id: balance.accountId },
426
+ value: balance.balanceMicros
427
+ });
428
+ }
429
+ for (const accountId of previous) {
430
+ if (!current.has(accountId)) {
431
+ observability.setGauge({
432
+ name: "opengeni_credit_balance_micros",
433
+ help: "Current credit balance in micros by account.",
434
+ labels: { account_id: accountId },
435
+ value: 0
436
+ });
437
+ }
438
+ }
439
+ creditBalanceGaugeAccounts.set(observability, current);
440
+ }
441
+ function recordSandboxOrphansTerminated(observability, count) {
442
+ if (count <= 0) {
443
+ return;
444
+ }
445
+ observability.incrementCounter({
446
+ name: "opengeni_sandbox_orphans_terminated_total",
447
+ help: "Total provider-side orphan sandboxes terminated by defensive sweeps.",
448
+ amount: count
449
+ });
450
+ }
451
+ function recordSandboxCheckpointArtifactGauges(observability, counts) {
452
+ for (const state of [
453
+ "candidate",
454
+ "current",
455
+ "previous",
456
+ "delete_pending",
457
+ "deleting",
458
+ "delete_failed",
459
+ "deleted"
460
+ ]) {
461
+ observability.setGauge({
462
+ name: "opengeni_sandbox_checkpoint_artifacts",
463
+ help: "Current durable provider checkpoint artifacts by lifecycle state.",
464
+ labels: { state },
465
+ value: counts[state]
466
+ });
467
+ }
468
+ }
469
+ function recordSandboxCheckpointArtifactOutcome(observability, outcome, count = 1) {
470
+ if (count <= 0) return;
471
+ observability.incrementCounter({
472
+ name: "opengeni_sandbox_checkpoint_artifact_operations_total",
473
+ help: "Durable provider checkpoint artifact operations by fixed outcome.",
474
+ labels: { outcome },
475
+ amount: count
476
+ });
477
+ }
478
+ function recordSandboxDeadlineRotationsRequested(observability, count) {
479
+ if (count <= 0) return;
480
+ observability.incrementCounter({
481
+ name: "opengeni_sandbox_deadline_rotations_requested_total",
482
+ help: "Total finite-lifetime sandbox rotations requested before provider deadline.",
483
+ amount: count
484
+ });
485
+ }
486
+ function recordSandboxRotationBacklogGauges(observability, backlog) {
487
+ const values = {
488
+ requested: backlog.requested,
489
+ overdue: backlog.overdue,
490
+ turn_blocked: backlog.turnBlocked,
491
+ direct_blocked: backlog.directBlocked,
492
+ process_blocked: backlog.processBlocked
493
+ };
494
+ for (const [kind, value] of Object.entries(values)) {
495
+ observability.setGauge({
496
+ name: "opengeni_sandbox_rotation_backlog",
497
+ help: "Current finite-lifetime sandbox rotation backlog by fixed condition.",
498
+ labels: { kind },
499
+ value
500
+ });
501
+ }
502
+ }
503
+ var RETAINED_PROCESS_OWNER_STATES = [
504
+ "direct",
505
+ "queued",
506
+ "running",
507
+ "requires_action",
508
+ "recovering",
509
+ "waiting_capacity",
510
+ "completed",
511
+ "failed",
512
+ "cancelled",
513
+ "superseded",
514
+ "withdrawn_for_edit",
515
+ "missing",
516
+ "unknown"
517
+ ];
518
+ var RETAINED_PROCESS_OWNER_STATE_SET = new Set(RETAINED_PROCESS_OWNER_STATES);
519
+ function recordRetainedProcessInventoryGauges(observability, counts) {
520
+ const normalized = /* @__PURE__ */ new Map();
521
+ for (const ownerState of RETAINED_PROCESS_OWNER_STATES) {
522
+ normalized.set(ownerState, { active: 0, terminal: 0 });
523
+ }
524
+ for (const count of counts) {
525
+ const ownerState = RETAINED_PROCESS_OWNER_STATE_SET.has(count.ownerState) ? count.ownerState : "unknown";
526
+ const current = normalized.get(ownerState);
527
+ current.active += Math.max(0, count.activeCount);
528
+ current.terminal += Math.max(0, count.terminalOwnerCount);
529
+ }
530
+ for (const [ownerState, count] of normalized) {
531
+ observability.setGauge({
532
+ name: "opengeni_retained_processes_active",
533
+ help: "Current active retained provider processes by durable owner state.",
534
+ labels: { owner_state: ownerState },
535
+ value: count.active
536
+ });
537
+ observability.setGauge({
538
+ name: "opengeni_retained_processes_terminal_owner_backlog",
539
+ help: "Current active retained processes whose exact owner attempt is terminal.",
540
+ labels: { owner_state: ownerState },
541
+ value: count.terminal
542
+ });
543
+ }
544
+ }
545
+ var EXPIRED_DRAINING_BACKENDS = [...SandboxBackend.options, "unknown"];
546
+ var EXPIRED_DRAINING_BACKEND_SET = new Set(EXPIRED_DRAINING_BACKENDS);
547
+ var EXPIRED_DRAINING_AGE_BUCKETS = ["lt_5m", "5m_1h", "1h_1d", "gte_1d"];
548
+ function recordExpiredDrainingSandboxLeaseGauges(observability, counts) {
549
+ const normalized = /* @__PURE__ */ new Map();
550
+ for (const backend of EXPIRED_DRAINING_BACKENDS) {
551
+ for (const ageBucket of EXPIRED_DRAINING_AGE_BUCKETS) {
552
+ normalized.set(`${backend}:${ageBucket}`, 0);
553
+ }
554
+ }
555
+ for (const count of counts) {
556
+ const backend = EXPIRED_DRAINING_BACKEND_SET.has(count.backend) ? count.backend : "unknown";
557
+ if (!EXPIRED_DRAINING_AGE_BUCKETS.includes(count.ageBucket)) continue;
558
+ const key = `${backend}:${count.ageBucket}`;
559
+ normalized.set(key, (normalized.get(key) ?? 0) + Math.max(0, count.count));
560
+ }
561
+ for (const [key, value] of normalized) {
562
+ const [backend, ageBucket] = key.split(":");
563
+ observability.setGauge({
564
+ name: "opengeni_sandbox_leases_expired_draining",
565
+ help: "Current expired draining sandbox leases by backend and fixed age bucket.",
566
+ labels: { backend, age_bucket: ageBucket },
567
+ value
568
+ });
569
+ }
570
+ }
571
+ function recordRetainedProcessReconciliation(observability, outcome) {
572
+ observability.incrementCounter({
573
+ name: "opengeni_retained_process_reconciliation_total",
574
+ help: "Bounded retained-process reconciliation observations by fixed app outcome.",
575
+ labels: { outcome }
576
+ });
577
+ }
578
+ function recordCreditMicros(observability, kind, amountMicros) {
579
+ if (!observability || amountMicros <= 0) {
580
+ return;
581
+ }
582
+ observability.incrementCounter({
583
+ name: "opengeni_credit_micros_total",
584
+ help: "Total credit micros recorded by kind.",
585
+ labels: { kind },
586
+ amount: amountMicros
587
+ });
588
+ }
589
+ var MODEL_REQUEST_PHASE_BUCKETS = [
590
+ 5e-3,
591
+ 0.01,
592
+ 0.025,
593
+ 0.05,
594
+ 0.1,
595
+ 0.2,
596
+ 0.35,
597
+ 0.5,
598
+ 1,
599
+ 2,
600
+ 5,
601
+ 10,
602
+ 30,
603
+ 60,
604
+ 300
605
+ ];
606
+ function recordModelRequestPhase(observability, input) {
607
+ const outcome = input.outcome ?? "";
608
+ observability.incrementCounter({
609
+ name: "opengeni_model_request_phases_total",
610
+ help: "Provider model-request lifecycle phases by bounded phase and outcome.",
611
+ labels: { provider: input.provider, phase: input.phase, outcome }
612
+ });
613
+ observability.observeHistogram({
614
+ name: "opengeni_model_request_phase_duration_seconds",
615
+ help: "Monotonic seconds from provider dispatch to a model-request lifecycle phase.",
616
+ buckets: MODEL_REQUEST_PHASE_BUCKETS,
617
+ labels: { provider: input.provider, phase: input.phase },
618
+ value: Math.max(0, input.durationSeconds)
619
+ });
620
+ }
621
+ function contentDeltaClass(type) {
622
+ if (type === "agent.message.delta") {
623
+ return "message";
624
+ }
625
+ if (type === "agent.reasoning.delta") {
626
+ return "reasoning";
627
+ }
628
+ return null;
629
+ }
630
+ var STREAM_TTFT_BUCKETS = [0.02, 0.05, 0.1, 0.2, 0.35, 0.5, 0.75, 1, 1.5, 2, 3, 5, 10];
631
+ var STREAM_INTER_DELTA_BUCKETS = [5e-3, 0.01, 0.025, 0.05, 0.1, 0.2, 0.35, 0.5, 1, 2, 5];
632
+ var StreamTimingMetrics = class {
633
+ constructor(observability, options) {
634
+ this.observability = observability;
635
+ this.options = options;
636
+ this.now = options.now ?? (() => performance.now());
637
+ this.ttftAnchor = this.now();
638
+ }
639
+ now;
640
+ ttftAnchor;
641
+ ttftArmed = true;
642
+ lastDeltaAt = /* @__PURE__ */ new Map();
643
+ onEvent(type) {
644
+ const deltaClass = contentDeltaClass(type);
645
+ if (deltaClass === null) {
646
+ this.ttftAnchor = this.now();
647
+ this.ttftArmed = true;
648
+ this.lastDeltaAt.clear();
649
+ return;
650
+ }
651
+ const at = this.now();
652
+ if (this.ttftArmed) {
653
+ this.observability.observeHistogram({
654
+ name: "opengeni_stream_ttft_seconds",
655
+ help: "Seconds from a model (re)start to its first streamed content delta.",
656
+ buckets: STREAM_TTFT_BUCKETS,
657
+ labels: { provider: this.options.provider },
658
+ value: Math.max(0, (at - this.ttftAnchor) / 1e3)
659
+ });
660
+ this.ttftArmed = false;
661
+ }
662
+ const last = this.lastDeltaAt.get(deltaClass);
663
+ if (last !== void 0) {
664
+ this.observability.observeHistogram({
665
+ name: "opengeni_stream_inter_delta_gap_seconds",
666
+ help: "Seconds between consecutive streamed content deltas of the same class.",
667
+ buckets: STREAM_INTER_DELTA_BUCKETS,
668
+ labels: { provider: this.options.provider, class: deltaClass },
669
+ value: Math.max(0, (at - last) / 1e3)
670
+ });
671
+ }
672
+ this.lastDeltaAt.set(deltaClass, at);
673
+ }
674
+ };
675
+ var STREAM_BATCH_SIZE_BUCKETS = [1, 2, 5, 10, 20, 50, 100, 200, 500];
676
+ var STREAM_IO_BUCKETS = [1e-3, 25e-4, 5e-3, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5];
677
+ function recordBatchFlush(observability, input) {
678
+ observability.observeHistogram({
679
+ name: "opengeni_stream_batch_flush_events",
680
+ help: "Session events coalesced into one streaming batcher flush.",
681
+ buckets: STREAM_BATCH_SIZE_BUCKETS,
682
+ value: input.events
683
+ });
684
+ observability.observeHistogram({
685
+ name: "opengeni_stream_batch_flush_duration_seconds",
686
+ help: "Duration in seconds of one streaming batcher flush (append + publish).",
687
+ buckets: STREAM_IO_BUCKETS,
688
+ value: input.durationSeconds
689
+ });
690
+ }
691
+ function recordSessionEventAppendLatency(observability, input) {
692
+ observability.observeHistogram({
693
+ name: "opengeni_session_event_append_seconds",
694
+ help: "Duration in seconds of an appendSessionEvents DB write (the durable write path).",
695
+ buckets: STREAM_IO_BUCKETS,
696
+ value: input.durationSeconds
697
+ });
698
+ }
699
+ function recordSessionEventPublishLatency(observability, input) {
700
+ observability.observeHistogram({
701
+ name: "opengeni_session_event_publish_seconds",
702
+ help: "Duration in seconds of the best-effort NATS live fan-out publish (the delivery path).",
703
+ buckets: STREAM_IO_BUCKETS,
704
+ value: input.durationSeconds
705
+ });
706
+ }
707
+ var MODEL_INPUT_TOKENS_BUCKETS = [
708
+ 1e3,
709
+ 5e3,
710
+ 1e4,
711
+ 25e3,
712
+ 5e4,
713
+ 1e5,
714
+ 15e4,
715
+ 2e5,
716
+ 3e5,
717
+ 5e5,
718
+ 1e6
719
+ ];
720
+ function recordModelInputTokens(observability, provider, inputTokens) {
721
+ const normalizedInputTokens = modelUsageTokenCountOrNull(inputTokens);
722
+ if (normalizedInputTokens === null || normalizedInputTokens === 0) {
723
+ return;
724
+ }
725
+ observability.observeHistogram({
726
+ name: "opengeni_model_input_tokens",
727
+ help: "Observed input (context) tokens per model response, by provider.",
728
+ buckets: MODEL_INPUT_TOKENS_BUCKETS,
729
+ labels: { provider },
730
+ value: normalizedInputTokens
731
+ });
732
+ }
733
+ function recordContextCompaction(observability, trigger) {
734
+ observability.incrementCounter({
735
+ name: "opengeni_context_compactions_total",
736
+ help: "Total context compactions performed, by trigger.",
737
+ labels: { trigger }
738
+ });
739
+ }
740
+ var MODEL_CONTEXT_CONTRIBUTION_TOKEN_BUCKETS = [1, 8, 32, 128, 512, 2048, 8192];
741
+ function recordCompanyBrainContributions(observability, receipt) {
742
+ for (const contribution of receipt.contributions) {
743
+ const labels = {
744
+ category: contribution.category,
745
+ source: contribution.source,
746
+ inclusion_reason: contribution.inclusionReason,
747
+ authority_scope: contribution.authorityScope,
748
+ session_role: receipt.sessionRole,
749
+ memory_prompt_mode: receipt.memoryPromptMode
750
+ };
751
+ observability.incrementCounter({
752
+ name: "opengeni_model_context_contributions_total",
753
+ help: "Company Brain contributions exposed to a model, by bounded reason and authority.",
754
+ labels
755
+ });
756
+ observability.observeHistogram({
757
+ name: "opengeni_model_context_contribution_estimated_tokens",
758
+ help: "Estimated tokens per model-visible Company Brain contribution.",
759
+ buckets: MODEL_CONTEXT_CONTRIBUTION_TOKEN_BUCKETS,
760
+ labels,
761
+ value: contribution.estimatedTokens
762
+ });
763
+ }
764
+ }
765
+ var MODEL_CACHE_HIT_RATIO_BUCKETS = [
766
+ 0.05,
767
+ 0.1,
768
+ 0.2,
769
+ 0.3,
770
+ 0.4,
771
+ 0.5,
772
+ 0.6,
773
+ 0.7,
774
+ 0.8,
775
+ 0.9,
776
+ 0.95,
777
+ 0.99,
778
+ 1
779
+ ];
780
+ function recordModelCacheTokens(observability, provider, input) {
781
+ const cached = modelUsageTokenCountOrNull(input.cachedTokens);
782
+ const cacheWrite = modelUsageTokenCountOrNull(input.cacheWriteTokens);
783
+ const prompt = modelUsageTokenCountOrNull(input.promptTokens);
784
+ incrementBoundedModelCacheCounter(observability, {
785
+ name: "opengeni_model_cache_read_telemetry_total",
786
+ help: "Authoritative model calls with reported or missing cache-read telemetry, by provider.",
787
+ provider,
788
+ labels: { provider, status: cached === null ? "missing" : "reported" },
789
+ amount: 1
790
+ });
791
+ if (cached !== null && cached > 0) {
792
+ incrementBoundedModelCacheCounter(observability, {
793
+ name: "opengeni_model_cached_tokens_total",
794
+ help: "Total prompt tokens served from the provider's prompt cache, by provider.",
795
+ provider,
796
+ labels: { provider },
797
+ amount: cached
798
+ });
799
+ }
800
+ if (cacheWrite !== null && cacheWrite > 0) {
801
+ incrementBoundedModelCacheCounter(observability, {
802
+ name: "opengeni_model_cache_write_tokens_total",
803
+ help: "Total prompt tokens written to the provider's prompt cache, by provider.",
804
+ provider,
805
+ labels: { provider },
806
+ amount: cacheWrite
807
+ });
808
+ }
809
+ if (cached !== null && prompt !== null && prompt > 0) {
810
+ observability.observeHistogram({
811
+ name: "opengeni_model_cache_hit_ratio",
812
+ help: "Per-call prompt-cache hit ratio (cached/prompt tokens) by provider.",
813
+ buckets: MODEL_CACHE_HIT_RATIO_BUCKETS,
814
+ labels: { provider },
815
+ // Clamp to [0, 1]: a provider that (rarely) reports cached >= prompt must
816
+ // not skew the histogram past 1.0.
817
+ value: Math.min(1, cached / prompt)
818
+ });
819
+ }
820
+ }
821
+ function incrementBoundedModelCacheCounter(observability, input) {
822
+ const totals = modelCacheCounterTotals.get(observability) ?? /* @__PURE__ */ new Map();
823
+ if (!modelCacheCounterTotals.has(observability)) {
824
+ modelCacheCounterTotals.set(observability, totals);
825
+ }
826
+ const labelKey = Object.entries(input.labels).sort(([left], [right]) => left.localeCompare(right)).map(([key2, value]) => `${key2}=${value}`).join(",");
827
+ const key = `${input.name}:${labelKey}`;
828
+ const current = totals.get(key) ?? 0;
829
+ if (input.amount > MAX_MODEL_CACHE_COUNTER_TOTAL - current) {
830
+ observability.warn("model cache metric cumulative limit reached", {
831
+ provider: input.provider,
832
+ metric: input.name
833
+ });
834
+ return;
835
+ }
836
+ observability.incrementCounter({
837
+ name: input.name,
838
+ help: input.help,
839
+ labels: input.labels,
840
+ amount: input.amount
841
+ });
842
+ totals.set(key, current + input.amount);
843
+ }
844
+ function nonnegativeFinite(value) {
845
+ return Number.isFinite(value) && value > 0 ? value : 0;
846
+ }
847
+ function requiredTemporalNumber(value, field, options = {}) {
848
+ if (value === null || value === void 0) {
849
+ throw new Error(`Temporal stats omitted required ${field}`);
850
+ }
851
+ const parsed = Number(value);
852
+ if (!Number.isFinite(parsed) || parsed < 0 || options.integer && !Number.isSafeInteger(parsed)) {
853
+ throw new Error(`Temporal stats returned invalid ${field}: ${String(value)}`);
854
+ }
855
+ return parsed;
856
+ }
857
+ function optionalTemporalNumber(value, field, options = {}) {
858
+ return value === null || value === void 0 ? 0 : requiredTemporalNumber(value, field, options);
859
+ }
860
+ function stableAccountHash(credentialId) {
861
+ if (!credentialId) {
862
+ return "none";
863
+ }
864
+ return createHash("sha256").update(credentialId).digest("hex").slice(0, 12);
865
+ }
866
+ function modelCallAccountContext(input) {
867
+ const accountChangedFromPrevCall = input.isFirstCallOfTurn && input.servingCredentialId !== null && input.priorSessionCredentialId !== null && input.priorSessionCredentialId !== input.servingCredentialId;
868
+ return {
869
+ servingAccountHash: stableAccountHash(input.servingCredentialId),
870
+ accountChangedFromPrevCall
871
+ };
872
+ }
873
+
874
+ export {
875
+ observabilityEventLogger,
876
+ runtimeMetricsHooksForObservability,
877
+ makeMachineOpObserver,
878
+ turnLifecycleMetricsFor,
879
+ recordTurnsQueuedGauge,
880
+ normalizeTurnTaskQueueStats,
881
+ startTurnCapacityMonitor,
882
+ recordSandboxLeaseGauges,
883
+ recordSandboxInventoryProjectionSuccess,
884
+ recordSandboxInventoryProjectionFailure,
885
+ recordCreditBalanceGauges,
886
+ recordSandboxOrphansTerminated,
887
+ recordSandboxCheckpointArtifactGauges,
888
+ recordSandboxCheckpointArtifactOutcome,
889
+ recordSandboxDeadlineRotationsRequested,
890
+ recordSandboxRotationBacklogGauges,
891
+ recordRetainedProcessInventoryGauges,
892
+ recordExpiredDrainingSandboxLeaseGauges,
893
+ recordRetainedProcessReconciliation,
894
+ recordCreditMicros,
895
+ recordModelRequestPhase,
896
+ StreamTimingMetrics,
897
+ recordBatchFlush,
898
+ recordSessionEventAppendLatency,
899
+ recordSessionEventPublishLatency,
900
+ recordModelInputTokens,
901
+ recordContextCompaction,
902
+ recordCompanyBrainContributions,
903
+ recordModelCacheTokens,
904
+ modelCallAccountContext
905
+ };
906
+ //# sourceMappingURL=chunk-TYNPCG4U.js.map