maka-agent 0.2.0-dev.51.20260925 → 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 (97) hide show
  1. package/dist/acp/goal-plan-operations.js +142 -0
  2. package/dist/acp/goal-plan-routes.js +33 -0
  3. package/dist/acp/maka-acp-agent.js +41 -1
  4. package/dist/acp/session-domain-observation.js +185 -0
  5. package/dist/acp/session-event-mapper.js +1 -1
  6. package/dist/acp/session-registry.js +417 -9
  7. package/dist/acp/tool-event-mapper.js +36 -3
  8. package/dist/activation-command.js +11 -3
  9. package/dist/pi-tui-mcp-status.js +73 -5
  10. package/dist/pi-tui-runner.js +1 -1
  11. package/dist/runtime-host-run-command.js +39 -6
  12. package/dist/runtime-host-run-mcp.js +161 -0
  13. package/dist/runtime-host-session-channel.js +4 -0
  14. package/dist/runtime-host-session-driver.js +22 -2
  15. package/dist/tui-copy-catalog.js +6 -0
  16. package/dist/tui-mcp-control.js +11 -2
  17. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  18. package/node_modules/@maka/core/dist/attachments.js +7 -0
  19. package/node_modules/@maka/core/dist/events.js +11 -0
  20. package/node_modules/@maka/core/dist/openai-urls.js +51 -0
  21. package/node_modules/@maka/core/dist/provider-registry.js +11 -2
  22. package/node_modules/@maka/core/dist/relative-time.js +1 -9
  23. package/node_modules/@maka/core/dist/turn-origin.js +6 -0
  24. package/node_modules/@maka/core/package.json +1 -0
  25. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +1 -5
  26. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +90 -32
  27. package/node_modules/@maka/runtime/dist/bots/proxied-fetch.js +5 -4
  28. package/node_modules/@maka/runtime/dist/builtin-tools.js +2 -2
  29. package/node_modules/@maka/runtime/dist/computer-use-tools.js +136 -100
  30. package/node_modules/@maka/runtime/dist/context-budget-helpers.js +4 -0
  31. package/node_modules/@maka/runtime/dist/conversation-copy.js +51 -205
  32. package/node_modules/@maka/runtime/dist/edit-replace.js +7 -7
  33. package/node_modules/@maka/runtime/dist/filesystem-executor.js +7 -22
  34. package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +17 -28
  35. package/node_modules/@maka/runtime/dist/filesystem-worker/protocol.js +7 -4
  36. package/node_modules/@maka/runtime/dist/format-json.js +39 -0
  37. package/node_modules/@maka/runtime/dist/glob-search.js +18 -5
  38. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +1 -6
  39. package/node_modules/@maka/runtime/dist/image-file.js +22 -14
  40. package/node_modules/@maka/runtime/dist/model-adapter.js +18 -2
  41. package/node_modules/@maka/runtime/dist/model-factory.js +27 -1
  42. package/node_modules/@maka/runtime/dist/model-fetcher.js +2 -1
  43. package/node_modules/@maka/runtime/dist/model-history.js +201 -3
  44. package/node_modules/@maka/runtime/dist/model-runtime.js +5 -3
  45. package/node_modules/@maka/runtime/dist/network/abortable-connector.js +55 -0
  46. package/node_modules/@maka/runtime/dist/network/proxy-dispatcher.js +72 -37
  47. package/node_modules/@maka/runtime/dist/network/proxy-test.js +1 -1
  48. package/node_modules/@maka/runtime/dist/network/scoped-fetch-transport.js +7 -2
  49. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +1 -3
  50. package/node_modules/@maka/runtime/dist/provider-error-classification.js +36 -8
  51. package/node_modules/@maka/runtime/dist/provider-urls.js +1 -18
  52. package/node_modules/@maka/runtime/dist/recovery-resolver.js +1 -91
  53. package/node_modules/@maka/runtime/dist/runtime-kernel.js +44 -0
  54. package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +27 -2
  55. package/node_modules/@maka/runtime/dist/session-manager.js +54 -58
  56. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +84 -2
  57. package/node_modules/@maka/runtime/dist/test-connection.js +2 -2
  58. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +79 -57
  59. package/node_modules/@maka/runtime/dist/workspace-executor.js +5 -6
  60. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +27 -6
  61. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +4 -1
  62. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +9 -9
  63. package/node_modules/@maka/runtime-host/dist/client/session-catalog-summary.js +9 -1
  64. package/node_modules/@maka/runtime-host/dist/protocol/index.js +14 -1
  65. package/node_modules/@maka/runtime-host/dist/protocol/scheduled-task.js +8 -1
  66. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog-change.js +24 -6
  67. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +28 -6
  68. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +12 -2
  69. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +10 -7
  70. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +26 -5
  71. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +20 -16
  72. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +18 -1
  73. package/node_modules/@maka/runtime-host/dist/server/host-change-feed.js +15 -22
  74. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +2 -0
  75. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +30 -3
  76. package/node_modules/@maka/runtime-host/dist/server/interactive-turn-coordinator.js +4 -1
  77. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +4 -2
  78. package/node_modules/@maka/runtime-host/dist/server/operation-dispatcher.js +4 -0
  79. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +7 -6
  80. package/node_modules/@maka/runtime-host/dist/server/safe-boundary-resume-policy.js +27 -0
  81. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +5 -3
  82. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +23 -5
  83. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +11 -141
  84. package/node_modules/@maka/runtime-host/dist/server/session-revision-graph-references.js +46 -75
  85. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +18 -2
  86. package/node_modules/@maka/runtime-host/dist/server/workhub-result-coordinator.js +33 -3
  87. package/node_modules/@maka/runtime-host/dist/transport/framed-byte-stream-transport.js +39 -5
  88. package/node_modules/@maka/storage/dist/agent-run-store-contract.js +7 -1
  89. package/node_modules/@maka/storage/dist/artifact-store.js +1 -5
  90. package/node_modules/@maka/storage/dist/artifact-stores.js +0 -3
  91. package/node_modules/@maka/storage/dist/atomic-file-write.js +1 -0
  92. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +107 -57
  93. package/node_modules/@maka/storage/dist/codex-session-adapter.js +227 -19
  94. package/node_modules/@maka/storage/dist/external-session-importer.js +1 -1
  95. package/node_modules/@maka/storage/dist/mcp-config-store.js +22 -3
  96. package/node_modules/@maka/storage/dist/settings-store.js +281 -13
  97. package/package.json +1 -1
