@myagentroam/agent 0.9.159 → 0.9.161

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 (130) 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-limits.d.ts +0 -1
  106. package/dist/agent-core/tools/execution-limits.js +0 -1
  107. package/dist/agent-core/tools/execution.d.ts +11 -2
  108. package/dist/agent-core/tools/execution.js +58 -21
  109. package/dist/agent-core/tools/input.d.ts +2 -0
  110. package/dist/agent-core/tools/input.js +36 -0
  111. package/dist/agent-core/tools/local/apply-patch.js +21 -17
  112. package/dist/agent-core/tools/local/exec.d.ts +4 -4
  113. package/dist/agent-core/tools/local/exec.js +242 -63
  114. package/dist/agent-core/tools/local/registry.d.ts +6 -0
  115. package/dist/agent-core/tools/local/registry.js +60 -9
  116. package/dist/agent-core/tools/mcp/catalog.d.ts +6 -2
  117. package/dist/agent-core/tools/mcp/catalog.js +4 -4
  118. package/dist/agent-core/tools/mcp/history.js +2 -2
  119. package/dist/agent-core/tools/mcp/tool-search.d.ts +3 -1
  120. package/dist/agent-core/tools/mcp/tool-search.js +2 -2
  121. package/dist/agent-core/tools/output-projection.d.ts +3 -1
  122. package/dist/agent-core/tools/output-projection.js +11 -2
  123. package/dist/agent-core/tools/runtime-context.d.ts +1 -0
  124. package/dist/agent-core/tools/runtime.d.ts +3 -1
  125. package/dist/agent-core/tools/runtime.js +22 -7
  126. package/dist/agent-core/tools/scheduler.d.ts +2 -0
  127. package/dist/agent-core/tools/scheduler.js +43 -6
  128. package/dist/index.d.ts +21 -0
  129. package/dist/sandbox/linux/bubblewrap-sandbox-executor.js +5 -2
  130. 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'],
@@ -52,7 +53,12 @@ export const execToolDefinition = {
52
53
  type: 'string',
53
54
  description: 'Optional relative/absolute start directory; defaults to workspace. Command-internal relative paths resolve from this directory.'
54
55
  },
55
- timeoutMs: { type: 'integer', minimum: 1, maximum: TOOL_EXECUTION_LIMITS.execMaxTimeoutMs },
56
+ timeoutMs: {
57
+ type: 'integer',
58
+ minimum: 1,
59
+ maximum: TOOL_EXECUTION_LIMITS.execMaxTimeoutMs,
60
+ description: 'Optional process lifetime limit in milliseconds. Omitted means no process timeout; yieldMs only controls waiting.'
61
+ },
56
62
  yieldMs: {
57
63
  type: 'integer',
58
64
  minimum: 0,
@@ -144,7 +150,9 @@ export class ExecTool {
144
150
  this.#removeCompleted(input.processId);
145
151
  return { ...completed.result, cached: true };
146
152
  }
147
- if (!process || (owner !== undefined && process.ownerSessionId !== owner.sessionId))
153
+ if (!process ||
154
+ process.native ||
155
+ (owner !== undefined && process.ownerSessionId !== owner.sessionId))
148
156
  throw new MarAgentError('MAR_AGENT_PROCESS_NOT_FOUND', 'Managed process was not found.');
149
157
  if (input.action === 'poll' && input.yieldMs)
150
158
  await waitForProcessChange(process, Math.min(Math.max(input.yieldMs, 0), TOOL_EXECUTION_LIMITS.execMaxPollYieldMs), signal);
@@ -160,36 +168,65 @@ export class ExecTool {
160
168
  }
161
169
  return result;
162
170
  }
