maka-agent 0.2.0-dev.42.20260918 → 0.2.0-dev.43.20260919

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 (26) hide show
  1. package/dist/acp/maka-acp-agent.js +17 -6
  2. package/dist/acp/session-event-mapper.js +6 -0
  3. package/dist/acp/session-interactions.js +520 -0
  4. package/dist/acp/session-registry.js +80 -9
  5. package/dist/acp/tool-event-mapper.js +60 -2
  6. package/dist/pi-tui-runner.js +57 -6
  7. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  8. package/node_modules/@maka/core/dist/connection-usage.js +27 -0
  9. package/node_modules/@maka/core/dist/external-session.js +4 -3
  10. package/node_modules/@maka/core/dist/provider-auth.js +9 -1
  11. package/node_modules/@maka/core/dist/skill-locations.js +29 -0
  12. package/node_modules/@maka/core/package.json +2 -0
  13. package/node_modules/@maka/runtime/dist/commandcode-cli-language-model.js +27 -3
  14. package/node_modules/@maka/runtime/dist/connection-usage.js +232 -0
  15. package/node_modules/@maka/runtime/dist/skills-discovery.js +17 -23
  16. package/node_modules/@maka/runtime/package.json +1 -0
  17. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +132 -1
  18. package/node_modules/@maka/runtime-host/dist/protocol/index.js +7 -3
  19. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  20. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +57 -1
  21. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +4 -3
  22. package/node_modules/@maka/storage/dist/codex-session-adapter.js +26 -28
  23. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +34 -1
  24. package/node_modules/@maka/storage/dist/runtime-policy-stores.js +2 -0
  25. package/node_modules/@maka/storage/dist/session-store.js +5 -2
  26. package/package.json +1 -1
