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

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 (59) hide show
  1. package/LICENSE +12 -6
  2. package/dist/acp/maka-acp-agent.js +17 -6
  3. package/dist/acp/session-event-mapper.js +6 -0
  4. package/dist/acp/session-interactions.js +520 -0
  5. package/dist/acp/session-registry.js +80 -9
  6. package/dist/acp/tool-event-mapper.js +60 -2
  7. package/dist/mcp-capability-provider.js +7 -0
  8. package/dist/pi-tui-runner.js +57 -6
  9. package/dist/runtime-host-tui-command.js +1 -1
  10. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  11. package/node_modules/@maka/core/dist/chat-model-choice.js +3 -0
  12. package/node_modules/@maka/core/dist/connection-usage.js +27 -0
  13. package/node_modules/@maka/core/dist/external-session.js +4 -3
  14. package/node_modules/@maka/core/dist/llm-connections.js +3 -21
  15. package/node_modules/@maka/core/dist/model-catalog.js +8 -20
  16. package/node_modules/@maka/core/dist/model-metadata.generated.js +304 -304
  17. package/node_modules/@maka/core/dist/model-thinking.js +16 -1
  18. package/node_modules/@maka/core/dist/models-dev-projection.js +0 -1
  19. package/node_modules/@maka/core/dist/provider-auth.js +9 -1
  20. package/node_modules/@maka/core/dist/provider-registry.js +7 -51
  21. package/node_modules/@maka/core/dist/runtime-policy/connection-catalog-codec.js +7 -0
  22. package/node_modules/@maka/core/dist/runtime-policy/model-catalog-entry-codec.js +14 -1
  23. package/node_modules/@maka/core/dist/settings.js +2 -3
  24. package/node_modules/@maka/core/dist/skill-locations.js +29 -0
  25. package/node_modules/@maka/core/package.json +2 -0
  26. package/node_modules/@maka/mcp/dist/index.js +22 -0
  27. package/node_modules/@maka/mcp/dist/oauth.js +4 -2
  28. package/node_modules/@maka/mcp/dist/tool-progress.js +45 -0
  29. package/node_modules/@maka/runtime/dist/commandcode-cli-language-model.js +27 -3
  30. package/node_modules/@maka/runtime/dist/connection-usage.js +232 -0
  31. package/node_modules/@maka/runtime/dist/opencode-session-header.js +2 -3
  32. package/node_modules/@maka/runtime/dist/session-manager.js +1 -44
  33. package/node_modules/@maka/runtime/dist/skills-discovery.js +17 -23
  34. package/node_modules/@maka/runtime/dist/test-connection.js +3 -66
  35. package/node_modules/@maka/runtime/package.json +1 -0
  36. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +44 -9
  37. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  38. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +33 -3
  39. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +132 -1
  40. package/node_modules/@maka/runtime-host/dist/protocol/index.js +13 -3
  41. package/node_modules/@maka/runtime-host/dist/protocol/message.js +10 -0
  42. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -1
  43. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +1 -1
  44. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +0 -33
  45. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +2 -0
  46. package/node_modules/@maka/runtime-host/dist/server/bootstrap-runtime-policy.js +31 -104
  47. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +57 -1
  48. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +4 -5
  49. package/node_modules/@maka/runtime-host/dist/server/interactive-turn-coordinator.js +1 -16
  50. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +46 -28
  51. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +5 -16
  52. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +21 -12
  53. package/node_modules/@maka/runtime-host/dist/server/session-turn-access-request-coordinator.js +7 -17
  54. package/node_modules/@maka/storage/dist/codex-session-adapter.js +26 -28
  55. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +0 -62
  56. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +34 -4
  57. package/node_modules/@maka/storage/dist/runtime-policy-stores.js +2 -1
  58. package/node_modules/@maka/storage/dist/session-store.js +5 -2
  59. package/package.json +1 -1
