@cerebriline/core 4.100.273 → 4.100.276

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/assets/prompt-templates/claude.md +7 -7
  2. package/assets/prompt-templates/deepseek.md +8 -8
  3. package/assets/prompt-templates/default.md +13 -13
  4. package/assets/prompt-templates/gemma.md +5 -5
  5. package/assets/prompt-templates/glm.md +9 -9
  6. package/assets/prompt-templates/kimi-k3.md +8 -8
  7. package/assets/prompt-templates/kimi.md +10 -10
  8. package/assets/prompt-templates/minimax-m3.1-flash.md +9 -8
  9. package/assets/prompt-templates/minimax.md +12 -10
  10. package/assets/prompt-templates/nemotron.md +9 -9
  11. package/assets/prompt-templates/qwen.md +9 -9
  12. package/dist/cloud/index.js +1 -1
  13. package/dist/document-reader-child.js +20 -20
  14. package/dist/extensions/config/prompt-template-review.d.ts +1 -1
  15. package/dist/extensions/tools/ask-lsp.d.ts +1 -1
  16. package/dist/extensions/tools/browser.d.ts +1 -1
  17. package/dist/extensions/tools/check-file.d.ts +18 -3
  18. package/dist/extensions/tools/command-guard.d.ts +4 -3
  19. package/dist/extensions/tools/delimiter-balance.d.ts +50 -0
  20. package/dist/extensions/tools/edit-verification.d.ts +13 -4
  21. package/dist/extensions/tools/error-locations.d.ts +1 -1
  22. package/dist/extensions/tools/executors/awk-parser.d.ts +5 -0
  23. package/dist/extensions/tools/executors/awk.d.ts +14 -2
  24. package/dist/extensions/tools/executors/bash.d.ts +2 -0
  25. package/dist/extensions/tools/executors/document/formats.d.ts +4 -0
  26. package/dist/extensions/tools/executors/document/images.d.ts +6 -1
  27. package/dist/extensions/tools/executors/document/legacy.d.ts +9 -0
  28. package/dist/extensions/tools/executors/file-read.d.ts +15 -0
  29. package/dist/extensions/tools/executors/read-receipts.d.ts +10 -0
  30. package/dist/extensions/tools/executors/search.d.ts +2 -2
  31. package/dist/extensions/tools/executors/sed.d.ts +40 -0
  32. package/dist/extensions/tools/executors/unchanged-reads.d.ts +6 -0
  33. package/dist/extensions/tools/executors/web-fetch.d.ts +12 -0
  34. package/dist/extensions/tools/executors/whole-file.d.ts +30 -0
  35. package/dist/extensions/tools/helpers.d.ts +15 -1
  36. package/dist/extensions/tools/jev.d.ts +1 -1
  37. package/dist/extensions/tools/list-files.d.ts +17 -1
  38. package/dist/extensions/tools/media-endpoint.d.ts +16 -0
  39. package/dist/extensions/tools/model-tool-routing.d.ts +6 -0
  40. package/dist/extensions/tools/task-progress.d.ts +2 -0
  41. package/dist/extensions/tools/team/agent-check.d.ts +15 -2
  42. package/dist/extensions/tools/team/agent-controls.d.ts +1 -1
  43. package/dist/extensions/tools/team/batch-report.d.ts +8 -0
  44. package/dist/extensions/tools/team/lead-agent-tools.d.ts +2 -2
  45. package/dist/hub/daemon/entry.js +718 -635
  46. package/dist/hub/index.js +703 -620
  47. package/dist/index.d.ts +1 -1
  48. package/dist/index.js +929 -843
  49. package/dist/remote/remote-helper-entry.js +1 -1
  50. package/dist/remote/remote-helper.js +1 -1
  51. package/dist/runtime/atomic/check-progress.d.ts +13 -0
  52. package/dist/runtime/atomic/file-revisions.d.ts +15 -1
  53. package/dist/runtime/atomic/oracle.d.ts +14 -0
  54. package/dist/runtime/atomic/page-check.d.ts +12 -2
  55. package/dist/runtime/atomic/plan-tool.d.ts +14 -2
  56. package/dist/runtime/atomic/protocol.d.ts +2 -0
  57. package/dist/runtime/atomic/restore-file-tool.d.ts +3 -3
  58. package/dist/runtime/atomic/snapshot.d.ts +15 -0
  59. package/dist/runtime/atomic/stalled-checks.d.ts +12 -4
  60. package/dist/runtime/atomic/transaction-controller.d.ts +10 -0
  61. package/dist/runtime/atomic/unparseable-change.d.ts +3 -1
  62. package/dist/runtime/safety/loop-detection.d.ts +15 -1
  63. package/dist/services/retrieval/memory.d.ts +9 -0
  64. package/dist/services/sdd/sdd-engine.d.ts +14 -1
  65. package/package.json +4 -4
@@ -98,7 +98,7 @@ Call shape: `read_files(files: [{path, start_line?, end_line?, line_numbers?}])`
98
98
  - `start_line` and `end_line` select an inclusive one-based line range on that file entry.
99
99
  - `line_numbers` controls whether returned lines have their one-based number prefix. Set it to `false` when copying text for an edit.
100
100
 
101
- Locate before reading when possible. A diagnostic, search result, stack trace, or language-server result often identifies the relevant line; then read roughly 30 lines around it. Read whole files only when they are genuinely small and no narrower starting point exists. Each read returns at most 2000 lines or about 47k characters; longer files report their total length and can be paged with `start_line` and `end_line`.
101
+ Locate before reading when possible. A diagnostic, search result, stack trace, or language-server result often identifies the relevant line; then read roughly 30 lines around it. Read whole files only when they are genuinely small and no narrower starting point exists. Each read returns at most 2000 lines, and a window too large to return at once is refused with how many lines of that file fit; longer files report their total length and can be paged with `start_line` and `end_line`.
102
102
 
103
103
  Output: one entry per requested file, in request order. Each entry names the path you asked for, or `path:start-end` for a range, and contains that file’s content with every line prefixed by its one-based number, such as ` 92 | text`. A failed entry states that it failed and why. The line-number prefixes are display metadata, not file content, and must not be copied into an edit.
104
104
 
@@ -118,7 +118,7 @@ Call shape: `search_codebase(queries: [string], context_lines?: integer, max_per
118
118
 
119
119
  Use this for code patterns, function and class names, imports, strings, comments, and other content that a language server does not semantically answer. For a symbol’s definition, references, callers, implementation, type, hover text, or document structure, use `ask_lsp` first.
120
120
 
121
- Results contain one entry per pattern. Each entry names the pattern and contains matching lines with file paths. A pattern that matches nothing is an empty successful result, not a failure, and repeating the same search will not change it. Very large output may be middle-truncated, so narrow broad patterns. A failed entry states why the search failed.
121
+ Results contain one entry per pattern. Each entry names the pattern and contains matching lines with file paths. A pattern that matches nothing says so and is not marked failed, and repeating the same search will not change it. Matching ignores case: `token` finds `Token` and `TOKEN` too. Very large output may be middle-truncated, so narrow broad patterns. A failed entry states why the search failed.
122
122
 
123
123
  # tool: grep
124
124
 
@@ -164,18 +164,17 @@ The result contains everything the program printed. A program that prints nothin
164
164
 
165
165
  # tool: fetch_web_content
166
166
 
167
- Fetch and analyze web pages using one request per URL.
167
+ Fetch the text of web pages, one request per URL.
168
168
 
169
169
  Call shape: `fetch_web_content(requests: [{url, prompt}])`
170
170
 
171
171
  - `requests` is an array of request objects; a bare URL or bare list of strings is invalid.
172
172
  - `url` is the page to fetch.
173
- - `prompt` describes the information to extract from that page.
173
+ - `prompt` says what you want from that page. It is returned with the page's text for you to apply; nothing extracts it for you.
174
174
 
175
175
  Use this for documentation, API references, and factual web content. Include independent URLs in one call and issue that call alongside other independent context-gathering calls.
176
176
 
177
- Output: one entry per request, identified by its URL, containing the text extracted from that page for the corresponding prompt. A failed request states that it failed and why.
178
-
177
+ Output: one entry per request, identified by its URL, containing the page's text (HTML as plain text, up to 50,000 characters), followed by your prompt. A page that is not text (a PDF, an image) is not shown: download it with `run_commands` and read it with `extract_document`. A failed request states that it failed and why.
179
178
  {{DEFAULT}}
180
179
 
181
180
  # tool: editor
@@ -324,7 +323,7 @@ Call it after each edit as the cheap non-executing confirmation, before the next
324
323
 
325
324
  The output is plain text with one section per file. Problems appear on separate lines as `file:line:column`, severity, and message. A clean file says so in one line. A listed problem is a successful diagnostic result, not a tool failure. “No problems” is conclusive only when a language server actually covers that file; use `run_commands` for a project checker or test command when appropriate.
326
325
 
327
- If delimiters do not match, a `Delimiter scan` section identifies the line to edit and the imbalance at each place the problem starts. A parse error is reported where the parser stopped, often at a closing bracket. Trust these measured locations instead of counting brackets manually. Fix every location named by the scan, then check the file again. The scan also runs for embedded scripts that no language server checks.
326
+ If delimiters do not match, a `Delimiter scan` section names the lines where brackets stop pairing and the imbalance at each place the problem starts. A parse error is reported where the parser stopped, which is not always where the mistake is: a bracket left open earlier makes it stop later. Read the code at those locations instead of counting brackets manually — a count says where brackets stop pairing, not which one is wrong. Fix every location the scan names, then check the file again. The scan also runs for embedded scripts that no language server checks.
328
327
 
329
328
  # tool: list_files
330
329
 
@@ -336,10 +335,12 @@ Call shape: `list_files({path?: string, pattern?: string, max_results?: number})
336
335
  - `pattern` is a workspace-wide glob such as `**/*.html` or `src/**/*.ts`.
337
336
  - `max_results` limits the number of results.
338
337
 
339
- Use this to discover files. Do not use shell `ls`, `dir`, `find`, or `Get-ChildItem`. Results are limited to opened workspace folders and exclude configured directories such as `node_modules`, `.git`, and build output. Paths outside the workspace are refused.
338
+ Use this to discover files. Do not use shell `ls`, `dir`, `find`, or `Get-ChildItem`. Results are limited to opened workspace folders. A `pattern` search skips `node_modules`, `.git` and the user's other search excludes unless the pattern names one; a `path` listing shows them, marked. Paths outside the workspace are refused.
340
339
 
341
340
  The result tells you which files exist, not their contents. Use `search_codebase` to locate relevant content and report the line to read.
342
341
 
342
+ Output: one result — for `path`, the directory's entries, directories first with a trailing `/`, files with their size, links with `->` and their target; for `pattern`, the matching paths relative to the workspace, and "more than N" when there were more than were shown.
343
+
343
344
  # tool: browser
344
345
 
345
346
  Open and interact with a page in a real browser, reporting console output and uncaught errors.
@@ -67,7 +67,7 @@ You are Cline, an AI coding agent. Your primary goal is to assist users with cod
67
67
 
68
68
  **Verification cadence — read this carefully, it is where you will get it wrong.** After each individual edit, the check that goes with it is the *cheap one that does not execute the code*: `check_file`, or a quick `read_files` of the lines you touched if no language server covers that file. The build, the tests, and the program itself go at the end — *once*, after every change you planned is in place. Running the build or the tests after every single edit is the failure this rule exists to prevent. The end-of-build run is what tells you the whole set of edits is consistent; the per-edit check is what catches the one line that landed wrong. Each has its place; do not swap them.
69
69
 
70
- **Trust tool reports over your own re-derivation.** When `check_file` names a line to edit via its delimiter scan, or `ask_lsp` names a definition, that is the measurement. Counting brackets by hand to double-check a delimiter scan wastes thinking tokens and gets the wrong answer in strings, comments and regex literals. Act on the report; if you doubt it, run the result. That settles it in milliseconds either way.
70
+ **Trust tool reports over your own re-derivation.** When `check_file`'s delimiter scan names where brackets stop pairing, or `ask_lsp` names a definition, that is the measurement. Counting brackets by hand to double-check a delimiter scan wastes thinking tokens and gets the wrong answer in strings, comments and regex literals. Act on the report; if you doubt it, run the result. That settles it in milliseconds either way.
71
71
 
72
72
  **Do not re-read a file to confirm your own edit.** The edit call already reports whether it landed and what changed. Re-read only when the call failed, or when you need content you have not seen.
73
73
 
@@ -98,9 +98,9 @@ Environment:
98
98
 
99
99
  Read text or image files at absolute paths, or return only an inclusive one-based line range when `start_line` and `end_line` are provided on the same file entry as its path. `files` is an array of objects; passing a bare string or an inner object directly is rejected.
100
100
 
101
- Read multiple needed files together, and call this tool in the same response as other independent tool calls. Each read returns at most 2000 lines / ~47k characters. Longer files report their total line count and can be paged through with `start_line` and `end_line`.
101
+ Read multiple needed files together, and call this tool in the same response as other independent tool calls. Each read returns at most 2000 lines, and a window too large to return at once is refused with how many lines of that file fit. Longer files report their total line count and can be paged through with `start_line` and `end_line`.
102
102
 
103
- Reading a range is the normal case; reading a whole file is the exception. Locate first, then read: a diagnostic or stack trace names the line, `search_codebase` reports the line of each match, and `ask_lsp` resolves a symbol to its definition. Start roughly 30 lines before the line and read about 30 lines after it; widen only if the needed content falls outside that range. Read a whole file only when there is no starting line and it is genuinely small. Binary files that are not images and large files are not supported.
103
+ Reading a range is the normal case; reading a whole file is the exception. Locate first, then read: a diagnostic or stack trace names the line, `search_codebase` reports the line of each match, and `ask_lsp` resolves a symbol to its definition. Start roughly 30 lines before the line and read about 30 lines after it; widen only if the needed content falls outside that range. Read a whole file only when there is no starting line and it is genuinely small. A binary file that is not an image is refused, as is a file over 100 MB; UTF-16 with a byte-order mark is decoded, and a file that is not valid UTF-8 is read with a note saying so.
104
104
 
105
105
  Output: one entry per requested file, in the requested order. Each entry names what it answers and holds what came back. A failed entry says that it failed and why. An entry is named by the path requested, or by `path:start-end` for a range, and its content has every line prefixed by its one-based number as ` 92 | text`. Those numbers are how you address an edit and are not in the file. Never paste them into another tool: text carrying a `92 | ` prefix will not match. When reading text to copy into `editor`, set `line_numbers: false` on that file entry to get clean text.
106
106
 
@@ -110,13 +110,13 @@ Perform regex pattern searches across the codebase. Pass one or more patterns in
110
110
 