@@ -22,16 +22,24 @@ import { globIterate } from 'glob';
22
22
  export async function globFiles(input) {
23
23
  let failure;
24
24
  const directories = new Set([resolve(input.cwd)]);
25
+ const files = [];
26
+ const limit = input.limit ?? 200;
27
+ let probingOverflow = false;
28
+ let probeIncomplete = false;
25
29
  function record(error, path) {
26
30
  // Speculative literal components may miss. A directory already admitted by
27
31
  // cwd, stat, or enumeration disappearing instead makes this walk incomplete.
28
32
  if (directories.has(resolve(path)) || (error.code !== 'ENOENT' && error.code !== 'ENOTDIR')) {
29
- failure ??= error;
33
+ if (probingOverflow)
34
+ probeIncomplete = true;
35
+ else
36
+ failure ??= error;
30
37
  }
31
38
  }
32
- const files = [];
39
+ let truncated = false;
33
40
  for await (const file of globIterate(input.pattern, {
34
41
  cwd: input.cwd,
42
+ signal: input.abortSignal,
35
43
  ignore: { childrenIgnored: (entry) => entry.isSymbolicLink() },
36
44
  fs: {
37
45
  readdir(path, options, callback) {
@@ -62,13 +70,18 @@ export async function globFiles(input) {
62
70
  },
63
71
  },
64
72
  })) {
73
+ if (files.length >= limit) {
74
+ // One match past the cap is the only proof the pattern had more to give.
75
+ truncated = true;
76
+ break;
77
+ }
65
78
  if (failure)
66
79
  throw failure;
67
80
  files.push(file);
68
- if (files.length >= (input.limit ?? 200))
69
- break;
81
+ if (files.length >= limit)
82
+ probingOverflow = true;
70
83
  }
71
84
  if (failure)
72
85
  throw failure;
73
- return { files };
86
+ return { files, truncated: truncated || probeIncomplete };
74
87
  }
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import { createHash } from 'node:crypto';
20
20
  import { Buffer } from 'node:buffer';
21
+ import { nonEmpty, sha256 } from './context-budget-helpers.js';
21
22
  import { stableStringify } from './request-shape.js';
22
23
  import { findCheckpointSummaryDefect, SECTIONED_SUMMARY_FORMAT, } from './history-compact-summary-validation.js';
23
24
  // v3: coverage identity and the source digest stay pinned on the RAW ledger
@@ -515,12 +516,6 @@ function effectiveDigestEvent(event) {
515
516
  }
516
517
  return { ...event, content: { ...identity, result } };
517
518
  }