@@ -0,0 +1,232 @@
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
+ import { providerReportsUsage } from '@maka/core/connection-usage';
20
+ import { commandCodeCliHeaders } from './commandcode-cli-language-model.js';
21
+ import { fetchForConnectionEffect } from './connection-effect-fetch.js';
22
+ export async function fetchConnectionUsage(input) {
23
+ if (!providerReportsUsage(input.providerType)) {
24
+ return { kind: 'unavailable', reason: 'unsupported' };
25
+ }
26
+ switch (input.providerType) {
27
+ case 'commandcode-go':
28
+ return fetchCommandCodeGoUsage(input);
29
+ // `commandcode` (the Provider-API plan) is deliberately NOT wired yet: its
30
+ // usage lives behind the same `/alpha/*` endpoints, but only a GO-tier key
31
+ // has been verified against them. Wiring it from inference alone could
32
+ // mis-report a plan's windows, which is worse than showing nothing.
33
+ default:
34
+ return { kind: 'unavailable', reason: 'unsupported' };
35
+ }
36
+ }
37
+ /**
38
+ * Command Code's account endpoints, fetched together with per-endpoint
39
+ * degradation: whichever endpoints answer, their facts land in the report, and
40
+ * only a total failure (no credential, or nothing answered) becomes
41
+ * `unavailable`.
42
+ */
43
+ async function fetchCommandCodeGoUsage(input) {
44
+ if (!input.apiKey)
45
+ return { kind: 'unavailable', reason: 'no-credential' };
46
+ const base = (input.baseUrl ?? 'https://api.commandcode.ai').replace(/\/+$/u, '');
47
+ const headers = commandCodeCliHeaders(input.apiKey, 'maka');
48
+ const get = async (path) => {
49
+ try {
50
+ const response = await fetchForConnectionEffect(input.fetch, `${base}${path}`, { headers });
51
+ if (!response.ok) {
52
+ return { ok: false, unauthorized: response.status === 401 || response.status === 403 };
53
+ }
54
+ return {
55
+ ok: true,
56
+ body: (await response.readJson()),
57
+ };
58
+ }
59
+ catch {
60
+ return { ok: false, unauthorized: false };
61
+ }
62
+ };
63
+ const [whoami, summary, credits, subscriptions] = await Promise.all([
64
+ get('/alpha/whoami'),
65
+ get('/alpha/usage/summary'),
66
+ get('/alpha/billing/credits'),
67
+ get('/alpha/billing/subscriptions'),
68
+ ]);
69
+ const endpoints = [whoami, summary, credits, subscriptions];
70
+ const answered = endpoints.filter((endpoint) => endpoint.ok);
71
+ const refused = endpoints.some((endpoint) => !endpoint.ok && endpoint.unauthorized);
72
+ if (answered.length === 0) {
73
+ // Every endpoint failed at once. If any rejection was an auth rejection, the
74
+ // credential is the problem, not the network.
75
+ return { kind: 'unavailable', reason: refused ? 'unauthorized' : 'network' };
76
+ }
77
+ // Some answered and some refused: a key that is valid but lacks a scope. The
78
+ // read is reported (so the card shows what it has) with the refusal flagged, so
79
+ // it can also say why the rest is missing — otherwise a partial report reads
80
+ // as a complete one and the page cannot name the credential as the cause.
81
+ const partiallyUnauthorized = refused;
82
+ const body = (endpoint) => endpoint.body;
83
+ const [whoamiBody, summaryBody, creditsBody, subscriptionsBody] = [
84
+ whoami.ok ? body(whoami) : undefined,
85
+ summary.ok ? body(summary) : undefined,
86
+ credits.ok ? body(credits) : undefined,
87
+ subscriptions.ok ? body(subscriptions) : undefined,
88
+ ];
89
+ const plan = subscriptionFacts(subscriptionsBody);
90
+ const windowLimits = record(record(creditsBody)?.windowLimits);
91
+ const windows = [];
92
+ const fiveHour = parseWindow('fiveHour', windowLimits?.fiveHour);
93
+ if (fiveHour)
94
+ windows.push(fiveHour);
95
+ const weekly = parseWindow('weekly', windowLimits?.weekly);
96
+ if (weekly)
97
+ windows.push(weekly);
98
+ const monthly = parseMonthly(creditsBody, plan);
99
+ if (monthly)
100
+ windows.push(monthly);
101
+ const stats = parseStats(summaryBody);
102
+ const report = {
103
+ ...(accountLabel(whoamiBody) !== undefined ? { accountLabel: accountLabel(whoamiBody) } : {}),
104
+ ...(plan.name !== undefined ? { planLabel: plan.name } : {}),
105
+ ...(stats !== undefined ? { stats } : {}),
106
+ windows,
107
+ ...(plan.periodEnd !== undefined ? { periodEnd: plan.periodEnd } : {}),
108
+ ...(partiallyUnauthorized ? { partiallyUnauthorized: true } : {}),
109
+ fetchedAt: Date.now(),
110
+ };
111
+ return { kind: 'report', report };
112
+ }
113
+ /**
114
+ * `command-code` subscription plans and their monthly credit allowance. The
115
+ * billing endpoint reports the monthly REMAINING balance, not the total, so the
116
+ * monthly window's cap has to come from the plan — the same table the official
117
+ * CLI resolves `getPlanInfo` from. Longest-prefix match so `individual-pro-v1`
118
+ * wins over `individual-pro`.
119
+ */
120
+ const SUBSCRIPTION_PLAN_MONTHLY_CREDITS = {
121
+ 'individual-go': 10,
122
+ 'individual-goat': 70,
123
+ 'individual-pro-v1': 80,
124
+ 'individual-pro': 30,
125
+ 'individual-provider': 15,
126
+ 'individual-max': 150,
127
+ 'individual-ultra': 300,
128
+ 'teams-pro': 40,
129
+ };
130
+ const SUBSCRIPTION_PLAN_NAMES = {
131
+ 'individual-go': 'Go',
132
+ 'individual-goat': 'GOAT',
133
+ 'individual-pro': 'Pro',
134
+ 'individual-provider': 'Provider',
135
+ 'individual-max': 'Max',
136
+ 'individual-ultra': 'Ultra',
137
+ 'teams-pro': 'Teams Pro',
138
+ };
139
+ function subscriptionFacts(subscriptions) {
140
+ const data = record(subscriptions?.data);
141
+ const planId = text(data?.planId);
142
+ const periodEnd = date(data?.currentPeriodEnd);
143
+ if (planId === undefined)
144
+ return periodEnd === undefined ? {} : { periodEnd };
145
+ const prefixes = Object.keys(SUBSCRIPTION_PLAN_MONTHLY_CREDITS).sort((a, b) => b.length - a.length);
146
+ const prefix = prefixes.find((candidate) => planId.startsWith(candidate));
147
+ return {
148
+ ...(prefix === undefined ? {} : { name: SUBSCRIPTION_PLAN_NAMES[prefix] }),
149
+ ...(prefix === undefined ? {} : { monthlyCredits: SUBSCRIPTION_PLAN_MONTHLY_CREDITS[prefix] }),
150
+ ...(periodEnd === undefined ? {} : { periodEnd }),
151
+ };
152
+ }
153
+ function parseWindow(id, value) {
154
+ const block = record(value);
155
+ if (block === undefined)
156
+ return undefined;
157
+ const used = number(block.used);
158
+ const cap = number(block.cap);
159
+ if (used === undefined && cap === undefined)
160
+ return undefined;
161
+ const resetAt = number(block.resetAt);
162
+ return {
163
+ id,
164
+ used: used ?? 0,
165
+ cap: cap ?? 0,
166
+ unit: 'credits',
167
+ ...(resetAt !== undefined && resetAt > 0 ? { resetsAt: resetAt } : {}),
168
+ };
169
+ }
170
+ /**
171
+ * The monthly window: cap from the plan, consumed = cap − remaining balance.
172
+ * Absent unless both the plan's total and the reported remaining balance are
173
+ * known — an unknown plan would otherwise render `limit − 0`, i.e. a confident
174
+ * "100% used" that is really "we do not know the limit".
175
+ */
176
+ function parseMonthly(credits, plan) {
177
+ const remaining = number(record(record(credits)?.credits)?.monthlyCredits);
178
+ if (plan.monthlyCredits === undefined || remaining === undefined)
179
+ return undefined;
180
+ const used = Math.max(0, plan.monthlyCredits - remaining);
181
+ return {
182
+ id: 'monthly',
183
+ used,
184
+ cap: plan.monthlyCredits,
185
+ unit: 'credits',
186
+ ...(plan.periodEnd !== undefined ? { resetsAt: plan.periodEnd } : {}),
187
+ };
188
+ }
189
+ function parseStats(summary) {
190
+ if (summary === undefined)
191
+ return undefined;
192
+ const stats = {
193
+ ...(number(summary.totalCount) !== undefined ? { requests: number(summary.totalCount) } : {}),
194
+ ...(number(summary.failedCount) !== undefined ? { failed: number(summary.failedCount) } : {}),
195
+ ...(number(summary.successRate) !== undefined
196
+ ? { successRate: number(summary.successRate) }
197
+ : {}),
198
+ ...(number(summary.totalCost) !== undefined ? { cost: number(summary.totalCost) } : {}),
199
+ ...(number(summary.totalTokensIn) !== undefined
200
+ ? { tokensIn: number(summary.totalTokensIn) }
201
+ : {}),
202
+ ...(number(summary.totalTokensOut) !== undefined
203
+ ? { tokensOut: number(summary.totalTokensOut) }
204
+ : {}),
205
+ };
206
+ return Object.keys(stats).length > 0 ? stats : undefined;
207
+ }
208
+ function accountLabel(whoami) {
209
+ const user = record(whoami?.user);
210
+ return text(user?.userName) ?? text(user?.name);
211
+ }
212
+ function record(value) {
213
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
214
+ ? value
215
+ : undefined;
216
+ }
217
+ function number(value) {
218
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
219
+ }
220
+ function text(value) {
221
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
222
+ }
223
+ function date(value) {
224
+ if (typeof value === 'number' && Number.isFinite(value))
225
+ return value;
226
+ if (typeof value === 'string') {
227
+ const parsed = Date.parse(value);
228
+ if (Number.isFinite(parsed))
229
+ return parsed;
230
+ }
231
+ return undefined;
232
+ }
@@ -20,6 +20,7 @@ import { createHash } from 'node:crypto';
20
20
  import { homedir } from 'node:os';