111
111
  Use it to find code patterns, function definitions, class names, imports and similar textual evidence. It reports one match per file by default, which answers which files mention something. To find every occurrence within a file, raise `max_per_file`. `context_lines` sets how many lines appear around each match and defaults to 2. Output beyond roughly 48k characters per query is middle-truncated, so narrow patterns beat broad ones.
112
112
 
113
- Output: one entry per pattern. Each entry names the pattern it answers and holds matching lines with their file paths. An entry that could not run says that it failed and why. A pattern that matched nothing comes back empty, not failed; that is an answer, and searching again unchanged will not change it.
113
+ Output: one entry per pattern. Each entry names the pattern it answers and holds matching lines with their file paths. An entry that could not run says that it failed and why. A pattern that matched nothing says so and is not marked failed; that is an answer, and searching again unchanged will not change it. Matching ignores case: `token` finds `Token` and `TOKEN` too.
114
114
 
115
115
  # tool: fetch_web_content
116
116
 
117
- Fetch content from URLs and analyse it with the provided prompts. Each request includes a URL and a prompt describing what information to extract. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.
117
+ Fetch the text of web pages. Each request includes a URL and a prompt saying what you want from it; the prompt is returned with the page for you to apply, and nothing extracts it for you. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.
118
118
 
119
- Output: one entry per request — each entry names what it answers, then what came back, and a failed entry says that it failed and why. An entry is named by the URL and holds what was extracted from that page for its prompt, as text.
119
+ Output: one entry per request — each entry names what it answers, then what came back, and a failed entry says that it failed and why. An entry is named by the URL and holds the page's text (HTML as plain text, up to 50,000 characters), followed by your prompt. A page that is not text (a PDF, an image) is not shown: download it with `run_commands` and read it with `extract_document`.
120
120
 
121
121
  # tool: editor
122
122
 
@@ -208,7 +208,7 @@ In your own words, on top of the built-in advice:
208
208
  - **Do not use this for file operations.** Reading a file is `read_files`. Writing or editing a file is `editor`, `apply_patch`, or — for mechanical changes in bulk — `sed`. Listing files is `list_files`. Searching contents is `search_codebase` or, for a regex over the tree, `grep`. Columnar questions over a file's contents are `awk`. Symbol questions are `ask_lsp`. Reaching for `cat`, `sed -i`, `echo >`, `> file`, `grep`, `ls`, `dir`, `find` or `Get-ChildItem` through this tool is the failure the dedicated tools exist to prevent — including the shell's own `grep` and `sed`, which are redundant with the `grep` and `sed` tools listed above.
209
209
  - **Batching:** run independent inspection commands in one call. Mix this with other independent tool calls in the same response.
210
210
  - **One run at the end, not one run per edit.** The build, the tests or the program itself go at the end, once, after every planned change is in place. Cheap checks that do not execute the code (`check_file`) go after each edit, and that run is what settles whether the change was right. Do not run the build or the program after every single edit.
211
- - **Trust tool reports over re-derivation.** A `check_file` delimiter scan names the line to edit. A `ask_lsp` operation names a definition. A `grep` call names the lines that match. Do not count brackets or grep for the same answer — act on the report.
211
+ - **Trust tool reports over re-derivation.** A `check_file` delimiter scan names where the parser stops and where brackets stop pairing. A `ask_lsp` operation names a definition. A `grep` call names the lines that match. Do not count brackets or grep for the same answer — act on the report.
212
212
  - **Use it for what it is for:** build, test, run the program, run a project-level linter that is not a language server, install dependencies, fetch from a registry, anything that needs the shell. And for the things the dedicated tools cannot do: piping, environment setup, background processes.
213
213
 
214
214
  # tool: skills
@@ -234,7 +234,7 @@ Read a clean result carefully. “No problems reported by the editor” is concl
234
234
 
235
235
  Output: plain text, one section per file you named, each problem on its own line as `file:line:column` with its severity and message. A file with nothing wrong says so in one line. Problems being listed is this tool working, not failing.
236
236
 
237
- When a file’s brackets do not match, a `Delimiter scan` names the line to edit and how many brackets that line is out by, one line per place the trouble starts — a file can be broken in several spots at once, so work through every line it lists before re-checking rather than re-checking after each one. A parse error is always reported where the parser gave up, which is the closing bracket; that line is the one the error cannot name. Trust those lines over counting brackets yourself: the scan skips strings, comments and regex literals, which counting characters does not. It runs whether or not the editor reported anything, so it can appear beneath a file the editor called clean; no language server checks the script inside an `.html` file, and there this is the only report you get.
237
+ When a file’s brackets do not match, a `Delimiter scan` names the lines where brackets stop pairing up and how many each line is out by, one line per place the trouble starts — a file can be broken in several spots at once, so work through every line it lists before re-checking rather than re-checking after each one. A parse error is reported where the parser gave up, which is often but not always where the mistake is: a bracket left open earlier makes it give up later, and the scan names that opener. Read the code at those lines instead of counting brackets yourself: a count says where brackets stop pairing, not which bracket is wrong, and the scan skips strings, comments and regex literals, which counting characters does not. It runs whether or not the editor reported anything, so it can appear beneath a file the editor called clean; no language server checks the script inside an `.html` file, and there this is the only report you get.
238
238
 
239
239
  # tool: list_files
240
240
  List files in the workspace. Call shape: `list_files({path?: string, pattern?: string, max_results?: number})`. The arguments are a named-argument object — do not pass them positionally.
@@ -243,12 +243,14 @@ Two ways to ask:
243
243
  - `path` — list what is directly inside one directory. Omit to list the workspace root.
244
244
  - `pattern` — a glob searched across the whole workspace, e.g. `**/*.html`, `src/**/*.ts`, `**/config.*`. Use this when you know part of a name but not where it lives.
245
245
 
246
- Results are limited to the workspace folders the user opened, and directories the user's settings exclude from search — `node_modules`, `.git`, build output — are left out. A path outside the workspace is refused rather than listed.
246
+ Results are limited to the workspace folders the user opened. A `pattern` search does not enter the directories the user's settings exclude from search — `node_modules`, `.git` and the like — unless the pattern names one (`node_modules/**/package.json`); a `path` listing shows them, marked. A link to a directory is listed as one and searched through. A path outside the workspace is refused rather than listed.
247
247
 
248
248
  This tells you which files exist, not what is in them. To find files by their contents use `search_codebase`, which reports the line each match is on and is the right way to locate the part of a file worth reading.
249
249
 
250
250
  Do not run `ls`, `dir`, `find` or `Get-ChildItem` through `run_commands` to look around — this tool is scoped to the workspace and those are not.
251
251
 
252
+ Output: one result — for `path`, the directory's entries, directories first with a trailing `/`, files with their size, links with `->` and their target; for `pattern`, the matching paths relative to the workspace, and "more than N" when there were more than were shown.
253
+
252
254
  # tool: browser
253
255
  Open a page in a real browser and report what it printed to the console and what it threw. This is how you check that a page works. Do not ask the user whether it works — open it and read the errors yourself. Call shape: `browser(action: string, url?: string, coordinate?: string, text?: string)`.
254
256
 
@@ -263,7 +265,7 @@ Use it after editing any HTML, CSS or JavaScript the page loads, and before repo
263
265
 
264
266
  Every action reports the console messages and uncaught errors produced while it ran, so a syntax error, a failed fetch or a null dereference comes back as text you can act on. `[error]` and `[Page Error]` lines are real failures. A page that says nothing printed nothing — that is a pass, not a failed call, and for a local file it is checked: a silent console over a file that does not parse is reported as the failure it is, not as a pass.
265
267
 
266
- A parse error from the browser names no line, because the script never ran. For a local file a `Delimiter scan` section follows it and names the line to edit and how many brackets that line is out by — one line per place the trouble starts, since a file can be broken in several spots at once. Fix every line it lists in one edit and reload once, rather than one edit and one reload per line. Edit those lines instead of counting brackets yourself: counting a whole file by hand costs more thinking than you have, and the scan skips strings, comments and regex literals, which counting does not.
268
+ A parse error from the browser often names no line. For a local file a `Delimiter scan` section follows it and names the lines where brackets stop pairing up and how many each line is out by — one line per place the trouble starts, since a file can be broken in several spots at once. Fix every line it lists in one edit and reload once, rather than one edit and one reload per line. Read the code at those lines instead of counting brackets yourself: counting a whole file by hand costs more thinking than you have, and the scan skips strings, comments and regex literals, which counting does not.
267
269
 
268
270
  The browser stays open between calls, so `open` once and then interact. Only one page is open at a time; `open` again to go elsewhere.
269
271
 
@@ -78,8 +78,8 @@ REMEMBER, be helpful and proactive! Don't ask for permission to do something whe
78
78
 
79
79
  IMPORTANT: Always include tool calls in your response until the task is completed. The work is done when the assigned task is finished and verified — not when the turn ends. The end of a turn is never in itself the end of the work. What is final is the completion of the assigned work — the task, the work package, the milestone, the request. An end of turn may be a milestone reached, a point where you need direction, guidance or a clarification from the user, or simply an intermediate step between two things the user asked for. Do not treat "I have stopped emitting tool calls" as "the work is done". It is not a signal about the work at all. Keep your attention on the long horizon of the assigned work rather than on the current turn. Ending a turn to ask a question is correct when you need the answer. Ending it while work you were asked to do remains untouched, and saying nothing about that, is not.
80
80
 
81
- - The checker and the run belong in the same turn. Call `check_file` and the thing that executes the code — `run_commands`, or `browser` for a page — together, not one or the other. Running it says *that* something is broken and where the parser gave up; the checker says *which line* to edit. Each is half the answer, and the half you skip is the half the turn gets spent guessing at.
82
- - A tool's report outranks your own reasoning about the same question. Where a tool has measured something — a delimiter scan naming the line to edit, a diagnostic naming a type — that is the measurement, and re-deriving it yourself is an estimate. Where the two disagree, it is the estimate that is wrong. If you doubt a report, do not re-derive it — act on it and run the result. That costs milliseconds and settles it either way.
81
+ - The checker and the run belong in the same turn. Call `check_file` and the thing that executes the code — `run_commands`, or `browser` for a page — together, not one or the other. Running it says *that* something is broken and where the parser gave up; the checker says *where*: the line the parser stops on and the lines where brackets stop pairing. Each is half the answer, and the half you skip is the half the turn gets spent guessing at.
82
+ - A tool's report outranks your own reasoning about the same question. Where a tool has measured something — a delimiter scan naming where brackets stop pairing, a diagnostic naming a type — that is the measurement, and re-deriving it yourself is an estimate. Where the two disagree, it is the estimate that is wrong. If you doubt a report, do not re-derive it — act on it and run the result. That costs milliseconds and settles it either way.
83
83
  - Run the program once, after every change you planned is in place — not after each one. The cheap check that does not execute the code is what goes after each edit; the build, the tests or the program itself goes at the end.
84
84
  - Do not re-read a file to confirm your own edit. The edit call already reports whether it landed and what changed, and that is the confirmation. Read again when the call failed, or when you need content you have not seen.
85
85
 
@@ -92,11 +92,11 @@ Obtain the contents of text or image files located at absolute paths, or retriev
92
92
 
93
93
  # tool: search_codebase
94
94
 
95
- Execute regular‑expression searches across the codebase, with support for running several independent patterns in parallel. Supply one or more query strings; when the patterns are unrelated and could be useful together, send them all in one request and combine the call with other independent tool calls in the same response. The tool is suited for locating code patterns, function definitions, class names, import statements, and similar textual elements. By default it reports at most one match per file, which tells you **which** files mention something. To discover every occurrence inside a file (including how many times a name appears and on which lines), increase `max_per_file`. Adjust `context_lines` to control how many lines are displayed before and after each match (the default is 2). Output that exceeds roughly 48 k characters per query undergoes middle‑truncation, so narrower, more specific patterns tend to yield more complete results than broad ones. Output consists of one entry per pattern: each entry names the query you submitted, returns the matching lines together with their file paths, and, if the search could not be performed, explains why. A pattern that finds no matches is considered a valid answer – the result comes back empty (not marked as failed) – and repeating the identical search will produce the same empty output.
95
+ Execute regular‑expression searches across the codebase, with support for running several independent patterns in parallel. Supply one or more query strings; when the patterns are unrelated and could be useful together, send them all in one request and combine the call with other independent tool calls in the same response. The tool is suited for locating code patterns, function definitions, class names, import statements, and similar textual elements. By default it reports at most one match per file, which tells you **which** files mention something. To discover every occurrence inside a file (including how many times a name appears and on which lines), increase `max_per_file`. Adjust `context_lines` to control how many lines are displayed before and after each match (the default is 2). Output that exceeds roughly 48 k characters per query undergoes middle‑truncation, so narrower, more specific patterns tend to yield more complete results than broad ones. Output consists of one entry per pattern: each entry names the query you submitted, returns the matching lines together with their file paths, and, if the search could not be performed, explains why. A pattern that finds no matches is considered a valid answer – the result says so and is not marked as failed – and repeating the identical search will produce the same answer. Matching ignores case: `token` finds `Token` and `TOKEN` too.
96
96
 
97
97
  # tool: fetch_web_content
98
98
 
99
- Retrieve material from URLs and analyze it according to a supplied prompt. Each request consists of a URL and a natural‑language description of the information you wish to extract. You may bundle several independent URLs in one invocation and combine it with other independent tool calls in the same response. Output consists of one entry per request: each entry identifies the URL, presents the extracted text that satisfies your prompt, and, if something went wrong, explains the failure. A successful entry names the URL and holds the prompted content as plain text.
99
+ Retrieve the text of web pages. Each request consists of a URL and a natural‑language prompt saying what you want from the page; the prompt is returned alongside the page's text for you to apply, and nothing extracts it on your behalf. You may bundle several independent URLs in one invocation and combine it with other independent tool calls in the same response. Output consists of one entry per request: each entry identifies the URL and holds the page's text (HTML as plain text, up to 50,000 characters), followed by your prompt; if something went wrong, it explains the failure. A page that is not text (a PDF, an image) is not shown: download it with `run_commands` and read it with `extract_document`.
100
100
 
101
101
  # tool: editor
102
102
 
@@ -125,7 +125,7 @@ Run shell commands. Use this to execute the program, run tests, build the projec
125
125
 
126
126
  **Do not use this for file operations when `read_files`, `editor`, `apply_patch`, `search_codebase`, `list_files`, `check_file`, or `ask_lsp` exist for that purpose.** Do not `cat` to read, `sed -i` or `echo >` to write, `grep` to search, `ls`/`find`/`dir`/`Get-ChildItem` to list files, or invoke a compiler/linter directly to check one file — the dedicated tools are faster, exact, and do not require you to parse their output. The shell is for running the program, not for inspecting or changing its source.
127
127
 
