maka-agent 0.2.0-dev.52.20260926 → 0.2.0-dev.53.20260927

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 (71) hide show
  1. package/dist/activation-command.js +11 -3
  2. package/dist/pi-tui-mcp-status.js +73 -5
  3. package/dist/pi-tui-runner.js +1 -1
  4. package/dist/runtime-host-run-command.js +39 -6
  5. package/dist/runtime-host-run-mcp.js +161 -0
  6. package/dist/runtime-host-session-driver.js +22 -2
  7. package/dist/tui-copy-catalog.js +6 -0
  8. package/dist/tui-mcp-control.js +11 -2
  9. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  10. package/node_modules/@maka/core/dist/attachments.js +7 -0
  11. package/node_modules/@maka/core/dist/events.js +11 -0
  12. package/node_modules/@maka/core/dist/provider-registry.js +11 -2
  13. package/node_modules/@maka/core/dist/turn-origin.js +6 -0
  14. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +1 -5
  15. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +80 -24
  16. package/node_modules/@maka/runtime/dist/bots/proxied-fetch.js +5 -4
  17. package/node_modules/@maka/runtime/dist/computer-use-tools.js +136 -100
  18. package/node_modules/@maka/runtime/dist/context-budget-helpers.js +4 -0
  19. package/node_modules/@maka/runtime/dist/conversation-copy.js +51 -205
  20. package/node_modules/@maka/runtime/dist/edit-replace.js +7 -7
  21. package/node_modules/@maka/runtime/dist/filesystem-executor.js +4 -20
  22. package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +17 -28
  23. package/node_modules/@maka/runtime/dist/format-json.js +39 -0
  24. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +1 -6
  25. package/node_modules/@maka/runtime/dist/image-file.js +22 -14
  26. package/node_modules/@maka/runtime/dist/model-adapter.js +18 -2
  27. package/node_modules/@maka/runtime/dist/model-history.js +201 -3
  28. package/node_modules/@maka/runtime/dist/network/abortable-connector.js +55 -0
  29. package/node_modules/@maka/runtime/dist/network/proxy-dispatcher.js +72 -37
  30. package/node_modules/@maka/runtime/dist/network/proxy-test.js +1 -1
  31. package/node_modules/@maka/runtime/dist/network/scoped-fetch-transport.js +7 -2
  32. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +1 -3
  33. package/node_modules/@maka/runtime/dist/provider-error-classification.js +36 -8
  34. package/node_modules/@maka/runtime/dist/recovery-resolver.js +1 -91
  35. package/node_modules/@maka/runtime/dist/runtime-kernel.js +44 -0
  36. package/node_modules/@maka/runtime/dist/session-manager.js +54 -58
  37. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +84 -2
  38. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +63 -51
  39. package/node_modules/@maka/runtime/dist/workspace-executor.js +5 -6
  40. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +27 -6
  41. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +4 -1
  42. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +9 -9
  43. package/node_modules/@maka/runtime-host/dist/client/session-catalog-summary.js +9 -1
  44. package/node_modules/@maka/runtime-host/dist/protocol/index.js +12 -1
  45. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +28 -6
  46. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +12 -2
  47. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +10 -7
  48. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +10 -2
  49. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +2 -0
  50. package/node_modules/@maka/runtime-host/dist/server/interactive-turn-coordinator.js +4 -1
  51. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +4 -2
  52. package/node_modules/@maka/runtime-host/dist/server/operation-dispatcher.js +4 -0
  53. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +6 -5
  54. package/node_modules/@maka/runtime-host/dist/server/safe-boundary-resume-policy.js +27 -0
  55. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +5 -3
  56. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +7 -2
  57. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +11 -141
  58. package/node_modules/@maka/runtime-host/dist/server/session-revision-graph-references.js +46 -75
  59. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +18 -2
  60. package/node_modules/@maka/runtime-host/dist/server/workhub-result-coordinator.js +33 -3
  61. package/node_modules/@maka/runtime-host/dist/transport/framed-byte-stream-transport.js +39 -5
  62. package/node_modules/@maka/storage/dist/agent-run-store-contract.js +7 -1
  63. package/node_modules/@maka/storage/dist/artifact-store.js +1 -5
  64. package/node_modules/@maka/storage/dist/artifact-stores.js +0 -3
  65. package/node_modules/@maka/storage/dist/atomic-file-write.js +1 -0
  66. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +107 -57
  67. package/node_modules/@maka/storage/dist/codex-session-adapter.js +227 -19
  68. package/node_modules/@maka/storage/dist/external-session-importer.js +1 -1
  69. package/node_modules/@maka/storage/dist/mcp-config-store.js +22 -3
  70. package/node_modules/@maka/storage/dist/settings-store.js +281 -13
  71. package/package.json +1 -1
