maka-agent 0.2.0-dev.41.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 (54) hide show
  1. package/LICENSE +7 -4
  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/pi-tui-runner.js +57 -6
  8. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  9. package/node_modules/@maka/core/dist/client-plugin-bridge.js +19 -0
  10. package/node_modules/@maka/core/dist/connection-usage.js +27 -0
  11. package/node_modules/@maka/core/dist/events.js +58 -7
  12. package/node_modules/@maka/core/dist/external-session.js +4 -3
  13. package/node_modules/@maka/core/dist/interaction.js +38 -4
  14. package/node_modules/@maka/core/dist/llm-connections.js +4 -0
  15. package/node_modules/@maka/core/dist/model-metadata.js +89 -0
  16. package/node_modules/@maka/core/dist/provider-auth.js +9 -1
  17. package/node_modules/@maka/core/dist/recall.js +198 -15
  18. package/node_modules/@maka/core/dist/redaction.js +8 -0
  19. package/node_modules/@maka/core/dist/session-reference.js +149 -0
  20. package/node_modules/@maka/core/dist/skill-locations.js +29 -0
  21. package/node_modules/@maka/core/package.json +4 -0
  22. package/node_modules/@maka/runtime/dist/commandcode-cli-language-model.js +27 -3
  23. package/node_modules/@maka/runtime/dist/connection-usage.js +232 -0
  24. package/node_modules/@maka/runtime/dist/model-factory.js +5 -3
  25. package/node_modules/@maka/runtime/dist/model-history.js +13 -2
  26. package/node_modules/@maka/runtime/dist/plugin-client-bridge-service.js +308 -0
  27. package/node_modules/@maka/runtime/dist/plugin-composition-loader.js +4 -3
  28. package/node_modules/@maka/runtime/dist/plugin-data-services.js +3 -3
  29. package/node_modules/@maka/runtime/dist/recall-tools.js +70 -2
  30. package/node_modules/@maka/runtime/dist/skills-discovery.js +17 -23
  31. package/node_modules/@maka/runtime/package.json +2 -0
  32. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +132 -1
  33. package/node_modules/@maka/runtime-host/dist/protocol/index.js +11 -1
  34. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +6 -0
  35. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +269 -0
  36. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +2 -0
  37. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +57 -1
  38. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +50 -9
  39. package/node_modules/@maka/runtime-host/dist/server/extension-package-manifest.js +19 -1
  40. package/node_modules/@maka/runtime-host/dist/server/plugin-package-loader.js +88 -14
  41. package/node_modules/@maka/runtime-host/dist/server/plugin-package-store.js +22 -5
  42. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +122 -1
  43. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +120 -1
  44. package/node_modules/@maka/runtime-host/dist/server/recall-material-fetch.js +92 -0
  45. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +14 -1
  46. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +17 -1
  47. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +67 -3
  48. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +9 -3
  49. package/node_modules/@maka/runtime-host/dist/server/workhub-target-execution-authority.js +161 -0
  50. package/node_modules/@maka/storage/dist/codex-session-adapter.js +26 -28
  51. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +34 -1
  52. package/node_modules/@maka/storage/dist/runtime-policy-stores.js +2 -0
  53. package/node_modules/@maka/storage/dist/session-store.js +5 -2
  54. package/package.json +1 -1