518
- function sha256(value) {
519
- return createHash('sha256').update(value).digest('hex');
520
- }
521
- function nonEmpty(value) {
522
- return typeof value === 'string' && value.length > 0;
523
- }
524
519
  function validHistoryCompactProviderState(value) {
525
520
  if (!value || typeof value !== 'object')
526
521
  return false;
@@ -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
@@ -27,7 +27,7 @@ import { createOpenAI } from '@ai-sdk/openai';
27
27
  import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
28
28
  import { isJSONArray, } from '@ai-sdk/provider';
29
29
  import { lookupModelMetadata } from '@maka/core/model-metadata';
30
- import { modelOverride, resolveThinkingLevel, supportsCustomFastServiceTier, thinkingOptionsForModel, thinkingVariantsForConnection, } from '@maka/core/model-thinking';
30
+ import { modelOverride, resolveThinkingLevel, THINKING_LEVELS, supportsCustomFastServiceTier, thinkingOptionsForModel, thinkingVariantsForConnection, } from '@maka/core/model-thinking';
31
31
  import { createOpenAiChatReasoningTransport, createOpenAiChatReasoningTransportState, } from './openai-chat-reasoning-transport.js';
32
32
  import { openResponsesUrl } from './provider-urls.js';
33
33
  import { createOpenResponsesCompatibilityFinalizer } from './open-responses-compatibility.js';
@@ -349,6 +349,32 @@ function claudeThinkingMode(providerType, modelId, thinkingOptions) {
349
349
  ? 'adaptive'
350
350
  : 'legacy';
351
351
  }
352
+ /**
353
+ * The level that asks this model for the least reasoning it accepts, for
354
+ * callers that want none but cannot rely on `'off'` surviving
355
+ * `resolveThinkingLevel`.
356
+ *
357
+ * `'off'` is used when the model declares it. It is also used when the model
358
+ * declares no levels, or is a Claude model on Anthropic Messages, because on
359
+ * those paths an omitted parameter already means no extended thinking, while
360
+ * the lowest effort would switch adaptive thinking on. That holds for Claude,
361
+ * not for every Anthropic Messages route: Kimi's K3 and kimi-for-coding think
362
+ * by default when no level is sent.
363
+ *
364
+ * Everywhere else a dropped `'off'` omits the effort parameter, and the
365
+ * provider then runs its default reasoning (medium on GPT-5, GPT-6 and o3,
366
+ * dynamic on Gemini 3). So this returns the model's lowest declared level
367
+ * instead, which the wire builders send explicitly.
368
+ */
369
+ export function leastReasoningThinkingLevel(connection, modelId, runtime = resolveModelRuntime(connection, modelId)) {
370
+ const variants = thinkingVariantsForConnection(connection, modelId);
371
+ if (variants.length === 0 || variants.includes('off'))
372
+ return 'off';
373
+ if (runtime.wire === 'anthropic-messages' && claudeFamilyId(modelId).startsWith('claude-')) {
374
+ return 'off';
375
+ }
376
+ return THINKING_LEVELS.find((level) => variants.includes(level)) ?? 'off';
377
+ }
352
378
  export function buildProviderOptions(connection, modelId, thinkingLevel, runtime = resolveModelRuntime(connection, modelId)) {
353
379
  return withParallelToolCallOptions(connection, modelId, buildThinkingProviderOptions(connection, modelId, thinkingLevel, runtime), runtime);
354
380
  }
@@ -16,6 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { openAiBaseUrl } from '@maka/core/openai-urls';
19
20
  import { PROVIDER_REGISTRY, providerFallbackModelIds, effectiveBaseUrl, isModelModality, providerAuthSupportsApiKey, } from '@maka/core/llm-connections';
20
21
  import { CONNECTION_CATALOG_MAX_MODELS_PER_CONNECTION, CONNECTION_MODEL_ID_MAX_LENGTH, decodeConnectionModels, } from '@maka/core/runtime-policy';
21
22
  import { anthropicV1Url, googleApiUrl } from './provider-urls.js';
@@ -107,7 +108,7 @@ async function fetchProviderModelsStrict(connection, apiKey, fetchFn) {
107
108
  }
108
109
  case 'openai':
109
110
  case 'openai-compatible': {
110
- const r = await fetchForConnectionEffect(fetchFn, modelListUrl(baseUrl, discovery.path, discovery.query), {
111
+ const r = await fetchForConnectionEffect(fetchFn, modelListUrl(openAiBaseUrl(baseUrl), discovery.path, discovery.query), {
111
112
  headers: {
112
113
  'content-type': 'application/json',
113
114
  ...(apiKey &&
@@ -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
  }
@@ -20,7 +20,7 @@ import { PROVIDER_REGISTRY, effectiveBaseUrl, } from '@maka/core/llm-connections
20
20
  import { lookupModelMetadata, lookupModelRuntimeOverride, openAiAdapterApiProtocol, } from '@maka/core/model-metadata';
21
21
  import { isRetiredProvider } from '@maka/core/provider-registry';
22
22
  import { declaredModelApiProtocol, modelOverride, } from '@maka/core/model-thinking';
23
- import { anthropicV1BaseUrl, googleV1BetaBaseUrl, openAiResponsesBaseUrl, } from './provider-urls.js';
23
+ import { anthropicV1BaseUrl, googleV1BetaBaseUrl, openAiResponsesBaseUrl, openAiChatBaseUrl, } from './provider-urls.js';
24
24
  import { resolveApplyPatchProfile } from './apply-patch-profile.js';
25
25
  export function resolveModelRuntime(connection, modelId) {
26
26
  // Model metadata cannot reactivate a retired provider.
@@ -57,10 +57,12 @@ export function resolveModelRuntime(connection, modelId) {
57
57
  : adapter.kind === 'google' && adapter.normalizeBaseUrl !== false
58
58
  ? googleV1BetaBaseUrl(resolvedBaseUrl)
59
59
  : adapter.kind === 'openai-compatible' && adapter.normalizeBaseUrl
60
- ? anthropicV1BaseUrl(resolvedBaseUrl)
60
+ ? anthropicV1BaseUrl(openAiChatBaseUrl(resolvedBaseUrl))
61
61
  : wire === 'openai-responses' && resolvedBaseUrl
62
62
  ? openAiResponsesBaseUrl(resolvedBaseUrl)
63
- : resolvedBaseUrl;
63
+ : wire === 'openai-chat' && resolvedBaseUrl
64
+ ? openAiChatBaseUrl(resolvedBaseUrl)
65
+ : resolvedBaseUrl;
64
66
  const parallelToolCalls = resolveParallelToolCalls(connection, modelId, baseAdapter);
65
67
  return {
66
68
  ...call,
@@ -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
+ }