@myagentroam/agent 0.14.33 → 0.15.0

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.
@@ -31,6 +31,7 @@ export declare function serializeModel(model: CliModelConfiguration): {
31
31
  defaultReasoningEffort?: "low" | "medium" | "high" | "xhigh" | "max" | "ultra" | undefined;
32
32
  titleGeneration: boolean;
33
33
  codeMode: boolean;
34
+ contextGcMode?: "off" | "auto" | "with_thought" | undefined;
34
35
  gcEnabled?: boolean | undefined;
35
36
  smartCompactEnabled?: boolean | undefined;
36
37
  fastMode?: boolean | undefined;
@@ -68,6 +69,7 @@ export declare function serializeModel(model: CliModelConfiguration): {
68
69
  defaultReasoningEffort?: "low" | "medium" | "high" | "xhigh" | "max" | "ultra" | undefined;
69
70
  titleGeneration: boolean;
70
71
  codeMode: boolean;
72
+ contextGcMode?: "off" | "auto" | "with_thought" | undefined;
71
73
  gcEnabled?: boolean | undefined;
72
74
  smartCompactEnabled?: boolean | undefined;
73
75
  fastMode?: boolean | undefined;
package/dist/cli/main.js CHANGED
@@ -149,7 +149,14 @@ async function modelsCommand(home, arguments_, codexAuthFile) {
149
149
  const defaultReasoningEffortOption = option('--default-reasoning-effort');
150
150
  const model = {
151
151
  useResourceUrl: existing?.useResourceUrl ?? false,
152
- gcEnabled: existing?.gcEnabled ?? true,
152
+ ...(existing === undefined
153
+ ? { contextGcMode: 'off' }
154
+ : {
155
+ ...(existing.contextGcMode === undefined
156
+ ? {}
157
+ : { contextGcMode: existing.contextGcMode }),
158
+ gcEnabled: existing.gcEnabled ?? true
159
+ }),
153
160
  id,
154
161
  name: required(option('--name', existing?.name), '--name'),
155
162
  protocol,
@@ -134,7 +134,7 @@ export class ExtensionSessionTools {
134
134
  this.assertToolAvailable(original, context);
135
135
  call = permissionPolicy.prepare(call, context, original.definition);
136
136
  const requestedApproval = call.permission?.action === 'ask';
137
- call = await permissionPolicy.authorize(call, context);
137
+ call = await permissionPolicy.authorize(call, context, original.source.kind === 'builtin' ? original.definition.eventInputFields : undefined);
138
138
  if (requestedApproval)
139
139
  approved = structuredClone(call);
140
140
  }
@@ -6,7 +6,7 @@ export interface ExtensionToolRuntime {
6
6
  readonly mode: string;
7
7
  assertDispatch(): void;
8
8
  prepare(input: ToolCall, call: ExtensionOperationContext, definition: ClientToolDefinition): ToolCall;
9
- authorize(input: ToolCall, call: ExtensionOperationContext): Promise<ToolCall>;
9
+ authorize(input: ToolCall, call: ExtensionOperationContext, publicInputFields?: readonly string[]): Promise<ToolCall>;
10
10
  } | undefined;
11
11
  normalizeInput(input: unknown, schema: unknown): unknown;
12
12
  validateResult(result: ToolExecutionResult): ToolExecutionResult;
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
3
  import { AgentError } from '../error.js';
4
+ import { THOUGHT_TOOL_NAME } from '../tools/agent/thought.js';
4
5
  import { fromJSONSchema } from 'zod';
5
6
  import { ExtensionResourceScope } from './resources.js';
6
7
  /** Builds one immutable catalog from real sources; snapshots keep their captured handlers. */
@@ -42,6 +43,8 @@ export class ExtensionTools {
42
43
  return registration;
43
44
  }
44
45
  register(owner, id, spec) {
46
+ if (spec.name === THOUGHT_TOOL_NAME)
47
+ throw new AgentError('MAR_AGENT_EXTENSION_TOOL_CONFLICT', 'Thought is reserved for SDK context management.');
45
48
  if (typeof spec.name !== 'string' ||
46
49
  !spec.name.trim() ||
47
50
  typeof spec.description !== 'string' ||
@@ -93,7 +96,7 @@ export class ExtensionTools {
93
96
  for (const original of [...base, ...sources]) {
94
97
  const binding = Object.freeze({
95
98
  ...original,
96
- definition: deepFreeze(copyDefinition(original.definition)),
99
+ definition: deepFreeze(copyDefinition(original.definition, original.source.kind === 'builtin')),
97
100
  source: Object.freeze({ ...original.source }),
98
101
  ...(original.mcp === undefined ? {} : { mcp: deepFreeze(structuredClone(original.mcp)) })
99
102
  });
@@ -278,7 +281,7 @@ function deepFreeze(value) {
278
281
  }
279
282
  return value;
280
283
  }
281
- function copyDefinition(spec) {
284
+ function copyDefinition(spec, builtin = false) {
282
285
  return {
283
286
  name: spec.name,
284
287
  description: spec.description,
@@ -290,6 +293,7 @@ function copyDefinition(spec) {
290
293
  ...(spec.codeModeExposure !== undefined ? { codeModeExposure: spec.codeModeExposure } : {}),
291
294
  ...(spec.inputMode ? { inputMode: spec.inputMode } : {}),
292
295
  ...(spec.parallelSafety ? { parallelSafety: spec.parallelSafety } : {}),
296
+ ...(builtin && spec.autoPermission === 'omit' ? { autoPermission: spec.autoPermission } : {}),
293
297
  ...(spec.agentScope ? { agentScope: spec.agentScope } : {})
294
298
  };
295
299
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { AgentError } from './error.js';
2
- export type { AgentModelConfiguration, AgentReasoningEffort, ModelCatalog, ModelCredential, ModelCredentialAcquireReason, ModelCredentialProvider, ResponsesTransport } from './model/configuration.js';
2
+ export type { AgentModelConfiguration, ContextGcMode, AgentReasoningEffort, ModelCatalog, ModelCredential, ModelCredentialAcquireReason, ModelCredentialProvider, ResponsesTransport } from './model/configuration.js';
3
3
  export { agentReasoningEffortSchema, parseModelCatalog, resolveModelDefaultReasoningEffort, SecretValue } from './model/configuration.js';
4
4
  export { testAgentModelTransport } from './model/transport-test.js';
5
5
  export type { ModelRequestUsage, ModelUsageObservation, ModelUsageObserver } from './model/usage-observer.js';
@@ -17,6 +17,16 @@ export declare const agentReasoningEffortSchema: z.ZodEnum<{
17
17
  ultra: "ultra";
18
18
  }>;
19
19
  export type AgentReasoningEffort = z.infer<typeof agentReasoningEffortSchema>;
20
+ declare const contextGcModeSchema: z.ZodEnum<{
21
+ off: "off";
22
+ auto: "auto";
23
+ with_thought: "with_thought";
24
+ }>;
25
+ export type ContextGcMode = z.infer<typeof contextGcModeSchema>;
26
+ export declare function resolveContextGcMode(model: {
27
+ contextGcMode?: ContextGcMode | undefined;
28
+ gcEnabled?: boolean | undefined;
29
+ }): ContextGcMode;
20
30
  declare const rawModelSchema: z.ZodObject<{
21
31
  id: z.ZodString;
22
32
  name: z.ZodString;
@@ -57,6 +67,11 @@ declare const rawModelSchema: z.ZodObject<{
57
67
  subagentModel: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
58
68
  titleGeneration: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
59
69
  codeMode: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
70
+ contextGcMode: z.ZodOptional<z.ZodEnum<{
71
+ off: "off";
72
+ auto: "auto";
73
+ with_thought: "with_thought";
74
+ }>>;
60
75
  gcEnabled: z.ZodOptional<z.ZodBoolean>;
61
76
  smartCompactEnabled: z.ZodOptional<z.ZodBoolean>;
62
77
  useResourceUrl: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
@@ -15,6 +15,10 @@ export const agentReasoningEffortSchema = z.enum([
15
15
  'max',
16
16
  'ultra'
17
17
  ]);
18
+ const contextGcModeSchema = z.enum(['off', 'auto', 'with_thought']);
19
+ export function resolveContextGcMode(model) {
20
+ return model.contextGcMode ?? (model.gcEnabled === false ? 'off' : 'auto');
21
+ }
18
22
  const modelFieldsSchema = z
19
23
  .object({
20
24
  id: z
@@ -40,6 +44,7 @@ const modelFieldsSchema = z
40
44
  subagentModel: z.boolean().optional().default(false),
41
45
  titleGeneration: z.boolean().optional().default(false),
42
46
  codeMode: z.boolean().optional().default(false),
47
+ contextGcMode: contextGcModeSchema.optional(),
43
48
  gcEnabled: z.boolean().optional(),
44
49
  smartCompactEnabled: z.boolean().optional(),
45
50
  useResourceUrl: z.boolean().optional().default(false),
@@ -1,6 +1,6 @@
1
1
  import type { ExecutionMode } from '../runtime/contracts.js';
2
2
  import { type PromptPart } from './prompt-sections.js';
3
- export declare const MAR_AGENT_PROMPT_VERSION = "1.77";
3
+ export declare const MAR_AGENT_PROMPT_VERSION = "1.78";
4
4
  interface SystemPromptInput {
5
5
  mode: ExecutionMode;
6
6
  platform: string;
@@ -3,7 +3,7 @@ import { compactionPrompt } from './compact.js';
3
3
  import { environmentPrompt, identityPrompt, instructionPriorityPrompt, progressCommunicationPrompt, securityPrompt } from './core.js';
4
4
  import { modePrompt } from './modes.js';
5
5
  import { toolUsagePrompt } from './workflow.js';
6
- export const MAR_AGENT_PROMPT_VERSION = '1.77';
6
+ export const MAR_AGENT_PROMPT_VERSION = '1.78';
7
7
  export function buildSystemPrompt(input) {
8
8
  return renderPromptSections(buildSystemPromptSections(input));
9
9
  }
@@ -1,3 +1,4 @@
1
+ import { THOUGHT_TOOL_NAME } from '../tools/agent/thought.js';
1
2
  export function toolUsagePrompt(tools, directTools = tools) {
2
3
  const names = new Set(tools);
3
4
  const clauses = [
@@ -13,5 +14,14 @@ export function toolUsagePrompt(tools, directTools = tools) {
13
14
  }
14
15
  if (names.has('exec'))
15
16
  clauses.push('You can use the built-in rg through exec to search file contents or rg --files to list file paths.');
16
- return clauses.join(' ');
17
+ const execution = clauses.join(' ');
18
+ if (!directTools.includes(THOUGHT_TOOL_NAME))
19
+ return execution;
20
+ return `${execution}
21
+
22
+ <reasoning>
23
+ During complex or extended tasks, use \`thought\` as significant intermediate insights accumulate, rather than waiting until the task is complete.
24
+
25
+ Avoid recording trivial observations or repeating existing conclusions.
26
+ </reasoning>`;
17
27
  }
@@ -32,6 +32,8 @@ export interface ContextGcCommitResult {
32
32
  export declare class ContextGcRuntime {
33
33
  #private;
34
34
  reset(): void;
35
+ /** Age ordinary GC backoff without evaluating a round that did not trigger GC. */
36
+ skipRollout(usage: ModelUsage | undefined, window: number): void;
35
37
  run(input: ContextGcRuntimeInput): Promise<ContextGcCommitResult | false>;
36
38
  }
37
39
  /**
@@ -14,6 +14,12 @@ export class ContextGcRuntime {
14
14
  this.#failures = 0;
15
15
  this.#remaining = 0;
16
16
  }
17
+ /** Age ordinary GC backoff without evaluating a round that did not trigger GC. */
18
+ skipRollout(usage, window) {
19
+ this.#observeUsage(contextGcEligibleUsage(usage ?? {}, window), window);
20
+ if (this.#remaining > 0)
21
+ this.#remaining--;
22
+ }
17
23
  async run(input) {
18
24
  const scope = JSON.stringify([
19
25
  input.sessionId,
@@ -29,19 +35,9 @@ export class ContextGcRuntime {
29
35
  const usage = mediaRequired
30
36
  ? (input.usage.contextInputTokens ?? input.usage.inputTokens ?? 0)
31
37
  : contextGcEligibleUsage(input.usage, input.contextWindowTokens);
32
- if (usage === undefined) {
33
- this.#lastUsage = undefined;
34
- this.#failures = 0;
35
- this.#remaining = 0;
38
+ const maximumInterval = this.#observeUsage(usage, input.contextWindowTokens);
39
+ if (maximumInterval === undefined)
36
40
  return false;
37
- }
38
- if (this.#lastUsage !== undefined && usage < this.#lastUsage) {
39
- this.#failures = 0;
40
- this.#remaining = 0;
41
- }
42
- this.#lastUsage = usage;
43
- const maximumInterval = usage / input.contextWindowTokens >= 0.8 ? 2 : 8;
44
- this.#remaining = Math.min(this.#remaining, maximumInterval - 1);
45
41
  if (this.#remaining > 0 && !mediaRequired) {
46
42
  this.#remaining--;
47
43
  return false;
@@ -58,6 +54,18 @@ export class ContextGcRuntime {
58
54
  }
59
55
  return attempt.result;
60
56
  }
57
+ #observeUsage(usage, window) {
58
+ if (usage === undefined || (this.#lastUsage !== undefined && usage < this.#lastUsage)) {
59
+ this.#failures = 0;
60
+ this.#remaining = 0;
61
+ }
62
+ this.#lastUsage = usage;
63
+ if (usage === undefined)
64
+ return undefined;
65
+ const maximumInterval = usage / window >= 0.8 ? 2 : 8;
66
+ this.#remaining = Math.min(this.#remaining, maximumInterval - 1);
67
+ return maximumInterval;
68
+ }
61
69
  }
62
70
  /**
63
71
  * Runs the deterministic planner and commits its checkpoint. Planning and
@@ -54,6 +54,10 @@ export type AgentEvent = AgentEventBase & ({
54
54
  type: 'plan.completed';
55
55
  itemId: string;
56
56
  text: string;
57
+ } | {
58
+ type: 'thought.recorded';
59
+ callId: string;
60
+ title: string;
57
61
  } | {
58
62
  type: 'reasoning.completed';
59
63
  itemId: string;
@@ -33,7 +33,7 @@ export interface ExecutionLoopInput<TScope = unknown> {
33
33
  readonly observeUsage: (usage: Omit<AuthoritativeModelUsage, 'historyMessages'> | undefined) => void;
34
34
  readonly observeContextTokens: (tokens: number) => void;
35
35
  readonly afterModel?: (closedPrefixLength: number, acceptedRequest?: ModelRequest) => Promise<void>;
36
- readonly checkpoint: (round: PreparedExecutionRound<TScope>, usage: ModelUsage | undefined) => Promise<void>;
36
+ readonly checkpoint: (round: PreparedExecutionRound<TScope>, usage: ModelUsage | undefined, thoughtCallIds: readonly string[]) => Promise<void>;
37
37
  readonly mailbox: {
38
38
  hasPending(): boolean;
39
39
  append(): Promise<boolean>;
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
2
2
  import { AgentError } from '../error.js';
3
3
  import { isProviderContextOverflow, recoverModelStream } from '../model/recovery.js';
4
4
  import { modelStreamEventObservedAt } from '../model/sse.js';
5
+ import { THOUGHT_TOOL_NAME } from '../tools/agent/thought.js';
5
6
  import { publicHostedToolEvents, publicModelUsage } from './event-projection.js';
6
7
  import { PlanOutputPrefix, splitPlanOutput } from './plan-output.js';
7
8
  import { ModelGenerationTiming } from './model-generation-timing.js';
@@ -368,7 +369,17 @@ export class ExecutionLoop {
368
369
  if (input.sourceType === 'subagent')
369
370
  this.finalAnswer = '';
370
371
  }
371
- await input.checkpoint(round, latestUsage);
372
+ const thoughtCallIds = [];
373
+ for (const result of toolResults) {
374
+ if (result.call.name !== THOUGHT_TOOL_NAME || result.failed)
375
+ continue;
376
+ const title = result.call.arguments?.title;
377
+ if (typeof title !== 'string')
378
+ continue;
379
+ await input.publish({ type: 'thought.recorded', callId: result.call.callId, title });
380
+ thoughtCallIds.push(result.call.callId);
381
+ }
382
+ await input.checkpoint(round, latestUsage, thoughtCallIds);
372
383
  if (input.signal.aborted) {
373
384
  const aborted = toolResults.find((result) => result.failed)?.error;
374
385
  throw aborted ?? new AgentError('MAR_AGENT_EXECUTION_CANCELLED', 'Execution cancelled.');
@@ -8,6 +8,12 @@ import type { SessionExecution } from './session-execution.js';
8
8
  import type { ExecutionModelLifecycle } from './execution-model-lifecycle.js';
9
9
  import type { createExecutionModelContext } from './execution-model-context.js';
10
10
  import type { ResourceInputProjection } from './resource-input.js';
11
+ import type { ContextGcMode } from '../model/configuration.js';
12
+ type GcRound = {
13
+ readonly request: Pick<PreparedExecutionRound<RoundToolScope>['request'], 'system'>;
14
+ readonly toolScope: Pick<RoundToolScope, 'tools'>;
15
+ };
16
+ type GcUsage = ContextGcRuntimeInput['usage'] | undefined;
11
17
  /** Coordinates safe-point adoption of Compact and GC without owning Session state. */
12
18
  export declare class ExecutionContextCoordinator {
13
19
  #private;
@@ -23,8 +29,8 @@ export declare class ExecutionContextCoordinator {
23
29
  readonly requests: Pick<CompactRequests, 'drain'>;
24
30
  readonly signal: AbortSignal;
25
31
  readonly window: number;
26
- readonly gcEnabled?: boolean;
27
- readonly gc: Pick<ContextGcRuntime, 'run'>;
32
+ readonly contextGcMode: ContextGcMode;
33
+ readonly gc: Pick<ContextGcRuntime, 'run' | 'skipRollout'>;
28
34
  readonly gcBase: Omit<ContextGcRuntimeInput, 'system' | 'tools' | 'usage' | 'inlineMedia' | 'mediaView' | 'getActiveProcessIds'>;
29
35
  start(input?: {
30
36
  focus?: string;
@@ -48,9 +54,9 @@ export declare class ExecutionContextCoordinator {
48
54
  updateEnvironment(): void;
49
55
  }): Promise<void>;
50
56
  ensureBudget(): Promise<void>;
51
- checkpoint(round: PreparedExecutionRound<RoundToolScope>, usage: ContextGcRuntimeInput['usage'] | undefined): Promise<void>;
52
- gc(round: {
53
- readonly request: Pick<PreparedExecutionRound<RoundToolScope>['request'], 'system'>;
54
- readonly toolScope: Pick<RoundToolScope, 'tools'>;
55
- }, usage: ContextGcRuntimeInput['usage'] | undefined, media: ContextGcRuntimeInput['inlineMedia'], includeProcesses?: boolean): Promise<boolean>;
57
+ checkpoint(round: PreparedExecutionRound<RoundToolScope>, usage: GcUsage, thoughtCallIds?: readonly string[]): Promise<void>;
58
+ /** Merge a one-round Thought trigger with the existing dispatch-time hard limit. */
59
+ prepareRequestGc(round: GcRound, messages: readonly SessionModelMessage[], usage: GcUsage, media: ContextGcRuntimeInput['inlineMedia']): Promise<boolean>;
60
+ gc(round: GcRound, usage: GcUsage, media: ContextGcRuntimeInput['inlineMedia'], includeProcesses?: boolean): Promise<boolean>;
56
61
  }
62
+ export {};
@@ -1,9 +1,11 @@
1
1
  import { AgentError } from '../error.js';
2
2
  import { AGENT_EXECUTION_POLICY } from '../runtime/execution-policy.js';
3
+ import { THOUGHT_TOOL_NAME } from '../tools/agent/thought.js';
3
4
  /** Coordinates safe-point adoption of Compact and GC without owning Session state. */
4
5
  export class ExecutionContextCoordinator {
5
6
  ports;
6
7
  #boundary;
8
+ #thought;
7
9
  constructor(ports) {
8
10
  this.ports = ports;
9
11
  this.#boundary = ports.initialBoundary;
@@ -70,7 +72,7 @@ export class ExecutionContextCoordinator {
70
72
  this.ports.start({ async: true });
71
73
  }
72
74
  }
73
- async checkpoint(round, usage) {
75
+ async checkpoint(round, usage, thoughtCallIds = []) {
74
76
  this.advanceBoundary();
75
77
  const blocking = this.drainRequests();
76
78
  if (blocking)
@@ -80,12 +82,33 @@ export class ExecutionContextCoordinator {
80
82
  this.ports.signal.throwIfAborted();
81
83
  this.ports.execution.assertContextValid();
82
84
  });
83
- if (this.ports.gcEnabled !== false && !this.ports.compact.pending)
85
+ if (this.ports.contextGcMode === 'auto' && !this.ports.compact.pending)
84
86
  await this.gc(round, usage, await this.ports.resources.gcCandidate(), true);
87
+ if (this.ports.contextGcMode === 'with_thought') {
88
+ this.#thought = thoughtCallIds.length === 0 ? undefined : { callIds: thoughtCallIds, usage };
89
+ if (this.#thought === undefined && !this.ports.compact.pending)
90
+ this.ports.gc.skipRollout(usage, this.ports.window);
91
+ }
92
+ }
93
+ /** Merge a one-round Thought trigger with the existing dispatch-time hard limit. */
94
+ async prepareRequestGc(round, messages, usage, media) {
95
+ const pending = this.#thought;
96
+ this.#thought = undefined;
97
+ const thought = pending !== undefined &&
98
+ messages.some((message) => message.role === 'tool_call' &&
99
+ message.name === THOUGHT_TOOL_NAME &&
100
+ message.callId !== undefined &&
101
+ pending.callIds.includes(message.callId));
102
+ const hardLimit = media?.reason === 'HARD_LIMIT';
103
+ if (!thought && !hardLimit)
104
+ return false;
105
+ // The image hard limit keeps its own usage source even when a Thought also triggers GC.
106
+ return this.gc(round, hardLimit ? usage : pending?.usage, media, thought);
85
107
  }
86
108
  async gc(round, usage, media, includeProcesses = false) {
87
- if (this.ports.gcEnabled === false || this.ports.compact.pending)
109
+ if (this.ports.contextGcMode === 'off' || this.ports.compact.pending)
88
110
  return false;
111
+ this.ports.signal.throwIfAborted();
89
112
  const appendBoundary = this.ports.execution.appendBoundary;
90
113
  const committed = await this.ports.gc.run({
91
114
  ...this.ports.gcBase,
@@ -7,6 +7,8 @@ import { discoveredMcpToolNames, rebindMcpToolSearchOutputs } from '../tools/mcp
7
7
  import { BUILTIN_TOOL_DEFINITIONS } from '../tools/registry.js';
8
8
  import { toolCallers } from '../tools/callers.js';
9
9
  import { ExecutionToolSources } from './extension-tools.js';
10
+ import { resolveContextGcMode } from '../model/configuration.js';
11
+ import { THOUGHT_TOOL_NAME } from '../tools/agent/thought.js';
10
12
  /** Initializes one Execution's catalog before Extension attachment owns its bindings. */
11
13
  export async function initializeExecutionToolCatalog(input) {
12
14
  const { host, context } = input;
@@ -59,6 +61,8 @@ export class ExecutionToolCatalog {
59
61
  toolCallers(tool);
60
62
  if (this.input.child && (tool.agentScope === 'ROOT_ONLY' || tool.name === 'question'))
61
63
  return false;
64
+ if (tool.name === THOUGHT_TOOL_NAME)
65
+ return (this.input.mode !== 'compact' && resolveContextGcMode(this.input.model) === 'with_thought');
62
66
  if (tool.name === 'tool_search')
63
67
  return this.input.registry.hasDeferred;
64
68
  return tool.name === 'code_exec' || tool.name === 'code_exec_wait'
@@ -1,3 +1,4 @@
1
+ import { resolveContextGcMode } from '../model/configuration.js';
1
2
  import { restoreMessages } from '../runtime/context/restore.js';
2
3
  import { latestModelUsage, reasoningEffortBaseline } from '../runtime/context/usage.js';
3
4
  import { publicModelUsage } from '../runtime/event-projection.js';
@@ -577,6 +578,7 @@ export function createSessionExecutionFactory(ports) {
577
578
  executionId,
578
579
  turnId
579
580
  });
581
+ const contextGcMode = resolveContextGcMode(selectedModel);
580
582
  const contextCoordinator = new ExecutionContextCoordinator({
581
583
  initialBoundary: restoredMessageCount,
582
584
  messages,
@@ -588,7 +590,7 @@ export function createSessionExecutionFactory(ports) {
588
590
  requests: compactRequests,
589
591
  signal: controller.signal,
590
592
  window: selectedModel.contextWindowTokens,
591
- gcEnabled: selectedModel.gcEnabled ?? true,
593
+ contextGcMode,
592
594
  gc: contextGc,
593
595
  gcBase: {
594
596
  store,
@@ -762,14 +764,11 @@ export function createSessionExecutionFactory(ports) {
762
764
  if (capturedDiscoveryRevision !== sessionRuntime.mcpDiscoveryRevision)
763
765
  return { retry: true };
764
766
  resourceInput.observe(candidateRequest.messages);
765
- const media = selectedModel.gcEnabled === false
767
+ const media = contextGcMode === 'off'
766
768
  ? undefined
767
769
  : await resourceInput.gcCandidate(request, candidateRequest.images);
768
- if (media?.reason === 'HARD_LIMIT') {
769
- const committed = await contextCoordinator.gc({ request, toolScope }, modelLifecycle.usage, media);
770
- if (committed)
771
- return { retry: true };
772
- }
770
+ if (await contextCoordinator.prepareRequestGc({ request, toolScope }, request.messages, modelLifecycle.usage, media))
771
+ return { retry: true };
773
772
  const prepared = await resourceInput.prepare(request, candidateRequest.images, candidateRequest.messages);
774
773
  controller.signal.throwIfAborted();
775
774
  if (capturedDiscoveryRevision !== sessionRuntime.mcpDiscoveryRevision)
@@ -835,7 +834,7 @@ export function createSessionExecutionFactory(ports) {
835
834
  afterModel: (closedPrefixLength, request) => modelLifecycle.afterModel(closedPrefixLength, request),
836
835
  observeContextTokens: (tokens) => modelLifecycle.observeTokens(tokens),
837
836
  observeUsage: (usage) => modelLifecycle.observeUsage(usage),
838
- checkpoint: (round, latestUsage) => contextCoordinator.checkpoint(round, latestUsage),
837
+ checkpoint: (round, latestUsage, thoughtCallIds) => contextCoordinator.checkpoint(round, latestUsage, thoughtCallIds),
839
838
  mailbox: {
840
839
  hasPending: () => inputs.hasBoundaryPending && !inputs.executing,
841
840
  append: appendMailboxMessages,
@@ -127,6 +127,7 @@ export function isGenericContextGcTool(toolName) {
127
127
  'web_fetch',
128
128
  'skill',
129
129
  'question',
130
+ 'thought',
130
131
  'todo',
131
132
  'todo_read',
132
133
  'todo_write',
@@ -2,6 +2,7 @@ import { AgentError } from '../../error.js';
2
2
  import { agentSkillSource, loadAgentSkill } from '../../runtime/context/instructions.js';
3
3
  export const skillToolDefinition = {
4
4
  name: 'skill_load',
5
+ autoPermission: 'omit',
5
6
  allowedCallers: ['direct', 'programmatic'],
6
7
  parallelSafety: 'safe',
7
8
  description: 'Load a Skill by its exact catalog name. Returns { success: true }; instructions are injected into the next eligible model request, not returned by the tool.',
@@ -3,6 +3,7 @@ import { TOOL_EXECUTION_LIMITS } from '../execution-limits.js';
3
3
  import { waitForToolCondition } from '../wait.js';
4
4
  export const sleepToolDefinition = {
5
5
  name: 'sleep',
6
+ autoPermission: 'omit',
6
7
  allowedCallers: ['direct'],
7
8
  parallelSafety: 'safe',
8
9
  description: 'Pause for up to durationMs milliseconds. Returns early when user input or a new public subagent message is available. Returns elapsed time and the wake reason.',
@@ -0,0 +1,11 @@
1
+ import type { ClientToolDefinition } from '../contracts.js';
2
+ export declare const THOUGHT_TOOL_NAME = "thought";
3
+ export declare const thoughtToolDefinition: ClientToolDefinition;
4
+ /** Validate the note fields independently of the invocation's framework metadata. */
5
+ export declare function readThoughtInput(input: unknown): {
6
+ title: string;
7
+ content: string;
8
+ };
9
+ export declare function executeThought(input: unknown): Promise<{
10
+ content: string;
11
+ }>;
@@ -0,0 +1,41 @@
1
+ import { AgentError } from '../../error.js';
2
+ export const THOUGHT_TOOL_NAME = 'thought';
3
+ const maxTitleLength = 256;
4
+ const maxContentBytes = 32 * 1024;
5
+ export const thoughtToolDefinition = {
6
+ name: THOUGHT_TOOL_NAME,
7
+ autoPermission: 'omit',
8
+ allowedCallers: ['direct'],
9
+ parallelSafety: 'safe',
10
+ eventInputFields: [],
11
+ description: 'Record dense, reusable insights not yet captured in durable artifacts: findings, decisions, rejected approaches with evidence, assumptions, and unresolved questions. Prefer terse domain shorthand, identifiers, and compact notation over narrative prose. Do not recap progress. Keep exact values and evidence needed to resume; distinguish verified facts from hypotheses. Do not include secrets or private deliberation.',
12
+ inputSchema: {
13
+ type: 'object',
14
+ properties: {
15
+ title: {
16
+ type: 'string',
17
+ description: "A concise, human-readable title capturing the key insight in the user's language.",
18
+ minLength: 1,
19
+ maxLength: maxTitleLength
20
+ },
21
+ content: { type: 'string', minLength: 1, maxLength: maxContentBytes }
22
+ },
23
+ required: ['title', 'content'],
24
+ additionalProperties: false
25
+ }
26
+ };
27
+ /** Validate the note fields independently of the invocation's framework metadata. */
28
+ export function readThoughtInput(input) {
29
+ const { title, content } = input && typeof input === 'object' ? input : {};
30
+ if (typeof title !== 'string' || !title.trim() || [...title].length > maxTitleLength)
31
+ throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Thought title must be non-blank and at most 256 characters.');
32
+ if (typeof content !== 'string' ||
33
+ !content.trim() ||
34
+ Buffer.byteLength(content) > maxContentBytes)
35
+ throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Thought content must be non-blank and at most 32 KiB (UTF-8).');
36
+ return { title, content };
37
+ }
38
+ export async function executeThought(input) {
39
+ readThoughtInput(input);
40
+ return { content: '{"status":"recorded"}' };
41
+ }
@@ -3,6 +3,7 @@ import { TOOL_EXECUTION_LIMITS } from '../execution-limits.js';
3
3
  /** Owns the model-facing Todo contract; Session state and restoration belong to TodoStore. */
4
4
  export const todoToolDefinition = {
5
5
  name: 'todo',
6
+ autoPermission: 'omit',
6
7
  allowedCallers: ['direct', 'programmatic'],
7
8
  parallelSafety: 'safe',
8
9
  description: 'Read or replace the session’s Todo list for coordination-heavy work. action=read returns revision and all items; omit items. action=write replaces the entire list with the supplied items array (empty clears it) and returns a text receipt with revision and count. In Code Mode, both actions return revision and items in data. No prior read or revision precondition is required. The list may contain at most one in_progress item.',
@@ -17,6 +17,8 @@ export interface ClientToolDefinition extends ModelToolDefinition {
17
17
  parallelSafety?: 'safe' | 'serial';
18
18
  /** Preserved business-schema eligibility after framework metadata projection. */
19
19
  parameterless?: boolean;
20
+ /** SDK built-ins only: omit the Auto permission field from a flat JSON model schema. */
21
+ autoPermission?: 'omit';
20
22
  /** Runtime-only Agent catalog scope; never forwarded as an upstream tool field. */
21
23
  agentScope?: 'ROOT_AND_SUBAGENTS' | 'ROOT_ONLY';
22
24
  }
@@ -9,6 +9,7 @@ import { executeRegisteredTool } from './runtime.js';
9
9
  import { failedToolResultExtensions } from './result-extensions.js';
10
10
  import { permissionStopFromError } from './permissions.js';
11
11
  import { scheduleToolCallBatch } from './scheduler.js';
12
+ import { readThoughtInput, THOUGHT_TOOL_NAME, thoughtToolDefinition } from './agent/thought.js';
12
13
  /** Shared raw context construction for physical tools and native calls in a real model round. */
13
14
  export async function createRoundToolRuntimeContext(scope, call, signal) {
14
15
  scope.assertLive();
@@ -89,7 +90,9 @@ export async function createRoundToolRuntimeContext(scope, call, signal) {
89
90
  /** Complete every call in model order even if individual execution fails. */
90
91
  export async function executeRoundTools(calls, scope) {
91
92
  const executeCall = async (call, signal = scope.context.signal, caller = 'direct', parentCallId) => {
92
- const inputFields = scope.tools.find((tool) => tool.name === call.name)?.eventInputFields;
93
+ const inputFields = call.name === THOUGHT_TOOL_NAME
94
+ ? thoughtToolDefinition.eventInputFields
95
+ : scope.tools.find((tool) => tool.name === call.name)?.eventInputFields;
93
96
  const publicInput = inputFields === undefined
94
97
  ? call.arguments
95
98
  : publicToolEventInput(call.arguments, inputFields);
@@ -105,10 +108,16 @@ export async function executeRoundTools(calls, scope) {
105
108
  throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', call.argumentError);
106
109
  if (!scope.tools.some((tool) => tool.name === call.name && allowsToolCaller(tool, caller)))
107
110
  throw new AgentError('MAR_AGENT_TOOL_NOT_AVAILABLE', 'Tool is unavailable in this execution.');
111
+ // Invocation hooks may edit their input; keep the recorded model argument intact.
112
+ let arguments_ = call.arguments;
113
+ if (call.name === THOUGHT_TOOL_NAME) {
114
+ readThoughtInput(arguments_);
115
+ arguments_ = structuredClone(arguments_);
116
+ }
108
117
  const context = await createRoundToolRuntimeContext(scope, call, signal);
109
118
  const runTool = () => {
110
119
  signal.throwIfAborted();
111
- return executeRegisteredTool(call.name, call.arguments, call.callId, context);
120
+ return executeRegisteredTool(call.name, arguments_, call.callId, context);
112
121
  };
113
122
  const rawOutput = call.name === 'code_exec' || call.name === 'code_exec_wait'
114
123
  ? await runTool()
@@ -9,6 +9,7 @@ export const TOOL_SEARCH_LIMITS = Object.freeze({
9
9
  });
10
10
  export const toolSearchToolDefinition = {
11
11
  name: 'tool_search',
12
+ autoPermission: 'omit',
12
13
  description: 'Search and load deferred MCP tools for the next model request. Returns matching names, or an empty list; definitions are supplied separately. Does not execute the discovered tools.',
13
14
  inputSchema: {
14
15
  type: 'object',
@@ -49,7 +49,7 @@ export declare class ExecutionToolPermissions {
49
49
  get stop(): PermissionStop | undefined;
50
50
  assertDispatch(): void;
51
51
  prepare(call: ToolCall, context: InvocationContext, tool: ClientToolDefinition): ToolCall;
52
- authorize(call: ToolCall, context: InvocationContext): Promise<ToolCall>;
52
+ authorize(call: ToolCall, context: InvocationContext, publicInputFields?: readonly string[]): Promise<ToolCall>;
53
53
  }
54
54
  export declare function isToolPermissionFailure(error: unknown): boolean;
55
55
  export declare function withToolPermissions<T>(policy: ExecutionToolPermissions, run: () => T): T;
@@ -1,6 +1,7 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { AgentError } from '../error.js';
4
+ import { publicToolEventInput } from './output-projection.js';
4
5
  const permissionContext = new AsyncLocalStorage();
5
6
  const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
6
7
  const schemaKeys = new Set([
@@ -39,6 +40,8 @@ function flatInput(tool) {
39
40
  }
40
41
  export function projectPermissionTool(tool) {
41
42
  const flat = flatInput(tool);
43
+ if (flat && tool.inputMode !== 'freeform' && tool.autoPermission === 'omit')
44
+ return tool;
42
45
  const parameterless = flat &&
43
46
  Object.keys(tool.inputSchema.properties).length === 0 &&
44
47
  (!Array.isArray(tool.inputSchema.required) || tool.inputSchema.required.length === 0);
@@ -153,7 +156,7 @@ export class ExecutionToolPermissions {
153
156
  }
154
157
  return prepared;
155
158
  }
156
- async authorize(call, context) {
159
+ async authorize(call, context, publicInputFields) {
157
160
  if (call.permission?.action !== 'ask' || !this.approval)
158
161
  return call;
159
162
  const { permission, ...captured } = structuredClone(call);
@@ -173,7 +176,9 @@ export class ExecutionToolPermissions {
173
176
  toolName: call.name,
174
177
  ...(context.parentToolCallId ? { parentCallId: context.parentToolCallId } : {})
175
178
  },
176
- input: structuredClone(captured.arguments),
179
+ input: publicInputFields === undefined
180
+ ? structuredClone(captured.arguments)
181
+ : publicToolEventInput(captured.arguments, publicInputFields),
177
182
  expiresAt: Date.now() + 10 * 60_000
178
183
  };
179
184
  const timer = setTimeout(() => timeout.abort(new AgentError('MAR_AGENT_APPROVAL_EXPIRED', 'Approval expired after 10 minutes without authorizing the tool call.')), 10 * 60_000);
@@ -9,6 +9,7 @@ import { executeToolSearch, toolSearchToolDefinition } from './mcp/tool-search.j
9
9
  import { viewImageToolDefinition } from './local/view-image.js';
10
10
  import { smartCompactToolDefinition, executeSmartCompact } from './agent/smart-compact.js';
11
11
  import { executeSleep, sleepToolDefinition } from './agent/sleep.js';
12
+ import { executeThought, thoughtToolDefinition } from './agent/thought.js';
12
13
  export const BUILTIN_TOOL_DEFINITIONS = [
13
14
  skillToolDefinition,
14
15
  toolSearchToolDefinition,
@@ -21,6 +22,7 @@ export const BUILTIN_TOOL_DEFINITIONS = [
21
22
  applyPatchToolDefinition,
22
23
  questionToolDefinition,
23
24
  todoToolDefinition,
25
+ thoughtToolDefinition,
24
26
  smartCompactToolDefinition,
25
27
  sleepToolDefinition
26
28
  ];
@@ -30,5 +32,6 @@ export const AGENT_TOOL_HANDLERS = new Map([
30
32
  ['smart_compact', executeSmartCompact],
31
33
  ['tool_search', executeToolSearch],
32
34
  ['todo', executeTodo],
35
+ [thoughtToolDefinition.name, executeThought],
33
36
  ['question', executeQuestion]
34
37
  ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myagentroam/agent",
3
- "version": "0.14.33",
3
+ "version": "0.15.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/myagentroam/mar.git",