@@ -0,0 +1,149 @@
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 { redactSecrets } from './redaction.js';
20
+ import { userFacingText } from './session.js';
21
+ const utf8Encoder = new TextEncoder();
22
+ /** Default per-reference budget. It is deliberately small enough to leave room for the active task. */
23
+ export const SESSION_SNAPSHOT_DEFAULT_MAX_CHARS = 12_000;
24
+ export const SESSION_SNAPSHOT_MAX_CHARS = 32_000;
25
+ export const SESSION_SNAPSHOT_MAX_BYTES = 32_000;
26
+ export const SESSION_SNAPSHOT_MAX_ITEMS = 24;
27
+ /**
28
+ * Build the model-safe portion of a Session transcript.
29
+ *
30
+ * Only user and assistant text is shareable. Tool calls/results, permission
31
+ * events, system notes, and other Runtime records remain outside this
32
+ * projection. Items are selected from the tail, then restored to transcript
33
+ * order so a large history cannot crowd the current request unexpectedly.
34
+ */
35
+ export function createSessionSnapshot(messages, options) {
36
+ const maxChars = clampPositiveInteger(options.maxChars ?? SESSION_SNAPSHOT_DEFAULT_MAX_CHARS, 1, SESSION_SNAPSHOT_MAX_CHARS);
37
+ const maxItems = clampPositiveInteger(options.maxItems ?? SESSION_SNAPSHOT_MAX_ITEMS, 1, SESSION_SNAPSHOT_MAX_ITEMS);
38
+ const candidates = messages.flatMap((message) => {
39
+ if (message.type !== 'user' && message.type !== 'assistant')
40
+ return [];
41
+ const text = message.type === 'user' ? userFacingText(message) : message.text;
42
+ const normalized = redactSecrets(text).trim();
43
+ if (!normalized)
44
+ return [];
45
+ return [
46
+ {
47
+ role: message.type,
48
+ text: normalized,
49
+ turnId: message.turnId,
50
+ ts: message.ts,
51
+ },
52
+ ];
53
+ });
54
+ const selected = [];
55
+ let usedChars = 0;
56
+ let usedBytes = 0;
57
+ let truncated = false;
58
+ for (let index = candidates.length - 1; index >= 0 && selected.length < maxItems; index -= 1) {
59
+ const candidate = candidates[index];
60
+ const line = formatSnapshotItem(candidate);
61
+ const separator = selected.length > 0 ? 2 : 0;
62
+ const available = maxChars - usedChars - separator;
63
+ const availableBytes = SESSION_SNAPSHOT_MAX_BYTES - usedBytes - separator;
64
+ if (available <= 0 || availableBytes <= 0) {
65
+ truncated = true;
66
+ break;
67
+ }
68
+ const lineBytes = utf8Encoder.encode(line).byteLength;
69
+ if (line.length <= available && lineBytes <= availableBytes) {
70
+ selected.push(candidate);
71
+ usedChars += separator + line.length;
72
+ usedBytes += separator + lineBytes;
73
+ continue;
74
+ }
75
+ if (selected.length === 0) {
76
+ const prefix = formatSnapshotItem({ ...candidate, text: '' });
77
+ const contentBudget = Math.max(0, available - prefix.length);
78
+ const byteBudget = Math.max(0, availableBytes - utf8Encoder.encode(prefix).byteLength);
79
+ if (contentBudget > 0 && byteBudget > 0) {
80
+ const text = sliceAtUtf8Boundary(sliceAtCodePointBoundary(candidate.text, contentBudget), byteBudget).trimEnd();
81
+ if (!text) {
82
+ truncated = true;
83
+ break;
84
+ }
85
+ selected.push({
86
+ ...candidate,
87
+ text,
88
+ });
89
+ usedChars = maxChars;
90
+ }
91
+ }
92
+ truncated = true;
93
+ break;
94
+ }
95
+ if (selected.length < candidates.length)
96
+ truncated = true;
97
+ selected.reverse();
98
+ const text = sliceAtCodePointBoundary(selected.map(formatSnapshotItem).join('\n\n'), maxChars);
99
+ return {
100
+ reference: {
101
+ sessionId: options.sessionId,
102
+ sessionName: redactSecrets(options.sessionName),
103
+ capturedAt: options.capturedAt ?? Date.now(),
104
+ },
105
+ items: selected,
106
+ text,
107
+ estimatedTokens: Math.ceil(text.length / 4),
108
+ maxChars,
109
+ truncated,
110
+ };
111
+ }
112
+ /** Convert a snapshot into the existing inline quote transport. */
113
+ export function sessionSnapshotToQuote(snapshot) {
114
+ const sessionName = redactSecrets(snapshot.reference.sessionName);
115
+ return {
116
+ text: snapshot.text,
117
+ label: sliceAtCodePointBoundary(`Session: ${sessionName}`, 200),
118
+ sourceSessionId: snapshot.reference.sessionId,
119
+ sourceSessionName: sliceAtCodePointBoundary(sessionName, 200),
120
+ sourceCapturedAt: snapshot.reference.capturedAt,
121
+ sourceTruncated: snapshot.truncated,
122
+ };
123
+ }
124
+ function formatSnapshotItem(item) {
125
+ return `${item.role === 'user' ? 'User' : 'Assistant'}: ${item.text}`;
126
+ }
127
+ /** Keep a UTF-16 slice from ending between the halves of a surrogate pair. */
128
+ function sliceAtCodePointBoundary(value, maxCodeUnits) {
129
+ const sliced = value.slice(0, maxCodeUnits);
130
+ const last = sliced.charCodeAt(sliced.length - 1);
131
+ return last >= 0xd800 && last <= 0xdbff ? sliced.slice(0, -1) : sliced;
132
+ }
133
+ function sliceAtUtf8Boundary(value, maxBytes) {
134
+ let bytes = 0;
135
+ let end = 0;
136
+ for (const codePoint of value) {
137
+ const nextBytes = utf8Encoder.encode(codePoint).byteLength;
138
+ if (bytes + nextBytes > maxBytes)
139
+ break;
140
+ bytes += nextBytes;
141
+ end += codePoint.length;
142
+ }
143
+ return value.slice(0, end);
144
+ }
145
+ function clampPositiveInteger(value, min, max) {
146
+ if (!Number.isSafeInteger(value))
147
+ return min;
148
+ return Math.max(min, Math.min(max, value));
149
+ }
@@ -0,0 +1,29 @@
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
+ /** Standard discovery locations in precedence order; also the directory-opening allowlist. */
20
+ export const STANDARD_SKILL_LOCATIONS = [
21
+ { ref: 'project:maka', scope: 'project', source: 'maka', segments: ['.maka', 'skills'] },
22
+ { ref: 'project:agents', scope: 'project', source: 'agents', segments: ['.agents', 'skills'] },
23
+ { ref: 'workspace:legacy', scope: 'workspace', source: 'legacy', segments: ['skills'] },
24
+ { ref: 'user:maka', scope: 'user', source: 'maka', segments: ['.maka', 'skills'] },
25
+ { ref: 'user:agents', scope: 'user', source: 'agents', segments: ['.agents', 'skills'] },
26
+ ];
27
+ export function findSkillLocation(ref) {
28
+ return STANDARD_SKILL_LOCATIONS.find((location) => location.ref === ref);
29
+ }
@@ -29,6 +29,7 @@
29
29
  "./provider-retry-countdown": "./dist/provider-retry-countdown.js",