171
+ const { id, managed } = await this.#startManaged(async () => {
172
+ const cwd = await this.paths.resolveWithDisplay(input.cwd ?? '.');
173
+ return {
174
+ command: input.command,
175
+ cwd: cwd.physicalPath,
176
+ shell: this.shell ?? true,
177
+ environment: this.environment,
178
+ displayCwd: cwd.displayPath,
179
+ detached: process.platform !== 'win32',
180
+ ...(owner === undefined ? {} : { owner }),
181
+ ...(signal === undefined ? {} : { signal })
182
+ };
183
+ }, owner?.sessionId, false);
184
+ if (input.timeoutMs !== undefined) {
185
+ managed.timer = setTimeout(() => {
186
+ void this.#terminate(managed, true).then(() => this.#retainCompleted(id, managed));
187
+ }, Math.min(input.timeoutMs, TOOL_EXECUTION_LIMITS.execMaxTimeoutMs));
188
+ managed.timer.unref();
189
+ }
190
+ await waitForExitOrDelay(managed.settled, Math.min(input.yieldMs ?? TOOL_EXECUTION_LIMITS.execDefaultYieldMs, TOOL_EXECUTION_LIMITS.execMaxYieldMs), signal);
191
+ const result = this.#result(id, managed);
192
+ if (managed.status !== 'running')
193
+ this.#retainCompleted(id, managed);
194
+ return result;
195
+ }
196
+ async #startManaged(request, ownerSessionId, native) {
163
197
  if (this.#processes.size + this.#startingProcesses.size >= this.maxProcesses)
164
198
  throw new MarAgentError('MAR_AGENT_PROCESS_LIMIT', `The Local Host shared managed-process limit (${this.maxProcesses}) was reached.`);
165
199
  let resolveStarting;
166
200
  const starting = {
167
- ...(owner === undefined ? {} : { ownerSessionId: owner.sessionId }),
201
+ ...(ownerSessionId === undefined ? {} : { ownerSessionId }),
168
202
  settled: new Promise((resolve) => (resolveStarting = resolve)),
169
203
  resolveSettled: () => resolveStarting()
170
204
  };
171
205
  this.#startingProcesses.add(starting);
172
- const id = randomUUID();
173
- let child;
174
- let managed;
175
206
  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
- });
207
+ const { displayCwd, ...input } = await request();
208
+ input.signal?.throwIfAborted();
209
+ let child;
210
+ try {
211
+ child = await this.processExecutor.spawn(input);
212
+ }
213
+ catch (error) {
214
+ input.signal?.throwIfAborted();
215
+ if (!native || error instanceof MarAgentError)
216
+ throw error;
217
+ throw new MarAgentError('MAR_AGENT_PROCESS_START_FAILED', 'Native process executor failed to start.', {
218
+ details: { reasonCode: error?.code ?? 'UNKNOWN' }
219
+ });
220
+ }
221
+ const id = randomUUID();
186
222
  let resolveExited;
187
223
  let resolveSettled;
