@myagentroam/agent 0.9.158 → 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 (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 +21 -0
  61. package/dist/agent-core/model/openai-responses.d.ts +3 -1
  62. package/dist/agent-core/model/openai-responses.js +248 -97
  63. package/dist/agent-core/model/text-blocks.d.ts +7 -0
  64. package/dist/agent-core/model/text-blocks.js +40 -0
  65. package/dist/agent-core/prompts/index.d.ts +6 -2
  66. package/dist/agent-core/prompts/index.js +38 -24
  67. package/dist/agent-core/runtime/context/gc-tokens.js +6 -1
  68. package/dist/agent-core/runtime/context/normalize.js +21 -1
  69. package/dist/agent-core/runtime/context/projection.js +35 -1
  70. package/dist/agent-core/runtime/context/request-budget.js +5 -2
  71. package/dist/agent-core/runtime/context/restore.d.ts +5 -0
  72. package/dist/agent-core/runtime/context/restore.js +47 -4
  73. package/dist/agent-core/runtime/context/usage.js +2 -3
  74. package/dist/agent-core/runtime/contracts.d.ts +2 -0
  75. package/dist/agent-core/runtime/execution.js +5 -2
  76. package/dist/agent-core/sdk/agent.js +177 -40
  77. package/dist/agent-core/sdk/extension-agents.d.ts +9 -0
  78. package/dist/agent-core/sdk/extension-agents.js +51 -0
  79. package/dist/agent-core/sdk/extension-models.d.ts +13 -0
  80. package/dist/agent-core/sdk/extension-models.js +128 -0
  81. package/dist/agent-core/sdk/extension-session.d.ts +30 -0
  82. package/dist/agent-core/sdk/extension-session.js +103 -0
  83. package/dist/agent-core/sdk/extension-tools.d.ts +16 -0
  84. package/dist/agent-core/sdk/extension-tools.js +126 -0
  85. package/dist/agent-core/sdk/session.d.ts +26 -2
  86. package/dist/agent-core/sdk/session.js +1215 -506
  87. package/dist/agent-core/sdk/types.d.ts +3 -0
  88. package/dist/agent-core/session/context-gc-checkpoint.js +1 -1
  89. package/dist/agent-core/session/jsonl-store.d.ts +28 -8
  90. package/dist/agent-core/session/jsonl-store.js +124 -84
  91. package/dist/agent-core/session/types.d.ts +4 -1
  92. package/dist/agent-core/storage/file-lock.d.ts +4 -0
  93. package/dist/agent-core/storage/file-lock.js +83 -0
  94. package/dist/agent-core/subagent/contracts.d.ts +11 -1
  95. package/dist/agent-core/subagent/scheduler.d.ts +8 -0
  96. package/dist/agent-core/subagent/session-controller.d.ts +22 -1
  97. package/dist/agent-core/subagent/session-controller.js +355 -98
  98. package/dist/agent-core/tools/agent/agent-start.d.ts +1 -1
  99. package/dist/agent-core/tools/code-mode/cells.js +5 -15
  100. package/dist/agent-core/tools/code-mode/dispatch.d.ts +1 -0
  101. package/dist/agent-core/tools/code-mode/dispatch.js +13 -1
  102. package/dist/agent-core/tools/code-mode/index.js +1 -2
  103. package/dist/agent-core/tools/code-mode/observations.d.ts +5 -0
  104. package/dist/agent-core/tools/code-mode/observations.js +16 -5
  105. package/dist/agent-core/tools/code-mode/quickjs-engine.js +10 -5
  106. package/dist/agent-core/tools/execution.d.ts +11 -2
  107. package/dist/agent-core/tools/execution.js +58 -21
  108. package/dist/agent-core/tools/input.d.ts +2 -0
  109. package/dist/agent-core/tools/input.js +36 -0
  110. package/dist/agent-core/tools/local/apply-patch.js +21 -17
  111. package/dist/agent-core/tools/local/exec.d.ts +4 -4
  112. package/dist/agent-core/tools/local/exec.js +234 -62
  113. package/dist/agent-core/tools/local/registry.d.ts +6 -0
  114. package/dist/agent-core/tools/local/registry.js +60 -9
  115. package/dist/agent-core/tools/local/view-image.js +108 -2
  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'],
@@ -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);
@@ -27,17 +27,25 @@ export class ViewImageTool {
27
27
  const path = await this.paths.resolve(input.path);
28
28
  const handle = await open(path, 'r');
29
29
  try {
30
- const stat = await handle.stat();
30
+ const stat = await handle.stat({ bigint: true });
31
31
  if (!stat.isFile())
32
32
  throw new MarAgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Path is not a regular file.');
33
- if (stat.size > TOOL_EXECUTION_LIMITS.viewImageMaxBytes)
33
+ if (stat.size > BigInt(TOOL_EXECUTION_LIMITS.viewImageMaxBytes))
34
34
  throw new MarAgentError('MAR_AGENT_TOOL_OUTPUT_LIMIT', `Image exceeds the ${TOOL_EXECUTION_LIMITS.viewImageMaxBytes}-byte limit.`);
35
35
  signal?.throwIfAborted();
36
36
  const data = await handle.readFile();
37
37
  signal?.throwIfAborted();
38
38
  if (data.byteLength > TOOL_EXECUTION_LIMITS.viewImageMaxBytes)
39
39
  throw new MarAgentError('MAR_AGENT_TOOL_OUTPUT_LIMIT', `Image exceeds the ${TOOL_EXECUTION_LIMITS.viewImageMaxBytes}-byte limit.`);
40
+ const after = await handle.stat({ bigint: true });
41
+ signal?.throwIfAborted();
42
+ if (stat.size !== after.size ||
43
+ after.size !== BigInt(data.byteLength) ||
44
+ stat.mtimeNs !== after.mtimeNs ||
45
+ stat.ctimeNs !== after.ctimeNs)
46
+ return incompleteImage();
40
47
  const mimeType = detectImageMime(data);
48
+ validateImageContainer(data, mimeType);
41
49
  const metadata = {
42
50
  path: input.path,
43
51
  mimeType,
@@ -80,3 +88,101 @@ export function detectImageMime(data) {
80
88
  function invalidInput() {
81
89
  throw new MarAgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'View image input is invalid.');
82
90
  }
91
+ // Basic container checks catch partial writes without decoding or changing pixels.
92
+ function validateImageContainer(data, mimeType) {
93
+ if (mimeType === 'image/jpeg') {
94
+ let offset = 2;
95
+ let inScan = false;
96
+ let hasScan = false;
97
+ while (offset < data.length) {
98
+ if (data[offset++] !== 0xff) {
99
+ if (!inScan)
100
+ incompleteImage();
101
+ continue;
102
+ }
103
+ while (data[offset] === 0xff)
104
+ offset++;
105
+ if (offset >= data.length)
106
+ incompleteImage();
107
+ const marker = data[offset++];
108
+ if (marker === 0 || (marker >= 0xd0 && marker <= 0xd7)) {
109
+ if (!inScan)
110
+ incompleteImage();
111
+ continue;
112
+ }
113
+ if (marker === 0xd9) {
114
+ if (!hasScan)
115
+ incompleteImage();
116
+ return;
117
+ }
118
+ if (marker === 0xd8)
119
+ incompleteImage();
120
+ if (marker === 1)
121
+ continue;
122
+ if (data.length - offset < 2)
123
+ incompleteImage();
124
+ const length = data.readUInt16BE(offset);
125
+ if (length < 2 || offset + length > data.length)
126
+ incompleteImage();
127
+ offset += length;
128
+ if (marker === 0xda)
129
+ hasScan = true;
130
+ inScan = marker === 0xda || (inScan && marker === 0xdc);
131
+ }
132
+ incompleteImage();
133
+ }
134
+ if (mimeType === 'image/webp') {
135
+ const end = data.readUInt32LE(4) + 8;
136
+ if (end > data.length || end < 20)
137
+ incompleteImage();
138
+ let offset = 12;
139
+ let hasPixels = false;
140
+ while (offset < end) {
141
+ if (end - offset < 8)
142
+ incompleteImage();
143
+ const length = data.readUInt32LE(offset + 4);
144
+ const next = offset + 8 + length + (length % 2);
145
+ if (next > end)
146
+ incompleteImage();
147
+ const type = data.toString('ascii', offset, offset + 4);
148
+ if ((type === 'VP8 ' || type === 'VP8L' || type === 'ANMF') && length > 0)
149
+ hasPixels = true;
150
+ offset = next;
151
+ }
152
+ if (!hasPixels)
153
+ incompleteImage();
154
+ return;
155
+ }
156
+ let offset = 8;
157
+ let hasPixels = false;
158
+ while (offset < data.length) {
159
+ if (data.length - offset < 12)
160
+ incompleteImage();
161
+ const length = data.readUInt32BE(offset);
162
+ const next = offset + 12 + length;
163
+ if (next > data.length)
164
+ incompleteImage();
165
+ const type = data.toString('ascii', offset + 4, offset + 8);
166
+ if (offset === 8) {
167
+ if (type !== 'IHDR' ||
168
+ length !== 13 ||
169
+ data.readUInt32BE(offset + 8) === 0 ||
170
+ data.readUInt32BE(offset + 12) === 0)
171
+ incompleteImage();
172
+ }
173
+ else if (type === 'IHDR')
174
+ incompleteImage();
175
+ if (type === 'IDAT' && length > 0)
176
+ hasPixels = true;
177
+ if (type === 'IEND') {
178
+ if (length !== 0 || !hasPixels)
179
+ incompleteImage();
180
+ return;
181
+ }
182
+ offset = next;
183
+ }
184
+ incompleteImage();
185
+ }
186
+ function incompleteImage() {
187
+ throw new MarAgentError('MAR_AGENT_IMAGE_INCOMPLETE', 'Image file is incomplete, malformed, or changed while reading. Wait for the writer to finish and read it again.');
188
+ }
@@ -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;