21
21
  import { lstat, readdir, realpath, stat } from 'node:fs/promises';
22
22
  import { join } from 'node:path';
23
+ import { STANDARD_SKILL_LOCATIONS, } from '@maka/core/skill-locations';
23
24
  import { isPathInside, readContainedRegularFile } from './path-containment.js';
24
25
  import { validateSkillMetadata } from './skills-metadata.js';
25
26
  import { getSkillRuntimePreference, migrateSkillRuntimePreferences, readSkillRuntimeState, } from './skills-state.js';
@@ -37,31 +38,24 @@ import { getSkillRuntimePreference, migrateSkillRuntimePreferences, readSkillRun
37
38
  *
38
39
  * Returns containment roots so `scanSkillDir` can reject ancestor-level
39
40
  * symlink escapes (e.g. `repo/.agents -> /outside`).
41
+ * A null cwd omits Project locations without substituting another scope's root.
40
42
  */
41
43
  export function resolveSkillDiscoveryPaths(cwd, workspaceRoot, homeDir) {
42
- const home = homeDir ?? homedir();
43
- const entries = [
44
- { dir: join(cwd, '.maka', 'skills'), containmentRoot: cwd, scope: 'project', source: 'maka' },
45
- {
46
- dir: join(cwd, '.agents', 'skills'),
47
- containmentRoot: cwd,
48
- scope: 'project',
49
- source: 'agents',
50
- },
51
- {
52
- dir: join(workspaceRoot, 'skills'),
53
- containmentRoot: workspaceRoot,
54
- scope: 'workspace',
55
- source: 'legacy',
56
- },
57
- { dir: join(home, '.maka', 'skills'), containmentRoot: home, scope: 'user', source: 'maka' },
58
- {
59
- dir: join(home, '.agents', 'skills'),
60
- containmentRoot: home,
61
- scope: 'user',
62
- source: 'agents',
63
- },
64
- ];
44
+ const roots = { project: cwd, workspace: workspaceRoot, user: homeDir ?? homedir() };
45
+ const entries = STANDARD_SKILL_LOCATIONS.flatMap((location) => {
46
+ const root = roots[location.scope];
47
+ return root === null
48
+ ? []
49
+ : [
50
+ {
51
+ dir: join(root, ...location.segments),
52
+ containmentRoot: root,
53
+ scope: location.scope,
54
+ source: location.source,
55
+ refPrefix: location.ref,
56
+ },
57
+ ];
58
+ });
65
59
  return { entries, dirs: entries.map((e) => e.dir), stateRoot: workspaceRoot };
66
60
  }
67
61
  /**
@@ -46,6 +46,7 @@
46
46
  "./computer-use-types": "./dist/computer-use-types.js",
47
47
  "./configured-subagent-catalog": "./dist/configured-subagent-catalog.js",
48
48
  "./connection-effect-fetch": "./dist/connection-effect-fetch.js",
49
+ "./connection-usage": "./dist/connection-usage.js",
49
50
  "./connection-effect-outcome": "./dist/connection-effect-outcome.js",
50
51
  "./context-budget-policy": "./dist/context-budget-policy.js",
51
52
  "./context-diagnostics": "./dist/context-diagnostics.js",
@@ -17,7 +17,7 @@
17
17
  * under the License.
18
18
  */
19
19
  import { CONNECTION_CATALOG_MAX_MODELS_PER_CONNECTION, decodeConnectionModelId, decodeConnectionModel, decodeConnectionName, decodeConnectionSlug, decodeProviderType, decodeConnectionTestSummary, decodeConnectionVersionBasis, RuntimePolicyDomainDecodeError, } from '@maka/core/runtime-policy';
20
- import { requireCount, requireEntityId, requireExactRecord, requireRecord, requireShapedRecord, requireString, } from './codec.js';
20
+ import { requireCount, requireEntityId, requireExactRecord, requireRecord, requireShapedRecord, requireString, requireUtf8String, } from './codec.js';
21
21
  import { invalidProtocolFrame } from './errors.js';
22
22
  import { defineOperation } from './operation-spec.js';
23
23
  const EFFECT_ERRORS = [
@@ -29,6 +29,13 @@ const EFFECT_ERRORS = [
29
29
  'persistence_failed',
30
30
  'commit_outcome_unknown',
31
31
  ];
32
+ /**
33
+ * Upper bound on the quota windows one usage report may carry. The producer
34
+ * emits three today (5-hour, weekly, monthly); the cap exists because a decoder
35
+ * is the boundary that does not trust its producer, matching how every other
36
+ * array in this package is bounded before mapping.
37
+ */
38
+ const CONNECTION_USAGE_MAX_WINDOWS = 16;
32
39
  export const CONNECTION_EFFECT_CHANGED_DOMAINS = [
33
40
  'connection',
34
41
  'credential',
@@ -77,6 +84,13 @@ export const CONNECTION_EFFECT_OPERATION_SPECS = {
77
84
  decodeInput: decodeConnectionTestRunInput,
78
85
  decodeOutput: decodeConnectionTestRunResult,
79
86
  }),
87
+ 'connection.usage.read': defineOperation({
88
+ mode: 'query',
89
+ availability: 'ready',
90
+ errors: EFFECT_ERRORS,
91
+ decodeInput: decodeConnectionUsageReadInput,
92
+ decodeOutput: decodeConnectionUsageReadResult,
93
+ }),
80
94
  };
81
95
  export function decodeConnectionOnboardingSaveInput(value) {
82
96
  const input = requireExactRecord(value, 'connection onboarding save input', [
@@ -282,6 +296,123 @@ export function decodeConnectionTestRunResult(value) {
282
296
  }
283
297
  return decodeNonEffectResult(result, 'connection test result');
284
298
  }
299
+ export function decodeConnectionUsageReadInput(value) {
300
+ const input = requireExactRecord(value, 'connection usage input', ['connectionId']);
301
+ return { connectionId: requireEntityId(input.connectionId, 'connectionId') };
302
+ }
303
+ export function decodeConnectionUsageReadResult(value) {
304
+ const result = requireRecord(value, 'connection usage result');
305
+ if (result.kind === 'report') {
306
+ const report = requireExactRecord(result, 'connection usage report', ['kind', 'report']);
307
+ return { kind: 'report', report: decodeUsageReport(report.report) };
308
+ }
309
+ if (result.kind === 'unavailable') {
310
+ const unavailable = requireExactRecord(result, 'connection usage unavailable', [
311
+ 'kind',
312
+ 'reason',
313
+ ]);
314
+ if (unavailable.reason !== 'unsupported' &&
315
+ unavailable.reason !== 'network' &&
316
+ unavailable.reason !== 'no-credential' &&
317
+ unavailable.reason !== 'unauthorized') {
318
+ throw invalidProtocolFrame('Invalid connection usage unavailable reason');
319
+ }
320
+ return { kind: 'unavailable', reason: unavailable.reason };
321
+ }
322
+ if (result.kind === 'rejected') {
323
+ const rejected = requireExactRecord(result, 'connection usage result', ['kind', 'reason']);
324
+ return { kind: 'rejected', reason: rejectionReason(rejected.reason) };
325
+ }
326
+ throw invalidProtocolFrame('Invalid connection usage result');
327
+ }
328
+ function decodeUsageReport(value) {
329
+ const report = requireExactRecord(value, 'connection usage report body', [
330
+ 'accountLabel',
331
+ 'planLabel',
332
+ 'stats',
333
+ 'windows',
334
+ 'periodEnd',
335
+ 'partiallyUnauthorized',
336
+ 'fetchedAt',
337
+ ]);
338
+ if (!Array.isArray(report.windows) || report.windows.length > CONNECTION_USAGE_MAX_WINDOWS) {
339
+ throw invalidProtocolFrame('Invalid connection usage windows');
340
+ }
341
+ return {
342
+ accountLabel: optionalText(report.accountLabel, 'account label'),
343
+ planLabel: optionalText(report.planLabel, 'plan label'),
344
+ stats: report.stats === null ? null : decodeUsageStats(report.stats),
345
+ windows: report.windows.map(decodeUsageWindow),
346
+ periodEnd: optionalMillis(report.periodEnd, 'period end'),
347
+ partiallyUnauthorized: requireBoolean(report.partiallyUnauthorized, 'partially unauthorized'),
348
+ fetchedAt: requireCount(report.fetchedAt, 'usage fetchedAt'),
349
+ };
350
+ }
351
+ function decodeUsageStats(value) {
352
+ const stats = requireExactRecord(value, 'connection usage stats', [
353
+ 'requests',
354
+ 'failed',
355
+ 'successRate',
356
+ 'cost',
357
+ 'tokensIn',
358
+ 'tokensOut',
359
+ ]);
360
+ return {
361
+ requests: optionalCount(stats.requests, 'requests'),
362
+ failed: optionalCount(stats.failed, 'failed'),
363
+ successRate: optionalAmount(stats.successRate, 'success rate'),
364
+ cost: optionalAmount(stats.cost, 'cost'),
365
+ tokensIn: optionalCount(stats.tokensIn, 'tokens in'),
366
+ tokensOut: optionalCount(stats.tokensOut, 'tokens out'),
367
+ };
368
+ }
369
+ function decodeUsageWindow(value) {
370
+ const window = requireExactRecord(value, 'connection usage window', [
371
+ 'id',
372
+ 'label',
373
+ 'used',
374
+ 'cap',
375
+ 'unit',
376
+ 'resetsAt',
377
+ 'unlimited',
378
+ ]);
379
+ const unit = window.unit;
380
+ if (unit !== 'credits' && unit !== 'usd' && unit !== 'tokens') {
381
+ throw invalidProtocolFrame('Invalid connection usage unit');
382
+ }
383
+ return {
384
+ id: requireUtf8String(window.id, 'usage window id', 64),
385
+ label: optionalText(window.label, 'usage window label'),
386
+ used: requireAmount(window.used, 'usage window used'),
387
+ cap: requireAmount(window.cap, 'usage window cap'),
388
+ unit,
389
+ resetsAt: optionalMillis(window.resetsAt, 'usage window reset'),
390
+ unlimited: window.unlimited === null ? null : requireBoolean(window.unlimited, 'unlimited'),
391
+ };
392
+ }
393
+ function optionalText(value, label) {
394
+ return value === null ? null : requireUtf8String(value, label, 256);
395
+ }
396
+ function optionalCount(value, label) {
397
+ return value === null ? null : requireCount(value, label);
398
+ }
399
+ function requireAmount(value, label) {
400
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
401
+ throw invalidProtocolFrame(`Invalid ${label}`);
402
+ }
403
+ return value;
404
+ }
405
+ function optionalAmount(value, label) {
406
+ return value === null ? null : requireAmount(value, label);
407
+ }
408
+ function optionalMillis(value, label) {
409
+ return value === null ? null : requireCount(value, label);
410
+ }
411
+ function requireBoolean(value, label) {
412
+ if (typeof value !== 'boolean')
413
+ throw invalidProtocolFrame(`Invalid ${label}`);
414
+ return value;
415
+ }
285
416
  function decodeConnectionTestProjection(value) {
286
417
  const projection = requireRecord(value, 'connection test projection');
287
418
  if (projection.kind === 'verified') {
@@ -62,11 +62,15 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1;
62
62
  export const RUNTIME_HOST_PROTOCOL_VERSION = 0;
63
63
  // Increment when the same protocol version no longer guarantees safe Client-Host
64
64
  // interoperability. Mismatches are rejected before domain commands are admitted.
65
- export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 165;
66
- // 164: Client Plugin bundles, desktop-ui composition, generation-fenced Host
67
- // Remote calls, and pull streams are projected through strict Host contracts.
65
+ export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 166;
66
+ // 166: Connection usage reads add an operation, an accepted availability reason
67
+ // (`unauthorized`), a report field (`partiallyUnauthorized`), and a bounded
68
+ // window list. Peers older than this epoch take the added operation for an
69
+ // unknown key and reject the new reason and field.
68
70
  // 165: WorkHub coordination resolve adds a model_required error code. Older
69
71
  // peers reject the new operation outcome rather than misdiagnosing prose.
72
+ // 164: Client Plugin bundles, desktop-ui composition, generation-fenced Host
73
+ // Remote calls, and pull streams are projected through strict Host contracts.
70
74
  // 163: Session reference quotes carry strict capture and truncation provenance.
71
75
  // Epoch-162 peers reject the added QuoteRef fields.
72
76
  // 162: Runtime Resource control and stop replies drop the unused resource
@@ -131,6 +131,7 @@ export const REMOTE_OWNER_OPERATION_GRANTS = Object.freeze([
131
131
  'connection.request-headers.query',
132
132
  'connection.request-headers.replace',
133
133
  'connection.test.run',
134
+ 'connection.usage.read',
134
135
  'context.compact',
135
136
  'context.diagnostics.query',
136
137
  'credential.vault.delete',
@@ -17,12 +17,13 @@
17
17
  * under the License.
18
18
  */
19
19
  import { parseRequestHeaders } from '@maka/core/runtime-policy';
20
- import { PROVIDER_REGISTRY, providerFallbackModelIds } from '@maka/core/llm-connections';
20
+ import { PROVIDER_REGISTRY, effectiveBaseUrl, providerFallbackModelIds, } from '@maka/core/llm-connections';
21
21
  import { createConnectionEffectFetchTransport, } from '@maka/runtime/network/scoped-fetch-transport';
22
22
  import { createRequestCustomizationFetch } from '@maka/runtime/request-customization-fetch';
23
23
  import { isOAuthSubscriptionProvider, parseOAuthSubscriptionTokens, } from '@maka/runtime/subscription-credentials';
24
24
  import { runConnectionModelDiscoveryEffect } from '@maka/runtime/model-fetcher';
25
25
  import { runConnectionTestEffect } from '@maka/runtime/test-connection';
26
+ import { fetchConnectionUsage } from '@maka/runtime/connection-usage';
26
27
  import { authenticateRuntimePolicyStoresWriter, RuntimePolicyStoreError, } from '@maka/storage/runtime-policy-stores';
27
28
  import { toRuntimePolicyProxy } from './runtime-policy-proxy.js';
28
29
  /** Runs provider I/O outside Storage lanes and conditionally commits canonical results. */
@@ -32,6 +33,7 @@ export class HostConnectionEffectCoordinator {
32
33
  'connection.onboarding.verify': (input) => this.#verifyOnboarding(input),
33
34
  'connection.models.fetch': (input) => this.#fetchModels(input),
34
35
  'connection.test.run': (input) => this.#testConnection(input),
36
+ 'connection.usage.read': (input) => this.#readConnectionUsage(input),
35
37
  };
36
38
  #stores;
37
39
  #activation;
@@ -263,6 +265,32 @@ export class HostConnectionEffectCoordinator {
263
265
  : projectSuperseded(completion);
264
266
  });
265
267
  }
268
+ /**
269
+ * Read-only: fetch the account's usage and project it. Nothing is committed,
270
+ * so no superseded branch exists — the ticket is spent and the report
271
+ * returned.
272
+ */
273
+ #readConnectionUsage(input) {
274
+ return this.#admit(input.connectionId, 'connection.usage.read', async () => {
275
+ const prepared = await this.#stores.operations.beginConnectionUsage(input.connectionId);
276
+ if (prepared.kind !== 'ready')
277
+ return preparationResult(prepared);
278
+ try {
279
+ const result = await this.#withTransport(prepared, (fetch, secret) => fetchConnectionUsage({
280
+ providerType: prepared.connection.providerType,
281
+ apiKey: secret,
282
+ baseUrl: effectiveBaseUrl(prepared.connection),
283
+ fetch,
284
+ }));
285
+ return result.kind === 'report'
286
+ ? { kind: 'report', report: projectUsageReport(result.report) }
287
+ : { kind: 'unavailable', reason: result.reason };
288
+ }
289
+ finally {
290
+ await this.#stores.operations.completeConnectionUsage(prepared.ticket);
291
+ }
292
+ });
293
+ }
266
294
  #admit(connectionId, operation, run) {
