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
@@ -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
+ }
@@ -17,11 +17,10 @@
17
17
  * under the License.
18
18
  */
19
19
  export const OPENCODE_SESSION_HEADER = 'x-opencode-session';
20
- /** Adds OpenCode Go/Free session identity without overriding an explicit header. */
20
+ /** Adds OpenCode Go session identity without overriding an explicit header. */
21
21
  export function withOpenCodeSessionHeader(providerType, sessionId, headers) {
22
22
  const normalizedSessionId = sessionId?.trim();
23
- if ((providerType !== 'opencode-go' && providerType !== 'opencode-free') ||
24
- !normalizedSessionId) {
23
+ if (providerType !== 'opencode-go' || !normalizedSessionId) {
25
24
  return headers;
26
25
  }
27
26
  if (Object.keys(headers ?? {}).some((name) => name.toLowerCase() === OPENCODE_SESSION_HEADER)) {
@@ -20,7 +20,7 @@ import { countRecallSearchableMessages, listRecallCandidateSessions, } from './r
20
20
  import { createHash } from 'node:crypto';
21
21
  import { isDeepStrictEqual } from 'node:util';
22
22
  import { setTimeout as delay } from 'node:timers/promises';
23
- import { messageContentsEqual, normalizeMessageContent } from '@maka/core/events';
23
+ import { messageContentsEqual } from '@maka/core/events';
24
24
  import { isCanonicalReadOnlyPermissionProfile } from '@maka/core/permission-profile';
25
25
  import { DEFAULT_TOOL_MODE } from '@maka/core/tool-mode';
26
26
  import { PLAN_USER_ABANDON_REASON, PLAN_USER_CANCEL_REASON, PlanConflictError, activePlanExecution, } from '@maka/core/plan';
@@ -97,14 +97,6 @@ export class SessionConfigurationRevisionConflictError extends Error {
97
97
  this.actualRevision = actualRevision;
98
98
  }
99
99
  }
100
- export class RuntimeRegenerateTurnError extends Error {
101
- code;
102
- name = 'RuntimeRegenerateTurnError';
103
- constructor(code, message) {
104
- super(message);
105
- this.code = code;
106
- }
107
- }
108
100
  export class BackendRegistry {
109
101
  registrations = new Map();
110
102
  register(kind, registration) {
@@ -2752,41 +2744,6 @@ export class SessionManager {
2752
2744
  ? authority.stopRoot(identity, input)
2753
2745
  : this.runtimeKernel.stopSession(identity.sessionId, input);
2754
2746
  }
2755
- async *regenerateTurn(sessionId, input) {
2756
- const execution = this.runtimeKernel.claimExecution(sessionId);
2757
- try {
2758
- const source = await this.prepareRegenerateTurn(sessionId, input.sourceTurnId);
2759
- yield* this.sendMessage(sessionId, {
2760
- turnId: input.turnId ?? this.deps.newId(),
2761
- ...source.content,
2762
- parentTurnId: source.sourceTurnId,
2763
- regeneratedFromTurnId: source.sourceTurnId,
2764
- }, { execution });
2765
- }
2766
- finally {
2767
- execution.release();
2768
- }
2769
- }
2770
- async prepareRegenerateTurn(sessionId, sourceTurnId) {
2771
- const view = await this.getSessionView(sessionId);
2772
- const source = view.turns.find((candidate) => candidate.turnId === sourceTurnId);
2773
- if (!source) {
2774
- throw new RuntimeRegenerateTurnError('not_found', `Cannot regenerate unknown Turn ${sourceTurnId}`);
2775
- }
2776
- if (source.status !== 'failed' &&
2777
- source.status !== 'aborted' &&
2778
- source.status !== 'completed') {
2779
- throw new RuntimeRegenerateTurnError('operation_conflict', `Cannot regenerate Turn ${sourceTurnId} while it is ${source.status}`);
2780
- }
2781
- const user = view.messages.find((message) => message.type === 'user' && message.turnId === sourceTurnId);
2782
- if (!user) {
2783
- throw new RuntimeRegenerateTurnError('operation_conflict', `Turn ${sourceTurnId} has no UserMessage`);
2784
- }
2785
- return {
2786
- sourceTurnId,
2787
- content: normalizeMessageContent(user),
2788
- };
2789
- }
2790
2747
  /** Canonical, repaired source view for a Host-owned cross-Session copy. */
2791
2748
  async readConversationCopySnapshot(sessionId) {
2792
2749
  return this.getSessionView(sessionId);
@@ -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
  /**
@@ -106,47 +106,15 @@ async function testConnectionStrict(connection, apiKey, model, fetchFn, t0, time
106
106
  if (!defaults) {
107
107
  return { ok: false, errorMessage: `Unknown provider type "${connection.providerType}"` };
108
108
  }
109
- const sessionId = connection.providerType === 'opencode-go' || connection.providerType === 'opencode-free'
110
- ? randomUUID()
111
- : undefined;
109
+ if (defaults.retired)
110
+ return retiredProviderTestResult(connection.providerType);
111
+ const sessionId = connection.providerType === 'opencode-go' ? randomUUID() : undefined;
112
112
  const auth = defaults.authKind;
113
113
  const secret = auth === 'none' ? '' : apiKey;
114
114
  const testModel = resolveConnectionTestModel(connection, model, providerFallbackModelIds(defaults));
115
115
  if (!testModel) {
116
116
  return { ok: false, errorMessage: 'No model to test' };
117
117
  }
118
- if (connection.providerType === 'opencode-free' && !model?.trim()) {
119
- const brokenModelIds = new Set(defaults.brokenModelIds ?? []);
120
- const candidates = [
121
- ...new Set([
122
- ...connectionEnabledModelIds(connection).filter((id) => !brokenModelIds.has(id)),
123
- ...providerFallbackModelIds(defaults),
124
- ]),
125
- ];
126
- if (candidates.length === 0) {
127
- return { ok: false, errorMessage: 'No model to test' };
128
- }
129
- let lastFailure;
130
- for (let index = 0; index < candidates.length; index += 1) {
131
- const candidate = candidates[index];
132
- const remainingMs = timeoutMs - (Date.now() - t0);
133
- if (remainingMs <= 0) {
134
- return connectionTestFailure(new ConnectionEffectFetchError('timeout'), t0);
135
- }
136
- const remainingCandidates = candidates.length - index;
137
- const attemptTimeoutMs = Math.max(1, Math.floor(remainingMs / remainingCandidates));
138
- try {
139
- const result = await testConnectionModel(connection, secret, candidate, fetchFn, t0, attemptTimeoutMs, sessionId);
140
- if (result.ok)
141
- return result;
142
- lastFailure = result;
143
- }
144
- catch (error) {
145
- lastFailure = connectionTestFailure(error, t0, true);
146
- }
147
- }
148
- return lastFailure ?? connectionTestFailure(new ConnectionEffectFetchError('timeout'), t0);
149
- }
150
118
  return await testConnectionModel(connection, secret, testModel, fetchFn, t0, timeoutMs, sessionId);
151
119
  }
152
120
  async function testConnectionModel(connection, secret, testModel, fetchFn, t0, timeoutMs = CONNECTION_TEST_TIMEOUT_MS, sessionId) {
@@ -332,40 +300,9 @@ async function probeOpenAI(connection, baseUrl, apiKey, model, t0, fetchFn, time
332
300
  });
333
301
  if (!r.ok)
334
302
  return httpFailure(r, t0);
335
- if (connection.providerType === 'opencode-free') {
336
- const body = await r.readJson();
337
- if (!isOpenAIChatCompletion(body)) {
338
- return {
339
- ok: false,
340
- errorMessage: 'OpenCode Free returned no valid chat completion',
341
- errorClass: 'provider_unavailable',
342
- latencyMs: Date.now() - t0,
343
- modelTested: model,
344
- };
345
- }
346
- return { ok: true, latencyMs: Date.now() - t0, modelTested: model };
347
- }
348
303
  await r.cancel();
349
304
  return { ok: true, latencyMs: Date.now() - t0, modelTested: model };
350
305
  }
351
- function isOpenAIChatCompletion(value) {
352
- if (!value || typeof value !== 'object')
353
- return false;
354
- const choices = value.choices;
355
- return (Array.isArray(choices) &&
356
- choices.some((choice) => {
357
- if (!choice || typeof choice !== 'object')
358
- return false;
359
- const message = choice.message;
360
- if (!message || typeof message !== 'object')
361
- return false;
362
- const completion = message;
363
- return (typeof completion.content === 'string' ||
364
- typeof completion.reasoning === 'string' ||
365
- typeof completion.reasoning_content === 'string' ||
366
- (Array.isArray(completion.tool_calls) && completion.tool_calls.length > 0));
367
- }));
368
- }
369
306
  async function probeGoogle(baseUrl, apiKey, model, t0, normalizeBaseUrl, fetchFn) {
370
307
  const url = `${stripTrailing(baseUrl)}/models/${encodeURIComponent(model)}:generateContent${normalizeBaseUrl ? `?key=${encodeURIComponent(apiKey)}` : ''}`;
371
308
  const r = await fetchForConnectionEffect(fetchFn, url, {
@@ -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 { randomUUID } from 'node:crypto';
20
- import { CLIENT_CAPABILITY_MAX_RESULT_BYTES, CLIENT_CAPABILITY_RESULT_CHUNK_MAX_BYTES, decodeClientCapabilityClientFrame, decodeClientCapabilityReplaceInput, decodeClientCapabilityResult, } from '../protocol/index.js';
20
+ import { CLIENT_CAPABILITY_MAX_PROGRESS_TOTAL, CLIENT_CAPABILITY_MAX_RESULT_BYTES, CLIENT_CAPABILITY_RESULT_CHUNK_MAX_BYTES, decodeClientCapabilityClientFrame, decodeClientCapabilityReplaceInput, decodeClientCapabilityResult, } from '../protocol/index.js';
21
21
  /** Client-owned registration, reverse invocation, and teardown lifecycle. */
22
22
  export class ClientCapabilityChannel {
23
23
  #options;
@@ -247,6 +247,40 @@ export class ClientCapabilityChannel {
247
247
  });
248
248
  return accepting;
249
249
  };
250
+ let pendingProgress;
251
+ let progressWriting = false;
252
+ let progressWrite = Promise.resolve();
253
+ const scheduleProgressWrite = () => {
254
+ if (progressWriting)
255
+ return;
256
+ progressWriting = true;
257
+ progressWrite = (async () => {
258
+ while (pendingProgress) {
259
+ const next = pendingProgress;
260
+ pendingProgress = undefined;
261
+ try {
262
+ await this.#options.write({
263
+ kind: 'client.capability.progress',
264
+ invocationId,
265
+ current: next.current,
266
+ total: next.total,
267
+ });
268
+ }
269
+ catch {
270
+ // Progress is advisory: a failed write must not fail the invocation.
271
+ return;
272
+ }
273
+ }
274
+ })().finally(() => {
275
+ progressWriting = false;
276
+ });
277
+ };
278
+ const flushProgress = async () => {
279
+ do {
280
+ scheduleProgressWrite();
281
+ await progressWrite;
282
+ } while (pendingProgress);
283
+ };
250
284
  try {
251
285
  const progress = (current, total) => {
252
286
  if (!accepted ||
@@ -255,17 +289,17 @@ export class ClientCapabilityChannel {
255
289
  !Number.isInteger(total) ||
256
290
  current < 0 ||
257
291
  total < 1 ||
292
+ total > CLIENT_CAPABILITY_MAX_PROGRESS_TOTAL ||
258
293
  current > total) {
259
294
  return;
260
295
  }
261
- void this.#options
262
- .write({
263
- kind: 'client.capability.progress',
264
- invocationId,
265
- current,
266
- total,
267
- })
268
- .catch((error) => this.#options.onFailure(asError(error)));
296
+ const previous = invocation.progress;
297
+ if (previous && (previous.total !== total || current <= previous.current)) {
298
+ return;
299
+ }
300
+ invocation.progress = { current, total };
301
+ pendingProgress = { current, total };
302
+ scheduleProgressWrite();
269
303
  };
270
304
  const requestInteraction = async (request) => {
271
305
  if (!accepted) {
@@ -315,6 +349,7 @@ export class ClientCapabilityChannel {
315
349
  throw new Error('Client Capability provider returned with a pending interaction');
316
350
  }
317
351
  await accept({ kind: 'none' });
352
+ await flushProgress();
318
353
  await this.#sendResult(invocationId, result, invocation);
319
354
  }
320
355
  catch (error) {
@@ -30,7 +30,7 @@ export { RuntimeHostSshOperatorActivationError, activateRuntimeHostSshOperator,
30
30
  export { normalizeRuntimeHostSshDestination, openRuntimeHostSshTunnel, } from './ssh-tunnel.js';
31
31
  export { RuntimeHostPermanentReconnectError, startRuntimeHostReconnectLifecycle, } from './reconnect-lifecycle.js';
32
32
  export { RUNTIME_HOST_REMOTE_INCOMPATIBLE_CODE, RuntimeHostRemoteCompatibilityError, } from './remote-compatibility-error.js';
33
- export { RuntimeHostSubscriptionError, } from './session-subscription.js';
33
+ export { RuntimeHostSubscriptionError, SessionRemovedSubscriptionError, subscriptionClosedError, } from './session-subscription.js';
34
34
  export { RuntimeHostStartupError, runtimeHostStartupError, } from './startup-error.js';
35
35
  export { connectRuntimeHostWslEnvironment, listRuntimeHostWslDistributions, normalizeRuntimeHostWslDistribution, resolveSystemRuntimeHostWslExecutable, } from './wsl-environment.js';
36
36
  export { RuntimeHostCatalogReadError, RuntimeHostSessionCatalogRevisionChangedError, readRuntimeHostConnectionCatalog, readRuntimeHostInvocableSkills, readRuntimeHostProjectDetails, readRuntimeHostResources, readRuntimeHostProjects, readRuntimeHostSessionCatalogPage, readRuntimeHostSessions, readRuntimeHostSkillCatalog, } from './catalog-reader.js';
@@ -28,6 +28,18 @@ export class RuntimeHostSubscriptionError extends Error {
28
28
  this.name = 'RuntimeHostSubscriptionError';
29
29
  }
30
30
  }
31
+ export class SessionRemovedSubscriptionError extends Error {
32
+ name = 'SessionRemovedSubscriptionError';
33
+ }
34
+ export function subscriptionClosedError(reason) {
35
+ if (reason === 'session_removed') {
36
+ return new SessionRemovedSubscriptionError('Runtime Host Session was removed while it was observed');
37
+ }
38
+ if (reason === 'access_revoked') {
39
+ return new SessionRemovedSubscriptionError('Access to the shared Runtime Host Session was revoked');
40
+ }
41
+ return new RuntimeHostSubscriptionError('slow_consumer', 'Runtime Host Session subscription closed for a slow consumer');
42
+ }
31
43
  function errorMessage(error) {
32
44
  return error instanceof Error ? error.message : String(error);
33
45
  }
@@ -42,6 +54,16 @@ export class ClientSessionSubscription {
42
54
  #readyTask;
43
55
  #readTranscriptPage;
44
56
  #expectedSessionId;
57
+ get transcriptWatermark() {
58
+ return this.#latestTranscriptThroughSequence;
59
+ }
60
+ get deathCause() {
61
+ // #closedReason is recorded at accept()-time, before #terminalError can
62
+ // exist — it is always the authoritative death statement.
63
+ return this.#closedReason === undefined
64
+ ? this.#terminalError
65
+ : subscriptionClosedError(this.#closedReason);
66
+ }
45
67
  #queue = [];
46
68
  #ptyListeners = new Set();
47
69
  #sessionDomainListeners = new Set();
@@ -50,6 +72,7 @@ export class ClientSessionSubscription {
50
72
  #latestProjectionRevision;
51
73
  #waiting;
52
74
  #terminalError;
75
+ #closedReason;
53
76
  #done = false;
54
77
  #doneAfterQueue = false;
55
78
  #closing = false;
@@ -237,7 +260,9 @@ export class ClientSessionSubscription {
237
260
  }
238
261
  }
239
262
  #assertTranscriptReadable() {
240
- if (this.#closing || this.#done || this.#terminalError) {
263
+ if (this.#terminalError)
264
+ throw this.#terminalError;
265
+ if (this.#closing || this.#done) {
241
266
  throw new RuntimeHostSubscriptionError('connection_closed', 'Session subscription closed during transcript loading');
242
267
  }
243
268
  }
@@ -318,9 +343,14 @@ export class ClientSessionSubscription {
318
343
  }
319
344
  }
320
345
  }
321
- this.#offer(frame);
322
- if (frame.kind === 'subscription.closed')
346
+ if (frame.kind === 'subscription.closed') {
347
+ // Record the reason before the offer: a full client queue makes #offer
348
+ // throw 'slow_consumer', which would otherwise discard the real reason
349
+ // the Host gave for closing this subscription.
350
+ this.#closedReason = frame.reason;
323
351
  this.#doneAfterQueue = true;
352
+ }
353
+ this.#offer(frame);
324
354
  }
325
355
  finish() {
326
356
  this.#ptyListeners.clear();