zen-code 4.9.1 → 4.10.0
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/dist/app.js +175 -166
- package/dist/chunk-075hks9v.js +1 -0
- package/dist/chunk-0fj768k4.js +112 -0
- package/dist/chunk-19mf2aa7.js +1 -0
- package/dist/chunk-1mq2jmfy.js +2 -0
- package/dist/chunk-1v863afn.js +278 -0
- package/dist/chunk-1vn8d8b8.js +1 -0
- package/dist/{chunk-mmq834zt.js → chunk-1w19w1bm.js} +1 -1
- package/dist/chunk-3dnayvgx.js +224 -0
- package/dist/chunk-4hg13vwj.js +1 -0
- package/dist/chunk-4scrkcqv.js +1 -0
- package/dist/chunk-54cdhhqm.js +1 -0
- package/dist/chunk-5m4yb9av.js +91 -0
- package/dist/chunk-5yd4ntp6.js +8 -0
- package/dist/{chunk-b52b0t16.js → chunk-6scjjkn3.js} +1 -1
- package/dist/chunk-7jatn15w.js +2 -0
- package/dist/{chunk-4nsg4vcd.js → chunk-7w9y11hj.js} +1 -1
- package/dist/chunk-7yzv6385.js +1 -0
- package/dist/{chunk-g377vrpj.js → chunk-875hayaj.js} +3 -3
- package/dist/chunk-8bs8r50r.js +1 -0
- package/dist/chunk-8waww0j9.js +6 -0
- package/dist/chunk-8ysg0rga.js +1 -0
- package/dist/chunk-9czhw5k6.js +4 -0
- package/dist/chunk-9tgp14v7.js +16 -0
- package/dist/chunk-a239dn0b.js +1 -0
- package/dist/chunk-arv4h3h1.js +2 -0
- package/dist/chunk-b2551zfb.js +2 -0
- package/dist/chunk-b9emn03n.js +1 -0
- package/dist/chunk-bm7578sn.js +1 -0
- package/dist/{chunk-1y82m5kn.js → chunk-bytq4kd1.js} +3 -125
- package/dist/chunk-c2wfgbj6.js +1 -0
- package/dist/{chunk-gcm4jp0d.js → chunk-cef4vbtb.js} +1 -1
- package/dist/chunk-cnzhxgn5.js +4 -0
- package/dist/chunk-d2770b2z.js +1 -0
- package/dist/chunk-d72063sm.js +2 -0
- package/dist/{chunk-9k5d9vf1.js → chunk-d988tv30.js} +1 -1
- package/dist/{chunk-va71tsw3.js → chunk-dx9k6sdd.js} +3 -3
- package/dist/chunk-e6ggkg36.js +2 -0
- package/dist/chunk-fjqtrakn.js +1 -0
- package/dist/chunk-gbfpab0j.js +1 -0
- package/dist/chunk-gkvx829z.js +1 -0
- package/dist/{chunk-9dahn9h7.js → chunk-gwf8b14k.js} +1 -1
- package/dist/chunk-gz7fz9fg.js +1 -0
- package/dist/chunk-h0q3dvnv.js +5 -0
- package/dist/chunk-h0qb9jk1.js +1 -0
- package/dist/chunk-h9y136h8.js +1 -0
- package/dist/chunk-hrcxdj3c.js +54 -0
- package/dist/chunk-hz9yw7cs.js +166 -0
- package/dist/chunk-j4y5rjne.js +79 -0
- package/dist/chunk-k12y05c3.js +3 -0
- package/dist/chunk-k6fxqssr.js +18 -0
- package/dist/{chunk-rncpxz1b.js → chunk-kmxdq21k.js} +2 -2
- package/dist/chunk-mcb8rewr.js +213 -0
- package/dist/{chunk-wn43r152.js → chunk-mm9w91rj.js} +1 -1
- package/dist/chunk-mv0xzmq8.js +2 -0
- package/dist/chunk-n849zsd3.js +1 -0
- package/dist/chunk-nm253hhf.js +81 -0
- package/dist/chunk-prg6489q.js +1 -0
- package/dist/{chunk-cggjws6a.js → chunk-pxdgy0vr.js} +1 -1
- package/dist/chunk-qhzm2qw9.js +2 -0
- package/dist/{chunk-98f6hg43.js → chunk-qmxtys9q.js} +1 -1
- package/dist/chunk-r0cfe5c1.js +294 -0
- package/dist/chunk-rtjytfhh.js +1 -0
- package/dist/chunk-s7ttf0pm.js +2 -0
- package/dist/chunk-t01t72t2.js +140 -0
- package/dist/{chunk-ns6tjjkq.js → chunk-t0f66x64.js} +1 -1
- package/dist/chunk-tn356gwf.js +93 -0
- package/dist/chunk-vd8kwzra.js +41 -0
- package/dist/chunk-vhn13anh.js +233 -0
- package/dist/chunk-vnewbtjy.js +1 -0
- package/dist/chunk-wbm7rn9w.js +2 -0
- package/dist/chunk-wd3gkd45.js +3 -0
- package/dist/chunk-whdf0vbb.js +1 -0
- package/dist/{chunk-j7a40ww9.js → chunk-ws232ksq.js} +2 -2
- package/dist/{chunk-8g2zdcy0.js → chunk-yerf10k7.js} +1 -1
- package/dist/{chunk-heasksrr.js → chunk-yzv3n8mw.js} +2 -2
- package/dist/chunk-z3e4c424.js +2 -0
- package/dist/chunk-znw7fpep.js +6 -0
- package/dist/chunk-zq2g4rfd.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/nonInteractive.js +314 -4
- package/dist/zen-keyboard.js +1 -1
- package/package.json +37 -37
- package/dist/chunk-02vv5584.js +0 -1
- package/dist/chunk-13nyfrmm.js +0 -310
- package/dist/chunk-1edvf7b5.js +0 -1
- package/dist/chunk-1rmnbdef.js +0 -1
- package/dist/chunk-1ttywx0y.js +0 -6
- package/dist/chunk-30sq2w0d.js +0 -8
- package/dist/chunk-32ase1cw.js +0 -2
- package/dist/chunk-3490ntd8.js +0 -1
- package/dist/chunk-3pcybja5.js +0 -7
- package/dist/chunk-5rr85f28.js +0 -1
- package/dist/chunk-5x8nxw0t.js +0 -137
- package/dist/chunk-6rfc36jg.js +0 -1
- package/dist/chunk-76h8pe7x.js +0 -2
- package/dist/chunk-7kdvr78m.js +0 -31
- package/dist/chunk-8z38ybz7.js +0 -1
- package/dist/chunk-b8dxq9rq.js +0 -1
- package/dist/chunk-cjqarwdn.js +0 -1
- package/dist/chunk-cs73xbzz.js +0 -1
- package/dist/chunk-cyexd09c.js +0 -2
- package/dist/chunk-ep2es95e.js +0 -81
- package/dist/chunk-f8ewggk1.js +0 -1
- package/dist/chunk-g7pm00z7.js +0 -253
- package/dist/chunk-hfve7nf5.js +0 -2
- package/dist/chunk-j9aysaeb.js +0 -1
- package/dist/chunk-jbf8ve63.js +0 -3
- package/dist/chunk-jfhc5c0d.js +0 -1
- package/dist/chunk-jxsfzfac.js +0 -2
- package/dist/chunk-kba8akjs.js +0 -2
- package/dist/chunk-m76ya904.js +0 -1
- package/dist/chunk-mjzeawnq.js +0 -6
- package/dist/chunk-nwy6n6b6.js +0 -274
- package/dist/chunk-qd305hg1.js +0 -1
- package/dist/chunk-qez6ejd4.js +0 -1
- package/dist/chunk-r2h3x9zv.js +0 -2
- package/dist/chunk-rz3b356n.js +0 -1
- package/dist/chunk-trjpzw1n.js +0 -91
- package/dist/chunk-xhnvpygg.js +0 -2
- package/dist/chunk-xkz5z0zn.js +0 -1
- package/dist/chunk-zwxjkwqd.js +0 -26
- package/dist/chunk-zz32kgt2.js +0 -1
package/dist/chunk-qd305hg1.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{tb as a}from"./chunk-1ttywx0y.js";import"./chunk-kba8akjs.js";export{a as FileSystemSkillStore};
|
package/dist/chunk-qez6ejd4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{pb as a,qb as b}from"./chunk-cyexd09c.js";import"./chunk-kba8akjs.js";export{a as createFSManager,b as createCustomManager};
|
package/dist/chunk-r2h3x9zv.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{Low as K}from"lowdb";import{JSONFile as M}from"lowdb/node";import Q from"os";import E from"path";import z from"fs";import R from"proper-lockfile";var A={config:{provider_id:"default",provider_type:"openai",model_id:"glm-5",providers:[{id:"default",type:"openai",apiKey:"",baseUrl:"https://api.openai.com/v1"}],compact_mode:!0}};function T(j){return"main_model"in j&&!("providers"in j)}function U(j){let q=[];if(j.model_provider==="openai"||j.openai_api_key||j.openai_base_url)q.push({id:"openai",type:"openai",apiKey:j.openai_api_key||"",baseUrl:j.openai_base_url||"https://api.openai.com/v1"});if(j.model_provider==="anthropic"||j.anthropic_api_key||j.anthropic_base_url)q.push({id:"anthropic",type:"anthropic",apiKey:j.anthropic_api_key||"",baseUrl:j.anthropic_base_url||"https://api.anthropic.com"});if(q.length===0)q.push({id:"default",type:"openai",apiKey:"",baseUrl:"https://api.openai.com/v1"});let x=j.model_provider==="anthropic"?"anthropic":"openai",B=q.find((G)=>G.id===x)||q[0];return{provider_id:B.id,provider_type:B.type,model_id:j.main_model,providers:q,mcp_config:j.mcp_config,stream_refresh_interval:j.stream_refresh_interval,enable_thinking:j.enable_thinking,switch_command:j.switch_command,compact_mode:j.compact_mode,permissions:j.permissions}}class V{db;zenConfigDir;dbPath;getLockfilePath(){return`${this.dbPath}.lock`}lockOptions={stale:5000,retries:{retries:5,minTimeout:100,maxTimeout:1000}};constructor(){let j=Q.homedir();this.zenConfigDir=E.join(j,".zen-code");let q=E.join(this.zenConfigDir,"settings.json"),x=new M(q);this.dbPath=q,this.db=new K(x,A)}async withLock(j){if(await z.promises.mkdir(this.zenConfigDir,{recursive:!0}),!z.existsSync(this.dbPath))await z.promises.writeFile(this.dbPath,JSON.stringify(A,null,2),"utf-8");let q=await R.lock(this.dbPath,{...this.lockOptions,lockfilePath:this.getLockfilePath()});try{return await j()}finally{await q()}}async initialize(){await this.withLock(async()=>{if(await this.db.read(),!this.db.data||!this.db.data.config)this.db.data=A,await this.db.write();else if(T(this.db.data.config))console.log("Migrating legacy config to new format..."),this.db.data.config=U(this.db.data.config),await this.db.write(),console.log("Config migration completed.");this.syncEnvFromConfig()})}async getConfig(){return this.withLock(async()=>{return await this.db.read(),this.db.data.config})}async updateConfig(j){await this.withLock(async()=>{await this.db.read(),Object.assign(this.db.data.config,j),await this.db.write(),this.syncEnvFromConfig()})}syncEnvFromConfig(){let j=this.db.data.config,q=j.providers.find((x)=>x.id===j.provider_id);if(q){if(q.type==="openai")process.env.MODEL_PROVIDER="openai",process.env.OPENAI_API_KEY=q.apiKey,process.env.OPENAI_BASE_URL=q.baseUrl;else if(q.type==="anthropic")process.env.MODEL_PROVIDER="anthropic",process.env.ANTHROPIC_API_KEY=q.apiKey,process.env.ANTHROPIC_BASE_URL=q.baseUrl;else if(q.type==="gemini"||q.type==="google")process.env.MODEL_PROVIDER="gemini",process.env.GOOGLE_API_KEY=q.apiKey,process.env.GOOGLE_BASE_URL=q.baseUrl}}getZenConfigDir(){return this.zenConfigDir}}
|
|
2
|
-
export{V as sb};
|
package/dist/chunk-rz3b356n.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Aa as a}from"./chunk-7kdvr78m.js";import"./chunk-xhnvpygg.js";import"./chunk-kba8akjs.js";export{a as MemoriesMiddleware};
|
package/dist/chunk-trjpzw1n.js
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import{X as z,Y as P,Z as K,_ as O}from"./chunk-jxsfzfac.js";import{yb as b}from"./chunk-kba8akjs.js";import{Kysely as L,sql as D}from"kysely";var G={maxRetries:3,baseDelayMs:100,nonRetryablePatterns:["database disk image is malformed","database is malformed","cannot rollback","no transaction is active","database or disk is full"],isRetryableError:(H)=>{let J=H?.message?.toLowerCase()||"";for(let V of G.nonRetryablePatterns)if(J.includes(V.toLowerCase()))return!1;return J.includes("sqlite_busy")||J.includes("database is locked")||J==="sqlite_busy"||J==="database is locked"}};async function F(H,J){let V=null;for(let Z=0;Z<G.maxRetries;Z++)try{return await H()}catch($){V=$;let X=$?.message?.toLowerCase()||"";if(!G.isRetryableError($)){if(X.includes("malformed")){let j=Error(`SQLite database is corrupted: ${$.message}
|
|
2
|
-
|
|
3
|
-
Context: ${J||"unknown"}
|
|
4
|
-
|
|
5
|
-
Possible causes:
|
|
6
|
-
1. Database file was manually deleted or modified
|
|
7
|
-
2. Disk I/O errors during write operations
|
|
8
|
-
3. Concurrent access without proper locking
|
|
9
|
-
|
|
10
|
-
Recovery options:
|
|
11
|
-
- Delete the database file to start fresh (data will be lost)
|
|
12
|
-
- Use SQLite recovery tools: sqlite3 <db> ".recover" > recover.sql
|
|
13
|
-
- Switch to PostgreSQL/Redis for production use`);throw j.name="SQLiteCorruptError",j.cause=$,j}throw $}if(Z<G.maxRetries-1){let j=G.baseDelayMs*Math.pow(2,Z);console.warn(`SQLite lock detected${J?` (${J})`:""}, retrying in ${j}ms (attempt ${Z+1}/${G.maxRetries})`),await new Promise((U)=>setTimeout(U,j))}}throw V}var R=["source","step","parents"];function x(H){return H}var E=x(R);class N extends K{db;isSetup;constructor(H,J){super(J);this.db=new L({dialect:H}),this.isSetup=!1}static async fromConnStringAsync(H){let J;if(globalThis.Bun){console.log("LG | Using BunWorkerDialect "+H);let{BunSqliteDialect:V}=await import("kysely-bun-worker/normal");J=new N(new V({url:H}))}else{console.log("LG | Using NodeWasmDialect");let{default:V}=await import("node-sqlite3-wasm"),{NodeWasmDialect:Z}=await import("kysely-wasm");console.log(H);let $=new Z({database:new V.Database(H)});J=new N($)}return await J.setup(),J}async setup(){if(this.isSetup)return;await D`PRAGMA busy_timeout = 5000`.execute(this.db),await D`PRAGMA journal_mode = WAL`.execute(this.db),await D`PRAGMA synchronous = NORMAL`.execute(this.db),await D`PRAGMA wal_autocheckpoint = 1000`.execute(this.db),await D`
|
|
14
|
-
CREATE TABLE IF NOT EXISTS checkpoints (
|
|
15
|
-
thread_id TEXT NOT NULL,
|
|
16
|
-
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
17
|
-
checkpoint_id TEXT NOT NULL,
|
|
18
|
-
parent_checkpoint_id TEXT,
|
|
19
|
-
type TEXT,
|
|
20
|
-
checkpoint BLOB,
|
|
21
|
-
metadata BLOB,
|
|
22
|
-
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
|
|
23
|
-
)`.execute(this.db),await D`
|
|
24
|
-
CREATE TABLE IF NOT EXISTS writes (
|
|
25
|
-
thread_id TEXT NOT NULL,
|
|
26
|
-
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
27
|
-
checkpoint_id TEXT NOT NULL,
|
|
28
|
-
task_id TEXT NOT NULL,
|
|
29
|
-
idx INTEGER NOT NULL,
|
|
30
|
-
channel TEXT NOT NULL,
|
|
31
|
-
type TEXT,
|
|
32
|
-
value BLOB,
|
|
33
|
-
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
|
34
|
-
)`.execute(this.db),this.isSetup=!0}async getTuple(H){await this.setup();let{thread_id:J,checkpoint_ns:V="",checkpoint_id:Z}=H.configurable??{},$=this.db.selectFrom("checkpoints").select(["thread_id","checkpoint_ns","checkpoint_id","parent_checkpoint_id","type","checkpoint","metadata",D`(
|
|
35
|
-
SELECT json_group_array(
|
|
36
|
-
json_object(
|
|
37
|
-
'task_id', pw.task_id,
|
|
38
|
-
'channel', pw.channel,
|
|
39
|
-
'type', pw.type,
|
|
40
|
-
'value', CAST(pw.value AS TEXT)
|
|
41
|
-
)
|
|
42
|
-
)
|
|
43
|
-
FROM writes as pw
|
|
44
|
-
WHERE pw.thread_id = checkpoints.thread_id
|
|
45
|
-
AND pw.checkpoint_ns = checkpoints.checkpoint_ns
|
|
46
|
-
AND pw.checkpoint_id = checkpoints.checkpoint_id
|
|
47
|
-
)`.as("pending_writes"),D`(
|
|
48
|
-
SELECT json_group_array(
|
|
49
|
-
json_object(
|
|
50
|
-
'type', ps.type,
|
|
51
|
-
'value', CAST(ps.value AS TEXT)
|
|
52
|
-
)
|
|
53
|
-
)
|
|
54
|
-
FROM writes as ps
|
|
55
|
-
WHERE ps.thread_id = checkpoints.thread_id
|
|
56
|
-
AND ps.checkpoint_ns = checkpoints.checkpoint_ns
|
|
57
|
-
AND ps.checkpoint_id = checkpoints.parent_checkpoint_id
|
|
58
|
-
AND ps.channel = ${z}
|
|
59
|
-
ORDER BY ps.idx
|
|
60
|
-
)`.as("pending_sends")]).where("thread_id","=",J).where("checkpoint_ns","=",V);if(Z)$=$.where("checkpoint_id","=",Z);else $=$.orderBy("checkpoint_id","desc").limit(1);let X=await $.executeTakeFirst();if(!X)return;let j=H;if(!Z)j={configurable:{thread_id:X.thread_id,checkpoint_ns:V,checkpoint_id:X.checkpoint_id}};if(j.configurable?.thread_id===void 0||j.configurable?.checkpoint_id===void 0)throw Error("Missing thread_id or checkpoint_id");let U=await Promise.all(JSON.parse(X.pending_writes).map(async(A)=>{return[A.task_id,A.channel,await this.serde.loadsTyped(A.type??"json",A.value??"")]})),W=await this.serde.loadsTyped(X.type??"json",new TextDecoder().decode(X.checkpoint));if(W.v<4&&X.parent_checkpoint_id!=null)await this.migratePendingSends(W,X.thread_id,X.parent_checkpoint_id);return{checkpoint:W,config:j,metadata:await this.serde.loadsTyped(X.type??"json",new TextDecoder().decode(X.metadata)),parentConfig:X.parent_checkpoint_id?{configurable:{thread_id:X.thread_id,checkpoint_ns:V,checkpoint_id:X.parent_checkpoint_id}}:void 0,pendingWrites:U}}async*list(H,J){let{limit:V,before:Z,filter:$}=J??{};await this.setup();let X=H.configurable?.thread_id,j=H.configurable?.checkpoint_ns,U=this.db.selectFrom("checkpoints").select(["thread_id","checkpoint_ns","checkpoint_id","parent_checkpoint_id","type","checkpoint","metadata",D`(
|
|
61
|
-
SELECT json_group_array(
|
|
62
|
-
json_object(
|
|
63
|
-
'task_id', pw.task_id,
|
|
64
|
-
'channel', pw.channel,
|
|
65
|
-
'type', pw.type,
|
|
66
|
-
'value', CAST(pw.value AS TEXT)
|
|
67
|
-
)
|
|
68
|
-
)
|
|
69
|
-
FROM writes as pw
|
|
70
|
-
WHERE pw.thread_id = checkpoints.thread_id
|
|
71
|
-
AND pw.checkpoint_ns = checkpoints.checkpoint_ns
|
|
72
|
-
AND pw.checkpoint_id = checkpoints.checkpoint_id
|
|
73
|
-
)`.as("pending_writes"),D`(
|
|
74
|
-
SELECT json_group_array(
|
|
75
|
-
json_object(
|
|
76
|
-
'type', ps.type,
|
|
77
|
-
'value', CAST(ps.value AS TEXT)
|
|
78
|
-
)
|
|
79
|
-
)
|
|
80
|
-
FROM writes as ps
|
|
81
|
-
WHERE ps.thread_id = checkpoints.thread_id
|
|
82
|
-
AND ps.checkpoint_ns = checkpoints.checkpoint_ns
|
|
83
|
-
AND ps.checkpoint_id = checkpoints.parent_checkpoint_id
|
|
84
|
-
AND ps.channel = ${z}
|
|
85
|
-
ORDER BY ps.idx
|
|
86
|
-
)`.as("pending_sends")]);if(X)U=U.where("thread_id","=",X);if(j!==void 0&&j!==null)U=U.where("checkpoint_ns","=",j);if(Z?.configurable?.checkpoint_id!==void 0)U=U.where("checkpoint_id","<",Z.configurable.checkpoint_id);let W=Object.fromEntries(Object.entries($??{}).filter(([B,M])=>M!==void 0&&E.includes(B)));for(let[B,M]of Object.entries(W))U=U.where(D`json_extract(CAST(metadata AS TEXT), ${D.lit("$."+B)})`,"=",D.lit(JSON.stringify(M)));if(U=U.orderBy("checkpoint_id","desc"),V)U=U.limit(parseInt(V,10));let A=await U.execute();for(let B of A){let M=await Promise.all(JSON.parse(B.pending_writes).map(async(Q)=>{return[Q.task_id,Q.channel,await this.serde.loadsTyped(Q.type??"json",Q.value??"")]})),Y=await this.serde.loadsTyped(B.type??"json",new TextDecoder().decode(B.checkpoint));if(Y.v<4&&B.parent_checkpoint_id!=null)await this.migratePendingSends(Y,B.thread_id,B.parent_checkpoint_id);yield{config:{configurable:{thread_id:B.thread_id,checkpoint_ns:B.checkpoint_ns,checkpoint_id:B.checkpoint_id}},checkpoint:Y,metadata:await this.serde.loadsTyped(B.type??"json",new TextDecoder().decode(B.metadata)),parentConfig:B.parent_checkpoint_id?{configurable:{thread_id:B.thread_id,checkpoint_ns:B.checkpoint_ns,checkpoint_id:B.parent_checkpoint_id}}:void 0,pendingWrites:M}}}async put(H,J,V){if(await this.setup(),!H.configurable)throw Error("Empty configuration supplied.");let Z=H.configurable?.thread_id,$=H.configurable?.checkpoint_ns??"",X=H.configurable?.checkpoint_id;if(!Z)throw Error('Missing "thread_id" field in passed "config.configurable".');let j=P(J),[[U,W],[A,B]]=await Promise.all([this.serde.dumpsTyped(j),this.serde.dumpsTyped(V)]);if(U!==A)throw Error("Failed to serialized checkpoint and metadata to the same type.");return await F(async()=>{await this.db.insertInto("checkpoints").values({thread_id:Z,checkpoint_ns:$,checkpoint_id:J.id,parent_checkpoint_id:X??null,type:U,checkpoint:new Uint8Array(Buffer.from(W)),metadata:new Uint8Array(Buffer.from(B))}).onConflict((M)=>M.columns(["thread_id","checkpoint_ns","checkpoint_id"]).doUpdateSet({parent_checkpoint_id:X??null,type:U,checkpoint:new Uint8Array(Buffer.from(W)),metadata:new Uint8Array(Buffer.from(B))})).execute()},`put(${Z}/${J.id})`),{configurable:{thread_id:Z,checkpoint_ns:$,checkpoint_id:J.id}}}async putWrites(H,J,V){if(await this.setup(),!H.configurable)throw Error("Empty configuration supplied.");if(!H.configurable?.thread_id)throw Error("Missing thread_id field in config.configurable.");if(!H.configurable?.checkpoint_id)throw Error("Missing checkpoint_id field in config.configurable.");let Z=await Promise.all(J.map(async(j,U)=>{let[W,A]=await this.serde.dumpsTyped(j[1]);return{thread_id:H.configurable.thread_id,checkpoint_ns:H.configurable.checkpoint_ns??"",checkpoint_id:H.configurable.checkpoint_id,task_id:V,idx:U,channel:j[0],type:W,value:new Uint8Array(Buffer.from(A))}}));if(Z.length===0)return;let $=H.configurable.thread_id,X=H.configurable.checkpoint_id;await F(async()=>{await this.db.transaction().execute(async(j)=>{await j.deleteFrom("writes").where("thread_id","=",$).where("checkpoint_ns","=",Z[0].checkpoint_ns).where("checkpoint_id","=",X).where("task_id","=",V).execute();for(let U of Z)await j.insertInto("writes").values(U).execute()})},`putWrites(${$}/${X}/${V})`)}async deleteThread(H){await F(async()=>{await this.db.transaction().execute(async(J)=>{await J.deleteFrom("checkpoints").where("thread_id","=",H).execute(),await J.deleteFrom("writes").where("thread_id","=",H).execute()})},`deleteThread(${H})`)}async migratePendingSends(H,J,V){let Z=await this.db.selectFrom("writes as ps").select(["ps.checkpoint_id",D`json_group_array(
|
|
87
|
-
json_object(
|
|
88
|
-
'type', ps.type,
|
|
89
|
-
'value', CAST(ps.value AS TEXT)
|
|
90
|
-
)
|
|
91
|
-
)`.as("pending_sends")]).where("ps.thread_id","=",J).where("ps.checkpoint_id","=",V).where("ps.channel","=",z).orderBy("ps.idx").executeTakeFirst();if(!Z)return;let $=H;$.channel_values??={},$.channel_values[z]=await Promise.all(JSON.parse(Z.pending_sends).map(({type:X,value:j})=>this.serde.loadsTyped(X,j))),$.channel_versions[z]=Object.keys(H.channel_versions).length>0?O(...Object.values(H.channel_versions)):this.getNextVersion(void 0)}}export{N as SqliteSaver};
|
package/dist/chunk-xhnvpygg.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{readFileSync as I,statSync as O,existsSync as B,readdirSync as R,lstatSync as u}from"fs";import{join as G,resolve as V,relative as N}from"path";import{parse as g}from"yaml";var p=10485760,v=64,F=1024;function H(k,K){try{let q=V(k),Q=V(K),z=N(Q,q);if(!z)return!0;if(z.startsWith("..")||z.includes(":"))return!1;return!0}catch(q){return!1}}function E(k){if(!k)return[!1,"name is required"];if(k.length>v)return[!1,"name exceeds 64 characters"];if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(k))return[!1,"name must be lowercase alphanumeric with single hyphens only"];return[!0,""]}function f(k){let K=["architecture","bug-fix","workflow","configuration","optimization"];if(!k)return[!1,"category is required"];if(!K.includes(k))return[!1,`category must be one of: ${K.join(", ")}`];return[!0,""]}function S(k,K){try{let q=O(k);if(q.size>p)return console.warn(`Skipping ${k}: file too large (${q.size} bytes)`),null;let Q=I(k,"utf-8"),z=/^---\s*\n([\s\S]*?)\n---\s*\n/,W=Q.match(z);if(!W)return console.warn(`Skipping ${k}: no valid YAML frontmatter found`),null;let $=W[1],J;try{J=g($)}catch(j){return console.warn(`Invalid YAML in ${k}: ${j}`),null}if(typeof J!=="object"||J===null)return console.warn(`Skipping ${k}: frontmatter is not a mapping`),null;let{name:U,description:w,tags:Z,category:x}=J;if(!U||!w||!Z||!x)return console.warn(`Skipping ${k}: missing required fields (name, description, tags, category)`),null;let[X,Y]=E(String(U));if(!X)console.warn(`Memory '${U}' in ${k} does not follow naming convention: ${Y}. Consider renaming to be compliant.`);let[A,C]=f(String(x));if(!A)return console.warn(`Skipping ${k}: ${C}`),null;let b=String(w);if(b.length>F)console.warn(`Description exceeds ${F} chars in ${k}, truncating`),b=b.substring(0,F);if(!Array.isArray(Z))return console.warn(`Skipping ${k}: tags must be an array`),null;let T=Z.map(String);return{name:String(U),description:b,tags:T,category:String(x),path:k,source:K,created:J.created,last_updated:J.last_updated,priority:J.priority||"medium",context_scope:J.context_scope||"project"}}catch(q){return console.warn(`Error reading ${k}: ${q.message}`),null}}function L(k,K){if(!B(k))return[];let q;try{q=V(k)}catch(W){return[]}let Q=[],z;try{z=R(k)}catch(W){return[]}for(let W of z){let $=G(k,W);if(!H($,q))continue;let J;try{J=u($)}catch(Z){continue}if(!J.isDirectory())continue;let U=G($,"MEMORY.md");if(!B(U))continue;if(!H(U,q))continue;let w=S(U,K);if(w)Q.push(w)}return Q}function D(k,K){let q=new Map;if(k){let Q=L(k,"user");for(let z of Q)q.set(z.name,z)}if(K){let Q=L(K,"project");for(let z of Q)q.set(z.name,z)}return Array.from(q.values())}
|
|
2
|
-
export{D as Ba};
|
package/dist/chunk-xkz5z0zn.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{N as k}from"./chunk-hfve7nf5.js";import"./chunk-va71tsw3.js";import{ea as R,fa as g,ga as r,oa as B,pa as b}from"./chunk-nwy6n6b6.js";import"./chunk-5rr85f28.js";import"./chunk-cggjws6a.js";import"./chunk-cyexd09c.js";import"./chunk-r2h3x9zv.js";import"./chunk-1ttywx0y.js";import{ub as m}from"./chunk-kba8akjs.js";var w=m(R(),1);var u=m(R(),1);var n=m(b(),1),H=({field:e,value:t,isFocused:o})=>n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:t?"green":"gray",bold:o,children:t?"ON":"OFF"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J=({field:e,value:t,isFocused:o})=>n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:o?"yellow":void 0,bold:o,children:t??e.min??0},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:" ms"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L=({field:e,value:t,isFocused:o})=>{let a=e.options?.find((y)=>y.value===t);return n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:o?"yellow":void 0,bold:o,children:a?.label||t},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},Y=({field:e,value:t,isFocused:o})=>n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:o?"yellow":"gray",bold:o,children:t||e.placeholder||"-"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q=(e)=>{switch(e.field.type){case"toggle":return n.jsxDEV(H,{...e},void 0,!1,void 0,this);case"number":return n.jsxDEV(J,{...e},void 0,!1,void 0,this);case"select":return n.jsxDEV(L,{...e},void 0,!1,void 0,this);case"input":return n.jsxDEV(Y,{...e},void 0,!1,void 0,this);default:return n.jsxDEV(r,{color:"red",children:"Unknown"},void 0,!1,void 0,this)}},M=q;var x=[{key:"compact_mode",label:"紧凑模式",type:"toggle",group:"显示",tab:"General",help:"紧凑显示消息 (Ctrl+O)"},{key:"show_detailed_info",label:"系统信息",type:"toggle",group:"显示",tab:"General",help:"显示系统资源信息"},{key:"enable_thinking",label:"思考模式",type:"toggle",group:"模型",tab:"General",help:"启用模型思考"},{key:"stream_refresh_interval",label:"流刷新间隔",type:"number",group:"模型",tab:"General",min:50,max:1000,step:50,help:"流刷新间隔 (ms)"}],S=(()=>{let e=new Map;return x.forEach((t)=>{let o=t.tab||"General";if(!e.has(o))e.set(o,{id:o,label:o,icon:"⚙"})}),Array.from(e.values())})(),D=(()=>{let e=new Map;return x.forEach((t)=>{if(!e.has(t.group))e.set(t.group,{id:t.group,label:t.group,fields:[]});e.get(t.group).fields.push(t)}),Array.from(e.values())})();function z(e){return x.filter((t)=>(t.tab||"General")===e)}function _(e){let t=z(e),o=new Map;return t.forEach((a)=>{if(!o.has(a.group))o.set(a.group,{id:a.group,label:a.group,fields:[]});o.get(a.group).fields.push(a)}),Array.from(o.values())}var f=m(b(),1);function K(e){switch(e.type){case"toggle":return!1;case"number":return e.min??0;case"select":return e.options?.[0]?.value;case"input":return"";default:return}}var Q=({schema:e,config:t,onUpdate:o,activeTab:a="General"})=>{let y=u.useMemo(()=>_(a),[a]),T=u.useMemo(()=>y.flatMap((l)=>l.fields),[y]),[P,h]=u.useState(0),p=T[P],c=u.useCallback((l,i)=>{o(l.key,i)},[o]),G=u.useCallback((l)=>{c(l,!t[l.key])},[t,c]),A=u.useCallback((l,i)=>{let d=t[l.key]??K(l),F=l.step||1,C=l.min??-1/0,I=l.max??1/0;c(l,Math.max(C,Math.min(I,d+i*F)))},[t,c]),U=u.useCallback((l,i)=>{let d=l.options||[];if(!d.length)return;let C=(d.findIndex((I)=>I.value===t[l.key])+i+d.length)%d.length;c(l,d[C].value)},[t,c]);B((l,i)=>{if(i.upArrow)h((d)=>Math.max(0,d-1));else if(i.downArrow)h((d)=>Math.min(T.length-1,d+1));else if(i.leftArrow||i.rightArrow){let d=i.leftArrow?-1:1;if(p?.type==="toggle")G(p);else if(p?.type==="number")A(p,d);else if(p?.type==="select")U(p,d)}},{isActive:!0});let X=0;return f.jsxDEV(g,{flexDirection:"column",paddingX:2,paddingY:1,children:[y.map((l)=>f.jsxDEV(g,{flexDirection:"column",marginBottom:1,children:[f.jsxDEV(r,{bold:!0,color:"gray",children:["[",l.label,"]"]},void 0,!0,void 0,this),l.fields.map((i)=>{let F=X++===P;return f.jsxDEV(g,{flexDirection:"column",children:[f.jsxDEV(M,{field:i,value:t[i.key],onChange:(C)=>c(i,C),isFocused:F},void 0,!1,void 0,this),F&&i.help&&f.jsxDEV(r,{dimColor:!0,color:"yellow",children:[" ","→ ",i.help]},void 0,!0,void 0,this)]},i.key,!0,void 0,this)})]},l.id,!0,void 0,this)),f.jsxDEV(g,{marginTop:1,children:f.jsxDEV(r,{dimColor:!0,children:"↑↓ 导航 | ←→ 修改"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},v=Q;var s=m(b(),1),W=({onClose:e})=>{let{config:t,updateConfig:o}=k(),[a,y]=w.useState("General"),T=S.length>1,P=w.useCallback(async(p,c)=>{await o({[p]:c})},[o]),h=w.useCallback((p)=>{if(!T)return;let G=(S.findIndex((A)=>A.id===a)+p+S.length)%S.length;y(S[G].id)},[a,T]);if(B((p,c)=>{if(c.escape)e();else if(c.leftArrow&&c.alt)h(-1);else if(c.rightArrow&&c.alt)h(1)},{isActive:t!==null}),!t)return s.jsxDEV(g,{padding:2,children:s.jsxDEV(r,{children:"Loading..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);return s.jsxDEV(g,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",children:[s.jsxDEV(g,{paddingX:2,borderBottom:!0,borderColor:"gray",children:s.jsxDEV(r,{bold:!0,color:"cyan",children:"⚙ Settings"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T&&s.jsxDEV(g,{flexDirection:"row",gap:2,paddingX:2,borderBottom:!0,borderColor:"gray",children:S.map((p)=>s.jsxDEV(r,{bold:a===p.id,color:a===p.id?"cyan":"gray",children:[p.icon," ",p.label]},p.id,!0,void 0,this))},void 0,!1,void 0,this),s.jsxDEV(v,{schema:x,config:t,onUpdate:P,activeTab:a},void 0,!1,void 0,this),s.jsxDEV(g,{paddingX:2,borderTop:!0,borderColor:"gray",children:s.jsxDEV(r,{dimColor:!0,children:"Esc: Close | Auto-save | Global: Ctrl+O (Compact)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},N=W;var O=m(b(),1),Z=({onClose:e})=>{return O.jsxDEV(N,{onClose:e},void 0,!1,void 0,this)},ue=Z;export{ue as default};
|
package/dist/chunk-zwxjkwqd.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import{Ta as a}from"./chunk-13nyfrmm.js";import{sb as s}from"./chunk-r2h3x9zv.js";import{Annotation as S}from"@langchain/langgraph";var _=(...G)=>{return{build:(U={})=>{return S.Root(Object.assign({},...G.map((W)=>W.spec),U))}}},q=(G)=>S({reducer:(U,W)=>W,default:G});import{tool as U1}from"@langchain/core/tools";import{z as P}from"zod";var W1=P.object({thought:P.string().describe("Your current thinking step"),nextThoughtNeeded:P.boolean().describe("Whether another thought step is needed"),thoughtNumber:P.number().min(1).describe("Current thought number"),totalThoughts:P.number().min(1).describe("Estimated total thoughts needed"),isRevision:P.boolean().optional().describe("Whether this revises previous thinking"),revisesThought:P.number().min(1).optional().describe("Which thought is being reconsidered"),branchFromThought:P.number().min(1).optional().describe("Branching point thought number"),branchId:P.string().optional().describe("Branch identifier"),needsMoreThoughts:P.boolean().optional().describe("If more thoughts are needed")}),w=[],I={},m1=U1(async(G)=>{try{if(G.thoughtNumber>G.totalThoughts)G.totalThoughts=G.thoughtNumber;if(w.push(G),G.branchFromThought&&G.branchId){if(!I[G.branchId])I[G.branchId]=[];I[G.branchId].push(G)}return JSON.stringify({thoughtNumber:G.thoughtNumber,totalThoughts:G.totalThoughts,nextThoughtNeeded:G.nextThoughtNeeded,branches:Object.keys(I),thoughtHistoryLength:w.length},null,2)}catch(U){return JSON.stringify({error:U instanceof Error?U.message:String(U),status:"failed"},null,2)}},{name:"sequential-thinking",description:`A detailed tool for dynamic and reflective problem-solving through thoughts.
|
|
2
|
-
This tool helps analyze problems through a flexible thinking process that can adapt and evolve.
|
|
3
|
-
Each thought can build on, question, or revise previous insights as understanding deepens.
|
|
4
|
-
|
|
5
|
-
When to use this tool:
|
|
6
|
-
- Breaking down complex problems into steps
|
|
7
|
-
- Planning and design with room for revision
|
|
8
|
-
- Analysis that might need course correction
|
|
9
|
-
- Problems where the full scope might not be clear initially
|
|
10
|
-
- Problems that require a multi-step solution
|
|
11
|
-
- Tasks that need to maintain context over multiple steps
|
|
12
|
-
- Situations where irrelevant information needs to be filtered out
|
|
13
|
-
|
|
14
|
-
Key features:
|
|
15
|
-
- You can adjust total_thoughts up or down as you progress
|
|
16
|
-
- You can question or revise previous thoughts
|
|
17
|
-
- You can add more thoughts even after reaching what seemed like the end
|
|
18
|
-
- You can express uncertainty and explore alternative approaches
|
|
19
|
-
- Not every thought needs to build linearly - you can branch or backtrack
|
|
20
|
-
- Generates a solution hypothesis
|
|
21
|
-
- Verifies the hypothesis based on the Chain of Thought steps
|
|
22
|
-
- Repeats the process until satisfied
|
|
23
|
-
- Provides a correct answer`,schema:W1});import{tool as f}from"@langchain/core/tools";import{z as $}from"zod";var X1=$.object({url:$.string().url().describe("the url to crawl"),raw:$.boolean().optional().default(!1).describe("return raw html")}),B1=$.object({query:$.string().describe("the query to search"),engines:$.array($.enum(["basic","npm","juejin","anthropic","github"])).default(["basic"]).describe("the engines to use"),returnType:$.enum(["json","markdown"]).default("json").describe("the content type to return"),withMetadata:$.boolean().default(!0).describe("whether to include metadata in the search results")}),s1=f(async({url:G})=>{if(!G)return{status:"error",error:"URL is required"};let U=await fetch(`${process.env.SEARCH_SERVER_URL||"http://localhost:8123"}/website-to-md/extract`,{method:"POST",body:JSON.stringify({url:G})});if(!U.ok)throw Error(`HTTP error! status: ${U.status}`);return await U.text()},{name:"read_web_page",description:"A powerful web content extraction tool that retrieves and processes raw content from specified URLs, ideal for data collection, content analysis, and research tasks.",schema:$.object(X1.shape)}),a1=f(async({query:G,engines:U})=>{let W=await fetch(`${process.env.SEARCH_SERVER_URL||"http://localhost:8123"}/website-to-md/search`,{method:"POST",body:JSON.stringify({query:G,engines:U,returnType:"json",withMetadata:!0})});if(!W.ok)throw Error(`HTTP error! status: ${W.status}`);return await W.text()},{name:"web_search",description:"A powerful web search tool that provides comprehensive, real-time results using search engine. Returns relevant web content with customizable parameters for result count, content type, and domain filtering. Ideal for gathering current information, news, and detailed web content analysis.",schema:$.object(B1.shape)});import{AIMessage as v0,ToolMessage as x0}from"@langchain/core/messages";import{AIMessage as X0,HumanMessage as B0,SystemMessage as J0,ToolMessage as L0}from"@langchain/core/messages";var Q0=(G)=>{return G?.configurable?.thread_id};import{Command as H0,getCurrentTaskInput as P0}from"@langchain/langgraph";import{z as E0}from"zod";import{ToolMessage as y0}from"@langchain/core/messages";import{tool as R0}from"@langchain/core/tools";import{Annotation as N,MessagesAnnotation as L1,START as D0,StateGraph as S0}from"@langchain/langgraph";var A=N.Root({...L1.spec,activeAgent:N});import{z as C0}from"zod";import{ToolMessage as k0}from"@langchain/core/messages";import{tool as d0}from"@langchain/core/tools";import{Command as i0,getCurrentTaskInput as c0}from"@langchain/langgraph";import{Command as n0}from"@langchain/langgraph";import{ChatOpenAI as UG}from"@langchain/openai";import{SystemMessage as BG,HumanMessage as JG,AIMessageChunk as LG,ToolMessage as KG}from"@langchain/core/messages";import{z as b}from"zod";import{withLangGraph as Z1}from"@langchain/langgraph/zod";import{MessagesZodMeta as v1}from"@langchain/langgraph";var T=b.object({messages:Z1(b.custom(),v1).default([])});import{AIMessage as h1,AIMessageChunk as _1,isAIMessage as D1}from"@langchain/core/messages";import{ChatGenerationChunk as n}from"@langchain/core/outputs";import{wrapOpenAIClientError as S1}from"@langchain/openai";import{convertToOpenAITool as jG,isLangChainTool as qG}from"@langchain/core/utils/function_calling";import{isInteropZodSchema as HG}from"@langchain/core/utils/types";import{toJsonSchema as OG}from"@langchain/core/utils/json_schema";function M(G){if(!G)return;else if(G==="any"||G==="required")return"required";else if(G==="auto")return"auto";else if(G==="none")return"none";else if(typeof G==="string")return{type:"function",function:{name:G}};else return G}import{BaseChatOpenAI as w1}from"@langchain/openai";import{AIMessage as d,AIMessageChunk as x1,ChatMessage as V1,ChatMessageChunk as Q1,FunctionMessageChunk as j1,HumanMessageChunk as q1,SystemMessageChunk as u,ToolMessage as p,ToolMessageChunk as $1,parseBase64DataUrl as k,parseMimeType as r,isDataContentBlock as H1,iife as P1,convertToProviderContentBlock as O1}from"@langchain/core/messages";import{convertLangChainToolCallToOpenAI as E1,makeInvalidToolCall as F1,parseToolCall as y1}from"@langchain/core/output_parsers/openai_tools";import{isZodSchemaV3 as yG,isZodSchemaV4 as zG}from"@langchain/core/utils/types";import{toJSONSchema as IG,parse as hG}from"zod/v4/core";import{zodResponseFormat as DG}from"openai/helpers/zod";function C(G,U){if(U&&typeof U==="object"&&"images"in U&&Array.isArray(U.images)){let W=U.images.filter((X)=>typeof X?.image_url?.url==="string").map((X)=>({type:"image",url:X.image_url.url}));return[{type:"text",text:G},...W]}return G}import{messageToOpenAIRole as i}from"@langchain/openai";var z1={providerName:"ChatOpenAI",fromStandardTextBlock(G){return{type:"text",text:G.text}},fromStandardImageBlock(G){if(G.source_type==="url")return{type:"image_url",image_url:{url:G.url,...G.metadata?.detail?{detail:G.metadata.detail}:{}}};if(G.source_type==="base64")return{type:"image_url",image_url:{url:`data:${G.mime_type??""};base64,${G.data}`,...G.metadata?.detail?{detail:G.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${G.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(G){if(G.source_type==="url"){let U=k({dataUrl:G.url});if(!U)throw Error(`URL audio blocks with source_type ${G.source_type} must be formatted as a data URL for ChatOpenAI`);let W=U.mime_type||G.mime_type||"",X;try{X=r(W)}catch{throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`)}if(X.type!=="audio"||X.subtype!=="wav"&&X.subtype!=="mp3")throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:X.subtype,data:U.data}}}if(G.source_type==="base64"){let U;try{U=r(G.mime_type??"")}catch{throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`)}if(U.type!=="audio"||U.subtype!=="wav"&&U.subtype!=="mp3")throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:U.subtype,data:G.data}}}throw Error(`Audio content blocks with source_type ${G.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(G){if(G.source_type==="url"){if(!k({dataUrl:G.url}))throw Error(`URL file blocks with source_type ${G.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:G.url,...G.metadata?.filename||G.metadata?.name?{filename:G.metadata?.filename||G.metadata?.name}:{}}}}if(G.source_type==="base64")return{type:"file",file:{file_data:`data:${G.mime_type??""};base64,${G.data}`,...G.metadata?.filename||G.metadata?.name||G.metadata?.title?{filename:G.metadata?.filename||G.metadata?.name||G.metadata?.title}:{}}};if(G.source_type==="id")return{type:"file",file:{file_id:G.id}};throw Error(`File content blocks with source_type ${G.source_type} are not supported for ChatOpenAI`)}},c=({message:G,rawResponse:U,includeRawResponse:W})=>{let X=G.tool_calls;switch(G.role){case"assistant":{let B=[],J=[];for(let Y of X??[])try{B.push(y1(Y,{returnId:!0}))}catch(Q){J.push(F1(Y,Q.message))}let L={function_call:G.function_call,tool_calls:X};if(W!==void 0)L.__raw_response=U;let K={model_provider:"openai",model_name:U.model,...U.system_fingerprint?{usage:{...U.usage},system_fingerprint:U.system_fingerprint}:{}};if(G.audio)L.audio=G.audio;let v=C(G.content||"",U.choices?.[0]?.message);return new d({content:v,tool_calls:B,invalid_tool_calls:J,additional_kwargs:L,response_metadata:K,id:U.id})}default:return new V1(G.content||"",G.role??"unknown")}},g=({delta:G,rawResponse:U,includeRawResponse:W,defaultRole:X})=>{let B=G.role??X,J=G.content??"",L;if(G.function_call)L={function_call:G.function_call};else if(G.tool_calls)L={tool_calls:G.tool_calls};else L={};if(W)L.__raw_response=U;if(G.audio)L.audio={...G.audio,index:U.choices[0].index};let K={model_provider:"openai",usage:{...U.usage}};if(B==="user")return new q1({content:J,response_metadata:K});else if(B==="assistant"){let v=[];if(Array.isArray(G.tool_calls))for(let Y of G.tool_calls)v.push({name:Y.function?.name,args:Y.function?.arguments,id:Y.id,index:Y.index,type:"tool_call_chunk"});return new x1({content:J,tool_call_chunks:v,additional_kwargs:L,id:U.id,response_metadata:K})}else if(B==="system")return new u({content:J,response_metadata:K});else if(B==="developer")return new u({content:J,response_metadata:K,additional_kwargs:{__openai_role__:"developer"}});else if(B==="function")return new j1({content:J,additional_kwargs:L,name:G.name,response_metadata:K});else if(B==="tool")return new $1({content:J,additional_kwargs:L,tool_call_id:G.tool_call_id,response_metadata:K});else return new Q1({content:J,role:B,response_metadata:K})},R1=(G)=>{if(G.type==="image"){if(G.url)return{type:"image_url",image_url:{url:G.url}};else if(G.data)return{type:"image_url",image_url:{url:`data:${G.mimeType};base64,${G.data}`}}}if(G.type==="audio"){if(G.data){let U=P1(()=>{let[,W]=G.mimeType.split("/");if(W==="wav"||W==="mp3")return W;return"wav"});return{type:"input_audio",input_audio:{data:G.data.toString(),format:U}}}}if(G.type==="file"){if(G.data)return{type:"file",file:{file_data:G.data.toString()}};if(G.fileId)return{type:"file",file:{file_id:G.fileId}}}return};function m(G){if(!G)return!1;if(/^o\d/.test(G??""))return!0;if(G.startsWith("gpt-5")&&!G.startsWith("gpt-5-chat"))return!0;return!1}var I1=({message:G,model:U})=>{let W=i(G);if(W==="system"&&m(U))W="developer";if(W==="developer")return{role:"developer",content:G.contentBlocks.filter((B)=>B.type==="text")};else if(W==="system")return{role:"system",content:G.contentBlocks.filter((B)=>B.type==="text")};else if(W==="assistant")return{role:"assistant",content:G.contentBlocks.filter((B)=>B.type==="text")};else if(W==="tool"&&p.isInstance(G))return{role:"tool",tool_call_id:G.tool_call_id,content:G.contentBlocks.filter((B)=>B.type==="text")};else if(W==="function")return{role:"function",name:G.name??"",content:G.contentBlocks.filter((B)=>B.type==="text").join("")};function*X(B){for(let J of B){if(J.type==="text")yield{type:"text",text:J.text};let L=R1(J);if(L)yield L}}return{role:"user",content:Array.from(X(G.contentBlocks))}},D=({messages:G,model:U})=>{return G.flatMap((W)=>{if("output_version"in W.response_metadata&&W.response_metadata?.output_version==="v1")return I1({message:W});let X=i(W);if(X==="system"&&m(U))X="developer";let B=typeof W.content==="string"?W.content:W.content.map((L)=>{if(H1(L))return O1(L,z1);return L}),J={role:X,content:B};if(W.name!=null)J.name=W.name;if(W.additional_kwargs.function_call!=null)J.function_call=W.additional_kwargs.function_call,J.content="";if(W.additional_kwargs?.reasoning_content&&U?.includes("deepseek"))J.reasoning_content=W.additional_kwargs.reasoning_content;if(d.isInstance(W)&&!!W.tool_calls?.length)J.tool_calls=W.tool_calls.map(E1),J.content="";else{if(W.additional_kwargs.tool_calls!=null)J.tool_calls=W.additional_kwargs.tool_calls;if(p.isInstance(W)&&W.tool_call_id!=null)J.tool_call_id=W.tool_call_id}if(W.additional_kwargs.audio&&typeof W.additional_kwargs.audio==="object"&&"id"in W.additional_kwargs.audio){let L={role:"assistant",audio:{id:W.additional_kwargs.audio.id}};return[J,L]}return J})};class R extends w1{invocationParams(G,U){let W;if(G?.strict!==void 0)W=G.strict;else if(this.supportsStrictToolCalling!==void 0)W=this.supportsStrictToolCalling;let X={};if(G?.stream_options!==void 0)X={stream_options:G.stream_options};else if(this.streamUsage&&(this.streaming||U?.streaming))X={stream_options:{include_usage:!0}};let B={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:G?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:G?.functions,function_call:G?.function_call,tools:G?.tools?.length?G.tools.map((L)=>this._convertChatOpenAIToolToCompletionsTool(L,{strict:W})):void 0,tool_choice:M(G?.tool_choice),response_format:this._getResponseFormat(G?.response_format),seed:G?.seed,...X,parallel_tool_calls:G?.parallel_tool_calls,...this.audio||G?.audio?{audio:this.audio||G?.audio}:{},...this.modalities||G?.modalities?{modalities:this.modalities||G?.modalities}:{},...this.modelKwargs,prompt_cache_key:G?.promptCacheKey??this.promptCacheKey,verbosity:G?.verbosity??this.verbosity};if(G?.prediction!==void 0)B.prediction=G.prediction;if(this.service_tier!==void 0)B.service_tier=this.service_tier;if(G?.service_tier!==void 0)B.service_tier=G.service_tier;let J=this._getReasoningParams(G);if(J!==void 0&&J.effort!==void 0)B.reasoning_effort=J.effort;if(this.reasoning)B.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens;else B.max_tokens=this.maxTokens===-1?void 0:this.maxTokens;return B}async _generate(G,U,W){let X={},B=this.invocationParams(U),J=D({messages:G,model:this.model});if(B.stream){let L=this._streamResponseChunks(G,U,W),K={};for await(let Z of L){Z.message.response_metadata={...Z.generationInfo,...Z.message.response_metadata};let V=Z.generationInfo?.completion??0;if(K[V]===void 0)K[V]=Z;else K[V]=K[V].concat(Z)}let v=Object.entries(K).sort(([Z],[V])=>parseInt(Z,10)-parseInt(V,10)).map(([Z,V])=>V),{functions:Y,function_call:Q}=this.invocationParams(U),x=await this._getEstimatedTokenCountFromPrompt(G,Y,Q),H=await this._getNumTokensFromGenerations(v);return X.input_tokens=x,X.output_tokens=H,X.total_tokens=x+H,{generations:v,llmOutput:{estimatedTokenUsage:{promptTokens:X.input_tokens,completionTokens:X.output_tokens,totalTokens:X.total_tokens}}}}else{let L=await this.completionWithRetry({...B,stream:!1,messages:J},{signal:U?.signal,...U?.options}),{completion_tokens:K,prompt_tokens:v,total_tokens:Y,prompt_tokens_details:Q,completion_tokens_details:x}=L?.usage??{};if(K)X.output_tokens=(X.output_tokens??0)+K;if(v)X.input_tokens=(X.input_tokens??0)+v;if(Y)X.total_tokens=(X.total_tokens??0)+Y;if(Q?.audio_tokens!==null||Q?.cached_tokens!==null)X.input_token_details={...Q?.audio_tokens!==null&&{audio:Q?.audio_tokens},...Q?.cached_tokens!==null&&{cache_read:Q?.cached_tokens}};if(x?.audio_tokens!==null||x?.reasoning_tokens!==null)X.output_token_details={...x?.audio_tokens!==null&&{audio:x?.audio_tokens},...x?.reasoning_tokens!==null&&{reasoning:x?.reasoning_tokens}};let H=[];for(let Z of L?.choices??[]){let V=Z.message?.content??"",F=Z.message?.reasoning_content??Z.message?.reasoning??"",j={text:V,message:this._convertCompletionsMessageToBaseMessage(Z.message??{role:"assistant"},L)};if(j.message.additional_kwargs={...j.message.additional_kwargs,reasoning_content:F},j.generationInfo={...Z.finish_reason?{finish_reason:Z.finish_reason}:{},...Z.logprobs?{logprobs:Z.logprobs}:{}},D1(j.message))j.message.usage_metadata=X;j.message=new h1(Object.fromEntries(Object.entries(j.message).filter(([y])=>!y.startsWith("lc_")))),H.push(j)}return{generations:H,llmOutput:{tokenUsage:{promptTokens:X.input_tokens,completionTokens:X.output_tokens,totalTokens:X.total_tokens}}}}}async*_streamResponseChunks(G,U,W){let X=D({messages:G,model:this.model}),B={...this.invocationParams(U,{streaming:!0}),messages:X,stream:!0},J,L=await this.completionWithRetry(B,U),K;for await(let v of L){let Y=v?.choices?.[0];if(v.usage)K=v.usage;if(!Y)continue;let{delta:Q}=Y;if(!Q)continue;let x=this._convertCompletionsDeltaToBaseMessageChunk(Q,v,J),H=Q.reasoning_content??Q.reasoning??"";if(H)x.additional_kwargs={...x.additional_kwargs,reasoning_content:H};J=Q.role??J;let Z={prompt:U.promptIndex??0,completion:Y.index??0};if(typeof x.content!=="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let V={...Z};if(Y.finish_reason!=null)V.finish_reason=Y.finish_reason,V.system_fingerprint=v.system_fingerprint,V.model_name=v.model,V.service_tier=v.service_tier;if(this.logprobs)V.logprobs=Y.logprobs;let F=new n({message:x,text:x.content,generationInfo:V});yield F,await W?.handleLLMNewToken(F.text??"",Z,void 0,void 0,void 0,{chunk:F})}if(K){let v={...K.prompt_tokens_details?.audio_tokens!==null&&{audio:K.prompt_tokens_details?.audio_tokens},...K.prompt_tokens_details?.cached_tokens!==null&&{cache_read:K.prompt_tokens_details?.cached_tokens}},Y={...K.completion_tokens_details?.audio_tokens!==null&&{audio:K.completion_tokens_details?.audio_tokens},...K.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:K.completion_tokens_details?.reasoning_tokens}};yield new n({message:new _1({content:"",response_metadata:{usage:{...K}},usage_metadata:{input_tokens:K.prompt_tokens,output_tokens:K.completion_tokens,total_tokens:K.total_tokens,...Object.keys(v).length>0&&{input_token_details:v},...Object.keys(Y).length>0&&{output_token_details:Y}}}),text:""})}if(U.signal?.aborted)throw Error("AbortError")}async completionWithRetry(G,U){let W=this._getClientOptions(U),X=G.response_format&&G.response_format.type==="json_schema";return this.caller.call(async()=>{try{if(X&&!G.stream)return await this.client.chat.completions.parse(G,W);else return await this.client.chat.completions.create(G,W)}catch(B){throw S1(B)}})}_convertCompletionsDeltaToBaseMessageChunk(G,U,W){return g({delta:G,rawResponse:U,includeRawResponse:this.__includeRawResponse,defaultRole:W})}_convertCompletionsMessageToBaseMessage(G,U){return c({message:G,rawResponse:U,includeRawResponse:this.__includeRawResponse})}}import{createMiddleware as cG}from"langchain";import{z as O}from"zod";import{MessagesAnnotation as f1}from"@langchain/langgraph";import{SubAgentAnnotation as N1,SubAgentStateSchema as A1}from"@langgraph-js/standard-agent";var YU=T.extend(A1.shape).extend({provider_id:O.string().default("default"),provider_type:O.string().default("openai"),model_id:O.string().default("qwen-plus"),agent_name:O.string().default("Code Agent"),switch_command:O.string().optional(),enable_thinking:O.boolean().default(!0),user_id:O.string().optional(),thread_id:O.string().optional(),cwd:O.string().default(process.cwd())}),l=_(N1,f1).build({provider_id:q(()=>"default"),provider_type:q(()=>"openai"),model_id:q(()=>"qwen-plus"),agent_name:q(()=>"Code Agent"),switch_command:q(()=>null),enable_thinking:q(()=>!0),user_id:q(()=>""),thread_id:q(()=>""),cwd:q(()=>process.cwd())});import{ChatAnthropic as b1}from"@langchain/anthropic";import{ChatGoogleGenerativeAI as T1}from"@langchain/google-genai";var t=async(G,U={})=>{let{modelProvider:W,enableThinking:X=!0}=U,B="v1",J;if(W==="anthropic")J=new b1({model:G,streamUsage:!0,streaming:!0,maxRetries:1,maxTokens:64000,thinking:X?{budget_tokens:1024,type:"enabled"}:void 0,apiKey:U.apiKey,anthropicApiUrl:U.baseURL,metadata:U.metadata,outputVersion:"v1"});else if(W==="gemini"||W==="google")J=new T1({model:G,apiKey:U.apiKey,baseUrl:U.baseURL||process.env.GOOGLE_BASE_URL,maxRetries:1,streaming:!0,streamUsage:!0,thinkingConfig:{},metadata:U.metadata,outputVersion:"v1"});else J=new R({model:G,configuration:{baseURL:U.baseURL,apiKey:U.apiKey},streamUsage:!0,maxRetries:1,modelKwargs:X?{thinking:{type:"enabled"}}:void 0,metadata:U.metadata,outputVersion:"v1"});return J};import{createAgent as C1,tool as u1}from"langchain";import{anthropicPromptCachingMiddleware as k1}from"@langgraph-js/standard-agent";import{MCPMiddleware as M1}from"@langgraph-js/standard-agent";class h extends M1{constructor(G){super({configProvider:async()=>h.loadConfigFromStore(),cache:G})}static async loadConfigFromStore(){try{let G=new s;await G.initialize();let U=await G.getConfig();if(!U.mcp_config||Object.keys(U.mcp_config).length===0)return null;return{servers:U.mcp_config}}catch(G){return console.error("Failed to load MCP config from store:",G),null}}}import{humanInTheLoopMiddleware as r1}from"@langgraph-js/standard-agent";var d1={ask_user_questions:{allowedDecisions:["respond","approve","reject","edit"]}};async function fU(G,U,W,X,B){let J=!!B?.parent_id,L=await U.getAgent(G);if(!L)throw Error(`Agent not found: ${G}`);let K=await U.validateAgent(G);if(!K.valid)throw Error(`Agent validation failed: ${JSON.stringify(K.errors)}`);let v=await t(W.model_id,{modelProvider:W.provider_type,streamUsage:!0,enableThinking:W.enable_thinking,metadata:{parent_id:B?.parent_id}}),Y=[],Q=U.tools;for(let[j,y]of Object.entries(L.tools)){let E=Q.getImplementation(j);if(!E){console.warn(`Tool ${j} not found in registry`);continue}if(!E.name||!y)continue;let o=u1(async(e,G1)=>{let z=await E.execute(e,G1);if(z&&typeof z==="object"&&"content"in z)return z.content;return z},{name:E.name,description:E.description,schema:E.paramsSchema});Y.push(o)}let x=[];for(let[j,y]of Object.entries(L.middleware)){if(j==="subagents"&&J)continue;let E=U.middlewares.getImplementation(j);if(!y)continue;x.push(await E.execute(y.customParams||{}))}let H=new h;x.push(H);let Z={...d1};if(process.env.YOLO_MODE!=="true")Object.assign(Z,{terminal:{allowedDecisions:["approve","reject","edit"]}});if(x.push(r1({interruptOn:Z})),process.env.MODEL_PROVIDER==="anthropic")x.push(k1());let V=await U.getPromptWithContent(L.systemPromptId);if(!V)throw Error(`Prompt not found: ${L.systemPromptId}`);let F=V.content+`
|
|
24
|
-
|
|
25
|
-
${await a(W)}`;return C1({name:J?`subagent_${B.parent_id}`:L.name,model:v,systemPrompt:F,tools:Y,stateSchema:l,middleware:x})}async function NU(G){return(await G.listAgents()).map((W)=>W.id)}
|
|
26
|
-
export{Q0 as Ma,YU as Na,l as Oa,t as Pa,fU as Qa,NU as Ra};
|
package/dist/chunk-zz32kgt2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{N as M}from"./chunk-hfve7nf5.js";import"./chunk-va71tsw3.js";import{ea as T,ga as G,ja as Z,pa as Y,ra as _,ta as $}from"./chunk-nwy6n6b6.js";import{wa as L}from"./chunk-mmq834zt.js";import{Ea as w}from"./chunk-1y82m5kn.js";import"./chunk-5x8nxw0t.js";import"./chunk-13nyfrmm.js";import"./chunk-5rr85f28.js";import"./chunk-cggjws6a.js";import"./chunk-cyexd09c.js";import"./chunk-r2h3x9zv.js";import"./chunk-1ttywx0y.js";import{ub as K}from"./chunk-kba8akjs.js";var z=K(T(),1);var y=K(Y(),1),h=({onClose:H})=>{let{config:U,updateConfig:N}=M(),B=U?.switch_command||"default",O=z.useCallback(async()=>{let q=await L(w);return Object.values(q)},[]),Q=z.useCallback((q,F,J)=>{let P=q.id===B;return y.jsxDEV(_,{isSelected:J,isCurrent:P,children:[y.jsxDEV(G,{bold:!0,children:[F+1,". ",q.id]},void 0,!0,void 0,this),y.jsxDEV(Z,{},void 0,!1,void 0,this),y.jsxDEV(G,{dimColor:!0,children:q.description},void 0,!1,void 0,this)]},`agent-${q.id}`,!0,void 0,this)},[B]),R=z.useCallback((q)=>{return q.id===B},[B]),W=z.useCallback(async(q)=>{let F=q.id==="default"?"":q.id;N({switch_command:F}),H()},[N,H]),X=z.useCallback((q)=>{let F=q.find((J)=>J.id===B);return F?y.jsxDEV(G,{color:"gray",dimColor:!0,children:["当前 Agent: ",y.jsxDEV(G,{color:"green",children:F.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this):null},[B]),v=z.useMemo(()=>({id:"agent",title:"Agent 选择",icon:"\uD83E\uDD16",dataSource:O,searchable:!0,searchFields:["id","name","description"],searchPlaceholder:"搜索 agent (名称/描述)...",filterable:!0,filters:[{id:"default",label:"默认",predicate:(q)=>q.id==="default"},{id:"custom",label:"自定义",predicate:(q)=>q.id!=="default"}],defaultFilter:"all",itemHeight:3,visibleCount:15,renderItem:Q,isSelected:R,onSelect:W,showCount:!0,statusInfo:X}),[O,Q,R,W,X]);return y.jsxDEV($,{config:v,onClose:H},void 0,!1,void 0,this)},m=h;export{m as default};
|