@myagentroam/agent 0.15.4 → 0.15.5

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.
@@ -1,7 +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
+ import { THOUGHT_TOOL_NAME } from '../runtime/context/thought-contract.js';
5
5
  import { fromJSONSchema } from 'zod';
6
6
  import { ExtensionResourceScope } from './resources.js';
7
7
  /** Builds one immutable catalog from real sources; snapshots keep their captured handlers. */
@@ -1,9 +1,3 @@
1
1
  import type { ModelMessage } from './contracts.js';
2
- /** Adapters persist native items at completion; consumers need only type and identity. */
3
- export declare function completedNativeThinkingIdentity(payload: {
4
- role?: unknown;
5
- provider?: unknown;
6
- item?: unknown;
7
- }, recordId: string): string | undefined;
8
2
  /** Interpret only the existing native context record shapes and their model ownership. */
9
3
  export declare function restoreNativeModelContext(payload: Record<string, unknown>, activeModelId?: string): ModelMessage | undefined;
@@ -1,19 +1,4 @@
1
1
  import { anthropicThinkingBlock } from './anthropic-thinking.js';
2
- /** Adapters persist native items at completion; consumers need only type and identity. */
3
- export function completedNativeThinkingIdentity(payload, recordId) {
4
- if (payload.role !== 'provider')
5
- return undefined;
6
- const item = payload.item;
7
- if (!item || typeof item !== 'object' || Array.isArray(item))
8
- return undefined;
9
- const block = item;
10
- if (payload.provider === 'ANTHROPIC_MESSAGES') {
11
- return block.type === 'thinking' || block.type === 'redacted_thinking' ? recordId : undefined;
12
- }
13
- if (payload.provider !== 'OPENAI_RESPONSES' || block.type !== 'reasoning')
14
- return undefined;
15
- return typeof block.id === 'string' ? block.id : recordId;
16
- }
17
2
  /** Interpret only the existing native context record shapes and their model ownership. */