@@ -16,26 +16,34 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { stat, readFile } from 'node:fs/promises';
19
+ import { open } from 'node:fs/promises';
20
20
  import { extname } from 'node:path';
21
21
  import { imageDimensionsFromData } from 'image-dimensions';
22
- import { MAX_MODEL_IMAGE_EDGE, MAX_READ_IMAGE_BYTES, READ_IMAGE_TOO_LARGE_MESSAGE, sniffAttachmentMimeType, } from '@maka/core/attachments';
22
+ import { ATTACHMENT_MIME_SNIFF_BYTES, MAX_MODEL_IMAGE_EDGE, MAX_READ_IMAGE_BYTES, READ_IMAGE_TOO_LARGE_MESSAGE, sniffAttachmentMimeType, } from '@maka/core/attachments';
23
23
  const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp']);
24
24
  export function isSupportedImagePath(path) {
25
25
  return IMAGE_EXTENSIONS.has(extname(path).toLowerCase());
26
26
  }
27
- export async function readWorkspaceImage(path) {
28
- const size = await stat(path).catch(() => {
29
- throw new Error('Image could not be read.');
30
- });
31
- if (!size.isFile())
32
- throw new Error('Image path is not a file.');
33
- if (size.size > MAX_READ_IMAGE_BYTES)
34
- throw imageTooLargeError();
35
- const bytes = await readFile(path).catch(() => {
36
- throw new Error('Image could not be read.');
37
- });
38
- return validateImageBytes(bytes);
27
+ /** Classify a bounded prefix before decoding text or allocating an image body. */
28
+ export async function readWorkspaceFile(path) {
29
+ const file = await open(path, 'r');
30
+ try {
31
+ const prefix = Buffer.alloc(ATTACHMENT_MIME_SNIFF_BYTES);
32
+ // A positioned read leaves the descriptor's offset at zero for readFile.
33
+ const { bytesRead } = await file.read(prefix, 0, prefix.length, 0);
34
+ if (isSupportedImagePath(path) || sniffImageMime(prefix.subarray(0, bytesRead))) {
35
+ const size = await file.stat();
36
+ if (!size.isFile())
37
+ throw new Error('Image path is not a file.');
38
+ if (size.size > MAX_READ_IMAGE_BYTES)
39
+ throw imageTooLargeError();
40
+ return validateImageBytes(await file.readFile());
41
+ }
42
+ return { content: await file.readFile('utf8') };
43
+ }
44
+ finally {
45
+ await file.close();
46
+ }
39
47
  }
40
48
  export function validateImageBytes(bytes) {
41
49
  if (bytes.length > MAX_READ_IMAGE_BYTES)
@@ -20,6 +20,7 @@ import { openai } from '@ai-sdk/openai';
20
20
  import { anthropic } from '@ai-sdk/anthropic';
21
21
  import { providerAuthRequiresSecret, } from '@maka/core/llm-connections';
22
22
  import { lookupModelMetadata } from '@maka/core/model-metadata';
23
+ import { providerAcceptsOutputTokenLimit } from '@maka/core/provider-registry';
23
24
  import { rawFinishReasonString } from './model-protocol.js';
24
25
  import { resolveModelRuntime } from './model-runtime.js';
25
26
  import { resolveSelectedModelContextWindow } from './context-budget-policy.js';
@@ -95,7 +96,17 @@ export class ModelAdapter {
95
96
  : {}),
96
97
  });
97
98
  }
99
+ /**
100
+ * Whether a request to this connection may carry an output-token limit at
101
+ * all. When it may not, no limit is sent: neither a configured per-model
102
+ * limit nor the context-recovery cap.
103
+ */
104
+ acceptsOutputTokenLimit() {
105
+ return providerAcceptsOutputTokenLimit(this.input.connection.providerType);
106
+ }
98
107
  maxOutputTokens() {
108
+ if (!this.acceptsOutputTokenLimit())
109
+ return undefined;
99
110
  return selectedModelMaxOutputTokens(this.input.connection, this.input.modelId, this.input.providerOptions, this.runtime);
100
111
  }
