@myagentroam/agent 0.9.159 → 0.9.160

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 (128) hide show
  1. package/dist/agent-core/extensions/agents.d.ts +69 -0
  2. package/dist/agent-core/extensions/agents.js +160 -0
  3. package/dist/agent-core/extensions/contracts.d.ts +260 -0
  4. package/dist/agent-core/extensions/contracts.js +1 -0
  5. package/dist/agent-core/extensions/data.d.ts +84 -0
  6. package/dist/agent-core/extensions/data.js +83 -0
  7. package/dist/agent-core/extensions/environment.d.ts +27 -0
  8. package/dist/agent-core/extensions/environment.js +52 -0
  9. package/dist/agent-core/extensions/files.d.ts +64 -0
  10. package/dist/agent-core/extensions/files.js +26 -0
  11. package/dist/agent-core/extensions/hooks.d.ts +32 -0
  12. package/dist/agent-core/extensions/hooks.js +135 -0
  13. package/dist/agent-core/extensions/manager.d.ts +39 -0
  14. package/dist/agent-core/extensions/manager.js +458 -0
  15. package/dist/agent-core/extensions/mcp.d.ts +99 -0
  16. package/dist/agent-core/extensions/mcp.js +433 -0
  17. package/dist/agent-core/extensions/model-request.d.ts +60 -0
  18. package/dist/agent-core/extensions/model-request.js +167 -0
  19. package/dist/agent-core/extensions/model-stream.d.ts +9 -0
  20. package/dist/agent-core/extensions/model-stream.js +101 -0
  21. package/dist/agent-core/extensions/models.d.ts +43 -0
  22. package/dist/agent-core/extensions/models.js +1 -0
  23. package/dist/agent-core/extensions/network.d.ts +32 -0
  24. package/dist/agent-core/extensions/network.js +97 -0
  25. package/dist/agent-core/extensions/operation.d.ts +29 -0
  26. package/dist/agent-core/extensions/operation.js +98 -0
  27. package/dist/agent-core/extensions/processes.d.ts +52 -0
  28. package/dist/agent-core/extensions/processes.js +283 -0
  29. package/dist/agent-core/extensions/prompt-composition.d.ts +24 -0
  30. package/dist/agent-core/extensions/prompt-composition.js +106 -0
  31. package/dist/agent-core/extensions/prompt-input.d.ts +23 -0
  32. package/dist/agent-core/extensions/prompt-input.js +46 -0
  33. package/dist/agent-core/extensions/resources.d.ts +27 -0
  34. package/dist/agent-core/extensions/resources.js +221 -0
  35. package/dist/agent-core/extensions/services.d.ts +31 -0
  36. package/dist/agent-core/extensions/services.js +61 -0
  37. package/dist/agent-core/extensions/session-input.d.ts +151 -0
  38. package/dist/agent-core/extensions/session-input.js +351 -0
  39. package/dist/agent-core/extensions/session-messages.d.ts +41 -0
  40. package/dist/agent-core/extensions/session-messages.js +76 -0
  41. package/dist/agent-core/extensions/session.d.ts +68 -0
  42. package/dist/agent-core/extensions/session.js +593 -0
  43. package/dist/agent-core/extensions/settings.d.ts +59 -0
  44. package/dist/agent-core/extensions/settings.js +115 -0
  45. package/dist/agent-core/extensions/store.d.ts +10 -0
  46. package/dist/agent-core/extensions/store.js +131 -0
  47. package/dist/agent-core/extensions/tools.d.ts +61 -0
  48. package/dist/agent-core/extensions/tools.js +266 -0
  49. package/dist/agent-core/host/contracts.d.ts +25 -0
  50. package/dist/agent-core/host/local-agent-host.d.ts +10 -1
  51. package/dist/agent-core/host/local-agent-host.js +132 -20
  52. package/dist/agent-core/host/local-file-access.d.ts +30 -0
  53. package/dist/agent-core/host/local-file-access.js +107 -0
  54. package/dist/agent-core/host/local-network-access.d.ts +6 -0
  55. package/dist/agent-core/host/local-network-access.js +97 -0
  56. package/dist/agent-core/host/local-process-executor.d.ts +5 -1
  57. package/dist/agent-core/host/local-session-environment.d.ts +18 -0
  58. package/dist/agent-core/host/local-session-environment.js +102 -0
  59. package/dist/agent-core/model/anthropic-messages.js +73 -23
  60. package/dist/agent-core/model/contracts.d.ts +12 -0
  61. package/dist/agent-core/model/openai-responses.js +73 -12
  62. package/dist/agent-core/model/text-blocks.d.ts +7 -0
  63. package/dist/agent-core/model/text-blocks.js +40 -0
  64. package/dist/agent-core/prompts/index.d.ts +6 -2
  65. package/dist/agent-core/prompts/index.js +38 -24
  66. package/dist/agent-core/runtime/context/gc-tokens.js +6 -1
  67. package/dist/agent-core/runtime/context/normalize.js +21 -1
  68. package/dist/agent-core/runtime/context/projection.js +35 -1
  69. package/dist/agent-core/runtime/context/request-budget.js +5 -2
  70. package/dist/agent-core/runtime/context/restore.d.ts +5 -0
  71. package/dist/agent-core/runtime/context/restore.js +47 -4
  72. package/dist/agent-core/runtime/context/usage.js +2 -3
  73. package/dist/agent-core/runtime/contracts.d.ts +2 -0
  74. package/dist/agent-core/runtime/execution.js +5 -2
  75. package/dist/agent-core/sdk/agent.js +177 -40
  76. package/dist/agent-core/sdk/extension-agents.d.ts +9 -0
  77. package/dist/agent-core/sdk/extension-agents.js +51 -0
  78. package/dist/agent-core/sdk/extension-models.d.ts +13 -0
  79. package/dist/agent-core/sdk/extension-models.js +128 -0
  80. package/dist/agent-core/sdk/extension-session.d.ts +30 -0
  81. package/dist/agent-core/sdk/extension-session.js +103 -0
  82. package/dist/agent-core/sdk/extension-tools.d.ts +16 -0
  83. package/dist/agent-core/sdk/extension-tools.js +126 -0
  84. package/dist/agent-core/sdk/session.d.ts +26 -2
  85. package/dist/agent-core/sdk/session.js +1215 -506
  86. package/dist/agent-core/sdk/types.d.ts +3 -0
  87. package/dist/agent-core/session/context-gc-checkpoint.js +1 -1
  88. package/dist/agent-core/session/jsonl-store.d.ts +28 -8
  89. package/dist/agent-core/session/jsonl-store.js +124 -84
  90. package/dist/agent-core/session/types.d.ts +4 -1
  91. package/dist/agent-core/storage/file-lock.d.ts +4 -0
  92. package/dist/agent-core/storage/file-lock.js +83 -0
  93. package/dist/agent-core/subagent/contracts.d.ts +11 -1
  94. package/dist/agent-core/subagent/scheduler.d.ts +8 -0
  95. package/dist/agent-core/subagent/session-controller.d.ts +22 -1
  96. package/dist/agent-core/subagent/session-controller.js +355 -98
  97. package/dist/agent-core/tools/agent/agent-start.d.ts +1 -1
  98. package/dist/agent-core/tools/code-mode/cells.js +5 -15
  99. package/dist/agent-core/tools/code-mode/dispatch.d.ts +1 -0
  100. package/dist/agent-core/tools/code-mode/dispatch.js +13 -1
  101. package/dist/agent-core/tools/code-mode/index.js +1 -2
  102. package/dist/agent-core/tools/code-mode/observations.d.ts +5 -0
  103. package/dist/agent-core/tools/code-mode/observations.js +16 -5
  104. package/dist/agent-core/tools/code-mode/quickjs-engine.js +10 -5
  105. package/dist/agent-core/tools/execution.d.ts +11 -2
  106. package/dist/agent-core/tools/execution.js +58 -21
  107. package/dist/agent-core/tools/input.d.ts +2 -0
  108. package/dist/agent-core/tools/input.js +36 -0
  109. package/dist/agent-core/tools/local/apply-patch.js +21 -17
  110. package/dist/agent-core/tools/local/exec.d.ts +4 -4
  111. package/dist/agent-core/tools/local/exec.js +234 -62
  112. package/dist/agent-core/tools/local/registry.d.ts +6 -0
  113. package/dist/agent-core/tools/local/registry.js +60 -9
  114. package/dist/agent-core/tools/mcp/catalog.d.ts +6 -2
  115. package/dist/agent-core/tools/mcp/catalog.js +4 -4
  116. package/dist/agent-core/tools/mcp/history.js +2 -2
  117. package/dist/agent-core/tools/mcp/tool-search.d.ts +3 -1
  118. package/dist/agent-core/tools/mcp/tool-search.js +2 -2
  119. package/dist/agent-core/tools/output-projection.d.ts +3 -1
  120. package/dist/agent-core/tools/output-projection.js +11 -2
  121. package/dist/agent-core/tools/runtime-context.d.ts +1 -0
  122. package/dist/agent-core/tools/runtime.d.ts +3 -1
  123. package/dist/agent-core/tools/runtime.js +22 -7
  124. package/dist/agent-core/tools/scheduler.d.ts +2 -0
  125. package/dist/agent-core/tools/scheduler.js +43 -6
  126. package/dist/index.d.ts +21 -0
  127. package/dist/sandbox/linux/bubblewrap-sandbox-executor.js +5 -2
  128. package/package.json +1 -1
