maka-agent 0.2.0-dev.15.20260902 → 0.2.0-dev.16.20260903

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 (160) hide show
  1. package/dist/cli-core.js +0 -1
  2. package/dist/pi-transcript.js +48 -0
  3. package/dist/pi-tui-form-interaction.js +497 -0
  4. package/dist/pi-tui-pickers.js +256 -55
  5. package/dist/pi-tui-runner.js +215 -12
  6. package/dist/runtime-host-cli.js +17 -42
  7. package/dist/runtime-host-lifecycle-transaction.js +31 -13
  8. package/dist/runtime-host-managed-lifecycle-manager.js +1 -1
  9. package/dist/runtime-host-onboarding.js +3 -1
  10. package/dist/runtime-host-openrc-service.js +469 -0
  11. package/dist/runtime-host-run-command.js +6 -2
  12. package/dist/runtime-host-service-command.js +3 -3
  13. package/dist/runtime-host-service-management-command.js +43 -15
  14. package/dist/runtime-host-session-channel.js +3 -0
  15. package/dist/runtime-host-session-driver.js +21 -6
  16. package/dist/runtime-host-setup-command.js +30 -31
  17. package/dist/tui-context-refresh.js +103 -0
  18. package/dist/tui-copy-catalog.js +73 -0
  19. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  20. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  21. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  22. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  23. package/node_modules/@maka/core/dist/chat-model-choice.js +4 -0
  24. package/node_modules/@maka/core/dist/computer-use.js +27 -92
  25. package/node_modules/@maka/core/dist/interaction.js +577 -3
  26. package/node_modules/@maka/core/dist/llm-connections.js +4 -0
  27. package/node_modules/@maka/core/dist/local-memory.js +2 -2
  28. package/node_modules/@maka/core/dist/model-call-usage-projection.js +3 -0
  29. package/node_modules/@maka/core/dist/model-metadata.js +26 -7
  30. package/node_modules/@maka/core/dist/model-thinking.js +17 -0
  31. package/node_modules/@maka/core/dist/provider-registry.js +1 -0
  32. package/node_modules/@maka/core/dist/runtime-event.js +23 -1
  33. package/node_modules/@maka/core/dist/scheduled-task.js +4 -0
  34. package/node_modules/@maka/core/dist/session.js +95 -2
  35. package/node_modules/@maka/core/dist/text-sanitize.js +19 -0
  36. package/node_modules/@maka/core/dist/usage-ledger-merge.js +3 -0
  37. package/node_modules/@maka/core/dist/usage-record-schema.js +11 -5
  38. package/node_modules/@maka/core/dist/workhub-creation-intent.js +75 -9
  39. package/node_modules/@maka/core/dist/workhub-session-resolver.js +50 -0
  40. package/node_modules/@maka/core/package.json +2 -0
  41. package/node_modules/@maka/eval/dist/harbor-external-subject.js +2 -1
  42. package/node_modules/@maka/eval/dist/harness-executor.js +3 -2
  43. package/node_modules/@maka/eval/dist/install-preflight.js +39 -10
  44. package/node_modules/@maka/eval/dist/process-termination.js +83 -0
  45. package/node_modules/@maka/mcp/dist/sep-2243.js +3 -3
  46. package/node_modules/@maka/runtime/dist/agent-run.js +6 -3
  47. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +332 -118
  48. package/node_modules/@maka/runtime/dist/ai-sdk-compaction-contract.js +6 -1
  49. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +171 -341
  50. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +3 -26
  51. package/node_modules/@maka/runtime/dist/bundled-skill-catalog.generated.js +1 -1
  52. package/node_modules/@maka/runtime/dist/computer-use-codec.js +1 -141
  53. package/node_modules/@maka/runtime/dist/computer-use-tools.js +23 -105
  54. package/node_modules/@maka/runtime/dist/context-budget-policy.js +20 -26
  55. package/node_modules/@maka/runtime/dist/context-budget.js +18 -20
  56. package/node_modules/@maka/runtime/dist/conversation-copy.js +23 -19
  57. package/node_modules/@maka/runtime/dist/cua-frame-state.js +1 -69
  58. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +267 -0
  59. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +6 -9
  60. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +67 -23
  61. package/node_modules/@maka/runtime/dist/history-compact-summary-validation.js +11 -18
  62. package/node_modules/@maka/runtime/dist/history-compaction.js +66 -73
  63. package/node_modules/@maka/runtime/dist/interaction-authority.js +69 -0
  64. package/node_modules/@maka/runtime/dist/mcp-tools.js +13 -1
  65. package/node_modules/@maka/runtime/dist/memory-extraction.js +11 -11
  66. package/node_modules/@maka/runtime/dist/model-adapter.js +24 -6
  67. package/node_modules/@maka/runtime/dist/model-factory.js +14 -5
  68. package/node_modules/@maka/runtime/dist/oauth-provider-contracts.js +28 -1
  69. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +7 -6
  70. package/node_modules/@maka/runtime/dist/opencode-session-header.js +29 -0
  71. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +11 -1
  72. package/node_modules/@maka/runtime/dist/runtime-kernel.js +12 -11
  73. package/node_modules/@maka/runtime/dist/runtime-read-model.js +51 -13
  74. package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +3 -0
  75. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +26 -0
  76. package/node_modules/@maka/runtime/dist/session-manager.js +1 -0
  77. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +16 -1
  78. package/node_modules/@maka/runtime/dist/stream-graph-projection.js +6 -0
  79. package/node_modules/@maka/runtime/dist/stream-graph-read-model.js +5 -0
  80. package/node_modules/@maka/runtime/dist/stream-usage-fallback-fetch.js +74 -0
  81. package/node_modules/@maka/runtime/dist/subscription-credentials.js +51 -4
  82. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +47 -3
  83. package/node_modules/@maka/runtime/dist/system-prompt/main-session-prompt.js +20 -1
  84. package/node_modules/@maka/runtime/dist/test-connection.js +18 -11
  85. package/node_modules/@maka/runtime/dist/tool-runtime.js +183 -0
  86. package/node_modules/@maka/runtime/package.json +1 -0
  87. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +14 -0
  88. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +84 -1
  89. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +68 -51
  90. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  91. package/node_modules/@maka/runtime-host/dist/client/owner-connection-code.js +8 -5
  92. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +342 -36
  93. package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +60 -4
  94. package/node_modules/@maka/runtime-host/dist/peer-mesh/index.js +3 -3
  95. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +1 -1
  96. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +48 -60
  97. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +847 -431
  98. package/node_modules/@maka/runtime-host/dist/peer-mesh/owner.js +33 -74
  99. package/node_modules/@maka/runtime-host/dist/peer-mesh/store.js +82 -69
  100. package/node_modules/@maka/runtime-host/dist/peer-reachability/index.js +21 -0
  101. package/node_modules/@maka/runtime-host/dist/peer-reachability/model.js +202 -0
  102. package/node_modules/@maka/runtime-host/dist/peer-reachability/owner.js +119 -0
  103. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +245 -0
  104. package/node_modules/@maka/runtime-host/dist/protocol/agent-graph.js +4 -1
  105. package/node_modules/@maka/runtime-host/dist/protocol/client-capability.js +68 -0
  106. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +15 -8
  107. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +7 -23
  108. package/node_modules/@maka/runtime-host/dist/protocol/index.js +47 -1
  109. package/node_modules/@maka/runtime-host/dist/protocol/oauth.js +25 -1
  110. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  111. package/node_modules/@maka/runtime-host/dist/protocol/peer-mesh.js +14 -31
  112. package/node_modules/@maka/runtime-host/dist/protocol/scheduled-task.js +19 -6
  113. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +36 -1
  114. package/node_modules/@maka/runtime-host/dist/protocol/session-revision.js +11 -2
  115. package/node_modules/@maka/runtime-host/dist/protocol/usage-pricing.js +16 -2
  116. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +51 -2
  117. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +35 -2
  118. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  119. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +12 -10
  120. package/node_modules/@maka/runtime-host/dist/server/client-capability-invocation-broker.js +163 -30
  121. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +38 -14
  122. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +45 -22
  123. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +78 -20
  124. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +4 -2
  125. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +2 -1
  126. package/node_modules/@maka/runtime-host/dist/server/execution-service.js +49 -28
  127. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +3 -6
  128. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +130 -27
  129. package/node_modules/@maka/runtime-host/dist/server/interaction-projection.js +30 -1
  130. package/node_modules/@maka/runtime-host/dist/server/listener-set.js +2 -4
  131. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +16 -3
  132. package/node_modules/@maka/runtime-host/dist/server/oauth-coordinator.js +66 -3
  133. package/node_modules/@maka/runtime-host/dist/server/oauth-execution-authority.js +20 -3
  134. package/node_modules/@maka/runtime-host/dist/server/peer-listener.js +8 -21
  135. package/node_modules/@maka/runtime-host/dist/server/peer-mesh-authority.js +1 -1
  136. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +6 -3
  137. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +72 -12
  138. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +48 -18
  139. package/node_modules/@maka/runtime-host/dist/server/session-turn-access-request-coordinator.js +43 -26
  140. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +15 -1
  141. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +229 -4
  142. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +146 -8
  143. package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +32 -6
  144. package/node_modules/@maka/runtime-host/package.json +1 -0
  145. package/node_modules/@maka/storage/dist/agent-run-store.js +18 -5
  146. package/node_modules/@maka/storage/dist/codex-session-adapter.js +14 -0
  147. package/node_modules/@maka/storage/dist/execution-stores.js +5 -0
  148. package/node_modules/@maka/storage/dist/interaction-store.js +13 -1
  149. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +9 -3
  150. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +49 -19
  151. package/node_modules/@maka/storage/dist/runtime-policy/oauth-login-receipt-document.js +3 -1
  152. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +13 -5
  153. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +4 -2
  154. package/node_modules/@maka/storage/dist/session-store.js +39 -6
  155. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +16 -9
  156. package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +30 -3
  157. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +117 -0
  158. package/node_modules/@maka/storage/dist/sqlite-usage-store.js +29 -6
  159. package/node_modules/@maka/storage/dist/usage-stores.js +3 -1
  160. package/package.json +1 -1