101
112
  /**
@@ -130,8 +141,13 @@ export class ModelAdapter {
130
141
  throw new Error(`Failed to load 'ai' package. Run \`npm install ai\`. Inner: ${err.message}`);
131
142
  });
132
143
  const { streamText, wrapLanguageModel } = ai;
133
- const maxOutputTokens = input.maxOutputTokens ??
134
- selectedModelMaxOutputTokens(this.input.connection, this.input.modelId, this.input.providerOptions, this.runtime);
144
+ // The one place a main-turn output limit reaches the wire. A provider that
145
+ // rejects any limit gets none, whether it came from the caller (overflow
146
+ // recovery, a resumed request) or from the configured model limit.
147
+ const maxOutputTokens = this.acceptsOutputTokenLimit()
148
+ ? (input.maxOutputTokens ??
149
+ selectedModelMaxOutputTokens(this.input.connection, this.input.modelId, this.input.providerOptions, this.runtime))
150
+ : undefined;
135
151
  let settleAccounting;
136
152
  const terminalModel = withProviderFinishBoundary(input.model, wrapLanguageModel);
137
153
  const trackedModel = input.providerRequestTracker
@@ -48,10 +48,195 @@
48
48
  */
49
49
  import { isPartialRuntimeEvent, isTerminalRuntimeEvent, runtimeEventHasModelVisibleContent, } from '@maka/core/runtime-event';
50
50
  import { formatAttachmentResourceRef } from '@maka/core/attachments';
51
+ import { runtimeInvocationFailureClass } from './runtime-event-read-model.js';
51
52
  import { decodeEffectiveToolResultProjection, durableProjectionToToolResultOutput, effectiveToolResultMedia, } from './durable-tool-result-projection.js';
52
53
  import { MATERIALIZED_IMAGE_TOKENS } from '@maka/core/attachments';
53
54
  import { estimateTokens, stableJsonLength, turnKey } from './context-budget-helpers.js';
55
+ import { resolveRuntimeRecovery } from './recovery-resolver.js';
54
56
  export const PROVIDER_REPLAY_PROJECTION_VERSION = 2;