267
295
  if (!this.#accepting) {
268
296
  return Promise.resolve({
@@ -351,6 +379,34 @@ function projectSuperseded(completion) {
351
379
  changed: completion.changed.map((domain) => domain),
352
380
  };
353
381
  }
382
+ function projectUsageReport(report) {
383
+ return {
384
+ accountLabel: report.accountLabel ?? null,
385
+ planLabel: report.planLabel ?? null,
386
+ stats: report.stats
387
+ ? {
388
+ requests: report.stats.requests ?? null,
389
+ failed: report.stats.failed ?? null,
390
+ successRate: report.stats.successRate ?? null,
391
+ cost: report.stats.cost ?? null,
392
+ tokensIn: report.stats.tokensIn ?? null,
393
+ tokensOut: report.stats.tokensOut ?? null,
394
+ }
395
+ : null,
396
+ windows: report.windows.map((window) => ({
397
+ id: window.id,
398
+ label: window.label ?? null,
399
+ used: window.used,
400
+ cap: window.cap,
401
+ unit: window.unit,
402
+ resetsAt: window.resetsAt ?? null,
403
+ unlimited: window.unlimited ?? null,
404
+ })),
405
+ periodEnd: report.periodEnd ?? null,
406
+ partiallyUnauthorized: report.partiallyUnauthorized === true,
407
+ fetchedAt: report.fetchedAt,
408
+ };
409
+ }
354
410
  function projectConnectionTest(outcome, checkedAt) {
355
411
  const checkedAtIso = new Date(checkedAt).toISOString();
356
412
  if (outcome.ok) {
@@ -24,6 +24,7 @@ import { NO_REAL_CONNECTION_CODE } from '@maka/core/connection-error-copy';
24
24
  import { generalizedErrorMessage } from '@maka/core/redaction';
25
25
  import { emptyPlanSessionState } from '@maka/core/plan';
26
26
  import { readLogicalRuntimeExecutionForRun } from '@maka/core/runtime-logical-execution';
27
+ import { foldForMatch } from '@maka/core/thread-search';
27
28
  import { runtimeInvocationOutcome, } from '@maka/core/runtime-invocation';
28
29
  import { isDeepResearchSession, WORKHUB_COORDINATION_SESSION_ID, WORKHUB_COORDINATION_REPLACEMENT_SCHEMA_VERSION, } from '@maka/core/session';
29
30
  import { AgentGraphClientOperationError, AgentGraphCoordinator, } from '@maka/runtime/stream-graph-coordinator';
@@ -1311,17 +1312,17 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1311
1312
  });
1312
1313
  },
1313
1314
  search: async (request, caller) => {
1314
- const query = request.query.toLocaleLowerCase();
1315
+ const query = foldForMatch(request.query);
1315
1316
  const sessions = await visibleAgentSessions(sessionQueryInitiator(caller));
1316
1317
  const matches = [];
1317
1318
  for (const session of sessions) {
1318
- const headerText = `${session.name}\n${session.cwd ?? ''}`.toLocaleLowerCase();
1319
+ const headerText = foldForMatch(`${session.name}\n${session.cwd ?? ''}`);
1319
1320
  if (headerText.includes(query)) {
1320
1321
  matches.push(session);
1321
1322
  continue;
1322
1323
  }
1323
1324
  const messages = await requireSessionManager(manager).getMessages(session.id);
1324
- if (messages.some((message) => JSON.stringify(message).toLocaleLowerCase().includes(query))) {
1325
+ if (messages.some((message) => foldForMatch(JSON.stringify(message)).includes(query))) {
1325
1326
  matches.push(session);
1326
1327
  }
1327
1328
  }