30
30
  "./interaction": "./dist/interaction.js",
31
31
  "./session": "./dist/session.js",
32
+ "./session-reference": "./dist/session-reference.js",
32
33
  "./session-revisions": "./dist/session-revisions.js",
33
34
  "./collaboration": "./dist/collaboration.js",
34
35
  "./orchestration": "./dist/orchestration.js",
@@ -61,11 +62,13 @@
61
62
  "./artifacts": "./dist/artifacts.js",
62
63
  "./pet": "./dist/pet.js",
63
64
  "./skill-invocation": "./dist/skill-invocation.js",
65
+ "./skill-locations": "./dist/skill-locations.js",
64
66
  "./runtime-inputs": "./dist/runtime-inputs.js",
65
67
  "./e2e-fixture": "./dist/e2e-fixture.js",
66
68
  "./capabilities": "./dist/capabilities.js",
67
69
  "./capability-audit": "./dist/capability-audit.js",
68
70
  "./client-capability-grant": "./dist/client-capability-grant.js",
71
+ "./client-plugin-bridge": "./dist/client-plugin-bridge.js",
69
72
  "./health": "./dist/health.js",
70
73
  "./search": "./dist/search.js",
71
74
  "./bot-events": "./dist/bot-events.js",
@@ -132,6 +135,7 @@
132
135
  "./bot-onboarding": "./dist/bot-onboarding.js",
133
136
  "./computer-use": "./dist/computer-use.js",
134
137
  "./connection-error-copy": "./dist/connection-error-copy.js",
138
+ "./connection-usage": "./dist/connection-usage.js",
135
139
  "./git-review": "./dist/git-review.js",
136
140
  "./graph-command": "./dist/graph-command.js",
137
141
  "./project": "./dist/project.js",
@@ -576,6 +576,12 @@ function cliEventsToStreamParts(input) {
576
576
  let reasoningId;
577
577
  let nextId = 0;
578
578
  let finished = false;
579
+ // The wire splits one call's usage across two events: `finish-step` carries
580
+ // the provider's OWN body (`prompt_tokens`, `prompt_cache_hit_tokens`, …)
581
+ // under `usage.raw`, and `finish` carries only the normalized totals. The
582
+ // provider keys are what telemetry's cache accounting reads, so keep the
583
+ // body here until the finish event can carry it out.
584
+ let providerUsageRaw;
579
585
  const closeText = (controller) => {
580
586
  if (textId === undefined)
581
587
  return;
@@ -644,13 +650,20 @@ function cliEventsToStreamParts(input) {
644
650
  controller.enqueue({ type: 'tool-call', toolCallId: id, toolName, input: args });
645
651
  break;
646
652
  }
653
+ case 'finish-step': {
654
+ // Carries the provider's own usage body; `finish` normalizes it away.
655
+ const usage = isRecord(event.usage) ? event.usage : undefined;
656
+ if (isRecord(usage?.raw))
657
+ providerUsageRaw = usage.raw;
658
+ break;
659
+ }
647
660
  case 'finish': {
648
661
  closeText(controller);
649
662
  closeReasoning(controller);
650
663
  finished = true;
651
664
  controller.enqueue({
652
665
  type: 'finish',
653
- usage: usageFromEvent(event.totalUsage),
666
+ usage: usageFromEvent(event.totalUsage, providerUsageRaw),
654
667
  finishReason: mapFinishReason(event.finishReason),
655
668
  });
656
669
  break;
@@ -685,7 +698,7 @@ function cliEventsToStreamParts(input) {
685
698
  },
686
699
  });
687
700
  }
