@yukino.js/yukino 0.0.17 → 0.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -29
- package/dist/{anthropic-3WALTWVK.js → anthropic-D72CIYEQ.js} +1 -1
- package/dist/browser/dist/static/{highlight-3YCG6EL4.js → highlight-ZDY7K2CR.js} +12 -12
- package/dist/browser/dist/static/index.js +77 -70
- package/dist/browser/dist/static/{webapi-2B2CRWRA.js → webapi-HZESKPJE.js} +1 -1
- package/dist/chunk-456FRBGE.js +4 -0
- package/dist/{chunk-XWPHUABN.js → chunk-676RWZYX.js} +1 -1
- package/dist/{chunk-QZ5RINXE.js → chunk-6SWKDCK3.js} +1 -1
- package/dist/chunk-7WYSSZKU.js +18 -0
- package/dist/{chunk-E5GNPWNI.js → chunk-A4IB5PNW.js} +1 -1
- package/dist/{chunk-6RBGIE4I.js → chunk-BCYFGWSM.js} +16 -16
- package/dist/chunk-DGDF5PBF.js +869 -0
- package/dist/chunk-FNQMXCCE.js +4 -0
- package/dist/chunk-HKQWGX5S.js +4 -0
- package/dist/{chunk-HRAX6543.js → chunk-N7G2FDAI.js} +1 -1
- package/dist/chunk-NPIMUWFO.js +4 -0
- package/dist/{chunk-OARVZDYW.js → chunk-PYFRT6N5.js} +1 -1
- package/dist/{chunk-6ZJ6N7IH.js → chunk-QDMUFOED.js} +1 -1
- package/dist/chunk-QYUIIFJY.js +4 -0
- package/dist/{chunk-IGVEI6KM.js → chunk-S56AXDDN.js} +1 -1
- package/dist/chunk-U6NE2CTP.js +4 -0
- package/dist/{chunk-3NCODM6S.js → chunk-UX5DJPHN.js} +29 -29
- package/dist/{chunk-K6F424MN.js → chunk-WKKH2UE5.js} +1 -1
- package/dist/{chunk-7S5SR6KL.js → chunk-XDERLDVW.js} +8 -8
- package/dist/{esm-RASD3BGK.js → esm-46K5BSA6.js} +1 -1
- package/dist/{esm-6WYDAALC.js → esm-63A57VQM.js} +1 -1
- package/dist/esm-6D27H27M.js +225 -0
- package/dist/{esm-7VCKZ3CE.js → esm-73AG4F4H.js} +1 -1
- package/dist/{esm-AFNMXGOY.js → esm-FURF4AWD.js} +1 -1
- package/dist/esm-HB7M3TZY.js +4 -0
- package/dist/{esm-MYMSBMIY.js → esm-QAEO3U72.js} +1 -1
- package/dist/file-type-PSFVPAEH.js +12 -0
- package/dist/{getMachineId-bsd-SR65JA23.js → getMachineId-bsd-2MDOCJCH.js} +1 -1
- package/dist/{getMachineId-bsd-MTZJBHHS.js → getMachineId-bsd-JZNSGCLM.js} +1 -1
- package/dist/getMachineId-bsd-L5XEQF74.js +4 -0
- package/dist/{getMachineId-darwin-J7BNWNFS.js → getMachineId-darwin-32V6AVQO.js} +1 -1
- package/dist/{getMachineId-darwin-UX2LWEFP.js → getMachineId-darwin-SMQEPEZ2.js} +1 -1
- package/dist/getMachineId-darwin-V3OSZDJX.js +5 -0
- package/dist/getMachineId-linux-C4WJW6ZL.js +4 -0
- package/dist/{getMachineId-linux-XGLIABQN.js → getMachineId-linux-OWR5YFVH.js} +1 -1
- package/dist/{getMachineId-linux-RNGA35ZF.js → getMachineId-linux-T543G3ZF.js} +1 -1
- package/dist/{getMachineId-unsupported-JDNTBZDQ.js → getMachineId-unsupported-J7U5FNFT.js} +1 -1
- package/dist/getMachineId-unsupported-M7AEHRA4.js +4 -0
- package/dist/{getMachineId-unsupported-4ACRY4OO.js → getMachineId-unsupported-ZH5H5BSP.js} +1 -1
- package/dist/getMachineId-win-2ZKMVYDE.js +4 -0
- package/dist/getMachineId-win-JHSGKXX7.js +4 -0
- package/dist/getMachineId-win-JOM5JSRW.js +4 -0
- package/dist/image-worker.js +1 -1
- package/dist/lib/{anthropic-7WH7P3RI.js → anthropic-I7ZSAP7Z.js} +3 -3
- package/dist/lib/{chunk-2TTVGX57.js → chunk-MJHQUFUL.js} +2 -2
- package/dist/lib/{chunk-PGTK52O6.js → chunk-T4WEXOQ7.js} +21 -1
- package/dist/lib/{chunk-6NWFDYBU.js → chunk-TO34ITLQ.js} +2 -2
- package/dist/lib/{chunk-XBRU3RBT.js → chunk-UU6ZV6GB.js} +1 -1
- package/dist/lib/{chunk-WZQR25VY.js → chunk-YZURLYHG.js} +2 -2
- package/dist/lib/index.d.ts +2223 -1463
- package/dist/lib/index.js +3133 -962
- package/dist/lib/{openai-WF5FTR27.js → openai-Y4P7SWUB.js} +3 -3
- package/dist/lib/{providers-EPEZ5LNH.js → providers-MRGAAMBB.js} +2 -2
- package/dist/{main-JAXZTXEK.js → main-MHJXHOY6.js} +246 -238
- package/dist/main.js +2 -2
- package/dist/{openai-VOM3AZYR.js → openai-3IGA2BCD.js} +1 -1
- package/dist/providers-GRYPIKCY.js +4 -0
- package/dist/server-XBVP3S5Q.js +4 -0
- package/dist/{server-WA7I53NC.js → server-ZYP54JBK.js} +1 -1
- package/dist/{src-EZJEUBJC.js → src-CHQYSTW5.js} +1 -1
- package/dist/{src-32KR7AJY.js → src-HH6MC5CF.js} +1 -1
- package/dist/src-P2WNZ6IY.js +12 -0
- package/dist/{src-7S4T5QVZ.js → src-YWYPK5QA.js} +1 -1
- package/dist/stdio-UHDEALLA.js +5 -0
- package/dist/{websocket-4BV3XTZ3.js → websocket-J5DE5FRQ.js} +1 -1
- package/package.json +2 -1
- package/dist/chunk-5ZELCP2G.js +0 -4
- package/dist/chunk-IQT2IFSO.js +0 -4
- package/dist/chunk-IRS7KPMN.js +0 -820
- package/dist/chunk-UDW5FQQ2.js +0 -18
- package/dist/chunk-W2VWX7HR.js +0 -4
- package/dist/chunk-XQCCZYMT.js +0 -4
- package/dist/esm-BOD3YQPE.js +0 -225
- package/dist/esm-UKQMXG2A.js +0 -4
- package/dist/file-type-P5MHDLHF.js +0 -12
- package/dist/getMachineId-win-BLVGSBMB.js +0 -4
- package/dist/getMachineId-win-PANZD46Y.js +0 -4
- package/dist/providers-OW3JL52M.js +0 -4
- package/dist/server-Z3ZXR2HE.js +0 -4
- package/dist/src-VLEWSGZD.js +0 -12
- package/dist/stdio-FINC2RYM.js +0 -5
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ Beyond interactive use, Yukino supports a non-interactive print mode for scripti
|
|
|
14
14
|
|
|
15
15
|
- Multi-provider LLM support with Anthropic (Anthropic Messages), OpenAI (OpenAI Responses), and OpenAI-compatible (OpenAI Chat Completions) protocols
|
|
16
16
|
- Interactive terminal UI with streaming text, thinking indicators, and tool execution display
|
|
17
|
-
- Built-in tool set: ReadFile, WriteFile, EditFile, Bash, PowerShell, Glob, Grep, WebFetch, LSP, ComputerUse, ToolSearch, McpCall, EnterWorktree, ExitWorktree, ExitPlanMode, Goal, the TodoWrite tracking tool, plus Agent, LoadSkill, InstallSkill, AskUserQuestion, SyntheticOutput, TeamCreate, SendMessage, TeamDelete, TaskOutput, and TaskStop
|
|
17
|
+
- Built-in tool set: ReadFile, WriteFile, EditFile, Bash, PowerShell, Glob, Grep, WebFetch, LSP, ComputerUse, ToolSearch, McpCall, EnterWorktree, ExitWorktree, ExitPlanMode, Goal, the TodoWrite tracking tool, plus Workflow, Agent, LoadSkill, InstallSkill, AskUserQuestion, SyntheticOutput, TeamCreate, SendMessage, TeamDelete, TaskOutput, and TaskStop
|
|
18
18
|
- MCP (Model Context Protocol) server integration for extending the tool set with external services
|
|
19
19
|
- Permission system with four modes: default, acceptEdits, plan (read-only), and bypassPermissions
|
|
20
20
|
- Sandbox support for isolated command execution (bwrap on Linux, seatbelt on macOS)
|
|
@@ -599,9 +599,37 @@ Task tracking and task execution are separate:
|
|
|
599
599
|
|
|
600
600
|
The common built-in registry is used by terminal, print, Remote/ACP/A2A, and in-process teammates. Delegation, coordinator, and per-agent tool restrictions still filter that registry.
|
|
601
601
|
|
|
602
|
+
### Workflows
|
|
603
|
+
|
|
604
|
+
`Workflow` runs a plain JavaScript script that orchestrates Yukino subagents in the background. Start with `/ultracode <task>`, invoke a named script with `/<name>`, or call the tool with one of `script`, `name`, or `scriptPath` plus JSON `args`. Named scripts live in `.yukino/workflows/<name>.js`, `.mjs`, or `.ts` in the project. TypeScript syntax is not transpiled.
|
|
605
|
+
|
|
606
|
+
```js
|
|
607
|
+
export const meta = {
|
|
608
|
+
name: "review-files",
|
|
609
|
+
description: "Review files independently, then collect the findings",
|
|
610
|
+
phases: [{ title: "Review" }],
|
|
611
|
+
};
|
|
612
|
+
phase("Review");
|
|
613
|
+
const results = await parallel(
|
|
614
|
+
args.files.map(
|
|
615
|
+
(file) => () =>
|
|
616
|
+
agent("Review " + file, { agentType: "review", label: file }),
|
|
617
|
+
),
|
|
618
|
+
);
|
|
619
|
+
return results.filter(Boolean);
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
Scripts receive `agent(prompt, options)`, `parallel(thunks)`, `pipeline(items, ...stages)`, `phase(title)`, `log(message)`, `workflow(name | {scriptPath}, args)`, `args`, and `budget`. A pipeline runs stages sequentially within each item while items overlap. A nested workflow may invoke agents but cannot nest another workflow. Use top-level `return` for results; imports and extra exports are rejected. Time and randomness must be supplied through args for replay. Scripts run in the host process.
|
|
623
|
+
|
|
624
|
+
Agent options include JSON `schema`, `agentType`, `model`, `maxTokens`, `allowedTools`, `label`, `phase`, and `isolation: "worktree"`. Agent roles, tool restrictions, and permissions still apply. Failed agents retry once and return `null` if both attempts fail; scripts must handle null results. A script can complete with partial results. Concurrent agents default to 3, with `maxConcurrency` configurable up to 16; the per-run agent-call limit is 1000. Worktree changes remain separate and are not merged automatically.
|
|
625
|
+
|
|
626
|
+
The tool returns `run_id`, `task_id`, and a saved script path. Results arrive through the normal task-notification channel; `TaskOutput` and `TaskStop` use `task_id`. Print mode waits for workflow tasks before exiting. `/workflows` opens the terminal monitor with phase and agent progress: Tab switches runs, ↑↓ selects agents, x stops one agent, K stops a run, r resumes a finished run, and Esc closes the panel. In every host, `/workflows list`, `/workflows <run_id>`, `/workflows stop <run_id>`, and `/workflows resume <run_id>` provide text controls.
|
|
627
|
+
|
|
628
|
+
Source snapshots, JSON arguments, journals, and run state live under `~/.yukino/projects/<project-key>/workflow-runs/<run_id>/`. Resume with `Workflow({resumeFromRunId: "..."})` to reuse the saved source and arguments. Supply a new source or args to override them. Matching successful agent calls replay from the journal; a divergence preserves the matching prefix and executes the rest again. Ordinary JavaScript runs again during replay. Keep side effects inside agents and keep script control flow deterministic.
|
|
629
|
+
|
|
602
630
|
### Worker lifecycle
|
|
603
631
|
|
|
604
|
-
Agent defaults to `kind: "teammate"`, joins the
|
|
632
|
+
Agent defaults to `kind: "teammate"`, joins the selected team or creates one automatically when none exists, and generates the teammate name from its description. Multiple teams can coexist; pass `team_name` when multiple teams exist. Use `kind: "subagent"` for one-shot runs and `worktree: true` for Git worktree isolation; agent definitions also accept a boolean `worktree` default, which a call can override. The optional `model` field is unnecessary for most tasks. `TeamCreate` adds a team, named via its optional `name` parameter or auto-generated when omitted, and keeps existing teams running. `TeamList` lists all teams. Use `team_name` with Agent, SendMessage, TodoWrite, TaskStop, and TeamDelete to select the target team; when only one team matches, it can be omitted. Teammates always send messages and edit tasks within their own team. The progress display combines tasks from all teams.
|
|
605
633
|
|
|
606
634
|
`Agent` selects its role and context independently: `subagent_type` defaults to `"general-purpose"`, while `fork` defaults to `true` (or the configured `enable_fork` value). An explicit `fork` value overrides the configuration for every role.
|
|
607
635
|
|
|
@@ -665,7 +693,7 @@ Mandatory policy constraints take precedence over rank composition:
|
|
|
665
693
|
|
|
666
694
|
Permission composition selects a mode; tool availability, explicit permission rules, and applicable sandbox policies still govern individual operations. An effective `plan` mode blocks mutations, even through allow rules or sandbox auto-allow, except the declared plan file and internal coordination tools. `max_turns` must be a positive integer. Built-in explore uses the selected parent model unless explicitly overridden.
|
|
667
695
|
|
|
668
|
-
Teammates run only in-process and route permission requests through the main session. Requests identify the agent and working directory; remembered permission patterns apply to all agents in the project. Plan-mode definitions can use `ExitPlanMode` unless explicitly excluded by their tool restrictions; `EnterPlanMode` remains unavailable to delegated agents. One-shot planning subagents return their plans to the parent without changing its mode. In coordinator mode, teammates with `subagent_type: "plan"` stay read-only until the leader reviews the plan and sends `SendMessage(type="plan_approval_response", to=teammate, request_id=requestId, approve=true/false, content=review feedback)`. The built-in `plan` role plans and then executes as a teammate; one-shot `plan` subagents and all built-in `explore` workers remain permanently read-only and return research without entering execution approval. Rejected plans must be revised and resubmitted. Outside coordinator mode, submitted execution plans remain automatically approved. Approval writes the leader's current mode into the teammate's own mode (`default` when the leader remains in `plan`) and resumes execution under rank composition; it does not authorize subsequent tool calls. This stored mode remains available to later permission checks: a teammate approved under `bypassPermissions` retains that own mode when the leader later switches to `default`, `acceptEdits`, or `plan`. Before resuming execution or plan revision, the host includes queued ordinary team messages with the review feedback so scope corrections are applied in that next turn. Stopped teammates release their task ownership; restored sessions mark old runtimes inactive and reclaim unfinished work. Edited worktrees are retained for explicit integration, not deleted as part of runtime cleanup. Agent teammate calls reuse the
|
|
696
|
+
Teammates run only in-process and route permission requests through the main session. Requests identify the agent and working directory; remembered permission patterns apply to all agents in the project. Plan-mode definitions can use `ExitPlanMode` unless explicitly excluded by their tool restrictions; `EnterPlanMode` remains unavailable to delegated agents. One-shot planning subagents return their plans to the parent without changing its mode. In coordinator mode, teammates with `subagent_type: "plan"` stay read-only until the leader reviews the plan and sends `SendMessage(type="plan_approval_response", to=teammate, request_id=requestId, approve=true/false, content=review feedback)`. The built-in `plan` role plans and then executes as a teammate; one-shot `plan` subagents and all built-in `explore` workers remain permanently read-only and return research without entering execution approval. Rejected plans must be revised and resubmitted. Outside coordinator mode, submitted execution plans remain automatically approved. Approval writes the leader's current mode into the teammate's own mode (`default` when the leader remains in `plan`) and resumes execution under rank composition; it does not authorize subsequent tool calls. This stored mode remains available to later permission checks: a teammate approved under `bypassPermissions` retains that own mode when the leader later switches to `default`, `acceptEdits`, or `plan`. Before resuming execution or plan revision, the host includes queued ordinary team messages with the review feedback so scope corrections are applied in that next turn. Stopped teammates release their task ownership; restored sessions mark old runtimes inactive and reclaim unfinished work. Edited worktrees are retained for explicit integration, not deleted as part of runtime cleanup. Agent teammate calls reuse the selected team; an explicit TeamCreate adds another team without stopping or deleting existing teams. TeamDelete stops and removes only the selected team.
|
|
669
697
|
|
|
670
698
|
Bash and PowerShell commands recognized by `isSafeCommand` can run in parallel. Unrecognized commands and file mutations share a process-wide FIFO queue keyed by canonical working directory, so agents in the same workspace cannot perform these operations simultaneously. Independent worktree directories have independent queues. Queued operations can be cancelled and recheck permissions before starting. Background commands hold their workspace slot until the tracked shell exits; moving a command to the background does not release it.
|
|
671
699
|
|
|
@@ -759,32 +787,53 @@ Serves Yukino as an Agent2Agent (`@a2a-js/sdk`) agent so other A2A-compatible ag
|
|
|
759
787
|
|
|
760
788
|
Inside the UI, these commands are available:
|
|
761
789
|
|
|
762
|
-
| Command
|
|
763
|
-
|
|
|
764
|
-
| /login
|
|
765
|
-
| /provider
|
|
766
|
-
| /model [model]
|
|
767
|
-
| /help [command]
|
|
768
|
-
| /status
|
|
769
|
-
| /session
|
|
770
|
-
| /memory
|
|
771
|
-
| /memory clear
|
|
772
|
-
| /skills
|
|
773
|
-
| /skills reload
|
|
774
|
-
| /skill <name> [args]
|
|
775
|
-
| /plan [task]
|
|
776
|
-
| /goal [args]
|
|
777
|
-
| /compact
|
|
778
|
-
| /clear
|
|
779
|
-
| /resume [id]
|
|
780
|
-
| /rewind
|
|
781
|
-
| /sandbox [mode]
|
|
782
|
-
|
|
|
783
|
-
|
|
|
784
|
-
|
|
|
785
|
-
|
|
|
786
|
-
|
|
|
787
|
-
|
|
|
790
|
+
| Command | Description |
|
|
791
|
+
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
792
|
+
| /login | Configure, save, and activate an LLM provider |
|
|
793
|
+
| /provider | Switch the active provider |
|
|
794
|
+
| /model [model] | Switch the model of the current provider; without an argument, open the model picker |
|
|
795
|
+
| /help [command] | Show available commands, or details for a single command |
|
|
796
|
+
| /status | Show current session status (mode, model, provider, tokens, tools, sandbox, memories, skills, MCP, session, directory) |
|
|
797
|
+
| /session | Confirm the session is active; use /resume to list past sessions |
|
|
798
|
+
| /memory | List stored memories |
|
|
799
|
+
| /memory clear | Clear all memories |
|
|
800
|
+
| /skills | List available skills |
|
|
801
|
+
| /skills reload | Hot-reload skills from disk |
|
|
802
|
+
| /skill <name> [args] | Run a skill by name (shorthand for `/<name> [args]`; `/skill reload` routes to `/skills reload`) |
|
|
803
|
+
| /plan [task] | Run the built-in read-only plan agent synchronously with the main conversation context |
|
|
804
|
+
| /goal [args] | Set or view a persistent goal; pause, resume, replace, complete, clear, or continue after the turn limit |
|
|
805
|
+
| /compact | Force conversation compaction |
|
|
806
|
+
| /clear | Reset the session and clear the terminal |
|
|
807
|
+
| /resume [id] | List or restore a previous session |
|
|
808
|
+
| /rewind | Open checkpoint rewind dialog |
|
|
809
|
+
| /sandbox [mode] | Configure sandbox (auto=on+auto, manual=on+manual, off) |
|
|
810
|
+
| `/ultracode <task>` | Ask the main agent to create and execute a multi-agent workflow for the task |
|
|
811
|
+
| `/workflows` | Open the terminal workflow monitor; in other hosts, list workflow runs |
|
|
812
|
+
| `/workflows list` | List workflow run IDs, names, statuses, agent counts, and task IDs |
|
|
813
|
+
| `/workflows <run_id>` | Show a workflow run's status, result, or error |
|
|
814
|
+
| `/workflows stop <run_id>` | Stop a running workflow and cancel its agents |
|
|
815
|
+
| `/workflows resume <run_id>` | Resume a saved workflow using its script, JSON arguments, and journal |
|
|
816
|
+
| /worktree | List git worktrees |
|
|
817
|
+
| /mcp | Show MCP server status |
|
|
818
|
+
| /mcp reload | Re-read MCP config; disconnect every server and reconnect the freshly read list |
|
|
819
|
+
| /thinking [level] | Without an argument, open a picker of the supported thinking levels; with one, set the level (off, minimal, low, medium, high, xhigh, max). The setting persists to `~/.yukino/config.yaml` |
|
|
820
|
+
| /review [PR or URL] | Review a pull request in a foreground subagent; without arguments, list open PRs |
|
|
821
|
+
| /quit | Exit the application |
|
|
822
|
+
|
|
823
|
+
`/ultracode` gives the main agent workflow orchestration instructions. The agent scopes the task, writes a JavaScript workflow, and invokes the `Workflow` tool. Agents run in the background with a default concurrency of 3; their final result returns through a task notification.
|
|
824
|
+
|
|
825
|
+
```text
|
|
826
|
+
/ultracode Review the current changes for correctness, security, and test coverage; verify the findings and summarize.
|
|
827
|
+
/workflows
|
|
828
|
+
/workflows list
|
|
829
|
+
/workflows <run_id>
|
|
830
|
+
/workflows stop <run_id>
|
|
831
|
+
/workflows resume <run_id>
|
|
832
|
+
```
|
|
833
|
+
|
|
834
|
+
Replace `<run_id>` with the `run_id` returned by `Workflow` or listed by `/workflows list`. These commands use workflow run IDs; `TaskOutput` and `TaskStop` use the separate `task_id`. Resuming replays matching successful agent calls and reruns unfinished or divergent work.
|
|
835
|
+
|
|
836
|
+
In the terminal monitor, Tab/Shift+Tab switches runs, ↑/↓ selects agents, x stops the selected agent, K stops the whole workflow, r resumes a finished run, and Esc/q closes the monitor. Stopping work requires confirmation in the monitor. See [Workflows](#workflows) for script primitives, named workflows, and persistence details.
|
|
788
837
|
|
|
789
838
|
### User Bash Commands
|
|
790
839
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __yukinoCreateRequire } from "node:module";
|
|
3
3
|
const require = __yukinoCreateRequire(import.meta.url);
|
|
4
|
-
import{g}from"./chunk-UDDADKJP.js";import{a as ne}from"./chunk-P6DHMU7R.js";import{Oa as oe,a as Y,g as te}from"./chunk-
|
|
4
|
+
import{g}from"./chunk-UDDADKJP.js";import{a as ne}from"./chunk-P6DHMU7R.js";import{Oa as oe,a as Y,g as te}from"./chunk-QDMUFOED.js";import{Z as V,g as $,h as j,ja as W,ka as M,l as K,la as R,m as E,ma as J,na as u,o as G,oa as Q,p as H,pa as X,q as I,qa as Z,s as S,za as ee}from"./chunk-676RWZYX.js";import{Kc as q,Nc as p,Oc as z,Rc as D,Sa as F}from"./chunk-BCYFGWSM.js";import"./chunk-WLJL66O5.js";import"./chunk-WGRGSG2J.js";import"./chunk-7MKA3SHV.js";function re(n){for(let t=n.length-1;t>=0;t--){let e=n[t];if(e.defer_loading!==!0){e.cache_control={type:"ephemeral"};return}}}function ae(n){return n.some(t=>"defer_loading"in t&&t.defer_loading===!0)}function le(n,t){if("input_schema"in n){let e=n,{cache_control:s,...i}=e;return t||delete i.type,{...i,...t?{type:"custom"}:{},...e.defer_loading!==!0&&s?{cache_control:s}:{}}}throw new Error("Anthropic received a tool schema serialized for another protocol.")}var ce=F({module:"llm"});function k(n){return typeof n=="string"?[{type:"text",text:n}]:n.map(t=>{let e=Y(t);if(!e||e.type==="tool_reference")throw new Error(`Unsupported user content block: ${D(t,"type","unknown")}`);return e})}function pe(n){let t=[];for(let e of n)if(e.role==="assistant"){let s=[];if(e.thinkingBlocks)for(let r of e.thinkingBlocks)r.type==="redacted_thinking"?s.push({type:"redacted_thinking",data:r.data}):s.push({type:"thinking",thinking:r.thinking,signature:r.signature});let i=typeof e.content=="string"?e.content:q(e.content);if(i&&s.push({type:"text",text:i}),e.toolUses)for(let r of e.toolUses)s.push({type:"tool_use",id:r.toolUseId,name:r.toolName==="ComputerUse"?"computer":r.toolName,input:r.arguments});s.length===0&&s.push({type:"text",text:""}),t.push({role:"assistant",content:s})}else if(e.toolResults&&e.toolResults.length>0){let s=[];for(let i of e.toolResults)s.push({type:"tool_result",tool_use_id:i.toolUseId,is_error:i.isError,content:i.contentBlocks?.length?i.contentBlocks:i.content});e.content.length>0&&s.push(...k(e.content)),t.push({role:"user",content:s})}else{if(t.length===0){t.push({role:"user",content:k(e.content)});continue}let s=t[t.length-1],i=s.content;s.role==="user"?(typeof i=="string"&&(i=s.content=i.trim().length>0?[{type:"text",text:i}]:[]),i.push(...k(e.content))):t.push({role:"user",content:k(e.content)})}return t}var se=class{protocol="anthropic";client;model;thinkingLevel;systemPrompt;config;useExplicitCustomToolType;constructor(t,e){let s=V(t);if(!s)throw new R(ee);this.client=new g({apiKey:s,baseURL:t.base_url}),this.useExplicitCustomToolType=oe(t.base_url),this.model=t.model,this.config={...t},this.thinkingLevel=K(t),this.systemPrompt=e}setSystemPrompt(t){this.systemPrompt=t}setMaxOutputTokens(t){this.config={...this.config,max_output_tokens:t},this.setThinkingLevel(this.thinkingLevel)}setThinkingLevel(t){return this.thinkingLevel=I(this.config,t),this.thinkingLevel}getThinkingLevel(){return this.thinkingLevel}getSupportedThinkingLevels(){return H(this.config)}getOutputBudget(){return{maxOutputTokens:S(this.config),thinkingTokens:E(this.config,this.thinkingLevel)}}async*stream(t,e,s,i){let r=i?.maxOutputTokens===void 0?this.config:{...this.config,max_output_tokens:i.maxOutputTokens},C=S(r),N=pe(W(t.getMessages())),ie=ae(e),_=e.map(a=>le(a,this.useExplicitCustomToolType));re(_),ue(N);let h={model:this.model,max_tokens:C,stream:!0,system:[{type:"text",text:i?.systemPrompt??this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:N,..._.length>0?{tools:_}:{}},y=I(r,this.getThinkingLevel());if(r.reasoning!==!1)if(y==="off")h.thinking={type:"disabled"};else if(r.thinking_mode==="adaptive"){let a=G(y,r);a!==null&&(h.thinking={type:"adaptive"},h.output_config={effort:a})}else{let a=Math.max(j,i?.answerReserveTokens??0),f=Math.min(E(r,y),C-a);h.thinking=f>=$?{type:"enabled",budget_tokens:f}:{type:"disabled"}}let T=0,v=0,L=0,A=0,B="end_turn",x="",b="",w=!1,O="",P=!1,U=!1;try{let a=[...ie?[te]:[]],f=this.client.messages.stream(h,{...s?{signal:s}:{},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries},...a.length>0?{headers:{"anthropic-beta":a.join(",")}}:{}}),c="",m="",d="";for await(let l of f)switch(l.type){case"content_block_start":{let o=l.content_block;if(o.type==="thinking")w=!0,x="",b="";else if(o.type==="redacted_thinking")O=o.data,P=!0;else if(o.type==="tool_use"){if(!o.id||!o.name)throw new u("Anthropic tool call started without a valid id or name");m=o.id,c=o.name==="computer"?"ComputerUse":o.name,d="",yield{type:"tool_call_start",toolName:c,toolId:m}}break}case"content_block_delta":{let o=l.delta;if(o.type==="thinking_delta")x+=o.thinking,yield{type:"thinking_delta",text:o.thinking};else if(o.type==="signature_delta")b+=o.signature;else if(o.type==="text_delta")yield{type:"text_delta",text:o.text};else if(o.type==="input_json_delta"){if(!m||!c)throw new u("Anthropic tool arguments arrived before a valid tool call");d+=o.partial_json,yield{type:"tool_call_delta",text:o.partial_json}}break}case"content_block_stop":{if(w&&(yield{type:"thinking_complete",thinking:x,signature:b},w=!1),P&&(yield{type:"redacted_thinking_complete",data:O},P=!1),c){let o=ne(d);yield{type:"tool_call_complete",toolId:m,toolName:c,arguments:o.arguments,...o.parseError?{parseError:o.parseError}:{}},c="",m="",d=""}break}case"message_delta":{l.delta.stop_reason&&(B=l.delta.stop_reason);let o=l.usage;typeof o.output_tokens=="number"&&(v=o.output_tokens),typeof o.input_tokens=="number"&&(T=o.input_tokens),typeof o.cache_read_input_tokens=="number"&&(L=o.cache_read_input_tokens),typeof o.cache_creation_input_tokens=="number"&&(A=o.cache_creation_input_tokens);break}case"message_stop":{U=!0;break}case"message_start":{T=l.message.usage.input_tokens,v=l.message.usage.output_tokens,L=l.message.usage.cache_read_input_tokens??0,A=l.message.usage.cache_creation_input_tokens??0;break}}if(!U)throw new u("Anthropic stream ended without message_stop; response was truncated");yield{type:"stream_end",stopReason:B,usage:{inputTokens:T,outputTokens:v,cacheReadInputTokens:L,cacheCreationInputTokens:A}}}catch(a){throw ce.error({err:a},"llm operation failed"),he(a)}}};function ue(n){for(let t=n.length-1;t>=0;t--){if(n[t].role!=="user")continue;let e=n[t].content;if(typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0)return;typeof e=="string"&&(e=n[t].content=[{type:"text",text:e}]);let s=e[e.length-1];for(let i=e.length-1;i>=0;i--)if(e[i].type!=="image"){s=e[i];break}Reflect.set(s,"cache_control",{type:"ephemeral"});return}}function he(n){if(n instanceof M)return n;if(n instanceof g.APIConnectionError||n instanceof g.APIUserAbortError)return new u(`Network error: ${n.message}`);if(n instanceof g.APIError){if(n.status===413||n.status===400&&Z(n.message))return new X(`Prompt too long: ${n.message}`);if(n.status===401)return new R(`Invalid API key: ${n.message}`);if(n.status===429){let t=n.headers,e=t instanceof Headers?t.get("retry-after"):void 0,s="Rate Limited";if(e){let i=Number.parseInt(p(e));Number.isNaN(i)?s+=", please wait.":s+=`, retry after ${p(i)}s.`}else s+=", please wait.";return new J(s,e?p(e):void 0)}if(n.status!==void 0&&(n.status>=500||n.status===408)){let t=n.headers;return new Q(`Anthropic API error (${p(n.status)}): ${n.message}`,t instanceof Headers?t.get("retry-after")??void 0:void 0)}return new M(`Anthropic API error (${p(n.status)}): ${n.message}`)}return new u(`Network error: ${z(n)}`)}export{se as AnthropicClient,pe as buildAnthropicMessages,ue as markLastUserTailForCache,re as markToolsForCache,ae as needsToolSearchBeta};
|