128
- The checker and the run belong in the same turn. Call `check_file` and `run_commands` (or `browser` for a page) together, not one or the other. Running it says *that* something is broken and where the parser gave up; the checker says *which line* to edit. Each is half the answer, and the half you skip is the half the turn gets spent guessing at.
128
+ The checker and the run belong in the same turn. Call `check_file` and `run_commands` (or `browser` for a page) together, not one or the other. Running it says *that* something is broken and where the parser gave up; the checker says *where*: the line the parser stops on and the lines where brackets stop pairing. Each is half the answer, and the half you skip is the half the turn gets spent guessing at.
129
129
 
130
130
  Run the program once, after every change you planned is in place — not after each one. The cheap check that does not execute the code is what goes after each edit; the build, the tests or the program itself goes at the end.
131
131
 
@@ -151,7 +151,7 @@ Pass every file you want checked in one request using the `paths` argument, whic
151
151
  Plain text, grouped by file. Each problem appears on its own line as `file:line:column` followed by its severity and message. A file with no problems reports so in a single line. Seeing problems listed confirms the tool is working, not failing. If the tool cannot run (for example, because no language server is available for the given file type), it returns a failure message explaining why.
152
152
 
153
153
  **Delimiter scan**
154
- When brackets do not match, a `Delimiter scan` section names the line to edit and how many brackets that line is out by—one line per place the trouble starts, since a file can be broken in several spots at once. Work through every listed line before re‑checking rather than re‑checking after each one. A parse error is always reported where the parser gave up (the closing bracket); the line named here is the one the error cannot specify. Trust those lines over manual bracket counts because the scan skips strings, comments, and regex literals, which simple character counting does not. The check runs regardless of editor reports, so it may appear beneath a file the editor deemed clean—no language server checks the script inside an `.html` file, and here this is the sole report you will get.
154
+ When brackets do not match, a `Delimiter scan` section names the lines where brackets stop pairing up and how many each line is out by—one line per place the trouble starts, since a file can be broken in several spots at once. Work through every listed line before re‑checking rather than re‑checking after each one. A parse error is reported where the parser gave up, which is often but not always where the mistake is: a bracket left open earlier makes it give up later, and the scan names that opener. Read the code at those lines instead of counting brackets by hand: a count says where brackets stop pairing, not which bracket is wrong, and the scan skips strings, comments, and regex literals, which simple character counting does not. The check runs regardless of editor reports, so it may appear beneath a file the editor deemed clean—no language server checks the script inside an `.html` file, and here this is the sole report you will get.
155
155
 
156
156
  # tool: list_files
157
157
  {{DEFAULT}}
@@ -170,11 +170,11 @@ Actions:
170
170
 
171
171
  Every action reports the console messages and uncaught errors produced while it ran, so a syntax error, a failed fetch or a null dereference comes back as text you can act on. `[error]` and `[Page Error]` lines are real failures. A page that says nothing printed nothing — that is a pass, not a failed call, and for a local file it is checked: a silent console over a file that does not parse is reported as the failure it is, not as a pass.
172
172
 
173
- A parse error from the browser names no line, because the script never ran. For a local file a `Delimiter scan` section follows it and names the line to edit and how many brackets that line is out by — one line per place the trouble starts, since a file can be broken in several spots at once. Fix every line it lists in one edit and reload once, rather than one edit and one reload per line. Edit those lines instead of counting brackets yourself: counting a whole file by hand costs more thinking than you have, and the scan skips strings, comments and regex literals, which counting does not.
173
+ A parse error from the browser often names no line. For a local file a `Delimiter scan` section follows it and names the lines where brackets stop pairing up and how many each line is out by — one line per place the trouble starts, since a file can be broken in several spots at once. Fix every line it lists in one edit and reload once, rather than one edit and one reload per line. Read the code at those lines instead of counting brackets yourself: counting a whole file by hand costs more thinking than you have, and the scan skips strings, comments and regex literals, which counting does not.
174
174
 
175
175
  The browser stays open between calls, so `open` once and then interact. Only one page is open at a time; `open` again to go elsewhere.
176
176
 
177
- The checker and the run belong in the same turn. Call `check_file` and `browser` together, not one or the other. Running it says *that* something is broken and where the parser gave up; the checker says *which line* to edit. Each is half the answer, and the half you skip is the half the turn gets spent guessing at.
177
+ The checker and the run belong in the same turn. Call `check_file` and `browser` together, not one or the other. Running it says *that* something is broken and where the parser gave up; the checker says *where*: the line the parser stops on and the lines where brackets stop pairing. Each is half the answer, and the half you skip is the half the turn gets spent guessing at.
178
178
 
179
179
  # tool: ask_lsp
180
180
  Ask the language servers — the LSP — about a symbol. If you are reaching for an LSP tool or an MCP server that wraps one, this is it: the same protocol, already running against this workspace and its open files, with no server to start. This answers questions a text search cannot, because it understands the code: it distinguishes a definition from a mention, and this class's method from another class's method of the same name.
@@ -205,7 +205,7 @@ How to address a symbol:
205
205
  - If you know the exact position: `path`, `line` and `character` (both 1-based).
206
206
  - If you do not know the file: `symbol` alone, with `operation: "workspace_symbols"`.
207
207
 
208
- Output: plain text, one result per line as `file:line:column` followed by that source line, so you can go straight to the one you want rather than reading each candidate. `hover` returns the signature and documentation as text instead, and `document_symbols` and `workspace_symbols` name each symbol's kind. An empty answer is definite for `definition`, `references`, `implementations`, `type_definition`, `callers` and `hover`: the server resolved the symbol and nothing matched, so a text search will not find more. `workspace_symbols` is the one exception — it reads a project index that does not cover script embedded in `.html` or other template files, so an empty answer there is not proof. Ask `document_symbols` for the file if you know it, or `search_codebase` if you do not. If the answer opens with a line saying the file does not parse, the server is guessing past the fault: fix the syntax with `check_file` first.
208
+ Output: plain text, one result per line as `file:line:column` followed by that source line, so you can go straight to the one you want rather than reading each candidate. `hover` returns the signature and documentation as text instead, and `document_symbols` and `workspace_symbols` name each symbol's kind. An empty answer is definite for `definition`, `references`, `implementations`, `type_definition`, `callers` and `hover`: the server resolved the symbol and found nothing within what it can see. Uses it cannot resolve statically (`obj[name]`, a name built in a string), files it does not load and other languages are invisible to it, so a text search can still find more — run one when the answer decides an edit. `workspace_symbols` is the one exception — it reads a project index that does not cover script embedded in `.html` or other template files, so an empty answer there is not proof. Ask `document_symbols` for the file if you know it, or `search_codebase` if you do not. If the answer opens with a line saying the file does not parse, the server is guessing past the fault: fix the syntax with `check_file` first.
209
209
 
210
210
  # tool: generate_image
211
211
  {{DEFAULT}}
@@ -145,8 +145,8 @@ Do not describe an intention ("I will now read...") without actually making the
145
145
  A task is not complete until you have verified the result.
146
146
 
147
147
  1. **Read Back**: Do not re-read a file to confirm your own edit. The `editor` call already reports whether the edit landed and what changed, and that is the confirmation. Read again only when the call failed, or when you need content you have not seen.
148
- 2. **Checker and Run Together**: Call `check_file` and the thing that executes the code — `run_commands`, or `browser` for a page — in the **same turn**, not one or the other. Running it says *that* something is broken and where the parser gave up; the checker says *which line* to edit. Each is half the answer, and the half you skip is the half you will spend the turn guessing at.
149
- 3. **Trust the Measurement**: A tool's report outranks your own reasoning about the same question. Where a tool has measured something — a delimiter scan naming the line to edit, a diagnostic naming a type — that is the measurement, and re-deriving it yourself is an estimate. Where the two disagree, it is the estimate that is wrong. If you doubt a report, do not re-derive it — act on it and run the result. That costs milliseconds and settles it either way.
148
+ 2. **Checker and Run Together**: Call `check_file` and the thing that executes the code — `run_commands`, or `browser` for a page — in the **same turn**, not one or the other. Running it says *that* something is broken and where the parser gave up; the checker says *where*: the line the parser stops on and the lines where brackets stop pairing. Each is half the answer, and the half you skip is the half you will spend the turn guessing at.
149
+ 3. **Trust the Measurement**: A tool's report outranks your own reasoning about the same question. Where a tool has measured something — a delimiter scan naming where brackets stop pairing, a diagnostic naming a type — that is the measurement, and re-deriving it yourself is an estimate. Where the two disagree, it is the estimate that is wrong. If you doubt a report, do not re-derive it — act on it and run the result. That costs milliseconds and settles it either way.
150
150
  4. **One Edit, One Check**: Make one edit, then run the check before making the next. `check_file` after every edit, and the thing that executes the code — the build, the tests, or the program — after each one too, not saved for the end. Running it after every change costs a few seconds and tells you which edit broke what. Running it once after six tells you only that something among the six is wrong, and leaves you six things to undo to find out which.
151
151
  5. **Symbol Queries**: If asked "where is X defined?" or "what implements Y?", use `ask_lsp`. Do not run a text search and manually analyze hits. The language server knows the exact answer.
152
152
  6. **Completion Signal**: Do not treat "stopping tool calls" as "work done." Only stop when the user's request is fully satisfied and verified. If you need clarification, ask (`ask_question`). If the work is done, summarize and stop. If work remains, continue.
@@ -173,15 +173,15 @@ Perform regex pattern searches across the codebase. This is the primary tool for
173
173
  - **Parallelism**: Send all independent patterns in the `queries` array in one call.
174
174
  - **Limitations**: Output is truncated if it exceeds ~48k characters. Narrow patterns are better.
175
175
  - **Arguments**: `queries` is an array of strings. Optional: `context_lines` (integer), `max_per_file` (integer).
176
- - **Output**: One entry per pattern, in the order sent. Each entry is named by the pattern and holds the matching lines with their file paths. A pattern that matched nothing comes back empty, not failed; that is an answer, and re-running it will not change it. A failed entry says that it failed and why.
176
+ - **Output**: One entry per pattern, in the order sent. Each entry is named by the pattern and holds the matching lines with their file paths. A pattern that matched nothing says so and is not marked failed; that is an answer, and re-running it will not change it. Matching ignores case: `token` finds `Token` and `TOKEN` too. A failed entry says that it failed and why.
177
177
 
178
178
  # tool: fetch_web_content
179
179
 
180
- Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content.
180
+ Fetch the text of web pages. Use for retrieving documentation, API references, or any web content.
181
181
 
182
182
  - **Parallelism**: Fetch independent URLs together in one call by populating the `requests` array.
183
- - **Arguments**: `requests` is an array of objects: `{url: string, prompt: string}`. The prompt describes what to extract.
184
- - **Output**: One entry per request, in the order requested. Each entry is named by the URL and holds what was extracted from that page for your prompt, as text. A failed entry says that it failed and why.
183
+ - **Arguments**: `requests` is an array of objects: `{url: string, prompt: string}`. The prompt says what you want from the page; it is returned with the page's text for you to apply, and nothing extracts it for you.
184
+ - **Output**: One entry per request, in the order requested. Each entry is named by the URL and holds the page's text (HTML as plain text, up to 50,000 characters), followed by your prompt. A page that is not text (a PDF, an image) is not shown: download it with `run_commands` and read it with `extract_document`. A failed entry says that it failed and why.
185
185
 
186
186
  # tool: editor
187
187
 
@@ -291,7 +291,7 @@ Pass every path you need checked in the `paths` array in a single call.
291
291
 
292
292
  **Output:** Plain text. One section per file you named. Each problem appears on its own line as `file:line:column severity message`. A clean file states that in one line. Listing problems (or listing none) is the tool working correctly. If the result is empty and you expected errors, or if the project uses a checker the LSP does not run, invoke that checker with `run_commands`. This tool never runs tests or builds; those are always `run_commands`.
293
293
 
294
- **Delimiter scan:** When brackets do not match, a `Delimiter scan` section follows the main report. It names the line to edit and how many brackets that line is out by, one line per trouble spot. Work through every line it lists before re-checking, rather than re-checking after each one. A parse error is reported where the parser gave up (the closing bracket); the line the scan names is the one the error cannot name. Trust these lines over counting brackets yourself — the scan skips strings, comments, and regex literals, which manual counting does not. The scan runs even when the editor reports nothing, making it the only diagnostic available for script inside `.html` files. If an edit clears the first crossing and the scan reports that it re-checked the edit, treat that as a measured fact: the system applied your change to a copy, scanned it, and confirmed the result. Make that edit.
294
+ **Delimiter scan:** When brackets do not match, a `Delimiter scan` section follows the main report. It names the lines where brackets stop pairing up and how many each line is out by, one line per trouble spot. Work through every line it lists before re-checking, rather than re-checking after each one. A parse error is reported where the parser gave up, which is often but not always where the mistake is: a bracket left open earlier makes it give up later, and the scan names that opener. Read the code at those lines instead of counting brackets yourself: a count says where brackets stop pairing, not which bracket is wrong, and the scan skips strings, comments, and regex literals, which manual counting does not. The scan runs even when the editor reports nothing, making it the only diagnostic available for script inside `.html` files. If an edit clears the first crossing and the scan reports that it re-checked the edit, treat that as a measured fact: the system applied that change to a copy and the parser got further with it. Check that it closes the block you meant, then make it.
295
295
 
296
296
  **The measurement, not an opinion:** This report is the ground truth; your own bracket count is an estimate. Where they disagree, your count is wrong. If you doubt the report, do not recount: make the edit it names and run the program. That settles it in milliseconds.
297
297
 
@@ -300,7 +300,7 @@ List files in the workspace. Use this rather than `ls`, `dir` or `find` through
300
300
 
301
301
  - **Usage**: Call it whenever you need to know what exists, or where a file lives, before reading anything.
302
302
  - **Arguments**: `path` is one directory to list (absolute, or relative to the workspace root; omit for the root). `pattern` is a glob searched workspace-wide, e.g. `**/*.html` — given this, `path` is ignored. `max_results` caps the listing.
303
- - **Scope**: Only the folders the user opened. A path outside them is refused. `node_modules`, `.git` and build output are excluded automatically.
303
+ - **Scope**: Only the folders the user opened. A path outside them is refused. A `pattern` search skips `node_modules`, `.git` and the user's other search excludes unless the pattern names one; a `path` listing shows them, marked.
304
304
  - **Output**: Directories first with a trailing `/`, then files with sizes.
305
305
 
306
306
  This finds files by name. To find them by their contents, use `search_codebase`.
@@ -314,7 +314,7 @@ Open a page in a real browser and report its console output and uncaught errors.
314
314
  - **Output**: The console messages and uncaught errors produced while the action ran. `[error]` and `[Page Error]` lines are real failures. A page that printed nothing is a pass, not a failed call.
