@robota-sdk/agent-session 3.0.0-beta.79 → 3.0.0-beta.82

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.
package/README.md CHANGED
@@ -23,6 +23,10 @@ const session = new Session({
23
23
  provider,
24
24
  systemMessage: 'You are a helpful assistant.',
25
25
  terminal,
26
+ // ARCH-010: required. The session's execution root feeds every hook input, CLAUDE_PROJECT_DIR, the
27
+ // permission root and the persisted record — it is not read from the process any more, so a
28
+ // subagent runs in its own workspace rather than its parent's.
29
+ cwd: process.cwd(),
26
30
  permissions: { allow: ['Read(*)'], deny: [] },
27
31
  autoCompactThreshold: 0.75,
28
32
  });
@@ -37,61 +41,81 @@ console.log(`${state.usedPercentage.toFixed(1)}% context used`);
37
41
  await session.compact('Focus on the API changes');
38
42
  ```
39
43
 
44
+ ## Replay log validation
45
+
46
+ `FileSessionLogger` writes versioned JSONL. `loadSessionLogEntries` and
47
+ `decodeSessionLogEntries` validate every declared event before replay, including nested messages.
48
+ Unknown events, malformed fields, and unsupported versions raise `SessionLogDecodeError` with safe
49
+ field/line diagnostics. No malformed message is silently dropped or given an invented ID or date.
50
+ Unversioned legacy logs are not accepted; persisted session snapshots keep their existing format.
51
+
40
52
  ## Features
41
53
 
42
- | Feature | Description |
43
- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
44
- | **Permission enforcement** | Tool calls gated by 3-step policy (deny list, allow list, mode policy) |
45
- | **Hook execution** | PreToolUse, PostToolUse, PreCompact, PostCompact, SessionStart, Stop |
46
- | **Context tracking** | Effective token usage from the shared core estimator, configurable auto-compact threshold (default ~83.5%) |
47
- | **Compaction** | LLM-generated conversation summary to free context space; an invalid summary throws `CompactionError` and leaves history untouched |
48
- | **Persistence** | `SessionStore` for JSON file-based session save/load (atomic temp-file + rename writes) |
49
- | **Abort** | Cancel via `session.abort()` — propagates AbortSignal to `robota.run()`, throws `AbortError` to caller |
50
- | **Session logging** | `FileSessionLogger` writes JSONL event logs |
51
- | **Replay events** | Provider/tool execution boundary events are forwarded from core into append-only session logs |
52
- | **Provider capabilities** | Generic native web capability setup is requested through the provider contract, not provider-name branches |
54
+ | Feature | Description |
55
+ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
56
+ | **Permission enforcement** | Tool calls gated by 3-step policy (deny list, allow list, mode policy) |
57
+ | **Hook execution** | PreToolUse, PostToolUse, PreModelCall, PostModelCall, PreCompact, PostCompact, SessionStart, Stop; model-call hooks include selected effort (`auto` when unset) |
58
+ | **Context tracking** | Effective token usage from the shared core estimator, configurable auto-compact threshold (default ~83.5%) |
59
+ | **Compaction** | LLM-generated conversation summary to free context space; an invalid summary throws `CompactionError` and leaves history untouched |
60
+ | **Persistence** | `IInteractiveSessionStore` injection; each completed `run()` and shutdown persist through the store; explicit `NodeSessionStore` uses atomic temp-file + rename writes |
61
+ | **Abort** | Cancel via `session.abort()` — propagates AbortSignal to `robota.run()`, throws `AbortError` to caller |
62
+ | **One turn at a time** | A concurrent `run()` is refused with `SessionBusyError` (RUNTIME-003); `isRunning()` is authoritative — see SPEC § Turn Identity |
63
+ | **Session logging** | `FileSessionLogger` writes JSONL through an injected neutral sink; `NodeSessionLogSink` is the explicit host adapter |
64
+ | **Replay events** | Provider/tool execution boundary events are forwarded from core into append-only session logs |
65
+ | **Usage observations** | Content-free top-level turn outcomes and invocation-scoped provider usage identities are preserved for cross-session analytics |
66
+ | **Provider capabilities** | Generic native web capability setup is requested through the provider contract, not provider-name branches |
53
67
 
54
68
  ## Key Methods
55
69
 
56
- | Method | Description |
57
- | ------------------------------------------------- | ------------------------------------------------------------------ |
58
- | `constructor(options)` (with `sessionId`) | Accepts optional `sessionId` for deterministic IDs |
59
- | `run(message)` | Send a message, returns AI response |
60
- | `injectMessage(message)` | Inject a message into history without running the agent |
61
- | `compact(instructions?)` | Compress conversation via LLM summary |
62
- | `getContextState()` | Effective token usage: `{ usedTokens, maxTokens, usedPercentage }` |
63
- | `getAutoCompactThreshold()` | Auto-compact threshold fraction, or `false` if disabled |
64
- | `getPermissionMode()` / `setPermissionMode(mode)` | Read/change permission mode |
65
- | `getHistory()` / `clearHistory()` | Access or clear conversation history |
66
- | `abort()` | Cancel running execution |
67
- | `isRunning()` | Returns true if a `run()` call is in progress |
68
- | `getSessionId()` | Returns the stable session identifier |
69
- | `getMessageCount()` | Returns the number of completed `run()` calls |
70
- | `getSessionAllowedTools()` | Tools approved for this session |
71
- | `clearSessionAllowedTools()` | Clears all session-scoped allow rules |
70
+ | Method | Description |
71
+ | ------------------------------------------------- | ----------------------------------------------------------------------- |
72
+ | `constructor(options)` (with `sessionId`) | Accepts optional `sessionId` for deterministic IDs |
73
+ | `run(message)` | Send a message, returns AI response |
74
+ | `injectMessage(message)` | Inject a message into history without running the agent |
75
+ | `compact(instructions?)` | Compress conversation via LLM summary |
76
+ | `getContextState()` | Effective token usage: `{ usedTokens, maxTokens, usedPercentage }` |
77
+ | `getAutoCompactThreshold()` | Auto-compact threshold fraction, or `false` if disabled |
78
+ | `getPermissionMode()` / `setPermissionMode(mode)` | Read/change permission mode |
79
+ | `getModelEffort()` | Read the model-effort selection for the next call (`auto` when unset) |
80
+ | `getHistory()` / `clearHistory()` | Access or clear conversation history |
81
+ | `abort()` | Signal the running turn to stop (it holds the session until it unwinds) |
82
+ | `isRunning()` | True while a turn is in flight, including one aborted and unwinding |
83
+ | `getSessionId()` | Returns the stable session identifier |
84
+ | `getMessageCount()` | Returns the number of completed `run()` calls |
85
+ | `getSessionAllowedTools()` | Tools approved for this session |
86
+ | `getRecentPermissionDenials()` | Calls this session refused, most recent first, with the reason |
87
+ | `clearSessionAllowedTools()` | Clears all session-scoped allow rules |
72
88
 
73
89
  ## Public API Surface
74
90
 
75
- | Export | Kind | Description |
76
- | ------------------------ | --------- | ------------------------------------------------------------ |
77
- | `Session` | Class | Wraps Robota with permissions, hooks, streaming, persistence |
78
- | `PermissionEnforcer` | Class | Tool permission checking, hook execution, output truncation |
79
- | `ContextWindowTracker` | Class | Effective token usage tracking and auto-compact threshold |
80
- | `CompactionOrchestrator` | Class | Conversation compaction via LLM summary |
81
- | `SessionStore` | Class | JSON file persistence for session records |
82
- | `FileSessionLogger` | Class | JSONL file-based session event logger |
83
- | `SilentSessionLogger` | Class | No-op session logger |
84
- | `ISessionOptions` | Interface | Constructor options for Session |
85
- | `TAutoCompactThreshold` | Type | Auto-compact threshold fraction, or `false` to disable |
86
- | `TPermissionHandler` | Type | Custom permission approval callback |
87
- | `TPermissionResult` | Type | Permission decision result (`boolean \| 'allow-session'`) |
88
- | `ITerminalOutput` | Interface | Terminal I/O abstraction (write, prompt, select, spinner) |
89
- | `ISpinner` | Interface | Spinner handle |
90
- | `ISessionLogger` | Interface | Pluggable session event logger interface |
91
- | `TSessionLogData` | Type | Structured log event data |
92
- | `ISessionRecord` | Interface | Persisted session record shape (includes `history` field) |
93
- | `ISessionStore` | Interface | Minimal persistence port implemented by `SessionStore` |
94
- | `IContextWindowState` | Type | Context window usage state (re-exported from agent-core) |
91
+ | Export | Kind | Description |
92
+ | ------------------------------------------ | --------- | -------------------------------------------------------------------------- |
93
+ | `Session` | Class | Wraps Robota with permissions, hooks, streaming, persistence |
94
+ | `PermissionEnforcer` | Class | Tool permission checking, hook execution, output truncation |
95
+ | `ContextWindowTracker` | Class | Effective token usage tracking and auto-compact threshold |
96
+ | `CompactionOrchestrator` | Class | Conversation compaction via LLM summary |
97
+ | `NodeSessionStore` | Class | Explicit host-filesystem JSON persistence adapter |
98
+ | `FileSessionLogger` | Class | Sink-driven JSONL session event logger |
99
+ | `NodeSessionLogSource` | Class | Explicit host adapter for a JSONL log and relative payload sidecars |
100
+ | `NodeSessionLogSink` | Class | Explicit host adapter for JSONL append and payload sidecars |
101
+ | `NodeExternalPayloadSource` | Class | Linux stable-handle host adapter for budget-bounded sidecar reads |
102
+ | `createSessionLogExternalPayloadReference` | Function | Validates and constructs the canonical content-addressed sidecar reference |
103
+ | `SilentSessionLogger` | Class | No-op session logger |
104
+ | `ISessionOptions` | Interface | Constructor options for Session |
105
+ | `TAutoCompactThreshold` | Type | Auto-compact threshold fraction, or `false` to disable |
106
+ | `TPermissionHandler` | Type | Custom permission approval callback |
107
+ | `TPermissionResult` | Type | Permission decision result (`boolean \| 'allow-session'`) |
108
+ | `ITerminalOutput` | Interface | Terminal I/O abstraction (write, prompt, select, spinner) |
109
+ | `ISpinner` | Interface | Spinner handle |
110
+ | `ISessionLogger` | Interface | Pluggable session event logger interface |
111
+ | `TSessionLogData` | Type | Structured log event data |
112
+ | `resolveSessionLogExternalPayloads` | Function | Bounded, integrity-checked hydration of JSON sidecar references |
113
+ | `SessionLogPayloadResolutionError` | Class | Typed sidecar resolution failure with a stable error code |
114
+ | `IInteractiveSessionRecord` | Interface | Canonical persisted session record (owned by agent-interface-transport) |
115
+ | `IInteractiveSessionStore` | Interface | Canonical persistence port implemented by `NodeSessionStore` |
116
+ | `ISessionLogSource` / `ISessionLogSink` | Interface | Neutral log read/write ports used by framework authority adapters |
117
+ | `ISessionRecord` / `ISessionStore` | Type | Compatibility-only renamed re-exports of the canonical contracts |
118
+ | `IContextWindowState` | Type | Context window usage state (re-exported from agent-core) |
95
119
 
96
120
  Note: `IPermissionEnforcerOptions` is an internal type and is not exported from the public API.
97
121
 
@@ -108,9 +132,23 @@ Note: `IPermissionEnforcerOptions` is an internal type and is not exported from
108
132
  - **`Robota`** (agent-core): Raw agent — conversation + tools + plugins. No permissions, no hooks.
109
133
  - **`Session`** (this package): Wraps Robota with permissions, hooks, compaction, and persistence. Used by the CLI and SDK.
110
134
 
111
- ### ISessionRecord
135
+ ### Interactive session record
136
+
137
+ `IInteractiveSessionRecord` is owned by `@robota-sdk/agent-interface-transport` and carries the full conversation and resumable state. `NodeSessionStore` persists this record without inspecting its payload. It is a conspicuously named host adapter: passing a directory does not establish workspace trust. Framework project composition instead adapts an accepted project-authority state facet to the same neutral store port. When a raw `Session` re-saves an existing record, it preserves fields it does not own and refreshes only its live conversation, history, prompt, schema, path, and timestamp fields.
112
138
 
113
- `ISessionRecord` includes a required `history` field (`IHistoryEntry[]`) that stores the full conversation timeline for session persistence, resume, and fork operations. It may also include `backgroundTasks` and `backgroundTaskEvents` so background work can be restored and debugged alongside the conversation. When a session is resumed, history entries are replayed via `Session.injectMessage()`.
139
+ When a raw `Session` re-saves an existing record, it preserves fields it does not own and refreshes
140
+ only its live conversation, history, prompt, schema, path, and timestamp fields. A resumed session
141
+ must reuse the record ID when its new turns are intended to update that record; sessions without a
142
+ store remain transient.
143
+
144
+ Session-log parsing is source-driven. `loadSessionLogEntries(source)` consumes an explicit
145
+ `ISessionLogSource`; it never converts a filename into filesystem authority. Use
146
+ `NodeSessionLogSource` only when the application deliberately owns the host path, or provide a
147
+ framework authority-backed source for project logs. Empty or whitespace-only Node log paths are
148
+ rejected before sidecar authority is derived. Externalized sidecars use a bounded, stable
149
+ root-relative reader on qualified Linux x64/arm64, macOS x64/arm64, and Windows x64 hosts. Parent or
150
+ final symlink/reparse replacement is refused rather than retried through an ambient pathname, and an
151
+ unsupported native capability is reported as `STABLE_PAYLOAD_READ_UNAVAILABLE`.
114
152
 
115
153
  Streaming text deltas are written to append-only JSONL session logs as `text_delta` events. Consumers should store high-frequency streaming chunks in JSONL logs/transcripts and keep session JSON focused on resumable snapshots and references.
116
154
 
@@ -130,18 +168,46 @@ Streaming text deltas are written to append-only JSONL session logs as `text_del
130
168
  - `tool_message_committed`
131
169
  - `history_mutation`
132
170
 
133
- `FileSessionLogger` redacts common secret fields before writing logs and stores large fields as content-addressed JSON payload references under `{sessionId}.payloads/`. `session-log-replay` exports replay readers and validators that reconstruct chat history from `history_mutation` and report missing provider/tool terminal events. Replay validation now also requires provider-native raw response or stream payload coverage for each `provider_request`.
171
+ `SESSION_LOG_EVENT` is the complete production and replay-reader vocabulary. Direct logger calls and core
172
+ execution-event literals must be members of that shared list, and the coverage test scans every source so a
173
+ new event cannot silently become writer-only or reader-only.
174
+
175
+ Manual and automatic compaction also share one session-owned trigger value. The same `manual` or `auto`
176
+ value reaches PreCompact, PostCompact, the `context_compact` log entry, and `onCompactEvent`; instructions
177
+ do not cause the compaction orchestrator to reclassify the trigger.
178
+
179
+ `FileSessionLogger` redacts common secret fields before writing logs and stores large fields as
180
+ content-addressed JSON payload references under `{sessionId}.payloads/`. `loadSessionLogEntries()`
181
+ hydrates those sidecars before replay and fails closed on malformed references, path/symlink escape,
182
+ missing or unreadable files, byte-length/hash mismatch, invalid JSON, cycles, or configured depth/byte
183
+ limits. Each source read receives the remaining aggregate byte budget; the Node adapter checks it before
184
+ allocation and reads from the same no-follow descriptor it validated. `session-log-replay` exports replay
185
+ readers and validators that reconstruct chat history from
186
+ `history_mutation` and report missing provider/tool terminal events; an unresolved history message or
187
+ normalized provider response is replay-incomplete. Replay validation also requires provider-native raw
188
+ response or stream payload coverage for each `provider_request`. Direct `NodeSessionLogSink` calls reject
189
+ unsafe session path components and reject payload digests that are malformed or do not hash the supplied
190
+ serialized content. Host and authority-backed sinks share
191
+ `createSessionLogExternalPayloadReference()` as the validation and reference-construction SSOT.
134
192
 
135
193
  A migration script is available for upgrading session records from older formats. See the package source for details.
136
194
 
137
195
  ## Assembly
138
196
 
139
- Most users should use `createSession()` from `@robota-sdk/agent-framework` instead of constructing `Session` directly. The SDK factory wires tools, provider, and system prompt automatically from config and context.
197
+ Most users should use `InteractiveSession` or `createQuery()` from `@robota-sdk/agent-framework` — or `createAgentRuntime().createSession()` for multi-session runtimes — instead of constructing `Session` directly. (`createSession()` itself is an internal assembly factory and is not part of the public entry.) The SDK wires tools, provider, and system prompt automatically from config and context.
140
198
 
141
199
  ## Dependencies
142
200
 
143
201
  - `@robota-sdk/agent-core` (production) — Robota agent, permission system, hook system, core types
144
202
 
203
+ ## Legacy Session Migration
204
+
205
+ For legacy session history, run `node scripts/migrate-session-history.mjs --sessions-dir
206
+ <absolute-directory>` from `packages/agent-session` in the repository. This writes the selected
207
+ legacy session files; back them up first. The disposable example
208
+ `node examples/verify-session-history-migration.mjs` checks conversion without using your stored
209
+ sessions. See [Session Data Migration](./docs/SPEC.md) for the exact policy.
210
+
145
211
  ## License
146
212
 
147
213
  Robota is dual-licensed under the [GNU AGPL-3.0](../../LICENSE) or a [commercial license](../../COMMERCIAL.md). See [LICENSING.md](../../LICENSING.md).
