maka-agent 0.2.0-dev.48.20260923 → 0.2.0-dev.49.20260924
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.
- package/dist/acp/session-event-mapper.js +1 -4
- package/dist/onboarding-catalog.js +20 -4
- package/dist/pi-transcript.js +0 -8
- package/dist/pi-tui-pickers.js +1 -1
- package/dist/pi-tui-runner.js +6 -4
- package/dist/runtime-host-onboarding.js +5 -3
- package/dist/runtime-host-session-channel.js +9 -3
- package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
- package/node_modules/@maka/core/dist/events.js +13 -0
- package/node_modules/@maka/core/dist/llm-connections.js +2 -5
- package/node_modules/@maka/core/dist/model-facts.js +2 -4
- package/node_modules/@maka/core/dist/model-metadata.generated.js +345 -248
- package/node_modules/@maka/core/dist/model-thinking.js +17 -17
- package/node_modules/@maka/core/dist/model-web-search.js +7 -9
- package/node_modules/@maka/core/dist/models-dev-projection.js +1 -1
- package/node_modules/@maka/core/dist/onboarding.js +1 -4
- package/node_modules/@maka/core/dist/provider-registry.js +60 -86
- package/node_modules/@maka/core/dist/runtime-event.js +2 -2
- package/node_modules/@maka/core/dist/runtime-policy/connection-catalog-codec.js +28 -16
- package/node_modules/@maka/core/dist/runtime-policy.js +1 -1
- package/node_modules/@maka/core/dist/session.js +23 -9
- package/node_modules/@maka/core/dist/transcript-search.js +1 -0
- package/node_modules/@maka/core/dist/usage-stats/types.js +1 -0
- package/node_modules/@maka/eval/dist/harbor-maka-subject.js +3 -0
- package/node_modules/@maka/eval/dist/maka-subject.js +8 -1
- package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +1 -11
- package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +2 -12
- package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +3 -71
- package/node_modules/@maka/runtime/dist/conversation-copy.js +2 -2
- package/node_modules/@maka/runtime/dist/local-web-fetch.js +23 -11
- package/node_modules/@maka/runtime/dist/model-adapter.js +10 -5
- package/node_modules/@maka/runtime/dist/model-factory.js +33 -30
- package/node_modules/@maka/runtime/dist/model-fetcher.js +4 -1
- package/node_modules/@maka/runtime/dist/model-runtime.js +3 -9
- package/node_modules/@maka/runtime/dist/read-page.js +11 -8
- package/node_modules/@maka/runtime/dist/recovery-resolver.js +47 -20
- package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +1 -0
- package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +39 -8
- package/node_modules/@maka/runtime/dist/session-manager.js +12 -2
- package/node_modules/@maka/runtime/dist/telemetry/model-pricing.generated.js +141 -134
- package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +3 -3
- package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +7 -6
- package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +28 -62
- package/node_modules/@maka/runtime-host/dist/client/hosted-execution-target.js +7 -1
- package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +3 -0
- package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +6 -3
- package/node_modules/@maka/runtime-host/dist/protocol/index.js +5 -1
- package/node_modules/@maka/runtime-host/dist/protocol/operations.js +4 -1
- package/node_modules/@maka/runtime-host/dist/protocol/prompt-suggestions.js +61 -0
- package/node_modules/@maka/runtime-host/dist/protocol/runtime-policy.js +4 -1
- package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +2 -1
- package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +3 -0
- package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +54 -6
- package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +38 -2
- package/node_modules/@maka/runtime-host/dist/server/generated-text.js +39 -0
- package/node_modules/@maka/runtime-host/dist/server/hosted-execution-tool-profile.js +8 -0
- package/node_modules/@maka/runtime-host/dist/server/prompt-suggestion.js +179 -0
- package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +2 -2
- package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +48 -16
- package/node_modules/@maka/runtime-host/dist/server/session-title.js +3 -16
- package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +38 -3
- package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +3 -0
- package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +6 -13
- package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +35 -11
- package/node_modules/@maka/storage/dist/config-transfer.js +14 -8
- package/node_modules/@maka/storage/dist/execution-stores.js +4 -3
- package/node_modules/@maka/storage/dist/interaction-store.js +13 -0
- package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +28 -17
- package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +9 -3
- package/node_modules/@maka/storage/dist/runtime-policy/legacy-custom-connection.js +65 -0
- package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +10 -5
- package/node_modules/@maka/storage/dist/session-bundle-policy.js +11 -0
- package/node_modules/@maka/storage/dist/session-store.js +29 -6
- package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +3 -0
- package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +125 -7
- package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +5 -3
- package/node_modules/@maka/storage/dist/usage-screen.js +138 -108
- package/package.json +1 -1
|
@@ -169,9 +169,9 @@ class SqliteSessionStore {
|
|
|
169
169
|
? message
|
|
170
170
|
: undefined;
|
|
171
171
|
}
|
|
172
|
-
async readActiveWorkHubAssignmentsByTarget(targetSessionIds, maxAssignmentsPerTarget) {
|
|
172
|
+
async readActiveWorkHubAssignmentsByTarget(targetSessionIds, maxAssignmentsPerTarget, includeStopped) {
|
|
173
173
|
await this.ensureReady();
|
|
174
|
-
return this.metadata.readActiveWorkHubAssignmentsByTarget(targetSessionIds, maxAssignmentsPerTarget);
|
|
174
|
+
return this.metadata.readActiveWorkHubAssignmentsByTarget(targetSessionIds, maxAssignmentsPerTarget, includeStopped);
|
|
175
175
|
}
|
|
176
176
|
async readWorkHubReplacement(delegationId) {
|
|
177
177
|
const message = await this.readWorkHubCoordinationMessage(`whp_${workHubIdentitySuffix(delegationId)}`);
|
|
@@ -193,14 +193,37 @@ class SqliteSessionStore {
|
|
|
193
193
|
? message
|
|
194
194
|
: undefined;
|
|
195
195
|
}
|
|
196
|
-
async readWorkHubStopRequest(delegationId) {
|
|
197
|
-
const
|
|
196
|
+
async readWorkHubStopRequest(delegationId, actionId) {
|
|
197
|
+
const first = await this.readWorkHubCoordinationMessage(`whq_${workHubIdentitySuffix(delegationId)}`);
|
|
198
|
+
const message = actionId &&
|
|
199
|
+
first?.type === 'workhub_coordination' &&
|
|
200
|
+
first.kind === 'delegation_stop_requested' &&
|
|
201
|
+
first.actionId !== actionId
|
|
202
|
+
? await this.readWorkHubCoordinationMessage(`whq_${workHubIdentitySuffix(JSON.stringify([delegationId, actionId]))}`)
|
|
203
|
+
: first;
|
|
198
204
|
return message?.type === 'workhub_coordination' && message.kind === 'delegation_stop_requested'
|
|
199
205
|
? message
|
|
200
206
|
: undefined;
|
|
201
207
|
}
|
|
202
|
-
async readWorkHubStopResolution(delegationId) {
|
|
203
|
-
|
|
208
|
+
async readWorkHubStopResolution(delegationId, actionId) {
|
|
209
|
+
if (!actionId) {
|
|
210
|
+
const terminal = await this.readWorkHubCoordinationMessage(`whzt_${workHubIdentitySuffix(delegationId)}`);
|
|
211
|
+
if (terminal?.type === 'workhub_coordination' &&
|
|
212
|
+
terminal.kind === 'delegation_stop_resolved' &&
|
|
213
|
+
terminal.outcome !== 'not_owned')
|
|
214
|
+
return terminal;
|
|
215
|
+
}
|
|
216
|
+
const scoped = actionId
|
|
217
|
+
? await this.readWorkHubCoordinationMessage(`whz_${workHubIdentitySuffix(JSON.stringify([delegationId, actionId]))}`)
|
|
218
|
+
: undefined;
|
|
219
|
+
const primary = await this.readWorkHubCoordinationMessage(`whz_${workHubIdentitySuffix(delegationId)}`);
|
|
220
|
+
const message = scoped ??
|
|
221
|
+
(actionId &&
|
|
222
|
+
primary?.type === 'workhub_coordination' &&
|
|
223
|
+
primary.kind === 'delegation_stop_resolved' &&
|
|
224
|
+
primary.actionId !== actionId
|
|
225
|
+
? undefined
|
|
226
|
+
: primary);
|
|
204
227
|
return message?.type === 'workhub_coordination' && message.kind === 'delegation_stop_resolved'
|
|
205
228
|
? message
|
|
206
229
|
: undefined;
|
|
@@ -105,6 +105,9 @@ export function migrateSqliteCoreExecutionDatabase(db) {
|
|
|
105
105
|
CREATE INDEX IF NOT EXISTS core_interaction_pending
|
|
106
106
|
ON core_interaction_requests(session_id, created_at, request_id);
|
|
107
107
|
|
|
108
|
+
CREATE INDEX IF NOT EXISTS core_interaction_requests_by_turn
|
|
109
|
+
ON core_interaction_requests(session_id, turn_id, created_at, request_id);
|
|
110
|
+
|
|
108
111
|
CREATE TABLE IF NOT EXISTS core_interaction_outcomes (
|
|
109
112
|
request_id TEXT PRIMARY KEY,
|
|
110
113
|
record_json TEXT NOT NULL,
|
|
@@ -270,7 +270,11 @@ export class SqliteRuntimeStore {
|
|
|
270
270
|
if (events.some(isToolLedgerBearingEvent)) {
|
|
271
271
|
this.assertToolLedgerTransition(events, 'generic_append');
|
|
272
272
|
}
|
|
273
|
-
|
|
273
|
+
// Batch imports preserve already-persisted history, including legacy
|
|
274
|
+
// terminal/tool gaps that recovery will classify when projections are
|
|
275
|
+
// rebuilt. New terminal writes through appendRuntimeEvent must obey the
|
|
276
|
+
// unsettled-operation invariant below.
|
|
277
|
+
const created = events.map((event) => this.importRuntimeEventSync(event, true));
|
|
274
278
|
return { created };
|
|
275
279
|
});
|
|
276
280
|
}
|
|
@@ -2666,6 +2670,65 @@ export class SqliteRuntimeStore {
|
|
|
2666
2670
|
async rebuildToolProjectionsFromRuntimeEvents() {
|
|
2667
2671
|
return this.transaction(() => this.rebuildToolProjectionsFromRuntimeEventsSync());
|
|
2668
2672
|
}
|
|
2673
|
+
/** Rebuild one Session's disposable tool projections while its owner holds a fence. */
|
|
2674
|
+
async rebuildToolProjectionsForSession(sessionId) {
|
|
2675
|
+
await this.transaction(() => this.rebuildToolProjectionsFromRuntimeEventsSync(sessionId));
|
|
2676
|
+
}
|
|
2677
|
+
/**
|
|
2678
|
+
* Repair terminal projections for unsettled tools without decoding the
|
|
2679
|
+
* Session's full RuntimeEvent history. Bundle export is a compatibility
|
|
2680
|
+
* boundary: unrelated historical payloads may be byte-preserved and newer
|
|
2681
|
+
* or older than the RuntimeEvent schema understood by this build.
|
|
2682
|
+
*/
|
|
2683
|
+
async rebuildTerminalToolProjectionsForSessions(sessionIds) {
|
|
2684
|
+
const operations = await this.listUnsettledToolOperations(sessionIds);
|
|
2685
|
+
if (operations.length === 0)
|
|
2686
|
+
return;
|
|
2687
|
+
this.transaction(() => {
|
|
2688
|
+
const dispatchSequence = this.db.prepare(`
|
|
2689
|
+
SELECT event_seq
|
|
2690
|
+
FROM runtime_events
|
|
2691
|
+
WHERE event_id = ? AND session_id = ? AND invocation_id = ?
|
|
2692
|
+
`);
|
|
2693
|
+
const firstTerminal = this.db.prepare(`
|
|
2694
|
+
SELECT event_id, event_seq, committed_at
|
|
2695
|
+
FROM runtime_events
|
|
2696
|
+
WHERE session_id = ? AND invocation_id = ?
|
|
2697
|
+
AND ${TERMINAL_RUNTIME_EVENT_SQL}
|
|
2698
|
+
ORDER BY event_seq ASC, event_id ASC
|
|
2699
|
+
LIMIT 1
|
|
2700
|
+
`);
|
|
2701
|
+
const insertJournal = this.db.prepare(`
|
|
2702
|
+
INSERT INTO tool_journal_events (
|
|
2703
|
+
journal_event_id, operation_id, invocation_id, run_id, turn_id, state,
|
|
2704
|
+
runtime_event_id, canonical_args_hash, recovery_mode, committed_at
|
|
2705
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2706
|
+
`);
|
|
2707
|
+
const updateOperation = this.db.prepare(`
|
|
2708
|
+
UPDATE tool_operations
|
|
2709
|
+
SET current_state = ?, version = version + 1
|
|
2710
|
+
WHERE operation_id = ? AND current_state = 'prepared' AND result_event_id IS NULL
|
|
2711
|
+
`);
|
|
2712
|
+
for (const operation of operations) {
|
|
2713
|
+
if (!operation.dispatchEventId)
|
|
2714
|
+
continue;
|
|
2715
|
+
const dispatch = dispatchSequence.get(operation.dispatchEventId, operation.sessionId, operation.invocationId);
|
|
2716
|
+
if (!dispatch)
|
|
2717
|
+
continue;
|
|
2718
|
+
const terminal = firstTerminal.get(operation.sessionId, operation.invocationId);
|
|
2719
|
+
if (!terminal || terminal.event_seq <= dispatch.event_seq)
|
|
2720
|
+
continue;
|
|
2721
|
+
const state = operation.toolName === 'AskUserQuestion' && operation.recoveryMode === 'never_auto_retry'
|
|
2722
|
+
? 'abandoned'
|
|
2723
|
+
: 'interrupted_unknown';
|
|
2724
|
+
insertJournal.run(journalEventIdFor(operation.operationId, terminal.event_id, state), operation.operationId, operation.invocationId, operation.runId, operation.turnId, state, terminal.event_id, operation.canonicalArgsHash, operation.recoveryMode, terminal.committed_at);
|
|
2725
|
+
const updated = updateOperation.run(state, operation.operationId);
|
|
2726
|
+
if (updated.changes !== 1) {
|
|
2727
|
+
throw new Error(`Tool operation projection changed during export: ${operation.operationId}`);
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
});
|
|
2731
|
+
}
|
|
2669
2732
|
rebuildToolProjectionsFromRuntimeEventsSync(sessionId) {
|
|
2670
2733
|
const statement = this.db.prepare(`
|
|
2671
2734
|
SELECT event_id, session_id, invocation_id, run_id, turn_id,
|
|
@@ -2679,6 +2742,14 @@ export class SqliteRuntimeStore {
|
|
|
2679
2742
|
: statement.all(sessionId));
|
|
2680
2743
|
const events = rows.map(decodeRuntimeEventStorageRow);
|
|
2681
2744
|
const eventOrder = new Map(events.map((event, index) => [event.id, index]));
|
|
2745
|
+
const runtimeInvocationKey = (event) => JSON.stringify([event.sessionId, event.invocationId]);
|
|
2746
|
+
const terminalEventsByInvocation = new Map();
|
|
2747
|
+
for (const event of events) {
|
|
2748
|
+
if (isTerminalRuntimeEvent(event) &&
|
|
2749
|
+
!terminalEventsByInvocation.has(runtimeInvocationKey(event))) {
|
|
2750
|
+
terminalEventsByInvocation.set(runtimeInvocationKey(event), event);
|
|
2751
|
+
}
|
|
2752
|
+
}
|
|
2682
2753
|
const committedAt = new Map(rows.map((row, index) => [events[index].id, row.committed_at]));
|
|
2683
2754
|
const scan = scanToolLedger(events);
|
|
2684
2755
|
if (scan.hasCorruption) {
|
|
@@ -2736,6 +2807,21 @@ export class SqliteRuntimeStore {
|
|
|
2736
2807
|
}
|
|
2737
2808
|
const reconcileEvent = recovery.kind === 'valid' ? recovery.reconcileEvent : undefined;
|
|
2738
2809
|
const decisionEvent = recovery.kind === 'valid' ? recovery.decisionEvent : undefined;
|
|
2810
|
+
const decision = recovery.kind === 'valid' ? recovery.decision : undefined;
|
|
2811
|
+
const terminalEvent = terminalEventsByInvocation.get(runtimeInvocationKey(event));
|
|
2812
|
+
const terminalAfterDispatch = terminalEvent !== undefined &&
|
|
2813
|
+
requireRuntimeEventOrder(eventOrder, terminalEvent.id) >
|
|
2814
|
+
requireRuntimeEventOrder(eventOrder, event.id);
|
|
2815
|
+
const abandoned = !decision &&
|
|
2816
|
+
!operation.responseEvent &&
|
|
2817
|
+
dispatch.toolName === 'AskUserQuestion' &&
|
|
2818
|
+
dispatch.recoveryMode === 'never_auto_retry' &&
|
|
2819
|
+
terminalAfterDispatch;
|
|
2820
|
+
// A terminal invocation closes the tool's execution window, but does not
|
|
2821
|
+
// prove whether an external side effect completed. Preserve that
|
|
2822
|
+
// uncertainty in the query projection without rewriting the immutable
|
|
2823
|
+
// RuntimeEvent history.
|
|
2824
|
+
const interruptedUnknown = !decision && !operation.responseEvent && !abandoned && terminalAfterDispatch;
|
|
2739
2825
|
this.db
|
|
2740
2826
|
.prepare(`
|
|
2741
2827
|
INSERT INTO tool_journal_events (
|
|
@@ -2746,14 +2832,17 @@ export class SqliteRuntimeStore {
|
|
|
2746
2832
|
.run(`${dispatch.operationId}_prepared`, dispatch.operationId, event.invocationId, event.runId, event.turnId, event.id, dispatch.canonicalArgsHash, dispatch.recoveryMode, committedAt.get(event.id) ?? event.ts);
|
|
2747
2833
|
journalEvents += 1;
|
|
2748
2834
|
const response = operation.responseEvent;
|
|
2749
|
-
const decision = recovery.kind === 'valid' ? recovery.decision : undefined;
|
|
2750
2835
|
const currentState = decision
|
|
2751
2836
|
? decision.disposition === 'completed'
|
|
2752
2837
|
? 'recovery_completed'
|
|
2753
2838
|
: 'recovery_parked'
|
|
2754
2839
|
: response
|
|
2755
2840
|
? 'outcome_committed'
|
|
2756
|
-
:
|
|
2841
|
+
: abandoned
|
|
2842
|
+
? 'abandoned'
|
|
2843
|
+
: interruptedUnknown
|
|
2844
|
+
? 'interrupted_unknown'
|
|
2845
|
+
: 'prepared';
|
|
2757
2846
|
const tail = [
|
|
2758
2847
|
...(reconcileEvent
|
|
2759
2848
|
? [{ event: reconcileEvent, state: 'reconcile_observed' }]
|
|
@@ -2769,6 +2858,12 @@ export class SqliteRuntimeStore {
|
|
|
2769
2858
|
},
|
|
2770
2859
|
]
|
|
2771
2860
|
: []),
|
|
2861
|
+
...(abandoned && terminalEvent
|
|
2862
|
+
? [{ event: terminalEvent, state: 'abandoned' }]
|
|
2863
|
+
: []),
|
|
2864
|
+
...(interruptedUnknown && terminalEvent
|
|
2865
|
+
? [{ event: terminalEvent, state: 'interrupted_unknown' }]
|
|
2866
|
+
: []),
|
|
2772
2867
|
].sort((a, b) => requireRuntimeEventOrder(eventOrder, a.event.id) -
|
|
2773
2868
|
requireRuntimeEventOrder(eventOrder, b.event.id));
|
|
2774
2869
|
this.db
|
|
@@ -2788,7 +2883,7 @@ export class SqliteRuntimeStore {
|
|
|
2788
2883
|
runtime_event_id, canonical_args_hash, recovery_mode, metadata_json, committed_at
|
|
2789
2884
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2790
2885
|
`)
|
|
2791
|
-
.run(journalEventIdFor(dispatch.operationId, item.event, item.state), dispatch.operationId, item.event.invocationId, item.event.runId, item.event.turnId, item.state, item.event.id, dispatch.canonicalArgsHash, dispatch.recoveryMode, item.event.actions?.toolRecovery
|
|
2886
|
+
.run(journalEventIdFor(dispatch.operationId, item.event.id, item.state), dispatch.operationId, item.event.invocationId, item.event.runId, item.event.turnId, item.state, item.event.id, dispatch.canonicalArgsHash, dispatch.recoveryMode, item.event.actions?.toolRecovery
|
|
2792
2887
|
? JSON.stringify(item.event.actions.toolRecovery)
|
|
2793
2888
|
: null, committedAt.get(item.event.id) ?? item.event.ts);
|
|
2794
2889
|
journalEvents += 1;
|
|
@@ -3556,7 +3651,7 @@ export class SqliteRuntimeStore {
|
|
|
3556
3651
|
throw new RunSealedError(event.runId);
|
|
3557
3652
|
}
|
|
3558
3653
|
}
|
|
3559
|
-
importRuntimeEventSync(event) {
|
|
3654
|
+
importRuntimeEventSync(event, allowLegacyTerminalWithUnsettledOperation = false) {
|
|
3560
3655
|
const canonicalEvent = canonicalizeRuntimeEventForStorage(event);
|
|
3561
3656
|
this.assertInvocationIdentity([canonicalEvent]);
|
|
3562
3657
|
const partial = partialRuntimeStream(canonicalEvent);
|
|
@@ -3575,6 +3670,21 @@ export class SqliteRuntimeStore {
|
|
|
3575
3670
|
// consult either.
|
|
3576
3671
|
if (!existing) {
|
|
3577
3672
|
this.assertContinuationAuthorityAllowsEvent(canonicalEvent);
|
|
3673
|
+
if (isTerminalRuntimeEvent(canonicalEvent) && !allowLegacyTerminalWithUnsettledOperation) {
|
|
3674
|
+
const unresolved = this.db
|
|
3675
|
+
.prepare(`
|
|
3676
|
+
SELECT operation_id FROM tool_operations
|
|
3677
|
+
WHERE invocation_id = ?
|
|
3678
|
+
AND current_state = 'prepared'
|
|
3679
|
+
AND result_event_id IS NULL
|
|
3680
|
+
AND dispatch_event_id IS NOT NULL
|
|
3681
|
+
LIMIT 1
|
|
3682
|
+
`)
|
|
3683
|
+
.get(canonicalEvent.invocationId);
|
|
3684
|
+
if (unresolved && typeof unresolved.operation_id === 'string') {
|
|
3685
|
+
throw new Error(`Cannot terminalize invocation ${canonicalEvent.invocationId} with unsettled tool operation ${unresolved.operation_id}`);
|
|
3686
|
+
}
|
|
3687
|
+
}
|
|
3578
3688
|
this.assertRunNotSealed(canonicalEvent);
|
|
3579
3689
|
}
|
|
3580
3690
|
if (isToolLedgerBearingEvent(canonicalEvent)) {
|
|
@@ -3947,8 +4057,16 @@ function requireRuntimeEventOrder(eventOrder, eventId) {
|
|
|
3947
4057
|
throw new Error(`Missing RuntimeEvent order for ${eventId}`);
|
|
3948
4058
|
return order;
|
|
3949
4059
|
}
|
|
3950
|
-
function journalEventIdFor(operationId,
|
|
3951
|
-
|
|
4060
|
+
function journalEventIdFor(operationId, eventId, state) {
|
|
4061
|
+
if (state === 'outcome_committed')
|
|
4062
|
+
return `${operationId}_outcome`;
|
|
4063
|
+
if (state === 'abandoned' || state === 'interrupted_unknown') {
|
|
4064
|
+
// One invocation terminal can close multiple tool operations. Its journal
|
|
4065
|
+
// fact is therefore unique per operation, unlike per-operation recovery
|
|
4066
|
+
// events whose RuntimeEvent ids are already distinct.
|
|
4067
|
+
return `${operationId}_${eventId}_journal`;
|
|
4068
|
+
}
|
|
4069
|
+
return `${eventId}_journal`;
|
|
3952
4070
|
}
|
|
3953
4071
|
function assertRecoveryAuthorityCapability(db) {
|
|
3954
4072
|
const row = db
|
|
@@ -1511,7 +1511,7 @@ export class SqliteSessionMetadataStore {
|
|
|
1511
1511
|
return rows.map((row) => decodeMessageAdmissionRow(sessionId, row));
|
|
1512
1512
|
});
|
|
1513
1513
|
}
|
|
1514
|
-
async readActiveWorkHubAssignmentsByTarget(targetSessionIds, maxAssignmentsPerTarget) {
|
|
1514
|
+
async readActiveWorkHubAssignmentsByTarget(targetSessionIds, maxAssignmentsPerTarget, includeStopped) {
|
|
1515
1515
|
this.assertOpen();
|
|
1516
1516
|
for (const sessionId of targetSessionIds)
|
|
1517
1517
|
assertSafeSessionId(sessionId);
|
|
@@ -1596,8 +1596,10 @@ export class SqliteSessionMetadataStore {
|
|
|
1596
1596
|
replacementAbort.kind === 'delegation_replacement_aborted') {
|
|
1597
1597
|
continue;
|
|
1598
1598
|
}
|
|
1599
|
-
const stopResolution = this.readMessageByIdSync(WORKHUB_COORDINATION_SESSION_ID, `
|
|
1600
|
-
|
|
1599
|
+
const stopResolution = this.readMessageByIdSync(WORKHUB_COORDINATION_SESSION_ID, `whzt_${terminalSuffix}`) ??
|
|
1600
|
+
this.readMessageByIdSync(WORKHUB_COORDINATION_SESSION_ID, `whz_${terminalSuffix}`);
|
|
1601
|
+
if (!includeStopped &&
|
|
1602
|
+
stopResolution?.type === 'workhub_coordination' &&
|
|
1601
1603
|
stopResolution.kind === 'delegation_stop_resolved' &&
|
|
1602
1604
|
stopResolution.outcome !== 'not_owned') {
|
|
1603
1605
|
continue;
|
|
@@ -62,8 +62,16 @@ export function createUsageScreenReader(root) {
|
|
|
62
62
|
// backup. This lifecycle fence prevents tokens from surviving that reopen.
|
|
63
63
|
const generation = randomUUID();
|
|
64
64
|
const db = lease.database;
|
|
65
|
+
// One complete range per reader; changing filters does not retain history or
|
|
66
|
+
// grow the cache. Revision includes the database incarnation and lifecycle.
|
|
67
|
+
let cached;
|
|
68
|
+
let closed = false;
|
|
65
69
|
return {
|
|
66
|
-
close: () =>
|
|
70
|
+
close: () => {
|
|
71
|
+
closed = true;
|
|
72
|
+
cached = undefined;
|
|
73
|
+
lease.close();
|
|
74
|
+
},
|
|
67
75
|
read: (input) => lease.transaction('read', () => {
|
|
68
76
|
validateQuery(input.query);
|
|
69
77
|
const state = db
|
|
@@ -83,124 +91,146 @@ export function createUsageScreenReader(root) {
|
|
|
83
91
|
page: { revision, queryIdentity, ...activity(db, input.query, input.cursor) },
|
|
84
92
|
};
|
|
85
93
|
}
|
|
86
|
-
const
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
SUM(source = 'canonical') AS attempts, SUM(costBasis = 'priced') AS pricedAttempts,
|
|
94
|
-
SUM(costBasis = 'unpriced') AS unpricedAttempts, SUM(usageBasis = 'reported') AS usageReportedAttempts,
|
|
95
|
-
SUM(usageBasis = 'partial') AS usagePartialAttempts, SUM(usageBasis = 'missing') AS usageMissingAttempts
|
|
96
|
-
FROM rows`)
|
|
97
|
-
.get(...modelArgs);
|
|
98
|
-
const breakdown = (column) => db
|
|
99
|
-
.prepare(`WITH rows AS (${MODEL_ROWS})
|
|
100
|
-
SELECT ${column} AS name, COUNT(*) AS requests, SUM(inputTokens + outputTokens) AS tokens,
|
|
101
|
-
COALESCE(SUM(costUsd), 0) AS costUsd FROM rows GROUP BY ${column} ORDER BY requests DESC, name LIMIT 101`)
|
|
102
|
-
.all(...modelArgs);
|
|
103
|
-
const tools = db
|
|
104
|
-
.prepare(`WITH rows AS (${TOOL_ROWS}) SELECT toolName AS tool,
|
|
105
|
-
COUNT(*) AS calls, SUM(status = 'success') AS success, SUM(status = 'error') AS errors,
|
|
106
|
-
ROUND(AVG(latencyMs)) AS avgDurationMs FROM rows GROUP BY toolName ORDER BY calls DESC, toolName LIMIT 101`)
|
|
107
|
-
.all(...rangeArgs);
|
|
108
|
-
const providers = breakdown('connection');
|
|
109
|
-
const models = breakdown('model');
|
|
110
|
-
// Read one sentinel past each wire count. It can only become a whole-screen
|
|
111
|
-
// failure, never a successful truncated collection. No history array is built.
|
|
112
|
-
for (const [rows, section] of [
|
|
113
|
-
[providers, 'provider_breakdown'],
|
|
114
|
-
[models, 'model_breakdown'],
|
|
115
|
-
[tools, 'tool_breakdown'],
|
|
116
|
-
]) {
|
|
117
|
-
if (rows.length > 100)
|
|
118
|
-
return { kind: 'screen_response_too_large', section };
|
|
119
|
-
}
|
|
120
|
-
const pricing = db
|
|
121
|
-
.prepare('SELECT record_json FROM usage_pricing_overrides ORDER BY model_key LIMIT 129')
|
|
122
|
-
.all()
|
|
123
|
-
.map((row) => {
|
|
124
|
-
const value = JSON.parse(String(row.record_json));
|
|
125
|
-
const separator = value.modelKey.indexOf(':');
|
|
126
|
-
return {
|
|
127
|
-
provider: separator < 0 ? '' : value.modelKey.slice(0, separator),
|
|
128
|
-
model: separator < 0 ? value.modelKey : value.modelKey.slice(separator + 1),
|
|
129
|
-
inputPerMTokUsd: value.inputUsdPer1M,
|
|
130
|
-
outputPerMTokUsd: value.outputUsdPer1M,
|
|
131
|
-
};
|
|
132
|
-
});
|
|
133
|
-
if (pricing.length > 128)
|
|
134
|
-
return { kind: 'screen_response_too_large', section: 'pricing' };
|
|
135
|
-
const unreadable = n(db
|
|
136
|
-
.prepare(`SELECT COUNT(*) AS count FROM usage_model_call_attempts
|
|
137
|
-
WHERE completed_at >= ? AND completed_at <= ? AND cost_basis IS NULL`)
|
|
138
|
-
.get(...rangeArgs)?.count) +
|
|
139
|
-
n(db
|
|
140
|
-
.prepare('SELECT SUM(unreadable_events) AS count FROM usage_model_call_projection_checkpoints')
|
|
141
|
-
.get()?.count);
|
|
142
|
-
const pending = n(db
|
|
143
|
-
.prepare(`SELECT COUNT(*) AS count FROM core_agent_runs AS source
|
|
144
|
-
LEFT JOIN usage_model_call_projection_checkpoints AS checkpoint
|
|
145
|
-
ON checkpoint.session_id = source.session_id AND checkpoint.run_id = source.run_id
|
|
146
|
-
WHERE source.latest_model_call_sequence > COALESCE(checkpoint.applied_through_sequence, -1)`)
|
|
147
|
-
.get()?.count);
|
|
94
|
+
const { from, to } = input.query.range;
|
|
95
|
+
const hit = cached?.revision === revision && cached.from === from && cached.to === to
|
|
96
|
+
? cached
|
|
97
|
+
: undefined;
|
|
98
|
+
const statistics = hit?.statistics ?? readRangeStatistics(db, input.query.range);
|
|
99
|
+
if ('kind' in statistics)
|
|
100
|
+
return statistics;
|
|
148
101
|
const screen = {
|
|
149
102
|
revision,
|
|
150
103
|
queryIdentity,
|
|
151
104
|
query: input.query,
|
|
152
105
|
activityTotal: activityCount(db, input.query),
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
totalTokens: n(aggregate.totalTokens),
|
|
157
|
-
inputTokens: n(aggregate.inputTokens),
|
|
158
|
-
outputTokens: n(aggregate.outputTokens),
|
|
159
|
-
cacheTokens: n(aggregate.cacheRead) + n(aggregate.cacheCreation),
|
|
160
|
-
cacheMiss: n(aggregate.cacheMiss),
|
|
161
|
-
cacheRead: n(aggregate.cacheRead),
|
|
162
|
-
cacheCreation: n(aggregate.cacheCreation),
|
|
163
|
-
reasoning: n(aggregate.reasoning),
|
|
164
|
-
},
|
|
165
|
-
byProvider: providers.map((row) => ({
|
|
166
|
-
provider: String(row.name),
|
|
167
|
-
requests: n(row.requests),
|
|
168
|
-
tokens: n(row.tokens),
|
|
169
|
-
costUsd: n(row.costUsd),
|
|
170
|
-
})),
|
|
171
|
-
byModel: models.map((row) => ({
|
|
172
|
-
model: String(row.name),
|
|
173
|
-
requests: n(row.requests),
|
|
174
|
-
tokens: n(row.tokens),
|
|
175
|
-
costUsd: n(row.costUsd),
|
|
176
|
-
})),
|
|
177
|
-
byTool: tools.map((row) => ({
|
|
178
|
-
tool: String(row.tool),
|
|
179
|
-
calls: n(row.calls),
|
|
180
|
-
success: n(row.success),
|
|
181
|
-
errors: n(row.errors),
|
|
182
|
-
avgDurationMs: n(row.avgDurationMs),
|
|
183
|
-
})),
|
|
184
|
-
pricing,
|
|
185
|
-
provenance: {
|
|
186
|
-
coverage: {
|
|
187
|
-
attempts: n(aggregate.attempts),
|
|
188
|
-
pricedAttempts: n(aggregate.pricedAttempts),
|
|
189
|
-
unpricedAttempts: n(aggregate.unpricedAttempts),
|
|
190
|
-
usageReportedAttempts: n(aggregate.usageReportedAttempts),
|
|
191
|
-
usagePartialAttempts: n(aggregate.usagePartialAttempts),
|
|
192
|
-
usageMissingAttempts: n(aggregate.usageMissingAttempts),
|
|
193
|
-
},
|
|
194
|
-
legacyRecords: n(aggregate.legacyRecords),
|
|
195
|
-
unreadableRecords: unreadable,
|
|
196
|
-
pendingRepairs: pending,
|
|
197
|
-
},
|
|
106
|
+
// Host projects identities and freezes replies; returned objects must
|
|
107
|
+
// never share mutable rows or arrays with another cached response.
|
|
108
|
+
...structuredClone(statistics),
|
|
198
109
|
...activity(db, input.query),
|
|
199
110
|
};
|
|
111
|
+
if (!hit) {
|
|
112
|
+
// A nested read can observe writes that later roll back and reuse the
|
|
113
|
+
// same revision counter. Publish only after the outermost commit.
|
|
114
|
+
lease.onTransactionSettled((committed) => {
|
|
115
|
+
if (committed && !closed)
|
|
116
|
+
cached = { revision, from, to, statistics };
|
|
117
|
+
});
|
|
118
|
+
}
|
|
200
119
|
return { kind: 'screen', screen };
|
|
201
120
|
}),
|
|
202
121
|
};
|
|
203
122
|
}
|
|
123
|
+
function readRangeStatistics(db, range) {
|
|
124
|
+
const rangeArgs = [range.from, range.to];
|
|
125
|
+
const modelArgs = [...rangeArgs, ...rangeArgs];
|
|
126
|
+
const aggregate = db
|
|
127
|
+
.prepare(`WITH rows AS (${MODEL_ROWS}) SELECT
|
|
128
|
+
COUNT(*) AS totalRequests, COALESCE(SUM(costUsd), 0) AS totalCostUsd,
|
|
129
|
+
${['totalTokens', 'inputTokens', 'outputTokens', 'cacheMiss', 'cacheRead', 'cacheCreation', 'reasoning'].map((k) => `COALESCE(SUM(${k}), 0) AS ${k}`).join(', ')},
|
|
130
|
+
SUM(source = 'legacy') AS legacyRecords,
|
|
131
|
+
SUM(source = 'canonical') AS attempts, SUM(costBasis = 'priced') AS pricedAttempts,
|
|
132
|
+
SUM(costBasis = 'unpriced') AS unpricedAttempts, SUM(usageBasis = 'reported') AS usageReportedAttempts,
|
|
133
|
+
SUM(usageBasis = 'partial') AS usagePartialAttempts, SUM(usageBasis = 'missing') AS usageMissingAttempts
|
|
134
|
+
FROM rows`)
|
|
135
|
+
.get(...modelArgs);
|
|
136
|
+
const breakdown = (column) => db
|
|
137
|
+
.prepare(`WITH rows AS (${MODEL_ROWS})
|
|
138
|
+
SELECT ${column} AS name, COUNT(*) AS requests, SUM(inputTokens + outputTokens) AS tokens,
|
|
139
|
+
COALESCE(SUM(costUsd), 0) AS costUsd FROM rows GROUP BY ${column} ORDER BY requests DESC, name LIMIT 101`)
|
|
140
|
+
.all(...modelArgs);
|
|
141
|
+
const tools = db
|
|
142
|
+
.prepare(`WITH rows AS (${TOOL_ROWS}) SELECT toolName AS tool,
|
|
143
|
+
COUNT(*) AS calls, SUM(status = 'success') AS success, SUM(status = 'error') AS errors,
|
|
144
|
+
ROUND(AVG(latencyMs)) AS avgDurationMs FROM rows GROUP BY toolName ORDER BY calls DESC, toolName LIMIT 101`)
|
|
145
|
+
.all(...rangeArgs);
|
|
146
|
+
const providers = breakdown('connection');
|
|
147
|
+
const models = breakdown('model');
|
|
148
|
+
// Read one sentinel past each wire count. It can only become a whole-screen
|
|
149
|
+
// failure, never a successful truncated collection. No history array is built.
|
|
150
|
+
for (const [rows, section] of [
|
|
151
|
+
[providers, 'provider_breakdown'],
|
|
152
|
+
[models, 'model_breakdown'],
|
|
153
|
+
[tools, 'tool_breakdown'],
|
|
154
|
+
]) {
|
|
155
|
+
if (rows.length > 100)
|
|
156
|
+
return { kind: 'screen_response_too_large', section };
|
|
157
|
+
}
|
|
158
|
+
const pricing = db
|
|
159
|
+
.prepare('SELECT record_json FROM usage_pricing_overrides ORDER BY model_key LIMIT 129')
|
|
160
|
+
.all()
|
|
161
|
+
.map((row) => {
|
|
162
|
+
const value = JSON.parse(String(row.record_json));
|
|
163
|
+
const separator = value.modelKey.indexOf(':');
|
|
164
|
+
return {
|
|
165
|
+
provider: separator < 0 ? '' : value.modelKey.slice(0, separator),
|
|
166
|
+
model: separator < 0 ? value.modelKey : value.modelKey.slice(separator + 1),
|
|
167
|
+
inputPerMTokUsd: value.inputUsdPer1M,
|
|
168
|
+
outputPerMTokUsd: value.outputUsdPer1M,
|
|
169
|
+
};
|
|
170
|
+
});
|
|
171
|
+
if (pricing.length > 128)
|
|
172
|
+
return { kind: 'screen_response_too_large', section: 'pricing' };
|
|
173
|
+
const unreadable = n(db
|
|
174
|
+
.prepare(`SELECT COUNT(*) AS count FROM usage_model_call_attempts
|
|
175
|
+
WHERE completed_at >= ? AND completed_at <= ? AND cost_basis IS NULL`)
|
|
176
|
+
.get(...rangeArgs)?.count) +
|
|
177
|
+
n(db
|
|
178
|
+
.prepare('SELECT SUM(unreadable_events) AS count FROM usage_model_call_projection_checkpoints')
|
|
179
|
+
.get()?.count);
|
|
180
|
+
const pending = n(db
|
|
181
|
+
.prepare(`SELECT COUNT(*) AS count FROM core_agent_runs AS source
|
|
182
|
+
LEFT JOIN usage_model_call_projection_checkpoints AS checkpoint
|
|
183
|
+
ON checkpoint.session_id = source.session_id AND checkpoint.run_id = source.run_id
|
|
184
|
+
WHERE source.latest_model_call_sequence > COALESCE(checkpoint.applied_through_sequence, -1)`)
|
|
185
|
+
.get()?.count);
|
|
186
|
+
return {
|
|
187
|
+
summary: {
|
|
188
|
+
totalRequests: n(aggregate.totalRequests),
|
|
189
|
+
totalCostUsd: n(aggregate.totalCostUsd),
|
|
190
|
+
totalTokens: n(aggregate.totalTokens),
|
|
191
|
+
inputTokens: n(aggregate.inputTokens),
|
|
192
|
+
outputTokens: n(aggregate.outputTokens),
|
|
193
|
+
cacheTokens: n(aggregate.cacheRead) + n(aggregate.cacheCreation),
|
|
194
|
+
cacheMiss: n(aggregate.cacheMiss),
|
|
195
|
+
cacheRead: n(aggregate.cacheRead),
|
|
196
|
+
cacheCreation: n(aggregate.cacheCreation),
|
|
197
|
+
reasoning: n(aggregate.reasoning),
|
|
198
|
+
},
|
|
199
|
+
byProvider: providers.map((row) => ({
|
|
200
|
+
provider: String(row.name),
|
|
201
|
+
requests: n(row.requests),
|
|
202
|
+
tokens: n(row.tokens),
|
|
203
|
+
costUsd: n(row.costUsd),
|
|
204
|
+
})),
|
|
205
|
+
byModel: models.map((row) => ({
|
|
206
|
+
model: String(row.name),
|
|
207
|
+
requests: n(row.requests),
|
|
208
|
+
tokens: n(row.tokens),
|
|
209
|
+
costUsd: n(row.costUsd),
|
|
210
|
+
})),
|
|
211
|
+
byTool: tools.map((row) => ({
|
|
212
|
+
tool: String(row.tool),
|
|
213
|
+
calls: n(row.calls),
|
|
214
|
+
success: n(row.success),
|
|
215
|
+
errors: n(row.errors),
|
|
216
|
+
avgDurationMs: n(row.avgDurationMs),
|
|
217
|
+
})),
|
|
218
|
+
pricing,
|
|
219
|
+
provenance: {
|
|
220
|
+
coverage: {
|
|
221
|
+
attempts: n(aggregate.attempts),
|
|
222
|
+
pricedAttempts: n(aggregate.pricedAttempts),
|
|
223
|
+
unpricedAttempts: n(aggregate.unpricedAttempts),
|
|
224
|
+
usageReportedAttempts: n(aggregate.usageReportedAttempts),
|
|
225
|
+
usagePartialAttempts: n(aggregate.usagePartialAttempts),
|
|
226
|
+
usageMissingAttempts: n(aggregate.usageMissingAttempts),
|
|
227
|
+
},
|
|
228
|
+
legacyRecords: n(aggregate.legacyRecords),
|
|
229
|
+
unreadableRecords: unreadable,
|
|
230
|
+
pendingRepairs: pending,
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
|
204
234
|
function validateQuery(query) {
|
|
205
235
|
if (!isUsageTimestamp(query.range.from) ||
|
|
206
236
|
!isUsageTimestamp(query.range.to) ||
|