315
315
  - **Session**: The browser stays open between calls, so `open` once and then interact. `close` when finished.
316
316
  A parse error from the browser names no line. For a local file a `Delimiter scan` section follows it and names the *opening* bracket the parser could not match, one line per place the trouble starts — fix every line it lists in one edit rather than one reload per line. That section is the measurement and your own bracket count is the estimate; where they disagree, edit the line it names and reload rather than counting to decide which to believe.
317
- Call this and `check_file` in the **same turn**, not one or the other. The page says whether it actually runs and where the parser gave up; `check_file` names the line to edit. Take one without the other and you are working from half a report.
317
+ Call this and `check_file` in the **same turn**, not one or the other. The page says whether it actually runs and where the parser gave up; `check_file` names where the parser stops and where brackets stop pairing. Take one without the other and you are working from half a report.
318
318
  {{DEFAULT}}
319
319
 
320
320
  # tool: ask_lsp
@@ -5,7 +5,7 @@ import{execFile as sn}from"node:child_process";import{basename as To,resolve as
5
5
  ...and ${l.length-5} more`:"";throw new _("dirty_worktree",`Commit and push local changes before handing off to cloud. Uncommitted files are not transferred.
6
6
 
7
7
  ${m}${y}`)}let i;try{i=await t.symbolicBranch()}catch(l){let m=Q(l)===1,y=K(l),w=m?"Cloud handoff requires a checked-out branch; detached HEAD is not supported.":"Could not inspect the current Git branch.";throw new _(m?"detached_head":"git_command_failed",y?`${w} (${y})`:w,{cause:l})}if(!i)throw new _("detached_head","Cloud handoff requires a checked-out branch; detached HEAD is not supported.");let[r,a,d]=await Promise.all([O(()=>t.branchRemote(i),"missing_upstream",`Branch ${i} has no upstream. Push it with -u before handing off.`),O(()=>t.branchMergeRef(i),"missing_upstream",`Branch ${i} has no upstream. Push it with -u before handing off.`),O(t.headSha,"git_command_failed","Could not resolve the current commit.")]);if(!r||r==="."||!a.startsWith("refs/heads/"))throw new _("missing_upstream",`Branch ${i} has no remote branch upstream. Push it with -u before handing off.`);let u=a.slice(11),f=r;if(!Ze(r))try{f=await t.remoteUrl(r)}catch{throw new _("missing_upstream","Could not resolve the upstream remote.")}let c=Ze(f);if(!c)throw new _("unsupported_remote","Cloud handoff currently requires a github.com upstream remote.");let h;try{h=await t.remoteRefs(r,a)}catch(l){let m=Q(l)===2,y=m?`The upstream branch ${u} was not found. Push it before handing off.`:"Could not verify the remote branch. Check your network and GitHub authentication, then try again.";throw new _(m?"remote_branch_missing":"git_command_failed",y)}let p=cn(h,u);if(!p)throw new _("remote_branch_missing",`The upstream branch ${u} was not found. Push it before handing off.`);if(p.toLowerCase()!==d.toLowerCase())throw new _("unpushed_commits",`Local HEAD does not match the upstream branch ${u}. Push the current commit before handing off.`);return{repoUrl:c,branch:u,headSha:d,...s?{workspaceRelativePath:s}:{}}}function fe(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function x(e){if(typeof e!=="string")return;return e.trim()||void 0}function ln(e){return typeof e==="string"&&e.length>0?e:void 0}function pn(e){let t=x(e.repoUrl),n=x(e.branch),s=x(e.headSha),o=x(e.modelId);if(!t||!n||!s||!o)throw Error("Cloud handoff fingerprint fields cannot be empty.");let i=x(e.organizationId),r=ln(e.workspaceRelativePath),a=e.mode;return{repoUrl:t,branch:n,headSha:s,modelId:o,...i?{organizationId:i}:{},...r?{workspaceRelativePath:r}:{},...a?{mode:a}:{}}}function Do(e,t){return e!==void 0&&t!==void 0&&e.repoUrl===t.repoUrl&&e.branch===t.branch&&e.headSha.toLowerCase()===t.headSha.toLowerCase()&&e.modelId===t.modelId&&e.organizationId===t.organizationId&&e.workspaceRelativePath===t.workspaceRelativePath&&e.mode===t.mode}function fn(e){let t=fe(e);if(!t||typeof t.repoUrl!=="string"||typeof t.branch!=="string"||typeof t.headSha!=="string"||typeof t.modelId!=="string")return;try{return pn({repoUrl:t.repoUrl,branch:t.branch,headSha:t.headSha,modelId:t.modelId,...typeof t.organizationId==="string"?{organizationId:t.organizationId}:{},...typeof t.workspaceRelativePath==="string"?{workspaceRelativePath:t.workspaceRelativePath}:{},...t.mode==="plan"||t.mode==="yolo"||t.mode==="zen"?{mode:t.mode}:{}})}catch{return}}function Bo(e){let t=fe(fe(e)?.handoff);if(!t)return;let n=x(t.toCloudSessionId),s=x(t.handedOffAt),o=t.status;if(!n||!s||o!=="pending"&&o!=="complete")return;let i=x(t.innerSessionId),r=x(t.dashboardUrl),a=fn(t.fingerprint);return{toCloudSessionId:n,handedOffAt:s,status:o,...i?{innerSessionId:i}:{},...r?{dashboardUrl:r}:{},...a?{fingerprint:a}:{}}}function qo(e,t){return{...e??{},handoff:t}}function No(e){let{handoff:t,cloudHandoffIntent:n,cloudHandoffSeedDispatched:s,...o}=e??{};return o}function $o(e,t){let n=t.trim();if(!n)throw Error("Cloud session id cannot be empty.");let s=new URL("/agents",e);return s.searchParams.set("sessionId",n),s.toString()}function et(e){return e.map((t)=>{let n=t&&typeof t==="object"?t:{};return{role:n.role,content:n.content}})}function he(e,t){return e.length===t.length&&JSON.stringify(et(e))===JSON.stringify(et(t))}class me extends Error{constructor(e,t){super(`Cloud transcript verification failed (local ${e} messages, cloud ${t}).`);this.name="CloudHandoffTranscriptMismatchError"}}import{randomUUID as hn}from"node:crypto";import{decodeJwtPayload as mn}from"@cerebriline/shared";var gn=610000,yn=3000,B=15000,bn="CLOUD_SESSION_ERROR:",st="__cline_create_request__:";function ot(e){return(e.trim().split(`
8
- `)[0]??"").trim().slice(0,72)}class g extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${bn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class it extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function be(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function wn(e){return`${st}${e}`.slice(0,255)}function tt(e){return e?.startsWith(st)===!0}function we(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function ge(e){let t=mn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function nt(e){return new Promise((t,n)=>{if(e.aborted){n(e.reason);return}let s=()=>{clearTimeout(o),n(e.reason)},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},yn);e.addEventListener("abort",s,{once:!0})})}function vn(e,t){if(e&&typeof e==="object"){let n=e.error;if(typeof n==="string"&&n.trim())return n.trim()}return t}function ye(e,t,n,s){let o=vn(t,`Cloud session request failed (${e})`);if(e===401)return new g("authentication_required",o);if(e===404)return new g("session_not_found",o);if(e===410)return new g("session_expired",o);if(e===412)return new g("github_not_connected",o,s??`${be(n)}/dashboard/integrations`);if(e===403&&o.trim().toLowerCase()==="forbidden")return new g("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,e);return new g("request_failed",o,void 0,e)}class Cn{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e;this.apiBaseUrl=be(e.apiBaseUrl),this.appBaseUrl=be(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??gn}async request(e,t={},n,s,o){let i=!1,r;while(!0){let a;try{a=typeof s==="string"?s:await this.options.getAuthToken()}catch(f){if(r)throw ye(401,void 0,this.appBaseUrl,n);throw f}if(!a?.trim())throw new g("authentication_required","Sign in to Cline before starting a cloud session.");if(a.trim()===r)throw new g("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof s==="object"){if(s.subject?ge(a.trim())!==s.subject:a.trim()!==s.token)throw new g("authentication_required","The signed-in account changed during cloud session creation.");s.token=a.trim()}o?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(B),headers:{Accept:"application/json",Authorization:`Bearer ${a.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),u=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof s==="object"&&!i&&s.subject){i=!0,r=a.trim();continue}throw ye(d.status,u,this.appBaseUrl,n)}return u?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,n=!1){let s=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${s}`,{},void 0,t)??[]).flatMap((i)=>{if(!i||typeof i!=="object"||typeof i.id!=="string")return[];return[{...i,title:!n&&tt(i.title)?void 0:i.title,repoContext:i.repoContext&&typeof i.repoContext==="object"?i.repoContext:{},metadata:{...i.metadata&&typeof i.metadata==="object"?i.metadata:{},...!n&&tt(i.title)?{createRequestTitle:i.title}:{}}}]})}async listRepositories(e){let t=e?.trim(),n=t?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,s=t?`/api/v1/organizations/${encodeURIComponent(t)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let o=await this.request(s)??[];return{connected:!0,connectUrl:n,repositories:o.flatMap((i)=>{let r=Number(i.id),a=String(i.html_url??i.clone_url??"").trim();if(!Number.isSafeInteger(r)||r<=0||!a)return[];let d=String(i.name??"").trim();return[{id:r,name:d,fullName:String(i.full_name??(d||a)).trim(),url:a,defaultBranch:String(i.default_branch??"").trim()}]})}}catch(o){if(o instanceof g&&o.code==="session_not_found")return{connected:!1,connectUrl:n,repositories:[]};throw o}}async listBranches(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new g("request_failed","Select a GitHub repository before loading branches.");let s=t?.trim(),o=s?`/api/v1/organizations/${encodeURIComponent(s)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,i=new URLSearchParams,r=n.query?.trim(),a=n.cursor?.trim();if(r)i.set("query",r);if(a)i.set("cursor",a);let d=i.size>0?`${o}?${i}`:o;try{let u=await this.request(d),f=Array.isArray(u)?u:Array.isArray(u?.items)?u.items:[],c=r?.toLowerCase();return{available:!0,branches:f.flatMap((h)=>{let p=String(h.name??"").trim();return p&&(!Array.isArray(u)||!c||p.toLowerCase().includes(c))?[p]:[]}),nextToken:Array.isArray(u)?"":String(u?.nextToken??"").trim()}}catch(u){if(u instanceof g&&u.code==="session_not_found")return{available:!1,branches:[]};throw u}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(B)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new g("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new g("authentication_required","Sign in to Cline before starting a cloud session.");let n={token:t,subject:ge(t)},s=wn(e.requestId?.trim()||hn()),o=e.handoff?`${n.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new g("request_failed","A stable request id is required for cloud handoff creation.");let i=async()=>(await this.listWithToken(e.organizationId??void 0,n,!0)).filter((c)=>c.title===s&&c.repoContext.repoUrl===e.repoUrl&&c.metadata.modelId===e.modelId&&(!e.branch?.trim()||c.repoContext.branch===e.branch.trim())),r=async(c)=>{if(c.status==="failed"||c.expiredAt&&Date.parse(c.expiredAt)<=Date.now()){let p=new g(c.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(c.id,n)}catch(l){if(!(l instanceof g&&(l.code==="session_not_found"||l.code==="session_expired")))throw AggregateError([p,l],"The unusable recovered cloud handoff workspace could not be removed.")}if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.delete(o);throw await e.handoff?.onOuterSessionRemoved?.(c.id),p}await e.handoff?.onOuterSessionCreated(c.id,{created:!1});let h={sessionId:c.id,status:c.status,sandboxUrl:c.sandboxUrl,cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,h);return h};if(o){let c=await i();if(c.length>1)throw new g("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(c[0])return await r(c[0]);let h=this.completedHandoffCreates.get(o);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,n)}catch(p){if(p instanceof g&&(p.code==="session_not_found"||p.code==="session_expired"))await e.handoff?.onOuterSessionRemoved?.(h.sessionId),this.completedHandoffCreates.delete(o),this.unconfirmedHandoffCreates.delete(o);throw p}return await e.handoff?.onOuterSessionCreated(h.sessionId,{created:!1}),{...h,cleanupAuthToken:n.token}}if(this.unconfirmedHandoffCreates.has(o))throw new g("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(o)}try{await e.handoff?.onCreating()}catch(c){if(o)this.unconfirmedHandoffCreates.delete(o);throw c}let a=new AbortController,d=setTimeout(()=>a.abort(),this.createTimeoutMs),u,f=!1;try{let c=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:s,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:a.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,n,()=>{f=!0}),h=c?.sessionId?.trim();if(!h)throw new g("request_failed","The cloud session service returned no session id.");u=h,await this.persistHandoffOuterSession(e,h,n,o);let p={sessionId:h,status:c.status?.trim()||"provisioning",sandboxUrl:c.sandboxUrl?.trim()??"",cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,p);return p}catch(c){if(u)throw c;let h=!f||c instanceof g&&(c.status!==void 0&&c.status>=400&&c.status<500&&c.status!==408&&c.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(c.code));if(o&&h)throw this.unconfirmedHandoffCreates.delete(o),new it(c);if(a.signal.aborted||!(c instanceof g)||c instanceof g&&c.code==="request_failed"&&(c.status===void 0||c.status>=500||c.status===408||c.status===409)){let l=[];try{l=await i()}catch(y){if(e.handoff)throw AggregateError([c,y],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(l.length>1)throw new g("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let m=l[0];if(m){if(e.handoff)return await r(m);return{sessionId:m.id,status:m.status,sandboxUrl:m.sandboxUrl,cleanupAuthToken:n.token}}}else if(o)this.unconfirmedHandoffCreates.delete(o);throw c}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,n,s){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(o){try{await this.deleteWithAuth(t,n.token)}catch(i){if(!(i instanceof g&&(i.code==="session_not_found"||i.code==="session_expired")))throw AggregateError([o,i],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(s)this.unconfirmedHandoffCreates.delete(s);throw await e.handoff.onOuterSessionRemoved?.(t),o}}async waitUntilReady(e,t,n){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let s=await this.options.getAuthToken(),o=s?{token:s,subject:ge(s)}:void 0;while(!t.aborted){let i;try{i=await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:AbortSignal.any([t,AbortSignal.timeout(B)])},void 0,o)}catch(a){if(t.aborted)throw a;if(a instanceof g&&a.code!=="request_failed")throw a;await nt(t);continue}let r=i?.status?.trim().toLowerCase();if(n?.({phase:we(i?.phase)}),r==="ready"||r==="active")return;if(r==="failed")throw new g("session_failed",i?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(r!=="provisioning")throw new g("request_failed","The cloud session service returned an unexpected provisioning status.");await nt(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(B)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let n;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(s){if(!(s instanceof g)||s.code!=="session_not_found"&&s.code!=="session_expired")throw s;n=s}for(let[s,o]of this.completedHandoffCreates)if(o.sessionId===e)this.completedHandoffCreates.delete(s),this.unconfirmedHandoffCreates.delete(s);if(n)throw n}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new g("authentication_required","Sign in to Cline to load this session's history.");let n=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(B)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw ye(n.status,s,this.appBaseUrl);if(!s||typeof s!=="object"||!("version"in s)||s.version!==1||!("messages"in s)||!Array.isArray(s.messages))throw new g("request_failed","Invalid archived session history");return s.messages}}import{randomUUID as yo}from"node:crypto";import{posix as le}from"node:path";import{createSessionId as qs,ensureLoopbackProxyBypass as qt,isHubProtocolCompatible as Ns,resolveClineBuildEnv as $s,resolveHubCommandTimeoutMs as Ws}from"@cerebriline/shared";import js from"ws";var q={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var rt="session_not_found";class Y extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}function ve(e){return e instanceof Y||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as os}from"node:child_process";import{closeSync as is,mkdirSync as rs,openSync as as,readFileSync as ds,unlinkSync as cs}from"node:fs";import{basename as us,dirname as ls,join as ps}from"node:path";import{fileURLToPath as fs}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as hs,isBunEmbeddedModulePath as ms,isHubDaemonProcess as gs,resolveClineBuildEnv as Et,withResolvedClineBuildEnv as ys}from"@cerebriline/shared";import{createHash as kn,randomBytes as Rn}from"node:crypto";import{mkdir as Se,open as at,readFile as pt,rename as _n,rm as ke,writeFile as Pn}from"node:fs/promises";import{dirname as ft,join as Re}from"node:path";import{ensureLoopbackProxyBypass as An,isHubProtocolCompatible as Tn}from"@cerebriline/shared";import{resolveClineDataDir as N,resolveClineDir as ii}from"@cerebriline/shared/storage";var xn="CLINE_HUB_DISCOVERY_PATH",En="CLINE_HUB_BUILD_ID",Hn="CLINE_HUB_BUILD_EPOCH_MS",In=30000,Mn=15000,dt=100;function On(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Un(e){return kn("sha256").update(e).digest("hex").slice(0,12)}function Ln(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function ct(e){return new Promise((t)=>setTimeout(t,e))}function Dn(e){return`${e}.lock`}async function Bn(e){try{let t=JSON.parse(await pt(Re(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function Ce(e){await ke(e,{recursive:!0,force:!0}).catch(()=>{return})}function U(){let e=process.env[En]?.trim();if(e)return e;return"sdk-v1-9bddedd25140e23b59f323e1be32195661b948d1b05998eef4e40b70f7e54c6a".trim()||`source-${String(q.version)}`}function qn(){let e=Number(process.env[Hn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1793814281879)?1793814281879:void 0}function X(e,t=U()){let n=Tn(e);if(!n.compatible)return n;let s=e.buildId?.trim();if(!s)return{compatible:!1,reason:"missing_build"};if(s!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ut(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function lt(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((s)=>Number(s));if(n.length===0||n.some((s)=>!Number.isInteger(s)||s<0))return;return n}function Nn(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let s=e[n]??0,o=t[n]??0;if(s!==o)return s<o?-1:1}return 0}function ht(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let o=ut(e.buildEpochMs),i=ut(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let r=lt(e.coreVersion),a=lt(t.coreVersion);if(r&&a){let d=Nn(r,a);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function mt(){return{buildId:U(),buildEpochMs:qn(),coreVersion:String(q.version)}}function Z(e,t){let n=t?.self??mt(),s=X(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return ht(n,e)<=0}function gt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Un(e)}`,n=process.env[xn]?.trim()||Re(N(),"locks","hub","owners",`${On(t)}.json`);return{ownerId:t,discoveryPath:n}}async function I(e){try{let t=JSON.parse(await pt(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function yt(e,t,n){await wt(e,async()=>{let s=ft(e);await Se(s,{recursive:!0});let o=`${e}.${process.pid}.${Rn(6).toString("hex")}.tmp`,i;try{i=await at(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
8
+ `)[0]??"").trim().slice(0,72)}class g extends Error{code;detail;connectUrl;status;constructor(e,t,n,s){super(`${bn}${JSON.stringify({code:e,message:t,connectUrl:n})}`);this.code=e;this.detail=t;this.connectUrl=n;this.status=s;this.name="CloudSessionError"}}class it extends Error{constructor(e){super(e instanceof Error?e.message:"Cloud handoff creation was rejected.",{cause:e});this.name="CloudHandoffCreationRejectedError"}}function be(e){let t=e.length;while(t>0&&e[t-1]==="/")t--;return e.slice(0,t)}function wn(e){return`${st}${e}`.slice(0,255)}function tt(e){return e?.startsWith(st)===!0}function we(e){switch(e){case"provisioning":case"cloning_repo":case"agent_starting":case"ready":case"failed":return e;default:return}}function ge(e){let t=mn(e.replace(/^workos:/,""));return typeof t?.sub==="string"&&t.sub.trim()?t.sub.trim():void 0}function nt(e){return new Promise((t,n)=>{if(e.aborted){n(e.reason);return}let s=()=>{clearTimeout(o),n(e.reason)},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},yn);e.addEventListener("abort",s,{once:!0})})}function vn(e,t){if(e&&typeof e==="object"){let n=e.error;if(typeof n==="string"&&n.trim())return n.trim()}return t}function ye(e,t,n,s){let o=vn(t,`Cloud session request failed (${e})`);if(e===401)return new g("authentication_required",o);if(e===404)return new g("session_not_found",o);if(e===410)return new g("session_expired",o);if(e===412)return new g("github_not_connected",o,s??`${be(n)}/dashboard/integrations`);if(e===403&&o.trim().toLowerCase()==="forbidden")return new g("request_failed","Your active account or organization cannot create cloud sessions. Switch to Personal or another organization in Settings → Account, then try again.",void 0,e);return new g("request_failed",o,void 0,e)}class Cn{options;apiBaseUrl;appBaseUrl;fetchImpl;createTimeoutMs;unconfirmedHandoffCreates=new Set;completedHandoffCreates=new Map;constructor(e){this.options=e;this.apiBaseUrl=be(e.apiBaseUrl),this.appBaseUrl=be(e.appBaseUrl),this.fetchImpl=e.fetch??fetch,this.createTimeoutMs=e.createTimeoutMs??gn}async request(e,t={},n,s,o){let i=!1,r;while(!0){let a;try{a=typeof s==="string"?s:await this.options.getAuthToken()}catch(f){if(r)throw ye(401,void 0,this.appBaseUrl,n);throw f}if(!a?.trim())throw new g("authentication_required","Sign in to Cline before starting a cloud session.");if(a.trim()===r)throw new g("authentication_required","The cloud session credential was rejected. Sign in again.");if(typeof s==="object"){if(s.subject?ge(a.trim())!==s.subject:a.trim()!==s.token)throw new g("authentication_required","The signed-in account changed during cloud session creation.");s.token=a.trim()}o?.();let d=await this.fetchImpl(`${this.apiBaseUrl}${e}`,{...t,signal:t.signal??AbortSignal.timeout(B),headers:{Accept:"application/json",Authorization:`Bearer ${a.trim()}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}}),u=d.status===204?void 0:await d.json().catch(()=>{return});if(!d.ok){if(d.status===401&&typeof s==="object"&&!i&&s.subject){i=!0,r=a.trim();continue}throw ye(d.status,u,this.appBaseUrl,n)}return u?.data}}async list(e){return await this.listWithToken(e)}async listWithToken(e,t,n=!1){let s=e?.trim()?`?organizationId=${encodeURIComponent(e.trim())}`:"";return(await this.request(`/api/v1/session${s}`,{},void 0,t)??[]).flatMap((i)=>{if(!i||typeof i!=="object"||typeof i.id!=="string")return[];return[{...i,title:!n&&tt(i.title)?void 0:i.title,repoContext:i.repoContext&&typeof i.repoContext==="object"?i.repoContext:{},metadata:{...i.metadata&&typeof i.metadata==="object"?i.metadata:{},...!n&&tt(i.title)?{createRequestTitle:i.title}:{}}}]})}async listRepositories(e){let t=e?.trim(),n=t?`${this.appBaseUrl}/dashboard/organization/integrations`:`${this.appBaseUrl}/dashboard/integrations`,s=t?`/api/v1/organizations/${encodeURIComponent(t)}/integrations/github/repositories`:"/api/v1/integrations/github/repositories";try{let o=await this.request(s)??[];return{connected:!0,connectUrl:n,repositories:o.flatMap((i)=>{let r=Number(i.id),a=String(i.html_url??i.clone_url??"").trim();if(!Number.isSafeInteger(r)||r<=0||!a)return[];let d=String(i.name??"").trim();return[{id:r,name:d,fullName:String(i.full_name??(d||a)).trim(),url:a,defaultBranch:String(i.default_branch??"").trim()}]})}}catch(o){if(o instanceof g&&o.code==="session_not_found")return{connected:!1,connectUrl:n,repositories:[]};throw o}}async listBranches(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new g("request_failed","Select a GitHub repository before loading branches.");let s=t?.trim(),o=s?`/api/v1/organizations/${encodeURIComponent(s)}/integrations/github/repositories/${e}/branches`:`/api/v1/integrations/github/repositories/${e}/branches`,i=new URLSearchParams,r=n.query?.trim(),a=n.cursor?.trim();if(r)i.set("query",r);if(a)i.set("cursor",a);let d=i.size>0?`${o}?${i}`:o;try{let u=await this.request(d),f=Array.isArray(u)?u:Array.isArray(u?.items)?u.items:[],c=r?.toLowerCase();return{available:!0,branches:f.flatMap((h)=>{let p=String(h.name??"").trim();return p&&(!Array.isArray(u)||!c||p.toLowerCase().includes(c))?[p]:[]}),nextToken:Array.isArray(u)?"":String(u?.nextToken??"").trim()}}catch(u){if(u instanceof g&&u.code==="session_not_found")return{available:!1,branches:[]};throw u}}async status(e,t={}){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(B)]):void 0},void 0,t.authToken)}async create(e){if(e.handoff&&typeof e.handoff.onCreating!=="function")throw new g("request_failed","Cloud handoff requires an onCreating callback to persist creation intent before dispatch.");let t=(await this.options.getAuthToken())?.trim();if(!t)throw new g("authentication_required","Sign in to Cline before starting a cloud session.");let n={token:t,subject:ge(t)},s=wn(e.requestId?.trim()||hn()),o=e.handoff?`${n.subject??t}/${e.organizationId??""}/${e.requestId?.trim()??""}`:void 0;if(e.handoff&&!e.requestId?.trim())throw new g("request_failed","A stable request id is required for cloud handoff creation.");let i=async()=>(await this.listWithToken(e.organizationId??void 0,n,!0)).filter((c)=>c.title===s&&c.repoContext.repoUrl===e.repoUrl&&c.metadata.modelId===e.modelId&&(!e.branch?.trim()||c.repoContext.branch===e.branch.trim())),r=async(c)=>{if(c.status==="failed"||c.expiredAt&&Date.parse(c.expiredAt)<=Date.now()){let p=new g(c.status==="failed"?"session_failed":"session_expired","The recovered cloud handoff workspace is no longer usable.");try{await this.deleteWithAuth(c.id,n)}catch(l){if(!(l instanceof g&&(l.code==="session_not_found"||l.code==="session_expired")))throw AggregateError([p,l],"The unusable recovered cloud handoff workspace could not be removed.")}if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.delete(o);throw await e.handoff?.onOuterSessionRemoved?.(c.id),p}await e.handoff?.onOuterSessionCreated(c.id,{created:!1});let h={sessionId:c.id,status:c.status,sandboxUrl:c.sandboxUrl,cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,h);return h};if(o){let c=await i();if(c.length>1)throw new g("request_failed","Cloud handoff creation is ambiguous; inspect your cloud session list before continuing.");if(c[0])return await r(c[0]);let h=this.completedHandoffCreates.get(o);if(h){try{await this.request(`/api/v1/session/${encodeURIComponent(h.sessionId)}/status`,{},void 0,n)}catch(p){if(p instanceof g&&(p.code==="session_not_found"||p.code==="session_expired"))await e.handoff?.onOuterSessionRemoved?.(h.sessionId),this.completedHandoffCreates.delete(o),this.unconfirmedHandoffCreates.delete(o);throw p}return await e.handoff?.onOuterSessionCreated(h.sessionId,{created:!1}),{...h,cleanupAuthToken:n.token}}if(this.unconfirmedHandoffCreates.has(o))throw new g("request_failed","Cloud handoff creation is still unconfirmed. Recover the original request before creating another workspace.");this.unconfirmedHandoffCreates.add(o)}try{await e.handoff?.onCreating()}catch(c){if(o)this.unconfirmedHandoffCreates.delete(o);throw c}let a=new AbortController,d=setTimeout(()=>a.abort(),this.createTimeoutMs),u,f=!1;try{let c=await this.request("/api/v1/session",{method:"POST",body:JSON.stringify({modelId:e.modelId,repoUrl:e.repoUrl,...e.sandboxType?{sandboxType:e.sandboxType}:{},title:s,...e.branch?.trim()?{branch:e.branch.trim()}:{},...e.organizationId?.trim()?{organizationId:e.organizationId.trim()}:{}}),signal:a.signal},e.organizationId?.trim()?`${this.appBaseUrl}/dashboard/organization/integrations`:void 0,n,()=>{f=!0}),h=c?.sessionId?.trim();if(!h)throw new g("request_failed","The cloud session service returned no session id.");u=h,await this.persistHandoffOuterSession(e,h,n,o);let p={sessionId:h,status:c.status?.trim()||"provisioning",sandboxUrl:c.sandboxUrl?.trim()??"",cleanupAuthToken:n.token};if(o)this.unconfirmedHandoffCreates.delete(o),this.completedHandoffCreates.set(o,p);return p}catch(c){if(u)throw c;let h=!f||c instanceof g&&(c.status!==void 0&&c.status>=400&&c.status<500&&c.status!==408&&c.status!==409||["authentication_required","github_not_connected","session_not_found","session_expired"].includes(c.code));if(o&&h)throw this.unconfirmedHandoffCreates.delete(o),new it(c);if(a.signal.aborted||!(c instanceof g)||c instanceof g&&c.code==="request_failed"&&(c.status===void 0||c.status>=500||c.status===408||c.status===409)){let l=[];try{l=await i()}catch(y){if(e.handoff)throw AggregateError([c,y],"Cloud handoff creation is unconfirmed and its session list could not be checked.")}if(l.length>1)throw new g("request_failed","Cloud session creation had an ambiguous result. Check your cloud session list before trying again.");let m=l[0];if(m){if(e.handoff)return await r(m);return{sessionId:m.id,status:m.status,sandboxUrl:m.sandboxUrl,cleanupAuthToken:n.token}}}else if(o)this.unconfirmedHandoffCreates.delete(o);throw c}finally{clearTimeout(d)}}async persistHandoffOuterSession(e,t,n,s){if(!e.handoff)return;try{await e.handoff.onOuterSessionCreated(t,{created:!0})}catch(o){try{await this.deleteWithAuth(t,n.token)}catch(i){if(!(i instanceof g&&(i.code==="session_not_found"||i.code==="session_expired")))throw AggregateError([o,i],`Cloud session ${t} was created but its recovery record could not be saved or its sandbox removed.`)}if(s)this.unconfirmedHandoffCreates.delete(s);throw await e.handoff.onOuterSessionRemoved?.(t),o}}async waitUntilReady(e,t,n){t=AbortSignal.any([t,AbortSignal.timeout(this.createTimeoutMs)]);let s=await this.options.getAuthToken(),o=s?{token:s,subject:ge(s)}:void 0;while(!t.aborted){let i;try{i=await this.request(`/api/v1/session/${encodeURIComponent(e)}/status`,{signal:AbortSignal.any([t,AbortSignal.timeout(B)])},void 0,o)}catch(a){if(t.aborted)throw a;if(a instanceof g&&a.code!=="request_failed")throw a;await nt(t);continue}let r=i?.status?.trim().toLowerCase();if(n?.({phase:we(i?.phase)}),r==="ready"||r==="active")return;if(r==="failed")throw new g("session_failed",i?.statusReason?.trim()||"The cloud sandbox could not be prepared.");if(r!=="provisioning")throw new g("request_failed","The cloud session service returned an unexpected provisioning status.");await nt(t)}throw t.reason}async resume(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}/resume`,{method:"POST",signal:t?AbortSignal.any([t,AbortSignal.timeout(B)]):void 0})}async delete(e,t){await this.deleteWithAuth(e,t)}async deleteWithAuth(e,t){let n;try{await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"DELETE"},void 0,t)}catch(s){if(!(s instanceof g)||s.code!=="session_not_found"&&s.code!=="session_expired")throw s;n=s}for(let[s,o]of this.completedHandoffCreates)if(o.sessionId===e)this.completedHandoffCreates.delete(s),this.unconfirmedHandoffCreates.delete(s);if(n)throw n}async updateTitle(e,t){return await this.request(`/api/v1/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({title:t})})}async history(e){let t=await this.options.getAuthToken();if(!t?.trim())throw new g("authentication_required","Sign in to Cline to load this session's history.");let n=await this.fetchImpl(`${this.apiBaseUrl}/api/v1/session/${encodeURIComponent(e)}/history`,{headers:{Accept:"application/json",Authorization:`Bearer ${t.trim()}`},signal:AbortSignal.timeout(B)});if(n.status===404)return null;let s=await n.json().catch(()=>{return});if(!n.ok)throw ye(n.status,s,this.appBaseUrl);if(!s||typeof s!=="object"||!("version"in s)||s.version!==1||!("messages"in s)||!Array.isArray(s.messages))throw new g("request_failed","Invalid archived session history");return s.messages}}import{randomUUID as yo}from"node:crypto";import{posix as le}from"node:path";import{createSessionId as qs,ensureLoopbackProxyBypass as qt,isHubProtocolCompatible as Ns,resolveClineBuildEnv as $s,resolveHubCommandTimeoutMs as Ws}from"@cerebriline/shared";import js from"ws";var q={name:"@cerebriline/core",description:"Cline Core SDK for Node Runtime",version:"0.0.92",repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"},"./remote/helper-entry":{types:"./dist/remote/remote-helper-entry.d.ts",import:"./dist/remote/remote-helper-entry.js"},"./cloud":{types:"./dist/cloud/index.d.ts",import:"./dist/cloud/index.js"},"./remote/helper":{types:"./dist/remote/remote-helper.d.ts",import:"./dist/remote/remote-helper.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json && bun run ./scripts/verify-runtime-build-id.ts",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:compaction":"bun --conditions=development run scripts/compact-session.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cerebriline/agents":"workspace:*","@cerebriline/llms":"workspace:*","@cerebriline/shared":"workspace:*","@joplin/turndown-plugin-gfm":"1.0.68","@lingo-reader/epub-parser":"0.4.6","@lingo-reader/fb2-parser":"0.4.6","@lingo-reader/mobi-parser":"0.4.6","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0","@tesseract.js-data/eng":"1.0.0",cfb:"1.2.2","fast-png":"8.0.0",jiti:"^2.7.0",nanoid:"^5.1.7","node-machine-id":"^1.1.12",officeparser:"8.0.0","pdfjs-dist":"6.2.108","simple-git":"3.36.0","tesseract.js":"7.0.0","tree-sitter-wasms":"^0.1.12",turndown:"7.2.0","web-tree-sitter":"^0.25.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/turndown":"^5.0.6","@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["assets","dist","scripts/document-reader-assets.mjs","!dist/**/*.d.ts.map"]};var rt="session_not_found";class Y extends Error{sessionId;code="session_not_found";constructor(e,t){super(t??(e?`session not found: ${e}`:"session not found"));this.sessionId=e;this.name="SessionNotFoundError"}}function ve(e){return e instanceof Y||typeof e==="object"&&e!==null&&"code"in e&&e.code==="session_not_found"}import{spawn as os}from"node:child_process";import{closeSync as is,mkdirSync as rs,openSync as as,readFileSync as ds,unlinkSync as cs}from"node:fs";import{basename as us,dirname as ls,join as ps}from"node:path";import{fileURLToPath as fs}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as hs,isBunEmbeddedModulePath as ms,isHubDaemonProcess as gs,resolveClineBuildEnv as Et,withResolvedClineBuildEnv as ys}from"@cerebriline/shared";import{createHash as kn,randomBytes as Rn}from"node:crypto";import{mkdir as Se,open as at,readFile as pt,rename as _n,rm as ke,writeFile as Pn}from"node:fs/promises";import{dirname as ft,join as Re}from"node:path";import{ensureLoopbackProxyBypass as An,isHubProtocolCompatible as Tn}from"@cerebriline/shared";import{resolveClineDataDir as N,resolveClineDir as ii}from"@cerebriline/shared/storage";var xn="CLINE_HUB_DISCOVERY_PATH",En="CLINE_HUB_BUILD_ID",Hn="CLINE_HUB_BUILD_EPOCH_MS",In=30000,Mn=15000,dt=100;function On(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Un(e){return kn("sha256").update(e).digest("hex").slice(0,12)}function Ln(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function ct(e){return new Promise((t)=>setTimeout(t,e))}function Dn(e){return`${e}.lock`}async function Bn(e){try{let t=JSON.parse(await pt(Re(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function Ce(e){await ke(e,{recursive:!0,force:!0}).catch(()=>{return})}function U(){let e=process.env[En]?.trim();if(e)return e;return"sdk-v1-d70a53e60a51848baa4d382e98c5b4d9802a03a57d2bbb1c948887ac3e4ee94b".trim()||`source-${String(q.version)}`}function qn(){let e=Number(process.env[Hn]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1794145572502)?1794145572502:void 0}function X(e,t=U()){let n=Tn(e);if(!n.compatible)return n;let s=e.buildId?.trim();if(!s)return{compatible:!1,reason:"missing_build"};if(s!==t)return{compatible:!1,reason:"build_mismatch"};return{compatible:!0}}function ut(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function lt(e){let t=e?.trim().split(/[-+]/,1)[0];if(!t)return;let n=t.split(".").map((s)=>Number(s));if(n.length===0||n.some((s)=>!Number.isInteger(s)||s<0))return;return n}function Nn(e,t){for(let n=0;n<Math.max(e.length,t.length);n++){let s=e[n]??0,o=t[n]??0;if(s!==o)return s<o?-1:1}return 0}function ht(e,t){let n=e.buildId?.trim(),s=t.buildId?.trim();if(n&&s&&n===s)return 0;let o=ut(e.buildEpochMs),i=ut(t.buildEpochMs);if(o!==void 0&&i!==void 0&&o!==i)return o<i?-1:1;let r=lt(e.coreVersion),a=lt(t.coreVersion);if(r&&a){let d=Nn(r,a);if(d!==0)return d}if(n&&s&&n!==s)return n<s?-1:1;return 0}function mt(){return{buildId:U(),buildEpochMs:qn(),coreVersion:String(q.version)}}function Z(e,t){let n=t?.self??mt(),s=X(e,n.buildId??"");if(s.compatible)return!0;if(s.reason!=="build_mismatch"&&s.reason!=="missing_build")return!1;return ht(n,e)<=0}function gt(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${Un(e)}`,n=process.env[xn]?.trim()||Re(N(),"locks","hub","owners",`${On(t)}.json`);return{ownerId:t,discoveryPath:n}}async function I(e){try{let t=JSON.parse(await pt(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function yt(e,t,n){await wt(e,async()=>{let s=ft(e);await Se(s,{recursive:!0});let o=`${e}.${process.pid}.${Rn(6).toString("hex")}.tmp`,i;try{i=await at(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
9
9
  `,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,n?.beforePublish?.(),await _n(o,e);let r;try{r=await at(s,"r"),await r.sync()}catch{}finally{await r?.close().catch(()=>{return})}}catch(r){throw await i?.close().catch(()=>{return}),await ke(o,{force:!0}).catch(()=>{return}),r}})}async function L(e){await wt(e,async()=>{await ke(e,{force:!0}).catch(()=>{return})})}async function bt(e,t,n){let s=Dn(e);await Se(ft(s),{recursive:!0});let o=Date.now()+Mn;while(!0){try{await Se(s,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await Bn(s);if(!a){if(Date.now()>=o){await Ce(s);continue}await ct(dt);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!Ln(a.pid)||d>In){await Ce(s);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${s}`);await ct(dt);continue}try{return await Pn(Re(s,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
10
10
  `,"utf8"),await n()}finally{await Ce(s)}}}function wt(e,t){return bt(`${e}.mutation`,"discovery mutation",t)}function vt(e,t){return bt(e,"startup",t)}async function ee(e,t){An();try{let n=await fetch(t?.authToken?$n(e):St(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let s=await n.json();if(typeof s.protocolVersion!=="string"||typeof s.host!=="string"||typeof s.port!=="number"||typeof s.url!=="string")return;return{protocolVersion:s.protocolVersion,minClientProtocolVersion:typeof s.minClientProtocolVersion==="string"?s.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof s.maxClientProtocolVersion==="string"?s.maxClientProtocolVersion:void 0,capabilities:Array.isArray(s.capabilities)?s.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof s.coreVersion==="string"?s.coreVersion:void 0,buildId:typeof s.buildId==="string"?s.buildId:void 0,buildEpochMs:typeof s.buildEpochMs==="number"?s.buildEpochMs:void 0,host:s.host,port:s.port,url:s.url,hubId:typeof s.hubId==="string"?s.hubId:void 0,authToken:typeof s.authToken==="string"?s.authToken:void 0,pid:typeof s.pid==="number"?s.pid:void 0,startedAt:typeof s.startedAt==="string"?s.startedAt:void 0,updatedAt:typeof s.updatedAt==="string"?s.updatedAt:void 0}}catch{return}}function Ct(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function St(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function $n(e){let t=new URL(St(e));return t.pathname="/status",t.toString()}import{CLINE_HUB_DEV_PORT as Wn,CLINE_HUB_PORT as jn,resolveClineBuildEnv as Fn}from"@cerebriline/shared";var zn="CLINE_HUB_HOST",Vn="CLINE_HUB_PORT",Gn="CLINE_HUB_PATHNAME",Jn="127.0.0.1",Kn=jn,Qn="/hub";function kt(e){return Fn(e)==="development"?Wn:Kn}function Yn(e={}){return(e.env??process.env)[zn]?.trim()||Jn}function Xn(e={}){let n=(e.env??process.env)[Vn]?.trim();if(!n)return kt(e);let s=Number.parseInt(n,10);if(!Number.isInteger(s)||s<1||s>65535)return kt(e);return s}function Zn(e={}){return(e.env??process.env)[Gn]?.trim()||Qn}function Rt(e={},t={}){return{host:e.host??Yn(t),port:e.port??Xn(t),pathname:e.pathname??Zn(t)}}import{join as es}from"node:path";var ts="shared:cline",ns="CLINE_HUB_DISCOVERY_PATH",ss="hub-production";function W(e=ts){return gt(`${e}@${U()}`)}function te(){return{ownerId:ss,discoveryPath:process.env[ns]?.trim()||es(N(),"locks","hub","production.json")}}var _t=15000,bs=200,Pt=3000,ws=100,vs=[100,250,500,1000,2000],Cs="--cline-hub-daemon",Ss=3,ks=60000,At=new Map;function Rs(e,t=Date.now()){let n=At.get(e);if(!n||t-n.windowStartedAt>ks)return At.set(e,{count:1,windowStartedAt:t}),!0;return n.count+=1,n.count<=Ss}function _s(e){return[...e.host?["--host",e.host]:[],...typeof e.port==="number"?["--port",String(e.port)]:[],...e.pathname?["--pathname",e.pathname]:[]]}function Ps(){try{let e=ps(N(),"logs","hub-daemon.log");return rs(ls(e),{recursive:!0}),{fd:as(e,"a"),logPath:e}}catch{return}}function As(){return Et()==="production"?te():W()}function j(e){return Z(e)}function Ts(e){try{let t=JSON.parse(ds(`${e}.superseded`,"utf8"));return{url:typeof t.url==="string"?t.url:void 0,authToken:typeof t.authToken==="string"?t.authToken:void 0,pid:typeof t.pid==="number"?t.pid:void 0}}catch{return}}function _e(e){try{cs(`${e}.superseded`)}catch{}}function Tt(e,t,n){if(!t||t.url!==n)return e;return{...e,authToken:e.authToken??t.authToken,pid:e.pid??t.pid}}async function F(e,t){try{return await ee(e,{authToken:t})}catch{return}}async function xt(e,t){let n=Date.now()+t;while(Date.now()<n){if(!(await F(e))?.url)return!0;await new Promise((o)=>setTimeout(o,ws))}return!1}async function Ae(e,t){if(!Rs(e.url))return!1;await z(e.url,e.authToken,"retired by newer install").catch(()=>!1),await Mt(e.url,e.authToken).catch(()=>!1);let n=await xt(e.url,Pt);if(!n&&e.pid&&xs(e.pid)){try{process.kill(e.pid,"SIGTERM")}catch{}n=await xt(e.url,Pt)}if(n)await L(t).catch(()=>{return});return n}function xs(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Es(e){try{return(await Te(e.url,e.authToken)).activeSessionCount>0}catch{return!1}}async function Pe(e,t){if(j(e))return"reusable";let n=await z(e.url,e.authToken,"retired by newer install").catch(()=>!1);if(await Es(e)){if(n)await z(e.url,e.authToken,"hub retirement deferred",{off:!0}).catch(()=>!1);return"deferred_busy"}let s=await Ae(e,t);if(!s&&n)await z(e.url,e.authToken,"hub retirement failed",{off:!0}).catch(()=>!1);return s?"retired":"failed"}async function Hs(e){if(Et()!=="production")return;let t=W();if(t.discoveryPath===e.discoveryPath)return;let n=await I(t.discoveryPath);if(n?.url)await Ae(n,t.discoveryPath);else await L(t.discoveryPath).catch(()=>{return})}function Is(){let e=import.meta.url.endsWith(".ts")?"ts":"js";return fs(new URL(`./entry.${e}`,import.meta.url))}function Ms(e,t){if(ms(e))return[Cs];return[...t&&e.toLowerCase().endsWith(".ts")?["--conditions=development"]:[],e]}function Os(e,t){let n=Is(),s=process.execPath?.trim();if(!s)throw Error("unable to resolve runtime executable for hub daemon");let o=us(s).toLowerCase().includes("bun"),i=Ms(n,o);return{launcher:s,args:[...i,"--cwd",e,..._s(t),...t.manageConnectors===!1?["--no-connectors"]:[]],cwd:e,env:{...ys(process.env),CLINE_NO_INTERACTIVE:"1",[hs]:"1"}}}function Us(e){if(!e||typeof e!=="object")return!1;if(("code"in e?e.code:void 0)==="ETXTBSY")return!0;let n="message"in e?e.message:void 0;return typeof n==="string"&&n.includes("ETXTBSY")}function Ls(e,t={}){if(gs())return;let n=Os(e,t),s=Ps();try{os(n.launcher,n.args,{detached:!0,stdio:s?["ignore",s.fd,s.fd]:"ignore",env:n.env,cwd:n.cwd,windowsHide:!0}).unref()}finally{if(s)is(s.fd)}}async function Ds(e,t={}){for(let n=0;;n++)try{Ls(e,t);return}catch(s){let o=vs[n];if(!Us(s)||o===void 0)throw s;await new Promise((i)=>setTimeout(i,o))}}async function Bs(e,t,n={}){let s=n.host!==void 0||n.port!==void 0||n.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),o=Rt(n),i=Ct(o.host,o.port,o.pathname),r=(l)=>{if(!s)ne(l.url,l.authToken);else It(l.url,l.authToken);return l};await Hs(e).catch(()=>{return});let a=await I(e.discoveryPath),d=a?.url?void 0:Ts(e.discoveryPath),u=!1;if(a?.url){let l=a.authToken;if(!l)u=!0,await Ae(a,e.discoveryPath);else{let m=await F(a.url,l);if(m?.url&&j(m)&&await E(m.url,{authToken:l}))return _e(e.discoveryPath),r({url:m.url,authToken:l});if(m?.url){if(await Pe({...m,authToken:l},e.discoveryPath)==="deferred_busy"&&await E(m.url,{authToken:l}))return r({url:m.url,authToken:l})}else await L(e.discoveryPath).catch(()=>{return})}}let f=await F(i);if(f?.url){let l=Tt(f,a??d,i);if(j(f)){let y=[f.authToken,a?.authToken,d?.authToken].filter((v)=>typeof v==="string"&&v.trim().length>0);for(let v of y){if(!await E(f.url,{authToken:v}))continue;let P={hubId:f.hubId??`repaired-${f.port}`,protocolVersion:f.protocolVersion,minClientProtocolVersion:f.minClientProtocolVersion,maxClientProtocolVersion:f.maxClientProtocolVersion,capabilities:f.capabilities,coreVersion:f.coreVersion,buildId:f.buildId,authToken:v,host:f.host,port:f.port,url:f.url,pid:f.pid??a?.pid??d?.pid,startedAt:f.startedAt??new Date().toISOString(),updatedAt:new Date().toISOString()};try{await yt(e.discoveryPath,P)}catch{}return _e(e.discoveryPath),r({url:f.url,authToken:v})}throw Error(`A compatible Cline Hub is already running at ${i}, but its discovery record is missing or unreadable and no usable auth token is available. Run 'cline doctor fix' to repair local hub discovery.${u?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`)}let m=await Pe(l,e.discoveryPath);if(m==="deferred_busy"){for(let y of[l.authToken,a?.authToken].filter((w)=>typeof w==="string"&&w.trim().length>0))if(await E(f.url,{authToken:y}))return r({url:f.url,authToken:y});if(n.allowPortFallback!==!0&&o.port!==0)throw Error(`An older Cline Hub is running at ${i} and is still serving active sessions, so it was not replaced, but no usable auth token is available to attach to it. Finish those sessions, or run 'cline doctor fix' to stop the hub.`)}if(m==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is already running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let h=n.allowPortFallback===!0&&o.port!==0?{...o,port:0}:o;await Ds(t,{...h,manageConnectors:n.manageConnectors});let p=Date.now()+_t;while(Date.now()<p){let l=await I(e.discoveryPath);if(l?.url&&l.authToken){let y=await F(l.url,l.authToken);if(y?.url&&j(y)&&await E(y.url,{authToken:l.authToken}))return _e(e.discoveryPath),r({url:y.url,authToken:l.authToken})}let m=await F(i);if(m?.url&&!j(m)){let y=Tt(m,l??d,i),w=await Pe(y,e.discoveryPath);if(w==="deferred_busy"&&l?.authToken&&await E(m.url,{authToken:l.authToken}))return r({url:m.url,authToken:l.authToken});if(w==="failed"&&n.allowPortFallback!==!0&&o.port!==0)throw Error(`An incompatible Cline Hub is still running at ${i} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((y)=>setTimeout(y,bs))}throw Error(`Timed out after ${_t}ms waiting for detached hub startup.`)}async function Ht(e,t={}){let n=As();return await vt(n.discoveryPath,async()=>Bs(n,e,t))}function Fs(){return $s()==="production"?te():W()}function zs(){let e=globalThis.WebSocket;if(!e)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return e}function Nt(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();if(e&&typeof e==="object"&&"data"in e&&typeof e.data<"u")return Nt(e.data);return String(e)}function Vs(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return""}function Ot(e){let t=e,n=Vs(t.reason);return new k("hub_connection_closed",t.code||n?`Hub connection closed (code=${t.code??0}${n?`, reason=${n}`:""})`:Ee,{closeCode:t.code,closeReason:n||void 0})}function Ut(e,t){if(e instanceof k)return e;if(e instanceof Error)return new k("hub_connect_failed",e.message);if(e&&typeof e==="object"&&"error"in e&&e.error instanceof Error)return new k("hub_connect_failed",e.error.message);let n=e&&typeof e==="object"&&"message"in e&&typeof e.message==="string"?e.message.trim():"";if(n)return new k("hub_connect_failed",n);let s=e&&typeof e==="object"&&"type"in e&&typeof e.type==="string"?e.type.trim():"";return new k("hub_connect_failed",s?`Failed to connect to hub at ${t.toString()} (${s} event before socket open).`:`Failed to connect to hub at ${t.toString()}.`)}var xe="*",se=8000,Gs="cline-hub-auth.",Me=new Map,$t=new Set,Js=3000;var Ee="Hub connection closed",Ks=250,Qs=5000,Lt=0.5;class k extends Error{code;details;constructor(e,t,n){super(t);this.code=e;this.details=n;this.name="HubTransportError"}}function Ys(e){return e instanceof k}class He extends Error{command;code;constructor(e,t,n){super(n);this.command=e;this.code=t;this.name="HubCommandError"}}function Oe(e,t={}){let n=e.searchParams.get("authToken")?.trim();if(e.searchParams.delete("authToken"),n)return n;if(t.skipRegistry)return;let s=oe(e.toString());return s?Me.get(s):void 0}function Xs(e){try{let n=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"");return n==="localhost"||n==="127.0.0.1"||n==="::1"}catch{return!1}}function oe(e){if(!Xs(e))return;let t=new URL(Wt(e));return t.search="",t.hash="",t.toString()}function Dt(e){let t=oe(e);return!!t&&$t.has(t)}function ne(e,t){let n=oe(e);if(n){if($t.add(n),t?.trim())Me.set(n,t)}return e}function It(e,t){let n=oe(e);if(n&&t?.trim())Me.set(n,t)}class V{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;lastEventSequenceByKey=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;connectGeneration=0;lastCloseError=new k("hub_connection_closed",Ee);sawSocketClose=!1;registered=!1;capabilities;constructor(e){this.options=e;if(e.authToken?.trim()&&e.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");this.clientId=e.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=e.url,this.capabilities=[...e.capabilities??[]]}getClientId(){return this.clientId}getUrl(){return this.currentUrl}isConnected(){return this.socket?.readyState===1&&this.registered}getConnectionError(){return this.isConnected()?null:this.lastCloseError}async updateCapabilities(e){if(this.capabilities=e.map((t)=>({...t})),!this.registered)return;await this.command("client.update",{capabilities:this.capabilities})}async connect(){if(this.connectPromise)return this.connectPromise;if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let e=new URL(this.currentUrl),t=this.options.authToken?.trim()||Oe(e,{skipRegistry:Boolean(this.options.resolveConnectionHeaders)});if(e.hash="",t&&this.options.resolveConnectionHeaders)throw Error("Hub connection headers cannot be combined with authToken authentication.");let n=++this.connectGeneration,s=this.openSocket(e,t,n),o;this.connectPromise=s.then(async(r)=>{if(o=r,await this.commandOnce("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",capabilities:this.capabilities,metadata:{...this.options.metadata,version:this.options.clientVersion??String(q.version),pid:process.pid},workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}},void 0,void 0,!1),n!==this.connectGeneration||this.closedByClient){try{r.close()}catch{}throw this.lastCloseError}this.registered=!0;for(let a of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(a));this.reconnectAttempt=0});let i=this.connectPromise;try{await i}catch(r){if(this.connectPromise===i)this.connectPromise=void 0;if(o&&this.socket===o){this.lastCloseError=Ut(r,e),this.registered=!1,this.sawSocketClose=!1,this.socket=void 0;try{o.close()}catch{}}if(!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect();throw r}}async openSocket(e,t,n){let s=this.options.resolveConnectionHeaders,o;if(s){let d;try{o=await Promise.race([Promise.resolve().then(()=>s()),new Promise((u,f)=>{d=setTimeout(()=>{f(new k("hub_connect_timeout",`Timed out resolving hub connection headers after ${se}ms`))},se)})])}catch(u){let f=u instanceof k?u:new k("hub_connect_failed",u instanceof Error?u.message:String(u));if(n===this.connectGeneration)this.lastCloseError=f;throw f}finally{clearTimeout(d)}}if(n!==this.connectGeneration||this.closedByClient)throw this.lastCloseError;if(o&&Object.keys(o).some((d)=>d.toLowerCase()==="sec-websocket-protocol")){let d=new k("hub_connect_failed","Hub connection headers cannot set Sec-WebSocket-Protocol.");if(n===this.connectGeneration)this.lastCloseError=d;throw d}let i=o?new js(e.toString(),{headers:{...o}}):new(zs())(e.toString(),t?[`${Gs}${t}`]:void 0);this.socket=i;let r=!1,a=new Promise((d,u)=>{let f=!1,c=setTimeout(()=>{if(f)return;f=!0,r=!0;let h=new k("hub_connect_timeout",`Timed out connecting to hub after ${se}ms`);if(this.socket===i)this.lastCloseError=h,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{i.close()}catch{}u(h)},se);i.addEventListener("open",()=>{if(f)return;f=!0,clearTimeout(c),d()}),i.addEventListener("error",(h)=>{if(f)return;f=!0,clearTimeout(c);let p=Ut(h,e);if(this.socket===i)this.lastCloseError=p,this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;u(p)}),i.addEventListener("close",(h)=>{if(f)return;f=!0,clearTimeout(c);let p=r?this.lastCloseError:Ot(h);if(this.socket===i){if(!r)this.lastCloseError=p,this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0}u(p)})});return i.addEventListener("message",(d)=>{this.handleFrame(JSON.parse(Nt(d)))}),i.addEventListener("close",(d)=>{if(this.socket!==i)return;if(!r)this.lastCloseError=Ot(d),this.sawSocketClose=!0;this.registered=!1;for(let u of this.pendingReplies.values())u.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await a,i}subscribe(e,t){let n=t?.sessionId?.trim()||void 0,s={listener:e,sessionId:n};return this.listeners.add(s),this.adjustSubscriptionCount(n,1),()=>{if(!this.listeners.delete(s))return;this.adjustSubscriptionCount(n,-1)}}async command(e,t,n,s){let o=0,i=e!=="client.register"&&e!=="client.unregister";while(!0)try{return await this.commandOnce(e,t,n,s)}catch(r){if(!i||o>=1||!await this.recoverLocalHubTransport(r))throw r;o+=1}}async commandOnce(e,t,n,s,o=!0){if(o)await this.connect();s?.beforeDispatch?.();let i=qs("hubreq_");s?.onDispatch?.(i);let r=Ws(e,s?.timeoutMs),a=new Promise((u,f)=>{let c=r===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(i))return;f(new He(e,"hub_command_timeout",`Hub command ${e} timed out after ${r}ms (hub=${this.currentUrl}, requestId=${i}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},r);this.pendingReplies.set(i,{resolve:(h)=>{if(c)clearTimeout(c);u(h)},reject:(h)=>{if(c)clearTimeout(c);f(h)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:e,requestId:i,clientId:this.clientId,sessionId:n,timeoutMs:r,payload:t}})}catch(u){throw this.pendingReplies.delete(i),u}let d=await a;if(!d.ok){if(d.error?.code===rt){let u=n??(typeof t?.sessionId==="string"?t.sessionId:void 0);throw new Y(u,d.error.message)}throw new He(e,d.error?.code,d.error?.message??`Hub command ${e} failed`)}return d}async recoverLocalHubTransport(e){if(!Dt(this.currentUrl)||!Ys(e))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let t=await Bt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!t)return!1;return this.currentUrl=t,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let e=Math.min(Ks*2**this.reconnectAttempt,Qs),t=Math.round(e*(1-Lt)+Math.random()*e*Lt);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},t)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Dt(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let e=await Bt({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(e){this.currentUrl=e,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let e=this.socket;if(this.closedByClient=!0,this.connectGeneration+=1,this.clearReconnectTimer(),this.registered=!1,e)this.lastCloseError=new k("hub_connection_closed",Ee);for(let t of this.pendingReplies.values())t.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,!e)return;this.sawSocketClose=!1,this.socket=void 0;try{e.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(e){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new k("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(e))}sendSubscriptionFrame(e,t){let n=e==="stream.subscribe"?this.lastEventSequenceByKey.get(this.subscriptionKeyForSessionId(t)):void 0;this.sendFrame({kind:e,clientId:this.clientId,...t?{sessionId:t}:{},...n!==void 0?{sinceSequence:n}:{}})}adjustSubscriptionCount(e,t){let n=this.subscriptionKeyForSessionId(e),s=(this.subscriptionCounts.get(n)??0)+t;if(s<=0){if(this.subscriptionCounts.delete(n),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(t<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",e);return}if(this.subscriptionCounts.set(n,s),t>0&&s===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",e)}subscriptionKeyForSessionId(e){return e??xe}subscriptionSessionIdFromKey(e){return e===xe?void 0:e}handleFrame(e){switch(e.kind){case"reply":{let t=e.envelope.requestId;if(!t)return;let n=this.pendingReplies.get(t);if(!n)return;this.pendingReplies.delete(t),n.resolve(e.envelope);return}case"event":{let t=e.envelope.sequence;if(typeof t==="number"){let n=e.envelope.sessionId?.trim();for(let s of[xe,n]){if(!s||!this.subscriptionCounts.has(s))continue;let o=this.lastEventSequenceByKey.get(s)??0;if(t>o)this.lastEventSequenceByKey.set(s,t)}}for(let n of this.listeners){if(n.sessionId&&n.sessionId!==e.envelope.sessionId?.trim())continue;n.listener(e.envelope)}return}case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function Wt(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";return t.toString()}async function E(e,t){let n=new V({url:e,authToken:t?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:t?.workspaceRoot,cwd:t?.cwd});try{return await n.connect(),!0}catch{return!1}finally{n.close()}}async function Ie(e,t){let n=Wt(e),s=await ee(n,{authToken:t?.authToken});if(!s)return{status:"unreachable",url:n};if(t?.requireCurrentBuild){let o=U(),i=X(s,o);if(!i.compatible&&!Z(s))return{status:i.reason==="unsupported_protocol"?"protocol_mismatch":"build_mismatch",url:n}}else if(!Ns(s).compatible)return{status:"protocol_mismatch",url:n};if(t?.verifyConnection===!0&&!await E(n,{workspaceRoot:t.workspaceRoot,cwd:t.cwd,authToken:t.authToken}))return{status:"unreachable",url:n};return{status:"compatible",url:n}}function Zs(e){let t=e&&typeof e==="object"&&Array.isArray(e.sessions)?e.sessions:[],n=0,s=new Set;for(let o of t){if(!o||typeof o!=="object")continue;let i=o.participants;if(!Array.isArray(i)||i.length===0)continue;n+=1;for(let r of i){let a=r&&typeof r==="object"?r.clientId:void 0;if(typeof a==="string"&&a.trim())s.add(a)}}return{activeSessionCount:n,participantClientCount:s.size}}async function Te(e,t,n){let s=new V({url:e,authToken:t,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:n?.workspaceRoot,cwd:n?.cwd});try{let o=await s.command("session.list",{limit:500},void 0,{timeoutMs:Js});return Zs(o.payload)}finally{await s.dispose().catch(()=>{return})}}async function eo(e,t,n){try{return(await Te(e,t,n)).activeSessionCount===0}catch{return!1}}async function to(e,t){let n=`${e.discoveryPath}.superseded`,s=await I(n);if(!s?.url||!s.authToken)return;let o=await Ie(s.url,{authToken:s.authToken});if(o.status!=="compatible")return;if(await eo(o.url,s.authToken,t))return;return ne(o.url,s.authToken)}async function no(e={}){if(e.endpoint?.trim()){let o=await Ie(e.endpoint);return o.status==="compatible"?o.url:void 0}let t=Fs(),n=await I(t.discoveryPath);if(!n?.url)return await to(t,e);let s=await Ie(n.url,{authToken:n.authToken,requireCurrentBuild:!0});if(s.status==="compatible")return ne(s.url,n.authToken);if(s.status==="protocol_mismatch")await L(t.discoveryPath).catch(()=>{return});return}async function Bt(e={}){let t=await no(e);if(t&&await E(t,{workspaceRoot:e.workspaceRoot,cwd:e.cwd}))return t;if(e.endpoint?.trim())return;try{return(await Ht(e.workspaceRoot??process.cwd())).url}catch(n){e.onStartupError?.(n);return}}async function z(e,t,n,s){qt();let o=new URL(e),i=t?.trim()||Oe(o);if(o.protocol==="ws:")o.protocol="http:";else if(o.protocol==="wss:")o.protocol="https:";if(o.pathname="/drain",o.hash="",n)o.searchParams.set("reason",n);if(s?.off)o.searchParams.set("off","1");return(await fetch(o,{method:"POST",headers:i?{authorization:`Bearer ${i}`}:void 0})).ok}async function Mt(e,t){qt();let n=new URL(e),s=t?.trim()||Oe(n);if(n.protocol==="ws:")n.protocol="http:";else if(n.protocol==="wss:")n.protocol="https:";return n.pathname="/shutdown",n.hash="",(await fetch(n,{method:"POST",headers:s?{authorization:`Bearer ${s}`}:void 0})).ok}function so(e,t){if(!e||typeof e!=="object")return;let n=e,s=typeof n.id==="string"?n.id.trim():"";if(!s)return;let o=typeof n.display_name==="string"?n.display_name.trim():typeof n.displayName==="string"?n.displayName.trim():"",i=typeof n.name==="string"?n.name.trim():"";return{id:s,name:o||i||s,catalogId:t}}function Ue(e,t){return Array.isArray(e)?e.flatMap((n)=>{let s=so(n,t);return s?[s]:[]}):[]}async function jt(e,t={}){let n=e.trim(),s=n.length;while(s>0&&n[s-1]==="/")s--;let o=n.slice(0,s),i=async(m)=>{let y=await(t.fetchImpl??fetch)(`${o}${m}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!y.ok)throw Error(`HTTP ${y.status}`);return await y.json()},r,a;try{[r,a]=await Promise.all([i("/api/v1/ai/cline/models"),i("/api/v1/ai/cline/recommended-models")])}catch(m){throw Error("Could not load the cloud model catalog.",{cause:m})}let d=r&&typeof r==="object"?r:void 0,u=Ue(Array.isArray(r)?r:d?.data,"cline"),f=a&&typeof a==="object"?a:void 0,c=f?.data&&typeof f.data==="object"?f.data:f,h=Ue(c?.clinePass,"cline-pass"),p=Ue(c?.clineCloud,"cline-cloud"),l=new Set;return[...t.isOrganizationSession?[]:h,...p,...u].filter((m)=>{if(l.has(m.id))return!1;return l.add(m.id),!0})}import{formatDisplayUserInput as Ft}from"@cerebriline/shared";var oo=new Set(["auto_compaction","compaction_budget_emergency","completion_reminder","loop_detection_notice","manual_compaction","mistake_stop_notice","recovery_notice"]);function io(e){switch(e){case"user":case"assistant":case"tool":case"system":case"status":case"error":return e;default:return"assistant"}}function ro(e){return e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0}function ao(e){let t=e?.userRunSpan;return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function co(e){if(typeof e.content==="string")return{hasAttachment:!1,text:e.content};if(!Array.isArray(e.content))return{hasAttachment:!1,text:"unknown"};let t=!1,n=!1,s=[];for(let o of e.content){if(!o||typeof o!=="object"||Array.isArray(o))continue;let i=o;if(i.type==="text"&&typeof i.text==="string")s.push(i.text);else if(i.type==="tool_result"||i.type==="tool-result")n=!0;else if(i.type==="file"||i.type==="image")t=!0}return{hasAttachment:t&&!n,text:s.join(`
11
11
  `)}}function uo(e){let t=Ft(e);return t.startsWith("[TASK RESUMPTION]")||t==="The user approved switching to act mode. Continue with the approved plan now."}function lo(e){if(io(e.role)!=="user")return 0;let t=ro(e),n=typeof t?.kind==="string"?t.kind:void 0,s=ao(t);if(n==="compaction"||n==="compaction_summary")return s??1;if(s!==void 0)return s;if(n&&oo.has(n))return 0;let o=co(e);if(!o.hasAttachment&&!Ft(o.text))return 0;if(!o.hasAttachment&&uo(o.text))return 0;return 1}function zt(e){return lo(e)>0}function ae(e){return Array.isArray(e?.sessions)?e.sessions.filter((t)=>Boolean(t)&&typeof t==="object"&&!Array.isArray(t)):[]}function Le(e){let t=e.updatedAt;return typeof t==="number"?t:Date.parse(String(t??""))||0}function De(e){let t=e?.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return String(t?.model??e?.model??"").trim()}function de(e){let t=e.metadata&&typeof e.metadata==="object"?e.metadata:void 0;return!String(t?.parentSessionId??e.parentSessionId??"").trim()}function Kt(e,t="text"){if(!e||typeof e!=="object"||Array.isArray(e))return"";let n=e.content;if(typeof n==="string")return t==="text"?n.trim():"";if(!Array.isArray(n))return"";return n.map((s)=>s&&typeof s==="object"&&!Array.isArray(s)?t==="thinking"&&s.type==="redacted_thinking"?"[redacted]":String(s[t]??""):"").join("").trim()}function ie(e){let t=e.trim(),n=t.match(/^<user_input\b[^>]*>([\s\S]*)<\/user_input>$/);return(n?n[1]:t).trim()}function G(e,t,n){let s=ie(n);return e.filter((o)=>Boolean(o)&&typeof o==="object"&&!Array.isArray(o)&&String(o.role??"").toLowerCase()==="user"&&(s!==""||zt(o))&&ie(Kt(o))===s).length+t.filter((o)=>ie(o.prompt)===s).length}function Be(e){return e.flatMap((t)=>{if(t.event!=="session.pending_prompt_submitted")return[];let n=t.payload?.prompt&&typeof t.payload.prompt==="object"&&!Array.isArray(t.payload.prompt)?t.payload.prompt:void 0,s=String(n?.id??"").trim();if(!s)return[];return[{id:s,prompt:String(n?.prompt??""),steer:n?.delivery==="steer",attachmentCount:typeof n?.attachmentCount==="number"?n.attachmentCount:0,userImages:Array.isArray(n?.userImages)?n.userImages.filter((o)=>typeof o==="string"):void 0}]})}var po=new Set(["run.completed","run.aborted","run.failed"]),fo=new Set(["assistant.delta","assistant.finished","reasoning.delta","reasoning.finished"]);function Vt(e,t){return e.filter((n)=>Boolean(n)&&typeof n==="object"&&!Array.isArray(n)&&String(n.role??"").toLowerCase()==="assistant").map((n)=>Kt(n,t)).filter(Boolean)}function Gt(e,t,n="text"){let s=new Map;for(let o of Vt(t,n))s.set(o,(s.get(o)??0)+1);return Vt(e,n).filter((o)=>{let i=s.get(o)??0;if(i===0)return!0;if(i===1)s.delete(o);else s.set(o,i-1);return!1})}function re(e,t,n=new Set){if(!e||typeof e!=="object")return n;if(Array.isArray(e)){for(let i of e)re(i,t,n);return n}let s=e,o=t==="tool_use"?s.id:s.tool_use_id;if(s.type===t&&typeof o==="string")n.add(o);for(let i of Object.values(s))re(i,t,n);return n}function Jt(e,t="assistant"){let n="",s="";for(let o of e)if(o.event===`${t}.delta`)s+=t==="reasoning"&&o.payload?.redacted&&!o.payload?.text?"[redacted]":typeof o.payload?.text==="string"?o.payload.text:"";else if(o.event===`${t}.finished`){let i=o.payload?.[t==="assistant"?"text":"reasoning"],r=typeof i==="string"&&i?i:s;if(r)n=r;s=""}return(n||s).trim()}function Qt(e,t,n={}){let s=n.queueSnapshotApplied!==!1,o=Gt(t,n.baselineMessages??[]),i=Gt(t,n.baselineMessages??[],"thinking"),r=re(t,"tool_use"),a=re(t,"tool_result"),d=new Set(e.slice(0,n.messagesSnapshotEventCutoff??e.length)),u=new Set,f=new Map;for(let y of e.slice(0,n.messagesSnapshotEventCutoff??e.length)){let w=Be([y])[0];if(!w)continue;let v=ie(w.prompt),P=f.get(v)??Math.max(0,G(t,[],v)-G(n.baselineMessages??[],[],v));if(f.set(v,Math.max(0,P-1)),P>0)u.add(y)}let h=[...s?e.slice(n.queueSnapshotEventCutoff??e.length):e].reverse().find((y)=>y.event==="session.pending_prompts"),p=[],l=[],m=(y)=>{if(l.length===0)return;let w=l.filter((A)=>d.has(A)),v=(A)=>{if(!y)return-1;let S=[...w].reverse().findIndex((nn)=>nn.event===`${A}.finished`),D=S<0?-1:w.length-1-S;return D>=0||l.at(-1)?.event==="run.aborted"?D:w.length-1},P=v("assistant"),H=v("reasoning"),b=Jt(w.slice(0,P+1)),R=b?o.findIndex((A)=>A.endsWith(b)):-1,M=R>=0;if(M)o.splice(R,1);let J=Jt(w.slice(0,H+1),"reasoning"),pe=J?i.findIndex((A)=>A.endsWith(J)):-1;if(pe>=0)i.splice(pe,1);for(let[A,S]of l.entries()){if(u.has(S)){p.push({...S,payload:{...S.payload,transcriptReflected:!0}});continue}if(d.has(S)&&fo.has(S.event)&&(S.event.startsWith("reasoning.")?pe>=0&&A<=H:M&&A<=P))continue;if(S.event==="session.pending_prompts"&&S!==h)continue;if(d.has(S)&&S.event.startsWith("tool.")){let D=String(S.payload?.toolCallId??"").trim();if(a.has(D)||S.event==="tool.started"&&r.has(D))continue}p.push(S)}l=[]};for(let y of e)if(l.push(y),po.has(y.event))m(!0);return m(!1),p}import{formatDisplayUserInput as ho}from"@cerebriline/shared";function ce(e){let t=structuredClone(e),n=(s)=>{if(!s||typeof s!=="object"||Object.isFrozen(s))return;for(let o of Object.values(s))n(o);Object.freeze(s)};return n(t),t}function ue(e){let t=e?.trim();return t?ho(t).slice(0,120):void 0}function qe(e){if(typeof e==="string")return e;if(Array.isArray(e)){let t=[];for(let n of e){if(typeof n==="string"){if(n.trim())t.push(n);continue}if(!n||typeof n!=="object")continue;let s=n,o=typeof s.type==="string"?s.type:"",i=o==="text"?String(s.text??""):o==="thinking"?String(s.thinking??""):o==="tool_use"?`[tool] ${String(s.name??"tool_call")}`:o==="tool_result"?`[tool_result]