@mxalbert/context-mode 2.0.4 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,14 +6,14 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "Claude Code plugins by Mert Koseoğlu",
9
- "version": "2.0.4"
9
+ "version": "2.0.5"
10
10
  },
11
11
  "plugins": [
12
12
  {
13
13
  "name": "context-mode",
14
14
  "source": "./",
15
15
  "description": "Claude Code MCP plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.",
16
- "version": "2.0.4",
16
+ "version": "2.0.5",
17
17
  "author": {
18
18
  "name": "Mert Koseoğlu"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-mode",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
4
  "description": "MCP server that saves 98% of your context window with session continuity. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and automatic state restore across compactions.",
5
5
  "author": {
6
6
  "name": "Mert Koseoğlu",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-mode",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
4
  "description": "MCP server that saves 98% of your context window with session continuity. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and automatic state restore across compactions.",
5
5
  "author": {
6
6
  "name": "Mert Koseoğlu",
@@ -3,7 +3,7 @@
3
3
  "name": "Context Mode",
4
4
  "kind": "tool",
5
5
  "description": "OpenClaw plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.",
6
- "version": "2.0.4",
6
+ "version": "2.0.5",
7
7
  "sandbox": {
8
8
  "mode": "permissive",
9
9
  "filesystem_access": "full",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mxalbert/context-mode",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
4
  "description": "OpenClaw plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.",
5
5
  "author": {
6
6
  "name": "Mert Koseoğlu",
@@ -10,7 +10,7 @@
10
10
  * entrypoint it supports. No `tui` marker is set (it would invalidate
11
11
  * server loading per the v2 migration guide).
12
12
  *
13
- * The v2 PluginContext surface is VERIFIED (opencode2 beta-19135 live probe
13
+ * The v2 PluginContext surface is VERIFIED (live probe
14
14
  * + docs at opencode.ai/v2/docs/build/plugins): ctx.tool.transform(editor)
15
15
  * registers native ctx_* tools (ToolEditor), ctx.tool.hook
16
16
  * ("execute.before"/"execute.after") bridges routing enforcement + capture,
@@ -10,7 +10,7 @@
10
10
  * entrypoint it supports. No `tui` marker is set (it would invalidate
11
11
  * server loading per the v2 migration guide).
12
12
  *
13
- * The v2 PluginContext surface is VERIFIED (opencode2 beta-19135 live probe
13
+ * The v2 PluginContext surface is VERIFIED (live probe
14
14
  * + docs at opencode.ai/v2/docs/build/plugins): ctx.tool.transform(editor)
15
15
  * registers native ctx_* tools (ToolEditor), ctx.tool.hook
16
16
  * ("execute.before"/"execute.after") bridges routing enforcement + capture,
@@ -1248,6 +1248,18 @@ async function registerEventBusV2(ctx, rt, handlers) {
1248
1248
  if (rt.closed)
1249
1249
  return Promise.resolve(); // torn down — silent no-op
1250
1250
  const ev = (raw ?? {});
1251
+ // OpenCode 2 publishes per-turn usage on `session.usage.updated`
1252
+ // ({ data: { sessionID, cost, tokens } }). Map it onto the shared v1
1253
+ // path so token/cost capture keeps working.
1254
+ if (ev.type === "session.usage.updated" && ev.data && typeof ev.data === "object") {
1255
+ const data = ev.data;
1256
+ return handlers.event({
1257
+ event: {
1258
+ type: "message.updated",
1259
+ properties: { info: { ...data, role: typeof data.role === "string" ? data.role : "assistant" } },
1260
+ },
1261
+ });
1262
+ }
1251
1263
  // Generic mapping: the shared handler filters by type and reads
1252
1264
  // properties defensively — a shape it does not understand is a no-op.
1253
1265
  return handlers.event({ event: { type: ev.type, properties: ev.properties ?? ev } });
@@ -1285,8 +1297,8 @@ async function registerEventBusV2(ctx, rt, handlers) {
1285
1297
  }
1286
1298
  /**
1287
1299
  * OPTIONAL: register the v2 permission "evaluate" hook — the surface that
1288
- * restores true ask/confirmation semantics on OpenCode v2 (verified against
1289
- * opencode2 beta-19135 live probe; see .research/opencode-v2-permission-hooks.md).
1300
+ * restores true ask/confirmation semantics on OpenCode v2 (verified via live
1301
+ * probe; see .research/opencode-v2-permission-hooks.md).
1290
1302
  *
1291
1303
  * The host asserts every core-tool action (shell, read, …) through its
1292
1304
  * permission system before execution and lets the hook MUTATE the decision
@@ -5,8 +5,8 @@
5
5
  * plugin.ts (which owns the shared v1 handlers, the v2 registration/
6
6
  * bridging functions, setupV2, and the hybrid activation guard):
7
7
  * - the host-client log types (shared by the v1 and v2 logging paths)
8
- * - the VERIFIED v2 setup-context surface types (opencode2 beta-19135
9
- * live probe + docs build/plugins)
8
+ * - the VERIFIED v2 setup-context surface types (live probe + docs
9
+ * build/plugins)
10
10
  * - the Zod → JSON-Schema converter feeding ToolInfo.input
11
11
  * - defensive field readers for the UNCONFIRMED v2 hook payload shapes
12
12
  *
@@ -32,7 +32,7 @@ export type PluginClient = {
32
32
  app: PluginClientApp;
33
33
  };
34
34
  /**
35
- * VERIFIED against opencode2 beta-19135 (live probe) + the v2 plugin docs
35
+ * VERIFIED against opencode 2 (live probe) + the v2 plugin docs
36
36
  * (opencode.ai/v2/docs/build/plugins):
37
37
  * ctx.tool { reload, transform, hook }
38
38
  * ctx.session { hook, create, get, prompt, interrupt, rename, context, … }
@@ -88,7 +88,7 @@ export type V2SetupContext = {
88
88
  }) => unknown;
89
89
  };
90
90
  /**
91
- * v2 permission domain (verified against opencode2 beta-19135 live probe:
91
+ * v2 permission domain (verified against opencode 2 live probe:
92
92
  * ctx.permission.hook("evaluate", cb) fires for every core-tool permission
93
93
  * assert with a MUTABLE event { action, resources, source?, effect, message? }
94
94
  * — hook mutations of effect/message win the decision). Optional: older v2
@@ -5,8 +5,8 @@
5
5
  * plugin.ts (which owns the shared v1 handlers, the v2 registration/
6
6
  * bridging functions, setupV2, and the hybrid activation guard):
7
7
  * - the host-client log types (shared by the v1 and v2 logging paths)
8
- * - the VERIFIED v2 setup-context surface types (opencode2 beta-19135
9
- * live probe + docs build/plugins)
8
+ * - the VERIFIED v2 setup-context surface types (live probe + docs
9
+ * build/plugins)
10
10
  * - the Zod → JSON-Schema converter feeding ToolInfo.input
11
11
  * - defensive field readers for the UNCONFIRMED v2 hook payload shapes
12
12
  *
@@ -2455,6 +2455,8 @@ const TOOL_NAME_NORMALIZE = {
2455
2455
  view: "Read",
2456
2456
  grep: "Grep",
2457
2457
  fetch: "WebFetch",
2458
+ read: "Read", // OpenCode 2 stable core tool name (lowercase)
2459
+ write: "Write", // OpenCode 2 stable core tool name (lowercase)
2458
2460
  // Codex CLI
2459
2461
  shell: "Bash",
2460
2462
  shell_command: "Bash",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-mode",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
4
  "description": "context-mode for Antigravity CLI (agy): sandboxed code execution, FTS5 knowledge base, and session capture. Saves your context window by keeping raw bytes out of the conversation.",
5
5
  "author": {
6
6
  "name": "Mert Koseoğlu",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "context-mode",
3
3
  "description": "context-mode for GitHub Copilot CLI: sandboxed code execution in 11 languages, an FTS5 knowledge base with BM25 ranking, and session capture. Saves your context window by keeping raw bytes out of the conversation.",
4
- "version": "2.0.4",
4
+ "version": "2.0.5",
5
5
  "keywords": [
6
6
  "mcp",
7
7
  "context-window",
@@ -1,3 +1,3 @@
1
1
  var O={"claude-opus-4-8":{input_per_mtok:5,output_per_mtok:25,cache_read_per_mtok:.5,cache_write_per_mtok:6.25,source:"https://platform.claude.com/docs/en/about-claude/pricing"},"claude-opus-4-7":{input_per_mtok:5,output_per_mtok:25,cache_read_per_mtok:.5,cache_write_per_mtok:6.25,source:"https://platform.claude.com/docs/en/about-claude/pricing"},"claude-opus-4-6":{input_per_mtok:5,output_per_mtok:25,cache_read_per_mtok:.5,cache_write_per_mtok:6.25,source:"https://platform.claude.com/docs/en/about-claude/pricing"},"claude-opus-4-5":{input_per_mtok:5,output_per_mtok:25,cache_read_per_mtok:.5,cache_write_per_mtok:6.25,source:"https://platform.claude.com/docs/en/about-claude/pricing"},"claude-sonnet-4-6":{input_per_mtok:3,output_per_mtok:15,cache_read_per_mtok:.3,cache_write_per_mtok:3.75,source:"https://platform.claude.com/docs/en/about-claude/pricing"},"claude-sonnet-4-5":{input_per_mtok:3,output_per_mtok:15,cache_read_per_mtok:.3,cache_write_per_mtok:3.75,source:"https://platform.claude.com/docs/en/about-claude/pricing"},"claude-haiku-4-5":{input_per_mtok:1,output_per_mtok:5,cache_read_per_mtok:.1,cache_write_per_mtok:1.25,source:"https://platform.claude.com/docs/en/about-claude/pricing"},"claude-3-7-sonnet":{input_per_mtok:3,output_per_mtok:15,cache_read_per_mtok:.3,cache_write_per_mtok:3.75,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"claude-3-5-haiku":{input_per_mtok:.8,output_per_mtok:4,cache_read_per_mtok:.08,cache_write_per_mtok:1,source:"https://platform.claude.com/docs/en/about-claude/pricing"},"claude-fable-5":{input_per_mtok:10,output_per_mtok:50,cache_read_per_mtok:1,cache_write_per_mtok:12.5,source:"https://platform.claude.com/docs/en/about-claude/pricing"},"gpt-5":{input_per_mtok:1.25,output_per_mtok:10,cache_read_per_mtok:.125,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"gpt-5-mini":{input_per_mtok:.25,output_per_mtok:2,cache_read_per_mtok:.025,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"gpt-5-nano":{input_per_mtok:.05,output_per_mtok:.4,cache_read_per_mtok:.005,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"gpt-5-codex":{input_per_mtok:1.25,output_per_mtok:10,cache_read_per_mtok:.125,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"gpt-4.1":{input_per_mtok:2,output_per_mtok:8,cache_read_per_mtok:.5,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"gpt-4.1-mini":{input_per_mtok:.4,output_per_mtok:1.6,cache_read_per_mtok:.1,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"gpt-4.1-nano":{input_per_mtok:.1,output_per_mtok:.4,cache_read_per_mtok:.025,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"gpt-4o":{input_per_mtok:2.5,output_per_mtok:10,cache_read_per_mtok:1.25,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"gpt-4o-mini":{input_per_mtok:.15,output_per_mtok:.6,cache_read_per_mtok:.075,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},o3:{input_per_mtok:2,output_per_mtok:8,cache_read_per_mtok:.5,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"o4-mini":{input_per_mtok:1.1,output_per_mtok:4.4,cache_read_per_mtok:.275,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"o3-mini":{input_per_mtok:1.1,output_per_mtok:4.4,cache_read_per_mtok:.55,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"codex-mini-latest":{input_per_mtok:1.5,output_per_mtok:6,cache_read_per_mtok:.375,cache_write_per_mtok:null,source:"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"},"gemini-2.5-pro":{input_per_mtok:1.25,output_per_mtok:10,cache_read_per_mtok:.125,cache_write_per_mtok:null,source:"https://ai.google.dev/gemini-api/docs/pricing"},"gemini-2.5-flash":{input_per_mtok:.3,output_per_mtok:2.5,cache_read_per_mtok:.03,cache_write_per_mtok:null,source:"https://ai.google.dev/gemini-api/docs/pricing"},"gemini-2.5-flash-lite":{input_per_mtok:.1,output_per_mtok:.4,cache_read_per_mtok:.01,cache_write_per_mtok:null,source:"https://ai.google.dev/gemini-api/docs/pricing"},"gemini-2.0-flash":{input_per_mtok:.1,output_per_mtok:.4,cache_read_per_mtok:.025,cache_write_per_mtok:null,source:"https://ai.google.dev/gemini-api/docs/pricing"},"gemini-2.0-flash-lite":{input_per_mtok:.075,output_per_mtok:.3,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://ai.google.dev/gemini-api/docs/pricing"},"gemini-3-pro-preview":{input_per_mtok:2,output_per_mtok:12,cache_read_per_mtok:.2,cache_write_per_mtok:null,source:"https://ai.google.dev/gemini-api/docs/pricing"},"gemini-3-flash-preview":{input_per_mtok:.5,output_per_mtok:3,cache_read_per_mtok:.05,cache_write_per_mtok:null,source:"https://ai.google.dev/gemini-api/docs/pricing"},"qwen3-coder":{input_per_mtok:1,output_per_mtok:5,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://www.alibabacloud.com/help/en/model-studio/models"},"qwen-max":{input_per_mtok:1.6,output_per_mtok:6.4,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://www.alibabacloud.com/help/en/model-studio/models"},"qwen-plus":{input_per_mtok:.4,output_per_mtok:1.2,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://www.alibabacloud.com/help/en/model-studio/models"},"qwen-turbo":{input_per_mtok:.05,output_per_mtok:.2,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://www.alibabacloud.com/help/en/model-studio/models"},"qwen3-max":{input_per_mtok:1.2,output_per_mtok:6,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://www.alibabacloud.com/help/en/model-studio/models"},"kimi-k2":{input_per_mtok:.6,output_per_mtok:2.5,cache_read_per_mtok:.15,cache_write_per_mtok:null,source:"https://platform.moonshot.ai/docs/pricing/chat"},"kimi-k2-turbo":{input_per_mtok:1.15,output_per_mtok:8,cache_read_per_mtok:.15,cache_write_per_mtok:null,source:"https://platform.moonshot.ai/docs/pricing/chat"},"moonshot-v1-8k":{input_per_mtok:.2,output_per_mtok:2,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://platform.moonshot.ai/docs/pricing"},"moonshot-v1-32k":{input_per_mtok:1,output_per_mtok:3,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://platform.moonshot.ai/docs/pricing"},"moonshot-v1-128k":{input_per_mtok:2,output_per_mtok:5,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://platform.moonshot.ai/docs/pricing"},"deepseek-v3":{input_per_mtok:.27,output_per_mtok:1.1,cache_read_per_mtok:.07,cache_write_per_mtok:0,source:"https://api-docs.deepseek.com/quick_start/pricing"},"deepseek-r1":{input_per_mtok:.55,output_per_mtok:2.19,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://api-docs.deepseek.com/quick_start/pricing"},"deepseek-chat":{input_per_mtok:.14,output_per_mtok:.28,cache_read_per_mtok:.0028,cache_write_per_mtok:null,source:"https://api-docs.deepseek.com/quick_start/pricing"},"deepseek-reasoner":{input_per_mtok:.14,output_per_mtok:.28,cache_read_per_mtok:.0028,cache_write_per_mtok:null,source:"https://api-docs.deepseek.com/quick_start/pricing"},"glm-4.6":{input_per_mtok:.6,output_per_mtok:2.2,cache_read_per_mtok:.11,cache_write_per_mtok:null,source:"https://docs.z.ai/guides/overview/pricing"},"glm-4-air":{input_per_mtok:.2,output_per_mtok:1.1,cache_read_per_mtok:.03,cache_write_per_mtok:null,source:"https://docs.z.ai/guides/overview/pricing"},"grok-4":{input_per_mtok:3,output_per_mtok:15,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://docs.x.ai/docs/pricing"},"grok-3":{input_per_mtok:3,output_per_mtok:15,cache_read_per_mtok:.75,cache_write_per_mtok:null,source:"https://docs.x.ai/docs/pricing"},"grok-code-fast-1":{input_per_mtok:.2,output_per_mtok:1.5,cache_read_per_mtok:.02,cache_write_per_mtok:null,source:"https://docs.x.ai/docs/pricing"},"grok-2":{input_per_mtok:2,output_per_mtok:10,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://docs.x.ai/docs/pricing"},"mistral-large-latest":{input_per_mtok:.5,output_per_mtok:1.5,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://mistral.ai/pricing"},"codestral-latest":{input_per_mtok:.3,output_per_mtok:.9,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://mistral.ai/pricing"},devstral:{input_per_mtok:.4,output_per_mtok:2,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://mistral.ai/pricing"},"mistral-medium":{input_per_mtok:.4,output_per_mtok:2,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://mistral.ai/pricing"},"llama-4-maverick":{input_per_mtok:.27,output_per_mtok:.85,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://www.together.ai/pricing"},"llama-4-scout":{input_per_mtok:.08,output_per_mtok:.3,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://www.together.ai/pricing"},"llama-3.3-70b":{input_per_mtok:.88,output_per_mtok:.88,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://www.together.ai/pricing"},"command-a":{input_per_mtok:2.5,output_per_mtok:10,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://cohere.com/pricing"},"command-r-plus":{input_per_mtok:2.5,output_per_mtok:10,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://cohere.com/pricing"},"amazon-nova-pro":{input_per_mtok:.8,output_per_mtok:3.2,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://aws.amazon.com/bedrock/pricing/"},"amazon-nova-lite":{input_per_mtok:.06,output_per_mtok:.24,cache_read_per_mtok:null,cache_write_per_mtok:null,source:"https://aws.amazon.com/bedrock/pricing/"}};function K(){let t=new Map,e=O;for(let o of Object.keys(e)){let n=e[o];n==null||typeof n!="object"||typeof n.input_per_mtok=="number"&&t.set(o,{input_per_mtok:n.input_per_mtok,output_per_mtok:typeof n.output_per_mtok=="number"?n.output_per_mtok:null,cache_read_per_mtok:typeof n.cache_read_per_mtok=="number"?n.cache_read_per_mtok:null,cache_write_per_mtok:typeof n.cache_write_per_mtok=="number"?n.cache_write_per_mtok:null})}return t}var T=K();function G(t){for(let e=0;e<t.length;e++)if(t.charCodeAt(e)===47)return e===0||e===t.length-1?null:t.slice(e+1);return null}function z(t){return t.trim().toLowerCase()}function I(t){if(typeof t!="string"||t.length===0)return null;let e=T.get(t);if(e)return e;let o=z(t),n=T.get(o);if(n)return n;let r=G(o);if(r){let s=T.get(r);if(s)return s}return null}function E(t,e,o){return t<=0?0:t*(typeof e=="number"?e:o)}function P(t,e){let o=typeof e.input_tokens=="number"?e.input_tokens:0,n=typeof e.output_tokens=="number"?e.output_tokens:0,r=typeof e.cache_read_tokens=="number"?e.cache_read_tokens:0,s=typeof e.cache_creation_tokens=="number"?e.cache_creation_tokens:0;if(o<=0&&n<=0&&r<=0&&s<=0)return null;let i=I(t);if(!i||typeof i.input_per_mtok!="number")return console.warn(`[pricing] no curated price for model id: ${t}`),null;let a=i.input_per_mtok;return(E(o,a,a)+E(n,i.output_per_mtok,a)+E(r,i.cache_read_per_mtok,a)+E(s,i.cache_write_per_mtok,a))/1e6}function x(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function L(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.type=="string"&&e.type!=="usage.record")return null;let o=e.usage;if(!o||typeof o!="object")return null;let n=o,r=x(n.inputOther),s=x(n.output),i=x(n.inputCacheRead),a=x(n.inputCacheCreation);return r<=0&&s<=0&&i<=0&&a<=0?null:{model_id:typeof e.model=="string"?e.model:"",input_tokens:r,output_tokens:s,cache_creation_tokens:a,cache_read_tokens:i,native_cost_usd:null}}function J(t,e){let o=V(e);if(typeof t!="string"||t.length===0)return{events:[],cursor:e??null};let n=[],r=t.split(`
2
2
  `);for(let u of r){let c=u.trim();if(c.length===0)continue;let l;try{l=JSON.parse(c)}catch{continue}if(!l||typeof l!="object"||l.type!=="usage.record")continue;let m=L(l);n.push(m??{model_id:"",input_tokens:0,output_tokens:0,cache_creation_tokens:0,cache_read_tokens:0,native_cost_usd:null})}let s=n.length;if(s===0)return{events:[],cursor:e??null};let i;o===null||o<=0?i=n:o>=s?o===s?i=[]:i=n.slice(s-1):i=n.slice(o);let a=new Map;for(let u of i){let c=a.get(u.model_id)??{input:0,output:0,cacheCreate:0,cacheRead:0};c.input+=u.input_tokens,c.output+=u.output_tokens,c.cacheCreate+=u.cache_creation_tokens,c.cacheRead+=u.cache_read_tokens,a.set(u.model_id,c)}let p=[];for(let[u,c]of a){let l=w({model_id:u,input_tokens:c.input,output_tokens:c.output,cache_creation_tokens:c.cacheCreate,cache_read_tokens:c.cacheRead});l&&p.push(l)}return{events:p,cursor:String(s)}}function V(t){if(typeof t!="string"||t.length===0)return null;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?null:e}function A(t){if(typeof t!="number"||!Number.isFinite(t))return 0;let e=Math.floor(t);return e>0?e:0}function N(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,o=e.usageMetadata;if(!o||typeof o!="object")return null;let n=o,r=A(n.promptTokenCount),s=A(n.candidatesTokenCount),i=A(n.thoughtsTokenCount),a=A(n.cachedContentTokenCount),p=s+i;return r<=0&&p<=0&&a<=0?null:{model_id:typeof e.model=="string"?e.model:"",input_tokens:r,output_tokens:p,cache_creation_tokens:0,cache_read_tokens:a,native_cost_usd:null}}function Q(t){return typeof t.id=="string"&&t.id.length>0?t.id:typeof t.messageId=="string"&&t.messageId.length>0?t.messageId:null}function X(t,e){let o=typeof e=="string"&&e.length>0?e:null;if(typeof t!="string"||t.length===0)return{events:[],cursor:o};let n=[],r=0;for(let u=0;u<=t.length;u++){if(u!==t.length&&t.charCodeAt(u)!==10)continue;let c=t.slice(r,u).trim();if(r=u+1,c.length===0)continue;let l;try{let m=JSON.parse(c);if(!m||typeof m!="object"||Array.isArray(m))continue;l=m}catch{continue}n.push({id:Q(l),counts:N(l)})}if(n.length===0)return{events:[],cursor:o};let s=o;for(let u=n.length-1;u>=0;u--)if(n[u].id!==null){s=n[u].id;break}let i;if(o===null)i=n;else{let u=-1;for(let c=0;c<n.length;c++)if(n[c].id===o){u=c;break}u>=0?i=n.slice(u+1):i=n.slice(n.length-1)}let a=new Map;for(let u of i){let c=u.counts;if(!c)continue;let l=a.get(c.model_id)??{input:0,output:0,cacheCreate:0,cacheRead:0};l.input+=c.input_tokens,l.output+=c.output_tokens,l.cacheCreate+=c.cache_creation_tokens,l.cacheRead+=c.cache_read_tokens,a.set(c.model_id,l)}let p=[];for(let[u,c]of a){let l=w({model_id:u,input_tokens:c.input,output_tokens:c.output,cache_creation_tokens:c.cacheCreate,cache_read_tokens:c.cacheRead});l&&p.push(l)}return{events:p,cursor:s}}function _(t){return t==null?"":String(t)}function B(t){return t==null?"":typeof t=="string"?t:JSON.stringify(t)}function v(t){let e=String(t.tool_response??""),o=String(t.tool_input?.command??"");if(e.startsWith("context-mode:")||o.startsWith('echo "context-mode:')||o.startsWith("echo 'context-mode:"))return!1;let n=t.tool_output?.isError===!0||t.tool_output?.is_error===!0;return t.tool_name==="Bash"&&/exit code [1-9]|error:|Error:|FAIL|failed/i.test(e)||n}function F(t){if(!t)return[];let e=[];for(let n of t.split(/\r?\n/)){if(n.startsWith("*** Add File: ")){e.push({path:n.slice(14).trim(),type:"file_write"});continue}if(n.startsWith("*** Update File: ")){e.push({path:n.slice(17).trim(),type:"file_edit"});continue}if(n.startsWith("*** Delete File: ")){e.push({path:n.slice(17).trim(),type:"file_edit"});continue}n.startsWith("*** Move to: ")&&e.push({path:n.slice(13).trim(),type:"file_edit"})}let o=new Set;return e.filter(n=>{if(!n.path)return!1;let r=`${n.type}:${n.path}`;return o.has(r)?!1:(o.add(r),!0)})}function M(t){return/(?:^|[/\\])\.claude[/\\]plans[/\\]/.test(t)}function Y(t){let{tool_name:e,tool_input:o,tool_response:n}=t,r=[];if(e==="Read"){let s=String(o.file_path??"");return(/(?:CLAUDE|AGENTS(?:\.override)?|GEMINI|QWEN|KIRO)\.md$/i.test(s)||/\/copilot-instructions\.md$/i.test(s)||/\/context-mode\.mdc$/i.test(s)||/\.claude[\\/]/i.test(s)||/[\\/]memor(?:y|ies)[\\/][^\\/]+\.md$/i.test(s))&&(r.push({type:"rule",category:"rule",data:_(s),priority:1}),n&&n.length>0&&r.push({type:"rule_content",category:"rule",data:_(n),priority:1})),r.push({type:"file_read",category:"file",data:_(s),priority:1}),r}if(e==="Edit"){let s=String(o.file_path??"");return r.push({type:"file_edit",category:"file",data:_(s),priority:1}),r}if(e==="NotebookEdit"){let s=String(o.notebook_path??"");return r.push({type:"file_edit",category:"file",data:_(s),priority:1}),r}if(e==="Write"){let s=String(o.file_path??"");return r.push({type:"file_write",category:"file",data:_(s),priority:1}),r}if(e==="apply_patch"){if(v(t))return[];let s=F(String(o.command??o.patch??""));for(let i of s)r.push({type:i.type,category:"file",data:_(i.path),priority:1});return r}if(e==="Glob"){let s=String(o.pattern??"");return r.push({type:"file_glob",category:"file",data:_(s),priority:3}),r}if(e==="Grep"){let s=String(o.pattern??""),i=String(o.path??"");return r.push({type:"file_search",category:"file",data:_(`${s} in ${i}`),priority:3}),r}return r}function Z(t){if(t.tool_name!=="Bash")return[];let o=String(t.tool_input.command??"").match(/\bcd\s+("([^"]+)"|'([^']+)'|(\S+))/);if(!o)return[];let n=o[2]??o[3]??o[4]??"";return[{type:"cwd",category:"cwd",data:_(n),priority:2}]}function tt(t){let{tool_response:e}=t,o=String(e??"");return v(t)?[{type:"error_tool",category:"error",data:_(o),priority:2}]:[]}var H=[{pattern:/\bgit\s+checkout\b/,operation:"branch"},{pattern:/\bgit\s+commit\b/,operation:"commit"},{pattern:/\bgit\s+merge\s+\S+/,operation:"merge"},{pattern:/\bgit\s+rebase\b/,operation:"rebase"},{pattern:/\bgit\s+stash\b/,operation:"stash"},{pattern:/\bgit\s+push\b/,operation:"push"},{pattern:/\bgit\s+pull\b/,operation:"pull"},{pattern:/\bgit\s+log\b/,operation:"log"},{pattern:/\bgit\s+diff\b/,operation:"diff"},{pattern:/\bgit\s+status\b/,operation:"status"},{pattern:/\bgit\s+branch\b/,operation:"branch"},{pattern:/\bgit\s+reset\b/,operation:"reset"},{pattern:/\bgit\s+add\b/,operation:"add"},{pattern:/\bgit\s+cherry-pick\b/,operation:"cherry-pick"},{pattern:/\bgit\s+tag\b/,operation:"tag"},{pattern:/\bgit\s+fetch\b/,operation:"fetch"},{pattern:/\bgit\s+clone\b/,operation:"clone"},{pattern:/\bgit\s+worktree\b/,operation:"worktree"}];function et(t){if(t.tool_name!=="Bash")return[];let e=String(t.tool_input.command??""),o=ot(e),n;if(o&&o.operation&&(n=H.find(s=>s.operation===o.operation)),n||(n=H.find(s=>s.pattern.test(e))),!n)return[];let r=[];if(o?.scopedDir&&r.push({type:"cwd",category:"cwd",data:_(o.scopedDir),priority:2}),n.operation==="commit"){let s=it(e);if(s)return r.push({type:"git_commit",category:"git",data:_(s),priority:2}),r}return r.push({type:"git",category:"git",data:_(n.operation),priority:2}),r}function nt(t){return typeof t!="string"||t.length===0?t:t==="~"?U():t.startsWith("~/")?U()+t.slice(1):t}function U(){try{return process.env.HOME||process.env.USERPROFILE||(process.env.HOMEDRIVE&&process.env.HOMEPATH?process.env.HOMEDRIVE+process.env.HOMEPATH:"")||"~"}catch{return"~"}}function ot(t){let e=W(t),o=0;for(;o<e.length&&rt(e[o]);)o++;for(;o<e.length&&e[o]!=="git"&&!e[o].endsWith("/git")&&st(e[o]);)o++;if(o>=e.length||e[o]!=="git"&&!e[o].endsWith("/git"))return null;o++;let n=null,r=null;for(;o<e.length;){let s=e[o];if(s==="-C"||s==="--directory"){n=e[o+1]??null,o+=2;continue}if(s.startsWith("--directory=")){n=s.slice(12),o++;continue}if(s.length>0&&s[0]==="-"){o++;continue}r=s;break}return n&&(n=nt(n)),{scopedDir:n,operation:r}}function rt(t){if(t.length===0)return!1;let e=!1;for(let o=0;o<t.length;o++){let n=t.charCodeAt(o);if(o===0){if(!(n>=65&&n<=90||n===95))return!1}else if(n===61){e=!0;break}else if(!(n>=65&&n<=90||n>=48&&n<=57||n===95))return!1}return e}function st(t){switch(t){case"sudo":case"doas":case"env":case"exec":case"time":return!0;default:return!1}}function W(t){let e=[],o=t.length,n=0;for(;n<o;){for(;n<o&&(t[n]===" "||t[n]===" ");)n++;if(n>=o)break;let r="";for(;n<o&&t[n]!==" "&&t[n]!==" ";){let s=t[n];if(s==='"'||s==="'"){let i=s;for(n++;n<o&&t[n]!==i;)t[n]==="\\"&&n+1<o?(r+=t[n+1],n+=2):(r+=t[n],n++);n<o&&n++}else s==="\\"&&n+1<o?(r+=t[n+1],n+=2):(r+=s,n++)}e.push(r)}return e}function it(t){let e=W(t),o="--message=";for(let n=0;n<e.length;n++){let r=e[n];if(r.length>o.length&&r.startsWith(o)){let s=r.slice(o.length);return s.length>0?s:null}if(r==="--message"){let s=e[n+1];return s&&s.length>0?s:null}if(r.length>=2&&r[0]==="-"&&r[1]!=="-"&&r[r.length-1]==="m"&&ct(r,1)){let s=e[n+1];return s&&s.length>0?s:null}}return null}function ct(t,e){if(e>=t.length)return!1;for(let o=e;o<t.length;o++){let n=t.charCodeAt(o);if(n<97||n>122)return!1}return!0}function ut(t){return new Set(["TodoWrite","TaskCreate","TaskUpdate"]).has(t.tool_name)?[{type:t.tool_name==="TaskUpdate"?"task_update":t.tool_name==="TaskCreate"?"task_create":"task",category:"task",data:_(JSON.stringify(t.tool_input)),priority:1}]:[]}function at(t){let e=2166136261;for(let o=0;o<t.length;o++)e^=t.charCodeAt(o),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}function pt(t){let e=t.tool_input.plan;if(typeof e=="string"&&e.length>0)return e;let o=t.tool_response;if(typeof o=="string"&&o.length>0)try{let n=JSON.parse(o);if(n&&typeof n=="object"&&typeof n.plan=="string")return n.plan}catch{}return null}function lt(t){if(t.tool_name==="EnterPlanMode")return[{type:"plan_enter",category:"plan",data:"entered plan mode",priority:2}];if(t.tool_name==="ExitPlanMode"){let e=[],o=t.tool_input.allowedPrompts,n=Array.isArray(o)&&o.length>0?`exited plan mode (allowed: ${B(o.map(i=>typeof i=="object"&&i!==null&&"prompt"in i?String(i.prompt):String(i)).join(", "))})`:"exited plan mode",r=pt(t);typeof r=="string"&&r.length>0&&(n+=` plan_bytes:${r.length} plan_hash:${at(r)}`),e.push({type:"plan_exit",category:"plan",data:_(n),priority:2});let s=String(t.tool_response??"").toLowerCase();return s.includes("approved")||s.includes("approve")?e.push({type:"plan_approved",category:"plan",data:"plan approved by user",priority:1}):(s.includes("rejected")||s.includes("decline")||s.includes("denied"))&&e.push({type:"plan_rejected",category:"plan",data:_(`plan rejected: ${t.tool_response??""}`),priority:2}),e}if(t.tool_name==="Write"||t.tool_name==="Edit"){let e=String(t.tool_input.file_path??"");if(M(e))return[{type:"plan_file_write",category:"plan",data:_(`plan file: ${e.split(/[/\\]/).pop()??e}`),priority:2}]}return t.tool_name==="apply_patch"?v(t)?[]:F(String(t.tool_input.command??t.tool_input.patch??"")).filter(o=>M(o.path)).map(o=>({type:"plan_file_write",category:"plan",data:_(`plan file: ${o.path.split(/[/\\]/).pop()??o.path}`),priority:2})):[]}var _t=[/\bsource\s+\S*activate\b/,/\bexport\s+\w+=/,/\bnvm\s+use\b/,/\bpyenv\s+(shell|local|global)\b/,/\bconda\s+activate\b/,/\brbenv\s+(shell|local|global)\b/,/\bnpm\s+install\b/,/\bnpm\s+ci\b/,/\bpip\s+install\b/,/\bbun\s+install\b/,/\byarn\s+(add|install)\b/,/\bpnpm\s+(add|install)\b/,/\bcargo\s+(install|add)\b/,/\bgo\s+(install|get)\b/,/\brustup\b/,/\basdf\b/,/\bvolta\b/,/\bdeno\s+install\b/];function mt(t){if(t.tool_name!=="Bash")return[];let e=String(t.tool_input.command??"");if(!_t.some(r=>r.test(e)))return[];let n=e.replace(/\bexport\s+(\w+)=\S*/g,"export $1=***");return[{type:"env",category:"env",data:_(n),priority:2}]}function dt(t){if(t.tool_name!=="Skill")return[];let e=String(t.tool_input.skill??"");return[{type:"skill",category:"skill",data:_(e),priority:2}]}function ht(t){if(!t.tool_response?.includes("Error")&&!t.tool_output?.isError)return[];let e=String(t.tool_response||""),o=[/not supported/i,/cannot/i,/does not support/i,/FAIL/i,/refused/i,/permission denied/i,/incompatible/i];for(let n of o){let r=e.match(n);if(r){let s=e.toLowerCase().indexOf(r[0].toLowerCase()),i=e.slice(Math.max(0,s-50),Math.min(e.length,s+200)).trim();return[{type:"constraint_discovered",category:"constraint",data:_(i),priority:2}]}}return[]}function ft(t){if(t.tool_name!=="Agent")return[];let e=_(String(t.tool_input.prompt??t.tool_input.description??"")),o=t.tool_response?_(String(t.tool_response)):"",n=o.length>0;return[{type:n?"subagent_completed":"subagent_launched",category:"subagent",data:_(n?`[completed] ${e} \u2192 ${o}`:`[launched] ${e}`),priority:n?2:3}]}function gt(t){let{tool_name:e,tool_input:o,tool_response:n}=t;if(!e.startsWith("mcp__"))return[];let r=e.split("__"),s=r[r.length-1]||e,i=Object.values(o).find(u=>typeof u=="string"),a=i?`: ${_(String(i))}`:"",p=n&&n.length>0?`
3
- response: ${_(n)}`:"";return[{type:"mcp",category:"mcp",data:_(`${s}${a}${p}`),priority:3}]}var kt=2048;function yt(t,e){if(Buffer.byteLength(t,"utf8")<=e)return{value:t,truncated:!1};let o=Buffer.from(t,"utf8"),n=e;for(;n>0&&(o[n]&192)===128;)n--;return{value:o.subarray(0,n).toString("utf8"),truncated:!0}}var bt=/(authorization|auth_token|access_token|refresh_token|bearer|token|secret|password|passwd|pwd|api[-_]?key|apikey|cookie|set-cookie|signature|private[-_]?key|client[-_]?secret|x[-_]?api[-_]?key)/i,wt="[REDACTED]";function j(t,e=new WeakSet){if(t==null||typeof t!="object")return t;if(e.has(t))return"[CIRCULAR]";e.add(t);let o;if(Array.isArray(t))o=t.map(n=>j(n,e));else{let n={};for(let[r,s]of Object.entries(t))bt.test(r)?n[r]=wt:n[r]=j(s,e);o=n}return e.delete(t),o}function St(t){let{tool_name:e,tool_input:o}=t;if(!e.startsWith("mcp__"))return[];let n=j(o??{}),r;try{r=JSON.stringify(n)}catch{r="{}"}let{value:s,truncated:i}=yt(r,kt),a=i?`{"tool_name":${JSON.stringify(e)},"params_raw":${JSON.stringify(s)},"truncated":true}`:`{"tool_name":${JSON.stringify(e)},"params":${s}}`,p={type:"mcp_tool_call",category:"mcp_tool_call",data:_(a),priority:4};if(vt(e)){let u=_(t.tool_response);u.length>0&&(p.bytes_retrieved=Buffer.byteLength(u,"utf8"))}return[p]}var Rt=["ctx_search","ctx_fetch_and_index"];function vt(t){for(let e of Rt)if(t.endsWith(e))return!0;return!1}function Et(t){if(t.tool_name!=="AskUserQuestion")return[];let e=t.tool_input.questions,o=Array.isArray(e)&&e.length>0?String(e[0].question??""):"",n=String(t.tool_response??""),r="";try{let p=JSON.parse(n)?.answers;if(p&&typeof p=="object"){let u=l=>typeof l=="string"?l:Array.isArray(l)?l.filter(m=>typeof m=="string").join(" | "):"",c=o?u(p[o]):"";c?r=c:r=Object.values(p).map(u).filter(m=>m.length>0).join(" | ")}}catch{}let s=_(r),i=o?`Q: ${_(o)} \u2192 A: ${s}`:`answer: ${s}`;return[{type:"decision_question",category:"decision",data:_(i),priority:2}]}function xt(t){if(t.tool_name!=="Agent")return[];if(!t.tool_response||t.tool_response.length===0)return[];let e=t.tool_response.length>500?t.tool_response.slice(0,500):t.tool_response;return[{type:"agent_finding",category:"agent-finding",data:_(e),priority:2}]}function At(t){let e=[B(t.tool_input),_(t.tool_response)].join(" ");if(e.length===0)return[];let o=new Set,n=e.match(/https?:\/\/[^\s)]+/g);if(n)for(let p of n)p=p.replace(/["'})\],;.]+$/,""),/localhost|127\.0\.0\.1/i.test(p)||o.add(p);let r=e.match(/(?<!\w)#(\d+)/g);if(r)for(let p of r)o.add(p);if(o.size===0)return[];let s,i=_(t.tool_response).match(/Fetched and indexed[^\(]*\(([\d.]+)\s*KB\)/i);if(i){let p=Number(i[1]);Number.isFinite(p)&&p>0&&(s=Math.round(p*1024))}let a={type:"external_ref",category:"external-ref",data:_(Array.from(o).join(", ")),priority:3};return s!==void 0&&(a.bytes_avoided=s),[a]}function Ct(t){if(t.tool_name==="EnterWorktree"){let e=String(t.tool_input.name??"unnamed");return[{type:"worktree",category:"env",data:_(`entered worktree: ${e}`),priority:2}]}if(t.tool_name==="ExitWorktree"){let e=!!t.tool_input.discard_changes;return[{type:"worktree_exit",category:"env",data:_(`exited worktree (discard_changes:${e})`),priority:2}]}return[]}function Tt(t){if(typeof t!="string"||t.length===0)return null;let e=t.indexOf("://");if(e<0)return null;let o=e+3;if(o>=t.length)return null;let n=t.length;for(let s=o;s<t.length;s++){let i=t.charCodeAt(s);if(i===47||i===63||i===35){n=s;break}}let r=t.slice(o,n);return r.length>0?r:null}function It(t){if(t.tool_name!=="WebFetch")return[];let e=t.tool_response;if(typeof e!="string"||e.length===0)return[];let o;try{o=JSON.parse(e)}catch{return[]}if(!o||typeof o!="object")return[];let n=o,r=[];if(typeof n.code=="number"&&r.push(`code:${n.code}`),typeof n.bytes=="number"&&r.push(`bytes:${n.bytes}`),typeof n.durationMs=="number"&&r.push(`durMs:${n.durationMs}`),typeof n.url=="string"){let s=Tt(n.url);s&&r.push(`host:${s}`)}return r.length===0?[]:[{type:"webfetch_metadata",category:"data",data:_(r.join(" ")),priority:3}]}function jt(t){if(t.tool_name!=="Bash")return[];let e=t.tool_response;if(typeof e!="string"||e.length===0)return[];let o;try{o=JSON.parse(e)}catch{return[]}if(!o||typeof o!="object")return[];let n=o;if(!(typeof n.interrupted=="boolean"||typeof n.stderr=="string"||typeof n.returnCodeInterpretation=="string"))return[];let s=[];return typeof n.interrupted=="boolean"&&s.push(`interrupted:${n.interrupted}`),typeof n.returnCodeInterpretation=="string"&&s.push(`rcInterp:${n.returnCodeInterpretation.slice(0,80)}`),typeof n.stderr=="string"&&s.push(`stderrBytes:${n.stderr.length}`),[{type:"bash_outcome",category:"data",data:_(s.join(" ")),priority:3}]}function $t(t){if(t.tool_name!=="Read")return[];let e=t.tool_response;if(typeof e!="string"||e.length===0)return[];let o;try{o=JSON.parse(e)}catch{return[]}if(!o||typeof o!="object")return[];let n=o,r=n.type;if(r!=="text"&&r!=="image")return[];let s=[`type:${r}`];if(r==="text")typeof n.numLines=="number"&&s.push(`lines:${n.numLines}`),typeof n.totalLines=="number"&&s.push(`totalLines:${n.totalLines}`),typeof n.startLine=="number"&&s.push(`start:${n.startLine}`);else{typeof n.originalSize=="number"&&s.push(`origSize:${n.originalSize}`);let i=n.dimensions;if(i&&typeof i=="object"){let a=i;typeof a.width=="number"&&typeof a.height=="number"&&s.push(`dims:${a.width}x${a.height}`)}}return[{type:"file_read_metadata",category:"data",data:_(s.join(" ")),priority:3}]}function Ot(t,e){let o=[t.tool_input?.model,t.model,e.model];for(let n of o)if(typeof n=="string"&&n.length>0)return n;return""}function Pt(t){for(let e=t.length-1;e>0;e--)if(t.charCodeAt(e)===45)return t.slice(0,e);return null}function Lt(t){let e=t;for(;e&&e.length>0;){if(I(e)!==null)return e;e=Pt(e)}return""}function Nt(t,e,o,n,r){let s=Lt(t);return P(s||t,{input_tokens:e,output_tokens:o,cache_creation_tokens:n,cache_read_tokens:r})}function Mt(t){let e=t.toFixed(6),o=e.length;for(;o>0&&e.charCodeAt(o-1)===48;)o--;return e=e.slice(0,o),e.length>0&&e.charCodeAt(e.length-1)===46&&(e+="0"),e}function Ht(t){if(t.tool_name!=="Task")return[];let e=t.tool_response;if(typeof e!="string"||e.length===0)return[];let o;try{o=JSON.parse(e)}catch{return[]}if(!o||typeof o!="object")return[];let n=o,r=n.usage&&typeof n.usage=="object"?n.usage:{};if(!(typeof n.totalTokens=="number"||typeof n.totalDurationMs=="number"||typeof r.input_tokens=="number"||typeof r.output_tokens=="number"||typeof r.service_tier=="string"))return[];let i=[];typeof n.totalTokens=="number"&&i.push(`totalTokens:${n.totalTokens}`),typeof n.totalDurationMs=="number"&&i.push(`totalDurMs:${n.totalDurationMs}`),typeof r.input_tokens=="number"&&i.push(`tokens_in:${r.input_tokens}`),typeof r.output_tokens=="number"&&i.push(`tokens_out:${r.output_tokens}`),typeof r.cache_creation_input_tokens=="number"&&i.push(`cache_create:${r.cache_creation_input_tokens}`),typeof r.cache_read_input_tokens=="number"&&i.push(`cache_read:${r.cache_read_input_tokens}`),typeof r.service_tier=="string"&&i.push(`tier:${r.service_tier.slice(0,32)}`);let a=Ot(t,n),p={type:"agent_usage",category:"cost",data:_(i.join(" ")),priority:2};return a.length>0&&(p.model_id=a),typeof r.input_tokens=="number"&&(p.input_tokens=r.input_tokens),typeof r.output_tokens=="number"&&(p.output_tokens=r.output_tokens),typeof r.cache_read_input_tokens=="number"&&(p.cache_read_tokens=r.cache_read_input_tokens),typeof r.cache_creation_input_tokens=="number"&&(p.cache_creation_tokens=r.cache_creation_input_tokens),p.usage_scope="task_cumulative",[p]}function Ee(t){if(!t||typeof t!="object")return null;let e=t,o=e.message,n=o&&typeof o=="object"?o:e;if(typeof n.role=="string"&&n.role!=="assistant")return null;let r=n.usage;if(!r||typeof r!="object")return null;let s=r,i=d=>typeof d=="number"&&Number.isFinite(d)&&d>0?d:0,a=i(s.input),p=i(s.output),u=i(s.cacheWrite),c=i(s.cacheRead);if(a<=0&&p<=0&&u<=0&&c<=0)return null;let l=null,m=s.cost;if(m&&typeof m=="object"){let d=m.total;typeof d=="number"&&Number.isFinite(d)&&(l=d)}return{model_id:typeof n.model=="string"?n.model:"",input_tokens:a,output_tokens:p,cache_creation_tokens:u,cache_read_tokens:c,native_cost_usd:l}}function xe(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.type=="string"&&e.type!=="model.usage")return null;let o=e.usage;if(!o||typeof o!="object")return null;let n=o,r=m=>typeof m=="number"&&Number.isFinite(m)&&m>0?m:0,s=r(n.input),i=r(n.output),a=r(n.cacheWrite),p=r(n.cacheRead);if(s<=0&&i<=0&&a<=0&&p<=0)return null;let u=e.costUsd,c=typeof u=="number"&&Number.isFinite(u)?u:null;return{model_id:typeof e.model=="string"?e.model:"",input_tokens:s,output_tokens:i,cache_creation_tokens:a,cache_read_tokens:p,native_cost_usd:c}}function Ae(t){if(!t||typeof t!="object")return null;let e=t,o=e.event&&typeof e.event=="object"?e.event:e,n=o.properties&&typeof o.properties=="object"?o.properties:o,r=n.info&&typeof n.info=="object"?n.info:e;if(typeof r.role=="string"&&r.role!=="assistant")return null;let s=r.tokens;if(!s||typeof s!="object")return null;let i=s,a=b=>typeof b=="number"&&Number.isFinite(b)&&b>0?b:0,p=i.cache,u=p&&typeof p=="object"?p:{},c=a(i.input),l=a(i.output),m=a(u.read),h=a(u.write);if(c<=0&&l<=0&&h<=0&&m<=0)return null;let d=r.cost,S=typeof d=="number"&&Number.isFinite(d)?d:null,y=typeof r.modelID=="string"?r.modelID:"",R=typeof r.providerID=="string"?r.providerID:"",f="";return y.length>0?f=R.length>0?`${R}/${y}`:y:typeof r.model=="string"&&(f=r.model),{model_id:f,input_tokens:c,output_tokens:l,cache_creation_tokens:h,cache_read_tokens:m,native_cost_usd:S}}function w(t){let{model_id:e,input_tokens:o,output_tokens:n,cache_creation_tokens:r,cache_read_tokens:s,native_cost_usd:i}=t;if(o<=0&&n<=0&&r<=0&&s<=0)return null;let a=[`tokens_in:${o}`,`tokens_out:${n}`];r>0&&a.push(`cache_create:${r}`),s>0&&a.push(`cache_read:${s}`);let p=typeof i=="number"&&Number.isFinite(i)?i:Nt(e,o,n,r,s);p!==null&&a.push(`cost_usd:${Mt(p)}`);let u={type:"agent_usage",category:"cost",data:_(a.join(" ")),priority:2};return e.length>0&&(u.model_id=e),u.input_tokens=o,u.output_tokens=n,s>0&&(u.cache_read_tokens=s),r>0&&(u.cache_creation_tokens=r),p!==null&&(u.cost_usd=p),u}function Ce(t){if(!t||typeof t!="object")return null;let e=t,o=e.llm_response;if(!o||typeof o!="object")return null;let n=o,r=n.usageMetadata;if(!r||typeof r!="object")return null;let s=r,i=y=>typeof y=="number"&&Number.isFinite(y)?y:0,a=i(s.promptTokenCount),p=i(s.candidatesTokenCount),u=i(s.thoughtsTokenCount),c=i(s.cachedContentTokenCount),l=p+u,m=e.llm_request,h=m&&typeof m=="object"&&typeof m.model=="string"?m.model:"",d=typeof n.modelVersion=="string"?n.modelVersion:"",S=d.length>0?d:h;return w({model_id:S,input_tokens:a,output_tokens:l,cache_creation_tokens:0,cache_read_tokens:c})}function Te(t){if(typeof t!="string"||t.length===0)return[];let e=new Map,o=0;for(let r=0;r<=t.length;r++){if(r!==t.length&&t.charCodeAt(r)!==10)continue;let s=t.slice(o,r).trim();if(o=r+1,s.length===0)continue;let i;try{let h=JSON.parse(s);if(!h||typeof h!="object")continue;i=h}catch{continue}if(i.type!=="assistant"||i.isSidechain===!0)continue;let a=i.message;if(!a||typeof a!="object")continue;let p=a,u=typeof p.model=="string"?p.model:"";if(u.length===0)continue;let c=p.usage;if(!c||typeof c!="object")continue;let l=c,m=e.get(u)??{input:0,output:0,cacheCreate:0,cacheRead:0};typeof l.input_tokens=="number"&&(m.input+=l.input_tokens),typeof l.output_tokens=="number"&&(m.output+=l.output_tokens),typeof l.cache_creation_input_tokens=="number"&&(m.cacheCreate+=l.cache_creation_input_tokens),typeof l.cache_read_input_tokens=="number"&&(m.cacheRead+=l.cache_read_input_tokens),e.set(u,m)}let n=[];for(let[r,s]of e){let i=w({model_id:r,input_tokens:s.input,output_tokens:s.output,cache_creation_tokens:s.cacheCreate,cache_read_tokens:s.cacheRead});i&&n.push(i)}return n}function Ie(t,e){let o=typeof e=="string"&&e.length>0?e:null;if(typeof t!="string"||t.length===0)return{events:[],cursor:o};let n=[],r=0;for(let c=0;c<=t.length;c++){if(c!==t.length&&t.charCodeAt(c)!==10)continue;let l=t.slice(r,c).trim();if(r=c+1,l.length===0)continue;let m;try{let b=JSON.parse(l);if(!b||typeof b!="object")continue;m=b}catch{continue}if(m.type!=="assistant"||m.isSidechain===!0)continue;let h=m.message;if(!h||typeof h!="object")continue;let d=h,S=typeof d.model=="string"?d.model:"";if(S.length===0)continue;let y=typeof m.uuid=="string"&&m.uuid.length>0?m.uuid:null,R=d.usage,f=R&&typeof R=="object"?R:{};n.push({uuid:y,model:S,input:typeof f.input_tokens=="number"?f.input_tokens:0,output:typeof f.output_tokens=="number"?f.output_tokens:0,cacheCreate:typeof f.cache_creation_input_tokens=="number"?f.cache_creation_input_tokens:0,cacheRead:typeof f.cache_read_input_tokens=="number"?f.cache_read_input_tokens:0})}if(n.length===0)return{events:[],cursor:o};let s=n[n.length-1].uuid,i=s!==null?s:o,a;if(o===null)a=n;else{let c=-1;for(let l=0;l<n.length;l++)if(n[l].uuid===o){c=l;break}c>=0?a=n.slice(c+1):a=n.slice(n.length-1)}let p=new Map;for(let c of a){let l=p.get(c.model)??{input:0,output:0,cacheCreate:0,cacheRead:0};l.input+=c.input,l.output+=c.output,l.cacheCreate+=c.cacheCreate,l.cacheRead+=c.cacheRead,p.set(c.model,l)}let u=[];for(let[c,l]of p){let m=w({model_id:c,input_tokens:l.input,output_tokens:l.output,cache_creation_tokens:l.cacheCreate,cache_read_tokens:l.cacheRead});m&&u.push(m)}return{events:u,cursor:i}}var D=/[,;,;、،]/u,Ut=15,Bt=500;function Ft(t){if(C.test(t)||!$.test(t)||!D.test(t))return!1;let e=[...t].length;return e>=Ut&&e<=Bt}function Wt(t){let e=t.trim();return Ft(e)?[{type:"decision",category:"decision",data:_(t),priority:2}]:[]}var Dt=8,qt=120,Kt=new RegExp("\\p{L}+\\s+\\p{L}+","u"),Gt=new RegExp("\\p{L}{6,}","u"),zt=new Set(["ok","okay","sure","yeah","yep","yup","alright","fine","well","so","hmm","right","please"]),Jt=["you are","you're","your role","you will be","you act","you will act","act as","act like","behave as","behave like","imagine you","pretend you","assume the role","take the role","play the role","respond as","tu es","tu est","vous etes","vous \xEAtes","sen ","siz ","eres ","t\xFA eres","usted es","\u0442\u044B ","\u0432\u044B ","\u3042\u306A\u305F\u306F","\u541B\u306F","\u304A\u524D\u306F","\u3042\u306A\u305F\u304C","\u4F60\u662F","\u60A8\u662F","\u0924\u0941\u092E ","\u0906\u092A ","\u0924\u0942 ","\u0623\u0646\u062A ","\u0627\u0646\u062A ","\u0623\u0646\u062A\u064E "],Vt=["always ","never ","respond ","reply ","answer ","speak ","write ","prefer ","format ","output ","communicate ","use only "];function Qt(t){let e=t.toLowerCase().trim();if(!e)return!1;let o=e.split(" ").filter(r=>r.length>0);for(;o.length>0&&zt.has(o[0]);)o.shift();let n=o.join(" ");if(!n)return!1;for(let r of Jt)if(n.startsWith(r))return!0;for(let r of Vt)if(n.startsWith(r))return!0;return!1}function Xt(t){let e=t.split(/[.!\n。!]/u)[0].trim();if(C.test(e)||D.test(e)||!$.test(e))return!1;let o=[...e].length;return o<Dt||o>qt||!Qt(e)?!1:Kt.test(e)||Gt.test(e)}function Yt(t){let e=t.trim();return Xt(e)?[{type:"role",category:"role",data:_(t),priority:3}]:[]}var C=/[??؟¿]/u,$=new RegExp("\\p{L}","u"),Zt=60;function te(t){if(C.test(t)||!$.test(t))return!1;let e=[...t].length;return e>0&&e<Zt}function ee(t){let e=t.trim();if(!e)return[];let o;return C.test(e)?o="investigate":te(e)&&(o="implement"),o?[{type:"intent",category:"intent",data:_(o),priority:4}]:[]}var ne=/^(?:\/goal\s+|(?:goal|objective)\s*:\s*)(.+)$/is;function oe(t){let e=t.trim();if(!e)return[];let o=e.match(ne);if(!o)return[];let n=o[1].trim();return n?[{type:"goal",category:"goal",data:_(n),priority:4}]:[]}var re=/(?:\bError\s*:|\bException\s*:|\bTraceback\b|\bat\s+\S+\s*\([^)]*:\d+:\d+\))/u,se=/[✓✔✅☑🎉]/u,ie=/^\s*(?:fixed|resolved)\s*:/iu;function ce(t){let e=[];return se.test(t)||ie.test(t)?(e.push({type:"blocker_resolved",category:"blocked-on",data:_(t),priority:2}),e):(re.test(t)&&e.push({type:"blocker",category:"blocked-on",data:_(t),priority:2}),e)}function ue(t){return t.length<=1024?[]:[{type:"data",category:"data",data:_(t),priority:4}]}var g=null;function ae(t){let{tool_name:e,tool_response:o}=t,n=String(o??"");if(v(t))return g={tool:e,error:n.slice(0,200),callsSince:0},[];if(!g)return[];if(g.callsSince++,g.callsSince>10)return g=null,[];if(!!v(t))return[];let s=e===g.tool,i=g.tool==="Read"&&(e==="Edit"||e==="Write"||e==="apply_patch");if(s||i){let a={type:"error_resolved",category:"error-resolution",data:_(`Error in ${g.tool}: ${g.error} \u2192 Fixed`),priority:2};return g=null,[a]}return[]}function je(){g=null}var k=[];function pe(t){return`${t.length}:${t.slice(0,20)}`}function le(t){let{tool_name:e,tool_input:o}=t,n=pe(JSON.stringify(o).slice(0,200));if(k.push({tool:e,inputHash:n}),k.length>50&&k.splice(0,k.length-50),k.length<3)return[];let r=0;for(let s=k.length-1;s>=0&&(k[s].tool===e&&k[s].inputHash===n);s--)r++;return r>=3?(k.splice(k.length-r),[{type:"retry_detected",category:"iteration-loop",data:_(`${e} called ${r} times with similar input`),priority:2}]):[]}function $e(){k.length=0}var _e={run_shell_command:"Bash",read_file:"Read",read_many_files:"Read",grep_search:"Grep",search_file_content:"Grep",web_fetch:"WebFetch",write_file:"Write",edit:"Edit",glob:"Glob",todo_write:"TodoWrite",ask_user_question:"AskUserQuestion",list_directory:"LS",save_memory:"Memory",skill:"Skill",exit_plan_mode:"ExitPlanMode",agent:"Agent",bash:"Bash",view:"Read",grep:"Grep",fetch:"WebFetch",shell:"Bash",shell_command:"Bash",exec_command:"Bash","container.exec":"Bash",local_shell:"Bash",grep_files:"Grep",run_command:"Bash",view_file:"Read",read_url_content:"WebFetch",list_dir:"LS",search_web:"WebSearch"};function me(t){let e=_e[t.tool_name];return!e||e===t.tool_name?t:{...t,tool_name:e}}function Oe(t){try{let e=me(t),o=[];return o.push(...Y(e)),o.push(...Z(e)),o.push(...tt(e)),o.push(...et(e)),o.push(...mt(e)),o.push(...ut(e)),o.push(...lt(e)),o.push(...dt(e)),o.push(...ft(e)),o.push(...gt(e)),o.push(...St(e)),o.push(...Et(e)),o.push(...ht(e)),o.push(...Ct(e)),o.push(...It(e)),o.push(...jt(e)),o.push(...$t(e)),o.push(...Ht(e)),o.push(...xt(e)),o.push(...At(e)),o.push(...ae(e)),o.push(...le(e)),o}catch{return[]}}function Pe(t){try{let e=[];return e.push(...fe(t)),e.push(...Wt(t)),e.push(...Yt(t)),e.push(...ee(t)),e.push(...oe(t)),e.push(...ce(t)),e.push(...ue(t)),e}catch{return[]}}function Le(t){if(!t||typeof t!="object")return[];let e=t,o=[],n=e.mcp_servers,r=null;return n&&typeof n=="object"&&!Array.isArray(n)&&(r=Object.keys(n),o.push(`mcp_count:${r.length}`),r.length>0&&o.push(`mcp_servers:${r.slice(0,8).join(",")}`)),typeof e.model=="string"&&o.push(`model:${e.model.slice(0,64)}`),typeof e.permission_mode=="string"&&o.push(`permission_mode:${e.permission_mode.slice(0,32)}`),o.length===0?[]:[{type:"session_settings_snapshot",category:"env",data:_(o.join(" ")),priority:2}]}var de=["Latin","Cyrillic","Arabic","Han","Hangul","Hiragana","Katakana","Devanagari","Hebrew","Thai","Greek"],he={prompt_length:0,prompt_word_count:0,prompt_uppercase_ratio:0,prompt_file_ref_count:0,prompt_path_ref_count:0,prompt_script_primary:null,prompt_script_count:0,prompt_question_glyph_count:0,prompt_code_block_count:0,prompt_url_count:0,prompt_word_tokens:[]};function Ne(t){if(typeof t!="string"||t.length===0)return{...he,prompt_word_tokens:[]};let e=t.match(new RegExp("\\p{L}+","gu"))??[],o=(t.match(new RegExp("\\p{Lu}","gu"))??[]).length,n=e.join("").length,r=(t.match(/```/g)??[]).length,s={};for(let u of de){let c=new RegExp(`\\p{Script=${u}}`,"gu"),l=(t.match(c)??[]).length;l>0&&(s[u]=l)}let i=Object.entries(s).sort((u,c)=>c[1]-u[1])[0]?.[0]??null,a=new Set,p=[];for(let u of e){if(u.length<3)continue;let c=u.toLowerCase();a.has(c)||(a.add(c),p.push(c))}return{prompt_length:t.length,prompt_word_count:e.length,prompt_uppercase_ratio:n===0?0:o/n,prompt_file_ref_count:(t.match(/(\w+\/)+\w+\.\w+/g)??[]).length,prompt_path_ref_count:(t.match(/\.{0,2}\/[\w\/.-]+/g)??[]).length,prompt_script_primary:i,prompt_script_count:Object.keys(s).length,prompt_question_glyph_count:(t.match(/[??؟]/gu)??[]).length,prompt_code_block_count:Math.floor(r/2),prompt_url_count:(t.match(/https?:\/\/[^\s]+/gu)??[]).length,prompt_word_tokens:p}}function fe(t){if(typeof t!="string"||t.length===0)return[];let e=0;for(;e<t.length;){let r=t.charCodeAt(e);if(r!==32&&r!==9)break;e++}if(e+5>t.length)return[];if(t.slice(e,e+5)!=="/plan")return[];if(e+5<t.length){let r=t.charCodeAt(e+5);if(!(r===32||r===9||r===10||r===13))return[]}let o=t.slice(e+5).trim(),n=o.length>0?`plan via /plan slash: ${o.slice(0,120)}`:"plan via /plan slash";return[{type:"plan_enter",category:"plan",data:_(n),priority:2}]}export{w as buildAgentUsageEvent,Oe as extractEvents,J as extractKimiUsageSince,X as extractQwenUsageSince,Le as extractSessionSettings,Te as extractTranscriptUsage,Ie as extractTranscriptUsageSince,Pe as extractUserEvents,Ne as extractUserPromptFeatures,Ce as parseGeminiUsage,L as parseKimiUsage,xe as parseOpenclawUsage,Ae as parseOpencodeUsage,Ee as parsePiUsage,N as parseQwenUsage,je as resetErrorResolutionState,$e as resetIterationLoopState};
3
+ response: ${_(n)}`:"";return[{type:"mcp",category:"mcp",data:_(`${s}${a}${p}`),priority:3}]}var kt=2048;function yt(t,e){if(Buffer.byteLength(t,"utf8")<=e)return{value:t,truncated:!1};let o=Buffer.from(t,"utf8"),n=e;for(;n>0&&(o[n]&192)===128;)n--;return{value:o.subarray(0,n).toString("utf8"),truncated:!0}}var bt=/(authorization|auth_token|access_token|refresh_token|bearer|token|secret|password|passwd|pwd|api[-_]?key|apikey|cookie|set-cookie|signature|private[-_]?key|client[-_]?secret|x[-_]?api[-_]?key)/i,wt="[REDACTED]";function j(t,e=new WeakSet){if(t==null||typeof t!="object")return t;if(e.has(t))return"[CIRCULAR]";e.add(t);let o;if(Array.isArray(t))o=t.map(n=>j(n,e));else{let n={};for(let[r,s]of Object.entries(t))bt.test(r)?n[r]=wt:n[r]=j(s,e);o=n}return e.delete(t),o}function St(t){let{tool_name:e,tool_input:o}=t;if(!e.startsWith("mcp__"))return[];let n=j(o??{}),r;try{r=JSON.stringify(n)}catch{r="{}"}let{value:s,truncated:i}=yt(r,kt),a=i?`{"tool_name":${JSON.stringify(e)},"params_raw":${JSON.stringify(s)},"truncated":true}`:`{"tool_name":${JSON.stringify(e)},"params":${s}}`,p={type:"mcp_tool_call",category:"mcp_tool_call",data:_(a),priority:4};if(vt(e)){let u=_(t.tool_response);u.length>0&&(p.bytes_retrieved=Buffer.byteLength(u,"utf8"))}return[p]}var Rt=["ctx_search","ctx_fetch_and_index"];function vt(t){for(let e of Rt)if(t.endsWith(e))return!0;return!1}function Et(t){if(t.tool_name!=="AskUserQuestion")return[];let e=t.tool_input.questions,o=Array.isArray(e)&&e.length>0?String(e[0].question??""):"",n=String(t.tool_response??""),r="";try{let p=JSON.parse(n)?.answers;if(p&&typeof p=="object"){let u=l=>typeof l=="string"?l:Array.isArray(l)?l.filter(m=>typeof m=="string").join(" | "):"",c=o?u(p[o]):"";c?r=c:r=Object.values(p).map(u).filter(m=>m.length>0).join(" | ")}}catch{}let s=_(r),i=o?`Q: ${_(o)} \u2192 A: ${s}`:`answer: ${s}`;return[{type:"decision_question",category:"decision",data:_(i),priority:2}]}function xt(t){if(t.tool_name!=="Agent")return[];if(!t.tool_response||t.tool_response.length===0)return[];let e=t.tool_response.length>500?t.tool_response.slice(0,500):t.tool_response;return[{type:"agent_finding",category:"agent-finding",data:_(e),priority:2}]}function At(t){let e=[B(t.tool_input),_(t.tool_response)].join(" ");if(e.length===0)return[];let o=new Set,n=e.match(/https?:\/\/[^\s)]+/g);if(n)for(let p of n)p=p.replace(/["'})\],;.]+$/,""),/localhost|127\.0\.0\.1/i.test(p)||o.add(p);let r=e.match(/(?<!\w)#(\d+)/g);if(r)for(let p of r)o.add(p);if(o.size===0)return[];let s,i=_(t.tool_response).match(/Fetched and indexed[^\(]*\(([\d.]+)\s*KB\)/i);if(i){let p=Number(i[1]);Number.isFinite(p)&&p>0&&(s=Math.round(p*1024))}let a={type:"external_ref",category:"external-ref",data:_(Array.from(o).join(", ")),priority:3};return s!==void 0&&(a.bytes_avoided=s),[a]}function Ct(t){if(t.tool_name==="EnterWorktree"){let e=String(t.tool_input.name??"unnamed");return[{type:"worktree",category:"env",data:_(`entered worktree: ${e}`),priority:2}]}if(t.tool_name==="ExitWorktree"){let e=!!t.tool_input.discard_changes;return[{type:"worktree_exit",category:"env",data:_(`exited worktree (discard_changes:${e})`),priority:2}]}return[]}function Tt(t){if(typeof t!="string"||t.length===0)return null;let e=t.indexOf("://");if(e<0)return null;let o=e+3;if(o>=t.length)return null;let n=t.length;for(let s=o;s<t.length;s++){let i=t.charCodeAt(s);if(i===47||i===63||i===35){n=s;break}}let r=t.slice(o,n);return r.length>0?r:null}function It(t){if(t.tool_name!=="WebFetch")return[];let e=t.tool_response;if(typeof e!="string"||e.length===0)return[];let o;try{o=JSON.parse(e)}catch{return[]}if(!o||typeof o!="object")return[];let n=o,r=[];if(typeof n.code=="number"&&r.push(`code:${n.code}`),typeof n.bytes=="number"&&r.push(`bytes:${n.bytes}`),typeof n.durationMs=="number"&&r.push(`durMs:${n.durationMs}`),typeof n.url=="string"){let s=Tt(n.url);s&&r.push(`host:${s}`)}return r.length===0?[]:[{type:"webfetch_metadata",category:"data",data:_(r.join(" ")),priority:3}]}function jt(t){if(t.tool_name!=="Bash")return[];let e=t.tool_response;if(typeof e!="string"||e.length===0)return[];let o;try{o=JSON.parse(e)}catch{return[]}if(!o||typeof o!="object")return[];let n=o;if(!(typeof n.interrupted=="boolean"||typeof n.stderr=="string"||typeof n.returnCodeInterpretation=="string"))return[];let s=[];return typeof n.interrupted=="boolean"&&s.push(`interrupted:${n.interrupted}`),typeof n.returnCodeInterpretation=="string"&&s.push(`rcInterp:${n.returnCodeInterpretation.slice(0,80)}`),typeof n.stderr=="string"&&s.push(`stderrBytes:${n.stderr.length}`),[{type:"bash_outcome",category:"data",data:_(s.join(" ")),priority:3}]}function $t(t){if(t.tool_name!=="Read")return[];let e=t.tool_response;if(typeof e!="string"||e.length===0)return[];let o;try{o=JSON.parse(e)}catch{return[]}if(!o||typeof o!="object")return[];let n=o,r=n.type;if(r!=="text"&&r!=="image")return[];let s=[`type:${r}`];if(r==="text")typeof n.numLines=="number"&&s.push(`lines:${n.numLines}`),typeof n.totalLines=="number"&&s.push(`totalLines:${n.totalLines}`),typeof n.startLine=="number"&&s.push(`start:${n.startLine}`);else{typeof n.originalSize=="number"&&s.push(`origSize:${n.originalSize}`);let i=n.dimensions;if(i&&typeof i=="object"){let a=i;typeof a.width=="number"&&typeof a.height=="number"&&s.push(`dims:${a.width}x${a.height}`)}}return[{type:"file_read_metadata",category:"data",data:_(s.join(" ")),priority:3}]}function Ot(t,e){let o=[t.tool_input?.model,t.model,e.model];for(let n of o)if(typeof n=="string"&&n.length>0)return n;return""}function Pt(t){for(let e=t.length-1;e>0;e--)if(t.charCodeAt(e)===45)return t.slice(0,e);return null}function Lt(t){let e=t;for(;e&&e.length>0;){if(I(e)!==null)return e;e=Pt(e)}return""}function Nt(t,e,o,n,r){let s=Lt(t);return P(s||t,{input_tokens:e,output_tokens:o,cache_creation_tokens:n,cache_read_tokens:r})}function Mt(t){let e=t.toFixed(6),o=e.length;for(;o>0&&e.charCodeAt(o-1)===48;)o--;return e=e.slice(0,o),e.length>0&&e.charCodeAt(e.length-1)===46&&(e+="0"),e}function Ht(t){if(t.tool_name!=="Task")return[];let e=t.tool_response;if(typeof e!="string"||e.length===0)return[];let o;try{o=JSON.parse(e)}catch{return[]}if(!o||typeof o!="object")return[];let n=o,r=n.usage&&typeof n.usage=="object"?n.usage:{};if(!(typeof n.totalTokens=="number"||typeof n.totalDurationMs=="number"||typeof r.input_tokens=="number"||typeof r.output_tokens=="number"||typeof r.service_tier=="string"))return[];let i=[];typeof n.totalTokens=="number"&&i.push(`totalTokens:${n.totalTokens}`),typeof n.totalDurationMs=="number"&&i.push(`totalDurMs:${n.totalDurationMs}`),typeof r.input_tokens=="number"&&i.push(`tokens_in:${r.input_tokens}`),typeof r.output_tokens=="number"&&i.push(`tokens_out:${r.output_tokens}`),typeof r.cache_creation_input_tokens=="number"&&i.push(`cache_create:${r.cache_creation_input_tokens}`),typeof r.cache_read_input_tokens=="number"&&i.push(`cache_read:${r.cache_read_input_tokens}`),typeof r.service_tier=="string"&&i.push(`tier:${r.service_tier.slice(0,32)}`);let a=Ot(t,n),p={type:"agent_usage",category:"cost",data:_(i.join(" ")),priority:2};return a.length>0&&(p.model_id=a),typeof r.input_tokens=="number"&&(p.input_tokens=r.input_tokens),typeof r.output_tokens=="number"&&(p.output_tokens=r.output_tokens),typeof r.cache_read_input_tokens=="number"&&(p.cache_read_tokens=r.cache_read_input_tokens),typeof r.cache_creation_input_tokens=="number"&&(p.cache_creation_tokens=r.cache_creation_input_tokens),p.usage_scope="task_cumulative",[p]}function Ee(t){if(!t||typeof t!="object")return null;let e=t,o=e.message,n=o&&typeof o=="object"?o:e;if(typeof n.role=="string"&&n.role!=="assistant")return null;let r=n.usage;if(!r||typeof r!="object")return null;let s=r,i=d=>typeof d=="number"&&Number.isFinite(d)&&d>0?d:0,a=i(s.input),p=i(s.output),u=i(s.cacheWrite),c=i(s.cacheRead);if(a<=0&&p<=0&&u<=0&&c<=0)return null;let l=null,m=s.cost;if(m&&typeof m=="object"){let d=m.total;typeof d=="number"&&Number.isFinite(d)&&(l=d)}return{model_id:typeof n.model=="string"?n.model:"",input_tokens:a,output_tokens:p,cache_creation_tokens:u,cache_read_tokens:c,native_cost_usd:l}}function xe(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.type=="string"&&e.type!=="model.usage")return null;let o=e.usage;if(!o||typeof o!="object")return null;let n=o,r=m=>typeof m=="number"&&Number.isFinite(m)&&m>0?m:0,s=r(n.input),i=r(n.output),a=r(n.cacheWrite),p=r(n.cacheRead);if(s<=0&&i<=0&&a<=0&&p<=0)return null;let u=e.costUsd,c=typeof u=="number"&&Number.isFinite(u)?u:null;return{model_id:typeof e.model=="string"?e.model:"",input_tokens:s,output_tokens:i,cache_creation_tokens:a,cache_read_tokens:p,native_cost_usd:c}}function Ae(t){if(!t||typeof t!="object")return null;let e=t,o=e.event&&typeof e.event=="object"?e.event:e,n=o.properties&&typeof o.properties=="object"?o.properties:o,r=n.info&&typeof n.info=="object"?n.info:e;if(typeof r.role=="string"&&r.role!=="assistant")return null;let s=r.tokens;if(!s||typeof s!="object")return null;let i=s,a=b=>typeof b=="number"&&Number.isFinite(b)&&b>0?b:0,p=i.cache,u=p&&typeof p=="object"?p:{},c=a(i.input),l=a(i.output),m=a(u.read),h=a(u.write);if(c<=0&&l<=0&&h<=0&&m<=0)return null;let d=r.cost,S=typeof d=="number"&&Number.isFinite(d)?d:null,y=typeof r.modelID=="string"?r.modelID:"",R=typeof r.providerID=="string"?r.providerID:"",f="";return y.length>0?f=R.length>0?`${R}/${y}`:y:typeof r.model=="string"&&(f=r.model),{model_id:f,input_tokens:c,output_tokens:l,cache_creation_tokens:h,cache_read_tokens:m,native_cost_usd:S}}function w(t){let{model_id:e,input_tokens:o,output_tokens:n,cache_creation_tokens:r,cache_read_tokens:s,native_cost_usd:i}=t;if(o<=0&&n<=0&&r<=0&&s<=0)return null;let a=[`tokens_in:${o}`,`tokens_out:${n}`];r>0&&a.push(`cache_create:${r}`),s>0&&a.push(`cache_read:${s}`);let p=typeof i=="number"&&Number.isFinite(i)?i:Nt(e,o,n,r,s);p!==null&&a.push(`cost_usd:${Mt(p)}`);let u={type:"agent_usage",category:"cost",data:_(a.join(" ")),priority:2};return e.length>0&&(u.model_id=e),u.input_tokens=o,u.output_tokens=n,s>0&&(u.cache_read_tokens=s),r>0&&(u.cache_creation_tokens=r),p!==null&&(u.cost_usd=p),u}function Ce(t){if(!t||typeof t!="object")return null;let e=t,o=e.llm_response;if(!o||typeof o!="object")return null;let n=o,r=n.usageMetadata;if(!r||typeof r!="object")return null;let s=r,i=y=>typeof y=="number"&&Number.isFinite(y)?y:0,a=i(s.promptTokenCount),p=i(s.candidatesTokenCount),u=i(s.thoughtsTokenCount),c=i(s.cachedContentTokenCount),l=p+u,m=e.llm_request,h=m&&typeof m=="object"&&typeof m.model=="string"?m.model:"",d=typeof n.modelVersion=="string"?n.modelVersion:"",S=d.length>0?d:h;return w({model_id:S,input_tokens:a,output_tokens:l,cache_creation_tokens:0,cache_read_tokens:c})}function Te(t){if(typeof t!="string"||t.length===0)return[];let e=new Map,o=0;for(let r=0;r<=t.length;r++){if(r!==t.length&&t.charCodeAt(r)!==10)continue;let s=t.slice(o,r).trim();if(o=r+1,s.length===0)continue;let i;try{let h=JSON.parse(s);if(!h||typeof h!="object")continue;i=h}catch{continue}if(i.type!=="assistant"||i.isSidechain===!0)continue;let a=i.message;if(!a||typeof a!="object")continue;let p=a,u=typeof p.model=="string"?p.model:"";if(u.length===0)continue;let c=p.usage;if(!c||typeof c!="object")continue;let l=c,m=e.get(u)??{input:0,output:0,cacheCreate:0,cacheRead:0};typeof l.input_tokens=="number"&&(m.input+=l.input_tokens),typeof l.output_tokens=="number"&&(m.output+=l.output_tokens),typeof l.cache_creation_input_tokens=="number"&&(m.cacheCreate+=l.cache_creation_input_tokens),typeof l.cache_read_input_tokens=="number"&&(m.cacheRead+=l.cache_read_input_tokens),e.set(u,m)}let n=[];for(let[r,s]of e){let i=w({model_id:r,input_tokens:s.input,output_tokens:s.output,cache_creation_tokens:s.cacheCreate,cache_read_tokens:s.cacheRead});i&&n.push(i)}return n}function Ie(t,e){let o=typeof e=="string"&&e.length>0?e:null;if(typeof t!="string"||t.length===0)return{events:[],cursor:o};let n=[],r=0;for(let c=0;c<=t.length;c++){if(c!==t.length&&t.charCodeAt(c)!==10)continue;let l=t.slice(r,c).trim();if(r=c+1,l.length===0)continue;let m;try{let b=JSON.parse(l);if(!b||typeof b!="object")continue;m=b}catch{continue}if(m.type!=="assistant"||m.isSidechain===!0)continue;let h=m.message;if(!h||typeof h!="object")continue;let d=h,S=typeof d.model=="string"?d.model:"";if(S.length===0)continue;let y=typeof m.uuid=="string"&&m.uuid.length>0?m.uuid:null,R=d.usage,f=R&&typeof R=="object"?R:{};n.push({uuid:y,model:S,input:typeof f.input_tokens=="number"?f.input_tokens:0,output:typeof f.output_tokens=="number"?f.output_tokens:0,cacheCreate:typeof f.cache_creation_input_tokens=="number"?f.cache_creation_input_tokens:0,cacheRead:typeof f.cache_read_input_tokens=="number"?f.cache_read_input_tokens:0})}if(n.length===0)return{events:[],cursor:o};let s=n[n.length-1].uuid,i=s!==null?s:o,a;if(o===null)a=n;else{let c=-1;for(let l=0;l<n.length;l++)if(n[l].uuid===o){c=l;break}c>=0?a=n.slice(c+1):a=n.slice(n.length-1)}let p=new Map;for(let c of a){let l=p.get(c.model)??{input:0,output:0,cacheCreate:0,cacheRead:0};l.input+=c.input,l.output+=c.output,l.cacheCreate+=c.cacheCreate,l.cacheRead+=c.cacheRead,p.set(c.model,l)}let u=[];for(let[c,l]of p){let m=w({model_id:c,input_tokens:l.input,output_tokens:l.output,cache_creation_tokens:l.cacheCreate,cache_read_tokens:l.cacheRead});m&&u.push(m)}return{events:u,cursor:i}}var D=/[,;,;、،]/u,Ut=15,Bt=500;function Ft(t){if(C.test(t)||!$.test(t)||!D.test(t))return!1;let e=[...t].length;return e>=Ut&&e<=Bt}function Wt(t){let e=t.trim();return Ft(e)?[{type:"decision",category:"decision",data:_(t),priority:2}]:[]}var Dt=8,qt=120,Kt=new RegExp("\\p{L}+\\s+\\p{L}+","u"),Gt=new RegExp("\\p{L}{6,}","u"),zt=new Set(["ok","okay","sure","yeah","yep","yup","alright","fine","well","so","hmm","right","please"]),Jt=["you are","you're","your role","you will be","you act","you will act","act as","act like","behave as","behave like","imagine you","pretend you","assume the role","take the role","play the role","respond as","tu es","tu est","vous etes","vous \xEAtes","sen ","siz ","eres ","t\xFA eres","usted es","\u0442\u044B ","\u0432\u044B ","\u3042\u306A\u305F\u306F","\u541B\u306F","\u304A\u524D\u306F","\u3042\u306A\u305F\u304C","\u4F60\u662F","\u60A8\u662F","\u0924\u0941\u092E ","\u0906\u092A ","\u0924\u0942 ","\u0623\u0646\u062A ","\u0627\u0646\u062A ","\u0623\u0646\u062A\u064E "],Vt=["always ","never ","respond ","reply ","answer ","speak ","write ","prefer ","format ","output ","communicate ","use only "];function Qt(t){let e=t.toLowerCase().trim();if(!e)return!1;let o=e.split(" ").filter(r=>r.length>0);for(;o.length>0&&zt.has(o[0]);)o.shift();let n=o.join(" ");if(!n)return!1;for(let r of Jt)if(n.startsWith(r))return!0;for(let r of Vt)if(n.startsWith(r))return!0;return!1}function Xt(t){let e=t.split(/[.!\n。!]/u)[0].trim();if(C.test(e)||D.test(e)||!$.test(e))return!1;let o=[...e].length;return o<Dt||o>qt||!Qt(e)?!1:Kt.test(e)||Gt.test(e)}function Yt(t){let e=t.trim();return Xt(e)?[{type:"role",category:"role",data:_(t),priority:3}]:[]}var C=/[??؟¿]/u,$=new RegExp("\\p{L}","u"),Zt=60;function te(t){if(C.test(t)||!$.test(t))return!1;let e=[...t].length;return e>0&&e<Zt}function ee(t){let e=t.trim();if(!e)return[];let o;return C.test(e)?o="investigate":te(e)&&(o="implement"),o?[{type:"intent",category:"intent",data:_(o),priority:4}]:[]}var ne=/^(?:\/goal\s+|(?:goal|objective)\s*:\s*)(.+)$/is;function oe(t){let e=t.trim();if(!e)return[];let o=e.match(ne);if(!o)return[];let n=o[1].trim();return n?[{type:"goal",category:"goal",data:_(n),priority:4}]:[]}var re=/(?:\bError\s*:|\bException\s*:|\bTraceback\b|\bat\s+\S+\s*\([^)]*:\d+:\d+\))/u,se=/[✓✔✅☑🎉]/u,ie=/^\s*(?:fixed|resolved)\s*:/iu;function ce(t){let e=[];return se.test(t)||ie.test(t)?(e.push({type:"blocker_resolved",category:"blocked-on",data:_(t),priority:2}),e):(re.test(t)&&e.push({type:"blocker",category:"blocked-on",data:_(t),priority:2}),e)}function ue(t){return t.length<=1024?[]:[{type:"data",category:"data",data:_(t),priority:4}]}var g=null;function ae(t){let{tool_name:e,tool_response:o}=t,n=String(o??"");if(v(t))return g={tool:e,error:n.slice(0,200),callsSince:0},[];if(!g)return[];if(g.callsSince++,g.callsSince>10)return g=null,[];if(!!v(t))return[];let s=e===g.tool,i=g.tool==="Read"&&(e==="Edit"||e==="Write"||e==="apply_patch");if(s||i){let a={type:"error_resolved",category:"error-resolution",data:_(`Error in ${g.tool}: ${g.error} \u2192 Fixed`),priority:2};return g=null,[a]}return[]}function je(){g=null}var k=[];function pe(t){return`${t.length}:${t.slice(0,20)}`}function le(t){let{tool_name:e,tool_input:o}=t,n=pe(JSON.stringify(o).slice(0,200));if(k.push({tool:e,inputHash:n}),k.length>50&&k.splice(0,k.length-50),k.length<3)return[];let r=0;for(let s=k.length-1;s>=0&&(k[s].tool===e&&k[s].inputHash===n);s--)r++;return r>=3?(k.splice(k.length-r),[{type:"retry_detected",category:"iteration-loop",data:_(`${e} called ${r} times with similar input`),priority:2}]):[]}function $e(){k.length=0}var _e={run_shell_command:"Bash",read_file:"Read",read_many_files:"Read",grep_search:"Grep",search_file_content:"Grep",web_fetch:"WebFetch",write_file:"Write",edit:"Edit",glob:"Glob",todo_write:"TodoWrite",ask_user_question:"AskUserQuestion",list_directory:"LS",save_memory:"Memory",skill:"Skill",exit_plan_mode:"ExitPlanMode",agent:"Agent",bash:"Bash",view:"Read",grep:"Grep",fetch:"WebFetch",read:"Read",write:"Write",shell:"Bash",shell_command:"Bash",exec_command:"Bash","container.exec":"Bash",local_shell:"Bash",grep_files:"Grep",run_command:"Bash",view_file:"Read",read_url_content:"WebFetch",list_dir:"LS",search_web:"WebSearch"};function me(t){let e=_e[t.tool_name];return!e||e===t.tool_name?t:{...t,tool_name:e}}function Oe(t){try{let e=me(t),o=[];return o.push(...Y(e)),o.push(...Z(e)),o.push(...tt(e)),o.push(...et(e)),o.push(...mt(e)),o.push(...ut(e)),o.push(...lt(e)),o.push(...dt(e)),o.push(...ft(e)),o.push(...gt(e)),o.push(...St(e)),o.push(...Et(e)),o.push(...ht(e)),o.push(...Ct(e)),o.push(...It(e)),o.push(...jt(e)),o.push(...$t(e)),o.push(...Ht(e)),o.push(...xt(e)),o.push(...At(e)),o.push(...ae(e)),o.push(...le(e)),o}catch{return[]}}function Pe(t){try{let e=[];return e.push(...fe(t)),e.push(...Wt(t)),e.push(...Yt(t)),e.push(...ee(t)),e.push(...oe(t)),e.push(...ce(t)),e.push(...ue(t)),e}catch{return[]}}function Le(t){if(!t||typeof t!="object")return[];let e=t,o=[],n=e.mcp_servers,r=null;return n&&typeof n=="object"&&!Array.isArray(n)&&(r=Object.keys(n),o.push(`mcp_count:${r.length}`),r.length>0&&o.push(`mcp_servers:${r.slice(0,8).join(",")}`)),typeof e.model=="string"&&o.push(`model:${e.model.slice(0,64)}`),typeof e.permission_mode=="string"&&o.push(`permission_mode:${e.permission_mode.slice(0,32)}`),o.length===0?[]:[{type:"session_settings_snapshot",category:"env",data:_(o.join(" ")),priority:2}]}var de=["Latin","Cyrillic","Arabic","Han","Hangul","Hiragana","Katakana","Devanagari","Hebrew","Thai","Greek"],he={prompt_length:0,prompt_word_count:0,prompt_uppercase_ratio:0,prompt_file_ref_count:0,prompt_path_ref_count:0,prompt_script_primary:null,prompt_script_count:0,prompt_question_glyph_count:0,prompt_code_block_count:0,prompt_url_count:0,prompt_word_tokens:[]};function Ne(t){if(typeof t!="string"||t.length===0)return{...he,prompt_word_tokens:[]};let e=t.match(new RegExp("\\p{L}+","gu"))??[],o=(t.match(new RegExp("\\p{Lu}","gu"))??[]).length,n=e.join("").length,r=(t.match(/```/g)??[]).length,s={};for(let u of de){let c=new RegExp(`\\p{Script=${u}}`,"gu"),l=(t.match(c)??[]).length;l>0&&(s[u]=l)}let i=Object.entries(s).sort((u,c)=>c[1]-u[1])[0]?.[0]??null,a=new Set,p=[];for(let u of e){if(u.length<3)continue;let c=u.toLowerCase();a.has(c)||(a.add(c),p.push(c))}return{prompt_length:t.length,prompt_word_count:e.length,prompt_uppercase_ratio:n===0?0:o/n,prompt_file_ref_count:(t.match(/(\w+\/)+\w+\.\w+/g)??[]).length,prompt_path_ref_count:(t.match(/\.{0,2}\/[\w\/.-]+/g)??[]).length,prompt_script_primary:i,prompt_script_count:Object.keys(s).length,prompt_question_glyph_count:(t.match(/[??؟]/gu)??[]).length,prompt_code_block_count:Math.floor(r/2),prompt_url_count:(t.match(/https?:\/\/[^\s]+/gu)??[]).length,prompt_word_tokens:p}}function fe(t){if(typeof t!="string"||t.length===0)return[];let e=0;for(;e<t.length;){let r=t.charCodeAt(e);if(r!==32&&r!==9)break;e++}if(e+5>t.length)return[];if(t.slice(e,e+5)!=="/plan")return[];if(e+5<t.length){let r=t.charCodeAt(e+5);if(!(r===32||r===9||r===10||r===13))return[]}let o=t.slice(e+5).trim(),n=o.length>0?`plan via /plan slash: ${o.slice(0,120)}`:"plan via /plan slash";return[{type:"plan_enter",category:"plan",data:_(n),priority:2}]}export{w as buildAgentUsageEvent,Oe as extractEvents,J as extractKimiUsageSince,X as extractQwenUsageSince,Le as extractSessionSettings,Te as extractTranscriptUsage,Ie as extractTranscriptUsageSince,Pe as extractUserEvents,Ne as extractUserPromptFeatures,Ce as parseGeminiUsage,L as parseKimiUsage,xe as parseOpenclawUsage,Ae as parseOpencodeUsage,Ee as parsePiUsage,N as parseQwenUsage,je as resetErrorResolutionState,$e as resetIterationLoopState};
@@ -3,7 +3,7 @@
3
3
  "name": "Context Mode",
4
4
  "kind": "tool",
5
5
  "description": "OpenClaw plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.",
6
- "version": "2.0.4",
6
+ "version": "2.0.5",
7
7
  "sandbox": {
8
8
  "mode": "permissive",
9
9
  "filesystem_access": "full",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mxalbert/context-mode",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
4
  "type": "module",
5
5
  "description": "MCP plugin that saves 98% of your context window. Works with Claude Code, Gemini CLI, VS Code Copilot, OpenCode, and Codex CLI. Sandboxed code execution, FTS5 knowledge base, and intent-driven search.",
6
6
  "author": "Mert Koseoğlu",