maka-agent 0.2.0-dev.22.20260905 → 0.2.0-dev.24.20260907

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 (194) hide show
  1. package/dist/acp/maka-acp-agent.js +2 -1
  2. package/dist/acp/session-configuration.js +143 -0
  3. package/dist/acp/session-registry.js +90 -4
  4. package/dist/cli-core.js +2 -0
  5. package/dist/pi-transcript.js +5 -12
  6. package/dist/pi-tui-runner.js +74 -4
  7. package/dist/runtime-host-cli-context.js +167 -78
  8. package/dist/runtime-host-cli-installation.js +8 -2
  9. package/dist/runtime-host-cli.js +31 -1
  10. package/dist/runtime-host-handoff-surface.js +81 -0
  11. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  12. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  13. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  14. package/dist/runtime-host-local-handoff.js +37 -4
  15. package/dist/runtime-host-local-managed-activation.js +84 -0
  16. package/dist/runtime-host-local-source-retirement.js +18 -2
  17. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  18. package/dist/runtime-host-operator-retirement.js +50 -0
  19. package/dist/runtime-host-service-manager.js +3 -0
  20. package/dist/runtime-host-session-driver.js +4 -25
  21. package/dist/runtime-host-session-update.js +62 -0
  22. package/dist/runtime-host-tui-command.js +38 -73
  23. package/dist/runtime-host-tui-context.js +1 -0
  24. package/dist/runtime-host-tui-owner.js +226 -0
  25. package/dist/tui-copy-catalog.js +140 -3
  26. package/dist/tui-host-owner-copy.js +24 -0
  27. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  28. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  29. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  30. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  31. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  32. package/node_modules/@maka/core/dist/bot-events.js +18 -63
  33. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  34. package/node_modules/@maka/core/dist/model-call-attempt.js +0 -82
  35. package/node_modules/@maka/core/dist/model-call-usage-projection.js +0 -186
  36. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  37. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  38. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  39. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  40. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  41. package/node_modules/@maka/core/dist/record-schema.js +22 -2
  42. package/node_modules/@maka/core/dist/redaction.js +41 -58
  43. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  44. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  45. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  46. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  47. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  48. package/node_modules/@maka/core/dist/session-trace.js +5 -1
  49. package/node_modules/@maka/core/dist/session.js +54 -52
  50. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  51. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  52. package/node_modules/@maka/core/dist/usage-ledger-merge.js +7 -9
  53. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  54. package/node_modules/@maka/core/dist/workhub-creation-intent.js +34 -20
  55. package/node_modules/@maka/core/package.json +4 -0
  56. package/node_modules/@maka/eval/harbor/egress-proxy/entrypoint.sh +2 -1
  57. package/node_modules/@maka/mcp/dist/index.js +131 -1
  58. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  59. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  60. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  61. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +155 -134
  62. package/node_modules/@maka/runtime/dist/bots/base-adapter.js +17 -0
  63. package/node_modules/@maka/runtime/dist/bots/bot-test.js +38 -22
  64. package/node_modules/@maka/runtime/dist/bots/dingtalk-bridge.js +7 -5
  65. package/node_modules/@maka/runtime/dist/bots/discord-bridge.js +4 -4
  66. package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +4 -5
  67. package/node_modules/@maka/runtime/dist/bots/qq-bridge.js +6 -4
  68. package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +3 -4
  69. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +4 -5
  70. package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +17 -19
  71. package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +5 -6
  72. package/node_modules/@maka/runtime/dist/bots/ws-bridge-base.js +2 -3
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  75. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  76. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  77. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  78. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  79. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  80. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  81. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  82. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  83. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  84. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  85. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  86. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  87. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  88. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  89. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  90. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  91. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  92. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  93. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  94. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  95. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  96. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  97. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  98. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  99. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  100. package/node_modules/@maka/runtime/dist/session-trace-projection.js +3 -30
  101. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  102. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  103. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  104. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  105. package/node_modules/@maka/runtime/package.json +1 -0
  106. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  107. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +4 -1
  108. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  109. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  110. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  111. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  112. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  113. package/node_modules/@maka/runtime-host/dist/client/index.js +3 -1
  114. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  115. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +13 -0
  116. package/node_modules/@maka/runtime-host/dist/client/registered-host-termination.js +0 -59
  117. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  118. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  119. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  120. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  121. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +28 -16
  122. package/node_modules/@maka/runtime-host/dist/protocol/external-session.js +4 -0
  123. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +29 -12
  124. package/node_modules/@maka/runtime-host/dist/protocol/index.js +37 -1
  125. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +2 -0
  126. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +28 -1
  127. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  128. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  129. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  130. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  131. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +33 -0
  132. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +26 -1
  133. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +6 -1
  134. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  135. package/node_modules/@maka/runtime-host/dist/server/canonical-usage-reader.js +24 -11
  136. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  137. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +7 -4
  138. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +168 -28
  139. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  140. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  141. package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +6 -3
  142. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  143. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +108 -23
  144. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  145. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  146. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  147. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +85 -8
  148. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +7 -0
  149. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +344 -71
  150. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  151. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  152. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +201 -12
  153. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  154. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  155. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  156. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  157. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  158. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  159. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  160. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +4 -11
  161. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +44 -15
  162. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +6 -2
  163. package/node_modules/@maka/storage/dist/agent-run-store.js +44 -0
  164. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  165. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  166. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  167. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  168. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  169. package/node_modules/@maka/storage/dist/conversation-operational-state.js +4 -0
  170. package/node_modules/@maka/storage/dist/execution-stores.js +11 -7
  171. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  172. package/node_modules/@maka/storage/dist/model-call-ledger.js +199 -32
  173. package/node_modules/@maka/storage/dist/model-call-usage-sql.js +136 -0
  174. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  175. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  176. package/node_modules/@maka/storage/dist/operational-state-store-public.js +1 -1
  177. package/node_modules/@maka/storage/dist/operational-state-store.js +5 -3
  178. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  179. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  180. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  181. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  182. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  183. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  184. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  185. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  186. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +17 -1
  187. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  188. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  189. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  190. package/node_modules/@maka/storage/dist/sqlite-usage-schema.js +200 -20
  191. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  192. package/node_modules/@maka/storage/dist/usage-stores.js +6 -2
  193. package/node_modules/@maka/storage/package.json +2 -0
  194. package/package.json +1 -1