188
- managed = {
224
+ const managed = {
189
225
  child,
190
- ...(owner === undefined ? {} : { ownerSessionId: owner.sessionId }),
226
+ native,
227
+ ...(ownerSessionId === undefined ? {} : { ownerSessionId }),
191
228
  command: input.command,
192
- cwd: cwd.displayPath,
229
+ cwd: displayCwd ?? input.cwd,
193
230
  stdout: createOutputBuffer(),
194
231
  stderr: createOutputBuffer(),
195
232
  stdoutHistory: createOutputBuffer(),
@@ -199,65 +236,199 @@ export class ExecTool {
199
236
  settled: new Promise((resolve) => (resolveSettled = resolve)),
200
237
  resolveExited,
201
238
  resolveSettled,
202
- exitObserved: child.exitCode !== null,
239
+ exitObserved: child.exitCode !== null || child.signalCode != null,
240
+ ...(child.exitCode === null ? {} : { exitCode: child.exitCode }),
241
+ ...(child.signalCode == null ? {} : { exitSignal: child.signalCode }),
203
242
  finalized: false,
204
243
  waiters: new Set()
205
244
  };
206
245
  this.#processes.set(id, managed);
246
+ if (native) {
247
+ // Keep unread bytes in the Readable buffer: Node otherwise resumes unused stdio at exit.
248
+ const readable = () => { };
249
+ child.stdout.on('readable', readable);
250
+ child.stderr.on('readable', readable);
251
+ child.once('close', () => {
252
+ child.stdout.removeListener('readable', readable);
253
+ child.stderr.removeListener('readable', readable);
254
+ });
255
+ }
256
+ if (!native) {
257
+ const listen = (name) => child[name].on('data', (chunk) => {
258
+ if (managed.finalized)
259
+ return;
260
+ const decoded = Buffer.from(managed[name].decoder.write(chunk));
261
+ appendOutput(managed[name], decoded, this.maxOutputBytes, chunk.length);
262
+ appendOutput(managed[name === 'stdout' ? 'stdoutHistory' : 'stderrHistory'], decoded, this.maxOutputBytes, chunk.length);
263
+ notifyProcessChange(managed);
264
+ });
265
+ listen('stdout');
266
+ listen('stderr');
267
+ }
268
+ child.once('exit', (code, signal) => {
269
+ managed.exitObserved = true;
270
+ managed.exitCode = code;
271
+ managed.exitSignal = signal;
272
+ managed.resolveExited();
273
+ if (!native)
274
+ void finalizeAfterOutputGrace(managed, this.maxOutputBytes).then(() => this.#retainCompleted(id, managed));
275
+ });
276
+ child.once('close', (code, signal) => {
277
+ managed.exitObserved = true;
278
+ managed.exitSignal = signal;
279
+ managed.resolveExited();
280
+ finalizeManagedProcess(managed, this.maxOutputBytes, code);
281
+ if (native)
282
+ this.#processes.delete(id);
283
+ else
284
+ this.#retainCompleted(id, managed);
285
+ });
286
+ child.once('error', (error) => {
287
+ if (managed.finalized)
288
+ return;
289
+ if (native) {
290
+ managed.failure = new MarAgentError('MAR_AGENT_PROCESS_START_FAILED', 'Native process failed to start.', {
291
+ details: { reasonCode: error.code ?? 'UNKNOWN' }
292
+ });
293
+ managed.exitObserved = true;
294
+ managed.resolveExited();
295
+ }
296
+ else {
297
+ const message = Buffer.from(error.message);
298
+ appendOutput(managed.stderr, message, this.maxOutputBytes);
299
+ appendOutput(managed.stderrHistory, message, this.maxOutputBytes);
300
+ notifyProcessChange(managed);
301
+ }
302
+ });
303
+ if (managed.exitObserved) {
304
+ managed.resolveExited();
305
+ if (child.stdout.closed && child.stderr.closed) {
306
+ finalizeManagedProcess(managed, this.maxOutputBytes, child.exitCode);
307
+ if (native)
308
+ this.#processes.delete(id);
309
+ else
310
+ this.#retainCompleted(id, managed);
311
+ }
312
+ }
313
+ return { id, managed };
207
314
  }
208
315
  finally {
209
316
  this.#startingProcesses.delete(starting);
210
317
  starting.resolveSettled();
211
318
  }
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);
319
+ }
320
+ async spawn(input, call) {
321
+ validateCoreProcessInput(input);
322
+ input = {
323
+ ...input,
324
+ ...(input.argv === undefined ? {} : { argv: [...input.argv] }),
325
+ ...(input.env === undefined ? {} : { env: { ...input.env } }),
326
+ ...(input.input instanceof Uint8Array ? { input: new Uint8Array(input.input) } : {})
327
+ };
328
+ const { id, managed } = await this.#startManaged(async () => {
329
+ const cwd = await this.paths.resolve(input.cwd ?? '.');
330
+ return {
331
+ command: input.executable,
332
+ args: [...(input.argv ?? [])],
333
+ cwd,
334
+ shell: false,
335
+ environment: { ...this.environment, ...input.env },
336
+ environmentKeys: Object.keys(input.env ?? {}),
337
+ ...(input.env === undefined ? {} : { environmentOverrides: input.env }),
338
+ detached: process.platform !== 'win32',
339
+ signal: call.signal,
340
+ owner: {
341
+ sessionId: call.sessionId,
342
+ operationId: call.operationId,
343
+ ...(call.executionId ? { executionId: call.executionId } : {}),
344
+ ...(call.ownerInstanceId ? { ownerInstanceId: call.ownerInstanceId } : {})
345
+ }
346
+ };
347
+ }, call.sessionId, true);
348
+ let cleanup;
349
+ const cancel = () => (cleanup ??= (async () => {
350
+ call.signal.removeEventListener('abort', abort);
351
+ await this.#terminate(managed, false);
352
+ destroyManagedStreams(managed);
353
+ this.#processes.delete(id);
354
+ })());
355
+ const abort = () => {
356
+ void cancel().catch(() => undefined);
357
+ };
358
+ call.signal.addEventListener('abort', abort, { once: true });
359
+ managed.child.once('close', () => call.signal.removeEventListener('abort', abort));
360
+ managed.child.stdin.on('error', (error) => {
361
+ if (error.code !== 'EPIPE' && !cleanup)
362
+ managed.failure = new MarAgentError('MAR_AGENT_PROCESS_IO_FAILED', 'Native process input failed.', {
363
+ details: { reasonCode: error.code ?? 'UNKNOWN' }
364
+ });
219
365
  });