@@ -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,21 @@ 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 = 169;
66
+ // 169: The message execution query reports an identity the Host can prove was
67
+ // never admitted as a positive `not_admitted` resolution instead of omitting
68
+ // it, so silence stops meaning both "not admitted" and "cannot say yet".
69
+ // Epoch-168 peers reject the new state as an invalid frame.
70
+ // 167: Removed the turn.regenerate operation. Older peers can no longer
71
+ // safely interoperate because they may submit or advertise that operation.
72
+ // 166: Connection usage reads add an operation, an accepted availability reason
73
+ // (`unauthorized`), a report field (`partiallyUnauthorized`), and a bounded
74
+ // window list. Peers older than this epoch take the added operation for an
75
+ // unknown key and reject the new reason and field.
68
76
  // 165: WorkHub coordination resolve adds a model_required error code. Older
69
77
  // peers reject the new operation outcome rather than misdiagnosing prose.
78
+ // 164: Client Plugin bundles, desktop-ui composition, generation-fenced Host
79
+ // Remote calls, and pull streams are projected through strict Host contracts.
70
80
  // 163: Session reference quotes carry strict capture and truncation provenance.
71
81
  // Epoch-162 peers reject the added QuoteRef fields.
72
82
  // 162: Runtime Resource control and stop replies drop the unused resource
@@ -200,6 +200,16 @@ function decodeTurnMessageExecutionQueryResult(value) {
200
200
  state: 'cancelled',
201
201
  };
202
202
  }