@@ -17,7 +17,11 @@
17
17
  * under the License.
18
18
  */
19
19
  import { decodeModelCallAttempt, MODEL_CALL_ATTEMPT_EVENT_TYPE, } from '@maka/core/model-call-attempt';
20
+ import { resolveUsageRange, } from '@maka/core/model-call-usage-projection';
21
+ import { usageBucketKey } from '@maka/core/usage-stats/bucket-key';
22
+ import { bucketGrouping, CACHE_READ_TOKENS, count, countableFilter, COVERAGE_SUMS, PRICED_COST, REQUEST_SUMS, TOKEN_SUMS, unreadableFilter, } from './model-call-usage-sql.js';
20
23
  import { acquireOperationalStateDatabase, } from './operational-state-store.js';
24
+ import { MODEL_CALL_COLUMNS } from './sqlite-usage-schema.js';
21
25
  export class ModelCallLedgerClosedError extends Error {
22
26
  constructor() {
23
27
  super('Model call ledger is draining or closed');
@@ -65,29 +69,112 @@ class SqliteModelCallLedger {
65
69
  const eventsPerRun = positiveInteger(input.eventsPerRun, 512, 'projection catch-up event limit');
66
70
  return this.write(() => catchUpModelCallProjection(this.#lease.database, input, limit, eventsPerRun));
67
71
  }
68
- read(range, sessionId) {
72
+ summary(query, now) {
73
+ const db = this.#open();
74
+ const range = resolveUsageRange(query.range, now);
75
+ const filter = countableFilter(query, range);
76
+ const row = db
77
+ .prepare(`SELECT ${REQUEST_SUMS}, ${TOKEN_SUMS}, ${COVERAGE_SUMS}
78
+ FROM usage_model_call_attempts WHERE ${filter.sql}`)
79
+ .get(...filter.parameters);
80
+ return {
81
+ projection: {
82
+ range,
83
+ totalRequests: count(row?.totalRequests),
84
+ totalCostUsd: count(row?.totalCostUsd),
85
+ totalDurationMs: count(row?.totalDurationMs),
86
+ totalTokens: readTokens(row),
87
+ cacheHitRequests: count(row?.cacheHitRequests),
88
+ cacheCreateRequests: count(row?.cacheCreateRequests),
89
+ errorRequests: count(row?.errorRequests),
90
+ coverage: readCoverage(row),
91
+ },
92
+ unreadableRecords: this.#unreadable(query, range),
93
+ };
94
+ }
95
+ buckets(query, groupBy, now) {
96
+ const db = this.#open();
97
+ const range = resolveUsageRange(query.range, now);
98
+ const filter = countableFilter(query, range);
99
+ const rows = db
100
+ .prepare(`SELECT MIN(provider_id) AS providerId, MIN(model_id) AS modelId,
101
+ MIN(completed_at) AS ts, COUNT(*) AS requests,
102
+ SUM(${PRICED_COST}) AS costUsd, SUM(latency_ms) AS latency,
103
+ SUM(status = 'failed') AS errors, ${TOKEN_SUMS}
104
+ FROM usage_model_call_attempts WHERE ${filter.sql}
105
+ GROUP BY ${bucketGrouping(groupBy)}`)
106
+ .all(...filter.parameters);
107
+ const buckets = rows
108
+ .map((row) => {
109
+ const requests = count(row.requests);
110
+ const tokens = readTokens(row);
111
+ const key = usageBucketKey({
112
+ providerId: String(row.providerId ?? ''),
113
+ modelId: String(row.modelId ?? ''),
114
+ ts: count(row.ts),
115
+ }, groupBy);
116
+ return {
117
+ key,
118
+ label: key,
119
+ requests,
120
+ inputTokens: tokens.input,
121
+ outputTokens: tokens.output,
122
+ cacheMissTokens: tokens.cacheMiss,
123
+ cacheReadTokens: tokens.cacheRead,
124
+ cacheWriteTokens: tokens.cacheWrite,
125
+ reasoningTokens: tokens.reasoning,
126
+ totalTokens: tokens.total,
127
+ costUsd: count(row.costUsd),
128
+ avgLatencyMs: requests === 0 ? 0 : count(row.latency) / requests,
129
+ errorRate: requests === 0 ? 0 : count(row.errors) / requests,
130
+ };
131
+ })
132
+ .sort((left, right) => right.requests - left.requests);
133
+ return {
134
+ projection: { buckets, coverage: this.#coverage(filter) },
135
+ unreadableRecords: this.#unreadable(query, range),
136
+ };
137
+ }
138
+ logs(query, now, offset, limit) {
139
+ const db = this.#open();
140
+ const range = resolveUsageRange(query.range, now);
141
+ const filter = countableFilter(query, range);
142
+ const rows = db
143
+ .prepare(`SELECT attempt_id, completed_at, call_kind, logical_call_id, connection_slug,
144
+ provider_id, model_id, cost_basis, cost_usd, latency_ms, status, error_class,
145
+ session_id, turn_id,
146
+ COALESCE(input_tokens, 0) AS input,
147
+ COALESCE(output_tokens, 0) AS output,
148
+ COALESCE(cache_miss_input_tokens, 0) AS cacheMiss,
149
+ ${CACHE_READ_TOKENS} AS cacheRead,
150
+ COALESCE(cache_write_input_tokens, 0) AS cacheWrite,
151
+ COALESCE(reasoning_tokens, 0) AS reasoning
152
+ FROM usage_model_call_attempts WHERE ${filter.sql}
153
+ ORDER BY completed_at DESC, attempt_id DESC
154
+ LIMIT ? OFFSET ?`)
155
+ .all(...filter.parameters, limit, offset);
156
+ const coverage = this.#coverage(filter);
157
+ return {
158
+ projection: { rows: rows.map(toUsageLogRow), total: coverage.attempts, coverage },
159
+ unreadableRecords: this.#unreadable(query, range),
160
+ };
161
+ }
162
+ #open() {
69
163
  if (this.#state !== 'open')
70
164
  throw new ModelCallLedgerClosedError();
71
- const rows = this.#lease.database
72
- .prepare(sessionId
73
- ? `SELECT record_json FROM usage_model_call_attempts
74
- WHERE session_id = ? AND completed_at >= ? AND completed_at <= ?
75
- ORDER BY completed_at ASC, attempt_id ASC`
76
- : `SELECT record_json FROM usage_model_call_attempts
77
- WHERE completed_at >= ? AND completed_at <= ?
78
- ORDER BY completed_at ASC, attempt_id ASC`)
79
- .all(...(sessionId ? [sessionId, range.from, range.to] : [range.from, range.to]));
80
- const attempts = [];
81
- let unreadableRecords = 0;
82
- for (const row of rows) {
83
- try {
84
- attempts.push(decodeModelCallAttempt(JSON.parse(row.record_json)));
85
- }
86
- catch {
87
- unreadableRecords += 1;
88
- }
89
- }
90
- return { attempts, unreadableRecords };
165
+ return this.#lease.database;
166
+ }
167
+ #coverage(filter) {
168
+ const row = this.#lease.database
169
+ .prepare(`SELECT ${COVERAGE_SUMS} FROM usage_model_call_attempts WHERE ${filter.sql}`)
170
+ .get(...filter.parameters);
171
+ return readCoverage(row);
172
+ }
173
+ #unreadable(query, range) {
174
+ const filter = unreadableFilter(query, range);
175
+ return count(this.#lease.database
176
+ .prepare(`SELECT COUNT(*) AS unreadable FROM usage_model_call_attempts WHERE ${filter.sql}`)
177
+ .get(...filter.parameters)?.unreadable);
91
178
  }
92
179
  async flush() {
93
180
  await this.#queue;
@@ -105,24 +192,104 @@ class SqliteModelCallLedger {
105
192
  return this.#closePromise;
106
193
  }
107
194
  }
195
+ function readTokens(row) {
196
+ return {
197
+ input: count(row?.input),
198
+ output: count(row?.output),
199
+ cacheMiss: count(row?.cacheMiss),
200
+ cacheRead: count(row?.cacheRead),
201
+ cacheWrite: count(row?.cacheWrite),
202
+ reasoning: count(row?.reasoning),
203
+ total: count(row?.total),
204
+ };
205
+ }
206
+ function readCoverage(row) {
207
+ return {
208
+ attempts: count(row?.attempts),
209
+ pricedAttempts: count(row?.pricedAttempts),
210
+ unpricedAttempts: count(row?.unpricedAttempts),
211
+ usageReportedAttempts: count(row?.usageReportedAttempts),
212
+ usagePartialAttempts: count(row?.usagePartialAttempts),
213
+ usageMissingAttempts: count(row?.usageMissingAttempts),
214
+ };
215
+ }
216
+ function toUsageLogRow(row) {
217
+ const costBasis = row.cost_basis;
218
+ return {
219
+ id: String(row.attempt_id),
220
+ ts: count(row.completed_at),
221
+ callKind: row.call_kind,
222
+ callId: String(row.logical_call_id),
223
+ ...(row.connection_slug === null ? {} : { connectionSlug: String(row.connection_slug) }),
224
+ providerId: String(row.provider_id),
225
+ modelId: String(row.model_id),
226
+ inputTokens: count(row.input),
227
+ outputTokens: count(row.output),
228
+ cacheMissTokens: count(row.cacheMiss),
229
+ cacheReadTokens: count(row.cacheRead),
230
+ cacheWriteTokens: count(row.cacheWrite),
231
+ reasoningTokens: count(row.reasoning),
232
+ totalTokens: count(row.input) + count(row.output),
233
+ // A row keeps its basis, not just its number. Collapsing an unpriced call
234
+ // to 0 here would reproduce, per row, exactly the ambiguity the coverage
235
+ // breakdown removes from the totals.
236
+ ...(costBasis === 'priced' ? { costUsd: count(row.cost_usd) } : {}),
237
+ costBasis,
238
+ latencyMs: count(row.latency_ms),
239
+ status: row.status === 'completed' ? 'success' : row.status === 'failed' ? 'error' : 'aborted',
240
+ ...(row.error_class === null ? {} : { errorClass: String(row.error_class) }),
241
+ sessionId: String(row.session_id),
242
+ turnId: String(row.turn_id),
243
+ };
244
+ }
108
245
  function positiveInteger(value, fallback, label) {
109
246
  const resolved = value ?? fallback;
110
247
  if (!Number.isSafeInteger(resolved) || resolved <= 0)
111
248
  throw new Error(`Invalid ${label}`);
112
249
  return resolved;
113
250
  }
251
+ const MODEL_CALL_UPSERT = `
252
+ INSERT INTO usage_model_call_attempts(${MODEL_CALL_COLUMNS.join(', ')})
253
+ VALUES (${MODEL_CALL_COLUMNS.map(() => '?').join(', ')})
254
+ ON CONFLICT(attempt_id) DO UPDATE SET
255
+ ${MODEL_CALL_COLUMNS.filter((column) => column !== 'attempt_id')
256
+ .map((column) => `${column} = excluded.${column}`)
257
+ .join(', ')}
258
+ `;
259
+ /**
260
+ * The attempt's pricing fields, in column order.
261
+ *
262
+ * Keyed by column so the binding list cannot drift from the table: a column
263
+ * added to `MODEL_CALL_COLUMNS` without a value here is a compile error.
264
+ */
265
+ function bindModelCallAttempt(attempt) {
266
+ const values = {
267
+ attempt_id: attempt.attemptId,
268
+ completed_at: attempt.completedAt,
269
+ session_id: attempt.sessionId,
270
+ logical_call_id: attempt.logicalCallId,
271
+ turn_id: attempt.turnId,
272
+ call_kind: attempt.callKind,
273
+ connection_slug: attempt.connectionSlug ?? null,
274
+ provider_id: attempt.providerId,
275
+ model_id: attempt.modelId,
276
+ latency_ms: attempt.latencyMs,
277
+ status: attempt.status,
278
+ error_class: attempt.errorClass ?? null,
279
+ usage_basis: attempt.usageBasis,
280
+ input_tokens: attempt.inputTokens ?? null,
281
+ output_tokens: attempt.outputTokens ?? null,
282
+ cache_read_input_tokens: attempt.cacheReadInputTokens ?? null,
283
+ cache_miss_input_tokens: attempt.cacheMissInputTokens ?? null,
284
+ cache_write_input_tokens: attempt.cacheWriteInputTokens ?? null,
285
+ reasoning_tokens: attempt.reasoningTokens ?? null,
286
+ cost_basis: attempt.costBasis,
287
+ cost_usd: attempt.costUsd ?? null,
288
+ };
289
+ return MODEL_CALL_COLUMNS.map((column) => values[column]);
290
+ }
114
291
  function writeModelCallAttempt(db, attempt) {
115
- db.prepare(`
116
- INSERT INTO usage_model_call_attempts(attempt_id, completed_at, record_json, session_id)
117
- VALUES (?, ?, ?, ?)
118
- ON CONFLICT(attempt_id) DO UPDATE SET
119
- completed_at = excluded.completed_at,
120
- record_json = excluded.record_json,
121
- session_id = excluded.session_id
122
- WHERE completed_at IS NOT excluded.completed_at
123
- OR record_json IS NOT excluded.record_json
124
- OR session_id IS NOT excluded.session_id
125
- `).run(attempt.attemptId, attempt.completedAt, JSON.stringify(attempt), attempt.sessionId);
292
+ db.prepare(MODEL_CALL_UPSERT).run(...bindModelCallAttempt(attempt));
126
293
  }
127
294
  function catchUpModelCallProjection(db, input, limit, eventsPerRun) {
128
295
  const scope = projectionScope(input);
@@ -0,0 +1,136 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ /**
20
+ * The Usage aggregation, expressed over the canonical ledger's columns.
21
+ *
22
+ * These fragments are the SQL half of rules whose vocabulary lives in
23
+ * `@maka/core`. Each one names the function it mirrors; change them together.
24
+ */
25
+ /** Mirrors `clampCacheReadTokens`: cache reads cannot exceed the prompt they came from. */
26
+ export const CACHE_READ_TOKENS = `
27
+ CASE WHEN input_tokens IS NULL
28
+ THEN COALESCE(cache_read_input_tokens, 0)
29
+ ELSE MIN(COALESCE(cache_read_input_tokens, 0), input_tokens)
30
+ END`;
31
+ /**
32
+ * Unpriced records contribute nothing rather than zero. What they cost is
33
+ * reported through coverage instead, so a total never claims a call was free
34
+ * when the price was simply never resolved.
35
+ */
36
+ export const PRICED_COST = `CASE WHEN cost_basis = 'priced' THEN COALESCE(cost_usd, 0) ELSE 0 END`;
37
+ /** Mirrors `usageStatusForAttempt`: only a provider failure is an error. */
38
+ const ERROR_ROW = `status = 'failed'`;
39
+ export const TOKEN_SUMS = `
40
+ SUM(COALESCE(input_tokens, 0)) AS input,
41
+ SUM(COALESCE(output_tokens, 0)) AS output,
42
+ SUM(COALESCE(cache_miss_input_tokens, 0)) AS cacheMiss,
43
+ SUM(${CACHE_READ_TOKENS}) AS cacheRead,
44
+ SUM(COALESCE(cache_write_input_tokens, 0)) AS cacheWrite,
45
+ SUM(COALESCE(reasoning_tokens, 0)) AS reasoning,
46
+ SUM(COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0)) AS total`;
47
+ export const COVERAGE_SUMS = `
48
+ COUNT(*) AS attempts,
49
+ SUM(cost_basis = 'priced') AS pricedAttempts,
50
+ SUM(cost_basis = 'unpriced') AS unpricedAttempts,
51
+ SUM(usage_basis = 'reported') AS usageReportedAttempts,
52
+ SUM(usage_basis = 'partial') AS usagePartialAttempts,
53
+ SUM(usage_basis = 'missing') AS usageMissingAttempts`;
54
+ export const REQUEST_SUMS = `
55
+ COUNT(*) AS totalRequests,
56
+ SUM(${PRICED_COST}) AS totalCostUsd,
57
+ SUM(latency_ms) AS totalDurationMs,
58
+ SUM((${CACHE_READ_TOKENS}) > 0) AS cacheHitRequests,
59
+ SUM(COALESCE(cache_write_input_tokens, 0) > 0) AS cacheCreateRequests,
60
+ SUM(${ERROR_ROW}) AS errorRequests`;
61
+ /**
62
+ * Rows a query addresses that can be counted.
63
+ *
64
+ * A tombstone — a row whose stored form was damaged before the ledger held
65
+ * columns — matches no filter and is excluded here; {@link unreadableFilter}
66
+ * counts it instead.
67
+ */
68
+ export function countableFilter(query, range) {
69
+ const clauses = ['cost_basis IS NOT NULL', 'completed_at >= ?', 'completed_at <= ?'];
70
+ const parameters = [range.from, range.to];
71
+ const equals = (column, value) => {
72
+ if (value === undefined)
73
+ return;
74
+ clauses.push(`${column} = ?`);
75
+ parameters.push(value);
76
+ };
77
+ equals('session_id', query.sessionId);
78
+ equals('provider_id', query.providerId);
79
+ equals('model_id', query.modelId);
80
+ equals('connection_slug', query.connectionSlug);
81
+ if (query.status !== undefined && query.status !== 'all') {
82
+ // `interrupted` joins `aborted`: both mean the call stopped short without
83
+ // the provider reporting a failure.
84
+ if (query.status === 'success')
85
+ clauses.push(`status = 'completed'`);
86
+ else if (query.status === 'error')
87
+ clauses.push(ERROR_ROW);
88
+ else
89
+ clauses.push(`status NOT IN ('completed', 'failed')`);
90
+ }
91
+ return { sql: clauses.join(' AND '), parameters };
92
+ }
93
+ /**
94
+ * Rows a query addresses whose pricing was lost.
95
+ *
96
+ * Scoped by window and Session only — the columns a tombstone keeps. Narrowing
97
+ * it by provider or status would drop the row from the report on the strength
98
+ * of a field the row no longer has, which is how a total quietly stops
99
+ * mentioning spend it cannot account for.
100
+ */
101
+ export function unreadableFilter(query, range) {
102
+ const clauses = ['cost_basis IS NULL', 'completed_at >= ?', 'completed_at <= ?'];
103
+ const parameters = [range.from, range.to];
104
+ if (query.sessionId !== undefined) {
105
+ clauses.push('session_id = ?');
106
+ parameters.push(query.sessionId);
107
+ }
108
+ return { sql: clauses.join(' AND '), parameters };
109
+ }
110
+ /**
111
+ * How SQL groups rows for a bucket query.
112
+ *
113
+ * SQLite decides only which rows belong together; the key string itself is
114
+ * still built by `usageBucketKey`, so both Usage sources keep deriving it from
115
+ * one place. `MIN(completed_at)` gives the time bucket a timestamp to name
116
+ * itself from.
117
+ */
118
+ export function bucketGrouping(groupBy) {
119
+ switch (groupBy) {
120
+ case 'provider':
121
+ return 'provider_id';
122
+ case 'model':
123
+ return 'provider_id, model_id';
124
+ case 'day':
125
+ return `strftime('%Y-%m-%d', completed_at / 1000, 'unixepoch')`;
126
+ case 'hour':
127
+ return `strftime('%Y-%m-%dT%H', completed_at / 1000, 'unixepoch')`;
128
+ case 'tool':
129
+ // Tool invocations live in their own ledger; nothing here describes them.
130
+ return `''`;
131
+ }
132
+ }
133
+ /** SQL aggregates arrive as `null` for an empty set and as bigint-safe numbers. */
134
+ export function count(value) {
135
+ return Number(value ?? 0);
136
+ }
@@ -222,7 +222,6 @@ export function convertTranscript(sessionId, messages, parts) {
222
222
  ts: turn.lastTs,
223
223
  status: 'failed',
224
224
  errorClass: 'opencode_error',
225
- partialOutputRetained: true,
226
225
  });
227
226
  }
228
227
  else if (turn.aborted) {
@@ -234,7 +233,6 @@ export function convertTranscript(sessionId, messages, parts) {
234
233
  status: 'aborted',
235
234
  abortedAt: turn.lastTs,
236
235
  abortSource: EXTERNAL_SNAPSHOT_ABORT_SOURCE,
237
- partialOutputRetained: true,
238
236
  });
239
237
  }
240
238
  else if (turn.closed) {
@@ -244,7 +242,6 @@ export function convertTranscript(sessionId, messages, parts) {
244
242
  turnId: turn.turnId,
245
243
  ts: turn.lastTs,
246
244
  status: 'completed',
247
- partialOutputRetained: true,
248
245
  });
249
246
  }
250
247
  else {
@@ -259,7 +256,6 @@ export function convertTranscript(sessionId, messages, parts) {
259
256
  status: 'aborted',
260
257
  abortedAt: turn.lastTs,
261
258
  abortSource: EXTERNAL_SNAPSHOT_ABORT_SOURCE,
262
- partialOutputRetained: true,
263
259
  });
264
260
  }
