@myagentroam/agent 0.14.8 → 0.14.10

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 (47) hide show
  1. package/dist/prompts/compact.js +2 -1
  2. package/dist/prompts/core.d.ts +1 -1
  3. package/dist/prompts/core.js +1 -1
  4. package/dist/prompts/index.d.ts +1 -1
  5. package/dist/prompts/index.js +1 -1
  6. package/dist/runtime/compaction/history.js +3 -1
  7. package/dist/runtime/compaction/retained-context.js +1 -0
  8. package/dist/runtime/context/projection.js +3 -0
  9. package/dist/runtime/context/world-state.d.ts +7 -1
  10. package/dist/runtime/context/world-state.js +72 -1
  11. package/dist/runtime/public-tool-metadata.js +1 -1
  12. package/dist/sdk/execution-compact-commit.d.ts +1 -0
  13. package/dist/sdk/execution-compact-commit.js +20 -3
  14. package/dist/sdk/execution-compaction.d.ts +1 -0
  15. package/dist/sdk/execution-compaction.js +2 -1
  16. package/dist/sdk/execution-model-context.js +11 -0
  17. package/dist/sdk/execution-model-lifecycle.d.ts +1 -1
  18. package/dist/sdk/execution-model-lifecycle.js +2 -1
  19. package/dist/sdk/execution-round-request.d.ts +3 -1
  20. package/dist/sdk/execution-round-request.js +23 -6
  21. package/dist/sdk/execution-tool-catalog.js +1 -1
  22. package/dist/sdk/execution-tool-scope.d.ts +3 -0
  23. package/dist/sdk/execution-tool-scope.js +7 -3
  24. package/dist/sdk/extension-tools.js +1 -1
  25. package/dist/sdk/request-preparation.d.ts +2 -2
  26. package/dist/sdk/request-preparation.js +53 -9
  27. package/dist/sdk/session-execution-factory.d.ts +1 -1
  28. package/dist/sdk/session-execution-factory.js +86 -39
  29. package/dist/sdk/session-runtime.d.ts +10 -1
  30. package/dist/sdk/session-runtime.js +56 -3
  31. package/dist/session/mcp-discovery.d.ts +9 -0
  32. package/dist/session/mcp-discovery.js +65 -0
  33. package/dist/session/model-request.d.ts +3 -0
  34. package/dist/session/tool-callers.js +1 -1
  35. package/dist/tools/agent/skill.d.ts +3 -0
  36. package/dist/tools/agent/skill.js +10 -5
  37. package/dist/tools/code-mode/dispatch.d.ts +1 -0
  38. package/dist/tools/code-mode/dispatch.js +5 -0
  39. package/dist/tools/code-mode/index.js +2 -2
  40. package/dist/tools/execution.js +1 -0
  41. package/dist/tools/mcp/history.d.ts +2 -0
  42. package/dist/tools/mcp/history.js +13 -2
  43. package/dist/tools/mcp/tool-search.d.ts +1 -0
  44. package/dist/tools/mcp/tool-search.js +6 -4
  45. package/dist/tools/registry.js +1 -1
  46. package/dist/tools/runtime-context.d.ts +4 -2
  47. package/package.json +1 -1
@@ -2,8 +2,9 @@ import { restoreMessages } from '../runtime/context/restore.js';
2
2
  import { latestModelUsage, reasoningEffortBaseline } from '../runtime/context/usage.js';
3
3
  import { publicModelUsage } from '../runtime/event-projection.js';
4
4
  import { truncateModelText } from '../runtime/token-budget.js';
5
+ import { MCP_DISCOVERY_DELIVERED } from '../session/mcp-discovery.js';
5
6
  import { executeRoundTools } from '../tools/execution.js';
6
- import { rebindMcpToolSearchOutputs } from '../tools/mcp/history.js';
7
+ import { pairedMcpToolNames } from '../tools/mcp/history.js';
7
8
  import { ExecutionToolPermissions, projectPermissionTool, resolvePermissionMode, withToolPermissions } from '../tools/permissions.js';
8
9
  import { createToolWaitInterrupt } from '../tools/wait.js';
9
10
  import { createExecutionCompactExtension } from './execution-compact-extension.js';
@@ -368,7 +369,6 @@ export function createSessionExecutionFactory(ports) {
368
369
  });
369
370
  const updateMcpRegistry = () => toolCatalog.updateRegistry();
370
371
  updateMcpRegistry();
371
- rebindMcpToolSearchOutputs(messages, mcpRegistry);
372
372
  const availableTools = toolCatalog.available();