@@ -3,6 +3,7 @@ import { StringDecoder } from 'node:string_decoder';
3
3
  import { MarAgentError } from '../../error.js';
4
4
  import { directLocalProcessExecutor, signalProcessTree } from '../../host/local-process-executor.js';
5
5
  import { TOOL_EXECUTION_LIMITS } from '../execution-limits.js';
6
+ import { validateCoreProcessInput } from '../../extensions/processes.js';
6
7
  export const execToolDefinition = {
7
8
  name: 'exec',
8
9
  allowedCallers: ['direct', 'programmatic'],
@@ -144,7 +145,9 @@ export class ExecTool {
144
145
  this.#removeCompleted(input.processId);
145
146
  return { ...completed.result, cached: true };
146
147
  }
147
- if (!process || (owner !== undefined && process.ownerSessionId !== owner.sessionId))
148
+ if (!process ||
149
+ process.native ||
150
+ (owner !== undefined && process.ownerSessionId !== owner.sessionId))
148
151
  throw new MarAgentError('MAR_AGENT_PROCESS_NOT_FOUND', 'Managed process was not found.');
149
152
  if (input.action === 'poll' && input.yieldMs)
150
153
  await waitForProcessChange(process, Math.min(Math.max(input.yieldMs, 0), TOOL_EXECUTION_LIMITS.execMaxPollYieldMs), signal);
@@ -160,36 +163,63 @@ export class ExecTool {
160
163
  }
161
164
  return result;
162
165
  }