@@ -1,6 +1,9 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@robota-sdk/agent-core"),t=require("node:crypto"),n=require("node:fs"),r=require("node:path"),i=require("fs"),a=require("path");var o=class{getPermissionMode(){return this.permissionMode}setPermissionMode(e){this.permissionMode=e}getActivePresetId(){return this.activePresetId}setActivePresetId(e){this.activePresetId=e}getParallelSubagentsEnabled(){return this.parallelSubagentsEnabled}setParallelSubagentsEnabled(e){this.parallelSubagentsEnabled=e}getSessionId(){return this.sessionId}getSystemMessage(){return this.systemMessage}updateSystemMessage(e){this.systemMessage=e,this.robota.updateSystemPrompt(e)}async applyModelOptions(e){await this.robota.ensureReady();let t=e.model??this.model;this.robota.setModel({provider:this.aiProvider.name,model:t,...e.effort!==void 0&&{effort:e.effort},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxOutputTokens!==void 0&&{maxTokens:e.maxOutputTokens}}),this.model=t}getToolSchemas(){return this.toolSchemas}getMessageCount(){return this.messageCount}getSessionAllowedTools(){return this.permissionEnforcer.getSessionAllowedTools()}clearSessionAllowedTools(){this.permissionEnforcer.clearSessionAllowedTools()}abort(){this.abortController&&=(this.abortController.abort(),null)}isRunning(){return this.abortController!==null}getContextState(){return this.contextTracker.getContextState()}syncContextFromHistory(){this.contextTracker.updateFromHistory(this.robota.getHistory())}getAutoCompactThreshold(){return this.contextTracker.getAutoCompactThreshold()}setAutoCompactThreshold(e){this.contextTracker.setAutoCompactThreshold(e)}getHistory(){return this.robota.getHistory()}getFullHistory(){return this.robota.getFullHistory()}getSessionTokenUsage(){let e=0,t=0,n=!1;for(let r of this.getFullHistory()){if(r.category!==`event`||r.type!==`usage-summary`)continue;let i=r.data;e+=i?.promptTokens??0,t+=i?.completionTokens??0,n=!0}return n?{inputTokens:e,outputTokens:t}:void 0}getModelId(){return this.model}addHistoryEntry(e){this.robota.addHistoryEntry(e)}injectMessage(e,t,n){this.robota.injectMessage(e,t,n)}injectRawMessage(e){this.robota.injectRawMessage(e)}clearHistory(){this.robota.clearHistory(),this.contextTracker.reset()}},s=class extends Error{constructor(e){super(e),this.name=`CompactionError`}},c=class{sessionId;cwd;model;hooks;compactInstructions;hookTypeExecutors;constructor(e){this.sessionId=e.sessionId,this.cwd=e.cwd,this.model=e.model,this.hooks=e.hooks,this.compactInstructions=e.compactInstructions,this.hookTypeExecutors=e.hookTypeExecutors}async compact(n,r,i){if(r.length===0)return``;let a=i===void 0?`auto`:`manual`,o={session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PreCompact`,trigger:a};await(0,e.runHooks)(this.hooks,`PreCompact`,o,this.hookTypeExecutors);let c=this.buildCompactionPrompt(r,i),l=await n.chat([{id:(0,t.randomUUID)(),role:`user`,content:c,state:`complete`,timestamp:new Date}],{model:this.model});if(typeof l.content!=`string`||l.content.trim()===``)throw new s(`Compaction produced an invalid summary (provider=${n.name}, content type=${typeof l.content}); conversation history preserved untouched`);return l.content}buildCompactionPrompt(e,t){let n=t??this.compactInstructions??``;return[`Summarize the following conversation concisely, preserving:`,`- User's original requests and goals`,`- Key decisions and conclusions`,`- Important code changes and file paths`,`- Current task status and next steps`,n?`\nAdditional focus:\n${n}\n`:``,`Drop verbose tool outputs, debugging steps, and exploratory work that didn't lead to results.`,``,`Conversation:`,e.map(e=>{let t=typeof e.content==`string`?e.content:JSON.stringify(e.content);return`${e.role}: ${t}`}).join(`
2
- `)].join(`
3
- `)}};const l=.835;var u=class{contextUsedTokens=0;contextMaxTokens;autoCompactThreshold;constructor(t,n,r){this.contextMaxTokens=n??(0,e.getModelContextWindow)(t),this.autoCompactThreshold=d(r)}getContextState(){let e=Math.min(100,this.contextUsedTokens/this.contextMaxTokens*100);return{maxTokens:this.contextMaxTokens,usedTokens:this.contextUsedTokens,usedPercentage:Math.round(e*100)/100,remainingPercentage:Math.round((100-e)*100)/100}}shouldAutoCompact(){return this.autoCompactThreshold===!1?!1:this.getContextState().usedPercentage>=this.autoCompactThreshold*100}getAutoCompactThreshold(){return this.autoCompactThreshold}setAutoCompactThreshold(e){this.autoCompactThreshold=d(e)}updateFromHistory(t){this.contextUsedTokens=(0,e.estimateContextTokensFromMessages)(t).usedTokens}reset(){this.contextUsedTokens=0}};function d(e){if(e===void 0)return l;if(e===!1)return!1;if(!Number.isFinite(e)||e<=0||e>1)throw RangeError(`autoCompactThreshold must be a number greater than 0 and at most 1.`);return e}const f={success:!0,data:JSON.stringify({success:!1,output:``,error:`Permission denied. The user did not approve this action.`}),metadata:{}},p=(0,e.createLogger)(`ToolHookHelpers`);function m(e){if(typeof e.data!=`string`||e.data.length<=3e4)return e;let t=15e3,n=e.data.substring(0,t),r=e.data.substring(e.data.length-t),i=`${n}\n\n[... output truncated: ${e.data.length.toLocaleString()} chars total, showing first and last ${t.toLocaleString()} chars ...]\n\n${r}`;return{...e,data:i}}function h(e,t,n,r,i,a){return{session_id:e,cwd:t,hook_event_name:`PreToolUse`,tool_name:n,tool_input:r,...i!==void 0&&{permission_mode:i},...a!==void 0&&{transcript_path:a}}}async function g(t,n,r){let i=await(0,e.runHooks)(t,`PreToolUse`,n,r);return i.blocked?{success:!0,data:JSON.stringify({blocked:!0,reason:i.reason??`Blocked by hook`}),metadata:{}}:null}function _(t,n,r,i){(0,e.runHooks)(t,`PostToolUse`,{...n,hook_event_name:`PostToolUse`,tool_output:typeof r.data==`string`?r.data:JSON.stringify(r.data)},i).catch(e=>p.warn(`hook failed`,{error:e}))}var v=class{sessionId;cwd;getPermissionMode;config;terminal;permissionHandler;promptForApprovalFn;sessionLogger;onToolExecution;hookTypeExecutors;transcriptPath;sessionAllowedTools=new Set;onProjectAllowTool;constructor(e){this.sessionId=e.sessionId,this.cwd=e.cwd,this.getPermissionMode=e.getPermissionMode,this.config=e.config,this.terminal=e.terminal,this.permissionHandler=e.permissionHandler,this.promptForApprovalFn=e.promptForApprovalFn,this.sessionLogger=e.sessionLogger,this.onToolExecution=e.onToolExecution,this.hookTypeExecutors=e.hookTypeExecutors,this.transcriptPath=e.transcriptPath,this.onProjectAllowTool=e.onProjectAllowTool}wrapTools(e){return e.map(e=>this.wrapToolWithPermission(e))}getSessionAllowedTools(){return[...this.sessionAllowedTools]}clearSessionAllowedTools(){this.sessionAllowedTools.clear()}wrapToolWithPermission(e){let t=this,n=e.execute.bind(e),r=Object.create(e);return r.execute=async(r,i)=>{try{let a=e.getName();t.log(`tool_call`,{tool:a,args:r});let o=h(t.sessionId,t.cwd,a,r,t.getPermissionMode(),t.transcriptPath),s=await g(t.config.hooks,o,t.hookTypeExecutors);if(s)return t.log(`tool_blocked`,{tool:a,reason:`hook`}),s;if(!await t.checkPermission(a,r))return t.log(`tool_denied`,{tool:a,reason:`permission`}),t.onToolExecution?.({type:`end`,toolName:a,toolArgs:r,success:!1,denied:!0,executionId:i?.executionId}),f;t.onToolExecution?.({type:`start`,toolName:a,toolArgs:r,executionId:i?.executionId});let c=await n(r,i),l=m(c);l!==c&&typeof c.data==`string`&&t.terminal.writeLine(` ⚠ Output truncated: ${c.data.length.toLocaleString()} chars total — model sees first and last 15,000 chars`),t.onToolExecution?.({type:`end`,toolName:a,toolArgs:r,success:l.success,toolResultData:typeof l.data==`string`?l.data:JSON.stringify(l.data),executionId:i?.executionId});let u=typeof l.data==`string`?l.data.length:JSON.stringify(l.data).length;return t.log(`tool_result`,{tool:a,success:l.success,dataChars:u,truncated:l!==c}),_(t.config.hooks,o,l,t.hookTypeExecutors),l}catch(e){let t=e instanceof Error?e.message:String(e);return{success:!0,data:JSON.stringify({success:!1,output:``,error:t}),metadata:{}}}},r}async checkPermission(t,n){let r=(0,e.evaluatePermission)(t,n,this.getPermissionMode(),{allow:this.config.permissions.allow,deny:this.config.permissions.deny});if(r===`auto`)return!0;if(r===`deny`)return!1;if(this.sessionAllowedTools.has(t))return!0;if(this.permissionHandler){let e=await this.permissionHandler(t,n);return e===`allow-session`?(this.sessionAllowedTools.add(t),!0):e===`allow-project`?(this.sessionAllowedTools.add(t),this.onProjectAllowTool?.(t),!0):e}if(this.promptForApprovalFn){let e=await this.promptForApprovalFn(this.terminal,t,n);return e===`allow-session`?(this.sessionAllowedTools.add(t),!0):e===`allow-project`?(this.sessionAllowedTools.add(t),this.onProjectAllowTool?.(t),!0):e}return!1}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}};function y(e,t,n,r,i){return new v({sessionId:t,cwd:n,getPermissionMode:r,config:{permissions:e.permissions??{allow:[],deny:[]},hooks:e.hooks},terminal:e.terminal,permissionHandler:e.permissionHandler,promptForApprovalFn:e.promptForApproval,sessionLogger:e.sessionLogger,onToolExecution:e.onToolExecution,hookTypeExecutors:e.hookTypeExecutors,transcriptPath:i,onProjectAllowTool:e.onProjectAllowTool})}function b(e,t,n,r){return{contextTracker:new u(t,e.contextMaxTokens,e.autoCompactThreshold),compactionOrchestrator:new c({sessionId:n,cwd:r,model:t,hooks:e.hooks,compactInstructions:e.compactInstructions,hookTypeExecutors:e.hookTypeExecutors})}}function x(t,n,r,i,a,o){let s=n.wrapTools(r);return new e.Robota({name:t.agentName??`agent`,aiProviders:[i],defaultModel:{provider:i.name,model:a,...t.effort!==void 0&&{effort:t.effort}},systemMessage:o,tools:s,logging:{enabled:!1},...t.providerTimeout!==void 0&&{timeout:t.providerTimeout},...t.responseFormat?{responseFormat:t.responseFormat}:{},...t.ask?{ask:t.ask}:{}})}const ee=(0,e.createLogger)(`SessionHistoryOps`);async function te(t,n){let r=n.robota.getHistory();if(r.length===0)return;n.contextTracker.updateFromHistory(r);let i=n.contextTracker.getContextState(),a=r.filter(e=>e.role!==`system`),o=await n.compactionOrchestrator.compact(n.aiProvider,a,t);n.robota.clearHistory(),n.robota.injectMessage(`system`,n.systemMessage),n.robota.injectMessage(`assistant`,`[Context Summary]\n${o}`),n.contextTracker.updateFromHistory(n.robota.getHistory());let s={session_id:n.sessionId,cwd:n.cwd,hook_event_name:`PostCompact`,trigger:n.trigger,compact_summary:o};(0,e.runHooks)(n.hooks,`PostCompact`,s,n.hookTypeExecutors).catch(e=>ee.warn(`hook failed`,{error:e}));let c=n.contextTracker.getContextState();n.log(`context_compact`,{trigger:n.trigger,before:i,after:c}),n.onCompactEventCallback?.({trigger:n.trigger,before:i,after:c}),n.onCompactCallback&&n.onCompactCallback(o)}function ne(e){let t=e.robota.getHistory(),n=new Date().toISOString(),r=e.sessionStore.load(e.sessionId),i={id:e.sessionId,name:r?.name,cwd:e.cwd,createdAt:r?.createdAt??n,updatedAt:n,messages:t,history:e.getFullHistory(),systemPrompt:e.systemPrompt,toolSchemas:e.toolSchemas};e.sessionStore.save(i)}const re=(0,e.createLogger)(`SessionLifecycle`);function S(e,t,n){e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>{n(`server_tool`,{tool:e,...t})})}function C(t,n,r,i,a,o,s){(0,e.runHooks)(r,`SessionStart`,{session_id:t,cwd:n,hook_event_name:`SessionStart`,...o!==void 0&&{permission_mode:o},...s!==void 0&&{transcript_path:s},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:t}},i).then(e=>{e.stdout&&a(e.stdout)}).catch(e=>re.warn(`SessionStart hook failed`,{error:e}))}async function w(t,n,r,i,a,o,s){await(0,e.runHooks)(i,`SessionEnd`,{session_id:t,cwd:n,hook_event_name:`SessionEnd`,reason:r,...o!==void 0&&{permission_mode:o},...s!==void 0&&{transcript_path:s},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:t}},a)}const T=`unknown_tool`;function E(e){return{knownToolNames:new Set(e.knownToolNames),unknownToolCallIds:new Set,...e.onToolExecution&&{onToolExecution:e.onToolExecution}}}function D(e,t,n){if(e.onToolExecution){if(t===`tool_execution_request`){O(e,n);return}t===`tool_execution_result`&&k(e,n)}}function O(e,t){let n=j(t.toolName),r=j(t.toolCallId);!n||!r||e.knownToolNames.has(n)||(e.unknownToolCallIds.add(r),e.onToolExecution?.({type:`start`,toolName:n,toolArgs:A(t.parameters)}))}function k(e,t){let n=j(t.toolName),r=j(t.toolCallId);if(!n||!r)return;let i=M(t.metadata);if(!(e.unknownToolCallIds.has(r)||i?.errorCode===T))return;e.unknownToolCallIds.delete(r);let a=j(t.error)??`Tool "${n}" is not registered.`;e.onToolExecution?.({type:`end`,toolName:n,success:!1,toolResultData:JSON.stringify({success:!1,error:a,errorCode:T,requestedTool:j(i?.requestedTool)??n,availableTools:N(i?.availableTools)})})}function A(e){let t=M(e);if(!t)return;let n={};for(let[e,r]of Object.entries(t))(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||typeof r==`object`&&r)&&(n[e]=r);return n}function j(e){return typeof e==`string`&&e.length>0?e:void 0}function M(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function N(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}const P=(0,e.createLogger)(`SessionRun`);async function F(t,n,r,i){if(r.contextTracker.updateFromHistory(r.robota.getHistory()),r.contextTracker.shouldAutoCompact()){let e=r.aiProvider,t=e.onTextDelta;e.onTextDelta=void 0;try{await r.compact()}finally{e.onTextDelta=t}}r.log(`user`,{content:t});let a=await(0,e.runHooks)(r.hooks,`UserPromptSubmit`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`UserPromptSubmit`,user_message:n??t,prompt:n??t,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors),o=[r.sessionStartStdout,a.stdout].filter(Boolean).join(`
4
- `),s=o?`<system-reminder>\n${o}\n</system-reminder>\n${t}`:t;r.clearSessionStartStdout();let c=r.robota.getHistory(),l=JSON.stringify(c),u=(0,e.getProviderCapabilities)(r.aiProvider);r.log(`pre_run`,{historyLength:c.length,historyChars:l.length,historyEstTokens:Math.ceil(l.length/e.CONTEXT_ESTIMATE_CHARS_PER_TOKEN),input:s,history:c,model:r.model,provider:r.aiProvider.name,maxTokens:r.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:u.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:u.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:u.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:u.nativeWebTools.webFetch.enabled}),r.contextTracker.updateFromHistory([...c,(0,e.createUserMessage)(s)]),r.onContextUpdate?.(r.contextTracker.getContextState());let d;try{let e=E({knownToolNames:r.knownToolNames??[],...r.onToolExecution&&{onToolExecution:r.onToolExecution}}),t=r.onTextDelta?e=>{r.log(`text_delta`,{delta:e}),r.onTextDelta?.(e)}:void 0;if(d=await r.robota.run(s,{signal:i,maxExecutionRounds:r.maxTurns??0,onExecutionEvent:(t,n)=>{r.log(t,n),D(e,t,n),t===`assistant_message_committed`&&(r.contextTracker.updateFromHistory(r.robota.getHistory()),r.onContextUpdate?.(r.contextTracker.getContextState()))},...t&&{onTextDelta:t}}),i.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(t){throw r.log(`error`,{message:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack??``:``,historyLength:r.robota.getHistory().length}),(0,e.runHooks)(r.hooks,`StopFailure`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`StopFailure`,reason:t instanceof Error?t.message:String(t),stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors).catch(e=>P.warn(`hook failed`,{error:e})),t}let f=r.robota.getHistory(),p=f.map(e=>{let t=`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0,n=t?e.toolCalls.map(e=>e.function.name):[];return{role:e.role,contentLength:typeof e.content==`string`?e.content.length:0,hasToolCalls:t,toolCallNames:n,...e.metadata?{metadata:e.metadata}:{}}});r.log(`assistant`,{content:d,historyLength:f.length,estimatedChars:JSON.stringify(f).length,history:f,historyStructure:p}),r.contextTracker.updateFromHistory(f);let m=r.contextTracker.getContextState();return r.onContextUpdate?.(m),r.log(`context`,{maxTokens:m.maxTokens,usedTokens:m.usedTokens,usedPercentage:m.usedPercentage,remainingPercentage:m.remainingPercentage}),(0,e.runHooks)(r.hooks,`Stop`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`Stop`,response:d.substring(0,500),last_assistant_message:d,stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors).catch(e=>P.warn(`hook failed`,{error:e})),r.getSessionStore()&&r.persistSession(),d}var I=class extends o{robota;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;abortController=null;terminal;sessionStore;cwd;hooks;hookTypeExecutors;onTextDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(t){super();let{tools:n,provider:r,systemMessage:i}=t;this.terminal=t.terminal,this.sessionStore=t.sessionStore,this.systemMessage=i,this.toolSchemas=n.map(e=>e.schema),this.cwd=process.cwd(),this.sessionLogger=t.sessionLogger,this.hooks=t.hooks,this.hookTypeExecutors=t.hookTypeExecutors,this.onTextDeltaCallback=t.onTextDelta,this.onContextUpdateCallback=t.onContextUpdate,this.onToolExecutionCallback=t.onToolExecution,this.onCompactCallback=t.onCompact,this.onCompactEventCallback=t.onCompactEvent,this.maxTurns=t.maxTurns,this.model=t.model??`claude-sonnet-4-5`,this.sessionId=t.sessionId??`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this.permissionMode=t.permissionMode??(t.defaultTrustLevel?e.TRUST_TO_MODE[t.defaultTrustLevel]:void 0)??`default`,this.activePresetId=t.activePresetId??`default`,this.parallelSubagentsEnabled=t.enableParallelSubagents??!0,this.transcriptPath=t.sessionStore?.getFilePath?.(this.sessionId),this.log(`session_init`,{cwd:this.cwd,systemPromptLength:i.length,systemPrompt:i,toolSchemas:this.toolSchemas,model:this.model,provider:r.name}),this.aiProvider=r,S(r,t,(e,t)=>this.log(e,t)),this.permissionEnforcer=y(t,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath);let{contextTracker:a,compactionOrchestrator:o}=b(t,this.model,this.sessionId,this.cwd);this.contextTracker=a,this.compactionOrchestrator=o,this.robota=x(t,this.permissionEnforcer,n,r,this.model,i),C(this.sessionId,this.cwd,this.hooks,this.hookTypeExecutors,e=>void(this.sessionStartStdout=e),this.permissionMode,this.transcriptPath)}async run(e,t){this.abortController=new AbortController;let{signal:n}=this.abortController;try{let r=await F(e,t,this.buildRunContext(),n);return this.messageCount+=1,r}finally{this.abortController=null}}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(){this.sessionStore&&ne({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,robota:this.robota,getFullHistory:()=>this.getFullHistory()})}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let t=e.reason??`other`,n=async(e,t)=>{try{await t()}catch(t){this.log(`session_shutdown_step_error`,{step:e,error:t instanceof Error?t.message:String(t)})}};return this.shutdownPromise=(async()=>{await n(`abort`,()=>this.abort()),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>w(this.sessionId,this.cwd,t,this.hooks,this.hookTypeExecutors,this.permissionMode,this.transcriptPath)),await n(`destroy-agent`,async()=>{await this.robota.destroy()})})(),this.shutdownPromise}swapProvider(e,t){this.robota.swapDefaultProvider(e,t),e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>this.log(`server_tool`,{tool:e,...t})),this.aiProvider=e}async compact(e,t=`manual`){await te(e,{sessionId:this.sessionId,cwd:this.cwd,systemMessage:this.systemMessage,robota:this.robota,aiProvider:this.aiProvider,compactionOrchestrator:this.compactionOrchestrator,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,onCompactCallback:this.onCompactCallback,onCompactEventCallback:this.onCompactEventCallback,trigger:t,log:(e,t)=>this.log(e,t)})}buildRunContext(){return{sessionId:this.sessionId,cwd:this.cwd,model:this.model,robota:this.robota,aiProvider:this.aiProvider,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,sessionStartStdout:this.sessionStartStdout,log:(e,t)=>this.log(e,t),compact:()=>this.compact(void 0,`auto`),persistSession:()=>this.persistSessionInternal(),getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,knownToolNames:this.toolSchemas.map(e=>e.name)}}};const L=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;var R=class{logDir;options;constructor(e,t={}){this.logDir=e,this.options={externalPayloadThresholdBytes:t.externalPayloadThresholdBytes??32768,redactedValue:t.redactedValue??`[REDACTED]`};try{(0,n.mkdirSync)(e,{recursive:!0})}catch{}}log(e,t,i){try{let a=z(e,this.logDir,i,this.options),o=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e,event:t,...a});(0,n.appendFileSync)((0,r.join)(this.logDir,`${e}.jsonl`),o+`
5
- `)}catch{}}};function z(e,t,n,r){let i={};for(let[a,o]of Object.entries(n))i[a]=B(e,t,a,o,r);return i}function B(e,t,n,r,i){if(L.test(n))return i.redactedValue;if(r==null||typeof r==`string`||typeof r==`number`)return V(e,t,r,i);if(typeof r==`boolean`)return r;if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return V(e,t,r.map(r=>B(e,t,n,r,i)),i);if(typeof r==`object`){let n=r,a={};for(let[r,o]of Object.entries(n))a[r]=B(e,t,r,o,i);return V(e,t,a,i)}return String(r)}function V(e,i,a,o){let s=JSON.stringify(a);if(s===void 0)return a;let c=Buffer.byteLength(s);if(c<=o.externalPayloadThresholdBytes)return a;let l=(0,t.createHash)(`sha256`).update(s).digest(`hex`),u=`${e}.payloads`,d=(0,r.join)(u,`${l}.json`),f=(0,r.join)(i,u),p=(0,r.join)(i,d);return(0,n.mkdirSync)(f,{recursive:!0}),(0,n.existsSync)(p)||(0,n.writeFileSync)(p,s,`utf-8`),{kind:`external-payload`,encoding:`json`,sha256:l,byteLength:c,relativePath:d}}var ie=class{log(){}};const H={sessionInit:`session_init`,sessionShutdown:`session_shutdown`,context:`context`,contextCompact:`context_compact`,error:`error`,historyMutation:`history_mutation`,providerRequest:`provider_request`,providerNativeRawPayload:`provider_native_raw_payload`,providerResponseRaw:`provider_response_raw`,providerResponseNormalized:`provider_response_normalized`,toolExecutionRequest:`tool_execution_request`,toolExecutionResult:`tool_execution_result`,user:`user`,preRun:`pre_run`,textDelta:`text_delta`,assistant:`assistant`,toolCall:`tool_call`,toolResult:`tool_result`,toolBlocked:`tool_blocked`,toolDenied:`tool_denied`,serverTool:`server_tool`};function U(e,t){return e.event===t}function W(e){let t=[],n=G(),r=K();return e.forEach((e,i)=>{X(e,i,t),q(n,e,i),J(r,e,i)}),Y(n,t),ae(r,t),{ok:t.length===0,issues:t}}function G(){return{requests:new Map,nativeRawPayloads:new Set,rawResponses:new Set,normalizedResponses:new Set}}function K(){return{requests:new Map,results:new Set}}function q(e,t,n){let r=oe(t);r&&(t.event===`provider_request`&&e.requests.set(r.key,{executionId:r.executionId,round:r.round,index:n}),t.event===`provider_response_raw`&&e.rawResponses.add(r.key),t.event===`provider_native_raw_payload`&&(t.payloadKind===`response`||t.payloadKind===`stream_event`)&&e.nativeRawPayloads.add(r.key),t.event===`provider_response_normalized`&&e.normalizedResponses.add(r.key))}function J(e,t,n){let r=se(t);r&&(t.event===`tool_execution_request`&&e.requests.set(r.key,{executionId:r.executionId,toolCallId:r.toolCallId,index:n}),t.event===`tool_execution_result`&&e.results.add(r.key))}function Y(e,t){for(let[n,r]of e.requests)e.nativeRawPayloads.has(n)||t.push({code:`PROVIDER_NATIVE_RAW_PAYLOAD_MISSING`,message:`Provider request ${n} has no provider-native raw response or stream payload event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.rawResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_RAW_MISSING`,message:`Provider request ${n} has no raw response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.normalizedResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_NORMALIZED_MISSING`,message:`Provider request ${n} has no normalized response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round})}function ae(e,t){for(let[n,r]of e.requests)e.results.has(n)||t.push({code:`TOOL_RESULT_MISSING`,message:`Tool request ${n} has no terminal result event.`,eventIndex:r.index,executionId:r.executionId,toolCallId:r.toolCallId})}function oe(e){if(typeof e.executionId!=`string`)return;let t=typeof e.round==`number`?e.round:Number(e.round);if(Number.isFinite(t))return{key:`${e.executionId}:${t}`,executionId:e.executionId,round:t}}function se(e){if(typeof e.executionId!=`string`)return;let t=typeof e.toolCallId==`string`?e.toolCallId:typeof e.toolExecutionId==`string`?e.toolExecutionId:void 0;if(t)return{key:`${e.executionId}:${t}`,executionId:e.executionId,toolCallId:t}}function X(e,t,n){if(Array.isArray(e)){e.forEach(e=>X(e,t,n));return}if(ce(e)){if(e.kind===`external-payload`){(e.encoding!==`json`||typeof e.sha256!=`string`||typeof e.relativePath!=`string`||typeof e.byteLength!=`number`)&&n.push({code:`PAYLOAD_REFERENCE_INVALID`,message:`External payload reference is missing required replay fields.`,eventIndex:t});return}Object.values(e).forEach(e=>X(e,t,n))}}function ce(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Z(e){return(0,n.existsSync)(e)?(0,n.readFileSync)(e,`utf-8`).split(`
6
- `).map(e=>e.trim()).filter(e=>e.length>0).map(e=>JSON.parse(e)):[]}function le(t){let n=[],r=[],i={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},a,o,s,c;for(let l of t){if(a??=l.sessionId,s??=l.timestamp,c=l.timestamp,l.event===`session_init`&&(o=typeof l.cwd==`string`?l.cwd:o),l.event===`history_mutation`&&l.mutation===`append_message`){let t=de(l.message);t&&(n.push(t),r.push((0,e.messageToHistoryEntry)(t)))}ue(l,i)}return{sessionId:a,cwd:o,createdAt:s,updatedAt:c,messages:n,history:r,backgroundTaskEvents:i.backgroundTaskEvents,backgroundJobGroupEvents:i.backgroundJobGroupEvents,memoryEvents:i.memoryEvents}}function ue(e,t){if(e.event===`background_task_event`){$(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){$(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&$(t.memoryEvents,e,`memoryEvent`,`data`)}function de(e){if(!fe(e))return;let t=e.role;if(t!==`user`&&t!==`assistant`&&t!==`system`&&t!==`tool`)return;let n=typeof e.id==`string`?e.id:`${t}-${Date.now()}`,r=e.timestamp instanceof Date?e.timestamp:new Date(typeof e.timestamp==`string`?e.timestamp:Date.now());return{...e,id:n,role:t,timestamp:r}}function fe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function $(e,t,n,r){let i=Q(t,n)??Q(t,r);i&&e.push(i)}function pe(){return process.env.HOME??process.env.USERPROFILE??`/`}var me=class{baseDir;constructor(e){this.baseDir=e??(0,a.join)(pe(),`.robota`,`sessions`)}ensureDir(){(0,i.existsSync)(this.baseDir)||(0,i.mkdirSync)(this.baseDir,{recursive:!0})}filePath(e){return(0,a.join)(this.baseDir,`${e}.json`)}getFilePath(e){return this.filePath(e)}save(e){this.ensureDir();let t=this.filePath(e.id),n=`${t}.${process.pid}.tmp`;(0,i.writeFileSync)(n,JSON.stringify(e,null,2),`utf-8`);try{(0,i.renameSync)(n,t)}catch(e){throw(0,i.unlinkSync)(n),e}}load(e){let t=this.filePath(e);if((0,i.existsSync)(t))try{let e=(0,i.readFileSync)(t,`utf-8`);return JSON.parse(e)}catch{return}}list(){if(!(0,i.existsSync)(this.baseDir))return[];let e=(0,i.readdirSync)(this.baseDir).filter(e=>e.endsWith(`.json`)),t=[];for(let n of e)try{let e=(0,i.readFileSync)((0,a.join)(this.baseDir,n),`utf-8`),r=JSON.parse(e);t.push(r)}catch{}return t.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime())}delete(e){let t=this.filePath(e);(0,i.existsSync)(t)&&(0,i.unlinkSync)(t)}};exports.AUTO_COMPACT_THRESHOLD=l,exports.CompactionError=s,exports.CompactionOrchestrator=c,exports.ContextWindowTracker=u,exports.FileSessionLogger=R,exports.PermissionEnforcer=v,exports.SESSION_LOG_EVENT=H,exports.Session=I,exports.SessionStore=me,exports.SilentSessionLogger=ie,exports.isSessionLogEvent=U,exports.loadSessionLogEntries=Z,exports.replaySessionLogEntries=le,exports.validateSessionReplayLogEntries=W;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@robota-sdk/agent-core"),t=require("node:path"),n=require("node:crypto"),r=require("node:os"),i=require("node:fs"),a=require("@robota-sdk/agent-core/node"),o=require("@robota-sdk/agent-file-authority"),s=require("fs"),c=require("path");function l(e){if(typeof e!=`string`||e.length===0)throw Error("Session requires `cwd`: the absolute path this session executes in (ARCH-010). It feeds every hook input, CLAUDE_PROJECT_DIR, the permission root and the persisted record. Pass `process.cwd()` explicitly if that is genuinely what you mean.");if(!(0,t.isAbsolute)(e))throw Error(`Session requires an ABSOLUTE \`cwd\`; got ${JSON.stringify(e)} (ARCH-010). A relative root is resolved against the process directory downstream, which is the ambient value this field exists to replace. Resolve it at your composition root.`);return e}var u=class extends Error{recoverable=!0;constructor(e){super(e),this.name=`SessionBusyError`}},d=class{controller=null;claim(){if(this.controller!==null)throw new u(`This session is already running a turn. A session is a single conversation: await the turn in flight, abort() it and await it, or use a separate session for concurrent work.`);return this.controller=new AbortController,this.controller}release(e){this.controller===e&&(this.controller=null)}abort(){this.controller?.abort()}isRunning(){return this.controller!==null}},f=class{cwd;constructor(e){this.cwd=l(e)}turnClaim=new d;permissionModeGuards=new Set;getPermissionMode(){return this.permissionMode}setPermissionMode(e){for(let t of this.permissionModeGuards)t(e);this.permissionMode=e}addPermissionModeGuard(e){return this.permissionModeGuards.add(e),()=>this.permissionModeGuards.delete(e)}getActivePresetId(){return this.activePresetId}setActivePresetId(e){this.activePresetId=e}getParallelSubagentsEnabled(){return this.parallelSubagentsEnabled}setParallelSubagentsEnabled(e){this.parallelSubagentsEnabled=e}getSessionId(){return this.sessionId}getCwd(){return this.cwd}getSystemMessage(){return this.systemMessage}updateSystemMessage(e){this.systemMessage=e,this.agent.updateSystemPrompt(e)}async applyModelOptions(e){await this.agent.ensureReady();let t=e.model??this.model;this.agent.setModel({provider:this.aiProvider.name,model:t,...e.effort!==void 0&&{effort:e.effort},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxOutputTokens!==void 0&&{maxTokens:e.maxOutputTokens}}),this.model=t}getModelEffort(){let e=this.agent.getModel;if(e===void 0)return`auto`;try{return e.call(this.agent).effort??`auto`}catch(e){if(e instanceof Error&&/disposed/i.test(e.message))return`auto`;throw e}}async withScopedModelEffort(e,t){let n=this.getModelEffort();await this.applyModelOptions({effort:e});try{return await t()}finally{await this.applyModelOptions({effort:n})}}async applyAgentName(e){await this.agent.updateConfiguration({name:e})}getToolSchemas(){return this.toolSchemas}getMessageCount(){return this.messageCount}applyPresetToolLists(e){this.permissionEnforcer.applyPresetToolLists(e)}getPermissionRules(){let e=this.permissionEnforcer.currentPermissionRules();return{allow:[...e.allow],deny:[...e.deny],ask:[...e.ask]}}getSessionAllowedTools(){return this.permissionEnforcer.getSessionAllowedTools()}checkToolPermission(e,t,n){return this.permissionEnforcer.checkDelegatedToolCall(e,t,n)}requireClassifierFor(e){if(e===`auto`&&!this.permissionEnforcer.hasPermissionClassifier())throw Error(`Auto mode is unavailable: this session has no permission classifier.`)}retryPermissionDenial(e){return this.permissionEnforcer.allowRetryOfDenial(e)}getRecentPermissionDenials(){return this.permissionEnforcer.getRecentDenials()}clearSessionAllowedTools(){this.permissionEnforcer.clearSessionAllowedTools()}abort(){this.turnClaim.abort()}isRunning(){return this.turnClaim.isRunning()}getContextState(){return this.contextTracker.getContextState()}syncContextFromHistory(){this.contextTracker.updateFromHistory(this.agent.getHistory())}getAutoCompactThreshold(){return this.contextTracker.getAutoCompactThreshold()}setAutoCompactThreshold(e){this.contextTracker.setAutoCompactThreshold(e)}getHistory(){return this.agent.getHistory()}getFullHistory(){return this.agent.getFullHistory()}getSessionTokenUsage(){let e=0,t=0,n=!1;for(let r of this.getFullHistory()){if(r.category!==`event`||r.type!==`usage-summary`)continue;let i=r.data;e+=i?.promptTokens??0,t+=i?.completionTokens??0,n=!0}return n?{inputTokens:e,outputTokens:t}:void 0}getModelId(){return this.model}getOfferedToolSchemas(){return this.agent.getOfferedToolSchemas()}getProvider(){return this.aiProvider}getProviderId(){return this.aiProvider.name}addHistoryEntry(e){this.agent.addHistoryEntry(e)}injectMessage(e,t,n){this.agent.injectMessage(e,t,n)}injectRawMessage(e){this.agent.injectRawMessage(e)}clearHistory(){this.agent.clearHistory(),this.contextTracker.reset()}};function p(e){return JSON.stringify(typeof e==`string`?e:e??``)}function m(t){let n=(0,e.peerDriverOf)(t);return n?`user [from ${JSON.stringify((0,e.printablePeerDriver)(n))}]`:`user`}function h(e){switch(e.role){case`user`:return[`${m(e)}: ${p(e.content)}`];case`assistant`:{let t=[];e.content!==null&&e.content!==``&&t.push(`assistant: ${p(e.content)}`);for(let n of e.toolCalls??[])t.push(`assistant tool call ${JSON.stringify(n.function.name)} [${JSON.stringify(n.id)}]: ${p(n.function.arguments)}`);return t.length>0?t:[`assistant: ""`]}case`tool`:return[`tool result${e.name?` ${JSON.stringify(e.name)}`:``} [${JSON.stringify(e.toolCallId)}]: ${p(e.content)}`];case`system`:return[`system: ${p(e.content)}`]}}function g(e){return e.map(e=>h(e).join(`
2
+ `))}var _=class extends Error{constructor(e){super(e),this.name=`CompactionError`}};const v=[`Summarize the following conversation concisely, preserving:`,`- User's original requests and goals`,`- Key decisions, conclusions, and important state`,`- Identifiers, names, and references needed to continue the work`,`- Current task status and next steps`,`Drop verbose intermediate outputs and exploratory work that didn't lead to results.`].join(`
3
+ `);var ee=class{sessionId;cwd;model;hooks;compactInstructions;basePrompt;hookTypeExecutors;constructor(e){this.sessionId=e.sessionId,this.cwd=e.cwd,this.model=e.model,this.hooks=e.hooks,this.compactInstructions=e.compactInstructions,this.basePrompt=e.basePrompt,this.hookTypeExecutors=e.hookTypeExecutors}async compact(t,r,i,a,o=`manual`,s){if(a?.throwIfAborted(),r.length===0)throw new _(`Compaction was asked to summarise an empty history; conversation history preserved untouched`);let c={session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PreCompact`,trigger:o};await(0,e.runHooks)(this.hooks,`PreCompact`,c,this.hookTypeExecutors,s);let l=this.buildCompactionPrompt(r,i),u=await t.chat([{id:(0,n.randomUUID)(),role:`user`,content:l,state:`complete`,timestamp:new Date}],{model:this.model,toolChoice:`none`,preserveContextWindow:!0,...a===void 0?{}:{signal:a}});if(a?.throwIfAborted(),typeof u.content!=`string`||u.content.trim()===``)throw new _(`Compaction produced an invalid summary (provider=${t.name}, content type=${typeof u.content}); conversation history preserved untouched`);return u.content}buildCompactionPrompt(e,t){let n=t??this.compactInstructions??``,r=n?`\nAdditional focus:\n${n}\n`:``,i=g(e).join(`
4
+ `);return[this.basePrompt??v,r,``,`Conversation:`,i].join(`
5
+ `)}};const y=.835;var b=class{contextUsedTokens=0;contextMaxTokens;autoCompactThreshold;constructor(t,n,r){this.contextMaxTokens=n??(0,e.getModelContextWindow)(t),this.autoCompactThreshold=te(r)}getContextState(){let e=Math.min(100,this.contextUsedTokens/this.contextMaxTokens*100);return{maxTokens:this.contextMaxTokens,usedTokens:this.contextUsedTokens,usedPercentage:Math.round(e*100)/100,remainingPercentage:Math.round((100-e)*100)/100}}shouldAutoCompact(){return this.autoCompactThreshold!==!1&&this.getContextState().usedPercentage>=this.autoCompactThreshold*100}getAutoCompactThreshold(){return this.autoCompactThreshold}setAutoCompactThreshold(e){this.autoCompactThreshold=te(e)}updateFromHistory(t){this.contextUsedTokens=(0,e.estimateContextTokensFromMessages)(t).usedTokens}reset(){this.contextUsedTokens=0}};function te(e){if(e===void 0)return y;if(e===!1)return!1;if(!Number.isFinite(e)||e<=0||e>1)throw RangeError(`autoCompactThreshold must be a number greater than 0 and at most 1.`);return e}async function ne(e,t){if(t===void 0)return e;if(t.aborted)return!1;let n;try{return await Promise.race([e,new Promise(e=>{n=()=>e(!1),t.addEventListener(`abort`,n,{once:!0})})])}finally{n!==void 0&&t.removeEventListener(`abort`,n)}}function re(e){return e===`allow-session`?{allowed:!0,rememberForSession:!0,rememberForProject:!1}:e===`allow-project`?{allowed:!0,rememberForSession:!0,rememberForProject:!0}:{allowed:e===!0,rememberForSession:!1,rememberForProject:!1}}async function ie(e){let t={allowed:!1,rememberForSession:!1,rememberForProject:!1};if(e.alreadyAllowed)return{allowed:!0,rememberForSession:!1,rememberForProject:!1};if(e.signal?.aborted===!0)return t;let n=e.handler?()=>e.handler(e.toolName,e.toolArgs):e.injectedPrompt&&e.terminal?()=>e.injectedPrompt(e.terminal,e.toolName,e.toolArgs):void 0;return n===void 0?t:re(await ne(n(),e.signal))}function ae(e,t){return`${e}\u0000${JSON.stringify(t)}`}var oe=class{classifier;consecutive=0;total=0;paused=!1;retries=new Set;constructor(e){this.classifier=e}isPaused(){return this.paused}resume(){this.paused=!1,this.consecutive=0}grantRetry(e,t){this.retries.add(ae(e,t))}takeRetry(e,t){return this.retries.delete(ae(e,t))}async judge(e,t){let n;try{n=await this.classifier.classify(e,t)}catch{n=void 0}if(n===void 0){t?.aborted!==!0&&(this.consecutive+=1);let e=this.consecutive>=3;return e&&(this.paused=!0),{kind:`unusable`,reason:`no usable verdict`,message:`The auto-mode classifier gave no usable verdict, so the call was not run. Try again, or ask the user to approve it.`+(e?` Auto mode is paused: the next calls ask the user.`:``)}}if(n.decision===`allow`)return this.consecutive=0,{kind:`allow`};this.consecutive+=1,this.total+=1;let r=this.consecutive>=3||this.total>=20;return this.total>=20&&(this.total=0),r&&(this.paused=!0),{kind:`block`,reason:n.reason,message:`Blocked by the auto-mode classifier: ${n.reason}. Do not retry the same action; take another approach or ask the user.`+(r?` Auto mode is paused after repeated blocks: the next calls ask the user.`:``)}}};function se(e){let t=e.replace(/\\/g,`/`),n=t.lastIndexOf(`/`);return n<0?`.`:n===0?`/`:t.slice(0,n)}function ce(e,t){switch(e){case`path`:{let e=se(t);return e===`/`?`/**`:`${e}/**`}case`url`:try{let e=new URL(t);return`${e.protocol}//${e.host}/**`}catch{return t}case`command`:{let e=t.trim().split(/\s+/)[0];return e?`${e} *`:void 0}default:return}}function le(t,n){let r=(0,e.getToolPermissionProfile)(t).argument;if(r===void 0)return t;let i=n[r.key];if(typeof i!=`string`||i===``)return t;let a=ce(r.kind,i);return a===void 0?t:`${t}(${a})`}function x(e,t,n){return{success:!1,outcome:e,error:t,data:JSON.stringify(n??{success:!1,output:``,error:t}),metadata:{}}}function ue(e,t,n){let r=e instanceof Error?e.message:String(e);return t?.({type:`end`,toolName:n.toolName,toolArgs:n.toolArgs,success:!1,executionId:n.executionId}),x(`threw`,r)}const de=x(`denied`,`Permission denied. The user did not approve this action.`),fe=(0,e.createLogger)(`ToolHookHelpers`);function pe(t){if((0,e.wasToolResultAdmitted)(t)||typeof t.data!=`string`||t.data.length<=3e4)return t;let n=15e3,r=t.data.substring(0,n),i=t.data.substring(t.data.length-n),a=`${r}\n\n[... output truncated: ${t.data.length.toLocaleString()} chars total, showing first and last ${n.toLocaleString()} chars ...]\n\n${i}`;return{...t,data:a}}function me(e,t,n,r,i,a){return{session_id:e,cwd:t,hook_event_name:`PreToolUse`,tool_name:n,tool_input:r,...i!==void 0&&{permission_mode:i},...a!==void 0&&{transcript_path:a}}}async function he(t,n,r,i){let a=await(0,e.runHooks)(t,`PreToolUse`,n,r,i);if(a.blocked){let e=a.reason??`Blocked by hook`;return x(`hook-blocked`,e,{blocked:!0,reason:e})}if((0,e.isEnforcing)(`PreToolUse`)){let e=a.errors,t=e?.[0],n=a.unknownHookTypes??[],r=n.length>0?`Hook type(s) with no registered executor: ${n.join(`, `)}. Nothing evaluated this gate, so the tool call is denied rather than silently allowed. Remove the hook from the PreToolUse configuration, or supply an executor for its type.`:``;if(e!==void 0&&t!==void 0){let n=e.length-1,i=`Hook could not evaluate (${t.kind}, source: ${t.source}): ${t.reason}.`+(n>0?` (+${n} more hook failure(s))`:``)+(r===``?``:` Also unevaluated — ${r}`);return x(`hook-blocked`,i,{blocked:!0,reason:i})}if(r!==``)return x(`hook-blocked`,r,{blocked:!0,reason:r})}return null}function ge(t,n,r,i,a){(0,e.runHooks)(t,`PostToolUse`,{...n,hook_event_name:`PostToolUse`,tool_output:typeof r.data==`string`?r.data:JSON.stringify(r.data)},i,a).catch(e=>fe.warn(`hook failed`,{error:e}))}function _e(t,n){let r=(0,e.getToolPermissionProfile)(t).argument?.key;if(r===void 0)return;let i=n[r];if(typeof i==`string`)return i.length>200?`${i.slice(0,200)}…`:i}var ve=class{capacity;now;entries=[];calls=[];constructor(e=20,t=Date.now){this.capacity=e,this.now=t}record(e,t,n,r){let i=_e(e,t);this.entries.unshift({toolName:e,...i===void 0?{}:{argument:i},reason:n,...r===void 0?{}:{detail:r},at:this.now()}),this.calls.unshift({toolName:e,toolArgs:t}),this.calls.length>this.capacity&&(this.calls.length=this.capacity),this.entries.length>this.capacity&&(this.entries.length=this.capacity)}list(){return[...this.entries]}callAt(e){return this.calls[e]}};function ye(n,r,i){let a=(0,e.getToolPermissionProfile)(n).argument;if(a===void 0||a.kind!==`path`)return r;let o=r[a.key];return typeof o!=`string`||o===``||(0,t.isAbsolute)(o)?r:{...r,[a.key]:(0,t.resolve)(i,o)}}const be=(0,e.createLogger)(`ToolBodyTrace`);function xe(t,n){try{t?.eventService?.emit(e.TOOL_PERMISSION_EVENTS.DECIDED,{timestamp:new Date,executionId:t.executionId,decidedAt:new Date().toISOString(),decision:n})}catch(e){be.warn(`tool permission observation failed`,e instanceof Error?e:Error(String(e)))}}function Se(t,n){let r=t.execute.bind(t),i=Object.create(t);return i.execute=async(i,a)=>{let o=i,s=`(unknown)`;try{s=t.getName(),o=ye(s,i,n.cwd),n.log(`tool_call`,{tool:s,args:o});let c=me(n.sessionId,n.cwd,s,o,n.getPermissionMode(),n.transcriptPath),l=await he(n.config.hooks,c,n.hookTypeExecutors,a?.hookTraceEnv);if(l)return n.log(`tool_blocked`,{tool:s,reason:`hook`}),xe(a,`hook-blocked`),l;let u=await n.checkPermission(s,o,a?.signal,a?.permissionInteraction,a?.hookTraceEnv);if(u!==!0)return n.log(`tool_denied`,{tool:s,reason:`permission`}),xe(a,`denied`),n.onToolExecution?.({type:`end`,toolName:s,toolArgs:o,success:!1,denied:!0,executionId:a?.executionId}),typeof u==`object`?x(`denied`,u.message):de;xe(a,`allowed`),a?.signal?.throwIfAborted(),n.onToolExecution?.({type:`start`,toolName:s,toolArgs:o,executionId:a?.executionId});let d=Date.now(),f=`failure`,p;try{p=await r(o,a),f=a?.signal?.aborted?`interrupted`:p.success?`success`:`failure`}catch(t){throw f=a?.signal?.aborted||(0,e.isAbortFailure)(t)?`interrupted`:`failure`,t}finally{try{a?.eventService?.emit(e.TOOL_BODY_EVENTS.COMPLETED,{timestamp:new Date,executionId:a.executionId,startedAt:new Date(d).toISOString(),endedAt:new Date(Math.max(Date.now(),d)).toISOString(),outcome:f,...typeof a.toolBodyId==`string`?{toolBodyId:a.toolBodyId}:{}})}catch(e){be.warn(`tool body observation failed`,e instanceof Error?e:Error(String(e)))}}let m=pe(p);m!==p&&typeof p.data==`string`&&n.terminal.writeLine(` ⚠ Output truncated: ${p.data.length.toLocaleString()} chars total — model sees first and last 15,000 chars`),n.onToolExecution?.({type:`end`,toolName:s,toolArgs:o,success:m.success,toolResultData:typeof m.data==`string`?m.data:JSON.stringify(m.data),executionId:a?.executionId});let h=typeof m.data==`string`?m.data.length:JSON.stringify(m.data)?.length??0;return n.log(`tool_result`,{tool:s,success:m.success,dataChars:h,truncated:m!==p}),ge(n.config.hooks,c,m,n.hookTypeExecutors,a?.hookTraceEnv),m}catch(e){return ue(e,n.onToolExecution,{toolName:s,toolArgs:o,executionId:a?.executionId})}},i.setEventService=e=>{t.setEventService(e)},i}function Ce(e){let n=e,r=[];for(;;)try{let e=(0,i.realpathSync)(n);return r.length===0?e:(0,t.resolve)(e,...r.reverse())}catch{let i=(0,t.dirname)(n);if(i===n)return e;r.push(n.slice(i.length).replace(/^[\\/]/,``)),n=i}}function we(e,n){let r=(0,t.relative)(e,n);return r===``||!r.startsWith(`..`)&&!(0,t.isAbsolute)(r)}function Te(e){return(n,r)=>{let i=Ce(e),a=Ce((0,t.resolve)(n??i,r));return we(i,a)?a:void 0}}function Ee(t){let n=[...(0,e.findInvalidPermissionPatterns)(t.allow,`allow`),...(0,e.findInvalidPermissionPatterns)(t.restrictive,`deny`)];if(n.length===0)return;let r=n.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Invalid permission pattern(s) in permissions.allow/deny/ask: ${r}. Fix the pattern where it is configured (issue #2428).`)}var De=class{sessionId;cwd;getPermissionMode;config;terminal;permissionHandler;promptForApprovalFn;sessionLogger;onToolExecution;hookTypeExecutors;transcriptPath;sessionAllowedTools=new Set;presetFreeRules;onProjectAllowTool;permissionPolicy;taskPermissions;homeDirectory;resolveInWorkspace;commandSandbox;denials=new ve;peerTurn=!1;autoMode;constructor(e){this.sessionId=e.sessionId,this.cwd=e.cwd,this.getPermissionMode=e.getPermissionMode,this.config=e.config,this.presetFreeRules=e.presetFreePermissions??{allow:[...e.config.permissions.allow],deny:[...e.config.permissions.deny]},Ee(this.configuredRules(e)),this.terminal=e.terminal,this.permissionHandler=e.permissionHandler,this.promptForApprovalFn=e.promptForApprovalFn,this.sessionLogger=e.sessionLogger,this.onToolExecution=e.onToolExecution,this.hookTypeExecutors=e.hookTypeExecutors,this.transcriptPath=e.transcriptPath,this.onProjectAllowTool=e.onProjectAllowTool,this.permissionPolicy=e.permissionPolicy,this.taskPermissions=e.taskPermissions,this.homeDirectory=e.homeDirectory??(0,r.homedir)(),this.resolveInWorkspace=Te(e.cwd),this.commandSandbox=e.commandSandbox,e.permissionClassifier!==void 0&&(this.autoMode=new oe(e.permissionClassifier))}beginTurn(e){this.peerTurn=e}endTurn(){this.peerTurn=!1}hasPermissionClassifier(){return this.autoMode!==void 0}allowRetryOfDenial(e){let t=this.denials.list()[e],n=this.denials.callAt(e);if(t?.reason===`classifier`&&n!==void 0&&this.autoMode!==void 0)return this.autoMode.grantRetry(n.toolName,n.toolArgs),t}configuredRules(e={config:this.config,...this.taskPermissions===void 0?{}:{taskPermissions:this.taskPermissions}}){return{allow:[...e.config.permissions.allow,...e.taskPermissions?.allow??[]],restrictive:[...e.config.permissions.deny,...e.config.permissions.ask??[],...e.taskPermissions?.deny??[]]}}isToolVisible(t){let n=(0,e.getToolPermissionProfile)(t);return!this.peerTurn&&n.repliesToPeer===!0||this.peerTurn&&n.notInPeerTurn===!0?!1:!(0,e.isToolDeniedOutright)(t,[...this.config.permissions.deny,...this.taskPermissions?.deny??[]])}registerToolParameters(t){for(let n of t){let t=n.schema;if(t===void 0)continue;let r=t.parameters?.properties??{};(0,e.registerToolPermissionProfile)(t.name,{parameters:Object.keys(r)})}let n=this.configuredRules();Ee(n);for(let{pattern:t,reason:r}of(0,e.findPermissionPatternWarnings)(n.restrictive))this.terminal.writeLine(` ⚠ Permission rule "${t}" ${r}.`)}wrapTools(e){this.registerToolParameters(e);let t={sessionId:this.sessionId,cwd:this.cwd,config:this.config,terminal:this.terminal,transcriptPath:this.transcriptPath,onToolExecution:this.onToolExecution,hookTypeExecutors:this.hookTypeExecutors,getPermissionMode:this.getPermissionMode,log:(e,t)=>this.log(e,t),checkPermission:(e,t,n,r,i)=>this.decidePermission(e,t,n,r,i)};return e.map(e=>Se(e,t))}getSessionAllowedTools(){return[...this.sessionAllowedTools]}getRecentDenials(){return this.denials.list()}clearSessionAllowedTools(){this.sessionAllowedTools.clear()}currentPermissionRules(){return{allow:[...this.config.permissions.allow],deny:[...this.config.permissions.deny],ask:[...this.config.permissions.ask??[]]}}applyPresetToolLists(t){let n=(0,e.applyPresetToolLists)(this.presetFreeRules,t);this.config.permissions.allow=n.allow,this.config.permissions.deny=n.deny}async checkPermission(e,t,n,r=`interactive`,i){return await this.decidePermission(e,t,n,r,i)===!0}async checkDelegatedToolCall(e,t,n){let r=me(this.sessionId,this.cwd,e,t,this.getPermissionMode(),this.transcriptPath);return await he(this.config.hooks,r,this.hookTypeExecutors)?(this.log(`tool_blocked`,{tool:e,reason:`hook`,delegated:!0}),!1):await this.decidePermission(e,t,n,`interactive`,void 0,{sandboxed:!1})===!0}async decidePermission(t,n,r,i=`interactive`,a,o={}){let s=this.permissionPolicy===void 0?void 0:(0,e.projectPermissionPolicy)(this.permissionPolicy,{taskAllow:this.taskPermissions?.allow,taskDeny:this.taskPermissions?.deny,parentAllow:this.config.permissions.allow}),c=this.getPermissionMode(),l=[...this.config.permissions.allow,...s?.allow??[]],u={allow:c===`auto`?(0,e.allowRulesForAutoMode)(l):l,deny:[...this.config.permissions.deny,...s?.deny??[]],ask:this.config.permissions.ask??[]},d={cwd:this.cwd,homeDirectory:this.homeDirectory},f=(0,e.evaluatePermission)(t,n,c,u,{...d,resolveInWorkspace:this.resolveInWorkspace,sandboxAutoApproved:o.sandboxed!==!1&&this.sandboxAutoApproves(t,n),...s?.ceiling===void 0?{}:{ceiling:s.ceiling},askAll:s?.askAll??!1,...this.peerTurn?{peerTurn:!0}:{}});if(this.firePermissionDecisionHook(t,n,f,a),f===`auto`)return!0;if(f===`deny`)return this.denials.record(t,n,`policy`),!1;let p=(0,e.requiresFreshApproval)(t,n,u,d);return c===`auto`&&this.autoMode!==void 0&&!p&&s?.askAll!==!0?this.decideInAutoMode(this.autoMode,t,n,r,i,a,o):this.promptForApproval(t,n,r,i,p)}async decideInAutoMode(t,n,r,i,a,o,s){if(t.takeRetry(n,r)||(0,e.matchesAnyPattern)(n,r,(0,e.allowRulesForAutoMode)([...this.sessionAllowedTools])))return!0;if(t.isPaused()){let e=await this.promptForApproval(n,r,i,a,!0);return e&&t.resume(),e}let c=await t.judge({toolName:n,toolArgs:r,cwd:this.cwd},i);return i?.aborted===!0?!1:this.getPermissionMode()===`auto`?c.kind===`allow`?!0:(this.denials.record(n,r,`classifier`,c.reason),{message:c.message}):this.decidePermission(n,r,i,a,o,s)}async promptForApproval(t,n,r,i=`interactive`,a=!1){let o=le(t,n),s=r?.aborted===!0,c=i===`interactive`&&(this.permissionHandler!==void 0||this.promptForApprovalFn!==void 0),l=await ie({toolName:t,alreadyAllowed:!a&&(0,e.matchesAnyPattern)(t,n,[...this.sessionAllowedTools]),...i===`interactive`&&this.permissionHandler?{handler:this.permissionHandler}:{},...i===`interactive`&&this.promptForApprovalFn?{injectedPrompt:this.promptForApprovalFn,terminal:this.terminal}:{},toolArgs:n,...r?{signal:r}:{}});if(!l.allowed&&!s&&this.denials.record(t,n,c?`user`:`no-approver`),a)return l.allowed;if(l.rememberForProject){if(this.onProjectAllowTool===void 0)throw Error(`Project-wide permission persistence is unavailable for this session.`);this.onProjectAllowTool(o)}return l.rememberForSession&&this.sessionAllowedTools.add(o),l.allowed}firePermissionDecisionHook(t,n,r,i){let a=this.getPermissionMode();(0,e.runHooks)(this.config.hooks,`PermissionDecision`,{session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PermissionDecision`,tool_name:t,tool_input:n,permission_decision:r,...a!==void 0&&{permission_mode:a},...this.transcriptPath!==void 0&&{transcript_path:this.transcriptPath},env:{CLAUDE_PROJECT_DIR:this.cwd,CLAUDE_SESSION_ID:this.sessionId}},this.hookTypeExecutors,i).catch(()=>void 0)}sandboxAutoApproves(t,n){if(this.commandSandbox===void 0)return!1;let r=(0,e.getToolPermissionProfile)(t).argument;if(r?.kind!==`command`)return!1;let i=n[r.key];return typeof i==`string`&&this.commandSandbox.autoApproves(t,i)}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}};function Oe(e,t,n,r,i){return new De({sessionId:t,cwd:n,getPermissionMode:r,config:{permissions:e.permissions??{allow:[],deny:[]},hooks:e.hooks},...e.presetFreePermissions===void 0?{}:{presetFreePermissions:e.presetFreePermissions},terminal:e.terminal,permissionHandler:e.permissionHandler,...e.commandSandbox===void 0?{}:{commandSandbox:e.commandSandbox},...e.permissionClassifier===void 0?{}:{permissionClassifier:e.permissionClassifier},promptForApprovalFn:e.promptForApproval,sessionLogger:e.sessionLogger,onToolExecution:e.onToolExecution,hookTypeExecutors:e.hookTypeExecutors,transcriptPath:i,onProjectAllowTool:e.onProjectAllowTool,permissionPolicy:e.permissionPolicy,taskPermissions:e.taskPermissions})}function ke(e,t,n,r){return{contextTracker:new b(t,e.contextMaxTokens,e.autoCompactThreshold),compactionOrchestrator:new ee({sessionId:n,cwd:r,model:t,hooks:e.hooks,compactInstructions:e.compactInstructions,basePrompt:e.compactionBasePrompt,hookTypeExecutors:e.hookTypeExecutors})}}function Ae(t,n,r,i,a,o,s){let c=n.wrapTools(r);return new e.Robota({name:t.agentName??`agent`,aiProviders:[i],defaultModel:{provider:i.name,model:a,...t.effort!==void 0&&{effort:t.effort},...t.temperature!==void 0&&{temperature:t.temperature},...t.maxOutputTokens!==void 0&&{maxTokens:t.maxOutputTokens}},systemMessage:o,tools:c,isToolVisible:e=>n.isToolVisible(e),logging:{enabled:!1},eventService:s,...t.providerTimeout!==void 0&&{timeout:t.providerTimeout},...t.responseFormat?{responseFormat:t.responseFormat}:{},...t.ask?{ask:t.ask}:{},...t.contextCapacityHint===void 0?{}:{contextCapacityHint:t.contextCapacityHint}})}const je=(0,e.createLogger)(`SessionHistoryOps`);function Me(e,t){return{...e,...t}}async function Ne(t,n,r){r?.throwIfAborted();let i=n.agent.getHistory(),a=i.filter(e=>e.role!==`system`);if(a.length===0)return;n.contextTracker.updateFromHistory(i);let o=n.contextTracker.getContextState(),s=await n.compactionOrchestrator.compact(n.aiProvider,a,t,r,n.trigger,n.hookTraceEnv);n.agent.clearHistory(),n.agent.injectMessage(`system`,n.systemMessage),n.agent.injectMessage(`assistant`,`[Context Summary]\n${s}`),n.contextTracker.updateFromHistory(n.agent.getHistory());let c={session_id:n.sessionId,cwd:n.cwd,hook_event_name:`PostCompact`,trigger:n.trigger,compact_summary:s};(0,e.runHooks)(n.hooks,`PostCompact`,c,n.hookTypeExecutors,n.hookTraceEnv).catch(e=>je.warn(`hook failed`,{error:e}));let l=n.contextTracker.getContextState();n.log(`context_compact`,{trigger:n.trigger,before:o,after:l}),n.onCompactEventCallback?.({trigger:n.trigger,before:o,after:l}),n.onCompactCallback&&n.onCompactCallback(s)}function Pe(e){let t=e.agent.getHistory(),n=new Date().toISOString(),r=e.sessionStore.load(e.sessionId);if(r.status!==`valid`&&r.status!==`missing`)return r;let i=r.status===`valid`?r.record:void 0,a={...i,id:e.sessionId,name:i?.name,cwd:e.cwd,createdAt:i?.createdAt??n,updatedAt:n,messages:t,history:e.getFullHistory(),systemPrompt:e.systemPrompt,toolSchemas:e.toolSchemas};return e.sessionStore.save(a),{status:`valid`,record:a}}const Fe=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Ie(){return`session_${(0,n.randomUUID)()}`}function Le(e){return e.length>0&&e.length<=128&&Fe.test(e)}function S(e){if(!Le(e))throw Error(`Invalid session id: ${JSON.stringify(e)}. A session id must be 1-128 characters of letters, digits, dot, underscore or hyphen, starting with a letter or digit.`)}const Re=(0,e.createLogger)(`SessionLifecycle`);function ze(e,t,n){e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>{n(`server_tool`,{tool:e,...t})})}function Be(t,n,r,i,a,o,s){(0,e.runHooks)(r,`SessionStart`,{session_id:t,cwd:n,hook_event_name:`SessionStart`,...o!==void 0&&{permission_mode:o},...s!==void 0&&{transcript_path:s},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:t}},i).then(e=>{e.stdout&&a(e.stdout)}).catch(e=>Re.warn(`SessionStart hook failed`,{error:e}))}async function Ve(t,n,r,i,a,o,s){await(0,e.runHooks)(i,`SessionEnd`,{session_id:t,cwd:n,hook_event_name:`SessionEnd`,reason:r,...o!==void 0&&{permission_mode:o},...s!==void 0&&{transcript_path:s},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:t}},a)}function He(e){return{...e?.ephemeralSystemContext!==void 0&&{ephemeralSystemContext:e.ephemeralSystemContext},...e?.driverId!==void 0&&{driverId:e.driverId},...e?.toolChoice!==void 0&&{toolChoice:e.toolChoice},...e?.traceContext!==void 0&&{traceContext:e.traceContext},...e?.peerTurn===!0&&{withholdHostedTools:!0}}}const Ue=`unknown_tool`;function We(e){return{knownToolNames:new Set(e.knownToolNames),unknownToolCallIds:new Set,...e.onToolExecution&&{onToolExecution:e.onToolExecution}}}function Ge(e,t,n){if(e.onToolExecution){if(t===`tool_execution_request`){Ke(e,n);return}t===`tool_execution_result`&&qe(e,n)}}function Ke(e,t){let n=C(t.toolName),r=C(t.toolCallId);!n||!r||e.knownToolNames.has(n)||(e.unknownToolCallIds.add(r),e.onToolExecution?.({type:`start`,toolName:n,toolArgs:Je(t.parameters)}))}function qe(e,t){let n=C(t.toolName),r=C(t.toolCallId);if(!n||!r)return;let i=Ye(t.metadata);if(!(e.unknownToolCallIds.has(r)||i?.errorCode===Ue))return;e.unknownToolCallIds.delete(r);let a=C(t.error)??`Tool "${n}" is not registered.`;e.onToolExecution?.({type:`end`,toolName:n,success:!1,toolResultData:JSON.stringify({success:!1,error:a,errorCode:Ue,requestedTool:C(i?.requestedTool)??n,availableTools:Xe(i?.availableTools)})})}function Je(e){let t=Ye(e);if(!t)return;let n={};for(let[e,r]of Object.entries(t))(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||typeof r==`object`&&r)&&(n[e]=r);return n}function C(e){return typeof e==`string`&&e.length>0?e:void 0}function Ye(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function Xe(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}const Ze=(0,e.createLogger)(`SessionRun`);function Qe(t,n,r,i){let a=typeof r.model==`string`?r.model:t.model,o=typeof r.provider==`string`?r.provider:t.aiProvider.name,s=r.effort,c=typeof s==`string`&&(0,e.isModelEffort)(s)?s:t.effort??(typeof t.agent.getModel==`function`?t.agent.getModel().effort:void 0)??`high`,l=typeof r.round==`number`?r.round:void 0;(0,e.runHooks)(t.hooks,n,{session_id:t.sessionId,cwd:t.cwd,hook_event_name:n,model:a,provider:o,effort:c,...l!==void 0&&{round:l},...t.permissionMode!==void 0&&{permission_mode:t.permissionMode},...t.transcriptPath!==void 0&&{transcript_path:t.transcriptPath},env:{CLAUDE_PROJECT_DIR:t.cwd,CLAUDE_SESSION_ID:t.sessionId}},t.hookTypeExecutors,i).catch(e=>Ze.warn(`hook failed`,{error:e}))}async function $e(t,n,r,i,a){let o=a?.traceContext,s=o?(0,e.traceEnvFor)(`hooks`,o,o.parentSpanId):void 0;if(r.contextTracker.updateFromHistory(r.agent.getHistory()),r.contextTracker.shouldAutoCompact()){let e=r.aiProvider,t=e.onTextDelta;e.onTextDelta=void 0;try{await(s?r.compact(i,s):r.compact(i))}finally{e.onTextDelta=t}}r.log(`user`,{content:t});let c=await(0,e.runHooks)(r.hooks,`UserPromptSubmit`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`UserPromptSubmit`,user_message:n??t,prompt:n??t,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s),l=[r.sessionStartStdout,c.stdout].filter(Boolean).join(`
6
+ `),u=l?`<system-reminder>\n${l}\n</system-reminder>\n${t}`:t;r.clearSessionStartStdout();let d=r.agent.getHistory(),f=JSON.stringify(d),p=(0,e.getProviderCapabilities)(r.aiProvider);r.log(`pre_run`,{historyLength:d.length,historyChars:f.length,historyEstTokens:Math.ceil(f.length/e.CONTEXT_ESTIMATE_CHARS_PER_TOKEN),input:u,history:d,model:r.model,provider:r.aiProvider.name,maxTokens:r.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:p.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:p.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:p.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:p.nativeWebTools.webFetch.enabled}),r.contextTracker.updateFromHistory([...d,(0,e.createUserMessage)(u)]),r.onContextUpdate?.(r.contextTracker.getContextState());let m;try{let t=We({knownToolNames:r.knownToolNames??[],...r.onToolExecution&&{onToolExecution:r.onToolExecution}}),n=r.onTextDelta?e=>{r.log(`text_delta`,{delta:e}),r.onTextDelta?.(e)}:void 0,o={};if(m=await r.agent.run(u,{signal:i,maxExecutionRounds:r.maxTurns??0,...He(a),onExecutionEvent:(n,i)=>{if(n!==e.PROVIDER_CALL_EVENTS.COMPLETED&&r.log(n,i),Ge(t,n,i),n===`provider_request`){let e=i;o={model:e.model,provider:e.provider},Qe(r,`PreModelCall`,e,s)}else if(n===`provider_response_normalized`)Qe(r,`PostModelCall`,{...i,...o},s);else if(n===e.PROVIDER_FALLBACK_EVENTS.SWITCHED){let t=(0,e.readModelFallbackNotice)(i);t!==void 0&&(Qe(r,`PostModelCall`,{round:i.round,model:t.from.model,provider:t.from.provider},s),r.emitProviderFallback?.(t))}else if(n===e.PROVIDER_CALL_EVENTS.COMPLETED&&r.emitProviderCallCompleted){let e=i;Number.isSafeInteger(e.round)&&e.round>0&&typeof e.startedAt==`string`&&typeof e.endedAt==`string`&&(e.outcome===`success`||e.outcome===`failure`||e.outcome===`interrupted`)&&r.emitProviderCallCompleted({round:e.round,startedAt:e.startedAt,endedAt:e.endedAt,outcome:e.outcome,...typeof e.callId==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e.callId)&&{callId:e.callId},...(e.disposition===`invoked`||e.disposition===`cache-hit`||e.disposition===`preflight-refused`)&&{disposition:e.disposition},...typeof e.providerId==`string`&&e.providerId.length>0&&e.providerId.length<=128&&[...e.providerId].every(e=>e.charCodeAt(0)>=32)&&{providerId:e.providerId},...typeof e.modelId==`string`&&e.modelId.length>0&&e.modelId.length<=128&&[...e.modelId].every(e=>e.charCodeAt(0)>=32)&&{modelId:e.modelId},...(e.usageProvenance===`complete`||e.usageProvenance===`partial`||e.usageProvenance===`absent`)&&{usageProvenance:e.usageProvenance},...e.usageProvenance===`complete`&&typeof e.promptTokens==`number`&&Number.isSafeInteger(e.promptTokens)&&e.promptTokens>=0&&typeof e.completionTokens==`number`&&Number.isSafeInteger(e.completionTokens)&&e.completionTokens>=0&&typeof e.totalTokens==`number`&&Number.isSafeInteger(e.totalTokens)&&e.totalTokens===e.promptTokens+e.completionTokens&&{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens},...e.disposition===`invoked`&&typeof e.providerRequestId==`string`&&{providerRequestId:e.providerRequestId}})}n===`assistant_message_committed`&&(r.contextTracker.updateFromHistory(r.agent.getHistory()),r.onContextUpdate?.(r.contextTracker.getContextState()))},...n&&{onTextDelta:n}}),i.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(t){throw r.log(`error`,{message:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack??``:``,historyLength:r.agent.getHistory().length}),(0,e.runHooks)(r.hooks,`StopFailure`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`StopFailure`,reason:t instanceof Error?t.message:String(t),stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s).catch(e=>Ze.warn(`hook failed`,{error:e})),t}let h=r.agent.getHistory(),g=h.map(e=>{let t=`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0,n=t?e.toolCalls.map(e=>e.function.name):[];return{role:e.role,contentLength:typeof e.content==`string`?e.content.length:0,hasToolCalls:t,toolCallNames:n,...e.metadata?{metadata:e.metadata}:{}}});r.log(`assistant`,{content:m,historyLength:h.length,estimatedChars:JSON.stringify(h).length,history:h,historyStructure:g}),r.contextTracker.updateFromHistory(h);let _=r.contextTracker.getContextState();return r.onContextUpdate?.(_),r.log(`context`,{maxTokens:_.maxTokens,usedTokens:_.usedTokens,usedPercentage:_.usedPercentage,remainingPercentage:_.remainingPercentage}),(0,e.runHooks)(r.hooks,`Stop`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`Stop`,response:m.substring(0,500),last_assistant_message:m,stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s).catch(e=>Ze.warn(`hook failed`,{error:e})),r.getSessionStore()&&r.persistSession(),m}var et=class{agent;claim;sessionId;execution=null;constructor(e,t,n){this.agent=e,this.claim=t,this.sessionId=n}async invoke(e,t,r){let i=this.claim.claim(),a=tt(i,r);try{return i.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:(0,n.randomUUID)(),sessionId:this.sessionId,signal:i.signal,permissionInteraction:`deny`}),await this.execution}finally{this.execution=null,a(),this.claim.release(i)}}async drain(){await this.execution}};function tt(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var nt=class extends f{agent;eventService=new e.ObservableEventService;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;terminal;sessionStore;hooks;hookTypeExecutors;onTextDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;runtimeTools;wrapAddedTools;pendingTools=[];toolChange=Promise.resolve();shuttingDown=!1;shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(t){super(t.cwd);let{tools:n,provider:r,systemMessage:i}=t;this.terminal=t.terminal,this.sessionStore=t.sessionStore,this.systemMessage=i,this.toolSchemas=n.map(e=>e.schema),this.wrapAddedTools=t.wrapAddedTools,this.sessionLogger=t.sessionLogger,this.hooks=t.hooks,this.hookTypeExecutors=t.hookTypeExecutors,this.onTextDeltaCallback=t.onTextDelta,this.onContextUpdateCallback=t.onContextUpdate,this.onToolExecutionCallback=t.onToolExecution,this.onCompactCallback=t.onCompact,this.onCompactEventCallback=t.onCompactEvent,this.maxTurns=t.maxTurns,this.model=t.model??`claude-sonnet-4-5`,this.sessionId=t.sessionId??Ie(),this.permissionMode=t.permissionMode??(t.defaultTrustLevel?e.TRUST_TO_MODE[t.defaultTrustLevel]:void 0)??`default`,this.activePresetId=t.activePresetId??`default`,this.parallelSubagentsEnabled=t.enableParallelSubagents??!0,this.transcriptPath=t.transcriptPath,this.log(`session_init`,{cwd:this.cwd,systemPromptLength:i.length,systemPrompt:i,toolSchemas:this.toolSchemas,model:this.model,provider:r.name}),this.aiProvider=r,ze(r,t,(e,t)=>this.log(e,t)),this.permissionEnforcer=Oe(t,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:a,compactionOrchestrator:o}=ke(t,this.model,this.sessionId,this.cwd);this.contextTracker=a,this.compactionOrchestrator=o,this.agent=Ae(t,this.permissionEnforcer,n,r,this.model,i,this.eventService),this.runtimeTools=new et(this.agent,this.turnClaim,this.sessionId),Be(this.sessionId,this.cwd,this.hooks,this.hookTypeExecutors,e=>void(this.sessionStartStdout=e),this.permissionMode,this.transcriptPath)}async run(e,t,n){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);let r=this.turnClaim.claim(),i=tt(r,n?.signal),{signal:a}=r;this.permissionEnforcer.beginTurn(n?.peerTurn===!0);try{a.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let r=await $e(e,t,this.buildRunContext(),a,n);return this.messageCount+=1,r}finally{this.permissionEnforcer.endTurn(),i(),this.turnClaim.release(r)}}addTools(e){return this.shuttingDown?Promise.reject(Error(`[LIFECYCLE] Session is shutting down`)):this.serializeToolChange(async()=>{let t=new Set([...this.toolSchemas.map(e=>e.name),...this.pendingTools.map(e=>e.schema.name)]),n=[];for(let r of e)t.has(r.schema.name)||(t.add(r.schema.name),n.push(r));return n.length===0?[]:(this.pendingTools.push(...n),this.turnClaim.isRunning()||await this.applyPendingTools(),n.map(e=>e.schema.name))})}serializeToolChange(e){let t=this.toolChange.then(e);return this.toolChange=t.then(()=>void 0,()=>void 0),t}async applyPendingTools(){if(this.pendingTools.length===0)return;let e=this.pendingTools.splice(0);await this.agent.ensureReady();let t=this.permissionEnforcer.wrapTools(this.wrapAddedTools?.(e)??e);await this.agent.updateTools([...this.agent.getConfig().tools??[],...t]),this.toolSchemas.push(...t.map(e=>e.schema))}async listRuntimeTools(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.agent.listRuntimeTools()}async invokeRuntimeTool(e,t,n){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.runtimeTools.invoke(e,t,n?.signal)}getEventService(){return this.eventService}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(){this.sessionStore&&Pe({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,agent:this.agent,getFullHistory:()=>this.getFullHistory()})}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;this.shuttingDown=!0;let t=e.reason??`other`,n=async(e,t)=>{try{await t()}catch(t){this.log(`session_shutdown_step_error`,{step:e,error:t instanceof Error?t.message:String(t)})}};return this.shutdownPromise=(async()=>{await n(`abort`,()=>this.abort()),await n(`drain-direct-tool`,()=>this.runtimeTools.drain()),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>Ve(this.sessionId,this.cwd,t,this.hooks,this.hookTypeExecutors,this.permissionMode,this.transcriptPath)),await n(`destroy-agent`,async()=>{await this.agent.destroy()})})(),this.shutdownPromise}swapProvider(e,t){this.agent.swapDefaultProvider(e,t),e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>this.log(`server_tool`,{tool:e,...t})),this.aiProvider=e}async compact(e,t=`manual`,n){await this.compactWith(e,t,n)}async compactWith(e,t,n,r){let i={systemMessage:this.systemMessage,compactionOrchestrator:this.compactionOrchestrator,onCompactCallback:this.onCompactCallback,onCompactEventCallback:this.onCompactEventCallback,trigger:t,...r?{hookTraceEnv:r}:{}};await Ne(e,Me(this.buildRunContext(),i),n)}buildRunContext(){return{sessionId:this.sessionId,cwd:this.cwd,model:this.model,effort:this.getModelEffort(),agent:this.agent,aiProvider:this.aiProvider,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,sessionStartStdout:this.sessionStartStdout,log:(e,t)=>this.log(e,t),compact:(e,t)=>this.compactWith(void 0,`auto`,e,t),persistSession:()=>this.persistSessionInternal(),getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,emitProviderCallCompleted:t=>this.eventService.emit(e.PROVIDER_CALL_EVENTS.COMPLETED,{timestamp:new Date,...t},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:t=>this.eventService.emit(e.PROVIDER_FALLBACK_EVENTS.SWITCHED,{timestamp:new Date,fromProvider:t.from.provider,fromModel:t.from.model,toProvider:t.to.provider,toModel:t.to.model,reason:t.reason},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),knownToolNames:this.toolSchemas.map(e=>e.name)}}};function w(e,t){return e.length===0?t:`${e}.${t}`}function T(e,t){return`${e}[${t}]`}function E(e,t,n){e.push({path:t,message:n})}function D(e){if(e===null)return`null`;if(Array.isArray(e))return`an array`;if(e instanceof Date)return`a Date`;switch(typeof e){case`undefined`:return`nothing`;case`string`:return`a string`;case`number`:return`a number`;case`boolean`:return`a boolean`;case`object`:return`an object`;default:return`a ${typeof e}`}}function O(e,t,n){n!==void 0&&(e[t]=n)}function k(e,t,n,r){if(e!==void 0)return r(e,t,n)}function A(e,t,n){if(typeof e==`string`)return e;E(n,t,`expected a string, received ${D(e)}`)}function j(e,t,n){if(typeof e==`number`&&Number.isFinite(e))return e;E(n,t,`expected a finite number, received ${D(e)}`)}function M(e,t,n){if(typeof e==`number`&&Number.isInteger(e))return e;E(n,t,`expected an integer, received ${D(e)}`)}function N(e,t,n){if(typeof e==`boolean`)return e;E(n,t,`expected a boolean, received ${D(e)}`)}function P(e,t,n,r){if(typeof e==`string`&&t.includes(e))return e;E(r,n,`expected one of ${t.join(` | `)}, received ${D(e)}`)}function F(e,t,n){if(typeof e!=`string`){E(n,t,`expected an ISO-8601 timestamp string, received ${D(e)}`);return}if(Number.isNaN(Date.parse(e))){E(n,t,`expected a timestamp a date can be parsed from`);return}return e}function rt(e,t,n){if(e instanceof Date){if(Number.isNaN(e.getTime())){E(n,t,`expected a valid Date, received an invalid one`);return}return e}if(typeof e==`string`&&!Number.isNaN(Date.parse(e)))return new Date(e);E(n,t,`expected a Date or an ISO-8601 timestamp string, received ${D(e)}`)}function I(e,t,n,r){if(!Array.isArray(e)){E(n,t,`expected an array, received ${D(e)}`);return}let i=[];return e.forEach((e,a)=>{let o=r(e,T(t,a),n);o!==void 0&&i.push(o)}),i}function it(e,t,n){return I(e,t,n,A)}function L(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e)){E(n,t,`expected an object, received ${D(e)}`);return}let i=e,a=new Set(r);for(let e of Object.keys(i))a.has(e)||E(n,w(t,e),`unknown key; the record contract does not declare it`);return i}function R(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e)){E(n,t,`expected an object, received ${D(e)}`);return}let i={};for(let[a,o]of Object.entries(e)){let e=r(o,w(t,a),n);e!==void 0&&(i[a]=e)}return i}function z(e,t,n){if(e===null||e instanceof Date||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){let r=[];return e.forEach((e,i)=>{let a=z(e,T(t,i),n);a!==void 0&&r.push(a)}),r}if(typeof e==`object`)return R(e,t,n,z);E(n,t,`expected a JSON-compatible value, received ${D(e)}`)}function at(e,t,n){if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;E(n,t,`expected a string, number or boolean, received ${D(e)}`)}const ot=[`complete`,`interrupted`],B=[`id`,`timestamp`,`state`,`metadata`,`role`,`content`,`parts`],st={user:[...B,`name`],assistant:[...B,`toolCalls`],system:[...B,`name`],tool:[...B,`toolCallId`,`name`]};function ct(e,t,n){if(e instanceof Date||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.every(e=>typeof e==`string`)||e.every(e=>typeof e==`number`))return e;E(n,t,`expected an array of only strings or only numbers`);return}if(typeof e==`object`&&e){let r={};for(let[i,a]of Object.entries(e)){if(typeof a!=`number`){E(n,w(t,i),`expected a number, received ${D(a)}`);continue}r[i]=a}return r}E(n,t,`expected a metadata value, received ${D(e)}`)}function lt(e,t,n){return R(e,t,n,ct)}function ut(e,t,n){let r=P(e?.type,[`text`,`image_inline`,`image_uri`],w(t,`type`),n);if(r===void 0)return;if(r===`text`){let r=L(e,t,n,[`type`,`text`]);if(r===void 0)return;let i=A(r.text,w(t,`text`),n);return i===void 0?void 0:{type:`text`,text:i}}if(r===`image_inline`){let r=L(e,t,n,[`type`,`mimeType`,`data`]);if(r===void 0)return;let i=A(r.mimeType,w(t,`mimeType`),n),a=A(r.data,w(t,`data`),n);return i===void 0||a===void 0?void 0:{type:`image_inline`,mimeType:i,data:a}}let i=L(e,t,n,[`type`,`uri`,`mimeType`]);if(i===void 0)return;let a=A(i.uri,w(t,`uri`),n);if(a===void 0)return;let o={type:`image_uri`,uri:a};return O(o,`mimeType`,k(i.mimeType,w(t,`mimeType`),n,A)),o}function dt(e,t,n){let r=L(e,t,n,[`id`,`type`,`function`]);if(r===void 0)return;let i=A(r.id,w(t,`id`),n),a=P(r.type,[`function`],w(t,`type`),n),o=w(t,`function`),s=L(r.function,o,n,[`name`,`arguments`]),c=s===void 0?void 0:A(s.name,w(o,`name`),n),l=s===void 0?void 0:A(s.arguments,w(o,`arguments`),n);if(i!==void 0&&a!==void 0&&c!==void 0&&l!==void 0)return{id:i,type:a,function:{name:c,arguments:l}}}function ft(e,t,n){let r=A(e.id,w(t,`id`),n),i=rt(e.timestamp,w(t,`timestamp`),n),a=P(e.state,ot,w(t,`state`),n);if(r!==void 0&&i!==void 0&&a!==void 0)return{id:r,timestamp:i,state:a}}function pt(e,t,n,r){O(e,`metadata`,k(t.metadata,w(n,`metadata`),r,lt)),O(e,`parts`,k(t.parts,w(n,`parts`),r,(e,t,n)=>I(e,t,n,ut)))}function V(e,t,n){let r=P(e?.role,[`user`,`assistant`,`system`,`tool`],w(t,`role`),n);if(r===void 0)return;let i=L(e,t,n,st[r]);if(i===void 0)return;let a=ft(i,t,n);if(a===void 0)return;let o=w(t,`content`);if(r===`assistant`){let e=i.content===null?null:A(i.content,o,n);if(e===void 0)return;let s={...a,role:r,content:e};return pt(s,i,t,n),O(s,`toolCalls`,k(i.toolCalls,w(t,`toolCalls`),n,(e,t,n)=>I(e,t,n,dt))),s}let s=A(i.content,o,n);if(s===void 0)return;if(r===`tool`){let e=A(i.toolCallId,w(t,`toolCallId`),n);if(e===void 0)return;let o={...a,role:r,content:s,toolCallId:e};return pt(o,i,t,n),O(o,`name`,k(i.name,w(t,`name`),n,A)),o}let c={...a,role:r,content:s};return pt(c,i,t,n),O(c,`name`,k(i.name,w(t,`name`),n,A)),c}function mt(e,t,n){let r=L(e,t,n,[`id`,`timestamp`,`category`,`type`,`data`]);if(r===void 0)return;let i=A(r.id,w(t,`id`),n),a=rt(r.timestamp,w(t,`timestamp`),n),o=A(r.category,w(t,`category`),n),s=A(r.type,w(t,`type`),n);if(i===void 0||a===void 0||o===void 0||s===void 0)return;let c={id:i,timestamp:a,category:o,type:s};return O(c,`data`,k(r.data,w(t,`data`),n,z)),c}const ht=[`agent`,`process`,`scheduled`,`tool-invocation`],gt=[`foreground`,`background`],_t=[`none`,`worktree`],vt=[`queued`,`running`,`waiting_permission`,`sleeping`,`paused`,`completed`,`failed`,`cancelled`],yt=[`idle`,`max_runtime`,`output_limit`,`repetition`,`stale_worker`],bt=[`validation`,`capacity`,`permission`,`timeout`,`runner`,`crash`,`provider`,`process`];function xt(e,t,n){return R(e,t,n,at)}function St(e,t,n){return R(e,t,n,A)}function Ct(e,t,n){let r=L(e,t,n,[`category`,`message`,`recoverable`]);if(r===void 0)return;let i=P(r.category,bt,w(t,`category`),n),a=A(r.message,w(t,`message`),n),o=N(r.recoverable,w(t,`recoverable`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{category:i,message:a,recoverable:o}}function wt(e,t,n){let r=L(e,t,n,[`promptTokens`,`completionTokens`,`totalTokens`]);if(r===void 0)return;let i=M(r.promptTokens,w(t,`promptTokens`),n),a=M(r.completionTokens,w(t,`completionTokens`),n),o=M(r.totalTokens,w(t,`totalTokens`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{promptTokens:i,completionTokens:a,totalTokens:o}}function Tt(e,t,n){let r=L(e,t,n,[`taskId`,`kind`,`output`,`exitCode`,`signalCode`,`metadata`,`usage`]);if(r===void 0)return;let i=A(r.taskId,w(t,`taskId`),n),a=P(r.kind,ht,w(t,`kind`),n),o=A(r.output,w(t,`output`),n);if(i===void 0||a===void 0||o===void 0)return;let s=k(r.exitCode,w(t,`exitCode`),n,M),c=k(r.signalCode,w(t,`signalCode`),n,A),l=k(r.metadata,w(t,`metadata`),n,xt),u=k(r.usage,w(t,`usage`),n,wt);switch(a!==`process`&&s!==void 0&&E(n,w(t,`exitCode`),`must not be set for a '${a}' result`),a!==`process`&&c!==void 0&&E(n,w(t,`signalCode`),`must not be set for a '${a}' result`),a!==`agent`&&u!==void 0&&E(n,w(t,`usage`),`must not be set for a '${a}' result`),a){case`process`:{let e={taskId:i,kind:a,output:o};return O(e,`exitCode`,s),O(e,`signalCode`,c),O(e,`metadata`,l),e}case`agent`:{let e={taskId:i,kind:a,output:o};return O(e,`metadata`,l),O(e,`usage`,u),e}case`scheduled`:{let e={taskId:i,kind:a,output:o};return O(e,`metadata`,l),e}case`tool-invocation`:{let e={taskId:i,kind:a,output:o};return O(e,`metadata`,l),e}}}function Et(e,t,n){let r=L(e,t,n,[`cronExpression`,`agentInstruction`,`command`,`shell`,`env`]);if(r===void 0)return;let i=A(r.cronExpression,w(t,`cronExpression`),n);if(i===void 0)return;let a={cronExpression:i};for(let e of[`agentInstruction`,`command`,`shell`])O(a,e,k(r[e],w(t,e),n,A));return O(a,`env`,k(r.env,w(t,`env`),n,St)),a}const Dt=[`detached`,`wait_all`,`wait_any`,`manual`],Ot=[`running`,`completed`],kt=[`background_job_group_created`,`background_job_group_updated`,`background_job_group_completed`];function At(e,t,n){let r=L(e,t,n,[`taskId`,`label`,`status`,`summary`,`outputRef`,`error`,`startedAt`,`completedAt`]);if(r===void 0)return;let i=A(r.taskId,w(t,`taskId`),n),a=A(r.label,w(t,`label`),n),o=P(r.status,vt,w(t,`status`),n);if(i===void 0||a===void 0||o===void 0)return;let s={taskId:i,label:a,status:o};for(let e of[`summary`,`outputRef`])O(s,e,k(r[e],w(t,e),n,A));for(let e of[`startedAt`,`completedAt`])O(s,e,k(r[e],w(t,e),n,F));return O(s,`error`,k(r.error,w(t,`error`),n,Ct)),s}function jt(e,t,n){let r=L(e,t,n,[`id`,`parentSessionId`,`waitPolicy`,`taskIds`,`status`,`createdAt`,`updatedAt`,`label`,`completedAt`,`results`]);if(r===void 0)return;let i=A(r.id,w(t,`id`),n),a=A(r.parentSessionId,w(t,`parentSessionId`),n),o=P(r.waitPolicy,Dt,w(t,`waitPolicy`),n),s=it(r.taskIds,w(t,`taskIds`),n),c=P(r.status,Ot,w(t,`status`),n),l=F(r.createdAt,w(t,`createdAt`),n),u=F(r.updatedAt,w(t,`updatedAt`),n),d=I(r.results,w(t,`results`),n,At);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0)return;let f={id:i,parentSessionId:a,waitPolicy:o,taskIds:s,status:c,createdAt:l,updatedAt:u,results:d};return O(f,`label`,k(r.label,w(t,`label`),n,A)),O(f,`completedAt`,k(r.completedAt,w(t,`completedAt`),n,F)),f}function Mt(e,t,n){let r=P(e?.type,kt,w(t,`type`),n);if(r===void 0)return;let i=L(e,t,n,[`type`,`group`]);if(i===void 0)return;let a=jt(i.group,w(t,`group`),n);return a===void 0?void 0:{type:r,group:a}}const Nt=[`parentTaskId`,`currentAction`,`logPath`,`transcriptPath`],Pt=[`agentType`,`resumeSessionId`,`promptPreview`,`worktreePath`,`branchName`,`worktreeStatus`,`worktreeNextAction`,`worktreeBaseRevision`,`parentWorktreeStatus`],Ft=[`commandPreview`],It=[`startedAt`,`lastActivityAt`,`completedAt`],Lt=[`id`,`kind`,`label`,`status`,`mode`,`parentSessionId`,`depth`,`cwd`,`pid`,`updatedAt`,`isolation`,`unread`,`result`,`error`,`timeoutReason`,`schedule`,`nextFireAt`,`metadata`,...Nt,...Pt,...Ft,...It];function Rt(e,t,n){let r=L(e,t,n,Lt);if(r===void 0)return;let i=A(r.id,w(t,`id`),n),a=P(r.kind,ht,w(t,`kind`),n),o=A(r.label,w(t,`label`),n),s=P(r.status,vt,w(t,`status`),n),c=P(r.mode,gt,w(t,`mode`),n),l=A(r.parentSessionId,w(t,`parentSessionId`),n),u=M(r.depth,w(t,`depth`),n),d=A(r.cwd,w(t,`cwd`),n),f=F(r.updatedAt,w(t,`updatedAt`),n),p=N(r.unread,w(t,`unread`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0||f===void 0||p===void 0)return;let m={id:i,label:o,status:s,mode:c,parentSessionId:l,depth:u,cwd:d,updatedAt:f,unread:p};for(let e of Nt)O(m,e,k(r[e],w(t,e),n,A));for(let e of It)O(m,e,k(r[e],w(t,e),n,F));O(m,`pid`,k(r.pid,w(t,`pid`),n,M)),O(m,`timeoutReason`,k(r.timeoutReason,w(t,`timeoutReason`),n,(e,t,n)=>P(e,yt,t,n))),O(m,`metadata`,k(r.metadata,w(t,`metadata`),n,xt)),O(m,`error`,k(r.error,w(t,`error`),n,Ct));let h=k(r.result,w(t,`result`),n,Tt);h!==void 0&&(h.taskId!==i&&E(n,w(w(t,`result`),`taskId`),`must match the task ID`),h.kind!==a&&E(n,w(w(t,`result`),`kind`),`must match the task kind`));let g=k(r.agentType,w(t,`agentType`),n,A),_=k(r.resumeSessionId,w(t,`resumeSessionId`),n,A),v=k(r.promptPreview,w(t,`promptPreview`),n,A),ee=k(r.isolation,w(t,`isolation`),n,(e,t,n)=>P(e,_t,t,n)),y={};for(let e of[`worktreePath`,`branchName`,`worktreeStatus`,`worktreeNextAction`,`worktreeBaseRevision`,`parentWorktreeStatus`])y[e]=k(r[e],w(t,e),n,A);for(let e of Pt){let r=e===`agentType`?g:e===`resumeSessionId`?_:e===`promptPreview`?v:y[e];a!==`agent`&&r!==void 0&&E(n,w(t,e),`must not be set for a '${a}' task`)}a!==`agent`&&ee!==void 0&&E(n,w(t,`isolation`),`must not be set for a '${a}' task`);let b=k(r.commandPreview,w(t,`commandPreview`),n,A);a===`agent`&&b!==void 0&&E(n,w(t,`commandPreview`),`must not be set for a '${a}' task`);let te=k(r.schedule,w(t,`schedule`),n,Et),ne=k(r.nextFireAt,w(t,`nextFireAt`),n,F);switch(a!==`scheduled`&&te!==void 0&&E(n,w(t,`schedule`),`must not be set for a '${a}' task`),a!==`scheduled`&&ne!==void 0&&E(n,w(t,`nextFireAt`),`must not be set for a '${a}' task`),a){case`agent`:{let e=h?.kind===`agent`?h:void 0,t={...m,kind:a};return O(t,`result`,e),O(t,`agentType`,g),O(t,`resumeSessionId`,_),O(t,`promptPreview`,v),O(t,`isolation`,ee),O(t,`worktreePath`,y.worktreePath),O(t,`branchName`,y.branchName),O(t,`worktreeStatus`,y.worktreeStatus),O(t,`worktreeNextAction`,y.worktreeNextAction),O(t,`worktreeBaseRevision`,y.worktreeBaseRevision),O(t,`parentWorktreeStatus`,y.parentWorktreeStatus),t}case`process`:{let e=h?.kind===`process`?h:void 0,t={...m,kind:a};return O(t,`result`,e),O(t,`commandPreview`,b),t}case`tool-invocation`:{let e=h?.kind===`tool-invocation`?h:void 0,t={...m,kind:a};return O(t,`result`,e),O(t,`commandPreview`,b),t}case`scheduled`:{let e=h?.kind===`scheduled`?h:void 0,t={...m,kind:a};return O(t,`result`,e),O(t,`commandPreview`,b),O(t,`schedule`,te),O(t,`nextFireAt`,ne),t}}}const zt=[`background_task_created`,`background_task_started`,`background_task_updated`,`background_task_completed`,`background_task_failed`,`background_task_cancelled`,`background_task_text_delta`,`background_task_tool_start`,`background_task_tool_end`,`background_task_permission_request`,`background_task_closed`,`background_task_waking`];function H(e,t,n){return A(e.taskId,w(t,`taskId`),n)}function Bt(e,t,n){let r=L(e,t,n,[`type`,`taskId`,`delta`]);if(r===void 0)return;let i=H(r,t,n),a=A(r.delta,w(t,`delta`),n);if(i!==void 0&&a!==void 0)return{type:`background_task_text_delta`,taskId:i,delta:a}}function Vt(e,t,n){let r=L(e,t,n,[`type`,`taskId`,`toolName`,`firstArg`]);if(r===void 0)return;let i=H(r,t,n),a=A(r.toolName,w(t,`toolName`),n);if(i===void 0||a===void 0)return;let o={type:`background_task_tool_start`,taskId:i,toolName:a};return O(o,`firstArg`,k(r.firstArg,w(t,`firstArg`),n,A)),o}function Ht(e,t,n){let r=L(e,t,n,[`type`,`taskId`,`toolName`,`success`,`error`]);if(r===void 0)return;let i=H(r,t,n),a=A(r.toolName,w(t,`toolName`),n),o=N(r.success,w(t,`success`),n);if(i===void 0||a===void 0||o===void 0)return;let s={type:`background_task_tool_end`,taskId:i,toolName:a,success:o};return O(s,`error`,k(r.error,w(t,`error`),n,A)),s}function Ut(e,t,n){let r=L(e,t,n,[`type`,`taskId`,`requestId`,`toolName`,`toolArgs`]);if(r===void 0)return;let i=H(r,t,n),a=A(r.requestId,w(t,`requestId`),n),o=A(r.toolName,w(t,`toolName`),n),s=xt(r.toolArgs,w(t,`toolArgs`),n);if(i!==void 0&&a!==void 0&&o!==void 0&&s!==void 0)return{type:`background_task_permission_request`,taskId:i,requestId:a,toolName:o,toolArgs:s}}function Wt(e,t,n){let r=L(e,t,n,[`type`,`taskId`]);if(r===void 0)return;let i=H(r,t,n);return i===void 0?void 0:{type:`background_task_closed`,taskId:i}}function Gt(e,t,n){let r=L(e,t,n,[`type`,`taskId`,`instruction`]);if(r===void 0)return;let i=H(r,t,n);if(i===void 0)return;let a={type:`background_task_waking`,taskId:i};return O(a,`instruction`,k(r.instruction,w(t,`instruction`),n,A)),a}function Kt(e,t,n,r){let i=L(t,n,r,[`type`,`task`]);if(i===void 0)return;let a=Rt(i.task,w(n,`task`),r);if(a!==void 0)return{type:e,task:a}}const qt={background_task_text_delta:Bt,background_task_tool_start:Vt,background_task_tool_end:Ht,background_task_permission_request:Ut,background_task_closed:Wt,background_task_waking:Gt};function Jt(e,t,n){let r=P(e?.type,zt,w(t,`type`),n);if(r===void 0)return;let i=qt[r];return i===void 0?Kt(r,e,t,n):i(e,t,n)}const Yt=[`skill`,`plugin`],Xt=[`user-slash`,`model-tool`],Zt=[`inject`,`fork`],Qt=[`started`,`completed`,`failed`],$t=[`memory_candidate_extracted`,`memory_candidate_queued`,`memory_candidate_saved`,`memory_candidate_skipped`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`],en=[`manual`,`prompt-reference`,`system`],tn=[`active`,`observed`];function nn(e,t,n){let r=L(e,t,n,[`type`,`skillName`,`source`,`invocation`,`mode`,`status`,`timestamp`,`qualifiedName`,`error`]);if(r===void 0)return;let i=P(r.type,[`skill-activation`],w(t,`type`),n),a=A(r.skillName,w(t,`skillName`),n),o=P(r.source,Yt,w(t,`source`),n),s=P(r.invocation,Xt,w(t,`invocation`),n),c=P(r.mode,Zt,w(t,`mode`),n),l=P(r.status,Qt,w(t,`status`),n),u=F(r.timestamp,w(t,`timestamp`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0)return;let d=k(r.qualifiedName,w(t,`qualifiedName`),n,A),f=k(r.error,w(t,`error`),n,A);return{type:i,skillName:a,source:o,invocation:s,mode:c,status:l,timestamp:u,...d===void 0?{}:{qualifiedName:d},...f===void 0?{}:{error:f}}}function rn(e,t,n){let r=L(e,t,n,[`topic`,`path`,`score`,`truncated`]);if(r===void 0)return;let i=A(r.topic,w(t,`topic`),n),a=A(r.path,w(t,`path`),n),o=j(r.score,w(t,`score`),n),s=N(r.truncated,w(t,`truncated`),n);if(i!==void 0&&a!==void 0&&o!==void 0&&s!==void 0)return{topic:i,path:a,score:o,truncated:s}}function an(e,t,n){let r=L(e,t,n,[`type`,`at`,`candidateId`,`topic`,`reason`,`data`]);if(r===void 0)return;let i=P(r.type,$t,w(t,`type`),n),a=F(r.at,w(t,`at`),n);if(i===void 0||a===void 0)return;let o={type:i,at:a};for(let e of[`candidateId`,`topic`,`reason`])O(o,e,k(r[e],w(t,e),n,A));return O(o,`data`,k(r.data,w(t,`data`),n,(e,t,n)=>R(e,t,n,z))),o}function on(e,t,n){let r=L(e,t,n,[`id`,`sourcePath`,`relativePath`,`originalReference`,`loadType`,`status`,`byteLength`,`loadedAt`,`lastUsedAt`]);if(r===void 0)return;let i=A(r.id,w(t,`id`),n),a=A(r.sourcePath,w(t,`sourcePath`),n),o=A(r.relativePath,w(t,`relativePath`),n),s=A(r.originalReference,w(t,`originalReference`),n),c=P(r.loadType,en,w(t,`loadType`),n),l=P(r.status,tn,w(t,`status`),n),u=M(r.byteLength,w(t,`byteLength`),n),d=F(r.loadedAt,w(t,`loadedAt`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0)return;let f={id:i,sourcePath:a,relativePath:o,originalReference:s,loadType:c,status:l,byteLength:u,loadedAt:d};return O(f,`lastUsedAt`,k(r.lastUsedAt,w(t,`lastUsedAt`),n,F)),f}const sn=[`active`,`satisfied`,`stopped`],cn=[`satisfied`,`max-iterations`,`cancelled`,`no-progress`],ln=[`continue`,`satisfied`],un=[`pending`,`in-progress`,`done`],dn=[`planning`,`awaiting-approval`,`executing`,`completed`];function fn(e,t,n){let r=L(e,t,n,[`iteration`,`signal`,`reason`]);if(r===void 0)return;let i=M(r.iteration,w(t,`iteration`),n),a=P(r.signal,ln,w(t,`signal`),n),o=A(r.reason,w(t,`reason`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{iteration:i,signal:a,reason:o}}function pn(e,t,n){let r=L(e,t,n,[`id`,`objective`,`status`,`stopReason`,`iterations`,`maxIterations`,`startedAt`,`progress`]);if(r===void 0)return;let i=A(r.id,w(t,`id`),n),a=A(r.objective,w(t,`objective`),n),o=P(r.status,sn,w(t,`status`),n),s=M(r.iterations,w(t,`iterations`),n),c=M(r.maxIterations,w(t,`maxIterations`),n),l=F(r.startedAt,w(t,`startedAt`),n),u=I(r.progress,w(t,`progress`),n,fn);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0)return;let d={id:i,objective:a,status:o,iterations:s,maxIterations:c,startedAt:l,progress:u};return O(d,`stopReason`,k(r.stopReason,w(t,`stopReason`),n,(e,t,n)=>P(e,cn,t,n))),d}function mn(e,t,n){let r=L(e,t,n,[`id`,`description`,`status`]);if(r===void 0)return;let i=A(r.id,w(t,`id`),n),a=A(r.description,w(t,`description`),n),o=P(r.status,un,w(t,`status`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{id:i,description:a,status:o}}function hn(e,t,n){let r=L(e,t,n,[`id`,`objective`,`steps`,`phase`,`createdAt`,`approvedAt`]);if(r===void 0)return;let i=A(r.id,w(t,`id`),n),a=A(r.objective,w(t,`objective`),n),o=I(r.steps,w(t,`steps`),n,mn),s=P(r.phase,dn,w(t,`phase`),n),c=F(r.createdAt,w(t,`createdAt`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0)return;let l={id:i,objective:a,steps:o,phase:s,createdAt:c};return O(l,`approvedAt`,k(r.approvedAt,w(t,`approvedAt`),n,F)),l}function gn(e,t,n){let r=L(e,t,n,[`branchId`,`checkpointId`]);if(r===void 0)return;let i=A(r.branchId,w(t,`branchId`),n),a=A(r.checkpointId,w(t,`checkpointId`),n);if(i!==void 0&&a!==void 0)return{branchId:i,checkpointId:a}}const _n=[`waiting`,`pending`,`running`,`stopped`,`expired`],vn=[`loopId`,`instruction`,`useDefaultPrompt`,`createdAt`,`expiresAt`,`revision`,`generation`,`phase`,`nextAllowedAt`,`delaySeconds`,`reason`,`fallbackUsed`,`terminalReason`];function yn(e,t,n){let r=L(e,t,n,vn);if(!r)return;let i=A(r.loopId,w(t,`loopId`),n),a=A(r.instruction,w(t,`instruction`),n),o=k(r.useDefaultPrompt,w(t,`useDefaultPrompt`),n,N),s=F(r.createdAt,w(t,`createdAt`),n),c=F(r.expiresAt,w(t,`expiresAt`),n),l=M(r.revision,w(t,`revision`),n),u=M(r.generation,w(t,`generation`),n),d=P(r.phase,_n,w(t,`phase`),n),f=N(r.fallbackUsed,w(t,`fallbackUsed`),n),p=k(r.nextAllowedAt,w(t,`nextAllowedAt`),n,F),m=k(r.delaySeconds,w(t,`delaySeconds`),n,M),h=k(r.reason,w(t,`reason`),n,A),g=k(r.terminalReason,w(t,`terminalReason`),n,A);if(l!==void 0&&(!Number.isSafeInteger(l)||l<0)&&E(n,w(t,`revision`),`expected a non-negative safe integer`),u!==void 0&&(!Number.isSafeInteger(u)||u<0)&&E(n,w(t,`generation`),`expected a non-negative safe integer`),m!==void 0&&(m<60||m>3600)&&E(n,w(t,`delaySeconds`),`expected a delay between 60 and 3600 seconds`),i!==void 0&&!i.trim()&&E(n,w(t,`loopId`),`expected a non-empty loop ID`),a!==void 0&&!a.trim()&&E(n,w(t,`instruction`),`expected a non-empty instruction`),d===`waiting`&&p===void 0&&r.nextAllowedAt===void 0&&E(n,w(t,`nextAllowedAt`),`waiting loop needs a next wake time`),i===void 0||a===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0||f===void 0)return;let _={loopId:i,instruction:a,createdAt:s,expiresAt:c,revision:l,generation:u,phase:d,fallbackUsed:f};return O(_,`useDefaultPrompt`,o),O(_,`nextAllowedAt`,p),O(_,`delaySeconds`,m),O(_,`reason`,h),O(_,`terminalReason`,g),_}const bn=[`string`,`number`,`integer`,`boolean`,`array`,`object`,`null`],xn=[`type`,`description`,`enum`,`items`,`properties`,`required`,`anyOf`,`additionalProperties`,`minimum`,`maximum`,`pattern`,`format`,`default`];function Sn(e,t,n){if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;E(n,t,`expected a string, number or boolean, received ${D(e)}`)}function Cn(e,t,n){return e===null?null:Sn(e,t,n)}function wn(e,t,n){return typeof e==`boolean`?e:U(e,t,n)}function U(e,t,n){let r=L(e,t,n,xn);if(r===void 0)return;let i={};return O(i,`type`,k(r.type,w(t,`type`),n,(e,t,n)=>P(e,bn,t,n))),O(i,`description`,k(r.description,w(t,`description`),n,A)),O(i,`enum`,k(r.enum,w(t,`enum`),n,(e,t,n)=>I(e,t,n,Sn))),O(i,`items`,k(r.items,w(t,`items`),n,U)),O(i,`properties`,k(r.properties,w(t,`properties`),n,(e,t,n)=>R(e,t,n,U))),O(i,`required`,k(r.required,w(t,`required`),n,it)),O(i,`anyOf`,k(r.anyOf,w(t,`anyOf`),n,(e,t,n)=>I(e,t,n,U))),O(i,`additionalProperties`,k(r.additionalProperties,w(t,`additionalProperties`),n,wn)),O(i,`minimum`,k(r.minimum,w(t,`minimum`),n,j)),O(i,`maximum`,k(r.maximum,w(t,`maximum`),n,j)),O(i,`pattern`,k(r.pattern,w(t,`pattern`),n,A)),O(i,`format`,k(r.format,w(t,`format`),n,A)),O(i,`default`,k(r.default,w(t,`default`),n,Cn)),i}function Tn(e,t,n){let r=U(e,t,n);if(r!==void 0){if(r.type!==`object`){E(n,w(t,`type`),`expected the root parameter schema to be type 'object'`);return}if(r.properties===void 0){E(n,w(t,`properties`),`expected the root parameter schema to name its properties`);return}return{...r,type:`object`,properties:r.properties}}}function En(e,t,n){let r=L(e,t,n,[`name`,`description`,`parameters`,`outputSchema`]);if(r===void 0)return;let i=A(r.name,w(t,`name`),n),a=A(r.description,w(t,`description`),n),o=Tn(r.parameters,w(t,`parameters`),n);if(i===void 0||a===void 0||o===void 0)return;let s={name:i,description:a,parameters:o};return O(s,`outputSchema`,k(r.outputSchema,w(t,`outputSchema`),n,U)),s}function W(e,t,n,r,i){return k(e[t],w(n,t),r,(e,t,n)=>I(e,t,n,i))}function Dn(e,t,n,r){for(let i of[`name`,`systemPrompt`,`sandboxSnapshotId`])O(e,i,k(t[i],w(n,i),r,A));O(e,`history`,W(t,`history`,n,r,mt)),O(e,`toolSchemas`,W(t,`toolSchemas`,n,r,En)),O(e,`backgroundTasks`,W(t,`backgroundTasks`,n,r,Rt)),O(e,`backgroundTaskEvents`,W(t,`backgroundTaskEvents`,n,r,Jt)),O(e,`backgroundJobGroups`,W(t,`backgroundJobGroups`,n,r,jt)),O(e,`backgroundJobGroupEvents`,W(t,`backgroundJobGroupEvents`,n,r,Mt)),O(e,`sessionLoops`,W(t,`sessionLoops`,n,r,yn)),O(e,`skillActivationEvents`,W(t,`skillActivationEvents`,n,r,nn)),O(e,`memoryEvents`,W(t,`memoryEvents`,n,r,an)),O(e,`usedMemoryReferences`,W(t,`usedMemoryReferences`,n,r,rn)),O(e,`contextReferences`,W(t,`contextReferences`,n,r,on)),O(e,`goal`,k(t.goal,w(n,`goal`),r,pn)),O(e,`plan`,k(t.plan,w(n,`plan`),r,hn)),O(e,`activeBranch`,k(t.activeBranch,w(n,`activeBranch`),r,gn))}const On=[`id`,`name`,`cwd`,`createdAt`,`updatedAt`,`messages`,`history`,`systemPrompt`,`toolSchemas`,`backgroundTasks`,`backgroundTaskEvents`,`backgroundJobGroups`,`backgroundJobGroupEvents`,`sessionLoops`,`skillActivationEvents`,`memoryEvents`,`usedMemoryReferences`,`contextReferences`,`sandboxSnapshotId`,`goal`,`plan`,`activeBranch`];function kn(e){let t=[],n=jn(e,``,t);return n===void 0||t.length>0?{status:`corrupt`,issues:t}:{status:`valid`,record:n}}function An(e){let t=[],n=L(e,``,t,[`schemaVersion`,`record`]);if(n===void 0)return{status:`corrupt`,issues:t};let r=n.schemaVersion;if(typeof r!=`number`||!Number.isFinite(r))return{status:`unsupported`,schemaVersion:void 0};if(r!==1)return{status:`unsupported`,schemaVersion:r};let i=jn(n.record,`record`,t);return i===void 0||t.length>0?{status:`corrupt`,issues:t}:{status:`valid`,record:i}}function jn(e,t,n){let r=L(e,t,n,On);if(r===void 0)return;let i=A(r.id,w(t,`id`),n),a=A(r.cwd,w(t,`cwd`),n),o=F(r.createdAt,w(t,`createdAt`),n),s=F(r.updatedAt,w(t,`updatedAt`),n),c=I(r.messages,w(t,`messages`),n,V);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0)return;let l={id:i,cwd:a,createdAt:o,updatedAt:s,messages:c};return Dn(l,r,t,n),l}function Mn(e){try{return JSON.parse(e)}catch{throw Error(`Invalid session artifact: the bytes are not JSON.`)}}function Nn(e,t={}){let n={schemaVersion:1,record:t.redact?t.redact(e):e};return JSON.stringify(n,null,2)}function Pn(e){let t=An(Mn(e));if(t.status===`unsupported`)throw Error(`Unsupported session artifact schema version ${t.schemaVersion??`(absent or not a number)`} (this build reads 1).`);if(t.status===`corrupt`){let e=t.issues.slice(0,5),n=e.map(e=>`${e.path===``?`(root)`:e.path}: ${e.message}`).join(`; `),r=t.issues.length>e.length?` (+${t.issues.length-e.length} more)`:``;throw Error(`Invalid session artifact: ${n}${r}`)}return t.record}const Fn=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function In(e){return Fn.test(e)}function Ln(e,t,n){if(e!==void 0&&In(e))return n;if(Array.isArray(t))return t.map(e=>Ln(void 0,e,n));if(typeof t==`object`&&t&&!(t instanceof Date)){let e=t,r={};for(let[t,i]of Object.entries(e))r[t]=Ln(t,i,n);return r}return t}function Rn(e,t=`[REDACTED]`){return Ln(void 0,e,t)}const zn={sessionInit:`session_init`,sessionShutdown:`session_shutdown`,sessionShutdownStepError:`session_shutdown_step_error`,context:`context`,contextCompact:`context_compact`,error:`error`,historyMutation:`history_mutation`,providerRequest:`provider_request`,providerNativeRawPayload:`provider_native_raw_payload`,providerStreamRawDelta:`provider_stream_raw_delta`,providerResponseRaw:`provider_response_raw`,providerResponseNormalized:`provider_response_normalized`,structuredOutputTransport:`structured_output_transport`,providerFallback:`provider_fallback`,assistantMessageCommitted:`assistant_message_committed`,toolExecutionRequest:`tool_execution_request`,toolExecutionResult:`tool_execution_result`,toolBatchStarted:`tool_batch_started`,toolMessageCommitted:`tool_message_committed`,backgroundTaskEvent:`background_task_event`,backgroundJobGroupEvent:`background_job_group_event`,memoryEvent:`memory_event`,user:`user`,preRun:`pre_run`,textDelta:`text_delta`,assistant:`assistant`,toolCall:`tool_call`,toolResult:`tool_result`,toolBlocked:`tool_blocked`,toolDenied:`tool_denied`,serverTool:`server_tool`};function Bn(e,t){return e.event===t}function Vn(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=Hn(e,a,o,n,r);return i}function Hn(e,t,n,r,i){if(In(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return Un(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return Un(e,n.map(n=>Hn(e,t,n,r,i)),r,i);if(typeof n==`object`){let t=n,a={};for(let[n,o]of Object.entries(t))a[n]=Hn(e,n,o,r,i);return Un(e,a,r,i)}return String(n)}function Un(e,t,r,i){let a=JSON.stringify(t);if(a===void 0||Buffer.byteLength(a)<=r.externalPayloadThresholdBytes||i===void 0)return t;let o=(0,n.createHash)(`sha256`).update(a).digest(`hex`);return i.writeJson(e,o,a)}const Wn=(0,e.createLogger)(`FileSessionLogger`),Gn=new Set([`text_delta`]),G=new Set;let Kn=!1;function qn(e){G.add(e),!Kn&&(typeof process>`u`||typeof process.on!=`function`||(Kn=!0,process.on(`exit`,()=>{for(let e of G)e.flush()})))}var Jn=class{sink;options;pending=new Map;pendingBytes=0;constructor(e,t={}){this.sink=e,this.options={externalPayloadThresholdBytes:t.externalPayloadThresholdBytes??32768,redactedValue:t.redactedValue??`[REDACTED]`}}log(e,t,n){if(Le(e))try{let r=Vn(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
7
+ `;if(Gn.has(t)){this.buffer(e,i);return}this.flush(),this.write(e,i)}catch(n){this.report(e,t,n)}}flush(){if(this.pending.size===0){G.delete(this);return}let e=[...this.pending.entries()];this.pending.clear(),this.pendingBytes=0,G.delete(this);for(let[t,n]of e)try{this.write(t,n.join(``))}catch(e){this.report(t,`flush`,e)}}buffer(e,t){qn(this);let n=this.pending.get(e)??[];n.push(t),this.pending.set(e,n),this.pendingBytes+=t.length,this.pendingBytes>=65536&&this.flush()}write(e,t){this.sink.append(e,t)}report(e,t,n){Wn.warn(`session log write failed`,{sessionId:e,event:t,error:n instanceof Error?n.message:String(n)})}},Yn=class{log(){}};const Xn=(0,e.createLogger)(`NodeSessionLogSink`),Zn=/^[0-9a-f]{64}$/;function Qn(e,t){let r=(0,n.createHash)(`sha256`).update(t).digest(`hex`);if(!Zn.test(e)||e!==r)throw Error(`Invalid sha256: external JSON payloads require their exact content digest.`)}function $n(e,n,r){return S(e),Qn(n,r),{kind:`external-payload`,encoding:`json`,sha256:n,byteLength:Buffer.byteLength(r),relativePath:(0,t.join)(`${e}.payloads`,`${n}.json`)}}var er=class{logDirectory;externalPayloadSink=this;enabled;constructor(e){this.logDirectory=e;try{(0,a.ensureOwnerOnlyDirectory)(e),this.enabled=!0}catch(t){this.enabled=!1,Xn.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(e,n){if(S(e),!this.enabled)return;let r=(0,t.join)(this.logDirectory,`${e}.jsonl`);(0,a.tightenExistingFile)(r),(0,i.appendFileSync)(r,n,{mode:a.OWNER_ONLY_FILE_MODE})}writeJson(e,n,r){let o=$n(e,n,r),s=`${e}.payloads`;if(this.enabled){(0,a.ensureOwnerOnlyDirectory)((0,t.join)(this.logDirectory,s));let e=(0,t.join)(this.logDirectory,o.relativePath);try{(0,i.writeFileSync)(e,r,{encoding:`utf8`,mode:a.OWNER_ONLY_FILE_MODE,flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;(0,a.tightenExistingFile)(e)}}return o}};const K=e=>({decode:e}),q=e=>({decode:e,optional:!0}),tr=(e,t,n)=>I(e,t,n,A),nr=(e,t,n)=>I(e,t,n,V),rr=(e,t,n)=>I(e,t,n,En),ir=(e,t,n)=>typeof e==`string`?e:V(e,t,n),J=(e,t,n)=>{let r=M(e,t,n);return r!==void 0&&r<0&&n.push({path:t,message:`expected a non-negative integer`}),r};function ar(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Y(e,t,n){if(!ar(e)){n.push({path:t,message:`expected an object, received ${D(e)}`});return}for(let[r,i]of Object.entries(e))X(i,w(t,r),n);return e}const or=[`maxTokens`,`usedTokens`,`usedPercentage`,`remainingPercentage`];function sr(e,t,n){let r=L(e,t,n,or);if(r===void 0)return;let i=j(r.maxTokens,w(t,`maxTokens`),n),a=j(r.usedTokens,w(t,`usedTokens`),n),o=j(r.usedPercentage,w(t,`usedPercentage`),n),s=j(r.remainingPercentage,w(t,`remainingPercentage`),n);if(i!==void 0&&a!==void 0&&o!==void 0&&s!==void 0)return{maxTokens:i,usedTokens:a,usedPercentage:o,remainingPercentage:s}}const cr=(e,t,n)=>I(e,t,n,(e,t,n)=>{let r=L(e,t,n,[`type`,`id`]);if(r===void 0)return;let i=A(r.type,w(t,`type`),n),a=A(r.id,w(t,`id`),n);return i===void 0||a===void 0?void 0:{type:i,id:a}});function X(e,t,n,r=new WeakSet){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||e instanceof Date){n.push({path:t,message:`expected a JSON-compatible value, received ${D(e)}`});return}if(!Array.isArray(e)&&!ar(e)){n.push({path:t,message:`expected a JSON-compatible object, received ${D(e)}`});return}if(r.has(e)){n.push({path:t,message:`expected an acyclic JSON-compatible value`});return}if(r.add(e),Array.isArray(e))for(let i=0;i<e.length;i++)X(e[i],T(t,i),n,r);else for(let[i,a]of Object.entries(e))X(a,w(t,i),n,r);return r.delete(e),e}function lr(e,t,n,r=new WeakSet){if(!(typeof e!=`object`||!e||e instanceof Date)){if(r.has(e)){n.push({path:t,message:`expected an acyclic value`});return}if(r.add(e),Array.isArray(e))for(let i=0;i<e.length;i++)Object.hasOwn(e,i)?lr(e[i],T(t,i),n,r):n.push({path:T(t,i),message:`expected an array element, received nothing`});else for(let[i,a]of Object.entries(e))lr(a,w(t,i),n,r);r.delete(e)}}const Z=(...e)=>(t,n,r)=>P(t,e,n,r),ur={session_init:{cwd:K(A),systemPromptLength:K(J),systemPrompt:K(A),toolSchemas:K(rr),model:K(A),provider:K(A)},session_shutdown:{reason:K(A)},session_shutdown_step_error:{step:K(A),error:K(A)},context:{maxTokens:K(j),usedTokens:K(j),usedPercentage:K(j),remainingPercentage:K(j)},context_compact:{trigger:K(A),before:K(sr),after:K(sr)},error:{message:K(A),stack:K(A),historyLength:K(J)},history_mutation:{executionId:q(A),conversationId:q(A),round:q(J),batchId:q(A),usageObservationId:q(A),providerId:q(A),modelId:q(A),providerError:q(N),contextOverflow:q(N),mutation:K(Z(`append_message`)),index:K(J),message:K(V)},provider_request:{executionId:K(A),conversationId:q(A),round:K(J),provider:K(A),model:K(A),effort:q(A),forcedSummary:q(N),messages:K(nr),tools:q(rr)},provider_native_raw_payload:{executionId:K(A),conversationId:q(A),round:K(J),provider:K(A),apiSurface:q(A),payloadKind:K(Z(`request`,`response`,`stream_event`)),sequence:K(J),payload:q(X),metadata:q(Y)},provider_stream_raw_delta:{executionId:K(A),conversationId:q(A),round:K(J),sequence:K(J),delta:K(A)},provider_response_raw:{executionId:K(A),conversationId:q(A),round:K(J),effort:q(A),response:K(V),responseKind:K(A)},provider_response_normalized:{executionId:K(A),conversationId:q(A),round:K(J),response:K(V),toolCallsCount:q(J)},structured_output_transport:{executionId:K(A),conversationId:q(A),round:K(J),provider:K(A),model:K(A),mechanism:K(Z(`response_schema`,`json_object`,`none`)),provenance:K(Z(`catalog`,`vendor-default`,`undeclared`,`unverified-endpoint`)),sent:K(N),schemaInPrompt:K(N),reason:q(A)},provider_fallback:{executionId:K(A),conversationId:q(A),round:K(J),fromProvider:K(A),fromModel:K(A),toProvider:K(A),toModel:K(A),reason:K(A)},assistant_message_committed:{executionId:K(A),conversationId:q(A),round:K(J),message:K(ir)},tool_execution_request:{executionId:K(A),conversationId:q(A),round:K(J),batchId:q(A),index:q(J),toolName:K(A),toolCallId:K(A),parameters:K(Y),ownerPath:q(cr)},tool_execution_result:{executionId:K(A),conversationId:q(A),round:K(J),batchId:q(A),index:q(J),toolName:q(A),toolCallId:q(A),success:K(N),result:q(X),error:q(A),metadata:q(Y)},tool_batch_started:{executionId:K(A),conversationId:q(A),round:K(J),batchId:q(A),mode:K(Z(`parallel`,`sequential`)),maxConcurrency:K(J),requestCount:K(J),tools:K(tr)},tool_message_committed:{executionId:K(A),conversationId:q(A),round:K(J),batchId:q(A),index:q(J),message:K(V)},background_task_event:{backgroundEventType:q(A),backgroundEvent:q(Jt),data:q(Jt),taskId:q(A),originToolCallId:q(A)},background_job_group_event:{backgroundJobGroupEvent:q(Mt),data:q(Mt)},memory_event:{memoryEvent:q(an),data:q(an)},user:{content:K(A)},pre_run:{historyLength:K(J),historyChars:K(J),historyEstTokens:K(J),input:K(A),history:K(nr),model:K(A),provider:K(A),maxTokens:K(j),nativeWebSearchSupported:K(N),nativeWebSearchEnabled:K(N),nativeWebFetchSupported:K(N),nativeWebFetchEnabled:K(N)},text_delta:{delta:K(A)},assistant:{content:K(A),historyLength:K(J),estimatedChars:K(J),history:K(nr),historyStructure:K((e,t,n)=>I(e,t,n,(e,t,n)=>{if(typeof e!=`object`||!e||Array.isArray(e)){n.push({path:t,message:`expected an object, received ${D(e)}`});return}let r=e;P(r.role,[`user`,`assistant`,`system`,`tool`],w(t,`role`),n),J(r.contentLength,w(t,`contentLength`),n),N(r.hasToolCalls,w(t,`hasToolCalls`),n),tr(r.toolCallNames,w(t,`toolCallNames`),n),r.metadata!==void 0&&Y(r.metadata,w(t,`metadata`),n);for(let e of Object.keys(r))[`role`,`contentLength`,`hasToolCalls`,`toolCallNames`,`metadata`].includes(e)||n.push({path:w(t,e),message:`unknown history structure field`});return r}))},tool_call:{tool:K(A),args:K(Y)},tool_result:{tool:K(A),success:K(N),dataChars:K(J),truncated:K(N)},tool_blocked:{tool:K(A),reason:K(A)},tool_denied:{tool:K(A),reason:K(A)},server_tool:{tool:K(A)}};var dr=class extends Error{code;issues;schemaVersion;constructor(e,t,n={}){super(`Session log decode failed: ${e}${t[0]?` at ${t[0].path}: ${t[0].message}`:``}`,{cause:n.cause}),this.name=`SessionLogDecodeError`,this.code=e,this.issues=t,n.schemaVersion!==void 0&&(this.schemaVersion=n.schemaVersion)}};const fr=new Set(Object.values(zn));function pr(e,t={}){if(!Array.isArray(e))throw new dr(`INVALID_EVENT`,[{path:`entries`,message:`expected an array, received ${D(e)}`}]);let n=[],r=[],i;for(let[a,o]of e.entries()){let e=mr(o,t.lineNumbers?.[a]===void 0?`[${a}]`:`line ${t.lineNumbers[a]}`,n);e.entry!==void 0&&r.push(e.entry),i??=e.unsupported}if(n.length>0)throw new dr(i===void 0?`INVALID_EVENT`:`UNSUPPORTED_VERSION`,n,{schemaVersion:i});return r}function mr(e,t,n){if(!ar(e))return n.push({path:t,message:`expected an object, received ${D(e)}`}),{};let r=n.length;if(lr(e,t,n),n.length!==r)return{};let i=hr(e,t,n);return i.event===void 0?{unsupported:i.unsupported}:(gr(e,i.event,t,i.output,n),{entry:i.output,unsupported:i.unsupported})}function hr(e,t,n){let r={schemaVersion:1},i;if(e.schemaVersion!==1){let r=e.schemaVersion;typeof r==`number`&&Number.isSafeInteger(r)&&r>=0?(i=r,n.push({path:w(t,`schemaVersion`),message:`unsupported schema version`})):n.push({path:w(t,`schemaVersion`),message:`expected schema version 1, received ${D(r)}`})}let a=F(e.timestamp,w(t,`timestamp`),n);a!==void 0&&(r.timestamp=a);let o=A(e.sessionId,w(t,`sessionId`),n);o===``&&n.push({path:w(t,`sessionId`),message:`expected a non-empty session ID`}),o!==void 0&&(r.sessionId=o);let s=e.event;return typeof s!=`string`||!fr.has(s)?(n.push({path:w(t,`event`),message:`expected a declared event name, received ${D(s)}`}),{output:r,unsupported:i}):(r.event=s,{output:r,event:s,unsupported:i})}function gr(e,t,n,r,i){let a=ur[t];for(let[t,o]of Object.entries(a)){if(!Object.hasOwn(e,t)&&o.optional)continue;let a=o.decode(e[t],w(n,t),i);a!==void 0&&(r[t]=a)}for(let o of Object.keys(e)){if([`schemaVersion`,`timestamp`,`sessionId`,`event`,...Object.keys(a)].includes(o))continue;if(t!==`server_tool`){i.push({path:w(n,o),message:`unknown event payload field`});continue}let s=X(e[o],w(n,o),i);s!==void 0&&(r[o]=s)}_r(e,t,n,i)}function _r(e,t,n,r){t===`background_task_event`&&e.backgroundEvent===void 0&&e.data===void 0&&r.push({path:n,message:`expected a background task event payload`}),t===`background_job_group_event`&&e.backgroundJobGroupEvent===void 0&&e.data===void 0&&r.push({path:n,message:`expected a background job group event payload`}),t===`memory_event`&&e.memoryEvent===void 0&&e.data===void 0&&r.push({path:n,message:`expected a memory event payload`})}var Q=class extends Error{code;metadata;constructor(e,t,n={},r){super(t,r===void 0?void 0:{cause:r}),this.name=`SessionLogPayloadResolutionError`,this.code=e,this.metadata=n}};function vr(e){if(e.trim().length===0||e.includes(`\0`)||(0,t.isAbsolute)(e)||t.win32.isAbsolute(e))throw br(e);let n=e.split(/[\\/]+/u);if(n.some(e=>e===`.`||e===`..`))throw br(e);return n}function yr(e){if(!Number.isFinite(e)||!Number.isSafeInteger(e)||e<0)throw new Q(`INVALID_LIMIT`,`External-payload maxBytes must be a finite, non-negative safe integer.`,{actual:String(e)})}function br(e,t){return new Q(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function xr(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?br(t,e):e.code===`UNSUPPORTED_BACKEND`?new Q(`STABLE_PAYLOAD_READ_UNAVAILABLE`,`Stable root-relative external-payload reads are unavailable on this host.`,{relativePath:t},e):e.code===`OVER_BUDGET`?new Q(`MAX_TOTAL_BYTES_EXCEEDED`,`External payload exceeds the remaining byte budget of ${n}.`,{relativePath:t,expected:n},e):new Q(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${t}.`,{relativePath:t},e)}var Sr=class{baseDirectory;constructor(e){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=(0,t.resolve)(e)}readBytes(e,t){yr(t);let n=vr(e);try{let e=(0,o.createStableRootedFileReader)(this.baseDirectory);try{return e.readBytes(n,t)}finally{e.close()}}catch(n){throw n instanceof Q?n:n instanceof o.StableFileAuthorityError?xr(n,e,t):new Q(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},n)}}},Cr=class{logFile;externalPayloadSource;constructor(e){if(this.logFile=e,e.trim().length===0)throw Error(`Session log-file path must not be empty.`);this.externalPayloadSource=new Sr((0,t.dirname)(e))}readText(){return(0,i.existsSync)(this.logFile)?(0,i.readFileSync)(this.logFile,`utf8`):void 0}};const wr=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,Tr=8*1024*1024,Er=i.constants.O_WRONLY|i.constants.O_CREAT|i.constants.O_EXCL|(i.constants.O_NOFOLLOW??0);var $=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}},Dr=class{directory;retentionMs;now;onCleanupFailure;entries=new Map;expiryTimer;closed=!1;constructor(e={}){let n=e.parentDirectory??(0,r.tmpdir)();if(this.retentionMs=e.retentionMs??36e5,this.now=e.now??Date.now,this.onCleanupFailure=e.onCleanupFailure,!Number.isSafeInteger(this.retentionMs)||this.retentionMs<=0)throw new $(`invalid-options`);try{let e=(0,i.lstatSync)(n);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=(0,i.mkdtempSync)((0,t.join)(n,`agent-tool-results-`)),process.platform!==`win32`&&(0,i.chmodSync)(this.directory,448),this.assertRoot()}catch{throw new $(`unsafe-root`)}}assertRoot(){try{let e=(0,i.lstatSync)(this.directory);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe directory`);if(process.platform!==`win32`&&e.mode&63)throw Error(`directory is not owner-only`)}catch{throw new $(`unsafe-root`)}}scheduleExpiry(e=1){if(this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.closed||this.entries.size===0)return;let t=1/0;for(let e of this.entries.values())e.expiresAt<t&&(t=e.expiresAt);let n=Math.min(2147483647,Math.max(e,t-this.now()));this.expiryTimer=setTimeout(()=>{this.expiryTimer=void 0,this.cleanupExpired().catch(()=>{try{this.onCleanupFailure?this.onCleanupFailure(`cleanup-failed`):process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}catch{process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}this.scheduleExpiry(6e4)})},n),this.expiryTimer.unref?.()}async write(e){if(this.closed)throw new $(`closed`);if(await this.cleanupExpired(),this.assertRoot(),Buffer.byteLength(e,`utf8`)>Tr)throw new $(`write-failed`);let r=(0,n.randomBytes)(18).toString(`base64url`),a=`${(0,n.randomBytes)(18).toString(`base64url`)}.partial`,o=`${r}.txt`,s=(0,t.join)(this.directory,a),c=(0,t.join)(this.directory,o),l,u=!1;try{l=(0,i.openSync)(s,Er,384),(0,i.writeFileSync)(l,e,`utf8`),(0,i.fsyncSync)(l),(0,i.closeSync)(l),l=void 0,(0,i.linkSync)(s,c),u=!0,(0,i.unlinkSync)(s);let t=`tool-result:${r}`;return this.entries.set(t,{fileName:o,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:t}}catch{let e=!1;if(l!==void 0)try{(0,i.closeSync)(l)}catch{e=!0}try{(0,i.unlinkSync)(s)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(u)try{(0,i.unlinkSync)(c)}catch{e=!0}throw new $(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new $(`closed`);if(!wr.test(e))throw new $(`invalid-reference`);let t=this.entries.get(e);if(!t)throw new $(`missing`);if(this.now()>=t.expiresAt)throw this.removeEntry(e,t),this.scheduleExpiry(),new $(`expired`);this.assertRoot();try{let e=new Sr(this.directory).readBytes(t.fileName,Tr);if(e===void 0)throw new $(`missing`);return Buffer.from(e).toString(`utf8`)}catch(e){throw e instanceof $?e:new $(`read-failed`)}}removeEntry(e,n){this.assertRoot();try{(0,i.unlinkSync)((0,t.join)(this.directory,n.fileName)),this.entries.delete(e)}catch{throw new $(`cleanup-failed`)}}async cleanupExpired(){if(this.closed)throw new $(`closed`);for(let[e,t]of this.entries)this.now()>=t.expiresAt&&this.removeEntry(e,t);this.scheduleExpiry()}async shutdown(){if(!this.closed){this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0;for(let[e,t]of this.entries)this.removeEntry(e,t);this.assertRoot();try{if((0,i.readdirSync)(this.directory).length!==0)throw Error(`unexpected files`);(0,i.rmdirSync)(this.directory),this.closed=!0}catch{throw new $(`cleanup-failed`)}}}};function Or(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.at==`string`&&typeof t.sessionId==`string`&&typeof t.project==`string`&&typeof t.text==`string`}function kr(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(Or(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function Ar(e){let t=[],n=0;for(let r of e){if(r.length===0)continue;let e=kr(r);e===void 0?n+=1:t.push(e)}return{entries:t,skippedLines:n}}function jr(e){return e.code===`ENOENT`}var Mr=class{path;blockBytes;ownedRoot;constructor(e,t={}){this.path=e,this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){(0,a.ensureOwnerOnlyDirectory)((0,t.dirname)(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),(0,a.tightenExistingFile)(this.path),(0,i.appendFileSync)(this.path,`${JSON.stringify(e)}\n`,{mode:a.OWNER_ONLY_FILE_MODE})}async*read(e){let t;try{t=(0,i.openSync)(this.path,i.constants.O_RDONLY|(i.constants.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&jr(e))return;throw e}try{let n=(0,i.fstatSync)(t).size,r=Buffer.alloc(0);for(;n>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,n);n-=e;let a=Buffer.alloc(e),o=(0,i.readSync)(t,a,0,e,n),s=Buffer.concat([a.subarray(0,o),r]),c=n===0?-1:s.indexOf(10);r=c===-1&&n>0?s:s.subarray(0,c+1);let l=n===0?s:c===-1?Buffer.alloc(0):s.subarray(c+1);n>0&&c===-1||(yield Ar(l.toString(`utf8`).split(`
8
+ `).reverse()))}}finally{(0,i.closeSync)(t)}}};const Nr=/^[0-9a-f]{64}$/i;function Pr(e){if(!Fr(e))throw new Q(`INVALID_REFERENCE`,`External payload reference has an invalid shape.`);return{kind:`external-payload`,encoding:`json`,sha256:String(e.sha256).toLowerCase(),byteLength:Number(e.byteLength),relativePath:String(e.relativePath)}}function Fr(e){let t=Object.keys(e).sort(),n=[`byteLength`,`encoding`,`kind`,`relativePath`,`sha256`];return t.length===n.length&&t.every((e,t)=>e===n[t])&&e.kind===`external-payload`&&e.encoding===`json`&&typeof e.sha256==`string`&&Nr.test(e.sha256)&&typeof e.byteLength==`number`&&Number.isSafeInteger(e.byteLength)&&e.byteLength>=0&&typeof e.relativePath==`string`&&e.relativePath.trim().length>0}function Ir(e,t){return zr(e,Lr(t),0)}function Lr(e){let t=Rr(`maxDepth`,e.maxDepth??32),n=Rr(`maxTotalBytes`,e.maxTotalBytes??67108864);return{source:e.source,maxDepth:t,maxTotalBytes:n,totalBytes:0,activePayloadPaths:new Set,activeObjects:new WeakSet}}function Rr(e,t){if(!Number.isFinite(t)||!Number.isSafeInteger(t)||t<0)throw new Q(`INVALID_LIMIT`,`${e} must be a finite, non-negative safe integer.`,{actual:String(t)});return t}function zr(e,t,n){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`number`)throw Hr(`Non-finite numbers are not valid session-log JSON values.`);if(typeof e!=`object`)throw Hr(`Unsupported session-log JSON value type: ${typeof e}.`);if(t.activeObjects.has(e))throw new Q(`CIRCULAR_REFERENCE`,`Circular in-memory value encountered while resolving external payloads.`,{depth:n});if(Ur(e))return Br(e,t,n);if(Array.isArray(e)){t.activeObjects.add(e);try{return e.map(e=>zr(e,t,n))}finally{t.activeObjects.delete(e)}}if(!Wr(e))throw Hr(`Session-log payload objects must be plain JSON records.`);t.activeObjects.add(e);try{return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,zr(r,t,n)]))}finally{t.activeObjects.delete(e)}}function Br(e,t,n){let r=Pr(e);if(n>=t.maxDepth)throw new Q(`MAX_DEPTH_EXCEEDED`,`External-payload reference depth exceeds the configured maximum of ${t.maxDepth}.`,{relativePath:r.relativePath,depth:n});if(t.source===void 0)throw new Q(`UNRESOLVED_REFERENCE`,`An external session-log payload requires an explicit payload source.`,{relativePath:r.relativePath,depth:n});if(t.activePayloadPaths.has(r.relativePath))throw new Q(`CIRCULAR_REFERENCE`,`External payload ${r.relativePath} recursively references an active payload.`,{relativePath:r.relativePath,depth:n});let i=Vr(r,t);t.activePayloadPaths.add(r.relativePath);try{return zr(i,t,n+1)}finally{t.activePayloadPaths.delete(r.relativePath)}}function Vr(e,t){let r=t.maxTotalBytes-t.totalBytes,i=t.source?.readBytes(e.relativePath,r);if(i===void 0)throw new Q(`PAYLOAD_NOT_FOUND`,`External payload was not found: ${e.relativePath}.`,{relativePath:e.relativePath});let a=t.totalBytes+i.byteLength;if(!Number.isSafeInteger(a)||a>t.maxTotalBytes)throw new Q(`MAX_TOTAL_BYTES_EXCEEDED`,`External-payload bytes exceed the configured maximum of ${t.maxTotalBytes}.`,{expected:t.maxTotalBytes,actual:a});if(t.totalBytes=a,i.byteLength!==e.byteLength)throw new Q(`BYTE_LENGTH_MISMATCH`,`External payload byte length does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.byteLength,actual:i.byteLength});let o=(0,n.createHash)(`sha256`).update(i).digest(`hex`);if(o!==e.sha256)throw new Q(`SHA256_MISMATCH`,`External payload sha256 does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.sha256,actual:o});try{return JSON.parse(Buffer.from(i).toString(`utf8`))}catch(t){throw new Q(`INVALID_JSON`,`External payload is not valid JSON: ${e.relativePath}.`,{relativePath:e.relativePath},t)}}function Hr(e){return new Q(`INVALID_JSON`,e)}function Ur(e){return!Array.isArray(e)&&`kind`in e&&e.kind===`external-payload`}function Wr(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Gr(e){let t=[],n=Kr(),r=qr();return pr(e).forEach((e,i)=>{ti(e,i,t),Yr(e,i,t),Jr(n,e,i),Xr(r,e,i)}),Zr(n,t),Qr(r,t),{ok:t.length===0,issues:t}}function Kr(){return{requests:new Map,nativeRawPayloads:new Set,rawResponses:new Set,normalizedResponses:new Set}}function qr(){return{requests:new Map,results:new Set}}function Jr(e,t,n){let r=$r(t);r&&(t.event===`provider_request`&&e.requests.set(r.key,{executionId:r.executionId,round:r.round,index:n}),t.event===`provider_response_raw`&&e.rawResponses.add(r.key),t.event===`provider_native_raw_payload`&&(t.payloadKind===`response`||t.payloadKind===`stream_event`)&&e.nativeRawPayloads.add(r.key),t.event===`provider_response_normalized`&&!ni(t.response)&&e.normalizedResponses.add(r.key))}function Yr(e,t,n){ni(e.event===`history_mutation`?e.message:e.event===`provider_response_normalized`?e.response:void 0)&&n.push({code:`UNRESOLVED_REPLAY_PAYLOAD`,message:`Replay substrate ${e.event} contains an unresolved external payload.`,eventIndex:t,executionId:typeof e.executionId==`string`?e.executionId:void 0,round:typeof e.round==`number`?e.round:void 0})}function Xr(e,t,n){let r=ei(t);r&&(t.event===`tool_execution_request`&&e.requests.set(r.key,{executionId:r.executionId,toolCallId:r.toolCallId,index:n}),t.event===`tool_execution_result`&&e.results.add(r.key))}function Zr(e,t){for(let[n,r]of e.requests)e.nativeRawPayloads.has(n)||t.push({code:`PROVIDER_NATIVE_RAW_PAYLOAD_MISSING`,message:`Provider request ${n} has no provider-native raw response or stream payload event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.rawResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_RAW_MISSING`,message:`Provider request ${n} has no raw response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.normalizedResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_NORMALIZED_MISSING`,message:`Provider request ${n} has no normalized response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round})}function Qr(e,t){for(let[n,r]of e.requests)e.results.has(n)||t.push({code:`TOOL_RESULT_MISSING`,message:`Tool request ${n} has no terminal result event.`,eventIndex:r.index,executionId:r.executionId,toolCallId:r.toolCallId})}function $r(e){if(typeof e.executionId!=`string`)return;let t=typeof e.round==`number`?e.round:Number(e.round);if(Number.isFinite(t))return{key:`${e.executionId}:${t}`,executionId:e.executionId,round:t}}function ei(e){if(typeof e.executionId!=`string`)return;let t=typeof e.toolCallId==`string`?e.toolCallId:typeof e.toolExecutionId==`string`?e.toolExecutionId:void 0;if(t)return{key:`${e.executionId}:${t}`,executionId:e.executionId,toolCallId:t}}function ti(e,t,n){if(Array.isArray(e)){e.forEach(e=>ti(e,t,n));return}if(ri(e)){if(e.kind===`external-payload`){Fr(e)||n.push({code:`PAYLOAD_REFERENCE_INVALID`,message:`External payload reference is missing required replay fields.`,eventIndex:t});return}Object.values(e).forEach(e=>ti(e,t,n))}}function ni(e){return Array.isArray(e)?e.some(e=>ni(e)):ri(e)?e.kind===`external-payload`||Object.values(e).some(e=>ni(e)):!1}function ri(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ii(e,t={}){let n=e.readText(),r=[];return n!==void 0&&n.split(`
9
+ `).forEach((e,t)=>{if(e.trim().length!==0)try{r.push({value:JSON.parse(e),lineNumber:t+1})}catch(e){throw new dr(`INVALID_JSON`,[{path:`line ${t+1}`,message:`expected valid JSON`}],{cause:e})}}),pr(Ir(r.map(({value:e})=>e),{source:t.externalPayloadSource??e.externalPayloadSource,...t}),{lineNumbers:r.map(({lineNumber:e})=>e)})}function ai(t){let n=[],r=[],i={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},a,o,s,c;for(let l of pr(t))a??=l.sessionId,s??=l.timestamp,c=l.timestamp,l.event===`session_init`&&(o=typeof l.cwd==`string`?l.cwd:o),l.event===`history_mutation`&&l.mutation===`append_message`&&(n.push(l.message),r.push((0,e.messageToHistoryEntry)(l.message))),oi(l,i);return{sessionId:a,cwd:o,createdAt:s,updatedAt:c,messages:n,history:r,backgroundTaskEvents:i.backgroundTaskEvents,backgroundJobGroupEvents:i.backgroundJobGroupEvents,memoryEvents:i.memoryEvents}}function oi(e,t){if(e.event===`background_task_event`){ci(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){ci(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&ci(t.memoryEvents,e,`memoryEvent`,`data`)}function si(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function ci(e,t,n,r){let i=si(t,n)??si(t,r);i&&e.push(i)}function li(e){return e instanceof Error?e.message:`unknown error`}function ui(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=An(t);return n.status===`valid`?{status:`valid`,record:n.record}:n.status===`unsupported`?{status:`unsupported`,schemaVersion:n.schemaVersion}:{status:`corrupt`,issues:n.issues}}function di(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var fi=class{baseDir;ownedRoot;constructor(e,t){this.baseDir=e,this.ownedRoot=t}ensureDir(){(0,a.ensureOwnerOnlyDirectory)(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){S(e);let t=(0,c.resolve)(this.baseDir),n=(0,c.resolve)(t,`${e}.json`);if(!n.startsWith(t+c.sep))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e){this.ensureDir(),(0,a.writeOwnerOnlyFile)(this.filePath(e.id),JSON.stringify({schemaVersion:1,record:e},null,2))}load(e){let t=this.filePath(e);if(!(0,s.existsSync)(t))return{status:`missing`};let n;try{n=(0,s.readFileSync)(t,`utf-8`)}catch(e){return{status:`corrupt`,issues:[{path:``,message:`could not read the session file: ${li(e)}`}]}}return ui(n)}list(){return(0,s.existsSync)(this.baseDir)?(0,s.readdirSync)(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})).sort(di):[]}outcomeForListedId(e){return Le(e)?this.load(e):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){let t=this.filePath(e);(0,s.existsSync)(t)&&(0,s.unlinkSync)(t)}},pi=class e{nodes=new Map;children=new Map;activeId;static fromNodes(t,n){let r=new e;for(let e of t){if(r.nodes.has(e.id))throw Error(`CheckpointTree: duplicate node "${e.id}"`);r.nodes.set(e.id,e.parentId===void 0?{id:e.id}:{...e})}for(let e of t)if(e.parentId!==void 0){let t=r.children.get(e.parentId)??[];t.push(e.id),r.children.set(e.parentId,t)}return r.activeId=n,r}addCheckpoint(e){if(this.nodes.has(e))throw Error(`CheckpointTree: duplicate checkpoint id "${e}"`);let t=this.activeId;if(this.nodes.set(e,t===void 0?{id:e}:{id:e,parentId:t}),t!==void 0){let n=this.children.get(t)??[];n.push(e),this.children.set(t,n)}this.activeId=e}fork(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);return this.activeId=e,e}switch(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);this.activeId=e}activeLeaf(){return this.activeId}listBranches(){let e=[];for(let t of this.nodes.keys())(this.children.get(t)?.length??0)===0&&e.push(t);return e}ancestors(e){let t=[],n=e;for(;n!==void 0&&this.nodes.has(n);)t.push(n),n=this.nodes.get(n).parentId;return t}has(e){return this.nodes.has(e)}get size(){return this.nodes.size}};exports.AUTO_COMPACT_THRESHOLD=y,exports.AutoModeGate=oe,exports.CONSECUTIVE_BLOCK_LIMIT=3,exports.CheckpointTree=pi,exports.CompactionError=_,exports.CompactionOrchestrator=ee,exports.ContextWindowTracker=b,exports.DEFAULT_COMPACTION_PROMPT=v,exports.DEFAULT_PROMPT_HISTORY_BLOCK_BYTES=65536,exports.FileSessionLogger=Jn,exports.INTERACTIVE_SESSION_RECORD_KEYS=On,exports.NodeExternalPayloadSource=Sr,exports.NodePromptHistoryFile=Mr,exports.NodeSessionLogSink=er,exports.NodeSessionLogSource=Cr,exports.NodeSessionStore=fi,exports.NodeToolResultSpillStore=Dr,exports.PermissionEnforcer=De,exports.SENSITIVE_KEY_PATTERN=Fn,exports.SESSION_LOG_EVENT=zn,exports.SESSION_LOG_SCHEMA_VERSION=1,exports.SESSION_RECORD_ENVELOPE_VERSION=1,exports.Session=nt,exports.SessionBusyError=u,exports.SessionLogDecodeError=dr,exports.SessionLogPayloadResolutionError=Q,exports.SilentSessionLogger=Yn,exports.TOTAL_BLOCK_LIMIT=20,exports.ToolResultSpillError=$,exports.TurnClaim=d,exports.assertSafeSessionId=S,exports.consentScopeFor=le,exports.createSessionLogExternalPayloadReference=$n,exports.decodeInteractiveSessionRecord=kn,exports.decodeSessionLogEntries=pr,exports.decodeVersionedInteractiveSessionRecord=An,exports.deserializeSessionArtifact=Pn,exports.formatConversationEntries=g,exports.isSafeSessionId=Le,exports.isSensitiveKey=In,exports.isSessionLogEvent=Bn,exports.loadSessionLogEntries=ii,exports.parsePromptHistoryLine=kr,exports.replaySessionLogEntries=ai,exports.resolveSessionLogExternalPayloads=Ir,exports.scrubSensitiveKeys=Rn,exports.serializeSessionArtifact=Nn,exports.validateSessionReplayLogEntries=Gr;