18
3
  export function restoreNativeModelContext(payload, activeModelId) {
19
4
  const modelId = typeof payload.providerModelId === 'string' && payload.providerModelId.length > 0
@@ -1,4 +1,4 @@
1
- import { THOUGHT_TOOL_NAME } from '../tools/agent/thought.js';
1
+ import { THOUGHT_TOOL_NAME } from '../runtime/context/thought-contract.js';
2
2
  export function toolUsagePrompt(tools, directTools = tools) {
3
3
  const names = new Set(tools);
4
4
  const clauses = [
@@ -1,10 +1,5 @@
1
1
  import type { SessionModelMessage as ModelMessage } from '../../session/model-request.js';
2
2
  import type { CompactSnapshotAnchor } from '../events.js';
3
- /** Keep the live suffix intact, extending into the snapshot only to fill three native blocks. */
4
- export declare function compactRetainedStart(messages: readonly ModelMessage[], snapshotLength: number, model: {
5
- readonly id: string;
6
- readonly protocol: ModelMessage['provider'];
7
- }): number;
8
3
  /** Use a public native identity, never private context text, as the visible boundary. */
9
4
  export declare function compactSnapshotAnchor(messages: readonly ModelMessage[], sources: WeakMap<ModelMessage, import('../../session/record-contract.js').SessionRecord>): CompactSnapshotAnchor | undefined;
10
5
  /** Decode the SDK-owned checkpoint suffix without promoting contextual text to real input. */
@@ -1,49 +1,6 @@
1
1
  import { parseModelInputMetadata } from '../../session/record-projection.js';
2
- import { providerToolCallId, restoreModelContext } from '../context/projection.js';
2
+ import { restoreModelContext } from '../context/projection.js';
3
3
  import { parseModelImages } from '../../model/image.js';
4
- import { completedNativeThinkingIdentity } from '../../model/native-context.js';
5
- /** Keep the live suffix intact, extending into the snapshot only to fill three native blocks. */
6
- export function compactRetainedStart(messages, snapshotLength, model) {
7
- let start = snapshotLength;
8
- const thinking = new Set();
9
- for (let index = messages.length - 1; index >= 0 && thinking.size < 3; index--) {
10
- const message = messages[index];
11
- if (message.provider !== model.protocol ||
12
- (message.providerModelId !== undefined && message.providerModelId !== model.id))
13
- continue;
14
- const identity = completedNativeThinkingIdentity(message, `message:${index}`);
15
- if (identity === undefined || thinking.has(identity))
16
- continue;
17
- thinking.add(identity);
18
- start = Math.min(start, index);
19
- }
20
- // The existing snapshot boundary already closes tool groups.
21
- if (start === snapshotLength)
22
- return start;
23
- // A native item can follow text or tool calls within the same assistant response.
24
- while (start > 0 && messages[start - 1].role !== 'user' && messages[start - 1].role !== 'tool')
25
- start--;
26
- // Resolve any retained result back to its call's assistant group in two linear passes.
27
- const calls = new Map();
28
- let responseStart = 0;
29
- for (let index = 0; index < start; index++) {
30
- const message = messages[index];
31
- if (message.role === 'user' || message.role === 'tool')
32
- responseStart = index + 1;
33
- const callId = message.role === 'tool_call' ? message.callId : providerToolCallId(message);
34
- if (callId !== undefined && !calls.has(callId))
35
- calls.set(callId, responseStart);
36
- }
37
- for (let index = messages.length - 1; index >= start; index--) {
38
- const message = messages[index];
39
- if (message.role !== 'tool' || message.callId === undefined)
40
- continue;
41
- const callStart = calls.get(message.callId);
42
- if (callStart !== undefined)
43
- start = Math.min(start, callStart);
44
- }
45
- return start;
46
- }
47
4
  /** Use a public native identity, never private context text, as the visible boundary. */
48
5
  export function compactSnapshotAnchor(messages, sources) {
49
6
  for (let index = messages.length - 1; index >= 0; index--) {
@@ -35,7 +35,7 @@ export function collectCodeModeCandidates(input, groups, existingTargets, candid
35
35
  evidenceSequence
36
36
  }
37
37
  ],
38
- observedRollouts: protection.rollouts,
38
+ observedRollouts: protection,
39
39
  evidenceSequence
40
40
  };
41
41
  const reclaimedTokens = candidateSavings(candidate);
@@ -99,7 +99,7 @@ export function collectCodeModeCandidates(input, groups, existingTargets, candid
99
99
  if (replacements.length === 0)
100
100
  continue;
101
101
  const protection = input.protection.after(Math.max(evidenceSequence, completionSequence));
102
- const observedRollouts = protection.rollouts;
102
+ const observedRollouts = protection;
103
103
  const candidate = { replacements, observedRollouts, evidenceSequence };
104
104
  const reclaimedTokens = candidateSavings(candidate);
105
105
  if (reclaimedTokens <= 0)
@@ -82,11 +82,11 @@ export function collectExecCandidates(input, groups, existingTargets, candidateS
82
82
  const protection = input.protection.after(Math.max(evidenceSequence, replacement.target.sequence));
83
83
  if (contextGcProtectionMature(protection)) {
84
84
  mature.push(replacement);
85
- observedRollouts = Math.min(observedRollouts, protection.rollouts);
85
+ observedRollouts = Math.min(observedRollouts, protection);
86
86
  }
87
- else if (protection.rollouts < CONTEXT_GC_TEXT_PROTECTION_ROLLOUTS) {
87
+ else {
88
88
  awaitingRollouts.push(replacement);
89
- retryAfterRollouts = Math.min(retryAfterRollouts, CONTEXT_GC_TEXT_PROTECTION_ROLLOUTS - protection.rollouts);
89
+ retryAfterRollouts = Math.min(retryAfterRollouts, CONTEXT_GC_TEXT_PROTECTION_ROLLOUTS - protection);
90
90
  }
91
91
  }
92
92
  if (awaitingRollouts.length)
@@ -105,11 +105,11 @@ export function collectDeterministicCandidates(input, groups, existingReplacemen
105
105
  const protection = input.protection.after(Math.max(evidenceSequence, replacement.target.sequence));
106
106
  if (contextGcProtectionMature(protection)) {
107
107
  mature.push(replacement);
108
- observedRollouts = Math.min(observedRollouts, protection.rollouts);
108
+ observedRollouts = Math.min(observedRollouts, protection);
109
109
  }
110
- else if (protection.rollouts < CONTEXT_GC_TEXT_PROTECTION_ROLLOUTS) {
110
+ else {
111
111
  awaitingRollouts.push(replacement);
112
- retryAfterRollouts = Math.min(retryAfterRollouts, CONTEXT_GC_TEXT_PROTECTION_ROLLOUTS - protection.rollouts);
112
+ retryAfterRollouts = Math.min(retryAfterRollouts, CONTEXT_GC_TEXT_PROTECTION_ROLLOUTS - protection);
113
113
  }
114
114
  }
115
115
  if (awaitingRollouts.length) {
@@ -187,7 +187,7 @@ export function collectDeterministicCandidates(input, groups, existingReplacemen
187
187
  };
188
188
  const candidate = {
189
189
  replacements: [replacement],
190
- observedRollouts: input.protection.after(evidenceSequence).rollouts,
190
+ observedRollouts: input.protection.after(evidenceSequence),
191
191
  evidenceSequence
192
192
  };
193
193
  if (candidateSavings(candidate) > 0) {
@@ -28,7 +28,7 @@ export function collectWebCandidates(input, groups, existingTargets, candidateSa
28
28
  continue;
29
29
  const evidenceSequence = group.result.record.sequence;
30
30
  const protection = input.protection.after(Math.max(evidenceSequence, target.sequence));
31
- const observedRollouts = protection.rollouts;
31
+ const observedRollouts = protection;
32
32
  const candidate = {
33
33
  replacements: [
34
34
  {
@@ -91,7 +91,7 @@ export function collectToolOutputCandidates(input, groups, existingTargets, cand
91
91
  if (evidence.length === 0)
92
92
  continue;
93
93
  const evidenceSequence = Math.max(...evidence);
94
- const observedRollouts = input.protection.after(Math.max(target.sequence, evidenceSequence)).rollouts;
94
+ const observedRollouts = input.protection.after(Math.max(target.sequence, evidenceSequence));
95
95
  const candidate = {
96
96
  replacements: [
97
97
  {
@@ -139,7 +139,7 @@ export function collectToolOutputCandidates(input, groups, existingTargets, cand
139
139
  if (!successor)
140
140
  continue;
141
141
  const evidenceSequence = successor.record.sequence;
142
- const observedRollouts = input.protection.after(Math.max(target.sequence, group.completed.sequence, evidenceSequence)).rollouts;
142
+ const observedRollouts = input.protection.after(Math.max(target.sequence, group.completed.sequence, evidenceSequence));
143
143
  let replacement;
144
144
  if (ownWrite && (group.toolName === 'todo_write' || group.toolName === 'todo')) {
145
145
  const args = group.call.message.arguments;
@@ -201,7 +201,7 @@ export function collectToolOutputCandidates(input, groups, existingTargets, cand
201
201
  if (!successor)
202
202
  continue;
203
203
  const evidenceSequence = successor.result.record.sequence;
204
- const observedRollouts = input.protection.after(Math.max(target.sequence, evidenceSequence)).rollouts;
204
+ const observedRollouts = input.protection.after(Math.max(target.sequence, evidenceSequence));
205
205
  const candidate = {
206
206
  replacements: [
207
207
  {
@@ -241,7 +241,7 @@ export function collectToolOutputCandidates(input, groups, existingTargets, cand
241
241
  continue;
242
242
  const evidenceSequence = group.result.record.sequence;
243
243
  const protection = input.protection.after(Math.max(evidenceSequence, target.sequence));
244
- const observedRollouts = protection.rollouts;
244
+ const observedRollouts = protection;
245
245
  const candidate = {
246
246
  replacements: [
247
247
  {
@@ -0,0 +1,2 @@
1
+ /** Reserved tool identity shared by context management, tool dispatch and extension registration. */
2
+ export declare const THOUGHT_TOOL_NAME = "thought";
@@ -0,0 +1,2 @@
1
+ /** Reserved tool identity shared by context management, tool dispatch and extension registration. */
2
+ export const THOUGHT_TOOL_NAME = 'thought';
@@ -2,7 +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
+ import { THOUGHT_TOOL_NAME } from './context/thought-contract.js';
6
6
  import { publicHostedToolEvents, publicModelUsage } from './event-projection.js';
7
7
  import { PlanOutputPrefix, splitPlanOutput } from './plan-output.js';
8
8
  import { ModelGenerationTiming } from './model-generation-timing.js';
@@ -2,7 +2,6 @@ import type { SessionModelMessage } from '../session/model-request.js';
2
2
  import type { SessionRecord } from '../session/record-contract.js';
3
3
  import type { SessionStore, SessionStoreCompactInput } from '../session/store/contracts.js';
4
4
  import type { ResourceInputProjection } from './resource-input.js';
5
- import { compactRetainedStart } from '../runtime/compaction/retained-context.js';
6
5
  /** Commits one validated snapshot and records its fact before fallible live projection. */
7
6
  export declare function commitExecutionCompaction(input: {
8
7
  readonly store: Pick<SessionStore, 'compact'>;
@@ -10,10 +9,9 @@ export declare function commitExecutionCompaction(input: {
10
9
  readonly signal: AbortSignal;
11
10
  readonly prefix: readonly SessionModelMessage[];
12
11
  readonly messages: readonly SessionModelMessage[];
13
- readonly model: Parameters<typeof compactRetainedStart>[2];
14
12
  readonly generation: string | undefined;
15
13
  readonly messageSources: WeakMap<SessionModelMessage, SessionRecord>;
16
- draft(retainedStart: number): Omit<SessionStoreCompactInput, 'retainedModelContext' | 'inlineMediaState'>;
14
+ draft(): Omit<SessionStoreCompactInput, 'retainedModelContext' | 'inlineMediaState'>;
17
15
  readonly checkpoint: ResourceInputProjection['checkpoint'];
18
16
  readonly withProjection: <T>(action: () => Promise<T>) => Promise<T>;
19
17
  readonly pendingDiscoveryNames: (message: SessionModelMessage) => readonly string[];
@@ -1,5 +1,4 @@
1
1
  import { AgentError } from '../error.js';
2
- import { compactRetainedStart } from '../runtime/compaction/retained-context.js';
3
2
  /** Commits one validated snapshot and records its fact before fallible live projection. */
4
3
  export async function commitExecutionCompaction(input) {
5
4
  return input.withProjection(async () => {
@@ -7,11 +6,10 @@ export async function commitExecutionCompaction(input) {
7
6
  if (input.currentGeneration() !== input.generation ||
8
7
  input.prefix.some((message, index) => input.messages[index] !== message))
9
8
  throw new AgentError('MAR_AGENT_COMPACT_STALE', 'The compaction prefix has changed.');
10
- const retainedStart = compactRetainedStart(input.messages, input.prefix.length, input.model);
11
- if (retainedStart === 0)
9
+ if (input.prefix.length === 0)
12
10
  return undefined;
13
11
  const retained = [
14
- ...input.messages.slice(0, retainedStart).flatMap((message) => {
12
+ ...input.prefix.flatMap((message) => {
15
13
  const receipt = message.mcpDiscovery;
16
14
  if (!receipt)
17
15
  return [];
@@ -24,7 +22,7 @@ export async function commitExecutionCompaction(input) {
24
22
  : [{ ...message, mcpDiscovery: { id: receipt.id, names } }];
25
23
  }),
26
24
  ...input.messages
27
- .slice(retainedStart)
25
+ .slice(input.prefix.length)
28
26
  .filter((message) => message.contextKind !== 'private' || message.role === 'provider')
29
27
  ];
30
28
  const retainedModelContext = retained.map((message) => {
@@ -51,7 +49,7 @@ export async function commitExecutionCompaction(input) {
51
49
  };
52
50
  });
53
51
  const record = await input.store.compact(input.sessionId, {
54
- ...input.draft(retainedStart),
52
+ ...input.draft(),
55
53
  inlineMediaState: input.checkpoint(retained),
56
54
  retainedModelContext
57
55
  }, { signal: input.signal });
@@ -17,7 +17,7 @@ export declare function createExecutionCompaction(ports: {
17
17
  readonly sessionId: string;
18
18
  readonly executionId: string;
19
19
  readonly turnId: string;
20
- readonly model: Pick<ResolvedModelConfiguration, 'id' | 'protocol' | 'contextWindowTokens'>;
20
+ readonly model: Pick<ResolvedModelConfiguration, 'id' | 'contextWindowTokens'>;
21
21
  readonly messages: SessionModelMessage[];
22
22
  readonly pendingInputs: Map<string, SessionRecord>;
23
23
  readonly messageSources: WeakMap<SessionModelMessage, SessionRecord>;
@@ -73,7 +73,6 @@ export function createExecutionCompaction(ports) {
73
73
  signal,
74
74
  prefix,
75
75
  messages,
76
- model: ports.model,
77
76
  generation,
78
77
  messageSources: ports.messageSources,
79
78
  checkpoint: (value) => ports.resourceInput.checkpoint(value),
@@ -88,8 +87,8 @@ export function createExecutionCompaction(ports) {
88
87
  modelContext.replaceCompactMessages(replacementHistory, value);
89
88
  ports.updateBoundary(messages.length - value.length);
90
89
  },
91
- draft: (retainedStart) => {
92
- replacementHistory = buildCompactedHistory(candidate.summary, modelContext.compactInputs(prefix.slice(0, retainedStart)), ports.userTokenLimit);
90
+ draft: () => {
91
+ replacementHistory = buildCompactedHistory(candidate.summary, modelContext.compactInputs(prefix), ports.userTokenLimit);
93
92
  return {
94
93
  summary: candidate.summary,
95
94
  replacementHistory,
@@ -1,5 +1,6 @@
1
1
  import type { ContextGcRuntime, ContextGcRuntimeInput } from '../runtime/context/gc-runtime.js';
2
2
  import type { SessionModelMessage } from '../session/model-request.js';
3
+ import type { SessionRecord } from '../session/record-contract.js';
3
4
  import type { PreparedExecutionRound } from '../runtime/execution.js';
4
5
  import type { RoundToolScope } from '../tools/execution.js';
5
6
  import type { CompactCoordinator, CompactFlight } from '../runtime/compaction/coordinator.js';
@@ -14,6 +15,14 @@ type GcRound = {
14
15
  readonly toolScope: Pick<RoundToolScope, 'tools'>;
15
16
  };
16
17
  type GcUsage = ContextGcRuntimeInput['usage'] | undefined;
18
+ type NaturalTurnGc = {
19
+ readonly usage: GcUsage;
20
+ };
21
+ /** Restore the preceding natural Turn's GC trigger without extending request calibration. */
22
+ export declare function previousNaturalTurnGc(records: readonly SessionRecord[], model: {
23
+ readonly id: string;
24
+ readonly contextWindowTokens: number;
25
+ }): NaturalTurnGc | undefined;
17
26
  /** Coordinates safe-point adoption of Compact and GC without owning Session state. */
18
27
  export declare class ExecutionContextCoordinator {
19
28
  #private;
@@ -30,6 +39,7 @@ export declare class ExecutionContextCoordinator {
30
39
  readonly signal: AbortSignal;
31
40
  readonly window: number;
32
41
  readonly contextGcMode: ContextGcMode;
42
+ readonly naturalTurnGc?: NaturalTurnGc | undefined;
33
43
  readonly gc: Pick<ContextGcRuntime, 'run' | 'skipRollout'>;
34
44
  readonly gcBase: Omit<ContextGcRuntimeInput, 'system' | 'tools' | 'usage' | 'inlineMedia' | 'mediaView' | 'getActiveProcessIds'>;
35
45
  start(input?: {
@@ -55,7 +65,8 @@ export declare class ExecutionContextCoordinator {
55
65
  }): Promise<void>;
56
66
  ensureBudget(): Promise<void>;
57
67
  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. */
68
+ invalidateNaturalTurnGc(): void;
69
+ /** Combine one-shot regular triggers with the dispatch-time image hard limit. */
59
70
  prepareRequestGc(round: GcRound, messages: readonly SessionModelMessage[], latestUsage: GcUsage, media: ContextGcRuntimeInput['inlineMedia']): Promise<boolean>;
60
71
  gc(round: GcRound, usage: GcUsage, media: ContextGcRuntimeInput['inlineMedia'], includeProcesses?: boolean): Promise<boolean>;
61
72
  }
@@ -1,14 +1,73 @@
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
+ import { modelContextUsage } from '../runtime/context/gc-admission.js';
4
+ import { isAgentEvent } from '../session/record-projection.js';
5
+ import { THOUGHT_TOOL_NAME } from '../runtime/context/thought-contract.js';
6
+ /** Restore the preceding natural Turn's GC trigger without extending request calibration. */
7
+ export function previousNaturalTurnGc(records, model) {
8
+ const terminalIndex = records.findLastIndex((record) => record.type === 'execution.started' ||
9
+ record.type === 'execution.completed' ||
10
+ record.type === 'execution.cancelled' ||
11
+ record.type === 'execution.failed');
12
+ const terminal = records[terminalIndex];
13
+ const event = terminal?.payload;
14
+ if (terminal?.type !== 'execution.completed' ||
15
+ !terminal.executionId ||
16
+ !isAgentEvent(event) ||
17
+ event.type !== 'execution.completed' ||
18
+ event.permissionStop !== undefined)
19
+ return undefined;
20
+ let hasAnswer = false;
21
+ let usage;
22
+ let canUseUsage = true;
23
+ for (let index = terminalIndex - 1; index >= 0; index--) {
24
+ const record = records[index];
25
+ if (record.type === 'context.gc.completed')
26
+ canUseUsage = false;
27
+ if (record.executionId !== terminal.executionId)
28
+ continue;
29
+ const payload = record.payload;
30
+ if (record.type === 'execution.started')
31
+ break;
32
+ // A Compact base can replace the execution header in restored context records.
33
+ if (record.type === 'execution.header' || record.type === 'compact.completed') {
34
+ const header = payload;
35
+ if (!hasAnswer || header?.mode === 'compact')
36
+ return undefined;
37
+ return {
38
+ usage: header?.modelId === model.id && header.contextWindowTokens === model.contextWindowTokens
39
+ ? usage
40
+ : undefined
41
+ };
42
+ }
43
+ if (!isAgentEvent(payload))
44
+ continue;
45
+ if (payload.type === 'message.completed' &&
46
+ payload.phase === 'final_answer' &&
47
+ typeof payload.text === 'string' &&
48
+ payload.text.trim())
49
+ hasAnswer = true;
50
+ if (canUseUsage &&
51
+ !usage &&
52
+ payload.type === 'usage.updated' &&
53
+ payload.purpose !== 'compact') {
54
+ const tokens = modelContextUsage(payload);
55
+ if (tokens !== undefined)
56
+ usage = { contextInputTokens: tokens };
57
+ }
58
+ }
59
+ return undefined;
60
+ }
4
61
  /** Coordinates safe-point adoption of Compact and GC without owning Session state. */
5
62
  export class ExecutionContextCoordinator {
6
63
  ports;
7
64
  #boundary;
8
65
  #thoughtCallIds = [];
66
+ #naturalTurnGc;
9
67
  constructor(ports) {
10
68
  this.ports = ports;
11
69
  this.#boundary = ports.initialBoundary;
70
+ this.#naturalTurnGc = ports.naturalTurnGc;
12
71
  }
13
72
  get boundary() {
14
73
  return this.#boundary;
@@ -90,19 +149,25 @@ export class ExecutionContextCoordinator {
90
149
  this.ports.gc.skipRollout(usage, this.ports.window);
91
150
  }
92
151
  }
93
- /** Merge a one-round Thought trigger with the existing dispatch-time hard limit. */
152
+ invalidateNaturalTurnGc() {
153
+ this.#naturalTurnGc = undefined;
154
+ }
155
+ /** Combine one-shot regular triggers with the dispatch-time image hard limit. */
94
156
  async prepareRequestGc(round, messages, latestUsage, media) {
95
157
  const pending = this.#thoughtCallIds;
96
158
  this.#thoughtCallIds = [];
159
+ const naturalTurn = this.#naturalTurnGc;
160
+ this.invalidateNaturalTurnGc();
97
161
  const thought = pending.length > 0 &&
98
162
  messages.some((message) => message.role === 'tool_call' &&
99
163
  message.name === THOUGHT_TOOL_NAME &&
100
164
  message.callId !== undefined &&
101
165
  pending.includes(message.callId));
102
166
  const hardLimit = media?.reason === 'HARD_LIMIT';
103
- if (!thought && !hardLimit)
167
+ if (!thought && !naturalTurn && !hardLimit)
104
168
  return false;
105
- return this.gc(round, latestUsage, media, thought);
169
+ const usage = naturalTurn && !thought ? naturalTurn.usage : latestUsage;
170
+ return this.gc(round, usage, media, thought || naturalTurn?.usage !== undefined);
106
171
  }
107
172
  async gc(round, usage, media, includeProcesses = false) {
108
173
  if (this.ports.contextGcMode === 'off' || this.ports.compact.pending)
@@ -7,7 +7,7 @@ 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 { THOUGHT_TOOL_NAME } from '../tools/agent/thought.js';
10
+ import { THOUGHT_TOOL_NAME } from '../runtime/context/thought-contract.js';
11
11
  /** Initializes one Execution's catalog before Extension attachment owns its bindings. */
12
12
  export async function initializeExecutionToolCatalog(input) {
13
13
  const { host, context } = input;
@@ -11,7 +11,7 @@ import { createExecutionCompactExtension } from './execution-compact-extension.j
11
11
  import { generateExecutionCompaction } from './execution-compact-generation.js';
12
12
  import { createExecutionCompactionFlight } from './execution-compaction-flight.js';
13
13
  import { createExecutionCompaction } from './execution-compaction.js';
14
- import { ExecutionContextCoordinator } from './execution-context-coordinator.js';
14
+ import { ExecutionContextCoordinator, previousNaturalTurnGc } from './execution-context-coordinator.js';
15
15
  import { createExecutionInput } from './execution-input.js';
16
16
  import { createExecutionModelContext } from './execution-model-context.js';
17
17
  import { ExecutionModelLifecycle } from './execution-model-lifecycle.js';
@@ -590,6 +590,9 @@ export function createSessionExecutionFactory(ports) {
590
590
  signal: controller.signal,
591
591
  window: selectedModel.contextWindowTokens,
592
592
  contextGcMode,
593
+ naturalTurnGc: contextGcMode !== 'off' && mode !== 'compact' && internal.inputSource === undefined
594
+ ? previousNaturalTurnGc(contextRecords, selectedModel)
595
+ : undefined,
593
596
  gc: contextGc,
594
597
  gcBase: {
595
598
  store,
@@ -611,6 +614,7 @@ export function createSessionExecutionFactory(ports) {
611
614
  });
612
615
  applyCompactBoundary = (value) => contextCoordinator.setBoundary(value);
613
616
  const invalidateCompactUsage = () => {
617
+ contextCoordinator.invalidateNaturalTurnGc();
614
618
  modelLifecycle.invalidate();
615
619
  requestReasoningEffort = prepareModelConfiguration(selectedModel, reasoningEffort, {
616
620
  checkpointAdopted: true
@@ -86,6 +86,7 @@ export declare class SessionExecution {
86
86
  }) | (import("./types.js").AgentEventBase & {
87
87
  type: "execution.cancelled";
88
88
  }) | undefined;
89
+ private readonly steer;
89
90
  bindViews(views: Partial<Pick<SessionExecutionContext, 'requestMessages' | 'appendedMessages' | 'toolSources'>>): void;
90
91
  acceptSteer(steer: NonNullable<SessionExecutionContext['steer']>): void;
91
92
  stopSteer(): void;
@@ -22,11 +22,21 @@ export class SessionExecution {
22
22
  #contextInvalid = false;
23
23
  #contextFailure;
24
24
  #bindings;
25
+ // The handle exists before its first input is committed. This only gates entry to the mailbox.
26
+ #steerReady = Promise.withResolvers();
27
+ steer = async (input, source) => {
28
+ if (input.expectedExecutionId !== this.executionId)
29
+ return { status: 'notAccepted' };
30
+ if (!this.#bindings.steer)
31
+ await this.#steerReady.promise;
32
+ return this.#bindings.steer?.(input, source) ?? { status: 'notAccepted' };
33
+ };
25
34
  bindViews(views) {
26
35
  Object.assign(this.#bindings, views);
27
36
  }
28
37
  acceptSteer(steer) {
29
38
  this.#bindings = { ...this.#bindings, steer };
39
+ this.#steerReady.resolve();
30
40
  }
31
41
  stopSteer() {
32
42
  delete this.#bindings.steer;
@@ -39,7 +49,8 @@ export class SessionExecution {
39
49
  delete this.#bindings.requestMessages;
40
50
  this.retireCompactRequests(reason);
41
51
  delete this.#bindings.appendedMessages;
42
- delete this.#bindings.steer;
52
+ this.stopSteer();
53
+ this.#steerReady.resolve();
43
54
  }
44
55
  detachToolSources() {
45
56
  delete this.#bindings.toolSources;
@@ -91,9 +102,7 @@ export class SessionExecution {
91
102
  get compactRequests() {
92
103
  return bindings().compactRequests;
93
104
  },
94
- get steer() {
95
- return bindings().steer;
96
- },
105
+ ...(kind === 'compact' ? {} : { steer: this.steer }),
97
106
  get requestMessages() {
98
107
  return bindings().requestMessages;
99
108
  },
@@ -428,5 +437,6 @@ export class SessionExecution {
428
437
  if (this.completionAdmitted)
429
438
  return;
430
439
  this.controller.abort(reason);
440
+ this.#steerReady.resolve();
431
441
  }
432
442
  }
@@ -1,13 +1,7 @@
1
1
  import type { SessionRecord } from './record-contract.js';
2
2
  export declare const CONTEXT_GC_TEXT_PROTECTION_ROLLOUTS = 10;
3
- export declare function contextGcProtectionMature(count: {
4
- readonly rollouts: number;
5
- readonly thinking: number;
6
- }): boolean;
3
+ export declare function contextGcProtectionMature(rollouts: number): boolean;
7
4
  /** One immutable boundary index; Compact seeds configuration when its execution header is sliced out. */
8
5
  export declare function buildContextGcProtection(records: readonly SessionRecord[], modelId: string, contextWindowTokens: number): {
9
- after(anchor: number): {
10
- rollouts: number;
11
- thinking: number;
12
- };
6
+ after(anchor: number): number;
13
7
  };
@@ -1,14 +1,12 @@
1
- import { completedNativeThinkingIdentity } from '../model/native-context.js';
2
1
  export const CONTEXT_GC_TEXT_PROTECTION_ROLLOUTS = 10;
3
- export function contextGcProtectionMature(count) {
4
- return count.rollouts >= CONTEXT_GC_TEXT_PROTECTION_ROLLOUTS && count.thinking >= 3;
2
+ export function contextGcProtectionMature(rollouts) {
3
+ return rollouts >= CONTEXT_GC_TEXT_PROTECTION_ROLLOUTS;
5
4
  }
6
5
  /** One immutable boundary index; Compact seeds configuration when its execution header is sliced out. */
7
6
  export function buildContextGcProtection(records, modelId, contextWindowTokens) {
8
7
  const configurations = new Map();
9
8
  const attempts = new Map();
10
9
  const successful = [];
11
- const thinking = [];
12
10
  let baseline = { modelId, window: contextWindowTokens };
13
11
  for (const record of records) {
14
12
  if (record.type === 'compact.completed' && isRecord(record.payload)) {
@@ -21,7 +19,7 @@ export function buildContextGcProtection(records, modelId, contextWindowTokens)
21
19
  continue;
22
20
  }
23
21
  if (!record.executionId ||
24
- !['execution.header', 'model.attempt', 'model.context'].includes(record.type) ||
22
+ (record.type !== 'execution.header' && record.type !== 'model.attempt') ||
25
23
  !isRecord(record.payload))
26
24
  continue;
27
25
  const key = record.executionId;
@@ -34,49 +32,26 @@ export function buildContextGcProtection(records, modelId, contextWindowTokens)
34
32
  : contextWindowTokens
35
33
  });
36
34
  }
37
- else if (record.type === 'model.attempt') {
38
- if (payload.purpose !== 'EXECUTION')
39
- continue;
35
+ else if (payload.purpose === 'EXECUTION') {
40
36
  if (payload.state === 'STARTED') {
41
37
  const configuration = configurations.get(key) ?? baseline;
42
- attempts.set(key, {
43
- start: record.sequence,
44
- matching: payload.purpose === 'EXECUTION' &&
45
- configuration.modelId === modelId &&
46
- configuration.window === contextWindowTokens,
47
- native: new Set()
48
- });
38
+ if (configuration.modelId === modelId && configuration.window === contextWindowTokens)
39
+ attempts.set(key, record.sequence);
40
+ else
41
+ attempts.delete(key);
49
42
  }
50
43
  else if (payload.state === 'SUCCEEDED' || payload.state === 'FAILED') {
51
- const attempt = attempts.get(key);
52
- if (attempt?.matching) {
53
- if (payload.state === 'SUCCEEDED')
54
- successful.push(attempt.start);
55
- for (let i = 0; i < attempt.native.size; i++)
56
- thinking.push(attempt.start);
57
- }
44
+ const start = attempts.get(key);
45
+ if (start !== undefined && payload.state === 'SUCCEEDED')
46
+ successful.push(start);
58
47
  attempts.delete(key);
59
48
  }
60
49
  }
61
- else if (record.type === 'model.context') {
62
- const attempt = attempts.get(key);
63
- if (!attempt?.matching ||
64
- (typeof payload.providerModelId === 'string' && payload.providerModelId !== modelId))
65
- continue;
66
- const identity = completedNativeThinkingIdentity(payload, record.recordId);
67
- if (identity !== undefined)
68
- attempt.native.add(identity);
69
- }
70
50
  }
71
- for (const attempt of attempts.values())
72
- if (attempt.matching)
73
- for (let i = 0; i < attempt.native.size; i++)
74
- thinking.push(attempt.start);
75
51
  successful.sort((a, b) => a - b);
76
- thinking.sort((a, b) => a - b);
77
52
  return {
78
53
  after(anchor) {
79
- return { rollouts: afterCount(successful, anchor), thinking: afterCount(thinking, anchor) };
54
+ return afterCount(successful, anchor);
80
55
  }
81
56
  };
82
57
  }
@@ -1,5 +1,4 @@
1
1
  import type { ClientToolDefinition } from '../contracts.js';
2
- export declare const THOUGHT_TOOL_NAME = "thought";
3
2
  export declare const thoughtToolDefinition: ClientToolDefinition;
4
3
  /** Validate the note fields independently of the invocation's framework metadata. */
5
4
  export declare function readThoughtInput(input: unknown): {
@@ -1,5 +1,5 @@
1
1
  import { AgentError } from '../../error.js';
2
- export const THOUGHT_TOOL_NAME = 'thought';
2
+ import { THOUGHT_TOOL_NAME } from '../../runtime/context/thought-contract.js';
3
3
  const maxTitleLength = 256;
4
4
  const maxContentBytes = 32 * 1024;
5
5
  export const thoughtToolDefinition = {
@@ -1,4 +1,5 @@
1
1
  import { AgentError, describeAgentError } from '../error.js';
2
+ import { THOUGHT_TOOL_NAME } from '../runtime/context/thought-contract.js';
2
3
  import { toolEventSummary } from '../runtime/event-projection.js';
3
4
  import { allowsToolCaller } from './callers.js';
4
5
  import { CodeCellExecutionError } from './code-mode/cells.js';
@@ -9,7 +10,7 @@ import { executeRegisteredTool } from './runtime.js';
9
10
  import { failedToolResultExtensions } from './result-extensions.js';
10
11
  import { permissionStopFromError } from './permissions.js';
11
12
  import { scheduleToolCallBatch } from './scheduler.js';
12
- import { readThoughtInput, THOUGHT_TOOL_NAME, thoughtToolDefinition } from './agent/thought.js';
13
+ import { readThoughtInput, thoughtToolDefinition } from './agent/thought.js';
13
14
  /** Shared raw context construction for physical tools and native calls in a real model round. */
14
15
  export async function createRoundToolRuntimeContext(scope, call, signal) {
15
16
  scope.assertLive();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myagentroam/agent",
3
- "version": "0.15.4",
3
+ "version": "0.15.5",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/myagentroam/mar.git",