688
- function usageFromEvent(value) {
701
+ function usageFromEvent(value, providerRaw) {
689
702
  if (!isRecord(value))
690
703
  return emptyUsage();
691
704
  const inputDetails = isRecord(value.inputTokenDetails) ? value.inputTokenDetails : undefined;
@@ -702,7 +715,18 @@ function usageFromEvent(value) {
702
715
  text: undefined,
703
716
  reasoning: numberValue(outputDetails?.reasoningTokens),
704
717
  },
705
- raw: value,
718
+ // `raw` must stay the PROVIDER's own usage body, which is where the
719
+ // OpenAI/Anthropic cache keys live (`prompt_tokens`,
720
+ // `prompt_tokens_details.cached_tokens`, `cache_read_input_tokens`, …).
721
+ // Only `finish-step` carries that body; `finish.totalUsage` is already
722
+ // normalized, so carrying the envelope here left telemetry's strict reader
723
+ // looking for `prompt_tokens` on an object that had only `inputTokens` —
724
+ // every attempt settled as `usageBasis: 'missing'` and the composer's
725
+ // context gauge never moved.
726
+ //
727
+ // The fallback keeps a body-less event readable on the normalized keys
728
+ // rather than handing telemetry `undefined`.
729
+ raw: (providerRaw ?? value),
706
730
  };
707
731
  }
708
732
  function emptyUsage() {
@@ -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
+ }
@@ -654,11 +654,13 @@ function buildFamilyWire(connection, modelId, level, thinkingOptions, requestedL
654
654
  : {},
655
655
  };
656
656
  case 'commandcode-cli':
657
- // The CLI wire takes `reasoning_effort` as the CLI's own effort words;
658
- // `max` has no counterpart there and rounds down to `high`.
657
+ // The CLI wire takes `reasoning_effort` as the CLI's own effort words.
658
+ // `max` is one of them (claude-fable-5-1, moonshotai/Kimi-K3, …), so the
659
+ // chosen level is forwarded verbatim — rounding it down would silently
660
+ // send a weaker request than the user asked for.
659
661
  return level === undefined || level === 'off'
660
662
  ? {}
661
- : { 'commandcode-cli': { reasoningEffort: level === 'max' ? 'high' : level } };
663
+ : { 'commandcode-cli': { reasoningEffort: level } };
662
664
  default:
663
665
  return {};
664
666
  }
@@ -799,8 +799,19 @@ function formatAttachmentRefs(attachments) {
799
799
  function formatQuoteRefs(quotes) {
800
800
  return quotes
801
801
  .map((q) => {
802
- const label = q.label === undefined ? '' : ` label="${q.label.replace(/"/g, "'")}"`;
803
- return `<quoted_excerpt${label}>\n${q.text}\n</quoted_excerpt>`;
802
+ const attributes = [
803
+ q.label === undefined ? undefined : `label="${quoteAttribute(q.label)}"`,
804
+ q.sourceSessionId === undefined
805
+ ? undefined
806
+ : `source_session="${quoteAttribute(q.sourceSessionId)}"`,
807
+ q.sourceCapturedAt === undefined ? undefined : `captured_at="${q.sourceCapturedAt}"`,
808
+ q.sourceTruncated === undefined ? undefined : `truncated="${q.sourceTruncated}"`,
809
+ ].filter((attribute) => attribute !== undefined);
810
+ const opening = attributes.length > 0 ? `<quoted_excerpt ${attributes.join(' ')}>` : '<quoted_excerpt>';
811
+ return `${opening}\n${q.text}\n</quoted_excerpt>`;
804
812
  })
805
813
  .join('\n');
806
814
  }
815
+ function quoteAttribute(value) {
816
+ return value.replace(/["<&>]/g, (character) => character === '"' ? "'" : `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`);
817
+ }