373
373
  const instructionContext = await loadAgentInstructions({
374
374
  home: description.homeDirectory,
@@ -383,8 +383,12 @@ export function createSessionExecutionFactory(ports) {
383
383
  const currentInstructionSnapshot = renderAgentInstructions(instructionEntries, false);
384
384
  instructionSkills = instructionContext?.skills;
385
385
  const baseTools = () => toolCatalog.base();
386
- toolCatalog.refresh();
387
- const restoreMcpDiscovery = () => toolCatalog.restore();
386
+ let discoveryRevision;
387
+ const restoreMcpDiscovery = () => {
388
+ toolCatalog.restore();
389
+ discoveryRevision = sessionRuntime.mcpDiscoveryRevision;
390
+ };
391
+ restoreMcpDiscovery();
388
392
  const loadRetainedSessionResources = async () => {
389
393
  const hostResources = (await host.listSessionResources?.(sessionId)) ?? {
390
394
  processes: []
@@ -438,6 +442,18 @@ export function createSessionExecutionFactory(ports) {
438
442
  todo,
439
443
  waitInterrupt,
440
444
  skills: instructionContext?.skills ?? new Map(),
445
+ publishSkillContext: (name, content) => sessionRuntime.publishSkillContext(name, content),
446
+ withRecordProjection,
447
+ publishMcpDiscovery: async (names, signal) => {
448
+ const message = {
449
+ role: 'user',
450
+ contextKind: 'contextual',
451
+ content: '',
452
+ mcpDiscovery: { id: randomUUID(), names }
453
+ };
454
+ const record = await store.append(sessionId, { type: 'model.context', payload: message, executionId, turnId }, { signal });
455
+ sessionRuntime.publishMcpDiscovery(record.recordId, message);
456
+ },
441
457
  coreExtensions,
442
458
  operations: extensionManager.operations,
443
459
  scheduleTool: sessionRuntime.scheduleTool,
@@ -470,7 +486,7 @@ export function createSessionExecutionFactory(ports) {
470
486
  ? normalizeMessagesForModel([...preparingRequestMessages, ...messages.slice(preparingRequestBaseLength)], { supportsImages: selectedModel.inputCapabilities.includes('IMAGE') })
471
487
  : projectSessionRequestMessages(messages.map((message, index) => index === currentExecutionUserIndex && modelInputImages?.length
472
488
  ? { ...message, images: modelInputImages }
473
- : message), modelContext.worldState.entries, mode !== 'compact' && selectedModel.inputCapabilities.includes('IMAGE'), baseTools().some((tool) => tool.name === 'code_exec'), permissionPolicy.mode === 'auto')
489
+ : message), modelContext.worldState.entries, mode !== 'compact' && selectedModel.inputCapabilities.includes('IMAGE'), baseTools().some((tool) => tool.name === 'code_exec'), permissionPolicy.mode === 'auto', projectTools(toolCatalog.tools))
474
490
  }
475
491
  });
476
492
  if (mode !== 'compact') {
@@ -618,7 +634,11 @@ export function createSessionExecutionFactory(ports) {
618
634
  updateBoundary: (value) => {
619
635
  contextCoordinator.setBoundary(value);
620
636
  },
621
- snapshotTools: () => projectTools(toolCatalog.tools),
637
+ snapshotTools: () => {
638
+ const resident = new Set(mcpRegistry.projectDirect(baseTools()).map(({ name }) => name));
639
+ const paired = pairedMcpToolNames(messages);
640
+ return projectTools(toolCatalog.tools.filter(({ name }) => resident.has(name) || paired.has(name)));
641
+ },
622
642
  projectRequest: (history, tools) => ({
623
643
  messages: projectSessionRequestMessages(history, modelContext.worldState.entries, false, tools.some((tool) => tool.name === 'code_exec'), permissionPolicy.mode === 'auto'),
624
644
  tools: projectSessionRequestTools(selectedModel, tools, projectTools(mcpRegistry.projectDirect(baseTools())))
@@ -639,6 +659,7 @@ export function createSessionExecutionFactory(ports) {
639
659
  }),
640
660
  retainedResources: async () => retainedSessionResourcesSnapshot(await loadRetainedSessionResources()),
641
661
  withProjection: withRecordProjection,
662
+ pendingDiscoveryNames: (message) => sessionRuntime.pendingMcpDiscoveryNames(message),
642
663
  recordCommit: (recordId) => inputs.recordCompactCommit({ changed: true, recordId, executionId }),
643
664
  invalidateContext: (error) => executionOwner.invalidateContext(error),
644
665
  invalidateUsage: invalidateCompactUsage,
@@ -681,6 +702,7 @@ export function createSessionExecutionFactory(ports) {
681
702
  await compactCoordinator.checkpoint(true);
682
703
  return;
683
704
  }
705
+ const preparedSkillLoads = new WeakMap();
684
706
  const prepareRound = createExecutionRoundPreparer({
685
707
  prepareInputs: (includeSessionContext) => contextCoordinator.prepareInputs({
686
708
  includeSessionContext,
@@ -690,36 +712,45 @@ export function createSessionExecutionFactory(ports) {
690
712
  },
691
713
  refreshTools: () => {
692
714
  updateMcpRegistry();
693
- toolCatalog.refresh();
715
+ if (discoveryRevision !== sessionRuntime.mcpDiscoveryRevision)
716
+ restoreMcpDiscovery();
717
+ else
718
+ toolCatalog.refresh();
694
719
  },
695
720
  updateEnvironment: () => {
696
721
  executionEnvironment = { ...currentEnvironment, ...currentLocalTimeContext() };
697
722
  }
698
723
  }),
699
- buildCandidate: (continuation) => prepareExecutionRoundRequest({
700
- messages,
701
- continuation,
702
- model: selectedModel,
703
- requestBase: {
704
- promptCacheKey: sessionId,
705
- reasoningEffort,
706
- ...(requestReasoningEffort === undefined ? {} : { requestReasoningEffort }),
707
- ...(modelInputImages?.length ? { images: modelInputImages } : {}),
708
- onAttemptDiagnostic: recordModelAttempt('EXECUTION')
709
- },
710
- residentTools: () => projectTools(mcpRegistry.projectDirect(baseTools())),
711
- autoPermission: permissionPolicy.mode === 'auto',
712
- signal: controller.signal,
713
- capture: captureRoundToolScope,
714
- bind: (scope) => sources.bind(scope),
715
- world: () => modelContext.worldState,
716
- commitWorld: (world) => modelContext.commitWorldState(world),
717
- preparing: (next, baseLength) => {
718
- preparingRequestMessages = next;
719
- preparingRequestBaseLength = baseLength;
720
- },
721
- transform: (candidate, bindings) => transformModelRequest(candidate, bindings)
722
- }),
724
+ buildCandidate: async (continuation) => {
725
+ const skillLoads = sessionRuntime.pendingSkillContext();
726
+ const capturedDiscoveryRevision = discoveryRevision;
727
+ const candidate = await prepareExecutionRoundRequest({
728
+ messages,
729
+ continuation,
730
+ skillLoads,
731
+ model: selectedModel,
732
+ requestBase: {
733
+ promptCacheKey: sessionId,
734
+ reasoningEffort,
735
+ ...(requestReasoningEffort === undefined ? {} : { requestReasoningEffort }),
736
+ ...(modelInputImages?.length ? { images: modelInputImages } : {}),
737
+ onAttemptDiagnostic: recordModelAttempt('EXECUTION')
738
+ },
739
+ residentTools: () => projectTools(mcpRegistry.projectDirect(baseTools())),
740
+ autoPermission: permissionPolicy.mode === 'auto',
741
+ signal: controller.signal,
742
+ capture: captureRoundToolScope,
743
+ bind: (scope) => sources.bind(scope),
744
+ world: () => modelContext.worldState,
745
+ commitWorld: (world) => modelContext.commitWorldState(world),
746
+ preparing: (next, baseLength) => {
747
+ preparingRequestMessages = next;
748
+ preparingRequestBaseLength = baseLength;
749
+ },
750
+ transform: (candidate, bindings) => transformModelRequest(candidate, bindings)
751
+ });
752
+ return { ...candidate, discoveryRevision: capturedDiscoveryRevision, skillLoads };
753
+ },
723
754
  adoptLateInput: async () => {
724
755
  const lateCoreChange = inputs.hasBoundaryCompactPending && (await appendMailboxMessages());
725
756
  const lateBlocking = compactRequests.drain((input) => startCompact({
@@ -729,7 +760,9 @@ export function createSessionExecutionFactory(ports) {
729
760
  const lateAdopted = lateBlocking && (await compactCoordinator.checkpoint(true));
730
761
  return Boolean(lateCoreChange || lateAdopted);
731
762
  },
732
- prepareResources: async ({ candidateRequest, request, toolScope }) => {
763
+ prepareResources: async ({ candidateRequest, request, toolScope, discoveryRevision: capturedDiscoveryRevision, skillLoads, commitSkillContext }) => {
764
+ if (capturedDiscoveryRevision !== sessionRuntime.mcpDiscoveryRevision)
765
+ return { retry: true };
733
766
  resourceInput.observe(candidateRequest.messages);
734
767
  const media = selectedModel.gcEnabled === false
735
768
  ? undefined
@@ -739,12 +772,14 @@ export function createSessionExecutionFactory(ports) {
739
772
  if (committed)
740
773
  return { retry: true };
741
774
  }
742
- return {
743
- round: {
744
- request: await resourceInput.prepare(request, candidateRequest.images, candidateRequest.messages),
745
- toolScope
746
- }
747
- };
775
+ const prepared = await resourceInput.prepare(request, candidateRequest.images, candidateRequest.messages);
776
+ controller.signal.throwIfAborted();
777
+ await commitSkillContext();
778
+ if (capturedDiscoveryRevision !== sessionRuntime.mcpDiscoveryRevision)
779
+ return { retry: true };
780
+ if (skillLoads.size)
781
+ preparedSkillLoads.set(prepared.messages, skillLoads);
782
+ return { round: { request: prepared, toolScope } };
748
783
  }
749
784
  });
750
785
  const completed = await executionOwner.runMainLoop({
@@ -767,7 +802,19 @@ export function createSessionExecutionFactory(ports) {
767
802
  }),
768
803
  prepareRound,
769
804
  runTools: executeRoundTools,
770
- startModel: (request) => modelLifecycle.start(request),
805
+ startModel: (request) => {
806
+ const skillLoads = preparedSkillLoads.get(request.messages);
807
+ return modelLifecycle.start(request, async () => {
808
+ if (skillLoads)
809
+ sessionRuntime.acknowledgeSkillContext(skillLoads);
810
+ await sessionRuntime.acknowledgeMcpDiscovery(request.messages, (receipts) => store.append(sessionId, {
811
+ type: MCP_DISCOVERY_DELIVERED,
812
+ payload: { receipts },
813
+ executionId,
814
+ turnId
815
+ }));
816
+ });
817
+ },
771
818
  recoverySignal: () => controller.signal,
772
819
  compactContext,
773
820
  afterModel: (closedPrefixLength, request) => modelLifecycle.afterModel(closedPrefixLength, request),
@@ -2,14 +2,16 @@ import { ExtensionRequestSnapshots, type ExtensionRequestSnapshot } from '../ext
2
2
  import type { ExtensionSessionBackend, SessionInputCoordinator } from '../extensions/session-input.js';
3
3
  import type { ModelAdapter } from '../model/contracts.js';
4
4
  import type { ModelCredentialProvider } from '../model/configuration.js';
5
- import type { SessionModelRequest as ModelRequest } from '../session/model-request.js';
5
+ import type { SessionModelMessage, SessionModelRequest as ModelRequest } from '../session/model-request.js';
6
6
  import type { SessionStore } from '../session/store/contracts.js';
7
+ import { type McpDiscoveryReceipt } from '../session/mcp-discovery.js';
7
8
  import { type ContextualWorldState } from '../runtime/context/world-state.js';
8
9
  import { TodoStore } from '../tools/agent/todo.js';
9
10
  import type { ExecutionResult } from './types.js';
10
11
  import type { AgentEvent } from '../runtime/events.js';
11
12
  import type { ResolvedModelConfiguration } from './model-runtime.js';
12
13
  import type { SessionExecution, SessionExecutionContext } from './session-execution.js';
14
+ /** Owns warm Session state shared across sequential Executions and retained cells. */
13
15
  export declare class SessionRuntime {
14
16
  #private;
15
17
  readonly storedSession: Awaited<ReturnType<SessionStore['getSession']>>;
@@ -27,6 +29,13 @@ export declare class SessionRuntime {
27
29
  retireInputs(): Promise<unknown> | undefined;
28
30
  getOrCreateInputs(create: () => SessionInputCoordinator): SessionInputCoordinator;
29
31
  resetAfterClear(generation: number): void;
32
+ publishSkillContext(name: string, content: string): void;
33
+ pendingSkillContext(): ReadonlyMap<string, string>;
34
+ acknowledgeSkillContext(delivered: ReadonlyMap<string, string>): void;
35
+ publishMcpDiscovery(recordId: string, message: SessionModelMessage): void;
36
+ get mcpDiscoveryRevision(): number;
37
+ pendingMcpDiscoveryNames(message: SessionModelMessage): readonly string[];
38
+ acknowledgeMcpDiscovery(messages: readonly SessionModelMessage[], persist: (receipts: readonly McpDiscoveryReceipt[]) => Promise<unknown>): Promise<void>;
30
39
  recordRequest(modelId: string, request: ModelRequest): ExtensionRequestSnapshot;
31
40
  completeRequest(snapshot: ExtensionRequestSnapshot): void;
32
41
  captureRequest(input: Parameters<ExtensionRequestSnapshots['capture']>[0]): ExtensionRequestSnapshot | undefined;
@@ -1,17 +1,22 @@
1
1
  import { AgentError } from '../error.js';
2
2
  import { ExtensionRequestSnapshots } from '../extensions/model-request.js';
3
- import { latestContextualWorldStateGeneration, parsePersistedContextualWorldState } from '../runtime/context/world-state.js';
3
+ import { restorePendingMcpDiscovery } from '../session/mcp-discovery.js';
4
+ import { assertLoadedSkillCapacity, latestContextualWorldStateGeneration, parsePersistedContextualWorldState, recoverLoadedSkillEntries } from '../runtime/context/world-state.js';
4
5
  import { TodoStore } from '../tools/agent/todo.js';
5
6
  import { createSessionToolScheduler } from '../tools/scheduler.js';
6
7
  import { SessionModelAdapters } from './session-model-adapters.js';
8
+ /** Owns warm Session state shared across sequential Executions and retained cells. */
7
9
  export class SessionRuntime {
8
10
  storedSession;
9
11
  onExecutionRegistered;
10
12
  #executionContext;
13
+ #mcpDiscoveryRevision = 0;
14
+ #pendingMcpDiscovery = new Map();
11
15
  #todo;
12
16
  scheduleTool = createSessionToolScheduler();
13
17
  #modelAdapters;
14
18
  #contextualWorldState;
19
+ #pendingSkillContext = new Map();
15
20
  #inputs;
16
21
  #requestSnapshots;
17
22
  #recordProjection;
@@ -55,12 +60,56 @@ export class SessionRuntime {
55
60
  return (this.#inputs ??= create());
56
61
  }
57
62
  resetAfterClear(generation) {
63
+ this.#pendingMcpDiscovery.clear();
58
64
  this.#modelAdapters.setGeneration(generation);
59
65
  this.#todo = undefined;
60
66
  this.#contextualWorldState = undefined;
67
+ this.#pendingSkillContext.clear();
61
68
  this.#inputs = undefined;
62
69
  this.#requestSnapshots = undefined;
63
70
  }
71
+ publishSkillContext(name, content) {
72
+ assertLoadedSkillCapacity(this.#contextualWorldState?.entries ?? [], this.#pendingSkillContext, name, content);
73
+ this.#pendingSkillContext.set(name, content);
74
+ }
75
+ pendingSkillContext() {
76
+ return new Map(this.#pendingSkillContext);
77
+ }
78
+ acknowledgeSkillContext(delivered) {
79
+ for (const [name, content] of delivered)
80
+ if (this.#pendingSkillContext.get(name) === content)
81
+ this.#pendingSkillContext.delete(name);
82
+ }
83
+ publishMcpDiscovery(recordId, message) {
84
+ const receipt = message.mcpDiscovery;
85
+ for (const name of receipt.names)
86
+ this.#pendingMcpDiscovery.set(name, receipt.id);
87
+ this.execution?.appendedMessages?.append(recordId, message);
88
+ this.#mcpDiscoveryRevision++;
89
+ }
90
+ get mcpDiscoveryRevision() {
91
+ return this.#mcpDiscoveryRevision;
92
+ }
93
+ pendingMcpDiscoveryNames(message) {
94
+ const receipt = message.mcpDiscovery;
95
+ return (receipt?.names.filter((name) => this.#pendingMcpDiscovery.get(name) === receipt.id) ?? []);
96
+ }
97
+ async acknowledgeMcpDiscovery(messages, persist) {
98
+ if (!this.#pendingMcpDiscovery.size)
99
+ return;
100
+ await this.withRecordProjection(async () => {
101
+ const receipts = messages.flatMap((message) => {
102
+ const names = this.pendingMcpDiscoveryNames(message);
103
+ return names.length ? [{ id: message.mcpDiscovery.id, names }] : [];
104
+ });
105
+ if (!receipts.length)
106
+ return;
107
+ await persist(receipts);
108
+ for (const receipt of receipts)
109
+ for (const name of receipt.names)
110
+ this.#pendingMcpDiscovery.delete(name);
111
+ });
112
+ }
64
113
  recordRequest(modelId, request) {
65
114
  return (this.#requestSnapshots ??= new ExtensionRequestSnapshots()).record(modelId, request);
66
115
  }
@@ -101,7 +150,11 @@ export class SessionRuntime {
101
150
  }
102
151
  async restoreExecutionState(store, writerOwner) {
103
152
  const sessionId = this.storedSession.id;
104
- const state = await store.readExecutionState(sessionId);
153
+ const state = await this.withRecordProjection(async () => {
154
+ const state = await store.readExecutionState(sessionId);
155
+ this.#pendingMcpDiscovery = restorePendingMcpDiscovery(state.contextRecords);
156
+ return state;
157
+ });
105
158
  const todo = this.restoreTodo(state.todo, store.hasRetainedSessionLease(sessionId, writerOwner));
106
159
  const generation = latestContextualWorldStateGeneration(state.contextRecords);
107
160
  const persisted = parsePersistedContextualWorldState(await store.readContextualWorldState(sessionId));
@@ -115,7 +168,7 @@ export class SessionRuntime {
115
168
  initialized: false,
116
169
  instructionSnapshot: undefined,
117
170
  resourceSnapshot: undefined,
118
- entries: []
171
+ entries: recoverLoadedSkillEntries(persisted, state.contextRecords)
119
172
  };
120
173
  this.#contextualWorldState = world;
121
174
  return { todo, contextRecords: state.contextRecords, generation, world };
@@ -0,0 +1,9 @@
1
+ import type { SessionRecord } from './record-contract.js';
2
+ export interface McpDiscoveryReceipt {
3
+ id: string;
4
+ names: readonly string[];
5
+ }
6
+ export declare const MCP_DISCOVERY_DELIVERED = "mcp.discovery.delivered";
7
+ export declare function parseMcpDiscoveryReceipt(value: unknown): McpDiscoveryReceipt | undefined;
8
+ /** Replay only delivery state. Current catalog policy still controls exposure. */
9
+ export declare function restorePendingMcpDiscovery(records: readonly SessionRecord[]): Map<string, string>;
@@ -0,0 +1,65 @@
1
+ import { compactSummaryFromCheckpoint } from './record-projection.js';
2
+ export const MCP_DISCOVERY_DELIVERED = 'mcp.discovery.delivered';
3
+ export function parseMcpDiscoveryReceipt(value) {
4
+ if (!isRecord(value))
5
+ return undefined;
6
+ const { id, names } = value;
7
+ if (typeof id === 'string' &&
8
+ id.length > 0 &&
9
+ id.length <= 128 &&
10
+ Array.isArray(names) &&
11
+ names.length <= 20 &&
12
+ names.every((name) => typeof name === 'string' && name.length <= 512))
13
+ return { id, names };
14
+ return undefined;
15
+ }
16
+ /** Replay only delivery state. Current catalog policy still controls exposure. */
17
+ export function restorePendingMcpDiscovery(records) {
18
+ const pending = new Map();
19
+ for (const record of records) {
20
+ const { type, payload } = record;
21
+ if (!isRecord(payload))
22
+ continue;
23
+ if (type === 'model.context' && payload.role === 'user') {
24
+ const receipt = parseMcpDiscoveryReceipt(payload.mcpDiscovery);
25
+ if (receipt)
26
+ for (const name of receipt.names)
27
+ pending.set(name, receipt.id);
28
+ }
29
+ else if (type === MCP_DISCOVERY_DELIVERED && Array.isArray(payload.receipts)) {
30
+ for (const value of payload.receipts) {
31
+ const receipt = parseMcpDiscoveryReceipt(value);
32
+ if (!receipt)
33
+ continue;
34
+ for (const name of receipt.names)
35
+ if (pending.get(name) === receipt.id)
36
+ pending.delete(name);
37
+ }
38
+ }
39
+ else if (type === 'compact.completed' && compactSummaryFromCheckpoint(record)) {
40
+ pending.clear();
41
+ if (!Array.isArray(payload.retainedModelContext))
42
+ continue;
43
+ for (const message of payload.retainedModelContext) {
44
+ if (!isRecord(message) || message.role !== 'user')
45
+ continue;
46
+ const receipt = parseMcpDiscoveryReceipt(message.mcpDiscovery);
47
+ if (!receipt)
48
+ continue;
49
+ const saved = Array.isArray(message.mcpDiscoveryPendingNames)
50
+ ? message.mcpDiscoveryPendingNames
51
+ : receipt.names;
52
+ for (const name of receipt.names) {
53
+ if (saved.includes(name))
54
+ pending.set(name, receipt.id);
55
+ else
56
+ pending.delete(name);
57
+ }
58
+ }
59
+ }
60
+ }
61
+ return pending;
62
+ }
63
+ function isRecord(value) {
64
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
65
+ }
@@ -1,12 +1,15 @@
1
1
  import type { ModelMessage, ModelRequest } from '../model/contracts.js';
2
2
  import type { ClientToolDefinition } from '../tools/contracts.js';
3
3
  import type { CodeObservation, CodeToolCallRecord } from './code-observation-contract.js';
4
+ import type { McpDiscoveryReceipt } from './mcp-discovery.js';
4
5
  /** Durable execution facts, projected to protocol input at the SDK adapter boundary. */
5
6
  export interface SessionModelMessage extends ModelMessage {
6
7
  calls?: readonly CodeToolCallRecord[];
7
8
  observations?: readonly CodeObservation[];
8
9
  observationId?: string;
9
10
  toolSearchTools?: readonly ClientToolDefinition[];
11
+ /** SDK discovery receipt; names are rebound to the current authorized catalog. */
12
+ mcpDiscovery?: McpDiscoveryReceipt;
10
13
  }
11
14
  export interface SessionModelRequest extends ModelRequest {
12
15
  messages: readonly SessionModelMessage[];
@@ -15,7 +15,7 @@ export function toolCallers(tool) {
15
15
  export function allowsToolCaller(tool, caller) {
16
16
  // Control tools cannot be widened by a Host override or historical definition.
17
17
  if (caller === 'programmatic' &&
18
- ['code_exec', 'code_exec_wait', 'tool_search', 'question', 'skill', 'sleep'].includes(tool.name))
18
+ ['code_exec', 'code_exec_wait', 'question', 'sleep'].includes(tool.name))
19
19
  return false;
20
20
  return toolCallers(tool).includes(caller);
21
21
  }
@@ -4,6 +4,9 @@ export declare const skillToolDefinition: ClientToolDefinition;
4
4
  export declare function executeSkill(arguments_: unknown, context: ToolRuntimeContext): Promise<{
5
5
  content: string;
6
6
  data: {
7
+ success: boolean;
8
+ };
9
+ eventData: {
7
10
  name: string;
8
11
  description: string;
9
12
  source: string;
@@ -1,10 +1,10 @@
1
1
  import { AgentError } from '../../error.js';
2
2
  import { agentSkillSource, loadAgentSkill } from '../../runtime/context/instructions.js';
3
3
  export const skillToolDefinition = {
4
- name: 'skill',
5
- allowedCallers: ['direct'],
4
+ name: 'skill_load',
5
+ allowedCallers: ['direct', 'programmatic'],
6
6
  parallelSafety: 'safe',
7
- description: "Load a Skill's instructions by its exact catalog name.",
7
+ description: 'Load a Skill by its exact catalog name. On success, returns { success: true } and adds the instructions to the next model context. Read them before acting on them.',
8
8
  inputSchema: {
9
9
  type: 'object',
10
10
  properties: {
@@ -27,12 +27,17 @@ export async function executeSkill(arguments_, context) {
27
27
  const skill = context.skills.get(input.name);
28
28
  if (!skill)
29
29
  throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Skill is not available.');
30
+ if (!context.publishSkillContext)
31
+ throw new AgentError('MAR_AGENT_TOOL_NOT_AVAILABLE', 'Skill context delivery is unavailable.');
30
32
  const content = await loadAgentSkill(skill);
31
33
  if (!content)
32
34
  throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Skill could not be loaded.');
33
35
  context.signal.throwIfAborted();
36
+ context.publishSkillContext(skill.name, content);
37
+ const data = { success: true };
34
38
  return {
35
- content,
36
- data: { name: skill.name, description: skill.description, source: agentSkillSource(skill) }
39
+ content: JSON.stringify(data),
40
+ data,
41
+ eventData: { name: skill.name, description: skill.description, source: agentSkillSource(skill) }
37
42
  };
38
43
  }
@@ -10,6 +10,7 @@ type Payload<T = ToolEvent> = T extends ToolEvent ? Omit<T, 'eventId' | 'sequenc
10
10
  /** Capture only the cell's immutable dispatch identity, never the model loop or its AbortSignal. */
11
11
  export declare function createCodeToolDispatch(input: {
12
12
  context: Omit<ToolRuntimeContext, 'signal' | 'codeMode' | 'expectedMcpTool' | 'searchMcpTools'>;
13
+ searchMcpTools?: NonNullable<ToolRuntimeContext['searchMcpTools']>;
13
14
  tools: readonly ClientToolDefinition[];
14
15
  expectations: ReadonlyMap<string, McpToolCallContext['expectedTool']>;
15
16
  parentCallId: string;
@@ -37,6 +37,11 @@ export function createCodeToolDispatch(input) {
37
37
  : input.context.emit(event),
38
38
  parentCallId: input.parentCallId,
39
39
  signal,
40
+ ...(input.searchMcpTools
41
+ ? {
42
+ searchMcpTools: (args, signal) => input.searchMcpTools(args, signal, 'programmatic')
43
+ }
44
+ : {}),
40
45
  ...(expected ? { expectedMcpTool: expected } : {})
41
46
  }, 'programmatic');
42
47
  const bounded = boundedModelToolOutput(call.name, result.content, result.data);
@@ -38,7 +38,7 @@ Tool calls:
38
38
  - tools.NAME(input) returns a Promise. Pass a JavaScript value matching the current catalog inputSchema. For parameterless tools prefer tools.NAME({}); tools.NAME() is accepted only for explicitly closed empty-object schemas.
39
39
  - Results use the MAR envelope: { content?: string, data?: unknown, images?: Array<{mimeType:string,dataBase64:string,url?:string,urlExpiresAt?:number}>, truncated?: boolean }. Redundant JSON content is omitted when it exactly renders data; independent text remains in content. Prefer data for programmatic results: result.data.results[0].text for read source text and result.data.exitCode/result.data.stdout for exec. content, when present, is rendered text, not raw file bytes. Use only fields documented by that tool; do not invent success or ok flags.
40
40
  - Tool errors reject with code/message and may be caught, except nested Auto deny, which skips only that call and resolves with data.error/data.message. A failed cell preserves already emitted output alongside its status and error; completed tool effects are not rolled back. Inspect it before retrying completed work. Await every call; unawaited calls fail the cell. Use Promise.all for independent calls and sequential await for dependencies. Runtime preserves safe/serial barriers and Host checks.
41
- - skill, tool_search, question, code_exec, code_exec_wait and direct-only tools cannot be called here. Load Skills directly and read their instructions before the next tool call. Use direct tool_search before a later code cell for deferred tools; the current cell's tools do not change.
41
+ - question, code_exec, code_exec_wait and other direct-only tools cannot be called here. When available, tools.tool_search discovers deferred tools for the next model response; the current cell's tools do not change.
42
42
 
43
43
  Built-in namespaces:
44
44
  - observe.result(result): void registers an unmodified complete tools.NAME result or caught tool error as a trusted tool_result, using the original text and all images without repeating program data. Non-original, copied or modified values are rejected. This selects evidence for the next model response, not a log and not a new model call. Prefer observe.result for inspecting tool results.
@@ -129,7 +129,7 @@ export function projectCodeModeTools(tools, residentTools = tools) {
129
129
  return direct.map((tool) => tool.name === 'code_exec'
130
130
  ? {
131
131
  ...tool,
132
- description: `${codeModeToolDefinition.description}\nDeferred MCP definitions are returned by direct tool_search and become callable from the next model response, not later in the same response; they are not appended to this description.\nProgrammatic tools: ${directory}`
132
+ description: `${codeModeToolDefinition.description}\nProgrammatic tools: ${directory}`
133
133
  }
134
134
  : tool);
135
135
  }
@@ -67,6 +67,7 @@ export async function createRoundToolRuntimeContext(scope, call, signal) {
67
67
  ...scope.captureCodeContext(),
68
68
  ...(recentImages === undefined ? {} : { recentImages })
69
69
  },
70
+ searchMcpTools: scope.searchMcpTools,
70
71
  tools: scope.tools,
71
72
  expectations: scope.expectations,
72
73
  parentCallId: call.callId,
@@ -1,4 +1,6 @@
1
1
  import type { SessionModelMessage as ModelMessage } from '../../session/model-request.js';
2
2
  import type { DeferredMcpRegistry } from './tool-search.js';
3
3
  export declare function discoveredMcpToolNames(messages: readonly ModelMessage[]): string[];
4
+ /** Native search receipts still carry definitions for normal and Compact protocol projection. */
5
+ export declare function pairedMcpToolNames(messages: readonly ModelMessage[]): ReadonlySet<string>;
4
6
  export declare function rebindMcpToolSearchOutputs(messages: readonly ModelMessage[], registry: DeferredMcpRegistry): void;
@@ -1,12 +1,23 @@
1
1
  import { providerToolCallId, providerToolName } from '../../runtime/context/projection.js';
2
2
  export function discoveredMcpToolNames(messages) {
3
+ return [...mcpToolNames(messages, true)];
4
+ }
5
+ /** Native search receipts still carry definitions for normal and Compact protocol projection. */
6
+ export function pairedMcpToolNames(messages) {
7
+ return mcpToolNames(messages, false);
8
+ }
9
+ function mcpToolNames(messages, includeProgrammatic) {
3
10
  const calls = toolSearchCallIds(messages);
4
11
  const names = new Set();
5
- for (const message of messages)
12
+ for (const message of messages) {
13
+ if (includeProgrammatic)
14
+ for (const name of message.mcpDiscovery?.names ?? [])
15
+ names.add(name);
6
16
  for (const tool of calls.has(message.callId ?? '') ? (message.toolSearchTools ?? []) : [])
7
17
  // Paired discovery receipts provide candidates; the current captured MCP catalog is authority.
8
18
  names.add(tool.name);
9
- return [...names];
19
+ }
20
+ return names;
10
21
  }
11
22
  export function rebindMcpToolSearchOutputs(messages, registry) {
12
23
  const calls = toolSearchCallIds(messages);
@@ -38,6 +38,7 @@ export declare class DeferredMcpRegistry {
38
38
  base: readonly ClientToolDefinition[];
39
39
  window: number;
40
40
  system: string;
41
+ publish?: (names: readonly string[]) => Promise<void>;
41
42
  }): Promise<ToolExecutionResult>;
42
43
  assertBudget(base: readonly ClientToolDefinition[], window: number, system: string, selection?: readonly string[], executionSelection?: ReadonlySet<string>): void;
43
44
  navigation(): string | undefined;
@@ -14,7 +14,7 @@ export const TOOL_SEARCH_LIMITS = Object.freeze({
14
14
  });
15
15
  export const toolSearchToolDefinition = {
16
16
  name: 'tool_search',
17
- description: 'Search deferred MCP metadata and return matching tool definitions for the next model call. Use the full callable name for exact selection, or keywords for BM25 search. Never executes the discovered tools. With Code Mode Only, programmatic tools use code_exec unless explicitly exposed for both direct and programmatic calls. Already exposed tools need not be searched again. The selected definitions must fit the exposure budget or the search fails atomically.',
17
+ description: 'Search and load deferred MCP tools for the next model request. Use an exact tool name or keywords. Returns matching names, or an empty list; definitions are supplied separately. Does not execute the discovered tools.',
18
18
  inputSchema: {
19
19
  type: 'object',
20
20
  properties: {
@@ -24,7 +24,7 @@ export const toolSearchToolDefinition = {
24
24
  required: ['query'],
25
25
  additionalProperties: false
26
26
  },
27
- allowedCallers: ['direct'],
27
+ allowedCallers: ['direct', 'programmatic'],
28
28
  parallelSafety: 'safe',
29
29
  nativeType: 'tool_search'
30
30
  };
@@ -201,13 +201,15 @@ export class DeferredMcpRegistry {
201
201
  }
202
202
  this.assertBudget(context.base, context.window, context.system, selection, executionSelection);
203
203
  context.signal.throwIfAborted();
204
+ const data = { tools: matches.map((tool) => tool.definition.name) };
205
+ if (context.publish && data.tools.length)
206
+ await context.publish(data.tools);
204
207
  this.#selected = selection;
205
208
  this.#executionSelected = executionSelection;
206
- const data = { tools: matches.map((tool) => tool.definition.name) };
207
209
  return {
208
210
  content: JSON.stringify(data),
209
211
  data,
210
- toolSearchTools: matches.map((tool) => tool.definition)
212
+ ...(context.publish ? {} : { toolSearchTools: matches.map((tool) => tool.definition) })
211
213
  };
212
214
  }
213
215
  assertBudget(base, window, system, selection = this.#selected, executionSelection = this.#executionSelected) {