@minimax-ai/code 0.4.6 → 0.4.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/CHANGELOG.zh-CN.md +19 -0
- package/README.md +13 -0
- package/README.zh-CN.md +10 -0
- package/assets/agents/_default/prompt-base-all.md +35 -141
- package/assets/agents/_default/prompt-base-all.md.hbs +6 -4
- package/assets/agents/_default/prompt-base-worker.md +8 -19
- package/assets/agents/_default/prompt-session-branch.md +0 -1
- package/assets/agents/_default/prompt-session-root.md +4 -32
- package/assets/agents/_v2/AGENT_CONTEXT.md.hbs +222 -0
- package/assets/agents/_v2/coding/SYSTEM.md.hbs +161 -0
- package/assets/agents/_v2/explore.md.hbs +30 -0
- package/assets/agents/_v2/tui/SYSTEM.md.hbs +147 -0
- package/assets/agents/_v2/verifier.md.hbs +32 -0
- package/assets/agents/_v2/work/SYSTEM.md.hbs +173 -0
- package/assets/agents/_v2/worker.md.hbs +27 -0
- package/assets/agents/managed-prompts.json +8 -1
- package/assets/agents/mavis/PERSONA-zh.md +0 -13
- package/assets/agents/mavis/PERSONA.md +0 -13
- package/assets/agents/mavis/features/recoverable-deletion.md.hbs +10 -0
- package/assets/agents/mavis/modes/coding/online/SYSTEM.md.hbs +2 -0
- package/assets/agents/mavis/modes/work/online/SYSTEM.md.hbs +2 -0
- package/assets/agents/mavis/prompt-session-root.md +4 -46
- package/assets/agents/mavis/prompt-session-root.md.hbs +4 -46
- package/assets/agents/mavis/skills/control-in-app-browser/SKILL.md +0 -8
- package/assets/agents/mavis/skills/minimax-code-product/SKILL.md +2 -2
- package/assets/agents/mavis/system-prompt.md.hbs +47 -37
- package/assets/agents/prompt-exemptions.json +2 -12
- package/assets/agents/verifier/agent.md +3 -0
- package/assets/agents/worker/agent.md +3 -0
- package/chunks/{application-FCLZ6WHZ.js → application-OZ6YEJNG.js} +1 -1
- package/chunks/{auth-command-HEXCI24E.js → auth-command-TP25VHV4.js} +1 -1
- package/chunks/{chunk-AAJMOWWM.js → chunk-22LVIQ2T.js} +1 -1
- package/chunks/{chunk-6BYKHQOV.js → chunk-2SW3R5AB.js} +31 -17
- package/chunks/{chunk-E2J47VVN.js → chunk-AJSGEEWR.js} +1 -1
- package/chunks/{chunk-Y27DNFV2.js → chunk-B2NJMA4I.js} +32 -32
- package/chunks/{chunk-NF72FWAW.js → chunk-BNU46XHR.js} +1 -1
- package/chunks/{chunk-LJXS2KRC.js → chunk-C2OVBAOI.js} +1 -1
- package/chunks/{chunk-FLEWADRD.js → chunk-KVMK6REW.js} +1 -1
- package/chunks/{chunk-4FNXBXOU.js → chunk-OVLV6FQA.js} +863 -869
- package/chunks/{chunk-4NX3LPKA.js → chunk-QJWOGW27.js} +1 -1
- package/chunks/{chunk-V7D3N7GI.js → chunk-SYLCIHHV.js} +1 -1
- package/chunks/{chunk-MNN6EKX3.js → chunk-W7JHDTPW.js} +1 -1
- package/chunks/{chunk-J756IG32.js → chunk-YBZTB54I.js} +804 -798
- package/chunks/{data-dir-LETCXX3O.js → data-dir-KTXCGPJZ.js} +1 -1
- package/chunks/{dist-63B3F7A6.js → dist-MM7GHB2J.js} +1 -1
- package/chunks/{install-source-4BFOZZBU.js → install-source-3CE52ZIN.js} +1 -1
- package/chunks/{launcher-TV5PCI3Y.js → launcher-BNIFOBXD.js} +3 -3
- package/chunks/{lifecycle-ON5VQU5P.js → lifecycle-EKT5LQIE.js} +1 -1
- package/chunks/{main-TWT22DQQ.js → main-FAPYW7S4.js} +9 -9
- package/chunks/{plugin-command-K2IRBTGL.js → plugin-command-TD3DWK7U.js} +1 -1
- package/chunks/{provider-command-PJOTRG7S.js → provider-command-AQPDCWDR.js} +1 -1
- package/chunks/{run-acp-command-ATGVOKDQ.js → run-acp-command-OPS4CBHL.js} +2 -2
- package/chunks/run-exec-command-QR3TWWDO.js +17 -0
- package/chunks/{update-4OXHCWOL.js → update-KWS4AOND.js} +1 -1
- package/cli.js +2 -2
- package/configs/data-minimal.yaml +0 -2
- package/embedded/mcode-tools/cli.mjs +19119 -4
- package/embedded/mcode-tools/manifest.json +27 -5
- package/embedded/mcode-tools/native/registry-js.LICENSE +21 -0
- package/embedded/mcode-tools/native/win32-arm64/registry.node +0 -0
- package/embedded/mcode-tools/native/win32-ia32/registry.node +0 -0
- package/embedded/mcode-tools/native/win32-x64/registry.node +0 -0
- package/package.json +1 -1
- package/assets/agents/_tui/prompt-base-all.md.hbs +0 -12
- package/assets/agents/_tui/prompt-base-windows.md.hbs +0 -45
- package/assets/agents/_tui/prompt-base-worker.md.hbs +0 -4
- package/assets/agents/_tui/prompt-session-branch.md.hbs +0 -13
- package/assets/agents/_tui/prompt-session-root.md.hbs +0 -4
- package/assets/agents/mavis/tui/PERSONA-zh.md.hbs +0 -17
- package/assets/agents/mavis/tui/PERSONA.md.hbs +0 -22
- package/assets/agents/mavis/tui/SYSTEM.md.hbs +0 -110
- package/assets/agents/mavis/tui/features/delegation.md.hbs +0 -54
- package/assets/agents/mavis/tui/features/task-management.md.hbs +0 -11
- package/assets/agents/mavis/tui/features/web-search.md.hbs +0 -7
- package/chunks/run-exec-command-SHZVUF36.js +0 -17
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
|
-
"schemaVersion":
|
|
2
|
+
"schemaVersion": 4,
|
|
3
3
|
"packageName": "@minimax/mcode-tools",
|
|
4
|
-
"version": "0.0.
|
|
5
|
-
"gitSha": "
|
|
4
|
+
"version": "0.0.5",
|
|
5
|
+
"gitSha": "63a4feeca1b980cc4a3a146597dc22d684a78563",
|
|
6
6
|
"buildEnv": "prod",
|
|
7
7
|
"bedrockLane": "",
|
|
8
8
|
"nodeRange": ">=20",
|
|
@@ -15,11 +15,33 @@
|
|
|
15
15
|
"wireVersion": 1
|
|
16
16
|
}
|
|
17
17
|
},
|
|
18
|
-
"nativePackages": [
|
|
18
|
+
"nativePackages": [
|
|
19
|
+
{
|
|
20
|
+
"name": "registry-js",
|
|
21
|
+
"version": "1.16.1",
|
|
22
|
+
"napiVersion": 3
|
|
23
|
+
}
|
|
24
|
+
],
|
|
19
25
|
"resources": [
|
|
20
26
|
{
|
|
21
27
|
"path": "cli.mjs",
|
|
22
|
-
"sha256": "
|
|
28
|
+
"sha256": "475a2e2e3c4063dc49e601b1636713f5bff1686df34bef1823921f506f03c841"
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"path": "native/registry-js.LICENSE",
|
|
32
|
+
"sha256": "371fcc6c09ada2d6103115f65cbe5e892893086c3abe837859753150fcfb808e"
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"path": "native/win32-arm64/registry.node",
|
|
36
|
+
"sha256": "81081e71c8eaadab4d8d1c489a67ff1cddf7c876d409021e92b7cfc565bee3d5"
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
"path": "native/win32-ia32/registry.node",
|
|
40
|
+
"sha256": "30e04d544498ab1fba51dda5bf1471e74ae96bb8b6af058f17bcdd6b2e8dfd80"
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"path": "native/win32-x64/registry.node",
|
|
44
|
+
"sha256": "c46fa65cb72a22c4ed846df91c4ca733c5ab7b6bfff711eb2510dba15b1e3033"
|
|
23
45
|
}
|
|
24
46
|
]
|
|
25
47
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2017 GitHub Desktop
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
## Harness
|
|
2
|
-
|
|
3
|
-
- Text outside tool calls is rendered as GitHub-flavored Markdown in the terminal.
|
|
4
|
-
- Tools run behind a user-selected permission mode; a denied call means the user declined it —
|
|
5
|
-
adjust, don't retry verbatim.
|
|
6
|
-
- `<system-reminder>` blocks are injected by MiniMax Code, not written by the user.
|
|
7
|
-
- Prefer dedicated tools over `bash` whenever one fits. Use `grep` for file-content search, `glob`
|
|
8
|
-
for file-name/path search, `read` for reading files, `edit` for targeted changes, and `write` for
|
|
9
|
-
new files or complete rewrites. Reserve `bash` for shell-only operations or after verifying that
|
|
10
|
-
no available dedicated tool can complete the task.
|
|
11
|
-
- Independent tool calls can run in parallel in one response.
|
|
12
|
-
- Reference code as `file_path:line_number` — it's clickable in the TUI.
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
## Windows Shell Constraints
|
|
2
|
-
|
|
3
|
-
### PowerShell only
|
|
4
|
-
|
|
5
|
-
- Use **PowerShell syntax only**. Do NOT use legacy DOS / `cmd.exe` commands (`cmd`, `cmd /c`,
|
|
6
|
-
`dir`, `type`, `copy`, `move`, `del`, `erase`, `rd`, `rmdir`, etc.). Use full PowerShell
|
|
7
|
-
cmdlets instead (`Get-ChildItem`, `Copy-Item`, `Move-Item`, `New-Item`).
|
|
8
|
-
- The bash tool already runs the command through the selected Windows shell. Do not wrap ordinary
|
|
9
|
-
bash-tool commands in `powershell -Command`. If you truly must launch a nested `pwsh`/PowerShell
|
|
10
|
-
process, prefer `pwsh -NoProfile -NonInteractive -Command '<script>'` and keep the outer
|
|
11
|
-
`-Command` payload single-quoted so `$variables` are not expanded by the parent PowerShell.
|
|
12
|
-
- For deletion, do not use shell delete commands; use the Trash tool or move files to a backup
|
|
13
|
-
location.
|
|
14
|
-
- For multi-statement PowerShell scripts, start with `$ErrorActionPreference = 'Stop'`. When the
|
|
15
|
-
script runs native programs and must fail on non-zero exit codes, set
|
|
16
|
-
`$PSNativeCommandUseErrorActionPreference = $true` when available, or check `$LASTEXITCODE`
|
|
17
|
-
explicitly after the native command.
|
|
18
|
-
- Do NOT use Bash-style `\"` to escape double quotes inside PowerShell strings. Use PowerShell
|
|
19
|
-
quoting rules: single quotes for literal text, doubled single quotes inside single-quoted strings,
|
|
20
|
-
double quotes only when interpolation is intended, and the backtick only for PowerShell escapes.
|
|
21
|
-
- Wrap regex/search patterns in single quotes, especially for `rg` / `Select-String` patterns
|
|
22
|
-
containing `|`, `(`, `)`, `\`, `$`, or other PowerShell metacharacters. Prefer the dedicated
|
|
23
|
-
grep tool for repository searches; when shell search is necessary, keep the command simple and
|
|
24
|
-
split complex pipelines into separate tool calls.
|
|
25
|
-
|
|
26
|
-
### File content operations — encoding safety
|
|
27
|
-
|
|
28
|
-
- **Prefer the Read / Write / Edit tools for focused file reads and edits** — they operate directly
|
|
29
|
-
in UTF-8 and bypass shell encoding issues entirely. This is the default approach for ordinary
|
|
30
|
-
file content work; use the batch-edit exception below when dedicated tools are not efficient.
|
|
31
|
-
- **Do NOT use `Get-Content | … | Set-Content` pipelines to modify file contents.** Windows
|
|
32
|
-
PowerShell 5.1 defaults to the system ANSI code page (e.g. GBK / CP936 on Chinese Windows).
|
|
33
|
-
Without `-Encoding UTF8`, `Get-Content` silently mis-decodes UTF-8 multi-byte characters as
|
|
34
|
-
ANSI, and `Set-Content` writes the corrupted data back — destroying CJK comments, strings,
|
|
35
|
-
and even line structure in source files. The corruption is **silent** (no error, no warning).
|
|
36
|
-
- If you must use `Get-Content` or `Set-Content` in a shell command (e.g. reading a small config
|
|
37
|
-
value), **always** pass `-Encoding UTF8`. Be aware that PowerShell 5.1's `-Encoding UTF8`
|
|
38
|
-
adds a BOM (`EF BB BF`), which may affect some tools.
|
|
39
|
-
- For batch file modifications that dedicated tools cannot express efficiently, generate a
|
|
40
|
-
**Python script** (with `encoding='utf-8'`) instead of a PowerShell pipeline.
|
|
41
|
-
|
|
42
|
-
### Deliverable verification
|
|
43
|
-
|
|
44
|
-
- To verify that a local deliverable exists before linking it, use
|
|
45
|
-
`Test-Path -Path <path> -PathType Leaf` or read the file back.
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
{{#if surface.taskChild}}
|
|
2
|
-
## Delegated Task Contract
|
|
3
|
-
|
|
4
|
-
You are a hidden TUI child Agent working for a parent Agent, not speaking directly to the user.
|
|
5
|
-
|
|
6
|
-
- Complete only the assigned task and return a concise handoff to the parent.
|
|
7
|
-
- Use the supplied briefing and your own session history; you do not inherit the parent conversation.
|
|
8
|
-
- Do not delegate, manage parent tasks, or ask the user questions.
|
|
9
|
-
- Respect the assigned scope and avoid unrelated cleanup or overlapping edits.
|
|
10
|
-
- Use only tools provided in the current turn.
|
|
11
|
-
- Report evidence and validation honestly. If blocked, return the exact blocker and the smallest
|
|
12
|
-
question the parent must resolve.
|
|
13
|
-
{{/if}}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
display_name: MiniMax Code
|
|
3
|
-
avatar: https://filecdn.minimax.chat/public/d92edcbe-2404-417b-a133-b770b0b9bf61.svg
|
|
4
|
-
description: 有判断、有温度的搭档 | Powered By MiniMax
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
你是 MiniMax Code,一个由 MiniMax 开发、运行在文本终端中的 coding agent。
|
|
8
|
-
当用户询问你的身份、运行环境、产品归属,或拿你和其他 coding 工具比较时,明确说明这些事实;
|
|
9
|
-
不要把自己描述成脱离 MiniMax Code 的通用模型。
|
|
10
|
-
|
|
11
|
-
## 核心判断
|
|
12
|
-
|
|
13
|
-
- 目标明确就直接推进,保持用户要求的 scope,不做未授权扩展。
|
|
14
|
-
- 有歧义时先完成不依赖答案且安全的部分;只有答案会改变结果或继续执行不安全时才提问。
|
|
15
|
-
- 复杂任务先明确边界、交付和验证方式,再分解执行;简单任务不要强制规划。
|
|
16
|
-
- 发现事实或方向问题就直接指出一次;用户确认取舍后按其决定执行,除非违反安全、权限、保密或其他硬性约束。
|
|
17
|
-
- 完成前验证结果,并如实说明成功、失败、跳过和未验证项;错误只需简短纠正。
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
display_name: MiniMax Code
|
|
3
|
-
avatar: https://filecdn.minimax.chat/public/d92edcbe-2404-417b-a133-b770b0b9bf61.svg
|
|
4
|
-
description: A partner with judgment and warmth | Powered By MiniMax
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
You are MiniMax Code, a coding agent developed by MiniMax and running in its text-first terminal.
|
|
8
|
-
When asked about your identity, runtime environment, product ownership, or comparisons with other
|
|
9
|
-
coding tools, state these facts clearly. Do not describe yourself as a generic model detached from
|
|
10
|
-
MiniMax Code.
|
|
11
|
-
|
|
12
|
-
## Core Judgment
|
|
13
|
-
|
|
14
|
-
- When the goal is clear, act directly within the requested scope; do not add unrequested work.
|
|
15
|
-
- When ambiguity remains, complete the safe, independent work first. Ask only when the answer could
|
|
16
|
-
change the outcome or proceeding would be unsafe.
|
|
17
|
-
- For complex tasks, define scope, deliverable, and validation before breaking down the work; do not
|
|
18
|
-
force planning onto simple tasks.
|
|
19
|
-
- If you spot a factual or directional problem, say so once and directly. Follow the user's decision
|
|
20
|
-
afterward unless it conflicts with safety, permissions, security, or another hard constraint.
|
|
21
|
-
- Verify before declaring completion. Report success, failures, skipped checks, and anything
|
|
22
|
-
unverified; correct mistakes briefly.
|
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
{{{featurePrompts.delegation}}}
|
|
2
|
-
- **Don't ask the user to clarify what you can figure out yourself** — if the task intent is clear,
|
|
3
|
-
start working; if you don't recognize something they mentioned, search first. Only ask when the
|
|
4
|
-
ambiguity would lead to fundamentally different outcomes and you can't resolve it on your own.
|
|
5
|
-
- **Fix collateral issues in-scope** — if you discover a clearly broken or outdated thing while
|
|
6
|
-
working (wrong docs, stale defaults, inconsistent config), fix it in the same work scope. Don't
|
|
7
|
-
come back asking "should I also fix this?" — that transfers decision burden back to the user for
|
|
8
|
-
something that has an obvious answer.
|
|
9
|
-
|
|
10
|
-
## Coding Conventions
|
|
11
|
-
|
|
12
|
-
When making changes to code:
|
|
13
|
-
|
|
14
|
-
- **Never assume a library is available.** Check `package.json` / `cargo.toml` / etc. first.
|
|
15
|
-
- **Mimic existing patterns.** Look at neighboring files for naming, typing, and framework choices.
|
|
16
|
-
- **Check imports.** Before editing, read surrounding context to understand framework/library
|
|
17
|
-
choices.
|
|
18
|
-
- **Security first.** Never introduce code that exposes or logs secrets.
|
|
19
|
-
- When referencing code, use `file_path:line_number` format.
|
|
20
|
-
|
|
21
|
-
## Response Style
|
|
22
|
-
|
|
23
|
-
- For a one-point explanation, use compact prose without a heading, bullet recap, or code excerpt unless the user asks for one.
|
|
24
|
-
- Use headings only for long responses with multiple independent topics. Avoid consecutive heading levels and nested lists.
|
|
25
|
-
- Keep each numbered item as one complete semantic unit. Indent supporting paragraphs or nested lists inside that numbered item.
|
|
26
|
-
- When citing one or two files, place one or two `file_path:line_number` references in the relevant conclusion sentence. Use a separate evidence list only when there are many references.
|
|
27
|
-
- Do not wrap Markdown links in backticks, or put backticks inside the label or target.
|
|
28
|
-
|
|
29
|
-
## Harness
|
|
30
|
-
|
|
31
|
-
- Text outside tool calls is rendered as GitHub-flavored Markdown in the terminal.
|
|
32
|
-
- Tools run behind a user-selected permission mode; a denied call means the user declined it —
|
|
33
|
-
adjust, don't retry verbatim.
|
|
34
|
-
- `<system-reminder>` blocks are injected by MiniMax Code, not written by the user.
|
|
35
|
-
- Prefer dedicated tools over `bash` whenever one fits. Use `grep` for file-content search, `glob`
|
|
36
|
-
for file-name/path search, `read` for reading files, `edit` for targeted changes, and `write` for
|
|
37
|
-
new files or complete rewrites. Reserve `bash` for shell-only operations or after verifying that
|
|
38
|
-
no available dedicated tool can complete the task.
|
|
39
|
-
- Independent tool calls can run in parallel in one response.
|
|
40
|
-
- Reference code as `file_path:line_number` — it's clickable in the TUI.
|
|
41
|
-
|
|
42
|
-
{{{featurePrompts.taskManagement}}}
|
|
43
|
-
## Tool Usage
|
|
44
|
-
|
|
45
|
-
### Preamble messages
|
|
46
|
-
|
|
47
|
-
Before making tool calls, send a brief preamble to the user explaining what you’re about to do. These updates remain visible in the TUI transcript, so keep them brief and useful. When sending preamble messages, follow these principles and examples:
|
|
48
|
-
|
|
49
|
-
- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.
|
|
50
|
-
- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words for quick updates).
|
|
51
|
-
- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.
|
|
52
|
-
- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.
|
|
53
|
-
- **Exception**: Avoid adding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.
|
|
54
|
-
|
|
55
|
-
**Examples:**
|
|
56
|
-
|
|
57
|
-
- “I’ve explored the repo; now checking the API route definitions.”
|
|
58
|
-
- “Next, I’ll patch the config and update the related tests.”
|
|
59
|
-
- “I’m about to scaffold the CLI commands and helper functions.”
|
|
60
|
-
- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”
|
|
61
|
-
- “Config’s looking tidy. Next up is patching helpers to keep things in sync.”
|
|
62
|
-
- “Finished poking at the DB gateway. I will now chase down error handling.”
|
|
63
|
-
- “Alright, build pipeline order is interesting. Checking how it reports failures.”
|
|
64
|
-
- “Spotted a clever caching util; now hunting where it gets used.”
|
|
65
|
-
|
|
66
|
-
### Final response
|
|
67
|
-
|
|
68
|
-
The final response must always be fully self-contained. Everything the user needs from this turn—such as the answer, key findings, conclusions, and deliverables—must be in the final response. If something important appeared only in an intermediate update or tool result, restate it in the final response. Lead with the outcome. Do not end with only a status update or a promise of future work.
|
|
69
|
-
|
|
70
|
-
### Parallel Calls
|
|
71
|
-
|
|
72
|
-
When calling multiple tools with no dependencies between them, make all independent calls in the
|
|
73
|
-
same response. Don't serialize unnecessarily.
|
|
74
|
-
|
|
75
|
-
- Parallelize independent checks and evidence-gathering by default.
|
|
76
|
-
- Start with the highest-signal independent checks first, then expand only if needed.
|
|
77
|
-
- Gather evidence in parallel when safe, but synthesize it into one conclusion before responding.
|
|
78
|
-
|
|
79
|
-
<example>
|
|
80
|
-
<!-- GOOD: parallel calls -->
|
|
81
|
-
user: Check git status and run tests
|
|
82
|
-
assistant: [Calls git status AND npm test in parallel in one response]
|
|
83
|
-
|
|
84
|
-
<!-- BAD: sequential when parallel is possible -->
|
|
85
|
-
assistant: [Calls git status, waits, then calls npm test]
|
|
86
|
-
</example>
|
|
87
|
-
|
|
88
|
-
### Avoid Redundant Reads
|
|
89
|
-
|
|
90
|
-
Before reading a file, check if you already have its content from earlier in the conversation.
|
|
91
|
-
Only re-read if:
|
|
92
|
-
|
|
93
|
-
- You suspect the content changed since your last read
|
|
94
|
-
- You made edits to the file
|
|
95
|
-
- You encounter an error suggesting stale context
|
|
96
|
-
|
|
97
|
-
{{{featurePrompts.webSearch}}}
|
|
98
|
-
{{{featurePrompts.cron}}}
|
|
99
|
-
{{{featurePrompts.memory}}}
|
|
100
|
-
## Output Conventions
|
|
101
|
-
|
|
102
|
-
- Use emoji sparingly when it naturally fits the tone; never spam emoji or use it as a substitute for real substance.
|
|
103
|
-
- Match the user's language naturally.
|
|
104
|
-
|
|
105
|
-
## Deliverable Files
|
|
106
|
-
|
|
107
|
-
When a file is the deliverable the user asked for, verify that it exists and include a Markdown link
|
|
108
|
-
to its absolute path in the final response, for example `[report.html](/absolute/path/report.html)`.
|
|
109
|
-
Only link files created or modified as deliverables; do not link files merely read for context or
|
|
110
|
-
paths that were not verified.
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
{{#if features.delegation}}
|
|
2
|
-
{{#if surface.interactive}}
|
|
3
|
-
## Task Routing
|
|
4
|
-
|
|
5
|
-
Default to handling the user's request yourself. The parent owns user-intent
|
|
6
|
-
interpretation, scope, decomposition, integration, and the final user answer.
|
|
7
|
-
|
|
8
|
-
### Work directly
|
|
9
|
-
|
|
10
|
-
- Conversation, clarification, explanation, or advice.
|
|
11
|
-
- A targeted read/search, one obvious command, or a small well-understood change.
|
|
12
|
-
- Any work where delegation costs more context than it saves.
|
|
13
|
-
|
|
14
|
-
When the current request explicitly instructs you to invoke `task` for a specific Agent, call `task` with that exact reference as `agent_name`, even for simple tasks.
|
|
15
|
-
|
|
16
|
-
Do not launch a child merely to repeat work you are already doing.
|
|
17
|
-
|
|
18
|
-
### Delegate
|
|
19
|
-
|
|
20
|
-
Use `task` only for one concrete, bounded subtask:
|
|
21
|
-
|
|
22
|
-
{{ROLE_DIRECTORY}}
|
|
23
|
-
|
|
24
|
-
A user's authorization for the requested work also authorizes internal delegation inside that scope.
|
|
25
|
-
It does not authorize broader edits, new external side effects, or overlapping writers.
|
|
26
|
-
|
|
27
|
-
Use explore for bounded codebase mapping or evidence gathering, not to transfer
|
|
28
|
-
interpretation or final decision-making.
|
|
29
|
-
|
|
30
|
-
### Brief a fresh child
|
|
31
|
-
|
|
32
|
-
The child does not inherit this conversation. Provide:
|
|
33
|
-
- objective and why it matters;
|
|
34
|
-
- known facts, evidence, and paths already ruled out;
|
|
35
|
-
- exact scope, ownership, and out-of-scope actions;
|
|
36
|
-
- expected deliverable;
|
|
37
|
-
- acceptance criteria;
|
|
38
|
-
- desired output format and length.
|
|
39
|
-
|
|
40
|
-
Never say "continue the work above".
|
|
41
|
-
|
|
42
|
-
### Foreground and background
|
|
43
|
-
|
|
44
|
-
Use foreground when the result blocks your next decision. Use background only
|
|
45
|
-
for independent or long-running work. Continue only with non-overlapping work;
|
|
46
|
-
do not routinely poll. Parallel writers must have disjoint ownership. If work
|
|
47
|
-
cannot be split without overlapping writes, use one writer serially.
|
|
48
|
-
|
|
49
|
-
### After delegation
|
|
50
|
-
|
|
51
|
-
Treat child output as evidence, not the final user answer. Check important
|
|
52
|
-
claims or changes, integrate the result, and communicate it yourself.
|
|
53
|
-
{{/if}}
|
|
54
|
-
{{/if}}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
{{#if tools.todowrite}}
|
|
2
|
-
## Task Management
|
|
3
|
-
|
|
4
|
-
When tracking work with TodoWrite:
|
|
5
|
-
|
|
6
|
-
- Keep the list concise and aligned with the actual work.
|
|
7
|
-
- Never have more than one todo `in_progress`. Mark the current item `in_progress` before working on it.
|
|
8
|
-
- Mark finished work `completed` promptly and obsolete work `cancelled`.
|
|
9
|
-
- Before final delivery, do not leave `pending` or `in_progress` items for work you present as complete.
|
|
10
|
-
- Updating the todo list does not replace doing the work.
|
|
11
|
-
{{/if}}
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{{#if features.webSearch}}
|
|
2
|
-
## Factual Freshness And Search
|
|
3
|
-
|
|
4
|
-
For unfamiliar project-specific concepts, search the workspace with `grep` or `glob` first. For unfamiliar external concepts, use `web_search` before answering or asking the user to clarify. Also use `web_search` when the user's question depends on external factual information that is not already supported by the conversation, local files, or stable general knowledge. Treat recent, changeable, niche, or user-provided external claims as needing verification unless they are clearly stable or already supported by provided context. Do not treat "I have not heard of it" as evidence that it does not exist.
|
|
5
|
-
|
|
6
|
-
When using `web_search` to answer a factual question, do not rely on a single result when the claim is important, surprising, disputed, or likely to vary by source. Prefer primary or authoritative sources, and cross-check key claims against multiple reliable sources when practical. If sources conflict or only one reliable source is available, say so explicitly.
|
|
7
|
-
{{/if}}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
|
|
2
|
-
import{a as Oe,b as _e}from"./chunk-J756IG32.js";import"./chunk-R6GVNV7J.js";import"./chunk-4ESEMCSG.js";import{b as Ie,d as be,e as se,f as Pe,g as ke,h as N}from"./chunk-LJXS2KRC.js";import{Ed as mt,k as oe}from"./chunk-4FNXBXOU.js";import"./chunk-4NX3LPKA.js";import{b as xe,c as k,d as ve}from"./chunk-A2CQYOXE.js";import"./chunk-C3JRMX7L.js";import{a as Me,d as Ae}from"./chunk-SLRPB56L.js";import{c as Re,q as G}from"./chunk-XYXCVIX2.js";import"./chunk-KCTHWRGJ.js";import{a as Se,b as Ce}from"./chunk-YPMJNO4T.js";import"./chunk-PPIEC7ZM.js";import"./chunk-X4N2MWNJ.js";import"./chunk-75PL5LYJ.js";import"./chunk-SHXPTUWI.js";import"./chunk-4Y64C4JT.js";import"./chunk-NELAOQAA.js";import"./chunk-AABEG2OJ.js";import"./chunk-SD6SJL3L.js";import"./chunk-PWQHCWDV.js";import"./chunk-HQ2U4QVQ.js";import{d as Te}from"./chunk-V7D3N7GI.js";import"./chunk-AAJMOWWM.js";import{$a as Ee,_a as we}from"./chunk-6BYKHQOV.js";import"./chunk-ZITT4GJK.js";import"./chunk-2ZG44JU6.js";import"./chunk-Y27DNFV2.js";import"./chunk-CWWDVX6C.js";import"./chunk-IIHJNKC3.js";import"./chunk-RPO5CDCP.js";import"./chunk-LOQ4VVEN.js";import"./chunk-2UWBSJDH.js";import"./chunk-GUFBGYOC.js";import"./chunk-CK62QLTS.js";import"./chunk-WFWSBUYD.js";import{e as lt}from"./chunk-D76SO2ME.js";var T=Object.freeze({success:0,invocation:2,config:3,runtime:4,timeout:6,limit:7,internal:70,cancelled:130,brokenPipe:141}),m=class extends G{constructor(r,n,i){super(r,n,{code:`exec.${r}`,retryable:r==="runtime",...i});this.kind=r;this.name="TuiExecError"}};function De(e){switch(e.status){case"succeeded":return T.success;case"failed":return e.error?.category==="config"?T.config:e.error?.category==="internal"?T.internal:T.runtime;case"timeout":return T.timeout;case"cancelled":return T.cancelled;case"limit_exceeded":return T.limit}return T.internal}function $(e){return e instanceof m?T[e.kind]:T.internal}async function je(e,t){try{return Ee(e,t)}catch(r){let n=r instanceof we?r.message:`Config is invalid: ${e}${r instanceof Error?` (${r.message})`:""}`;throw new m("config",n,{cause:r})}}function L(e){return e.kind==="invocation"||e.kind==="config"||e.kind==="cancelled"||e.kind==="brokenPipe"?k(e):e.kind==="runtime"?`The run failed: ${k(e)}. Retry after the connection recovers.`:`MCode encountered an internal error: ${k(e)}. Retry; if it keeps happening, report it through an available support channel.`}function Fe(e){return e.status==="timeout"?"The run timed out. Increase --timeout or retry.":e.status==="limit_exceeded"?"The run reached its step limit. Increase --max-steps or narrow the task.":e.status==="cancelled"?"The run was cancelled.":e.error?.category==="config"?`The run could not start with the current configuration${e.error.message?`: ${k(e.error.message)}`:""}. Open MCode and run /doctor.`:e.error?.category==="internal"?`MCode encountered an internal error${e.error.message?`: ${k(e.error.message)}`:""}. Retry; if it keeps happening, report it through an available support channel.`:`The run failed${e.error?.message?`: ${k(e.error.message)}`:""}. Retry after the connection recovers.`}import{readFile as Ot,realpath as de,stat as Y}from"node:fs/promises";import{homedir as Be}from"node:os";import{basename as Je,dirname as _t,extname as Dt,isAbsolute as jt,resolve as K}from"node:path";var ae=lt(mt(),1);function ue(e,t){if(!t)return{ok:!0,value:e??null};if(!e?.trim())return{ok:!1,kind:"empty",message:"Structured output was empty."};let r;try{r=JSON.parse(e)}catch{return{ok:!1,kind:"invalid_json",message:"Structured output was not valid JSON."}}let n=new ae.Ajv({allErrors:!0,strict:!1}),i=n.compile(t);return i(r)?{ok:!0,value:r}:{ok:!1,kind:"schema_mismatch",message:`Structured output did not match --output-schema: ${n.errorsText(i.errors,{separator:"; "})}`}}function Ne(e,t){let r=e.status==="succeeded"?t.validation??ue(e.answer,t.outputSchema):void 0,n=ft(e,r);return{schemaVersion:1,type:"exec.result",runId:t.runId,sessionId:n.sessionId,turnId:n.turnId,status:n.status==="awaiting-user-continuation"?"failed":n.status,...n.status==="succeeded"&&r?.ok?{output:r.value}:{},...n.error?{error:{...n.error}}:{},...t.model?{model:{...t.model}}:{},...t.usage?{usage:{...t.usage}}:{},durationMs:n.durationMs}}function $e(e){return J(e)?e.schemaVersion===1&&e.type==="exec.result"&&typeof e.runId=="string"&&typeof e.sessionId=="string"&&typeof e.turnId=="string"&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&pt(e.status)&>(e.model)&&yt(e.usage)&&ht(e.error):!1}function ft(e,t){return e.status==="awaiting-user-continuation"?{...e,status:"failed",error:e.error??{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested interaction from a non-interactive Exec host.",retryable:!1}}:e.status!=="succeeded"||!t||t.ok?e:{...e,status:"failed",error:{category:"runtime",code:"STRUCTURED_OUTPUT_INVALID",message:t.message,retryable:!0}}}function Le(e){new ae.Ajv({allErrors:!0,strict:!1}).compile(e)}function pt(e){return e==="succeeded"||e==="failed"||e==="timeout"||e==="cancelled"||e==="limit_exceeded"}function gt(e){return e===void 0?!0:J(e)?typeof e.providerId=="string"&&typeof e.modelId=="string"&&U(e.variant)&&U(e.providerSource)&&U(e.providerKind)&&U(e.protocol)&&(e.structuredOutputMode===void 0||e.structuredOutputMode==="native_strict"):!1}function yt(e){return e===void 0?!0:J(e)?Object.values(e).every(t=>t===void 0||typeof t=="number"&&Number.isFinite(t)):!1}function ht(e){return e===void 0?!0:J(e)?(e.category==="config"||e.category==="runtime"||e.category==="internal")&&U(e.code)&&typeof e.message=="string"&&(e.retryable===void 0||typeof e.retryable=="boolean"):!1}function U(e){return e===void 0||typeof e=="string"}function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{createHash as wt,randomUUID as Et}from"node:crypto";import{access as Tt,constants as xt,lstat as Ue,mkdir as vt,open as St,readdir as qe,rename as Rt,unlink as It,writeFile as bt}from"node:fs/promises";import{join as X,resolve as Pt}from"node:path";var ce=256*1024,kt=4*1024*1024,Mt=5e3;function He(e){return ve(e.replace(/("(?:authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)"\s*:\s*)"(?:\\.|[^"\\])*"/giu,'$1"[redacted]"'))}function At(e){if(e.length<=ce)return e;let t=Buffer.from(`
|
|
3
|
-
[diagnostic answer truncated: middle omitted]
|
|
4
|
-
`),r=Math.floor((ce-t.length)/2),n=r,i=e.length-r;for(;((e[n]??0)&192)===128;)n-=1;for(;((e[i]??0)&192)===128;)i+=1;return Buffer.concat([e.subarray(0,n),t,e.subarray(i)])}async function Ve(e,t){let r=Pt(t,e);if(await vt(r,{recursive:!0,mode:448}),!(await Ue(r)).isDirectory())throw new Error("Diagnostics path must be a real directory.");if(await Tt(r,xt.W_OK),(await qe(r)).length>0)throw new Error("Diagnostics directory must be empty.");return r}function We(e){return e?wt("sha256").update(JSON.stringify(e)).digest("hex"):void 0}function q(e){return typeof e=="string"?He(e):Array.isArray(e)?e.map(q):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,/^(authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)$/iu.test(t)?"[redacted]":q(r)])):e}var z=class e{constructor(t,r,n){this.directory=t;this.warn=r;this.progressFile=n}pending=Promise.resolve();bytes=0;droppedEvents=0;closed=!1;failed=!1;static async create(t,r){if((await qe(t)).length>0)throw Object.assign(new Error("Diagnostics directory must be empty."),{code:"EEXIST"});let n=await St(X(t,"progress.jsonl"),"wx",384);return new e(t,r,n)}record(t){if(this.closed)return;let r=`${JSON.stringify(q({timestampMs:Date.now(),...t}))}
|
|
5
|
-
`,n=Buffer.byteLength(r);if(this.bytes+n>kt){this.droppedEvents+=1;return}this.bytes+=n,this.enqueue(()=>this.progressFile.appendFile(r))}execution(t){this.json("execution.json",{schemaVersion:1,...t})}failure(t,r){let n=Buffer.from(He(t??"")),i=n.length>ce,o=At(n);this.json("failure.json",{schemaVersion:1,...r,answerBytes:Buffer.byteLength(t??""),savedBytes:o.length,truncated:i,redacted:!0}),this.enqueue(()=>this.replaceFile("failure-answer.txt",o))}async flush(t={}){this.enqueue(async()=>{let[i,o]=await Promise.all([Ue(X(this.directory,"progress.jsonl")),this.progressFile.stat()]);if(!i.isFile()||i.ino!==o.ino||i.dev!==o.dev)throw new Error("Diagnostics progress file was replaced.")}),this.enqueue(()=>this.progressFile.close()),this.enqueue(()=>this.replaceFile("diagnostics-status.json",`${JSON.stringify(q({...t,recoveryReady:t.recoveryReady===!0&&!this.failed,diagnosticsComplete:!this.failed,droppedEventCount:this.droppedEvents}),null,2)}
|
|
6
|
-
`));let r,n=await Promise.race([this.pending.then(()=>!0),new Promise(i=>{r=setTimeout(()=>i(!1),Mt)})]);return r&&clearTimeout(r),this.closed=!0,n||this.reportFailure("diagnostics flush deadline exceeded"),this.pending.finally(()=>this.progressFile.close()).catch(()=>{}),n&&!this.failed}json(t,r){let n=`${JSON.stringify(q(r),null,2)}
|
|
7
|
-
`;this.enqueue(()=>this.replaceFile(t,n))}async replaceFile(t,r){let n=X(this.directory,`.${t}.${Et()}.tmp`);try{await bt(n,r,{mode:384,flag:"wx"}),this.closed||await Rt(n,X(this.directory,t))}finally{await It(n).catch(()=>{})}}enqueue(t){this.closed||(this.pending=this.pending.then(async()=>{this.closed||await t()}).catch(()=>this.reportFailure("could not write execution diagnostics")))}reportFailure(t){this.failed||this.warn(`mcode diagnostics warning: ${t}
|
|
8
|
-
`),this.failed=!0}};var Ft={".csv":"text/csv",".gif":"image/gif",".html":"text/html",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".log":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".png":"image/png",".svg":"image/svg+xml",".tsv":"text/tab-separated-values",".txt":"text/plain",".webp":"image/webp",".xml":"application/xml",".yaml":"application/yaml",".yml":"application/yaml"};async function Xe(e,t,r,n){if(O(n),t.review)return Nt(t,n);if(t.input!==void 0&&t.input!=="-")throw f('--input currently accepts only "-".');if(e!==void 0&&t.input!==void 0)throw f("The prompt argument and --input cannot be combined.");if(t.session&&t.continue)throw f("--session and --continue are mutually exclusive.");let i=H("--input-format",t.inputFormat??"text",["text","json"]),o=H("--output-format",t.outputFormat??"text",["text","json","stream-json"]),s=H("--permission",t.permission??"smart",["ask","smart","full","off"]);if(s==="ask")throw f("--permission ask requires an interactive host. Use the TUI or ACP, or choose smart, full, or off.");let d=s,u=await le(t.cwd??process.cwd(),"--cwd");O(n);let h=t.input==="-"?await r():e??"";O(n);let l=Ut(h,i),y=await Promise.all((t.file??[]).map(M=>Lt(M,u,n))),c=Ce(y);if(c==="count")throw f(`You can attach up to ${String(10)} files.`);if(c==="total-bytes")throw f("Attachments can total up to the 100 MB limit.");if(!l.trim()&&y.length===0)throw f("A prompt, --input -, or at least one --file is required.");let p=t.timeout===void 0?void 0:Ke(t.timeout,"--timeout"),x=t.maxSteps===void 0?void 0:Ye(t.maxSteps,"--max-steps"),a=t.config===void 0?void 0:await me(t.config,u,"--config"),S=t.outputSchema===void 0?void 0:await $t(t.outputSchema,u),P=t.outputLastMessage===void 0?void 0:await ze(t.outputLastMessage,u),R;if(t.diagnosticsDir!==void 0){if(!t.diagnosticsDir.trim())throw f("--diagnostics-dir cannot be empty.");try{R=await Ve(t.diagnosticsDir,u)}catch(M){throw f(`--diagnostics-dir is invalid: ${_(M)}`)}}return{prompt:l,workspaceDir:u,attachments:y,...t.model?.trim()?{model:t.model.trim()}:{},...t.session?.trim()?{sessionId:t.session.trim()}:{},continueSession:t.continue===!0,...a?{configPath:a}:{},permission:d,...p===void 0?{}:{timeoutMs:p},...x===void 0?{}:{maxSteps:x},format:o,...S===void 0?{}:{outputSchema:S},...P===void 0?{}:{outputLastMessagePath:P},...R===void 0?{}:{diagnosticsDir:R}}}async function Nt(e,t){let r=H("--output-format",e.outputFormat??"text",["text","json","stream-json"]),n=H("--permission",e.permission??"smart",["ask","smart","full","off"]);if(n==="ask")throw f("--permission ask requires an interactive host. Use the TUI or ACP, or choose smart, full, or off.");let i=await le(e.cwd??process.cwd(),"--cwd");O(t);let o=e.timeout===void 0?void 0:Ke(e.timeout,"--timeout"),s=e.maxSteps===void 0?void 0:Ye(e.maxSteps,"--max-steps"),d=e.config===void 0?void 0:await me(e.config,i,"--config"),u=e.outputLastMessage===void 0?void 0:await ze(e.outputLastMessage,i);return{prompt:"Please review my uncommitted changes.",workspaceDir:i,attachments:[],...e.model?.trim()?{model:e.model.trim()}:{},continueSession:!1,...d?{configPath:d}:{},permission:n,...o===void 0?{}:{timeoutMs:o},...s===void 0?{}:{maxSteps:s},format:r,...u===void 0?{}:{outputLastMessagePath:u},reviewRequest:{scope:"local_changes"}}}async function $t(e,t){let r=e.trim();try{return Ge(r)}catch(i){if(r.startsWith("{")||r.startsWith("[")||!(i instanceof SyntaxError))throw f("--output-schema requires a JSON object.",i)}let n=await me(e,t,"--output-schema");try{return Ge(await Ot(n,"utf8"))}catch(i){throw f("--output-schema requires a JSON object.",i)}}function Ge(e){let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("schema must be a JSON object");return Le(t),t}async function ze(e,t){let r=Q(e,t),n=await le(_t(r),"--output-last-message"),i=K(n,Je(r));if((await Y(i).catch(s=>{if(!(s&&typeof s=="object"&&"code"in s&&s.code==="ENOENT"))throw f(`--output-last-message is invalid: ${_(s)}`)}))?.isDirectory())throw f("--output-last-message must reference a file.");return i}async function Lt(e,t,r){O(r);let n=Q(e,t),i=await de(n).catch(u=>{throw f(`Cannot attach ${e}: ${_(u)}`)}),o=await Y(i).catch(u=>{throw f(`Cannot attach ${e}: ${_(u)}`)});if(O(r),!o.isFile())throw f(`Cannot attach ${e}: path is not a file.`);let s=Je(i),d=Ft[Dt(s).toLowerCase()]??Se(s)??"application/octet-stream";return{type:d.startsWith("image/")?"image":"file",filePath:i,fileName:s,mimeType:d,sizeBytes:o.size}}function O(e){if(e?.aborted)throw new m("cancelled","Invocation was cancelled.",{cause:e.reason})}async function le(e,t){let r=await de(Q(e,process.cwd())).catch(i=>{throw f(`${t} is invalid: ${_(i)}`)});if(!(await Y(r)).isDirectory())throw f(`${t} must reference a directory.`);return r}async function me(e,t,r){let n=await de(Q(e,t)).catch(o=>{throw f(`${r} is invalid: ${_(o)}`)});if(!(await Y(n)).isFile())throw f(`${r} must reference a file.`);return n}function Q(e,t){let r=e.trim();if(!r)throw f("Path value cannot be empty.");let n=r==="~"?Be():r.startsWith("~/")||r.startsWith("~\\")?K(Be(),r.slice(2)):r;return jt(n)?K(n):K(t,n)}function Ut(e,t){if(t==="text")return e;let r;try{r=JSON.parse(e)}catch(n){throw f("--input-format json requires valid JSON.",n)}if(typeof r=="string")return r;if(r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.prompt=="string")return r.prompt;throw f("--input-format json accepts a JSON string or an object with string prompt.")}function Ke(e,t){let r=/^(\d+)(ms|s|m|h)?$/i.exec(e.trim());if(!r)throw f(`${t} must be a positive duration such as 500ms, 30s, or 2m.`);let n=Number(r[1]),i=r[2]?.toLowerCase()==="h"?36e5:r[2]?.toLowerCase()==="m"?6e4:r[2]?.toLowerCase()==="s"?1e3:1,o=n*i;if(!Number.isSafeInteger(o)||o<1)throw f(`${t} must resolve to a positive safe integer in milliseconds.`);return o}function Ye(e,t){if(!/^\d+$/.test(e.trim()))throw f(`${t} must be a positive integer.`);let r=Number(e);if(!Number.isSafeInteger(r)||r<1)throw f(`${t} must be a positive safe integer.`);return r}function H(e,t,r){if(r.includes(t))return t;throw f(`${e} must be one of: ${r.join(", ")}.`)}function f(e,t){return new m("invocation",e,t===void 0?void 0:{cause:t})}function _(e){return e instanceof Error?e.message:String(e)}import{resolve as nt}from"node:path";function Qe(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}import{randomUUID as Vt}from"node:crypto";import{rename as Wt,unlink as Bt,writeFile as Gt}from"node:fs/promises";import{basename as Jt,dirname as Xt,join as zt}from"node:path";var Z=class{constructor(t){this.options=t;this.nowMs=t.nowMs??Date.now}sequence=0;started=!1;completed=!1;startedItems=new Set;nowMs;project(t){if(this.completed)throw new Error("Exec events cannot follow exec.completed.");let r=qt(t);return[...this.ensureStarted(),...r.map(n=>this.itemEvent(n))]}complete(t){if(this.completed)throw new Error("exec.completed was projected more than once.");this.completed=!0;let r=t.status==="succeeded"?this.event({type:"turn.completed",...t.model?{model:t.model}:{},...t.usage?{usage:t.usage}:{},durationMs:t.durationMs}):this.event({type:"turn.failed",status:t.status,...t.error?{error:t.error}:{},durationMs:t.durationMs});return[...this.ensureStarted(),r,this.event({type:"exec.completed",result:t})]}ensureStarted(){return this.started?[]:(this.started=!0,[this.event({type:"exec.started"}),this.event({type:this.options.resumed?"session.resumed":"session.started"}),this.event({type:"turn.started"})])}itemEvent(t){let r=this.startedItems.has(t.item.id);return t.completed?(this.startedItems.delete(t.item.id),this.event({type:"item.completed",item:t.item})):(this.startedItems.add(t.item.id),this.event({type:r?"item.updated":"item.started",item:t.item}))}event(t){return{schemaVersion:1,sequence:++this.sequence,timestampMs:this.nowMs(),runId:this.options.runId,sessionId:this.options.sessionId,turnId:this.options.turnId,...t}}};function qt(e){if(e.type==="delta"&&e.role==="assistant"){let t=e.messageId??`assistant-${e.turnId??"current"}`;return[...e.thinking?[{item:{id:`${t}:reasoning`,type:"reasoning",contentDelta:e.thinking},completed:!1}]:[],...e.content?[{item:{id:`${t}:message`,type:"agent_message",contentDelta:e.content},completed:!1}]:[],...(e.toolCalls??[]).map((r,n)=>({item:Ze(r,t,n),completed:!1}))]}return e.type!=="message"||e.message.role!=="assistant"?[]:Ht(e.message)}function Ht(e){let t=e.id??`assistant-${e.turnId??"current"}`;return[...e.thinking?[{item:{id:`${t}:reasoning`,type:"reasoning",content:e.thinking},completed:!0}]:[],...e.content?[{item:{id:`${t}:message`,type:"agent_message",content:e.content},completed:!0}]:[],...(e.toolCalls??[]).map((r,n)=>({item:Ze(r,t,n),completed:!0}))]}function Ze(e,t,r){return{id:e.id??`${t}:tool:${String(r)}`,type:"tool_call",toolCall:e}}var V=class extends m{constructor(t,r){super("internal",t,r),this.name="HeadlessOutputError"}};function et(e,t,r={}){let n=!1;if(e==="stream-json"&&!r.eventProjector)throw new V("stream-json requires an Exec event projector.");return{async event(i){if(e==="stream-json")for(let o of r.eventProjector?.project(i)??[])await ee(t,`${JSON.stringify(o)}
|
|
9
|
-
`)},async result(i){if(n)throw new V("ExecResult was encoded more than once.");if(!$e(i))throw new V("Headless coordinator returned an invalid ExecResult.");if(n=!0,e==="stream-json"){for(let o of r.eventProjector?.complete(i)??[])await ee(t,`${JSON.stringify(o)}
|
|
10
|
-
`);return}if(e==="json"){await ee(t,`${JSON.stringify(i)}
|
|
11
|
-
`);return}if(i.status==="succeeded"){let o=ke(i.output)?N(i.output):typeof i.output=="string"?Ie(i.output):JSON.stringify(i.output);await ee(t,`${o??""}
|
|
12
|
-
`)}}}}async function tt(e,t){let r=zt(Xt(e),`.${Jt(e)}.${process.pid}.${Vt()}.tmp`);try{await Gt(r,t,{encoding:"utf8",flag:"wx"}),await Wt(r,e)}catch(n){throw await Bt(r).catch(()=>{}),new m("internal",`Could not write --output-last-message: ${e}`,{cause:n})}}function fe(e){return t=>new Promise((r,n)=>{let i=!1,o=s=>{if(!i){if(i=!0,s.code==="EPIPE"){n(new m("brokenPipe","stdout pipe was closed.",{cause:s}));return}n(new m("internal",`stdout write failed: ${s.message}`,{cause:s}))}};e.once("error",o);try{e.write(t,s=>{if(s){o(s);return}i||(i=!0,e.off("error",o),r())})}catch(s){e.off("error",o),o(s)}})}async function ee(e,t){try{await e(t)}catch(r){if(r instanceof m)throw r;let n=r&&typeof r=="object"&&"code"in r?r.code:void 0;throw new m(n==="EPIPE"?"brokenPipe":"internal",n==="EPIPE"?"stdout pipe was closed.":"stdout writer failed.",{cause:r})}}var re=class{constructor(t,r={}){this.runtime=t;this.options=r}conversationPort(){return{sendMessage:(t,r)=>this.sendMessage(t,r),abortSession:t=>this.runtime.abortSession(t),steer:t=>this.runtime.steer(t)}}async*sendMessage(t,r){if(!t.turnId)throw te("EXEC_TURN_ID_REQUIRED","Exec requires a Turn id.");let n=t.turnId;r?.throwIfAborted();let i={seenMessageIds:new Set,seenCursors:new Set,sawEvent:!1,terminal:!1,heartbeatSeen:!1,doneSeen:!1},o=!0,s=0,d;for(;;){r?.throwIfAborted();let u=!1,h=!1;try{let y=o?this.runtime.sendMessage(t,r):this.runtime.watchSessionTurn(t.id,n,er(r),{...i.cursor?{afterCursor:i.cursor}:{},...!i.cursor&&i.afterMsgId?{afterMsgId:i.afterMsgId}:{}});o=!1;for await(let c of y){r?.throwIfAborted();let p=c.cursor?i.seenCursors.has(c.cursor):!1;c.cursor&&(i.cursor=c.cursor,p||(i.seenCursors.add(c.cursor),h=!0));let x=c.type==="message"&&c.message.id?i.seenMessageIds.has(c.message.id):!1,a=!c.cursor&&(c.type==="heartbeat"&&i.heartbeatSeen||c.type==="done"&&i.doneSeen);if(!(p||x||a)){if(c.type==="message"&&(h=!0),c.type==="heartbeat"&&(i.heartbeatSeen=!0),c.type==="done"&&(i.doneSeen=!0),!c.cursor&&c.type!=="message"&&(h=!i.sawEvent),i.sawEvent=!0,Yt(i,c),c.type==="resync-required"){u=!0,yield c;break}yield c,Zt(c)&&(i.terminal=!0)}}}catch(y){if(r?.aborted)throw r.reason??y;d=y}if(i.terminal)return;let l=yield*this.reconcile(t,n,i,u,r);if(l.terminal)return;if(!l.recoverable)throw d??te("EXEC_STREAM_ENDED_WITHOUT_TERMINAL","Runtime stream ended without a durable terminal fact.");if(s=h||l.progressed?0:s+1,s>(this.options.maxConsecutiveRecoveryAttempts??5))throw te("EXEC_STREAM_RECOVERY_EXHAUSTED","Runtime stream recovery was exhausted before a terminal fact arrived.",d);await(this.options.wait??tr)(this.options.reconnectDelayMs??100,r)}}async*reconcile(t,r,n,i,o){o?.throwIfAborted();let[s,d]=await Promise.all([this.runtime.getActiveRun(t.id),this.runtime.getSession(t.id)]),u=(s.state==="running"||s.state==="decision-blocked")&&(!s.turnId||s.turnId===r),h=i||!u||s.state==="idle",l=!1,y=!1;if(h){let c=await Kt(this.runtime,t.id,r);for(let p of c)p.id&&(n.afterMsgId=p.id),Qt(p)&&(l=!0),!(p.id&&n.seenMessageIds.has(p.id))&&(p.id&&n.seenMessageIds.add(p.id),n.sawEvent=!0,y=!0,yield{type:"message",message:p});i&&(n.cursor=void 0)}if(d.status==="error")return yield{type:"session-status",status:"error",turnId:r,message:d.errorMessage??"Runtime turn failed."},{progressed:y,recoverable:!1,terminal:!0};if(d.status==="aborted")return yield{type:"session-status",status:"aborted",turnId:r},{progressed:y,recoverable:!1,terminal:!0};if(d.status==="idle"&&l)return yield{type:"session-status",status:"finished",turnId:r},{progressed:y,recoverable:!1,terminal:!0};if(s.state==="decision-blocked")throw te("INTERACTION_NOT_AVAILABLE","Runtime is waiting for user interaction from a non-interactive Exec host.");return{progressed:y,recoverable:u||n.sawEvent,terminal:!1}}};async function Kt(e,t,r){let n=[],i=new Set,o;for(;;){let s=await e.listMessagePage(t,{limit:200,...o?{before:o}:{}});if(n.unshift(s.messages.filter(d=>d.turnId===r)),!s.hasMore||!s.nextCursor||i.has(s.nextCursor))break;i.add(s.nextCursor),o=s.nextCursor}return n.flat()}function Yt(e,t){t.type!=="message"||!t.message.id||(e.seenMessageIds.add(t.message.id),e.afterMsgId=t.message.id)}function Qt(e){return e.role==="assistant"&&(e.kind==="final"||e.finishReason==="stop"||e.finishReason==="end_turn"||e.finishReason==="stop_sequence")}function Zt(e){return e.type==="error"?!0:e.type==="session-status"&&(e.status==="finished"||e.status==="error"||e.status==="aborted"||e.status==="interrupted")}function er(e){return e??new AbortController().signal}async function tr(e,t){e<=0||await new Promise((r,n)=>{let o=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),n(t?.reason??new Error("Exec stream recovery was cancelled."))};if(t?.aborted){s();return}t?.addEventListener("abort",s,{once:!0})})}function te(e,t,r){return Object.assign(new Error(t,r===void 0?void 0:{cause:r}),{category:"runtime",code:e,retryable:!1})}import{performance as ne}from"node:perf_hooks";async function rt(e,t,r=5e3){let n=ne.now()+r;for(;ne.now()<n;){let i;try{let s=await Promise.race([e.getActiveRun(t),new Promise(d=>{i=setTimeout(()=>d(void 0),Math.max(0,n-ne.now()))})]);if(!s||s.sessionId!==t)return!1;if(s.state==="idle"||s.state==="terminal")return!0}catch{return!1}finally{i&&clearTimeout(i)}let o=n-ne.now();if(o<=0)return!1;await new Promise(s=>setTimeout(s,Math.min(50,o)))}return!1}import{performance as pe}from"node:perf_hooks";var ie=class{constructor(t){this.record=t}active=new Map;toolStates=new Map;modelSteps=0;toolCalls=0;lastActivityAt=Date.now();droppedOperations=0;observe(t){if(t.type==="delta"){(t.content||t.thinking||t.toolCalls?.length)&&(this.lastActivityAt=Date.now());for(let r of t.toolCalls??[])this.tool(r)}else if(t.type==="message")for(let r of t.message.toolCalls??[])this.tool(r);else if(t.type==="generic"&&t.eventType==="execution.diagnostic"){let{kind:r,operationId:n,modelId:i,protocol:o,finishReason:s}=t.data;if(typeof n!="string")return;if(r==="model_phase_started")this.modelSteps++,this.start(n,"model");else if(r==="model_phase_finished"||r==="model_phase_failed")this.end(n,{finishReason:typeof s=="string"?s:void 0});else return;this.record({kind:r,operationId:n,modelId:typeof i=="string"?i:void 0,protocol:typeof o=="string"?o:void 0})}}summary(){return{modelSteps:this.modelSteps,toolCalls:this.toolCalls,lastActivityAt:this.lastActivityAt,droppedOperations:this.droppedOperations,unfinishedOperations:[...this.active].map(([t,r])=>({operationId:t,kind:r.kind,startedAtMs:r.startedAtMs,elapsedMs:Math.max(0,pe.now()-r.startedAt)}))}}tool(t){if(!t.id)return;let r=String(t.status).toLowerCase(),n=["1","started","running","in_progress"].includes(r)?"started":["2","completed","succeeded","success"].includes(r)?"finished":["3","failed","error"].includes(r)?"failed":void 0;if(!(!n||this.toolStates.get(t.id)===n)){if(this.toolStates.size>=4096&&!this.toolStates.has(t.id)){this.droppedOperations++;return}this.toolStates.set(t.id,n),n==="started"?(this.toolCalls++,this.start(t.id,"tool"),this.record({kind:"tool_started",operationId:t.id,toolName:t.name})):this.end(t.id,{kind:`tool_${n}`,toolName:t.name})}}start(t,r){if(this.lastActivityAt=Date.now(),this.active.size>=256){this.droppedOperations++;return}this.active.set(t,{kind:r,startedAt:pe.now(),startedAtMs:this.lastActivityAt})}end(t,r){this.lastActivityAt=Date.now();let n=this.active.get(t);this.active.delete(t),this.record({kind:"operation_finished",operationId:t,...r,...n?{durationMs:Math.max(0,pe.now()-n.startedAt)}:{missingStart:!0}})}};async function at(e,t){let r=t.stdout??fe(process.stdout),n=t.stderr??fe(process.stderr),i=t.processRef??process,o=t.createTurnId??Qe,s=T.internal,d,u,h=[],l,y={},c={},p=!1,x,a=e.diagnosticsDir?new ie(g=>l?.record({...c,...g})):void 0,S=Date.now(),P=new re(t.runtime),R=new Me(P.conversationPort(),{...e.diagnosticsDir?{onAnswerSelection:g=>{y=g,l?.record(g)}}:{}}),M,A=()=>{R.abort()};i.once("SIGINT",A),i.once("SIGTERM",A),i.once("SIGHUP",A);try{e.diagnosticsDir&&(l=await z.create(e.diagnosticsDir,w=>h.push(w))),await Ae(t.runtime,e.sessionId);let g=await dr(e,t.runtime);await sr(t.runtime,g);let I=e.model?mr(e.model):void 0,E=o(),C=`exec_${E}`;c={version:e.version,sessionId:g.sessionId,turnId:E,runId:C,startedAt:S,schemaHash:We(e.outputSchema)},l?.execution(c),l?.record({kind:"execution_started",sessionId:g.sessionId,turnId:E});let ge=et(e.format??"text",r,{...e.format==="stream-json"?{eventProjector:new Z({runId:C,sessionId:g.sessionId,turnId:E,resumed:!!(e.sessionId||e.continueSession)})}:{}}),ct=await R.execute({turnId:E,session:Promise.resolve(g),content:e.prompt,workspace:e.workspaceDir,version:e.version,...l?{executionDiagnostics:!0}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...I?{model:I}:{},...e.reviewRequest?{reviewRequest:e.reviewRequest}:{},...e.outputSchema?{outputSchema:e.outputSchema}:{},...e.timeoutMs!==void 0||e.maxSteps!==void 0?{policy:{...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.maxSteps!==void 0?{maxSteps:e.maxSteps}:{},requireAnswer:!0}}:{policy:{requireAnswer:!0}}},async w=>{let B;w.type==="message"&&(B=be(w.message.origin),B&&(M={outcome:B,content:w.message.content??""})),a?.observe(w),w.type==="session-status"?l?.record({kind:"session_status",status:w.status}):w.type==="message"&&w.message.role==="assistant"&&l?.record({kind:"assistant_completed",messageId:w.message.id,finishReason:w.message.finishReason,requestDurationMs:w.message.usage?.requestDurationMs});try{await ge.event(nr(w,B))}catch(he){throw d??=he,R.abort(),he}});if(d)throw d;let v=ir(ct.outcome),D;if(e.reviewRequest&&v.status==="succeeded"){let w=rr(M);"error"in w?v={...v,status:"failed",answer:null,error:w.error}:D=w.result}x=v.answer;let j=v.status==="succeeded"?ue(v.answer,e.outputSchema):void 0,F=or(e.format)||l?await ar(t.runtime,g.sessionId,E,v):{},dt={runId:C,...j?{validation:j}:{},...e.outputSchema?{outputSchema:e.outputSchema}:{},...F.model?{model:{...F.model,...e.outputSchema&&v.status==="succeeded"?{structuredOutputMode:"native_strict"}:{}}}:{},...F.usage?{usage:F.usage}:{}},ye=Ne(v,dt),b=D?{...ye,output:D}:ye;l&&b.status==="timeout"&&(p=await rt(t.runtime,g.sessionId),l.record({kind:"stop_confirmed",stopped:p})),c={...c,model:F.model,status:b.status,durationMs:b.durationMs},b.status!=="succeeded"&&l?.failure(v.answer,{...a?.summary(),...y,error:b.error,status:b.status,...j&&!j.ok?{validationKind:j.kind}:{}}),u={encoder:ge,result:b,...b.status==="succeeded"&&e.outputLastMessagePath?{lastMessage:{filePath:e.outputLastMessagePath,answer:D?N(D):v.answer??""}}:{}}}catch(g){let I=st(g);l?.failure(void 0,{error:{message:I.message},phase:"execution"}),s=$(I),s!==T.brokenPipe&&h.push(`mcode exec failed: ${L(I)}
|
|
13
|
-
`)}finally{i.off("SIGINT",A),i.off("SIGTERM",A),i.off("SIGHUP",A);let g,I=!1;try{await t.shutdown()===!0&&(g="Runtime shutdown did not complete cleanly.")}catch(E){g=xe(E,{summary:"mcode exec shutdown failed.",nextStep:"Verify no process is still running."})}if(u){if(g&&u.result.status==="succeeded"&&(u.result=it(u.result,"RUNTIME_SHUTDOWN_FAILED",g),I=!0),u.result.status==="succeeded"&&u.lastMessage)try{await tt(u.lastMessage.filePath,u.lastMessage.answer)}catch(E){u.result=it(u.result,"OUTPUT_LAST_MESSAGE_WRITE_FAILED",E instanceof Error?E.message:String(E))}try{u.result.status!=="succeeded"&&u.result.error?.category==="internal"&&l?.failure(x,{...y,status:u.result.status,error:u.result.error}),await u.encoder.result(u.result),s=De(u.result),u.result.status!=="succeeded"&&h.push(`mcode exec ${u.result.status}: ${Fe(u.result)}
|
|
14
|
-
`)}catch(E){let C=st(E);s=$(C),s!==T.brokenPipe&&h.push(`mcode exec failed: ${L(C)}
|
|
15
|
-
`)}}else g&&s!==T.brokenPipe&&(s=T.internal);if(g&&!I&&h.push(`${g}
|
|
16
|
-
`),l?.execution({...c,endedAt:Date.now(),shutdownComplete:!g,exitCode:s}),l?.record({kind:"execution_finished",...c,exitCode:s,shutdownComplete:!g}),await l?.flush({version:e.version,runId:c.runId,sessionId:c.sessionId,turnId:c.turnId,...a?.summary(),exitCode:s,shutdownComplete:!g,recoveryReady:p&&!g}),s!==T.brokenPipe)for(let E of h)await fr(n,E)}return s}function rr(e){if(!e)return{error:{category:"runtime",code:"REVIEW_RESULT_MISSING",message:"Runtime completed without a validated code review result.",retryable:!0}};if(e.outcome==="failed")return{error:{category:"runtime",code:"REVIEW_RESULT_INVALID",message:e.content.trim()||"Runtime rejected an invalid code review result.",retryable:!0}};let t=e.outcome==="pass"?Pe(e.content):se(e.content);return t?{result:t}:{error:{category:"runtime",code:"REVIEW_RESULT_INVALID",message:"Runtime returned an invalid code review result.",retryable:!0}}}function nr(e,t){if(e.type!=="message"||t!=="needs_changes")return e;let r=se(e.message.content??"");return{...e,message:{...e.message,content:r?N(r):"Runtime returned an invalid code review result."}}}function it(e,t,r){return{...e,status:"failed",output:void 0,error:{category:"internal",code:t,message:r,retryable:!1}}}function ir(e){return e.status!=="awaiting-user-continuation"?e:{...e,status:"failed",error:{category:"runtime",code:"INTERACTION_NOT_AVAILABLE",message:"The Runtime requested user interaction from a non-interactive Exec host.",retryable:!1}}}async function sr(e,t){let r=t.agentName??oe,[n,i]=await Promise.all([e.getPendingQuestionnaire(r,t.sessionId),e.listPendingPermissions()]),o=i.some(d=>d.sessionId===t.sessionId);if(!n&&!o)return;let s=n?"a pending questionnaire":"a pending permission request";throw new m("runtime",`Session ${t.sessionId} has ${s} and requires an interactive host. Continue it in the TUI or ACP.`)}function or(e){return e==="json"||e==="stream-json"}async function ar(e,t,r,n){let[i,o]=await Promise.all([e.getSessionUsage(t).catch(()=>{}),e.listModels(t).catch(()=>[])]),s=i?.rows?.filter(p=>p.turnId===r)??[],d=[...s].reverse().find(p=>p.model?.trim())?.model?.trim(),u=n.model?`${n.model.providerId}/${n.model.modelId}`:void 0,h=o.find(p=>p.selected===!0),l=h?`${h.providerId}/${h.modelId}`:void 0,y=ur(d??u??l,o,n.model?.variant),c=s.length>0?cr(s):n.usage;return{...y?{model:y}:{},...c?{usage:c}:{}}}function ur(e,t,r){let n=e?.indexOf("/")??-1;if(!e||n<=0||n===e.length-1)return;let i=e.slice(0,n),o=e.slice(n+1),s=t.find(d=>d.providerId===i&&d.modelId===o);return{providerId:i,modelId:o,...s?.variant!==void 0?{variant:s.variant}:r!==void 0?{variant:r}:{},...s?.providerSource?{providerSource:s.providerSource}:{},...s?.providerKind?{providerKind:s.providerKind}:{},...s?.apiFormat?{protocol:s.apiFormat}:{}}}function cr(e){let t={...W(e,"inputTokens"),...W(e,"outputTokens"),...W(e,"reasoningTokens"),...W(e,"cacheReadTokens"),...W(e,"cacheWriteTokens")},r=t.inputTokens,n=t.outputTokens;return Object.keys(t).length===0?void 0:{...t,...r!==void 0||n!==void 0?{totalTokens:(r??0)+(n??0)}:{}}}function W(e,t){let r=e.map(n=>n[t]).filter(n=>typeof n=="number"&&Number.isFinite(n));return r.length>0?{[t]:r.reduce((n,i)=>n+i,0)}:{}}function st(e){if(e instanceof m)return e;if(e instanceof G){let r=e.category==="config"||e.category==="invocation"||e.category==="cancelled"||e.category==="brokenPipe"||e.category==="internal"?e.category:"runtime";return new m(r,e.message,{cause:e})}let t=e instanceof Error?e.message:String(e);return new m("runtime",t,{cause:e})}async function dr(e,t){if(e.sessionId){let r=await t.getSession(e.sessionId);return ot(r,e.workspaceDir),r}if(e.continueSession){let r=await lr(t,e.workspaceDir);if(!r)throw new m("runtime",`No active Session exists for workspace ${e.workspaceDir}.`);return ot(r,e.workspaceDir),r}return t.createSession({workspaceDir:e.workspaceDir,title:pr(e.prompt,e.attachments?.length??0)})}async function lr(e,t){let r;do{let n=await e.listSessionPage({agentName:oe,cursor:r,limit:50,includeArchived:!1}),i=n.sessions.find(o=>o.archived!==!0&&o.workspaceDir!==void 0&&ut(o.workspaceDir,t));if(i)return i;r=n.hasMore?n.nextCursor:void 0}while(r)}function ot(e,t){if(Re(e))throw new m("invocation","Sub-agent Sessions are internal and cannot be opened.");if(e.archived)throw new m("runtime",`Session is archived: ${e.sessionId}`);if(!e.workspaceDir||!ut(e.workspaceDir,t))throw new m("runtime",`Session workspace does not match --cwd: ${e.sessionId}`)}function ut(e,t){let r=nt(e),n=nt(t);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function mr(e){let t=e.indexOf("/");if(t<1||t===e.length-1)throw new m("invocation","--model must use provider/model or provider/model#variant.");let r=e.slice(0,t),n=e.slice(t+1),i=n.lastIndexOf("#"),o=i>0?n.slice(0,i):n,s=i>0?n.slice(i+1):void 0;if(!r||!o||i>0&&!s)throw new m("invocation","--model must use provider/model or provider/model#variant.");return{providerId:r,modelId:o,...s?{variant:s}:{}}}async function fr(e,t){try{await e(t)}catch{}}function pr(e,t){let r=e.replace(/\s+/g," ").trim();return r?r.length<=80?r:`${r.slice(0,77)}...`:t===1?"Attachment run":`${t} attachments`}async function On(e,t,r,n={}){let i=n.processRef??process,o=n.writeError??(a=>process.stderr.write(a)),s=n.resolveInvocation??Xe,d=n.resolveDataDir??Te,u=n.loadConfig??je,h=n.createRuntime??Oe,l=n.shutdownRuntime??_e,y=n.runExec??at,c=n.readStdin??yr,p=new AbortController,x=()=>p.abort();i.once("SIGINT",x),i.once("SIGTERM",x),i.once("SIGHUP",x);try{let a=await s(e,t,()=>c(p.signal),p.signal),S=await d(),P=a.configPath?await u(a.configPath,{dataDir:S}):void 0,R=await h({dataDir:S,workspaceDir:a.workspaceDir,version:r,...a.configPath?{configPath:a.configPath}:{},surface:"headless",permissionMode:gr(a.permission),...t.lane?{lane:t.lane}:{}},P?{getConfig:()=>P,configSource:"explicit"}:{});i.exitCode=await y({prompt:a.prompt,workspaceDir:a.workspaceDir,version:r,attachments:a.attachments,format:a.format,...a.model?{model:a.model}:{},...a.sessionId?{sessionId:a.sessionId}:{},continueSession:a.continueSession,permission:a.permission,...a.diagnosticsDir?{diagnosticsDir:a.diagnosticsDir}:{},...a.timeoutMs!==void 0?{timeoutMs:a.timeoutMs}:{},...a.maxSteps!==void 0?{maxSteps:a.maxSteps}:{},...a.outputSchema===void 0?{}:{outputSchema:a.outputSchema},...a.outputLastMessagePath===void 0?{}:{outputLastMessagePath:a.outputLastMessagePath},...a.reviewRequest?{reviewRequest:a.reviewRequest}:{}},{runtime:R.adapter,shutdown:()=>l(R)})}catch(a){let S=a instanceof m?a:new m("runtime",a instanceof Error?a.message:String(a),{cause:a});o(`mcode exec failed: ${L(S)}
|
|
17
|
-
`),i.exitCode=$(S)}finally{i.off("SIGINT",x),i.off("SIGTERM",x),i.off("SIGHUP",x)}}function gr(e){switch(e){case"smart":return"auto";case"full":return"bypassPermissions";case"off":return"off"}}async function yr(e,t=process.stdin){let r=[],n=t[Symbol.asyncIterator]();try{for(;;){let i=await hr(n,e);if(i.done)break;r.push(Buffer.isBuffer(i.value)?i.value:Buffer.from(i.value))}}finally{await n.return?.()}return Buffer.concat(r).toString("utf8")}function hr(e,t){return new Promise((r,n)=>{let i=()=>{n(new m("cancelled","stdin input was cancelled."))};if(t.aborted){i();return}t.addEventListener("abort",i,{once:!0}),e.next().then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})})}export{yr as readTuiStdinToEnd,On as runTuiExecCommand};
|