265
261
  turn = undefined;
@@ -23,13 +23,14 @@ import { dirname, relative, resolve } from 'node:path';
23
23
  import { DatabaseSync } from 'node:sqlite';
24
24
  import { decodeArtifactRecordJsons } from './artifact-metadata-codec.js';
25
25
  import { withArtifactWriterLock } from './artifact-writer-lock.js';
26
+ import { withOfflineContextSnapshot, copyContextSnapshot, validateContextSnapshot, } from './context-offload-snapshot.js';
26
27
  import { decodeStoredMessage } from './execution-record-codec.js';
27
28
  import { acquireOperationalStateDatabase, inspectOperationalStateSchema, OPERATIONAL_STATE_DATABASE_NAME, } from './operational-state-store.js';
28
29
  import { assertCurrentOperationalTargetSchema } from './operational-target-schema.js';
29
30
  import { SQLITE_SESSION_MESSAGE_CHUNK_BYTES, SQLITE_SESSION_MESSAGE_CHUNK_MARKER, } from './sqlite-session-metadata-schema.js';
30
31
  import { syncDirectory, syncDirectoryChain, syncFile } from './stable-storage.js';
31
32
  export const OPERATIONAL_BACKUP_FORMAT = 'maka-operational-backup';
32
- export const OPERATIONAL_BACKUP_SCHEMA_VERSION = 3;
33
+ export const OPERATIONAL_BACKUP_SCHEMA_VERSION = 4;
33
34
  export const OPERATIONAL_BACKUP_MANIFEST_FILE = 'operational-backup.json';