220
- child.stderr.on('data', (chunk) => {
221
- if (managed.finalized)
366
+ managed.child.stdin.end(input.input);
367
+ if (call.signal.aborted) {
368
+ await cancel();
369
+ call.signal.throwIfAborted();
370
+ }
371
+ const opened = new Promise((resolve, reject) => {
372
+ if (managed.child.pid) {
373
+ resolve();
222
374
  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)
375
+ }
376
+ if (managed.failure) {
377
+ reject(managed.failure);
242
378
  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);
379
+ }
380
+ const spawned = () => {
381
+ managed.child.removeListener('error', failed);
382
+ resolve();
383
+ };
384
+ const failed = () => {
385
+ managed.child.removeListener('spawn', spawned);
386
+ reject(managed.failure);
387
+ };
388
+ managed.child.once('spawn', spawned);
389
+ managed.child.once('error', failed);
247
390
  });
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;
391
+ try {
392
+ await opened;
393
+ }
394
+ catch (error) {
395
+ await cancel();
396
+ throw error;
397
+ }
398
+ const stream = (name) => ({
399
+ async *[Symbol.asyncIterator]() {
400
+ try {
401
+ for await (const chunk of managed.child[name])
402
+ yield new Uint8Array(chunk);
403
+ }
404
+ catch (error) {
405
+ if (!cleanup && !call.signal.aborted)
406
+ throw new MarAgentError('MAR_AGENT_PROCESS_IO_FAILED', 'Native process output failed.', {
407
+ details: {
408
+ stream: name,
409
+ reasonCode: error.code ?? 'UNKNOWN'
410
+ }
411
+ });
412
+ }
413
+ }
414
+ });
415
+ return {
416
+ processId: id,
417
+ stdout: stream('stdout'),
418
+ stderr: stream('stderr'),
419
+ cancel,
420
+ wait: async () => {
421
+ await managed.exited;
422
+ call.signal.throwIfAborted();
423
+ if (managed.failure)
424
+ throw managed.failure;
425
+ return { code: managed.exitCode ?? null, signal: managed.exitSignal ?? null };
426
+ }
427
+ };
257
428
  }
258
429
  listSessionResources(sessionId) {
259
430
  return [
260
- ...[...this.#processes.entries()].flatMap(([processId, process]) => process.ownerSessionId === sessionId
431
+ ...[...this.#processes.entries()].flatMap(([processId, process]) => !process.native && process.ownerSessionId === sessionId
261
432
  ? [{ processId, status: process.status, command: process.command, cwd: process.cwd }]
262
433
  : []),
263
434
  ...[...this.#completed.entries()].flatMap(([processId, process]) => process.ownerSessionId === sessionId
@@ -292,7 +463,10 @@ export class ExecTool {
292
463
  this.#completed.delete(id);
293
464
  }
294
465
  #retainCompleted(id, process) {
295
- if (process.status === 'running' || !process.finalized || this.#processes.get(id) !== process)
466
+ if (process.native ||
467
+ process.status === 'running' ||
468
+ !process.finalized ||
469
+ this.#processes.get(id) !== process)
296
470
  return;
297
471
  this.#processes.delete(id);
298
472
  const stdout = consumeOutput(process.stdoutHistory);
@@ -325,6 +499,8 @@ export class ExecTool {
325
499
  return managed.terminate;
326
500
  managed.terminate = (async () => {
327
501
  if (managed.exitObserved || managed.child.exitCode !== null) {
502
+ if (managed.native && !managed.finalized)
503
+ await signalProcessTree(managed.child, 'SIGKILL');
328
504
  if (managed.child.exitCode !== null)
329
505
  managed.exitCode = managed.child.exitCode;
330
506
  if (waitForOutputClose) {
@@ -345,6 +521,9 @@ export class ExecTool {
345
521
  await signalProcessTree(managed.child, 'SIGKILL');
346
522
  await managed.exited;
347
523
  }
524
+ // A parent may exit on TERM while descendants ignore it and keep the pipes alive.
525
+ if (managed.native)
526
+ await signalProcessTree(managed.child, 'SIGKILL');
348
527
  if (waitForOutputClose) {
349
528
  const settled = await waitForExit(managed.settled, TOOL_EXECUTION_LIMITS.execTerminationGraceMs);
350
529
  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>;