166
+ const { id, managed } = await this.#startManaged(async () => {
167
+ const cwd = await this.paths.resolveWithDisplay(input.cwd ?? '.');
168
+ return {
169
+ command: input.command,
170
+ cwd: cwd.physicalPath,
171
+ shell: this.shell ?? true,
172
+ environment: this.environment,
173
+ displayCwd: cwd.displayPath,
174
+ detached: process.platform !== 'win32',
175
+ ...(owner === undefined ? {} : { owner }),
176
+ ...(signal === undefined ? {} : { signal })
177
+ };
178
+ }, owner?.sessionId, false);
179
+ managed.timer = setTimeout(() => {
180
+ void this.#terminate(managed, true).then(() => this.#retainCompleted(id, managed));
181
+ }, Math.min(input.timeoutMs ?? TOOL_EXECUTION_LIMITS.execDefaultTimeoutMs, TOOL_EXECUTION_LIMITS.execMaxTimeoutMs));
182
+ managed.timer.unref();
183
+ await waitForExitOrDelay(managed.settled, Math.min(input.yieldMs ?? TOOL_EXECUTION_LIMITS.execDefaultYieldMs, TOOL_EXECUTION_LIMITS.execMaxYieldMs), signal);
184
+ const result = this.#result(id, managed);
185
+ if (managed.status !== 'running')
186
+ this.#retainCompleted(id, managed);
187
+ return result;
188
+ }
189
+ async #startManaged(request, ownerSessionId, native) {
163
190
  if (this.#processes.size + this.#startingProcesses.size >= this.maxProcesses)
164
191
  throw new MarAgentError('MAR_AGENT_PROCESS_LIMIT', `The Local Host shared managed-process limit (${this.maxProcesses}) was reached.`);
165
192
  let resolveStarting;
166
193
  const starting = {
167
- ...(owner === undefined ? {} : { ownerSessionId: owner.sessionId }),
194
+ ...(ownerSessionId === undefined ? {} : { ownerSessionId }),
168
195
  settled: new Promise((resolve) => (resolveStarting = resolve)),
169
196
  resolveSettled: () => resolveStarting()
170
197
  };
171
198
  this.#startingProcesses.add(starting);
172
- const id = randomUUID();
173
- let child;
174
- let managed;
175
199
  try {
176
- const cwd = await this.paths.resolveWithDisplay(input.cwd ?? '.');
177
- child = await this.processExecutor.spawn({
178
- command: input.command,
179
- cwd: cwd.physicalPath,
180
- shell: this.shell ?? true,
181
- environment: this.environment,
182
- detached: process.platform !== 'win32',
183
- ...(owner === undefined ? {} : { owner }),
184
- ...(signal === undefined ? {} : { signal })
185
- });
200
+ const { displayCwd, ...input } = await request();
201
+ input.signal?.throwIfAborted();
202
+ let child;
203
+ try {
204
+ child = await this.processExecutor.spawn(input);
205
+ }
206
+ catch (error) {
207
+ input.signal?.throwIfAborted();
208
+ if (!native || error instanceof MarAgentError)
209
+ throw error;
210
+ throw new MarAgentError('MAR_AGENT_PROCESS_START_FAILED', 'Native process executor failed to start.', {
211
+ details: { reasonCode: error?.code ?? 'UNKNOWN' }
212
+ });
213
+ }
214
+ const id = randomUUID();
186
215
  let resolveExited;
187
216
  let resolveSettled;
188
- managed = {
217
+ const managed = {
189
218
  child,
190
- ...(owner === undefined ? {} : { ownerSessionId: owner.sessionId }),
219
+ native,
220
+ ...(ownerSessionId === undefined ? {} : { ownerSessionId }),
191
221
  command: input.command,
192
- cwd: cwd.displayPath,
222
+ cwd: displayCwd ?? input.cwd,
193
223
  stdout: createOutputBuffer(),
194
224
  stderr: createOutputBuffer(),
195
225
  stdoutHistory: createOutputBuffer(),
@@ -199,65 +229,199 @@ export class ExecTool {
199
229
  settled: new Promise((resolve) => (resolveSettled = resolve)),
200
230
  resolveExited,
201
231
  resolveSettled,
202
- exitObserved: child.exitCode !== null,
232
+ exitObserved: child.exitCode !== null || child.signalCode != null,
233
+ ...(child.exitCode === null ? {} : { exitCode: child.exitCode }),
234
+ ...(child.signalCode == null ? {} : { exitSignal: child.signalCode }),
203
235
  finalized: false,
204
236
  waiters: new Set()
205
237
  };
206
238
  this.#processes.set(id, managed);
239
+ if (native) {
240
+ // Keep unread bytes in the Readable buffer: Node otherwise resumes unused stdio at exit.
241
+ const readable = () => { };
242
+ child.stdout.on('readable', readable);
243
+ child.stderr.on('readable', readable);
244
+ child.once('close', () => {
245
+ child.stdout.removeListener('readable', readable);
246
+ child.stderr.removeListener('readable', readable);
247
+ });
248
+ }
249
+ if (!native) {
250
+ const listen = (name) => child[name].on('data', (chunk) => {
251
+ if (managed.finalized)
252
+ return;
253
+ const decoded = Buffer.from(managed[name].decoder.write(chunk));
254
+ appendOutput(managed[name], decoded, this.maxOutputBytes, chunk.length);
255
+ appendOutput(managed[name === 'stdout' ? 'stdoutHistory' : 'stderrHistory'], decoded, this.maxOutputBytes, chunk.length);
256
+ notifyProcessChange(managed);
257
+ });
258
+ listen('stdout');
259
+ listen('stderr');
260
+ }
261
+ child.once('exit', (code, signal) => {
262
+ managed.exitObserved = true;
263
+ managed.exitCode = code;
264
+ managed.exitSignal = signal;
265
+ managed.resolveExited();
266
+ if (!native)
267
+ void finalizeAfterOutputGrace(managed, this.maxOutputBytes).then(() => this.#retainCompleted(id, managed));
268
+ });
269
+ child.once('close', (code, signal) => {
270
+ managed.exitObserved = true;
271
+ managed.exitSignal = signal;
272
+ managed.resolveExited();
273
+ finalizeManagedProcess(managed, this.maxOutputBytes, code);
274
+ if (native)
275
+ this.#processes.delete(id);
276
+ else
277
+ this.#retainCompleted(id, managed);
278
+ });
279
+ child.once('error', (error) => {
280
+ if (managed.finalized)
281
+ return;
282
+ if (native) {
283
+ managed.failure = new MarAgentError('MAR_AGENT_PROCESS_START_FAILED', 'Native process failed to start.', {
284
+ details: { reasonCode: error.code ?? 'UNKNOWN' }
285
+ });
286
+ managed.exitObserved = true;
287
+ managed.resolveExited();
288
+ }
289
+ else {
290
+ const message = Buffer.from(error.message);
291
+ appendOutput(managed.stderr, message, this.maxOutputBytes);
292
+ appendOutput(managed.stderrHistory, message, this.maxOutputBytes);
293
+ notifyProcessChange(managed);
294
+ }
295
+ });
296
+ if (managed.exitObserved) {
297
+ managed.resolveExited();
298
+ if (child.stdout.closed && child.stderr.closed) {
299
+ finalizeManagedProcess(managed, this.maxOutputBytes, child.exitCode);
300
+ if (native)
301
+ this.#processes.delete(id);
302
+ else
303
+ this.#retainCompleted(id, managed);
304
+ }
305
+ }
306
+ return { id, managed };
207
307
  }
208
308
  finally {
209
309
  this.#startingProcesses.delete(starting);
210
310
  starting.resolveSettled();
211
311
  }
212
- child.stdout.on('data', (chunk) => {
213
- if (managed.finalized)
214
- return;
215
- const decoded = Buffer.from(managed.stdout.decoder.write(chunk));
216
- appendOutput(managed.stdout, decoded, this.maxOutputBytes, chunk.length);
217
- appendOutput(managed.stdoutHistory, decoded, this.maxOutputBytes, chunk.length);
218
- notifyProcessChange(managed);
312
+ }
313
+ async spawn(input, call) {
314
+ validateCoreProcessInput(input);
315
+ input = {
316
+ ...input,
317
+ ...(input.argv === undefined ? {} : { argv: [...input.argv] }),
318
+ ...(input.env === undefined ? {} : { env: { ...input.env } }),
319
+ ...(input.input instanceof Uint8Array ? { input: new Uint8Array(input.input) } : {})
320
+ };
321
+ const { id, managed } = await this.#startManaged(async () => {
322
+ const cwd = await this.paths.resolve(input.cwd ?? '.');
323
+ return {
324
+ command: input.executable,
325
+ args: [...(input.argv ?? [])],
326
+ cwd,
327
+ shell: false,
328
+ environment: { ...this.environment, ...input.env },
329
+ environmentKeys: Object.keys(input.env ?? {}),
330
+ ...(input.env === undefined ? {} : { environmentOverrides: input.env }),
331
+ detached: process.platform !== 'win32',
332
+ signal: call.signal,
333
+ owner: {
334
+ sessionId: call.sessionId,
335
+ operationId: call.operationId,
336
+ ...(call.executionId ? { executionId: call.executionId } : {}),
337
+ ...(call.ownerInstanceId ? { ownerInstanceId: call.ownerInstanceId } : {})
338
+ }
339
+ };
340
+ }, call.sessionId, true);
341
+ let cleanup;
342
+ const cancel = () => (cleanup ??= (async () => {
343
+ call.signal.removeEventListener('abort', abort);
344
+ await this.#terminate(managed, false);
345
+ destroyManagedStreams(managed);
346
+ this.#processes.delete(id);
347
+ })());
348
+ const abort = () => {
349
+ void cancel().catch(() => undefined);
350
+ };
351
+ call.signal.addEventListener('abort', abort, { once: true });
352
+ managed.child.once('close', () => call.signal.removeEventListener('abort', abort));
353
+ managed.child.stdin.on('error', (error) => {
354
+ if (error.code !== 'EPIPE' && !cleanup)
355
+ managed.failure = new MarAgentError('MAR_AGENT_PROCESS_IO_FAILED', 'Native process input failed.', {
356
+ details: { reasonCode: error.code ?? 'UNKNOWN' }
357
+ });
219
358
  });
220
- child.stderr.on('data', (chunk) => {
221
- if (managed.finalized)
359
+ managed.child.stdin.end(input.input);
360
+ if (call.signal.aborted) {
361
+ await cancel();
362
+ call.signal.throwIfAborted();
363
+ }
364
+ const opened = new Promise((resolve, reject) => {
365
+ if (managed.child.pid) {
366
+ resolve();
222
367
  return;
223
- const decoded = Buffer.from(managed.stderr.decoder.write(chunk));
224
- appendOutput(managed.stderr, decoded, this.maxOutputBytes, chunk.length);
225
- appendOutput(managed.stderrHistory, decoded, this.maxOutputBytes, chunk.length);
226
- notifyProcessChange(managed);
227
- });
228
- child.once('exit', (code) => {
229
- managed.exitObserved = true;
230
- managed.exitCode = code;
231
- managed.resolveExited();
232
- void finalizeAfterOutputGrace(managed, this.maxOutputBytes).then(() => this.#retainCompleted(id, managed));
233
- });
234
- child.once('close', (code) => {
235
- managed.exitObserved = true;
236
- managed.resolveExited();
237
- finalizeManagedProcess(managed, this.maxOutputBytes, code);
238
- this.#retainCompleted(id, managed);
239
- });
240
- child.once('error', (error) => {
241
- if (managed.finalized)
368
+ }
369
+ if (managed.failure) {
370
+ reject(managed.failure);
242
371
  return;
243
- const message = Buffer.from(error.message);
244
- appendOutput(managed.stderr, message, this.maxOutputBytes);
245
- appendOutput(managed.stderrHistory, message, this.maxOutputBytes);
246
- notifyProcessChange(managed);
372
+ }
373
+ const spawned = () => {
374
+ managed.child.removeListener('error', failed);
375
+ resolve();
376
+ };
377
+ const failed = () => {
378
+ managed.child.removeListener('spawn', spawned);
379
+ reject(managed.failure);
380
+ };
381
+ managed.child.once('spawn', spawned);
382
+ managed.child.once('error', failed);
247
383
  });
248
- managed.timer = setTimeout(() => {
249
- void this.#terminate(managed, true).then(() => this.#retainCompleted(id, managed));
250
- }, Math.min(input.timeoutMs ?? TOOL_EXECUTION_LIMITS.execDefaultTimeoutMs, TOOL_EXECUTION_LIMITS.execMaxTimeoutMs));
251
- managed.timer.unref();
252
- await waitForExitOrDelay(managed.settled, Math.min(input.yieldMs ?? TOOL_EXECUTION_LIMITS.execDefaultYieldMs, TOOL_EXECUTION_LIMITS.execMaxYieldMs), signal);
253
- const result = this.#result(id, managed);
254
- if (managed.status !== 'running')
255
- this.#retainCompleted(id, managed);
256
- return result;
384
+ try {
385
+ await opened;
386
+ }
387
+ catch (error) {
388
+ await cancel();
389
+ throw error;
390
+ }
391
+ const stream = (name) => ({
392
+ async *[Symbol.asyncIterator]() {
393
+ try {
394
+ for await (const chunk of managed.child[name])
395
+ yield new Uint8Array(chunk);
396
+ }
397
+ catch (error) {
398
+ if (!cleanup && !call.signal.aborted)
399
+ throw new MarAgentError('MAR_AGENT_PROCESS_IO_FAILED', 'Native process output failed.', {
400
+ details: {
401
+ stream: name,
402
+ reasonCode: error.code ?? 'UNKNOWN'
403
+ }
404
+ });
405
+ }
406
+ }
407
+ });
408
+ return {
409
+ processId: id,
410
+ stdout: stream('stdout'),
411
+ stderr: stream('stderr'),
412
+ cancel,
413
+ wait: async () => {
414
+ await managed.exited;
415
+ call.signal.throwIfAborted();
416
+ if (managed.failure)
417
+ throw managed.failure;
418
+ return { code: managed.exitCode ?? null, signal: managed.exitSignal ?? null };
419
+ }
420
+ };
257
421
  }
258
422
  listSessionResources(sessionId) {
259
423
  return [
260
- ...[...this.#processes.entries()].flatMap(([processId, process]) => process.ownerSessionId === sessionId
424
+ ...[...this.#processes.entries()].flatMap(([processId, process]) => !process.native && process.ownerSessionId === sessionId
261
425
  ? [{ processId, status: process.status, command: process.command, cwd: process.cwd }]
262
426
  : []),
263
427
  ...[...this.#completed.entries()].flatMap(([processId, process]) => process.ownerSessionId === sessionId
@@ -292,7 +456,10 @@ export class ExecTool {
292
456
  this.#completed.delete(id);
293
457
  }
294
458
  #retainCompleted(id, process) {
295
- if (process.status === 'running' || !process.finalized || this.#processes.get(id) !== process)
459
+ if (process.native ||
460
+ process.status === 'running' ||
461
+ !process.finalized ||
462
+ this.#processes.get(id) !== process)
296
463
  return;
297
464
  this.#processes.delete(id);
298
465
  const stdout = consumeOutput(process.stdoutHistory);
@@ -325,6 +492,8 @@ export class ExecTool {
325
492
  return managed.terminate;
326
493
  managed.terminate = (async () => {
327
494
  if (managed.exitObserved || managed.child.exitCode !== null) {
495
+ if (managed.native && !managed.finalized)
496
+ await signalProcessTree(managed.child, 'SIGKILL');
328
497
  if (managed.child.exitCode !== null)
329
498
  managed.exitCode = managed.child.exitCode;
330
499
  if (waitForOutputClose) {
@@ -345,6 +514,9 @@ export class ExecTool {
345
514
  await signalProcessTree(managed.child, 'SIGKILL');
346
515
  await managed.exited;
347
516
  }
517
+ // A parent may exit on TERM while descendants ignore it and keep the pipes alive.
518
+ if (managed.native)
519
+ await signalProcessTree(managed.child, 'SIGKILL');
348
520
  if (waitForOutputClose) {
349
521
  const settled = await waitForExit(managed.settled, TOOL_EXECUTION_LIMITS.execTerminationGraceMs);
350
522
  if (settled)
@@ -1,9 +1,13 @@
1
+ import { LocalFileAccess } from '../../host/local-file-access.js';
1
2
  import type { LocalProcessExecutor } from '../../host/local-process-executor.js';
2
3
  import type { CodeModeEngineFactory } from '../code-mode/engine.js';
3
4
  import type { ToolCall, ToolExecutionContext, ToolExecutionResult } from '../contracts.js';
4
5
  import { type WorkspacePathMount } from '../shared/path-resolver.js';
6
+ import type { CoreOperationContext } from '../../extensions/operation.js';
5
7
  export declare class LocalToolRegistry {
6
8
  #private;
9
+ readonly processes: import('../../extensions/processes.js').CoreProcessesBackend;
10
+ readonly files: LocalFileAccess;
7
11
  constructor(workspace: string, environment?: NodeJS.ProcessEnv, shell?: string, options?: {
8
12
  processExecutor?: LocalProcessExecutor;
9
13
  codeModeEngineFactory?: CodeModeEngineFactory;
@@ -12,6 +16,8 @@ export declare class LocalToolRegistry {
12
16
  pathMounts?: readonly WorkspacePathMount[];
13
17
  });
14
18
  execute(call: ToolCall, context: ToolExecutionContext): Promise<ToolExecutionResult>;
19
+ names(): readonly string[];
20
+ executeOperation(call: ToolCall, operation: CoreOperationContext): Promise<ToolExecutionResult>;
15
21
  listSessionResources(sessionId: string): {
16
22
  processId: string;
17
23
  status: "completed" | "cancelled" | "running";
@@ -1,11 +1,29 @@
1
1
  import { MarAgentError } from '../../error.js';
2
- import { ApplyPatchTool, applyPatchToolInput } from './apply-patch.js';
3
- import { CodeModeTool } from '../code-mode/index.js';
4
- import { ExecTool, execToolInput } from './exec.js';
5
- import { ReadTool, formatBatchReadOutput } from './read.js';
2
+ import { LocalFileAccess } from '../../host/local-file-access.js';
3
+ import { ApplyPatchTool, applyPatchToolInput, applyPatchToolDefinition } from './apply-patch.js';
4
+ import { CodeModeTool, codeModeToolDefinition, codeExecWaitToolDefinition } from '../code-mode/index.js';
5
+ import { normalizeToolInput } from '../input.js';
6
+ import { ExecTool, execToolInput, execToolDefinition, execWaitToolDefinition } from './exec.js';
7
+ import { ReadTool, formatBatchReadOutput, readToolDefinition } from './read.js';
6
8
  import { WorkspacePathResolver } from '../shared/path-resolver.js';
7
- import { ViewImageTool } from './view-image.js';
9
+ import { ViewImageTool, viewImageToolDefinition } from './view-image.js';
10
+ const definitions = [
11
+ readToolDefinition,
12
+ viewImageToolDefinition,
13
+ applyPatchToolDefinition,
14
+ execToolDefinition,
15
+ execWaitToolDefinition,
16
+ codeModeToolDefinition,
17
+ codeExecWaitToolDefinition
18
+ ];
19
+ function executionContext(context) {
20
+ if (!context.executionId)
21
+ throw new MarAgentError('MAR_AGENT_TOOL_NOT_AVAILABLE', 'Tool requires a real Execution.');
22
+ return { ...context, executionId: context.executionId };
23
+ }
8
24
  export class LocalToolRegistry {
25
+ processes;
26
+ files;
9
27
  #exec;
10
28
  #code;
11
29
  #handlers;
@@ -17,14 +35,22 @@ export class LocalToolRegistry {
17
35
  : { rootWritable: options.workspaceWritable }),
18
36
  ...(options.pathMounts === undefined ? {} : { mounts: options.pathMounts })
19
37
  });
38
+ this.files = new LocalFileAccess(paths);
20
39
  const read = new ReadTool(paths);
21
40
  const viewImage = new ViewImageTool(paths);
22
41
  const patch = new ApplyPatchTool(paths);
23
42
  this.#exec = new ExecTool(paths, undefined, undefined, environment, shell, options.processExecutor);
43
+ this.processes = { spawn: (input, call) => this.#exec.spawn(input, call) };
24
44
  this.#code = new CodeModeTool(paths, environment, options.processExecutor, options.codeModeEngineFactory);
25
45
  this.#handlers = new Map([
26
- ['code_exec', (arguments_, context) => this.#code.start(arguments_, context)],
27
- ['code_exec_wait', (arguments_, context) => this.#code.wait(arguments_, context)],
46
+ [
47
+ 'code_exec',
48
+ (arguments_, context) => this.#code.start(arguments_, executionContext(context))
49
+ ],
50
+ [
51
+ 'code_exec_wait',
52
+ (arguments_, context) => this.#code.wait(arguments_, executionContext(context))
53
+ ],
28
54
  [
29
55
  'read',
30
56
  async (arguments_, context) => {
@@ -53,7 +79,17 @@ export class LocalToolRegistry {
53
79
  async (arguments_, context) => {
54
80
  const result = await this.#exec.execute(execToolInput(name, arguments_), context.signal, {
55
81
  sessionId: context.sessionId,
56
- executionId: context.executionId
82
+ ...(context.executionId === undefined
83
+ ? {}
84
+ : { executionId: context.executionId }),
85
+ ...(context.operation === undefined
86
+ ? {}
87
+ : {
88
+ operationId: context.operation.operationId,
89
+ ...(context.operation.ownerInstanceId === undefined
90
+ ? {}
91
+ : { ownerInstanceId: context.operation.ownerInstanceId })
92
+ })
57
93
  });
58
94
  return { content: JSON.stringify(result), data: result, truncated: result.truncated };
59
95
  }
@@ -64,7 +100,22 @@ export class LocalToolRegistry {
64
100
  const handler = this.#handlers.get(call.name);
65
101
  if (!handler)
66
102
  throw new MarAgentError('MAR_AGENT_TOOL_NOT_AVAILABLE', 'Tool is unavailable.');
67
- return handler(call.arguments, context);
103
+ return handler(normalizeToolInput(call.arguments, definitions.find((tool) => tool.name === call.name).inputSchema), context);
104
+ }
105
+ names() {
106
+ return [...this.#handlers.keys()];
107
+ }
108
+ executeOperation(call, operation) {
109
+ const handler = this.#handlers.get(call.name);
110
+ if (!handler)
111
+ throw new MarAgentError('MAR_AGENT_TOOL_NOT_AVAILABLE', 'Tool is unavailable.');
112
+ return handler(normalizeToolInput(call.arguments, definitions.find((tool) => tool.name === call.name).inputSchema), {
113
+ mode: 'run',
114
+ signal: operation.signal,
115
+ sessionId: operation.sessionId,
116
+ ...(operation.executionId === undefined ? {} : { executionId: operation.executionId }),
117
+ operation
118
+ });
68
119
  }
69
120
  listSessionResources(sessionId) {
70
121
  return this.#exec.listSessionResources(sessionId);
@@ -8,5 +8,9 @@ export declare const MCP_DEFINITION_LIMITS: Readonly<{
8
8
  servers: 256;
9
9
  }>;
10
10
  /** Shared Host and Node publication boundary, not a provider-specific conversion. */
11
- export declare function assertMcpToolDefinition(value: unknown): asserts value is ClientToolDefinition;
12
- export declare function assertMcpToolCatalog(value: unknown): asserts value is McpToolCatalog;
11
+ export declare function assertMcpToolDefinition(value: unknown, options?: {
12
+ nativeToolNames?: boolean;
13
+ }): asserts value is ClientToolDefinition;
14
+ export declare function assertMcpToolCatalog(value: unknown, options?: {
15
+ nativeToolNames?: boolean;
16
+ }): asserts value is McpToolCatalog;
@@ -136,10 +136,10 @@ function assertSchema(schema) {
136
136
  }
137
137
  }
138
138
  /** Shared Host and Node publication boundary, not a provider-specific conversion. */
139
- export function assertMcpToolDefinition(value) {
139
+ export function assertMcpToolDefinition(value, options = {}) {
140
140
  if (!record(value) ||
141
141
  !text(value.name, 256) ||
142
- !/^mcp__[A-Za-z0-9_-]+__[A-Za-z0-9_-]+$/u.test(value.name) ||
142
+ (!options.nativeToolNames && !/^mcp__[A-Za-z0-9_-]+__[A-Za-z0-9_-]+$/u.test(value.name)) ||
143
143
  typeof value.description !== 'string' ||
144
144
  value.description.length > 65536 ||
145
145
  (value.parallelSafety !== undefined &&
@@ -159,7 +159,7 @@ export function assertMcpToolDefinition(value) {
159
159
  if (Buffer.byteLength(JSON.stringify(value)) > MCP_DEFINITION_LIMITS.definitionBytes)
160
160
  invalid();
161
161
  }
162
- export function assertMcpToolCatalog(value) {
162
+ export function assertMcpToolCatalog(value, options = {}) {
163
163
  if (!record(value) ||
164
164
  typeof value.revision !== 'string' ||
165
165
  value.revision.length > 512 ||
@@ -204,7 +204,7 @@ export function assertMcpToolCatalog(value) {
204
204
  !['session', 'execution'].includes(String(tool.lifetime)) ||
205
205
  !['direct', 'deferred'].includes(String(tool.exposure)))
206
206
  invalid();
207
- assertMcpToolDefinition(tool.definition);
207
+ assertMcpToolDefinition(tool.definition, options);
208
208
  if (tool.annotations !== undefined) {
209
209
  if (!record(tool.annotations))
210
210
  invalid();
@@ -4,8 +4,8 @@ export function discoveredMcpToolNames(messages) {
4
4
  const names = new Set();
5
5
  for (const message of messages)
6
6
  for (const tool of calls.has(message.callId ?? '') ? (message.toolSearchTools ?? []) : [])
7
- if (tool.name.startsWith('mcp__'))
8
- names.add(tool.name);
7
+ // Paired discovery receipts provide candidates; the current captured MCP catalog is authority.
8
+ names.add(tool.name);
9
9
  return [...names];
10
10
  }
11
11
  export function rebindMcpToolSearchOutputs(messages, registry) {
@@ -20,7 +20,9 @@ export declare class DeferredMcpRegistry {
20
20
  #private;
21
21
  constructor(discoveredNames: readonly string[]);
22
22
  restore(discoveredNames: readonly string[]): void;
23
- update(catalog: McpToolCatalog, eligible: (tool: McpCatalogTool) => boolean): void;
23
+ update(catalog: McpToolCatalog, eligible: (tool: McpCatalogTool) => boolean, options?: {
24
+ nativeToolNames?: boolean;
25
+ }): void;
24
26
  get hasDeferred(): boolean;
25
27
  snapshot(): readonly string[];
26
28
  expectedTool(name: string): {
@@ -63,8 +63,8 @@ export class DeferredMcpRegistry {
63
63
  // GC may remove evidence, but cannot grant a capability from another Execution.
64
64
  this.#executionSelected = new Set([...this.#executionSelected].filter((name) => surviving.has(name)));
65
65
  }
66
- update(catalog, eligible) {
67
- assertMcpToolCatalog(catalog);
66
+ update(catalog, eligible, options = {}) {
67
+ assertMcpToolCatalog(catalog, options);
68
68
  this.#catalog = { ...catalog, tools: catalog.tools.filter(eligible) };
69
69
  const validSession = new Set(this.#catalog.tools
70
70
  .filter((tool) => tool.lifetime === 'session' && tool.exposure === 'deferred')
@@ -1,5 +1,5 @@
1
1
  import type { SubagentTaskSnapshot } from '../subagent/contracts.js';
2
- import type { ApplyPatchResult, CodeCellEventData, ExecResult, MarAgentToolArtifact, ReadEventData, ViewImageResult } from './contracts.js';
2
+ import type { ApplyPatchResult, CodeCellEventData, ExecResult, MarAgentToolArtifact, ToolExecutionResult, ReadEventData, ViewImageResult } from './contracts.js';
3
3
  import type { ToolRuntimeImage } from './runtime-context.js';
4
4
  export declare function currentExecutionImages(modelInputImages: readonly {
5
5
  readonly mimeType: string;
@@ -12,3 +12,5 @@ export declare function boundedModelToolOutput(toolName: string, value: string,
12
12
  /** Project only known, validated tool result shapes into public structured events. */
13
13
  export declare function structuredToolEventData(toolName: string, value: unknown): CodeCellEventData | ExecResult | ApplyPatchResult | ReadEventData | ViewImageResult | SubagentTaskSnapshot | undefined;
14
14
  export declare function structuredToolArtifacts(value: readonly MarAgentToolArtifact[] | undefined): readonly MarAgentToolArtifact[] | undefined;
15
+ /** Shared result contract for model, programmatic, and native API callers. */
16
+ export declare function validateToolResult(value: ToolExecutionResult): ToolExecutionResult;
@@ -149,8 +149,10 @@ export function structuredToolEventData(toolName, value) {
149
149
  export function structuredToolArtifacts(value) {
150
150
  if (value === undefined)
151
151
  return undefined;
152
- if (value.length !== 1 ||
153
- value.some((artifact) => artifact.kind !== 'image' ||
152
+ if (!Array.isArray(value) ||
153
+ value.length !== 1 ||
154
+ value.some((artifact) => !artifact ||
155
+ artifact.kind !== 'image' ||
154
156
  artifact.mimeType !== 'image/png' ||
155
157
  typeof artifact.name !== 'string' ||
156
158
  artifact.name.length === 0 ||
@@ -162,6 +164,13 @@ export function structuredToolArtifacts(value) {
162
164
  throw new MarAgentError('MAR_AGENT_TOOL_OUTPUT_INVALID', 'Tool image artifact is invalid.');
163
165
  return value.map((artifact) => ({ ...artifact }));
164
166
  }
167
+ /** Shared result contract for model, programmatic, and native API callers. */
168
+ export function validateToolResult(value) {
169
+ if (!value || typeof value.content !== 'string')
170
+ throw new MarAgentError('MAR_AGENT_TOOL_OUTPUT_INVALID', 'Tool result must contain string content.');
171
+ const artifacts = structuredToolArtifacts(value.artifacts);
172
+ return artifacts === undefined ? value : { ...value, artifacts };
173
+ }
165
174
  function isRecord(value) {
166
175
  return value !== null && typeof value === 'object' && !Array.isArray(value);
167
176
  }
@@ -51,5 +51,6 @@ export interface ToolRuntimeContext {
51
51
  recentImages?: readonly ToolRuntimeImage[];
52
52
  searchMcpTools?: (input: unknown, signal: AbortSignal) => Promise<import('./contracts.js').ToolExecutionResult>;
53
53
  expectedMcpTool?: import('./contracts.js').McpToolCallContext['expectedTool'];
54
+ invokeTool?: (call: import('./contracts.js').ToolCall, context: ToolRuntimeContext, caller: import('./contracts.js').ToolCaller) => Promise<import('./contracts.js').ToolExecutionResult>;
54
55
  emit(event: ToolRuntimeEvent): Promise<void>;
55
56
  }
@@ -1,2 +1,4 @@
1
1
  import type { ToolRuntimeContext } from './runtime-context.js';
2
- export declare function executeRegisteredTool(name: string, arguments_: unknown, callId: string, context: ToolRuntimeContext): Promise<import("./contracts.js").ToolExecutionResult>;
2
+ export declare function executeRegisteredTool(name: string, arguments_: unknown, callId: string, context: ToolRuntimeContext, caller?: import('./contracts.js').ToolCaller): Promise<import("./contracts.js").ToolExecutionResult>;
3
+ /** Invoke an already captured source; names never reselect a different backend. */
4
+ export declare function executeCapturedTool(kind: 'builtin' | 'host' | 'mcp', call: import('./contracts.js').ToolCall, context: ToolRuntimeContext): Promise<import('./contracts.js').ToolExecutionResult>;