maka-agent 0.2.0-dev.48.20260923 → 0.2.0-dev.49.20260924

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 (78) hide show
  1. package/dist/acp/session-event-mapper.js +1 -4
  2. package/dist/onboarding-catalog.js +20 -4
  3. package/dist/pi-transcript.js +0 -8
  4. package/dist/pi-tui-pickers.js +1 -1
  5. package/dist/pi-tui-runner.js +6 -4
  6. package/dist/runtime-host-onboarding.js +5 -3
  7. package/dist/runtime-host-session-channel.js +9 -3
  8. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  9. package/node_modules/@maka/core/dist/events.js +13 -0
  10. package/node_modules/@maka/core/dist/llm-connections.js +2 -5
  11. package/node_modules/@maka/core/dist/model-facts.js +2 -4
  12. package/node_modules/@maka/core/dist/model-metadata.generated.js +345 -248
  13. package/node_modules/@maka/core/dist/model-thinking.js +17 -17
  14. package/node_modules/@maka/core/dist/model-web-search.js +7 -9
  15. package/node_modules/@maka/core/dist/models-dev-projection.js +1 -1
  16. package/node_modules/@maka/core/dist/onboarding.js +1 -4
  17. package/node_modules/@maka/core/dist/provider-registry.js +60 -86
  18. package/node_modules/@maka/core/dist/runtime-event.js +2 -2
  19. package/node_modules/@maka/core/dist/runtime-policy/connection-catalog-codec.js +28 -16
  20. package/node_modules/@maka/core/dist/runtime-policy.js +1 -1
  21. package/node_modules/@maka/core/dist/session.js +23 -9
  22. package/node_modules/@maka/core/dist/transcript-search.js +1 -0
  23. package/node_modules/@maka/core/dist/usage-stats/types.js +1 -0
  24. package/node_modules/@maka/eval/dist/harbor-maka-subject.js +3 -0
  25. package/node_modules/@maka/eval/dist/maka-subject.js +8 -1
  26. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +1 -11
  27. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +2 -12
  28. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +3 -71
  29. package/node_modules/@maka/runtime/dist/conversation-copy.js +2 -2
  30. package/node_modules/@maka/runtime/dist/local-web-fetch.js +23 -11
  31. package/node_modules/@maka/runtime/dist/model-adapter.js +10 -5
  32. package/node_modules/@maka/runtime/dist/model-factory.js +33 -30
  33. package/node_modules/@maka/runtime/dist/model-fetcher.js +4 -1
  34. package/node_modules/@maka/runtime/dist/model-runtime.js +3 -9
  35. package/node_modules/@maka/runtime/dist/read-page.js +11 -8
  36. package/node_modules/@maka/runtime/dist/recovery-resolver.js +47 -20
  37. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +1 -0
  38. package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +39 -8
  39. package/node_modules/@maka/runtime/dist/session-manager.js +12 -2
  40. package/node_modules/@maka/runtime/dist/telemetry/model-pricing.generated.js +141 -134
  41. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +3 -3
  42. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +7 -6
  43. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +28 -62
  44. package/node_modules/@maka/runtime-host/dist/client/hosted-execution-target.js +7 -1
  45. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +3 -0
  46. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +6 -3
  47. package/node_modules/@maka/runtime-host/dist/protocol/index.js +5 -1
  48. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +4 -1
  49. package/node_modules/@maka/runtime-host/dist/protocol/prompt-suggestions.js +61 -0
  50. package/node_modules/@maka/runtime-host/dist/protocol/runtime-policy.js +4 -1
  51. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +2 -1
  52. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +3 -0
  53. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +54 -6
  54. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +38 -2
  55. package/node_modules/@maka/runtime-host/dist/server/generated-text.js +39 -0
  56. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-tool-profile.js +8 -0
  57. package/node_modules/@maka/runtime-host/dist/server/prompt-suggestion.js +179 -0
  58. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +2 -2
  59. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +48 -16
  60. package/node_modules/@maka/runtime-host/dist/server/session-title.js +3 -16
  61. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +38 -3
  62. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +3 -0
  63. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +6 -13
  64. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +35 -11
  65. package/node_modules/@maka/storage/dist/config-transfer.js +14 -8
  66. package/node_modules/@maka/storage/dist/execution-stores.js +4 -3
  67. package/node_modules/@maka/storage/dist/interaction-store.js +13 -0
  68. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +28 -17
  69. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +9 -3
  70. package/node_modules/@maka/storage/dist/runtime-policy/legacy-custom-connection.js +65 -0
  71. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +10 -5
  72. package/node_modules/@maka/storage/dist/session-bundle-policy.js +11 -0
  73. package/node_modules/@maka/storage/dist/session-store.js +29 -6
  74. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +3 -0
  75. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +125 -7
  76. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +5 -3
  77. package/node_modules/@maka/storage/dist/usage-screen.js +138 -108
  78. package/package.json +1 -1