@@ -17,15 +17,19 @@
17
17
  * under the License.
18
18
  */
19
19
  import { lookupModelMetadata } from '@maka/core/model-metadata';
20
- import { relayModelProfile } from '@maka/core/model-thinking';
21
- export function buildDefaultContextBudgetPolicy(connection, options = {}) {
22
- const contextWindow = resolveSelectedModelContextWindow(connection, options.modelId);
23
- const reserveTokens = defaultCompactReserveTokens(contextWindow);
24
- const maxHistoryEstimatedTokens = defaultHistoryBudgetTokens(connection, contextWindow, reserveTokens);
20
+ import { declaredContextWindow, relayModelProfile } from '@maka/core/model-thinking';
21
+ /**
22
+ * The shipped context-budget policy. It carries no history budget and no
23
+ * reserve: whether a request fits is the provider's answer, and the only
24
+ * proactive threshold is the context window the user declared for the model
25
+ * (see `resolveDeclaredContextWindow`), read by the compaction seam itself.
26
+ * What remains here are content policies — how one oversized Tool Result
27
+ * enters the request — and the compaction switches (#4559).
28
+ */
29
+ export function buildDefaultContextBudgetPolicy(options = {}) {
25
30
  const surfaceName = (options.name ?? 'default-history-budget').replace(/-default-history-budget$/, '');
26
31
  return {
27
32
  name: options.name ?? 'default-history-budget',
28
- ...(maxHistoryEstimatedTokens !== undefined ? { maxHistoryEstimatedTokens } : {}),
29
33
  staleToolResultPrune: {
30
34
  enabled: true,
31
35
  maxResultEstimatedTokens: 2_048,
@@ -34,7 +38,7 @@ export function buildDefaultContextBudgetPolicy(connection, options = {}) {
34
38
  historyCompact: {
35
39
  enabled: true,
36
40
  highWaterName: `${surfaceName}-history-compact`,
37
- midTurn: { enabled: true, reserveTokens },
41
+ midTurn: { enabled: true },
38
42
  },
39
43
  activeToolResultPrune: {
40
44
  enabled: true,
@@ -44,26 +48,16 @@ export function buildDefaultContextBudgetPolicy(connection, options = {}) {
44
48
  },
45
49
  };
46
50
  }
47
- // Single owner of the compaction reserve default. The classic 16384 reserve
48
- // assumed large-window models; on an 8K window it derived a 1-token history
49
- // budget and a 1-token mid_turn high water — every multi-step turn ran the
50
- // summarizer for a checkpoint the replay gate could never admit. The default
51
- // is therefore bounded by the KNOWN window (a quarter of it, capped at 16384;
52
- // peers bound the same way: opencode caps its buffer by the model's output
53
- // limit, gemini-cli triggers at a window fraction). An unknown window keeps
54
- // the classic constant.
55
- function defaultCompactReserveTokens(contextWindow) {
56
- if (contextWindow === undefined)
57
- return 16_384;
58
- return Math.min(16_384, Math.max(1, Math.floor(contextWindow / 4)));
59
- }
60
- function defaultHistoryBudgetTokens(connection, contextWindow, reserveTokens) {
61
- if (contextWindow !== undefined) {
62
- return Math.max(1, contextWindow - reserveTokens);
63
- }
64
- if (connection.providerType === 'deepseek')
51
+ /**
52
+ * The Maka window for the selected model: the context window the user declared,
53
+ * resolved by core's single owner of that rule (`declaredContextWindow`), or
54
+ * undefined when nothing is declared — and then no proactive compaction runs.
55
+ */
56
+ export function resolveDeclaredContextWindow(connection, modelId) {
57
+ const selectedModelId = modelId ?? connection.defaultModel;
58
+ if (selectedModelId === undefined)
65
59
  return undefined;
66
- return 32_000;
60
+ return declaredContextWindow(connection, selectedModelId);
67
61
  }
68
62
  export function resolveSelectedModelContextWindow(connection, modelId) {
69
63
  const selectedModelId = modelId ?? connection.defaultModel;
@@ -22,19 +22,19 @@ import { estimateRuntimeEventsTokens } from './model-history.js';
22
22
  export { estimateTokens } from './context-budget-helpers.js';
23
23
  export { estimateRuntimeEventsTokens } from './model-history.js';
24
24
  export { ARCHIVED_TOOL_RESULT_PLACEHOLDER_KIND, ARCHIVED_TOOL_RESULT_REWRITE_VERSION, isArchivedToolResultPlaceholder, deserializeToolResultArchive, serializeToolResultForArchive, } from './tool-result-archive.js';
25
- import { applyRuntimeEventHistoryCompact as applyRuntimeEventHistoryCompactNarrow, evaluateHistoryCompactCheckpointReplay as evaluateHistoryCompactCheckpointReplayNarrow, } from './history-compaction.js';
25
+ import { applyRuntimeEventHistoryCompact as applyRuntimeEventHistoryCompactNarrow, } from './history-compaction.js';
26
26
  export function applyRuntimeEventContextBudget(events, policy) {
27
27
  const prunePolicy = policy?.staleToolResultPrune;
28
28
  const pruneEnabled = prunePolicy?.enabled === true;
29
29
  const historyCompactEnabled = policy?.historyCompact?.enabled === true;
30
- const enabled = Boolean(policy?.maxHistoryEstimatedTokens || pruneEnabled || historyCompactEnabled);
30
+ const enabled = pruneEnabled || historyCompactEnabled;
31
31
  if (!enabled)
32
32
  return undefined;
33
33
  if (!policy)
34
34
  return undefined;
35
35
  const charsPerToken = policy?.charsPerToken ?? 4;
36
36
  const estimatedTokensBefore = estimateRuntimeEventsTokens(events, charsPerToken);
37
- const compacted = applyRuntimeEventHistoryCompactNarrow(events, policy?.historyCompact, policy?.charsPerToken, policy?.maxHistoryEstimatedTokens, { charsPerToken });
37
+ const compacted = applyRuntimeEventHistoryCompactNarrow(events, policy?.historyCompact, charsPerToken);
38
38
  // Stale Tool Result pruning is no longer a step of the budget: it is a
39
39
  // durable projection transition committed before this projection runs, and
40
40
  // the events arriving here have already been folded through the reducer
@@ -46,9 +46,6 @@ export function applyRuntimeEventContextBudget(events, policy) {
46
46
  const diagnostic = {
47
47
  enabled: true,
48
48
  ...(policy?.name ? { policyName: policy.name } : {}),
49
- ...(policy.maxHistoryEstimatedTokens !== undefined
50
- ? { maxHistoryEstimatedTokens: policy.maxHistoryEstimatedTokens }
51
- : {}),
52
49
  estimatedTokensBefore,
53
50
  estimatedTokensAfter: estimateRuntimeEventsTokens(keptEvents, charsPerToken),
54
51
  keptTurns: keptTurnIds.size,
@@ -95,9 +92,6 @@ export function buildContextBudgetDiagnosticShell(before, after, policy) {
95
92
  return {
96
93
  enabled: true,
97
94
  ...(policy?.name ? { policyName: policy.name } : {}),
98
- ...(policy?.maxHistoryEstimatedTokens !== undefined
99
- ? { maxHistoryEstimatedTokens: policy.maxHistoryEstimatedTokens }
100
- : {}),
101
95
  estimatedTokensBefore: estimateRuntimeEventsTokens(before, charsPerToken),
102
96
  estimatedTokensAfter: estimateRuntimeEventsTokens(after, charsPerToken),
103
97
  keptTurns: turnCountAfter,
@@ -125,15 +119,22 @@ export function mergeContextBudgetDiagnosticPatches(left, right) {
125
119
  return left;
126
120
  return mergeContextBudgetDiagnostic(left, right);
127
121
  }
122
+ // A history fold reaches the user as one note per send, whichever stage
123
+ // performed it: the replay of an existing checkpoint at turn start
124
+ // (`priorReplay`) or a fold the request-projection hook made before a request
125
+ // of this send (`activeStep`, pre_turn or mid_turn). Since #4486 every new fold
126
+ // happens in the hook, so a note keyed on replay alone would arrive one turn
127
+ // late — the turn that was compacted would show nothing (#4559).
128
+ function hasHistoryCompactDecision(contextBudget, decision) {
129
+ return (contextBudget?.compactionDecisions?.some((candidate) => (candidate.stage === 'priorReplay' || candidate.stage === 'activeStep') &&
130
+ candidate.boundaryKind === 'historyCompact' &&
131
+ candidate.decision === decision) === true);
132
+ }
128
133
  export function shouldAppendContextCompactedNote(contextBudget) {
129
- return (contextBudget?.compactionDecisions?.some((decision) => decision.stage === 'priorReplay' &&
130
- decision.boundaryKind === 'historyCompact' &&
131
- decision.decision === 'replaced') === true);
134
+ return hasHistoryCompactDecision(contextBudget, 'replaced');
132
135
  }
133
136
  export function shouldAppendContextCompactionFailedOpenNote(contextBudget) {
134
- return (contextBudget?.compactionDecisions?.some((decision) => decision.stage === 'priorReplay' &&
135
- decision.boundaryKind === 'historyCompact' &&
136
- decision.decision === 'failedOpen') === true);
137
+ return hasHistoryCompactDecision(contextBudget, 'failedOpen');
137
138
  }
138
139
  export function minimalContextBudgetDiagnostic() {
139
140
  return {
@@ -160,9 +161,6 @@ function mergeCompactionDecisionDiagnostics(left, right) {
160
161
  // Public compat wrappers: preserve the pre-split `(events, policy, options)`
161
162
  // signature for @maka/runtime consumers. Internal callers (this module and
162
163
  // ai-sdk-backend) import the narrow leaf API directly from the leaf modules.
163
- export function applyRuntimeEventHistoryCompact(events, policy, options = {}) {
164
- return applyRuntimeEventHistoryCompactNarrow(events, policy?.historyCompact, policy?.charsPerToken, policy?.maxHistoryEstimatedTokens, options);
165
- }
166
- export function evaluateHistoryCompactCheckpointReplay(checkpoint, replayTail, policy, options = {}) {
167
- return evaluateHistoryCompactCheckpointReplayNarrow(checkpoint, replayTail, policy?.charsPerToken, policy?.maxHistoryEstimatedTokens, options);
164
+ export function applyRuntimeEventHistoryCompact(events, policy) {
165
+ return applyRuntimeEventHistoryCompactNarrow(events, policy?.historyCompact, policy?.charsPerToken);
168
166
  }
@@ -337,7 +337,6 @@ export async function cloneConversationRuntimeLedger(input) {
337
337
  plan,
338
338
  runId,
339
339
  clonedRun: cloneRunHeader(plan.run, input.referenceMap.targetSessionId, runId, invocationId, references),
340
- clonedRuntimeEvents: plan.events.map((event) => clonedEventBySourceId.get(event.id)),
341
340
  clonedOperationalEvents,
342
341
  terminalEvent,
343
342
  };
@@ -346,19 +345,25 @@ export async function cloneConversationRuntimeLedger(input) {
346
345
  for (const { clonedRun } of preparedPlans) {
347
346
  await input.runStore.createRun(clonedRun);
348
347
  }
349
- if (input.runtimeEventStore.importConversationCopyRuntimeEvents) {
350
- await input.runtimeEventStore.importConversationCopyRuntimeEvents(input.referenceMap.targetSessionId, preparedPlans.map(({ runId, clonedRuntimeEvents }) => ({
348
+ const importedSourceEventIds = new Set();
349
+ const orderedBatches = input.plan.inlineRuntimeEvents.flatMap((event) => {
350
+ const cloned = clonedEventBySourceId.get(event.id);
351
+ const runId = runIds.get(event.runId);
352
+ if (!cloned || !runId)
353
+ return [];
354
+ importedSourceEventIds.add(event.id);
355
+ return [{ runId, events: [cloned] }];
356
+ });
357
+ for (const { plan, runId } of preparedPlans) {
358
+ const remaining = plan.events.filter((event) => !importedSourceEventIds.has(event.id));
359
+ if (remaining.length === 0)
360
+ continue;
361
+ orderedBatches.push({
351
362
  runId,
352
- events: clonedRuntimeEvents,
353
- })));
354
- }
355
- else {
356
- for (const { runId, clonedRuntimeEvents } of preparedPlans) {
357
- for (const clonedEvent of clonedRuntimeEvents) {
358
- await input.runtimeEventStore.appendRuntimeEvent(input.referenceMap.targetSessionId, runId, clonedEvent);
359
- }
360
- }
363
+ events: remaining.map((event) => clonedEventBySourceId.get(event.id)),
364
+ });
361
365
  }
366
+ await input.runtimeEventStore.importConversationCopyRuntimeEvents(input.referenceMap.targetSessionId, orderedBatches);
362
367
  for (const { plan, runId, clonedOperationalEvents, terminalEvent } of preparedPlans) {
363
368
  for (const clonedEvent of clonedOperationalEvents) {
364
369
  await input.runStore.appendEvent(input.referenceMap.targetSessionId, runId, clonedEvent);
@@ -569,14 +574,13 @@ function cloneAgentRunEvent(event, ids, references, sourceCompactableEvents, clo
569
574
  return null;
570
575
  // Copy is an admission seam for the sectioned summary contract: a marked
571
576
  // checkpoint whose summary no longer satisfies the COMPLETE predicate —
572
- // including the size floor, re-runnable here because the matched covered
573
- // span is in hand — must not propagate into a fresh session. Unmarked
574
- // legacy summaries stay copyable under the truncation-only load policy
575
- // and keep their unmarked identity in the target.
577
+ // re-runnable here on structure and truncation (the size floor needs the
578
+ // summarizer call's usage, which a copy does not have) — must not
579
+ // propagate into a fresh session. Unmarked legacy summaries stay copyable
580
+ // under the truncation-only load policy and keep their unmarked identity
581
+ // in the target.
576
582
  if (sourceCheckpoint.summaryFormat !== undefined &&
577
- findCheckpointSummaryDefect(sourceCheckpoint.summary, {
578
- coveredRuntimeEvents: match.coveredRuntimeEvents,
579
- }) !== undefined) {
583
+ findCheckpointSummaryDefect(sourceCheckpoint.summary) !== undefined) {
580
584
  throw new Error(`Cannot copy invalid history compact checkpoint ${event.id}`);
581
585
  }
582
586
  const coveredRuntimeEvents = match.coveredRuntimeEvents.map((sourceEvent) => {
@@ -188,73 +188,7 @@ export function bindCuaSemanticActionToObservation(observation, input) {
188
188
  });
189
189
  }
190
190
  export function bindCuaActionToObservation(observation, action) {
191
- const base = bindCuaAction(observation, fingerprintCuaAction(action), observation.target);
192
- if (action.type === 'zoom') {
193
- const start = bindWindowPoint(observation, {
194
- x: Math.min(action.region.x1, action.region.x2),
195
- y: Math.min(action.region.y1, action.region.y2),
196
- });
197
- const end = bindWindowPoint(observation, {
198
- x: Math.max(action.region.x1, action.region.x2),
199
- y: Math.max(action.region.y1, action.region.y2),
200
- });
201
- if (!start || !end)
202
- return undefined;
203
- return {
204
- ...finalizeBoundAction({
205
- ...base,
206
- sourceStartCoordinate: start,
207
- sourceCoordinate: end,
208
- windowStartCoordinate: start,
209
- windowCoordinate: end,
210
- coordinateSpace: 'window-screenshot-local',
211
- }),
212
- };
213
- }
214
- if ('coordinate' in action) {
215
- const end = bindWindowPoint(observation, action.coordinate);
216
- if (!end)
217
- return undefined;
218
- if (action.type === 'left_click_drag') {
219
- const start = bindWindowPoint(observation, action.startCoordinate);
220
- if (!start)
221
- return undefined;
222
- return finalizeBoundAction({
223
- ...base,
224
- sourceStartCoordinate: start,
225
- sourceCoordinate: end,
226
- windowStartCoordinate: start,
227
- windowCoordinate: end,
228
- coordinateSpace: 'window-screenshot-local',
229
- });
230
- }
231
- return finalizeBoundAction({
232
- ...base,
233
- sourceCoordinate: end,
234
- windowCoordinate: end,
235
- coordinateSpace: 'window-screenshot-local',
236
- });
237
- }
238
- return base;
239
- }
240
- function bindWindowPoint(observation, point) {
241
- const width = observation.screenshotWidthPx ?? observation.target.sourceBoundsPx?.width ?? 0;
242
- const height = observation.screenshotHeightPx ?? observation.target.sourceBoundsPx?.height ?? 0;
243
- return width > 0 &&
244
- height > 0 &&
245
- point.x >= 0 &&
246
- point.y >= 0 &&
247
- point.x < width &&
248
- point.y < height
249
- ? point
250
- : undefined;
251
- }
252
- function finalizeBoundAction(action) {
253
- const withPlaceholder = { ...action, fingerprint: '' };
254
- return {
255
- ...withPlaceholder,
256
- fingerprint: fingerprintBoundAction(withPlaceholder),
257
- };
191
+ return bindCuaAction(observation, fingerprintCuaAction(action), observation.target);
258
192
  }
259
193
  function fingerprintBoundAction(action) {
260
194
  return JSON.stringify([
@@ -264,7 +198,5 @@ function fingerprintBoundAction(action) {
264
198
  action.target.pid,
265
199
  action.target.windowId,
266
200
  action.elementId ?? null,
267
- action.sourceStartCoordinate ?? null,
268
- action.sourceCoordinate ?? null,
269
201
  ]);
270
202
  }
@@ -0,0 +1,267 @@
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 { createGitHubCopilotAccountTokens, GITHUB_COPILOT_DEFAULT_API_ENDPOINT, isSupportedGitHubCopilotAccountToken, } from './subscription-credentials.js';
20
+ import { fetchGitHubCopilotModels } from './model-fetcher.js';
21
+ import { ConnectionEffectHttpError } from './connection-effect-outcome.js';
22
+ import { OAUTH_LOGIN_MAX_TOKEN_CHARS, OAuthTokenEndpointError, requestOAuthEndpointJson, } from './oauth-login.js';
23
+ import { OAUTH_PROVIDER_CONTRACTS, OAuthDeviceAuthorizationExpiredError, oauthExpiresAt, requireOAuthBoundedString, requireOAuthDataRecord, requireOAuthPositiveInteger, } from './oauth-provider-contracts.js';
24
+ const COPILOT = OAUTH_PROVIDER_CONTRACTS['github-copilot'];
25
+ const MAX_TOKEN_LIFETIME_SECONDS = 366 * 24 * 60 * 60;
26
+ /**
27
+ * A GitHub account authorized the grant, and the Copilot API then refused it —
28
+ * an account without a live subscription, or one whose organization withholds
29
+ * Copilot. The credential is real and the authorization succeeded, so this is
30
+ * the provider refusing the account rather than a failed login. Only a proven
31
+ * refusal reaches here: a catalog the account can read but that lists nothing,
32
+ * or a deterministic 401/403 from the Copilot API.
33
+ */
34
+ export class GitHubCopilotEntitlementError extends Error {
35
+ constructor(options) {
36
+ super('GitHub account exposes no usable Copilot model', options);
37
+ this.name = 'GitHubCopilotEntitlementError';
38
+ }
39
+ }
40
+ /**
41
+ * The entitlement question could not be answered — a timeout, a dropped
42
+ * connection, a rate limit, a 5xx, or a response the client could not read.
43
+ *
44
+ * This must never be reported as an ineligible account: nothing about the
45
+ * subscription was learned, no credential was committed, and the same login
46
+ * will usually succeed on the next attempt. The provider status is preserved
47
+ * for diagnosis, and the Host maps this to a retryable authorization failure.
48
+ */
49
+ export class GitHubCopilotEntitlementUnavailableError extends Error {
50
+ status;
51
+ constructor(status, options) {
52
+ super(status === undefined
53
+ ? 'GitHub Copilot entitlement could not be verified'
54
+ : `GitHub Copilot entitlement could not be verified (${status})`, options);
55
+ this.status = status;
56
+ this.name = 'GitHubCopilotEntitlementUnavailableError';
57
+ }
58
+ }
59
+ export async function startGitHubCopilotDeviceAuthorization(input) {
60
+ const response = await requestOAuthEndpointJson({
61
+ endpoint: COPILOT.deviceEndpoint,
62
+ init: {
63
+ method: 'POST',
64
+ headers: {
65
+ Accept: 'application/json',
66
+ 'Content-Type': 'application/x-www-form-urlencoded',
67
+ },
68
+ body: new URLSearchParams({
69
+ client_id: COPILOT.clientId,
70
+ scope: COPILOT.scope,
71
+ }).toString(),
72
+ },
73
+ fetchFn: input.fetchFn,
74
+ signal: input.signal,
75
+ timeoutMs: input.timeoutMs,
76
+ });
77
+ if (!response.ok)
78
+ throw new OAuthTokenEndpointError('provider_rejected', response.status);
79
+ const payload = requireOAuthDataRecord(response.payload);
80
+ // GitHub answers a malformed device request with HTTP 200 and an `error`
81
+ // body, so an ok status alone does not mean an authorization was issued.
82
+ const rejection = providerErrorCode(payload);
83
+ if (rejection)
84
+ throw new OAuthTokenEndpointError('provider_rejected', response.status);
85
+ const deviceCode = requireOAuthBoundedString(payload.device_code, OAUTH_LOGIN_MAX_TOKEN_CHARS);
86
+ const userCode = requireOAuthBoundedString(payload.user_code, 1_024);
87
+ const verificationUrl = requireOAuthBoundedString(payload.verification_uri, 8_192);
88
+ assertGitHubVerificationUrl(verificationUrl);
89
+ const now = input.now?.() ?? Date.now();
90
+ const expiresIn = requireOAuthPositiveInteger(payload.expires_in, 24 * 60 * 60);
91
+ const intervalSeconds = payload.interval === undefined ? 5 : requireOAuthPositiveInteger(payload.interval, 300);
92
+ return {
93
+ deviceCode,
94
+ userCode,
95
+ verificationUrl,
96
+ expiresAt: oauthExpiresAt(now, expiresIn, response.status),
97
+ intervalMs: intervalSeconds * 1_000,
98
+ };
99
+ }
100
+ export async function pollGitHubCopilotDeviceAuthorization(input) {
101
+ const now = input.now ?? (() => Date.now());
102
+ const sleep = input.sleep ?? abortableSleep;
103
+ let intervalMs = input.authorization.intervalMs;
104
+ for (;;) {
105
+ // Sleep at most until the window elapses, then re-check so no request is
106
+ // issued after the device code expired locally.
107
+ const remaining = input.authorization.expiresAt - now();
108
+ if (remaining <= 0)
109
+ throw new OAuthDeviceAuthorizationExpiredError();
110
+ await sleep(Math.min(intervalMs, remaining), input.signal);
111
+ input.signal.throwIfAborted();
112
+ if (now() >= input.authorization.expiresAt) {
113
+ throw new OAuthDeviceAuthorizationExpiredError();
114
+ }
115
+ input.onPollAdmission?.();
116
+ const response = await requestOAuthEndpointJson({
117
+ endpoint: COPILOT.tokenEndpoint,
118
+ init: {
119
+ method: 'POST',
120
+ headers: {
121
+ Accept: 'application/json',
122
+ 'Content-Type': 'application/x-www-form-urlencoded',
123
+ },
124
+ body: new URLSearchParams({
125
+ client_id: COPILOT.clientId,
126
+ device_code: input.authorization.deviceCode,
127
+ grant_type: COPILOT.deviceGrant,
128
+ }).toString(),
129
+ },
130
+ fetchFn: input.fetchFn,
131
+ // One token request is not cancellable: an abort between the grant being
132
+ // spent and the token being read would strand a usable credential.
133
+ signal: new AbortController().signal,
134
+ timeoutMs: input.timeoutMs,
135
+ });
136
+ if (!response.ok)
137
+ throw new OAuthTokenEndpointError('provider_rejected', response.status);
138
+ const payload = requireOAuthDataRecord(response.payload);
139
+ // Unlike xAI, GitHub reports pending/slow_down as HTTP 200 with an `error`
140
+ // body, so the error code must be read before the success shape.
141
+ const code = providerErrorCode(payload);
142
+ if (code === 'authorization_pending') {
143
+ input.onPollRetry?.();
144
+ input.signal.throwIfAborted();
145
+ continue;
146
+ }
147
+ if (code === 'slow_down') {
148
+ const advertised = payload.interval;
149
+ intervalMs =
150
+ advertised === undefined
151
+ ? Math.min(intervalMs + 5_000, 5 * 60 * 1_000)
152
+ : requireOAuthPositiveInteger(advertised, 300) * 1_000;
153
+ input.onPollRetry?.();
154
+ input.signal.throwIfAborted();
155
+ continue;
156
+ }
157
+ // A denial is the account refusing; `expired_token` only means the user did
158
+ // not finish in time, which the host maps to authorization_failed instead.
159
+ if (code === 'access_denied')
160
+ throw new OAuthTokenEndpointError('invalid_grant', response.status);
161
+ if (code === 'expired_token')
162
+ throw new OAuthDeviceAuthorizationExpiredError();
163
+ if (code)
164
+ throw new OAuthTokenEndpointError('provider_rejected', response.status);
165
+ return decodeGitHubCopilotAccountToken(payload, now);
166
+ }
167
+ }
168
+ /**
169
+ * The device grant proves a GitHub account, not a Copilot subscription: the
170
+ * token endpoint issues the same account token whether or not Copilot is
171
+ * entitled. Ask the Copilot API what that account can actually reach, so an
172
+ * unusable credential is refused while the login is still in flight instead of
173
+ * being committed and failing later on the first request.
174
+ *
175
+ * Runs on the caller's transport — the same one the grant was obtained over.
176
+ */
177
+ export async function verifyGitHubCopilotModelEntitlement(input) {
178
+ let models;
179
+ try {
180
+ models = await fetchGitHubCopilotModels(input.tokens.base_url ?? GITHUB_COPILOT_DEFAULT_API_ENDPOINT, input.tokens.access_token, input.fetchFn);
181
+ }
182
+ catch (error) {
183
+ // Only the provider refusing this account is an entitlement answer. A
184
+ // timeout, a dropped connection, a rate limit, a 5xx, or an unreadable
185
+ // body tell us nothing about the subscription, and reporting them as
186
+ // ineligibility would send a paying user back through a device login that
187
+ // was never the problem.
188
+ if (error instanceof ConnectionEffectHttpError &&
189
+ (error.status === 401 || error.status === 403)) {
190
+ throw new GitHubCopilotEntitlementError({ cause: error });
191
+ }
192
+ throw new GitHubCopilotEntitlementUnavailableError(error instanceof ConnectionEffectHttpError ? error.status : undefined, { cause: error });
193
+ }
194
+ // A catalog the account could read, listing nothing it may use.
195
+ if (models.length === 0)
196
+ throw new GitHubCopilotEntitlementError();
197
+ return models;
198
+ }
199
+ /**
200
+ * The device grant must yield a GitHub OAuth user token (`gho_`/`ghu_`). A
201
+ * classic PAT shape here would mean the flow resolved to something other than
202
+ * the account that authorized it, so it is rejected rather than stored.
203
+ *
204
+ * GitHub returns `expires_in`/`refresh_token` only when the OAuth app has
205
+ * expiring user tokens enabled. That lifetime is carried through verbatim so
206
+ * the credential can be renewed; an expiring token recorded as non-expiring
207
+ * would silently stop working and force another interactive login. An
208
+ * expiring response without a refresh token is unusable for the same reason
209
+ * and is rejected instead of stored.
210
+ */
211
+ function decodeGitHubCopilotAccountToken(payload, now) {
212
+ const accessToken = requireOAuthBoundedString(payload.access_token, OAUTH_LOGIN_MAX_TOKEN_CHARS);
213
+ if (!isSupportedGitHubCopilotAccountToken(accessToken)) {
214
+ throw new OAuthTokenEndpointError('invalid_response');
215
+ }
216
+ if (payload.expires_in === undefined)
217
+ return createGitHubCopilotAccountTokens(accessToken);
218
+ const expiresInSeconds = requireOAuthPositiveInteger(payload.expires_in, MAX_TOKEN_LIFETIME_SECONDS);
219
+ const refreshToken = requireOAuthBoundedString(payload.refresh_token, OAUTH_LOGIN_MAX_TOKEN_CHARS);
220
+ return createGitHubCopilotAccountTokens(accessToken, {
221
+ expiresAt: oauthExpiresAt(now(), expiresInSeconds),
222
+ refreshToken,
223
+ });
224
+ }
225
+ function providerErrorCode(value) {
226
+ if (!value || typeof value !== 'object' || Array.isArray(value))
227
+ return;
228
+ const error = value.error;
229
+ return typeof error === 'string' ? error.toLowerCase() : undefined;
230
+ }
231
+ /**
232
+ * The verification URL is handed to the presentation layer, which opens it in
233
+ * the user's browser. Pin it to github.com so a malformed response cannot
234
+ * redirect the user somewhere else to type a code that looks legitimate.
235
+ */
236
+ function assertGitHubVerificationUrl(value) {
237
+ let url;
238
+ try {
239
+ url = new URL(value);
240
+ }
241
+ catch {
242
+ throw new OAuthTokenEndpointError('invalid_response');
243
+ }
244
+ if (url.protocol !== 'https:' ||
245
+ url.username ||
246
+ url.password ||
247
+ (url.hostname !== 'github.com' && !url.hostname.endsWith('.github.com'))) {
248
+ throw new OAuthTokenEndpointError('invalid_response');
249
+ }
250
+ }
251
+ function abortableSleep(delayMs, signal) {
252
+ return new Promise((resolve, reject) => {
253
+ if (signal.aborted) {
254
+ reject(signal.reason ?? new DOMException('OAuth login cancelled', 'AbortError'));
255
+ return;
256
+ }
257
+ const onAbort = () => {
258
+ clearTimeout(timer);
259
+ reject(signal.reason ?? new DOMException('OAuth login cancelled', 'AbortError'));
260
+ };
261
+ const timer = setTimeout(() => {
262
+ signal.removeEventListener('abort', onAbort);
263
+ resolve();
264
+ }, delayMs);
265
+ signal.addEventListener('abort', onAbort, { once: true });
266
+ });
267
+ }
@@ -48,16 +48,13 @@ export function buildHistoryCompactCheckpoint(input) {
48
48
  throw new Error('History compact checkpoint requires valid provider compaction state');
49
49
  }
50
50
  // The sectioned marker is proof that the complete predicate held, so only
51
- // this builder assigns it — and only after re-checking against the covered
52
- // span (structure, truncation, AND the size floor, since the covered events
53
- // are in hand here at every construction seam, including copy). A caller
54
- // with unvalidated free-form text must declare `legacy_freeform` instead of
55
- // minting trust it did not earn.
51
+ // this builder assigns it — and only after re-checking structure and
52
+ // truncation at every construction seam, including copy. The size floor is
53
+ // the summarizer's own check: it needs the provider's usage for the call,
54
+ // which no construction seam has. A caller with unvalidated free-form text
55
+ // must declare `legacy_freeform` instead of minting trust it did not earn.
56
56
  if (!providerState && input.summaryFormat !== 'legacy_freeform') {
57
- const defect = findCheckpointSummaryDefect(summary, {
58
- coveredRuntimeEvents: input.coveredRuntimeEvents,
59
- ...(input.charsPerToken !== undefined ? { charsPerToken: input.charsPerToken } : {}),
60
- });
57
+ const defect = findCheckpointSummaryDefect(summary);
61
58
  if (defect) {
62
59
  throw new Error(`History compact checkpoint summary failed validation: ${defect}`);
63
60
  }