203
+ if (resolution.state === 'not_admitted') {
204
+ assertExactKeys(resolution, 'turn.message.execution.query not_admitted resolution', [
205
+ 'messageId',
206
+ 'state',
207
+ ]);
208
+ return {
209
+ messageId: requireEntityId(resolution.messageId, 'messageId'),
210
+ state: 'not_admitted',
211
+ };
212
+ }
203
213
  if (resolution.state === 'owned') {
204
214
  assertExactKeys(resolution, 'turn.message.execution.query owned resolution', [
205
215
  'messageId',
@@ -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',
@@ -218,7 +219,6 @@ export const REMOTE_OWNER_OPERATION_GRANTS = Object.freeze([
218
219
  'turn.message.query',
219
220
  'turn.message.submit',
220
221
  'turn.query',
221
- 'turn.regenerate',
222
222
  'turn.resume.query',
223
223
  'turn.resume.start',
224
224
  'turn.start',
@@ -273,7 +273,7 @@ export function decodeSessionCreateInput(value) {
273
273
  ...(target ? { modelTarget: target } : {}),
274
274
  ...(executorId ? { executorId } : {}),
275
275
  ...(Object.hasOwn(input, 'thinkingLevel')
276
- ? { thinkingLevel: thinkingLevel(input.thinkingLevel) }
276
+ ? { thinkingLevel: input.thinkingLevel === null ? null : thinkingLevel(input.thinkingLevel) }
277
277
  : {}),
278
278
  ...(Object.hasOwn(input, 'toolProfile')
279
279
  ? { toolProfile: sessionToolProfile(input.toolProfile) }
@@ -96,27 +96,6 @@ export const TURN_OPERATION_SPECS = {
96
96
  decodeInput: decodeTurnStopInput,
97
97
  decodeOutput: decodeTurnSnapshot,
98
98
  }),
99
- 'turn.regenerate': defineOperation({
100
- mode: 'command',
101
- availability: 'ready',
102
- errors: [
103
- 'host_not_ready',
104
- 'host_draining',
105
- 'operation_unavailable',
106
- 'not_found',
107
- 'session_archived',
108
- 'session_busy',
109
- 'operation_conflict',
110
- 'internal_failure',
111
- ],
112
- decodeInput: decodeTurnRegenerateInput,
113
- decodeOutput: decodeTurnSnapshot,
114
- assertOutputForInput: (input, output) => {
115
- if (input.sessionId !== output.sessionId || input.turnId !== output.turnId) {
116
- throw invalidProtocolFrame('Turn regenerate changed operation identity');
117
- }
118
- },
119
- }),
120
99
  'turn.resume.query': defineOperation({
121
100
  mode: 'query',
122
101
  availability: 'ready',
@@ -317,18 +296,6 @@ function decodeTurnStopInput(value) {
317
296
  runId: requireEntityId(record.runId, 'runId'),
318
297
  };
319
298
  }
320
- function decodeTurnRegenerateInput(value) {
321
- const record = requireExactRecord(value, 'turn.regenerate input', [
322
- 'sessionId',
323
- 'sourceTurnId',
324
- 'turnId',
325
- ]);
326
- return {
327
- sessionId: requireEntityId(record.sessionId, 'sessionId'),
328
- sourceTurnId: requireEntityId(record.sourceTurnId, 'sourceTurnId'),
329
- turnId: requireEntityId(record.turnId, 'turnId'),
330
- };
331
- }
332
299
  function decodeTurnResumeQueryInput(value) {
333
300
  const record = requireShapedRecord(value, 'turn.resume.query input', ['sessionId'], ['sourceRunId', 'expectedRuntimeEventHighWater']);
334
301
  if (record.expectedRuntimeEventHighWater !== undefined && record.sourceRunId === undefined) {
@@ -48,6 +48,8 @@ const PERSISTED_GRANT_MIGRATIONS = new Map([
48
48
  // Retired with the second execution-inspection contract; no shipped surface
49
49
  // called execution.inspect.resolve.
50
50
  ['execution.inspect.resolve', { kind: 'release' }],
51
+ // Retired in favor of editing and resending the original user message.
52
+ ['turn.regenerate', { kind: 'release' }],
51
53
  // Direct WorkHub actions and record writes were retired. Their grants do not
52
54
  // authorize actFromTurn, which requires the active coordination Turn.
53
55
  ['workhub.coordination.act', { kind: 'release' }],
@@ -19,70 +19,43 @@
19
19
  import { randomUUID } from 'node:crypto';
20
20
  import { readFile, rename, rm, writeFile } from 'node:fs/promises';
21
21
  import { join } from 'node:path';
22
- import { OPENCODE_FREE_DEFAULT_MODEL, defaultEnabledModelIdsWhenOmitted, } from '@maka/core/llm-connections';
23
22
  const JOURNAL_FILE = '.runtime-host-bootstrap.json';
24
- /**
25
- * What the seeded OpenCode Free connection starts with — the provider's own
26
- * declaration of the models a fresh connection to it enables, so the seed and
27
- * a hand-added connection cannot drift apart.
28
- */
29
- const OPENCODE_FREE_SEED_MODEL_IDS = defaultEnabledModelIdsWhenOmitted('opencode-free') ?? [];
30
- /** Establishes a usable first target before Runtime Host accepts clients. */
23
+ /** Imports a user's environment credential on first start, before accepting clients. */
31
24
  export async function ensureBootstrapRuntimePolicy(input) {
32
25
  if (input.initialization)
33
26
  await initializeHostedPolicy(input.stores, input.initialization);
34
27
  const journalPath = join(input.workspaceRoot, JOURNAL_FILE);
35
28
  const resuming = await readJournal(journalPath);
36
29
  const initialCatalog = await input.stores.connectionCatalog.getSnapshot();
37
- if (initialCatalog.connections.length > 0) {
38
- // One atomic catalog mutation: enabled ids, static inventory, and a
39
- // retarget of a system default the migration removes all land in the same
40
- // document write, so no restart can observe a half-migrated row.
41
- try {
42
- await input.stores.connectionCatalog.migrateSystemSeed({
43
- slug: 'opencode-free',
44
- providerType: 'opencode-free',
45
- legacyEnabledModelIds: LEGACY_OPENCODE_FREE_SEEDS,
46
- enabledModelIds: OPENCODE_FREE_SEED_MODEL_IDS,
47
- defaultModelId: OPENCODE_FREE_DEFAULT_MODEL,
48
- retiredModelIds: retiredOpencodeFreeModelIds(),
49
- });
50
- }
51
- catch (error) {
52
- input.onDeferredError?.(error);
53
- }
30
+ if (!resuming && initialCatalog.connections.length > 0)
31
+ return;
32
+ const seed = bootstrapSeed(input.environment ?? process.env);
33
+ if (!seed || initialCatalog.connections.some((connection) => connection.slug !== seed.slug)) {
34
+ await rm(journalPath, { force: true });
35
+ return;
54
36
  }
55
- if (!resuming) {
56
- if (initialCatalog.connections.length > 0)
57
- return;
37
+ if (!resuming)
58
38
  await writeJournal(journalPath);
59
- }
60
- const seeds = bootstrapSeeds(input.environment ?? process.env);
61
- const { connection: free } = await ensureConnection(input.stores, seeds[0]);
62
- await setDefaultIfMissing(input.stores, free);
63
- await rm(journalPath, { force: true });
39
+ let connection;
64
40
  try {
65
- let preferred = free;
66
- for (const seed of seeds.slice(1)) {
67
- const ensured = await ensureConnection(input.stores, seed);
68
- const connection = ensured.connection;
69
- if (seed.secret) {
70
- try {
71
- await ensureCredential(input.stores, connection, seed.secret);
72
- }
73
- catch (error) {
74
- if (ensured.created)
75
- await removeFailedBootstrapConnection(input.stores, connection);
76
- throw error;
77
- }
78
- }
79
- preferred = connection;
41
+ const ensured = await ensureConnection(input.stores, seed);
42
+ connection = ensured.connection;
43
+ try {
44
+ await ensureCredential(input.stores, connection, seed.secret);
45
+ }
46
+ catch (error) {
47
+ if (ensured.created)
48
+ await removeFailedBootstrapConnection(input.stores, ensured.connection);
49
+ throw error;
80
50
  }
81
- await replaceBootstrapDefault(input.stores, free, preferred);
82
51
  }
83
52
  catch (error) {
84
53
  input.onDeferredError?.(error);
54
+ await rm(journalPath, { force: true });
55
+ return;
85
56
  }
57
+ await setDefaultIfMissing(input.stores, connection);
58
+ await rm(journalPath, { force: true });
86
59
  }
87
60
  async function initializeHostedPolicy(stores, input) {
88
61
  if (input.incognito !== true ||
@@ -147,47 +120,39 @@ async function initializeHostedPolicy(stores, input) {
147
120
  if (result.kind !== 'committed')
148
121
  throw new Error('Hosted proxy initialization failed');
149
122
  }
150
- function bootstrapSeeds(environment) {
151
- const seeds = [
152
- {
153
- slug: 'opencode-free',
154
- name: 'OpenCode Free',
155
- providerType: 'opencode-free',
156
- enabledModelIds: OPENCODE_FREE_SEED_MODEL_IDS,
157
- },
158
- ];
123
+ function bootstrapSeed(environment) {
159
124
  const deepseek = environment.DEEPSEEK_API_KEY?.trim();
160
125
  const anthropic = environment.ANTHROPIC_API_KEY?.trim();
161
126
  const openai = environment.OPENAI_API_KEY?.trim();
162
127
  if (deepseek) {
163
- seeds.push({
128
+ return {
164
129
  slug: 'env-deepseek',
165
130
  name: 'DeepSeek (env)',
166
131
  providerType: 'deepseek',
167
132
  enabledModelIds: ['deepseek-v4-flash'],
168
133
  baseUrl: environment.DEEPSEEK_BASE_URL?.trim() || 'https://api.deepseek.com',
169
134
  secret: deepseek,
170
- });
135
+ };
171
136
  }
172
137
  else if (anthropic) {
173
- seeds.push({
138
+ return {
174
139
  slug: 'env-anthropic',
175
140
  name: 'Anthropic (env)',
176
141
  providerType: 'anthropic',
177
142
  enabledModelIds: ['claude-sonnet-4-5-20250929'],
178
143
  secret: anthropic,
179
- });
144
+ };
180
145
  }
181
146
  else if (openai) {
182
- seeds.push({
147
+ return {
183
148
  slug: 'env-openai',
184
149
  name: 'OpenAI (env)',
185
150
  providerType: 'openai',
186
151
  enabledModelIds: ['gpt-4o-mini'],
187
152
  secret: openai,
188
- });
153
+ };
189
154
  }
190
- return seeds;
155
+ return undefined;
191
156
  }
192
157
  async function ensureConnection(stores, seed) {
193
158
  for (let attempt = 0; attempt < 3; attempt += 1) {
@@ -219,24 +184,6 @@ async function ensureConnection(stores, seed) {
219
184
  }
220
185
  throw new Error(`Bootstrap Connection could not be created: ${seed.slug}`);
221
186
  }
222
- /**
223
- * Every opencode-free inventory a past release seeded, verbatim. A row still
224
- * equal to one of these is provably system-owned and may follow the current
225
- * seed; any other value is a user selection and is never touched. Every
226
- * release that changes the derived seed must append the previous value here,
227
- * or rows it planted read as user selections forever. (This exact-match
228
- * enumeration is deliberately lossy; the versioned seed policy discussed in
229
- * #3354 is the durable replacement.)
230
- */
231
- const LEGACY_OPENCODE_FREE_SEEDS = [
232
- ['big-pickle'],
233
- ['nemotron-3-ultra-free'],
234
- ['nemotron-3-ultra-free', 'mimo-v2.5-free', 'deepseek-v4-flash-free'],
235
- ];
236
- function retiredOpencodeFreeModelIds() {
237
- const current = new Set(OPENCODE_FREE_SEED_MODEL_IDS);
238
- return [...new Set(LEGACY_OPENCODE_FREE_SEEDS.flat())].filter((id) => !current.has(id));
239
- }
240
187
  async function removeFailedBootstrapConnection(stores, connection) {
241
188
  const removed = await stores.connectionCatalog.remove({
242
189
  expected: { connectionId: connection.connectionId, revision: connection.revision },
@@ -270,33 +217,13 @@ async function setDefaultIfMissing(stores, connection) {
270
217
  expectedCatalogRevision: catalog.revision,
271
218
  target: {
272
219
  connectionId: connection.connectionId,
273
- modelId: OPENCODE_FREE_DEFAULT_MODEL,
220
+ modelId: connection.enabledModelIds[0],
274
221
  },
275
222
  });
276
223
  if (committed.kind !== 'committed') {
277
224
  throw new Error(`Bootstrap default target could not be stored: ${committed.kind}`);
278
225
  }
279
226
  }
280
- async function replaceBootstrapDefault(stores, free, preferred) {
281
- if (preferred.connectionId === free.connectionId || !preferred.enabled)
282
- return;
283
- const catalog = await stores.connectionCatalog.getSnapshot();
284
- const current = catalog.defaultTarget;
285
- if (current !== null &&
286
- (current.connectionId !== free.connectionId || current.modelId !== OPENCODE_FREE_DEFAULT_MODEL)) {
287
- return;
288
- }
289
- const modelId = preferred.enabledModelIds[0];
290
- if (!modelId)
291
- return;
292
- const committed = await stores.connectionCatalog.setDefaultTarget({
293
- expectedCatalogRevision: catalog.revision,
294
- target: { connectionId: preferred.connectionId, modelId },
295
- });
296
- if (committed.kind !== 'committed') {
297
- throw new Error(`Bootstrap preferred target could not be stored: ${committed.kind}`);
298
- }
299
- }
300
227
  async function readJournal(path) {
301
228
  let contents;
302
229
  try {
@@ -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
  }
@@ -1483,7 +1484,6 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1483
1484
  const interactiveTurns = new HostInteractiveTurnCoordinator({
1484
1485
  executions: coordinator,
1485
1486
  turns: stores.agentRunStore,
1486
- runtime: manager,
1487
1487
  });
1488
1488
  // Compile-time guarantee that the three Turn coordinators together cover
1489
1489
  // every key in TURN_OPERATION_SPECS. Domain composition seeds all domain
@@ -1499,7 +1499,6 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1499
1499
  ? new SessionTurnAccessRequestCoordinator({
1500
1500
  authority: context.sessionAccessAuthority,
1501
1501
  startTurn: interactiveTurns.handlers['turn.start'],
1502
- regenerateTurn: interactiveTurns.handlers['turn.regenerate'],
1503
1502
  hostEpoch: context.hostEpoch,
1504
1503
  acquireResidency: () => context.acquireResidency('collaboration-turn-request'),
1505
1504
  requestDrain: context.requestDrain,