34
35
  export class OperationalBackupError extends Error {
35
36
  code;
@@ -44,7 +45,7 @@ export async function createOperationalStateBackup(input) {
44
45
  const destinationRoot = resolve(input.destinationRoot);
45
46
  assertSeparateRoots(stateRoot, destinationRoot);
46
47
  await assertMissing(destinationRoot, 'backup destination');
47
- return withArtifactWriterLock(stateRoot, async (canonicalStateRoot) => {
48
+ return withOfflineContextSnapshot(stateRoot, (contextLocked) => withArtifactWriterLock(stateRoot, async (canonicalStateRoot) => {
48
49
  assertSeparateRoots(canonicalStateRoot, destinationRoot);
49
50
  const stagingRoot = `${destinationRoot}.${process.pid}.${randomUUID()}.tmp`;
50
51
  try {
@@ -64,6 +65,7 @@ export async function createOperationalStateBackup(input) {
64
65
  if (await pathExists(artifactRoot)) {
65
66
  await copyRegularTree(artifactRoot, resolve(stagingRoot, 'artifacts'), artifactRoot, stagingRoot);
66
67
  }
68
+ await copyContextSnapshot(canonicalStateRoot, stagingRoot, contextLocked);
67
69
  const createdAt = (input.now ?? Date.now)();
68
70
  if (!Number.isSafeInteger(createdAt) || createdAt < 0) {
69
71
  throw new OperationalBackupError('corrupt_backup', 'Backup creation time is invalid');
@@ -92,7 +94,7 @@ export async function createOperationalStateBackup(input) {
92
94
  await rm(stagingRoot, { recursive: true, force: true }).catch(() => { });
93
95
  throw error;
94
96
  }
95
- });
97
+ }));
96
98
  }
97
99
  export async function validateOperationalStateBackup(backupRoot) {
98
100
  const root = resolve(backupRoot);
@@ -111,6 +113,7 @@ export async function validateOperationalStateBackup(backupRoot) {
111
113
  throw new OperationalBackupError('corrupt_backup', 'Backup file inventory does not match');
112
114
  }
113
115
  validateSqlite(resolve(root, OPERATIONAL_STATE_DATABASE_NAME), manifest.files);
116
+ await validateContextSnapshot(root);
114
117
  return manifest;
115
118
  }
116
119
  export async function restoreOperationalStateBackup(input) {
@@ -136,6 +139,7 @@ export async function restoreOperationalStateBackup(input) {
136
139
  throw new OperationalBackupError('corrupt_backup', 'Restored file inventory does not match');
137
140
  }
138
141
  validateSqlite(resolve(stagingRoot, OPERATIONAL_STATE_DATABASE_NAME), manifest.files);
142
+ await validateContextSnapshot(stagingRoot);
139
143
  await syncDirectoryChain(stagingRoot, stagingRoot);
140
144
  await mkdir(dirname(destinationRoot), { recursive: true });
141
145
  await rename(stagingRoot, destinationRoot);
@@ -155,7 +159,7 @@ function decodeManifest(value) {
155
159
  if (record.format !== OPERATIONAL_BACKUP_FORMAT) {
156
160
  throw new OperationalBackupError('corrupt_backup', 'Backup format is invalid');
157
161
  }
158
- if (record.schemaVersion !== OPERATIONAL_BACKUP_SCHEMA_VERSION) {
162
+ if (record.schemaVersion !== 3 && record.schemaVersion !== OPERATIONAL_BACKUP_SCHEMA_VERSION) {
159
163
  throw new OperationalBackupError('unsupported_schema', 'Backup schema is unsupported');
160
164
  }
161
165
  if (!Number.isSafeInteger(record.createdAt) ||
@@ -184,7 +188,7 @@ function decodeManifest(value) {
184
188
  }
185
189
  return {
186
190
  format: OPERATIONAL_BACKUP_FORMAT,
187
- schemaVersion: OPERATIONAL_BACKUP_SCHEMA_VERSION,
191
+ schemaVersion: record.schemaVersion,
188
192
  createdAt: record.createdAt,
189
193
  files,
190
194
  };
@@ -23,4 +23,4 @@
23
23
  * against a caller-supplied database and stay package-private, exactly as the
24
24
  * deleted barrel kept them.
25
25
  */
26
- export { acquireOperationalStateDatabase, OPERATIONAL_STATE_DATABASE_NAME, OPERATIONAL_STATE_SCHEMA_VERSION, resolveOperationalStateDatabasePath, } from './operational-state-store.js';
26
+ export { acquireOperationalStateDatabase, OperationalStateMigrationBlockedError, OPERATIONAL_STATE_DATABASE_NAME, OPERATIONAL_STATE_SCHEMA_VERSION, resolveOperationalStateDatabasePath, } from './operational-state-store.js';
@@ -106,11 +106,13 @@ const RELEASED_CUTOVER_STORE_VALIDATION_KEYS = new Map([
106
106
  const require = createRequire(import.meta.url);
107
107
  const owners = new Map();
108
108
  export class OperationalStateMigrationBlockedError extends Error {
109
+ reason;
109
110
  code = 'operational_state_migration_blocked';
110
- constructor(cause) {
111
+ constructor(cause, reason = 'blocked') {
111
112
  super(cause instanceof Error ? cause.message : 'Operational state migration is blocked', {
112
113
  cause,
113
114
  });
115
+ this.reason = reason;
114
116
  this.name = 'OperationalStateMigrationBlockedError';
115
117
  }
116
118
  }
@@ -139,7 +141,7 @@ class OperationalStateDatabaseOwner {
139
141
  constructor(databasePath, options) {
140
142
  this.databasePath = databasePath;
141
143
  if (options.schemaMigration === 'require_current' && !existsSync(databasePath)) {
142
- throw new OperationalStateMigrationBlockedError(new Error('Operational state has not been initialized by its Runtime Host'));
144
+ throw new OperationalStateMigrationBlockedError(new Error('Operational state has not been initialized by its Runtime Host'), 'requires_host_migration');
143
145
  }
144
146
  mkdirSync(dirname(databasePath), { recursive: true });
145
147
  const Database = loadDatabaseSync();
@@ -234,7 +236,7 @@ function requireCurrentOperationalState(database) {
234
236
  const inspection = inspectOperationalStateSchema(database);
235
237
  if (inspection.status === 'current' && isCurrentOperationalTargetSchema(database))
236
238
  return;
237
- throw new Error('Operational state requires migration by its Runtime Host');
239
+ throw new OperationalStateMigrationBlockedError(new Error('Operational state requires migration by its Runtime Host'), 'requires_host_migration');
238
240
  }
239
241
  catch (error) {
240
242
  if (isSqliteEnvironmentError(error))
@@ -48,6 +48,7 @@ export async function openRuntimeEventReadPersistence(input) {
48
48
  readRuntimeEventsBounded: (sessionId, runId, budget) => store.readRuntimeEventsBounded(sessionId, runId, budget),
49
49
  readImmutableRuntimeEvents: (sessionId, runId) => store.readImmutableRuntimeEvents(sessionId, runId),
50
50
  readSessionRuntimeEvents: (sessionId) => store.readSessionRuntimeEvents(sessionId),
51
+ readSessionRuntimeEventEntries: (sessionId) => store.readSessionRuntimeEventEntries(sessionId),
51
52
  }),
52
53
  close: () => store.close(),
53
54
  };