@@ -27,11 +27,11 @@ 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 { resolveThinkingLevel, supportsRelayFastServiceTier, thinkingOptionsForModel, thinkingVariantsForConnection, } from '@maka/core/model-thinking';
30
+ import { modelOverride, resolveThinkingLevel, 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';
34
- import { resolveModelRuntime, runtimeProviderName, } from './model-runtime.js';
34
+ import { resolveModelRuntime } from './model-runtime.js';
35
35
  import { openAiCodexHeaders } from './subscription-auth.js';
36
36
  import { createRequestCustomizationFetch } from './request-customization-fetch.js';
37
37
  import { createStreamUsageFallbackFetch } from './stream-usage-fallback-fetch.js';
@@ -65,7 +65,7 @@ export function getAIModel(input) {
65
65
  })
66
66
  : requestFetch;
67
67
  return createOpenResponses({
68
- name: runtimeProviderName(adapter, connection),
68
+ name: connection.providerType,
69
69
  apiKey,
70
70
  url: openResponsesUrl(baseURL),
71
71
  fetch: responsesFetch,
@@ -134,7 +134,7 @@ export function getAIModel(input) {
134
134
  ? composeRequestTransforms(reasoningTransport.transformRequestBody, replayAssistantReasoning('reasoning', true))
135
135
  : reasoningTransport.transformRequestBody;
136
136
  const model = createOpenAICompatible({
137
- name: runtimeProviderName(adapter, connection),
137
+ name: connection.providerType,
138
138
  apiKey,
139
139
  baseURL,
140
140
  // Ask every Chat Completions server for stream usage unless the
@@ -356,6 +356,21 @@ function buildThinkingProviderOptions(connection, modelId, thinkingLevel, runtim
356
356
  const thinkingOptions = thinkingOptionsForModel(connection.providerType, modelId);
357
357
  const level = resolveThinkingLevel(connection, modelId, thinkingLevel);
358
358
  switch (connection.providerType) {
359
+ case 'custom':
360
+ // Messages needs a thinking mode beside the effort. A declared level is
361
+ // the user's statement the gateway thinks, so it always gets adaptive.
362
+ // Messages has no `minimal` effort; `low` is its lowest.
363
+ if (runtime.wire === 'anthropic-messages') {
364
+ return level
365
+ ? {
366
+ anthropic: {
367
+ thinking: { type: 'adaptive', display: 'summarized' },
368
+ effort: level === 'minimal' ? 'low' : level,
369
+ },
370
+ }
371
+ : {};
372
+ }
373
+ return buildFamilyWire(connection, modelId, level, thinkingOptions, thinkingLevel, runtime);
359
374
  case 'kimi-coding-plan': {
360
375
  // Kimi's coding route has no off wire. Check the raw argument, not the
361
376
  // normalized level: the entry gate above drops unsupported levels to
@@ -541,7 +556,7 @@ function withParallelToolCallOptions(connection, modelId, options, runtime) {
541
556
  optionKey = 'parallelToolCalls';
542
557
  }
543
558
  else if (runtime.adapter.kind === 'openai-compatible') {
544
- providerKey = openAiCompatibleProviderOptionsKey(runtime.adapter, connection);
559
+ providerKey = openAiCompatibleProviderOptionsKey(connection);
545
560
  optionKey = 'parallel_tool_calls';
546
561
  }
547
562
  else {
@@ -559,18 +574,12 @@ function withParallelToolCallOptions(connection, modelId, options, runtime) {
559
574
  function buildFamilyWire(connection, modelId, level, thinkingOptions, requestedLevel, runtime) {
560
575
  const { adapter, wire, reasoningReplay } = runtime;
561
576
  const explicitReasoningEffort = level ? (level === 'off' ? 'none' : level) : undefined;
562
- const serviceTier = wire === 'openai-responses' &&
563
- reasoningReplay.kind === 'responses' &&
564
- reasoningReplay.contract.adapter === 'openai' &&
565
- supportsRelayFastServiceTier(connection.providerType, modelId)
566
- ? connection.modelOverrides?.[modelId]?.serviceTier
567
- : undefined;
568
577
  // Provider selection and reasoning continuation are independent. The OpenAI
569
578
  // provider reads its provider-options namespace; the Open Responses provider
570
579
  // consumes a provider-native reasoningEffort through the same namespace,
571
580
  // keyed by the provider name getAIModel passes to createOpenResponses.
572
581
  if (wire === 'openai-responses') {
573
- // Connection-aware: a relay model's declared variants count too.
582
+ // Connection-aware: a custom model's declared variants count too.
574
583
  const reasons = thinkingVariantsForConnection(connection, modelId).length > 0;
575
584
  if (reasoningReplay.contract.adapter === 'open-responses') {
576
585
  // @ai-sdk/open-responses@2.0.34 passes a provider-native reasoningEffort
@@ -579,15 +588,13 @@ function buildFamilyWire(connection, modelId, level, thinkingOptions, requestedL
579
588
  // sends `xhigh` to high, not max). The SDK resolves providerOptions
580
589
  // under the raw provider `name` — no camelCase alias, unlike
581
590
  // openai-compatible — so key by the same name getAIModel passes.
582
- return explicitReasoningEffort || serviceTier
583
- ? {
584
- [runtimeProviderName(adapter, connection)]: {
585
- ...(explicitReasoningEffort ? { reasoningEffort: explicitReasoningEffort } : {}),
586
- ...(serviceTier ? { serviceTier } : {}),
587
- },
588
- }
591
+ return explicitReasoningEffort
592
+ ? { [connection.providerType]: { reasoningEffort: explicitReasoningEffort } }
589
593
  : {};
590
594
  }
595
+ const serviceTier = supportsCustomFastServiceTier(connection, modelId)
596
+ ? modelOverride(connection, modelId)?.serviceTier
597
+ : undefined;
591
598
  const reasoningEffort = explicitReasoningEffort ??
592
599
  (requestedLevel === undefined ? defaultOpenAiReasoningEffort(modelId) : undefined);
593
600
  return {
@@ -612,25 +619,21 @@ function buildFamilyWire(connection, modelId, level, thinkingOptions, requestedL
612
619
  (requestedLevel === undefined ? defaultOpenAiReasoningEffort(modelId) : undefined);
613
620
  if (reasoningEffort) {
614
621
  return {
615
- [openAiCompatibleProviderOptionsKey(adapter, connection)]: { reasoningEffort },
622
+ [openAiCompatibleProviderOptionsKey(connection)]: { reasoningEffort },
616
623
  };
617
624
  }
618
625
  }
619
- if (!explicitReasoningEffort && !serviceTier)
626
+ if (!explicitReasoningEffort)
620
627
  return {};
621
628
  switch (adapter.kind) {
622
629
  case 'openai-compatible':
623
630
  return {
624
- [openAiCompatibleProviderOptionsKey(adapter, connection)]: {
625
- ...(explicitReasoningEffort ? { reasoningEffort: explicitReasoningEffort } : {}),
631
+ [openAiCompatibleProviderOptionsKey(connection)]: {
632
+ reasoningEffort: explicitReasoningEffort,
626
633
  },
627
634
  };
628
635
  case 'openai':
629
- return {
630
- openai: {
631
- ...(explicitReasoningEffort ? { reasoningEffort: explicitReasoningEffort } : {}),
632
- },
633
- };
636
+ return { openai: { reasoningEffort: explicitReasoningEffort } };
634
637
  case 'anthropic':
635
638
  // Anthropic-protocol models declare no `none` effort, so an off
636
639
  // choice only exists where an explicit case wires it.
@@ -667,6 +670,6 @@ function toCamelCase(name) {
667
670
  * A metadata reader keyed by the raw `connection.providerType` would
668
671
  * silently read nothing for dashed providers.
669
672
  */
670
- function openAiCompatibleProviderOptionsKey(adapter, connection) {
671
- return toCamelCase(runtimeProviderName(adapter, connection));
673
+ function openAiCompatibleProviderOptionsKey(connection) {
674
+ return toCamelCase(connection.providerType);
672
675
  }
@@ -86,7 +86,10 @@ async function fetchProviderModelsStrict(connection, apiKey, fetchFn) {
86
86
  // The wire is the Runtime adapter's, not a second field beside it. Only four
87
87
  // adapter kinds reach here: every other one returned above on its own
88
88
  // discovery branch, and both OpenAI-shaped kinds speak the same /models wire.
89
- switch (definition.runtimeAdapter.kind) {
89
+ const listAdapter = (connection.defaultApiProtocol &&
90
+ definition.protocolAdapters?.[connection.defaultApiProtocol]) ||
91
+ definition.runtimeAdapter;
92
+ switch (listAdapter.kind) {
90
93
  case 'anthropic': {
91
94
  const r = await fetchForConnectionEffect(fetchFn, anthropicV1Url(baseUrl, '/models'), {
92
95
  headers: anthropicModelHeaders(apiKey),
@@ -19,7 +19,7 @@
19
19
  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
- import { modelOverride } from '@maka/core/model-thinking';
22
+ import { declaredModelApiProtocol, modelOverride, } from '@maka/core/model-thinking';
23
23
  import { anthropicV1BaseUrl, googleV1BetaBaseUrl, openAiResponsesBaseUrl, } from './provider-urls.js';
24
24
  import { resolveApplyPatchProfile } from './apply-patch-profile.js';
25
25
  export function resolveModelRuntime(connection, modelId) {
@@ -32,7 +32,7 @@ export function resolveModelRuntime(connection, modelId) {
32
32
  if (!override && !defaults) {
33
33
  throw new Error(`Unknown provider type "${connection.providerType}"; cannot resolve model runtime.`);
34
34
  }
35
- const apiProtocol = connection.models?.find((model) => model.id === modelId)?.apiProtocol;
35
+ const apiProtocol = declaredModelApiProtocol(connection, modelId);
36
36
  const baseAdapter = override?.adapter ?? defaults.runtimeAdapter;
37
37
  const calls = adapterCalls(baseAdapter);
38
38
  const preferred = openAiAdapterApiProtocol(modelId, connection.providerType);
@@ -70,7 +70,7 @@ export function resolveModelRuntime(connection, modelId) {
70
70
  replay.contract.adapter === 'open-responses' &&
71
71
  replay.contract.reasoningReplay === 'plaintext-summary'
72
72
  ? {
73
- responsesProviderOptionsKey: runtimeProviderName(adapter, connection),
73
+ responsesProviderOptionsKey: connection.providerType,
74
74
  responsesReplayProfile: connection.slug ?? connection.providerType,
75
75
  }
76
76
  : {}),
@@ -99,12 +99,6 @@ function resolveParallelToolCalls(connection, modelId, adapter) {
99
99
  // they require an explicit model declaration instead of inheriting this.
100
100
  return adapter.kind === 'openai' || adapter.kind === 'openai-codex' ? true : undefined;
101
101
  }
102
- /** Provider identity used to name SDK instances and key their provider options. */
103
- export function runtimeProviderName(adapter, connection) {
104
- return adapter.kind === 'openai-compatible' && adapter.name === 'connection'
105
- ? (connection.slug ?? connection.providerType)
106
- : connection.providerType;
107
- }
108
102
  /** Native OpenAI lanes keep mutable continuation state inside ModelAdapter. */
109
103
  export function modelUsesNativeOpenAiResponses(connection, modelId) {
110
104
  return (connection.providerType === 'openai' &&
@@ -18,7 +18,9 @@
18
18
  */
19
19
  import { createHash } from 'node:crypto';
20
20
  import { z } from 'zod';
21
- export const READ_PAGE_MAX_CHARS = 7_500;
21
+ // Read page size and tool-result prune threshold. 7,500 UTF-8 bytes is about 2K tokens
22
+ // for both English and Chinese; counting characters would let Chinese reach ~3.3K.
23
+ export const READ_PAGE_MAX_BYTES = 7_500;
22
24
  export const READ_DESCRIPTION = 'Read a text file, view a PNG/JPEG/GIF/WebP image, or read a Maka resource returned by a tool. Only path is required. Images are returned as images, without text pagination. Text reads return one bounded page by default; offset and limit select a line range within the response-size cap. If next is non-null, pass its complete object to Read to continue, including partial lines; otherwise the requested range is complete.';
23
25
  export const readParameters = z.object({
24
26
  path: z
@@ -81,7 +83,7 @@ export function resolveReadInput(input) {
81
83
  function digestText(content) {
82
84
  return createHash('sha256').update(content).digest('hex').slice(0, 32);
83
85
  }
84
- export function readPage(content, input, maxChars = READ_PAGE_MAX_CHARS, continuation) {
86
+ export function readPage(content, input, maxBytes = READ_PAGE_MAX_BYTES, continuation) {
85
87
  const resolved = continuation ? { path: input.path, ...continuation } : resolveReadInput(input);
86
88
  if (resolved.digest && digestText(content) !== resolved.digest) {
87
89
  throw new Error('The content changed since the previous page. This continuation cannot be used. Read the original path again to start from the current content.');
@@ -140,16 +142,17 @@ export function readPage(content, input, maxChars = READ_PAGE_MAX_CHARS, continu
140
142
  next,
141
143
  };
142
144
  };
143
- if (end - start <= maxChars) {
145
+ const fits = (page) => Buffer.byteLength(JSON.stringify(page)) <= maxBytes;
146
+ if (end - start <= maxBytes) {
144
147
  const page = makePage(end);
145
- if (JSON.stringify(page).length <= maxChars)
148
+ if (fits(page))
146
149
  return page;
147
150
  }
148
151
  let low = start;
149
- let high = Math.min(end, start + maxChars);
152
+ let high = Math.min(end, start + maxBytes);
150
153
  while (low < high) {
151
154
  const middle = Math.ceil((low + high) / 2);
152
- if (JSON.stringify(makePage(middle)).length <= maxChars)
155
+ if (fits(makePage(middle)))
153
156
  low = middle;
154
157
  else
155
158
  high = middle - 1;
@@ -210,7 +213,7 @@ export function readableToolResult(serialized) {
210
213
  }
211
214
  return serialized;
212
215
  }
213
- export function readToolResultPage(serialized, input, maxChars = READ_PAGE_MAX_CHARS) {
216
+ export function readToolResultPage(serialized, input, maxBytes = READ_PAGE_MAX_BYTES) {
214
217
  let metadata;
215
218
  try {
216
219
  const value = JSON.parse(serialized);
@@ -226,6 +229,6 @@ export function readToolResultPage(serialized, input, maxChars = READ_PAGE_MAX_C
226
229
  catch {
227
230
  /* Text has no separate execution metadata. */
228
231
  }
229
- const page = readPage(readableToolResult(serialized), input, maxChars - (metadata ? JSON.stringify(metadata).length + 16 : 0));
232
+ const page = readPage(readableToolResult(serialized), input, maxBytes - (metadata ? Buffer.byteLength(JSON.stringify(metadata)) + 16 : 0));
230
233
  return metadata ? { ...page, metadata } : page;
231
234
  }
@@ -16,7 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { TOOL_BOUNDARY_PROTOCOL_V1, } from '@maka/core/runtime-event';
19
+ import { TOOL_BOUNDARY_PROTOCOL_V1, isTerminalRuntimeEvent, } from '@maka/core/runtime-event';
20
20
  import { scanToolLedger, } from '@maka/core/tool-ledger-scanner';
21
21
  import { interpretScannedToolRecovery } from '@maka/core/tool-recovery-bundle';
22
22
  import { compatibilityToolResultProjection } from './durable-tool-result-projection.js';
@@ -46,11 +46,12 @@ export function resolveRuntimeRecovery(events) {
46
46
  requiresReconciliation: !hasCorruption && decisions.some((decision) => decision.status === 'indeterminate'),
47
47
  };
48
48
  }
49
- export function buildInterruptedCodeModeOutcomeCommits(events, now, toolMode) {
50
- if (toolMode !== 'code_mode')
51
- return [];
49
+ export function buildInterruptedToolOutcomeCommits(events, now, toolMode) {
52
50
  const eventsById = new Map(events.map((event) => [event.id, event]));
51
+ const terminalInvocations = new Set(events.filter(isTerminalRuntimeEvent).map((event) => event.invocationId));
53
52
  const recovery = resolveRuntimeRecovery(events);
53
+ if (recovery.hasCorruption)
54
+ return [];
54
55
  return recovery.decisions.flatMap((decision) => {
55
56
  if (decision.status !== 'indeterminate' ||
56
57
  decision.reason !== 'dispatch_without_response' ||
@@ -60,21 +61,38 @@ export function buildInterruptedCodeModeOutcomeCommits(events, now, toolMode) {
60
61
  }
61
62
  const callEvent = eventsById.get(decision.callRuntimeEventId);
62
63
  const call = callEvent?.content;
63
- if (!callEvent ||
64
- call?.kind !== 'function_call' ||
65
- call.name !== 'exec' ||
66
- callEvent.origin === 'code_mode' ||
67
- callEvent.modelVisibility === 'hidden') {
64
+ if (!callEvent || call?.kind !== 'function_call') {
68
65
  return [];
69
66
  }
70
- const result = {
71
- kind: 'json',
72
- value: {
73
- kind: 'code_mode',
74
- status: 'interrupted',
75
- message: 'Code Mode execution was interrupted by runtime recovery.',
76
- },
77
- };
67
+ // A sealed invocation cannot accept new RuntimeEvents. Legacy sessions can
68
+ // still contain this gap; their projection is repaired from the terminal
69
+ // fact instead of appending a result after the immutable tail.
70
+ if (terminalInvocations.has(callEvent.invocationId))
71
+ return [];
72
+ const codeModeExec = toolMode === 'code_mode' &&
73
+ call.name === 'exec' &&
74
+ callEvent.origin !== 'code_mode' &&
75
+ callEvent.modelVisibility !== 'hidden';
76
+ const interaction = call.name === 'AskUserQuestion';
77
+ const result = codeModeExec
78
+ ? {
79
+ kind: 'json',
80
+ value: {
81
+ kind: 'code_mode',
82
+ status: 'interrupted',
83
+ message: 'Code Mode execution was interrupted by runtime recovery. Its side effects may or may not have occurred; do not retry it immediately. Inspect the current state first.',
84
+ uncertainOutcome: { code: 'outcome_unknown', retrySafe: false },
85
+ },
86
+ }
87
+ : {
88
+ kind: 'text',
89
+ text: interaction
90
+ ? 'This question was interrupted by runtime recovery before an answer was submitted.'
91
+ : `Tool ${call.name} was interrupted before its result was committed. Its side effects may or may not have occurred. Do not retry it immediately; inspect the current state first.`,
92
+ ...(!interaction
93
+ ? { uncertainOutcome: { code: 'outcome_unknown', retrySafe: false } }
94
+ : {}),
95
+ };
78
96
  const responseContent = {
79
97
  kind: 'function_response',
80
98
  id: call.id,
@@ -93,10 +111,19 @@ export function buildInterruptedCodeModeOutcomeCommits(events, now, toolMode) {
93
111
  partial: false,
94
112
  role: 'tool',
95
113
  author: 'tool',
96
- origin: 'provider',
97
- modelVisibility: 'visible',
114
+ origin: callEvent.origin ?? 'provider',
115
+ modelVisibility: callEvent.modelVisibility ?? 'visible',
98
116
  content: { ...responseContent, ...(modelProjection ? { modelProjection } : {}) },
99
- refs: { operationId: decision.operationId, toolCallId: call.id },
117
+ refs: {
118
+ operationId: decision.operationId,
119
+ toolCallId: call.id,
120
+ ...(callEvent.refs?.parentToolCallId
121
+ ? { parentToolCallId: callEvent.refs.parentToolCallId }
122
+ : {}),
123
+ ...(callEvent.refs?.parentOperationId
124
+ ? { parentOperationId: callEvent.refs.parentOperationId }
125
+ : {}),
126
+ },
100
127
  };
101
128
  return [
102
129
  {
@@ -280,6 +280,7 @@ export function backfillRuntimeEventsFromStoredMessages(input) {
280
280
  // Both are already accounted for elsewhere: the turn's ending becomes the
281
281
  // terminal RuntimeEvent below, and a coordination record is the WorkHub's
282
282
  // own durable proof, which no run ledger owns a copy of.
283
+ case 'form_interaction': // InteractionStore owns this read projection.
283
284
  case 'turn_state':
284
285
  case 'workhub_coordination':
285
286
  break;
@@ -62,13 +62,43 @@ const schema = z.object({
62
62
  id: z.string().min(1).optional().describe('[pause|resume|delete] task id'),
63
63
  maxFires: z.number().int().min(1).max(10_000).optional(),
64
64
  });
65
+ /**
66
+ * Renders an epoch in the Host's local time zone with an explicit offset, so a
67
+ * model can turn "today at 10:00" into `runAt` without a shell round trip.
68
+ */
69
+ export function formatScheduledTaskLocalTime(epochMs, timeZone) {
70
+ const zone = timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
71
+ const parts = Object.fromEntries(new Intl.DateTimeFormat('en-CA', {
72
+ timeZone: zone,
73
+ year: 'numeric',
74
+ month: '2-digit',
75
+ day: '2-digit',
76
+ hour: '2-digit',
77
+ minute: '2-digit',
78
+ second: '2-digit',
79
+ hourCycle: 'h23',
80
+ timeZoneName: 'longOffset',
81
+ })
82
+ .formatToParts(epochMs)
83
+ .map((part) => [part.type, part.value]));
84
+ const offset = parts.timeZoneName === 'GMT' ? '+00:00' : parts.timeZoneName?.replace('GMT', '');
85
+ return `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}${offset} (${zone})`;
86
+ }
65
87
  export function buildScheduledTaskTool(deps) {
88
+ const now = deps.now ?? Date.now;
89
+ const clockLine = () => {
90
+ const at = now();
91
+ return `now=${at} (${formatScheduledTaskLocalTime(at, deps.timeZone)})`;
92
+ };
93
+ const fireLine = (epochMs) => epochMs === null ? '—' : `${epochMs} (${formatScheduledTaskLocalTime(epochMs, deps.timeZone)})`;
66
94
  return {
67
95
  name: SCHEDULED_TASK_TOOL_NAME,
68
96
  displayName: 'ScheduledTask',
69
97
  description: 'Create and manage global scheduled tasks (定时任务). ' +
70
98
  'Use for every recurring or one-shot task. All tasks appear in the desktop Scheduled tasks page. ' +
71
- 'The default session_resume effect continues this conversation; use agent_run for independent work.',
99
+ 'The default session_resume effect continues this conversation; use agent_run for independent work. ' +
100
+ 'Times are epoch milliseconds. Only the list and create results report the current Host time and time zone; ' +
101
+ 'call mode=list first when you need it to compute runAt or startAt.',
72
102
  parameters: schema,
73
103
  impl: async (raw, ctx) => {
74
104
  const input = schema.parse(raw);
@@ -76,14 +106,15 @@ export function buildScheduledTaskTool(deps) {
76
106
  if (input.mode === 'list') {
77
107
  const tasks = await deps.authority.list();
78
108
  if (tasks.length === 0)
79
- return 'No scheduled tasks.';
80
- return tasks
81
- .map((task) => `- ${task.id} | ${task.title} | ${task.status} | next=${task.nextFireAt ?? '—'} | effect=${task.effect.kind}`)
82
- .join('\n');
109
+ return `No scheduled tasks.\n${clockLine()}`;
110
+ return [
111
+ ...tasks.map((task) => `- ${task.id} | ${task.title} | ${task.status} | next=${fireLine(task.nextFireAt)} | effect=${task.effect.kind}`),
112
+ clockLine(),
113
+ ].join('\n');
83
114
  }
84
115
  if (input.mode === 'create') {
85
116
  if (!input.title || !input.intentBody || !input.schedule) {
86
- return 'create requires title, intentBody, and schedule';
117
+ return `create requires title, intentBody, and schedule\n${clockLine()}`;
87
118
  }
88
119
  const result = await deps.authority.create({
89
120
  title: input.title,
@@ -94,8 +125,8 @@ export function buildScheduledTaskTool(deps) {
94
125
  ...(input.maxFires !== undefined ? { maxFires: input.maxFires } : {}),
95
126
  });
96
127
  if ('error' in result)
97
- return result.error;
98
- return `Scheduled task created: ${result.title} (${result.id})\nnextFireAt=${result.nextFireAt}\neffect=${result.effect.kind}`;
128
+ return `${result.error}\n${clockLine()}`;
129
+ return `Scheduled task created: ${result.title} (${result.id})\nnextFireAt=${fireLine(result.nextFireAt)}\neffect=${result.effect.kind}\n${clockLine()}`;
99
130
  }
100
131
  if (!input.id)
101
132
  return `${input.mode} requires id`;
@@ -45,7 +45,7 @@ import { isTranscriptLedgerInvocation, RuntimeLedgerRepair } from './runtime-led
45
45
  import { buildRecoveredTerminalRuntimeEvent, classifyTerminalRuntimeLedger, commitTerminalRunWithRuntimeFact, terminalRunStatusFromRuntimeEvent, } from './terminal-run-commit.js';
46
46
  import { readLatestContextDiagnostics } from './context-diagnostics.js';
47
47
  import { attributeSandboxBoundaryRestartClosure, classifyAgentRunRecovery, } from './agent-run-recovery.js';
48
- import { buildInterruptedCodeModeOutcomeCommits } from './recovery-resolver.js';
48
+ import { buildInterruptedToolOutcomeCommits, resolveRuntimeRecovery } from './recovery-resolver.js';
49
49
  import { isRuntimeHostedRootAuthority, RuntimeMessageAuthorityInvariantError, } from './message-authority.js';
50
50
  import { RuntimeInteractionInvariantError, } from './interaction-authority.js';
51
51
  import { RuntimeKernel, SessionQuiescentMutationBusyError, } from './runtime-kernel.js';
@@ -3205,7 +3205,7 @@ export class SessionManager {
3205
3205
  continue;
3206
3206
  }
3207
3207
  if (this.runtimeCommitSink) {
3208
- const interruptedOutcomes = buildInterruptedCodeModeOutcomeCommits(inspected.runtimeEvents, this.deps.now(), run.opening.configuration.toolMode);
3208
+ const interruptedOutcomes = buildInterruptedToolOutcomeCommits(inspected.runtimeEvents, this.deps.now(), run.opening.configuration.toolMode);
3209
3209
  let outcomeCommitFailed = false;
3210
3210
  for (const outcome of interruptedOutcomes) {
3211
3211
  const committed = await commitInterruptedOutcomeWithRetry(policy, () => this.runtimeCommitSink.commitToolOutcome(outcome));
@@ -3231,6 +3231,16 @@ export class SessionManager {
3231
3231
  });
3232
3232
  }
3233
3233
  }
3234
+ if (!inspected.runtimeEvents.some(isTerminalRuntimeEvent)) {
3235
+ const toolRecovery = resolveRuntimeRecovery(inspected.runtimeEvents);
3236
+ if (toolRecovery.hasCorruption ||
3237
+ toolRecovery.decisions.some((decision) => decision.status === 'indeterminate')) {
3238
+ // Never seal an invocation while a dispatched operation still lacks
3239
+ // a result or an explicit recovery decision. A later recovery pass
3240
+ // may retry the durable settlement; corruption stays fail-closed.
3241
+ continue;
3242
+ }
3243
+ }
3234
3244
  const terminalLedger = classifyTerminalRuntimeLedger(run, inspected.runtimeEvents);
3235
3245
  if (terminalLedger.kind === 'corrupt') {
3236
3246
  if (policy.kind === 'strict') {