57
+ /**
58
+ * An admitted root has the lineage its kind implies; an explicit user message
59
+ * has none at all. Exact emptiness, not a list of per-field negatives, so a
60
+ * lineage field added later cannot quietly widen what retires an unknown.
61
+ */
62
+ function lineageIsEmpty(lineage) {
63
+ if (lineage === undefined)
64
+ return true;
65
+ return Object.values(lineage).every((value) => value === undefined);
66
+ }
67
+ /**
68
+ * Retire an unknown only after the conversation demonstrably moved on with the
69
+ * model informed. While an unknown is active this gate admits explicit user
70
+ * turns alone, so a later user-rooted, fresh, lineage-free invocation that
71
+ * completed is exactly the turn the unknown was projected into. Retried,
72
+ * regenerated, branched, and sub-agent turns carry lineage; continuations and
73
+ * handoffs are not `fresh`; Goal, schedule, wake, and compaction runs root in
74
+ * their own authority kinds; every other automated turn fails at this gate
75
+ * before it could complete.
76
+ */
77
+ function unknownOutcomeRetired(invocation, invocations) {
78
+ const terminalTs = invocation.terminalEvent?.ts;
79
+ if (terminalTs === undefined)
80
+ return false;
81
+ return (invocations ?? []).some((later) => later.invocationId !== invocation.invocationId &&
82
+ later.openedAt > terminalTs &&
83
+ later.terminalEvent?.status === 'completed' &&
84
+ later.opening.root.kind === 'user' &&
85
+ later.opening.source.kind === 'fresh' &&
86
+ lineageIsEmpty(later.opening.lineage));
87
+ }
88
+ /**
89
+ * Admit only sealed T1-without-T2 facts for a manual fresh message. The
90
+ * synthetic tool response is request-local; it is never appended to the event
91
+ * ledger and must not be mistaken for evidence that the tool settled.
92
+ */
93
+ export function inspectPriorUnknownToolOutcomes(events, invocations) {
94
+ const eventsByInvocationId = new Map();
95
+ for (const event of events) {
96
+ const invocationEvents = eventsByInvocationId.get(event.invocationId) ?? [];
97
+ invocationEvents.push(event);
98
+ eventsByInvocationId.set(event.invocationId, invocationEvents);
99
+ }
100
+ const invocationById = new Map((invocations ?? []).map((run) => [run.invocationId, run]));
101
+ const indeterminate = [];
102
+ for (const [invocationId, invocationEvents] of eventsByInvocationId) {
103
+ const invocation = invocationById.get(invocationId);
104
+ const sealedUnknown = invocation?.terminalEvent &&
105
+ invocation.terminalEvent.status === 'failed' &&
106
+ runtimeInvocationFailureClass(invocation) === 'outcome_unknown';
107
+ if (sealedUnknown && invocation && unknownOutcomeRetired(invocation, invocations)) {
108
+ // The explicit turn this unknown was projected into completed with the
109
+ // model informed; the conversation moved on. Without this the sealed
110
+ // invocation would re-fire on every later turn forever.
111
+ continue;
112
+ }
113
+ const recovery = resolveRuntimeRecovery(invocationEvents);
114
+ if (recovery.hasCorruption) {
115
+ // Strict per-invocation framing is authoritative only for an invocation
116
+ // that claims an unknown tool outcome. Other groups are ordinary
117
+ // history — request-time context legitimately carries compaction
118
+ // artifacts (pruned or archived tool results, checkpoint transitions,
119
+ // tolerated orphans) that strict single-invocation framing rejects.
120
+ if (sealedUnknown) {
121
+ return { kind: 'blocked', reason: 'prior tool history is corrupt' };
122
+ }
123
+ continue;
124
+ }
125
+ indeterminate.push(...recovery.decisions.filter((decision) => decision.status === 'indeterminate'));
126
+ }
127
+ // Only a dispatch without its response is an unknown tool effect. A call
128
+ // that never crossed T1 provably produced no side effect, so other
129
+ // indeterminate shapes keep their pre-existing projection behavior and are
130
+ // not this gate's concern.
131
+ const dispatchedUnknown = indeterminate.filter((decision) => decision.reason === 'dispatch_without_response');
132
+ if (dispatchedUnknown.length === 0)
133
+ return { kind: 'none' };
134
+ if (dispatchedUnknown.some((decision) => !decision.operationId || !decision.callRuntimeEventId || !decision.dispatchRuntimeEventId)) {
135
+ return { kind: 'blocked', reason: 'prior tool outcome is not a sealed dispatched operation' };
136
+ }
137
+ const eventsById = new Map(events.map((event) => [event.id, event]));
138
+ const outcomes = [];
139
+ for (const decision of dispatchedUnknown) {
140
+ const callEvent = eventsById.get(decision.callRuntimeEventId);
141
+ const dispatchEvent = eventsById.get(decision.dispatchRuntimeEventId);
142
+ const call = callEvent?.content;
143
+ const invocation = callEvent ? invocationById.get(callEvent.invocationId) : undefined;
144
+ const dispatch = dispatchEvent?.actions?.toolDispatch;
145
+ if (!callEvent ||
146
+ call?.kind !== 'function_call' ||
147
+ !dispatch ||
148
+ dispatchEvent.invocationId !== callEvent.invocationId ||
149
+ dispatch.operationId !== decision.operationId ||
150
+ dispatch.providerToolCallId !== call.id ||
151
+ dispatch.toolName !== call.name ||
152
+ !decision.operationId ||
153
+ !invocation?.terminalEvent ||
154
+ invocation.sessionId !== callEvent.sessionId ||
155
+ invocation.runId !== callEvent.runId ||
156
+ invocation.turnId !== callEvent.turnId ||
157
+ invocation.terminalEvent.sessionId !== callEvent.sessionId ||
158
+ invocation.terminalEvent.runId !== callEvent.runId ||
159
+ invocation.terminalEvent.turnId !== callEvent.turnId ||
160
+ invocation.terminalEvent.invocationId !== callEvent.invocationId ||
161
+ !isTerminalRuntimeEvent(invocation.terminalEvent) ||
162
+ invocation.terminalEvent.status !== 'failed' ||
163
+ runtimeInvocationFailureClass(invocation) !== 'outcome_unknown') {
164
+ return { kind: 'blocked', reason: 'prior unknown tool outcome has no sealed invocation' };
165
+ }
166
+ // Hidden nested operations are an implementation detail of their parent
167
+ // tool. Validate their durable boundary above, but never surface their
168
+ // names or operation identities in model-visible request context.
169
+ if (callEvent.modelVisibility === 'hidden')
170
+ continue;
171
+ outcomes.push({
172
+ callEventId: callEvent.id,
173
+ toolCallId: call.id,
174
+ toolName: call.name,
175
+ operationId: decision.operationId,
176
+ });
177
+ }
178
+ if (outcomes.length === 0)
179
+ return { kind: 'none' };
180
+ const rows = outcomes
181
+ .slice(0, 64)
182
+ .map((outcome) => `- ${outcome.toolName} (operation ${outcome.operationId})`);
183
+ if (outcomes.length > 64)
184
+ rows.push(`- and ${outcomes.length - 64} more unknown operations`);
185
+ return {
186
+ kind: 'projected',
187
+ outcomes,
188
+ systemNotice: [
189
+ 'A prior execution was interrupted after these tools were dispatched. No durable tool results were recorded; their side effects may or may not have happened.',
190
+ 'The outcome_unknown tool responses in history are temporary context, not proof of success or failure. Inspect current state before repeating any action.',
191
+ ...rows,
192
+ ].join('\n'),
193
+ };
194
+ }
195
+ /** Insert request-only tool responses beside their calls so provider history stays well-formed. */
196
+ export function appendPriorUnknownToolResponses(events, projection) {
197
+ const byCallEventId = new Map(projection.outcomes.map((outcome) => [outcome.callEventId, outcome]));
198
+ const projected = [];
199
+ for (const event of events) {
200
+ projected.push(event);
201
+ const outcome = byCallEventId.get(event.id);
202
+ const call = event.content;
203
+ if (!outcome || call?.kind !== 'function_call')
204
+ continue;
205
+ projected.push({
206
+ id: `model-projection:outcome-unknown:${event.id}`,
207
+ invocationId: event.invocationId,
208
+ runId: event.runId,
209
+ sessionId: event.sessionId,
210
+ turnId: event.turnId,
211
+ ts: event.ts,
212
+ partial: false,
213
+ role: 'tool',
214
+ author: 'tool',
215
+ origin: event.origin ?? 'provider',
216
+ modelVisibility: event.modelVisibility ?? 'visible',
217
+ content: {
218
+ kind: 'function_response',
219
+ id: call.id,
220
+ name: call.name,
221
+ result: {
222
+ kind: 'text',
223
+ text: `outcome_unknown: ${call.name} was dispatched, but no durable result was recorded. Its effect may have happened. Inspect current state before deciding whether to repeat it.`,
224
+ uncertainOutcome: { code: 'outcome_unknown', retrySafe: false },
225
+ },
226
+ isError: true,
227
+ },
228
+ refs: {
229
+ operationId: outcome.operationId,
230
+ toolCallId: call.id,
231
+ ...(event.refs?.parentToolCallId ? { parentToolCallId: event.refs.parentToolCallId } : {}),
232
+ ...(event.refs?.parentOperationId
233
+ ? { parentOperationId: event.refs.parentOperationId }
234
+ : {}),
235
+ },
236
+ });
237
+ }
238
+ return projected;
239
+ }
55
240
  /**
56
241
  * Resolve the RuntimeEvents whose provider-owned reasoning may cross the
57
242
  * current provider boundary.
@@ -141,7 +326,7 @@ export function estimateRuntimeEventChars(event) {
141
326
  // history-compact gate drops a model-visible event (#4804).
142
327
  if (content.kind === 'text') {
143
328
  for (const quote of content.quotes ?? []) {
144
- total += quote.text.length + (quote.label?.length ?? 0);
329
+ total += formatQuoteRefs([quote]).length;
145
330
  }
146
331
  for (const attachment of content.attachments ?? []) {
147
332
  // Weight the block the projection actually emits, not the display
@@ -801,6 +986,7 @@ function formatQuoteRefs(quotes) {
801
986
  .map((q) => {
802
987
  const attributes = [
803
988
  q.label === undefined ? undefined : `label="${quoteAttribute(q.label)}"`,
989
+ q.comment === undefined ? undefined : `comment="${quoteAttribute(q.comment)}"`,
804
990
  q.sourceSessionId === undefined
805
991
  ? undefined
806
992
  : `source_session="${quoteAttribute(q.sourceSessionId)}"`,
@@ -808,10 +994,22 @@ function formatQuoteRefs(quotes) {
808
994
  q.sourceTruncated === undefined ? undefined : `truncated="${q.sourceTruncated}"`,
809
995
  ].filter((attribute) => attribute !== undefined);
810
996
  const opening = attributes.length > 0 ? `<quoted_excerpt ${attributes.join(' ')}>` : '<quoted_excerpt>';
811
- return `${opening}\n${q.text}\n</quoted_excerpt>`;
997
+ // A literal closing tag inside the excerpt would end the block early
998
+ // and let the text that follows open a second, forged excerpt — one
999
+ // whose comment attribute reads as the user's own words. The body is
1000
+ // otherwise verbatim, so only the tag boundary itself is neutralised.
1001
+ const body = q.text.replace(/<(\/?)quoted_excerpt/gi, '\\u003c$1quoted_excerpt');
1002
+ return `${opening}\n${body}\n</quoted_excerpt>`;
812
1003
  })
813
1004
  .join('\n');
814
1005
  }
1006
+ /**
1007
+ * One escaping rule for every attribute on a projected tag. A quote inside a
1008
+ * double-quoted attribute would end the value early, and a newline would put
1009
+ * the opening tag's boundary where a reader expects prose, so both are folded.
1010
+ */
815
1011
  function quoteAttribute(value) {
816
- return value.replace(/["<&>]/g, (character) => character === '"' ? "'" : `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`);
1012
+ return value
1013
+ .replace(/["<&>]/g, (character) => character === '"' ? "'" : `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`)
1014
+ .replace(/\s+/g, ' ');
817
1015
  }
@@ -0,0 +1,55 @@
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 { buildConnector } from 'undici';
20
+ import { Socket } from 'node:net';
21
+ /** Unlike Node's socket signal option, release the listener on socket close. */
22
+ export function abortSocket(signal, socket) {
23
+ const abort = () => socket.destroy(Object.assign(new Error('The operation was aborted', { cause: signal.reason }), {
24
+ name: 'AbortError',
25
+ code: 'ABORT_ERR',
26
+ }));
27
+ const dispose = () => {
28
+ signal.removeEventListener('abort', abort);
29
+ socket.off('close', dispose);
30
+ };
31
+ socket.once('close', dispose);
32
+ signal.addEventListener('abort', abort, { once: true });
33
+ if (signal.aborted)
34
+ abort();
35
+ return dispose;
36
+ }
37
+ /** Keep Undici's timeout and TLS session cache; own only the pending socket. */
38
+ export function buildAbortableConnector(signal, options = {}) {
39
+ return withSocketCancellation(buildConnector(options), signal);
40
+ }
41
+ export function withSocketCancellation(connect, signal) {
42
+ return (options, callback) => {
43
+ let dispose = () => { };
44
+ // Undici returns the socket immediately, although its TS signature is void.
45
+ // Regression coverage exercises this boundary with real TCP/TLS sockets.
46
+ const socket = connect(options, (...args) => {
47
+ dispose();
48
+ callback(...args);
49
+ });
50
+ // ProxyAgent's outer CONNECT connector is async; its upgraded tunnel is
51
+ // owned separately by the proxy pool's upgrade handler.
52
+ if (socket instanceof Socket)
53
+ dispose = abortSocket(signal, socket);
54
+ };
55
+ }
@@ -16,19 +16,41 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { Agent, ProxyAgent, buildConnector } from 'undici';
19
+ import { Agent, Pool, ProxyAgent } from 'undici';
20
20
  import { SocksClient } from 'socks';
21
- import { isIP } from 'node:net';
22
- import { connect as tlsConnect } from 'node:tls';
21
+ import { Socket } from 'node:net';
22
+ import { once } from 'node:events';
23
23
  import { buildProxyUrl } from './proxy-parser.js';
24
- export function buildProxyDispatcher(proxy) {
24
+ import { abortSocket, buildAbortableConnector, withSocketCancellation, } from './abortable-connector.js';
25
+ export function buildProxyDispatcher(proxy, signal) {
25
26
  if (proxy.type === 'socks5')
26
- return buildSocks5Dispatcher(proxy);
27
- return new ProxyAgent(buildProxyUrl(proxy));
27
+ return buildSocks5Dispatcher(proxy, signal);
28
+ const factory = (origin, options) => {
29
+ const poolOptions = options;
30
+ return new Pool(origin, {
31
+ ...poolOptions,
32
+ connect: typeof poolOptions.connect === 'function'
33
+ ? withSocketCancellation(poolOptions.connect, signal)
34
+ : buildAbortableConnector(signal, poolOptions.connect ?? {}),
35
+ });
36
+ };
37
+ return new ProxyAgent({
38
+ uri: buildProxyUrl(proxy),
39
+ factory,
40
+ clientFactory: (origin, options) => factory(origin, options).compose((dispatch) => (options, handler) => {
41
+ const onUpgrade = handler.onRequestUpgrade;
42
+ // CONNECT transfers the tunnel out of the proxy pool before target TLS
43
+ // settles. Keep that socket cancellable, but never retain a closed one.
44
+ handler.onRequestUpgrade = (controller, status, headers, socket) => {
45
+ abortSocket(signal, socket);
46
+ onUpgrade?.call(handler, controller, status, headers, socket);
47
+ };
48
+ return dispatch(options, handler);
49
+ }),
50
+ });
28
51
  }
29
- function buildSocks5Dispatcher(proxy) {
30
- const connector = buildConnector({ allowH2: false });
31
- void connector;
52
+ function buildSocks5Dispatcher(proxy, signal) {
53
+ const connector = buildAbortableConnector(signal, { allowH2: false });
32
54
  return new Agent({
33
55
  connect: (opts, callback) => {
34
56
  const connectionOptions = opts;
@@ -40,36 +62,13 @@ function buildSocks5Dispatcher(proxy) {
40
62
  const port = typeof connectionOptions.port === 'number'
41
63
  ? connectionOptions.port
42
64
  : Number(connectionOptions.port) || (connectionOptions.protocol === 'https:' ? 443 : 80);
43
- SocksClient.createConnection({
44
- proxy: {
45
- host: proxy.host,
46
- port: proxy.port,
47
- type: 5,
48
- userId: proxy.username,
49
- password: proxy.password,
50
- },
51
- command: 'connect',
52
- destination: { host, port },
53
- })
54
- .then(({ socket }) => {
65
+ connectSocksProxy(proxy, host, port, signal)
66
+ .then((socket) => {
55
67
  socket.setKeepAlive(true, 60_000);
56
68
  if (connectionOptions.protocol === 'https:') {
57
- const servername = connectionOptions.servername ?? (isIP(host) ? undefined : host);
58
- const tlsSocket = tlsConnect({
59
- ...opts,
60
- servername,
61
- host,
62
- port,
63
- socket,
64
- });
65
- tlsSocket.once('error', (error) => {
66
- socket.destroy();
67
- callback(error, null);
68
- });
69
- tlsSocket.once('secureConnect', () => {
70
- tlsSocket.setKeepAlive(true, 60_000);
71
- callback(null, tlsSocket);
72
- });
69
+ // Use Undici's bounded, single-callback TLS connector for the
70
+ // tunnel too, rather than leaving a custom handshake unowned.
71
+ connector({ ...opts, httpSocket: socket }, callback);
73
72
  return;
74
73
  }
75
74
  callback(null, socket);
@@ -78,3 +77,39 @@ function buildSocks5Dispatcher(proxy) {
78
77
  },
79
78
  });
80
79
  }
80
+ async function connectSocksProxy(proxy, host, port, signal) {
81
+ // SOCKS creates an unabortable Socket internally. Supply our own connected
82
+ // socket so close can interrupt TCP setup, SOCKS negotiation and the tunnel.
83
+ const socket = new Socket();
84
+ const onTimeout = () => socket.destroy(new Error('SOCKS proxy connection timed out'));
85
+ // Bound only TCP setup; SocksClient owns the negotiation deadline.
86
+ socket.setTimeout(30_000, onTimeout);
87
+ try {
88
+ socket.connect({ host: proxy.host, port: proxy.port });
89
+ abortSocket(signal, socket);
90
+ await once(socket, 'connect');
91
+ socket.setTimeout(0);
92
+ socket.off('timeout', onTimeout);
93
+ await SocksClient.createConnection({
94
+ proxy: {
95
+ host: proxy.host,
96
+ port: proxy.port,
97
+ type: 5,
98
+ userId: proxy.username,
99
+ password: proxy.password,
100
+ },
101
+ command: 'connect',
102
+ destination: { host, port },
103
+ existing_socket: socket,
104
+ });
105
+ return socket;
106
+ }
107
+ catch (error) {
108
+ socket.destroy();
109
+ throw error;
110
+ }
111
+ finally {
112
+ socket.setTimeout(0);
113
+ socket.off('timeout', onTimeout);
114
+ }
115
+ }
@@ -29,8 +29,8 @@ export async function testProxyConnection(input = {}, storedProxy) {
29
29
  return { ok: false, latencyMs: 0, error: 'Proxy disabled' };
30
30
  if (!proxy.host || !proxy.port)
31
31
  return { ok: false, latencyMs: 0, error: 'Proxy host/port required' };
32
- const dispatcher = buildProxyDispatcher(proxy);
33
32
  const controller = new AbortController();
33
+ const dispatcher = buildProxyDispatcher(proxy, controller.signal);
34
34
  let timedOut = false;
35
35
  const disposeDispatcher = async (force = false) => {
36
36
  const disposable = dispatcher;
@@ -19,6 +19,7 @@
19
19
  import { Agent, fetch as undiciFetch } from 'undici';
20
20
  import { matchesBypassList } from './bypass-matcher.js';
21
21
  import { buildProxyDispatcher } from './proxy-dispatcher.js';
22
+ import { buildAbortableConnector } from './abortable-connector.js';
22
23
  export const FETCH_PROXY_SNAPSHOT = Symbol.for('maka.fetch.proxy-snapshot');
23
24
  export function inheritFetchProxySnapshot(fetch, source) {
24
25
  const descriptor = Object.getOwnPropertyDescriptor(source, FETCH_PROXY_SNAPSHOT);
@@ -34,7 +35,10 @@ export function createProxiedFetchTransport(proxy) {
34
35
  const proxySnapshot = proxy?.enabled
35
36
  ? { ...proxy, bypassList: [...proxy.bypassList] }
36
37
  : null;
37
- const directDispatcher = new Agent();
38
+ // Dispatchers do not own sockets until their connectors call back. Abort
39
+ // direct and proxy connection establishment too, including TLS handshakes.
40
+ const connections = new AbortController();
41
+ const directDispatcher = new Agent({ connect: buildAbortableConnector(connections.signal) });
38
42
  let proxyDispatcher;
39
43
  let closePromise;
40
44
  let closed = false;
@@ -44,7 +48,7 @@ export function createProxiedFetchTransport(proxy) {
44
48
  const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
45
49
  const useProxy = proxySnapshot !== null && !matchesBypassList(new URL(url).hostname, proxySnapshot.bypassList);
46
50
  if (useProxy)
47
- proxyDispatcher ??= buildProxyDispatcher(proxySnapshot);
51
+ proxyDispatcher ??= buildProxyDispatcher(proxySnapshot, connections.signal);
48
52
  return (await undiciFetch(input, {
49
53
  ...init,
50
54
  dispatcher: useProxy ? proxyDispatcher : directDispatcher,
@@ -58,6 +62,7 @@ export function createProxiedFetchTransport(proxy) {
58
62
  if (closePromise)
59
63
  return closePromise;
60
64
  closed = true;
65
+ connections.abort(new Error('Connection effect fetch transport closed'));
61
66
  closePromise = Promise.all([
62
67
  directDispatcher
63
68
  .destroy(new Error('Connection effect fetch transport closed'))
@@ -17,6 +17,7 @@
17
17
  * under the License.
18
18
  */
19
19
  import { HistoryCompactSummarizerError } from './history-compact-error.js';
20
+ import { nonEmpty } from './context-budget-helpers.js';
20
21
  import { canContinueHistoryCompactCheckpointForModel, historyCompactCheckpointToModelMessage, isProviderHistoryCompactCheckpoint, } from './history-compact-checkpoint.js';
21
22
  import { admitProviderReasoningReplayItems, buildRuntimeEventModelReplayPlan, buildRuntimeEventReplayTimeline, compatibleProviderReasoningReplayEventIds, } from './model-history.js';
22
23
  import { withProviderStreamTracking } from './provider-request-telemetry.js';
@@ -275,9 +276,6 @@ function isOpenAiCompactionPart(value) {
275
276
  function isStreamErrorPart(value) {
276
277
  return Boolean(value && typeof value === 'object' && value.type === 'error');
277
278
  }
278
- function nonEmpty(value) {
279
- return typeof value === 'string' && value.length > 0;
280
- }
281
279
  async function loadAiSdkModule() {
282
280
  const ai = await import('ai').catch((err) => {
283
281
  throw new Error(`Failed to load 'ai' package for history compaction. Run \`npm install ai\`. Inner: ${err.message}`);