@uncarved/jade 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +187 -2
- package/bin/jade.js +20 -0
- package/dist/commands.d.ts +30 -0
- package/dist/commands.js +106 -0
- package/dist/commands.js.map +1 -0
- package/dist/config.d.ts +34 -0
- package/dist/config.js +130 -0
- package/dist/config.js.map +1 -0
- package/dist/context.d.ts +17 -0
- package/dist/context.js +53 -0
- package/dist/context.js.map +1 -0
- package/dist/distro.d.ts +93 -0
- package/dist/distro.js +277 -0
- package/dist/distro.js.map +1 -0
- package/dist/history.d.ts +10 -0
- package/dist/history.js +47 -0
- package/dist/history.js.map +1 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +1124 -0
- package/dist/main.js.map +1 -0
- package/dist/mcp.d.ts +114 -0
- package/dist/mcp.js +640 -0
- package/dist/mcp.js.map +1 -0
- package/dist/memory.d.ts +19 -0
- package/dist/memory.js +129 -0
- package/dist/memory.js.map +1 -0
- package/dist/mentions.d.ts +35 -0
- package/dist/mentions.js +130 -0
- package/dist/mentions.js.map +1 -0
- package/dist/plugin-cli.d.ts +16 -0
- package/dist/plugin-cli.js +251 -0
- package/dist/plugin-cli.js.map +1 -0
- package/dist/plugins/budget.d.ts +9 -0
- package/dist/plugins/budget.js +30 -0
- package/dist/plugins/budget.js.map +1 -0
- package/dist/plugins/builtins.d.ts +10 -0
- package/dist/plugins/builtins.js +22 -0
- package/dist/plugins/builtins.js.map +1 -0
- package/dist/plugins/checks.d.ts +70 -0
- package/dist/plugins/checks.js +335 -0
- package/dist/plugins/checks.js.map +1 -0
- package/dist/plugins/compact.d.ts +26 -0
- package/dist/plugins/compact.js +216 -0
- package/dist/plugins/compact.js.map +1 -0
- package/dist/plugins/core.d.ts +42 -0
- package/dist/plugins/core.js +190 -0
- package/dist/plugins/core.js.map +1 -0
- package/dist/plugins/install.d.ts +68 -0
- package/dist/plugins/install.js +377 -0
- package/dist/plugins/install.js.map +1 -0
- package/dist/plugins/loader.d.ts +182 -0
- package/dist/plugins/loader.js +253 -0
- package/dist/plugins/loader.js.map +1 -0
- package/dist/plugins/policy.d.ts +64 -0
- package/dist/plugins/policy.js +269 -0
- package/dist/plugins/policy.js.map +1 -0
- package/dist/plugins/prompts.d.ts +28 -0
- package/dist/plugins/prompts.js +169 -0
- package/dist/plugins/prompts.js.map +1 -0
- package/dist/plugins/repeats.d.ts +9 -0
- package/dist/plugins/repeats.js +55 -0
- package/dist/plugins/repeats.js.map +1 -0
- package/dist/plugins/schema.d.ts +2 -0
- package/dist/plugins/schema.js +64 -0
- package/dist/plugins/schema.js.map +1 -0
- package/dist/provider.d.ts +52 -0
- package/dist/provider.js +187 -0
- package/dist/provider.js.map +1 -0
- package/dist/sessions.d.ts +13 -0
- package/dist/sessions.js +40 -0
- package/dist/sessions.js.map +1 -0
- package/dist/skills.d.ts +37 -0
- package/dist/skills.js +179 -0
- package/dist/skills.js.map +1 -0
- package/dist/sys.d.ts +44 -0
- package/dist/sys.js +115 -0
- package/dist/sys.js.map +1 -0
- package/dist/tools/checkpoint.d.ts +43 -0
- package/dist/tools/checkpoint.js +144 -0
- package/dist/tools/checkpoint.js.map +1 -0
- package/dist/tools/fs.d.ts +35 -0
- package/dist/tools/fs.js +417 -0
- package/dist/tools/fs.js.map +1 -0
- package/dist/tools/grep.d.ts +6 -0
- package/dist/tools/grep.js +243 -0
- package/dist/tools/grep.js.map +1 -0
- package/dist/tools/shell.d.ts +49 -0
- package/dist/tools/shell.js +295 -0
- package/dist/tools/shell.js.map +1 -0
- package/dist/tools/task.d.ts +31 -0
- package/dist/tools/task.js +86 -0
- package/dist/tools/task.js.map +1 -0
- package/dist/tools/todo.d.ts +10 -0
- package/dist/tools/todo.js +55 -0
- package/dist/tools/todo.js.map +1 -0
- package/dist/tools/web.d.ts +23 -0
- package/dist/tools/web.js +426 -0
- package/dist/tools/web.js.map +1 -0
- package/dist/ui/configure.d.ts +20 -0
- package/dist/ui/configure.js +285 -0
- package/dist/ui/configure.js.map +1 -0
- package/dist/ui/diff.d.ts +20 -0
- package/dist/ui/diff.js +142 -0
- package/dist/ui/diff.js.map +1 -0
- package/dist/ui/editor.d.ts +33 -0
- package/dist/ui/editor.js +128 -0
- package/dist/ui/editor.js.map +1 -0
- package/dist/ui/render.d.ts +13 -0
- package/dist/ui/render.js +84 -0
- package/dist/ui/render.js.map +1 -0
- package/dist/ui/screen.d.ts +90 -0
- package/dist/ui/screen.js +105 -0
- package/dist/ui/screen.js.map +1 -0
- package/dist/ui/transcript.d.ts +33 -0
- package/dist/ui/transcript.js +336 -0
- package/dist/ui/transcript.js.map +1 -0
- package/dist/ui/tui.d.ts +28 -0
- package/dist/ui/tui.js +884 -0
- package/dist/ui/tui.js.map +1 -0
- package/package.json +59 -4
- package/src/commands.ts +120 -0
- package/src/config.ts +146 -0
- package/src/context.ts +64 -0
- package/src/distro.ts +358 -0
- package/src/history.ts +55 -0
- package/src/index.ts +26 -0
- package/src/main.ts +1180 -0
- package/src/mcp.ts +693 -0
- package/src/memory.ts +135 -0
- package/src/mentions.ts +135 -0
- package/src/plugin-cli.ts +239 -0
- package/src/plugins/budget.ts +37 -0
- package/src/plugins/builtins.ts +31 -0
- package/src/plugins/checks.ts +390 -0
- package/src/plugins/compact.ts +257 -0
- package/src/plugins/core.ts +217 -0
- package/src/plugins/install.ts +429 -0
- package/src/plugins/loader.ts +386 -0
- package/src/plugins/policy.ts +304 -0
- package/src/plugins/prompts.ts +200 -0
- package/src/plugins/repeats.ts +62 -0
- package/src/plugins/schema.ts +67 -0
- package/src/provider.ts +208 -0
- package/src/sessions.ts +48 -0
- package/src/skills.ts +197 -0
- package/src/sys.ts +133 -0
- package/src/tools/checkpoint.ts +164 -0
- package/src/tools/fs.ts +432 -0
- package/src/tools/grep.ts +268 -0
- package/src/tools/shell.ts +339 -0
- package/src/tools/task.ts +105 -0
- package/src/tools/todo.ts +67 -0
- package/src/tools/web.ts +451 -0
- package/src/ui/configure.ts +310 -0
- package/src/ui/diff.ts +136 -0
- package/src/ui/editor.ts +136 -0
- package/src/ui/render.ts +74 -0
- package/src/ui/screen.ts +164 -0
- package/src/ui/transcript.ts +345 -0
- package/src/ui/tui.tsx +1374 -0
package/src/provider.ts
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// Provider:按环境变量选择,外面包一层重试(4.7:重试是包装 Provider 的事)。
|
|
2
|
+
|
|
3
|
+
import { ProviderError, type Provider } from "uncarved";
|
|
4
|
+
import { parseTokens } from "./config.ts";
|
|
5
|
+
|
|
6
|
+
export interface RetryOptions {
|
|
7
|
+
/** 最多重试几次,默认 4 */
|
|
8
|
+
retries?: number;
|
|
9
|
+
/** 首次等待,之后每次翻倍,默认 1000ms;上游给了 retryAfterMs 时以它为准 */
|
|
10
|
+
baseDelayMs?: number;
|
|
11
|
+
maxDelayMs?: number;
|
|
12
|
+
/** 退避时间的随机数,默认 Math.random;测试用 */
|
|
13
|
+
random?: () => number;
|
|
14
|
+
/** 每次重试前通知宿主(显示用) */
|
|
15
|
+
onRetry?: (info: { attempt: number; delayMs: number; error: ProviderError }) => void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function withRetry(inner: Provider, opts: RetryOptions = {}): Provider {
|
|
19
|
+
const retries = opts.retries ?? 4;
|
|
20
|
+
const base = opts.baseDelayMs ?? 1000;
|
|
21
|
+
const max = opts.maxDelayMs ?? 60_000;
|
|
22
|
+
const random = opts.random ?? Math.random;
|
|
23
|
+
return {
|
|
24
|
+
id: `retry(${inner.id})`,
|
|
25
|
+
async complete(request, options) {
|
|
26
|
+
for (let attempt = 1; ; attempt++) {
|
|
27
|
+
let streamed = false;
|
|
28
|
+
try {
|
|
29
|
+
const res = await inner.complete(request, {
|
|
30
|
+
...options,
|
|
31
|
+
onDelta: (d) => {
|
|
32
|
+
streamed = true;
|
|
33
|
+
options.onDelta?.(d);
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
// 实际回复的是被包装者(4.7 第 3 款)
|
|
37
|
+
return { ...res, provider: res.provider ?? inner.id };
|
|
38
|
+
} catch (err) {
|
|
39
|
+
if (!(err instanceof ProviderError) || !err.retryable || attempt > retries || options.signal.aborted) throw err;
|
|
40
|
+
// 没有 retryAfterMs 时随机取后一半,并行的子 Agent 同时遇到 429 时不会同时重试
|
|
41
|
+
const delayMs = Math.min(err.retryAfterMs ?? base * 2 ** (attempt - 1) * (0.5 + 0.5 * random()), max);
|
|
42
|
+
// 失败的这次已经推送过增量的,先让订阅者作废它们(4.7)
|
|
43
|
+
if (streamed) options.onDelta?.({ kind: "reset" });
|
|
44
|
+
opts.onRetry?.({ attempt, delayMs, error: err });
|
|
45
|
+
await sleep(delayMs, options.signal);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
const done = () => {
|
|
55
|
+
signal.removeEventListener("abort", stop);
|
|
56
|
+
resolve();
|
|
57
|
+
};
|
|
58
|
+
const timer = setTimeout(done, ms);
|
|
59
|
+
const stop = () => {
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
reject(signal.reason);
|
|
62
|
+
};
|
|
63
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type ProviderKind = "openai-compat" | "openai" | "anthropic";
|
|
68
|
+
export const PROVIDER_KINDS: readonly ProviderKind[] = ["openai-compat", "openai", "anthropic"];
|
|
69
|
+
|
|
70
|
+
type Env = Record<string, string | undefined>;
|
|
71
|
+
|
|
72
|
+
/** JADE_EFFORT 可取的值;openai-compat 没有统一的字段,用 OPENAI_COMPAT_EXTRA_BODY 自己设 */
|
|
73
|
+
export const EFFORTS: Record<ProviderKind, readonly string[] | undefined> = {
|
|
74
|
+
anthropic: ["low", "medium", "high", "xhigh", "max"],
|
|
75
|
+
openai: ["minimal", "low", "medium", "high"],
|
|
76
|
+
"openai-compat": undefined,
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** JADE_EFFORT;不设时 Claude 用 high,OpenAI 用服务端默认值 */
|
|
80
|
+
export function effortFromEnv(env: Env = process.env): string | undefined {
|
|
81
|
+
const effort = env.JADE_EFFORT;
|
|
82
|
+
if (!effort) return undefined;
|
|
83
|
+
const kind = providerKind(env);
|
|
84
|
+
const allowed = EFFORTS[kind];
|
|
85
|
+
if (!allowed) throw new Error(`JADE_EFFORT is not supported for the ${kind} provider; set it in OPENAI_COMPAT_EXTRA_BODY instead`);
|
|
86
|
+
if (!allowed.includes(effort)) throw new Error(`JADE_EFFORT must be one of ${allowed.join(", ")} for the ${kind} provider, got ${JSON.stringify(effort)}`);
|
|
87
|
+
return effort;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** JADE_PROVIDER 指定时用它;否则按 OPENAI_API_KEY、OPENAI_COMPAT_BASE_URL、ANTHROPIC_API_KEY 的顺序 */
|
|
91
|
+
export function providerKind(env: Env = process.env): ProviderKind {
|
|
92
|
+
const named = env.JADE_PROVIDER;
|
|
93
|
+
if (named) {
|
|
94
|
+
if (!(PROVIDER_KINDS as readonly string[]).includes(named)) {
|
|
95
|
+
throw new Error(`JADE_PROVIDER must be one of ${PROVIDER_KINDS.join(", ")}, got ${JSON.stringify(named)}`);
|
|
96
|
+
}
|
|
97
|
+
return named as ProviderKind;
|
|
98
|
+
}
|
|
99
|
+
if (env.OPENAI_API_KEY) return "openai";
|
|
100
|
+
if (env.OPENAI_COMPAT_BASE_URL) return "openai-compat";
|
|
101
|
+
return "anthropic";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface ProviderInfo {
|
|
105
|
+
kind: ProviderKind;
|
|
106
|
+
model: string;
|
|
107
|
+
baseURL?: string;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 当前配置会用哪个服务、哪个模型(状态栏和 /model 显示用) */
|
|
111
|
+
export function providerInfo(env: Env = process.env): ProviderInfo {
|
|
112
|
+
const kind = providerKind(env);
|
|
113
|
+
if (kind === "openai") return { kind, model: env.OPENAI_MODEL ?? "gpt-5", baseURL: env.OPENAI_BASE_URL ?? "https://api.openai.com/v1" };
|
|
114
|
+
if (kind === "openai-compat") return { kind, model: env.OPENAI_COMPAT_MODEL ?? "", baseURL: env.OPENAI_COMPAT_BASE_URL };
|
|
115
|
+
return { kind, model: env.ANTHROPIC_MODEL ?? "claude-opus-5-5", baseURL: env.ANTHROPIC_BASE_URL };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 按环境变量创建,服务由 providerKind 决定:
|
|
120
|
+
* - openai:OpenAI Responses API,OPENAI_API_KEY,可选 OPENAI_BASE_URL、OPENAI_MODEL
|
|
121
|
+
* - openai-compat:兼容 /chat/completions 的服务,OPENAI_COMPAT_BASE_URL + OPENAI_COMPAT_MODEL(+ OPENAI_COMPAT_API_KEY),
|
|
122
|
+
* 可选 OPENAI_COMPAT_EXTRA_BODY(JSON 对象,合并进每次请求体,例如开启思考的 {"enable_thinking":true})
|
|
123
|
+
* - anthropic:Claude,ANTHROPIC_API_KEY,可选 ANTHROPIC_MODEL
|
|
124
|
+
* JADE_MAX_TOKENS 是每次回复的输出上限。不设时 Claude 用 64000,其他服务用服务端默认值(有的只有 4096,思考很容易用完)
|
|
125
|
+
* JADE_EFFORT 是思考的力度,见 effortFromEnv
|
|
126
|
+
* 只导入用到的那个服务的包:Anthropic 的 SDK 加载要一百多毫秒,拖慢启动
|
|
127
|
+
*/
|
|
128
|
+
export async function providerFromEnv(env: Env = process.env): Promise<Provider> {
|
|
129
|
+
const kind = providerKind(env);
|
|
130
|
+
const maxTokens = env.JADE_MAX_TOKENS ? parseTokens("JADE_MAX_TOKENS", env.JADE_MAX_TOKENS) : undefined;
|
|
131
|
+
const effort = effortFromEnv(env);
|
|
132
|
+
if (kind === "openai") {
|
|
133
|
+
if (!env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is required for the openai provider");
|
|
134
|
+
const { openaiResponsesProvider } = await import("@uncarved/provider-openai-responses");
|
|
135
|
+
return openaiResponsesProvider({
|
|
136
|
+
baseURL: env.OPENAI_BASE_URL ?? "https://api.openai.com/v1",
|
|
137
|
+
apiKey: env.OPENAI_API_KEY,
|
|
138
|
+
model: env.OPENAI_MODEL ?? "gpt-5",
|
|
139
|
+
maxTokens,
|
|
140
|
+
reasoning: effort ? { effort: effort as "minimal" | "low" | "medium" | "high" } : undefined,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (kind === "openai-compat") {
|
|
144
|
+
if (!env.OPENAI_COMPAT_BASE_URL) throw new Error("OPENAI_COMPAT_BASE_URL is required for the openai-compat provider");
|
|
145
|
+
if (!env.OPENAI_COMPAT_MODEL) throw new Error("OPENAI_COMPAT_MODEL is required when OPENAI_COMPAT_BASE_URL is set");
|
|
146
|
+
const { openaiCompatProvider } = await import("@uncarved/provider-openai-compat");
|
|
147
|
+
return openaiCompatProvider({
|
|
148
|
+
baseURL: env.OPENAI_COMPAT_BASE_URL,
|
|
149
|
+
apiKey: env.OPENAI_COMPAT_API_KEY,
|
|
150
|
+
model: env.OPENAI_COMPAT_MODEL,
|
|
151
|
+
maxTokens,
|
|
152
|
+
extraBody: env.OPENAI_COMPAT_EXTRA_BODY ? jsonObject("OPENAI_COMPAT_EXTRA_BODY", env.OPENAI_COMPAT_EXTRA_BODY) : undefined,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
const { anthropicProvider } = await import("@uncarved/provider-anthropic");
|
|
156
|
+
return anthropicProvider({ model: env.ANTHROPIC_MODEL, effort: (effort ?? "high") as "low" | "medium" | "high" | "xhigh" | "max", maxTokens });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 可以在会话中途换掉的 provider:/model 改配置后,压缩、子 Agent 等持有它的地方都跟着换 */
|
|
160
|
+
export interface SwitchableProvider extends Provider {
|
|
161
|
+
set(next: Provider): void;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function switchable(initial: Provider): SwitchableProvider {
|
|
165
|
+
let current = initial;
|
|
166
|
+
return {
|
|
167
|
+
id: "switchable",
|
|
168
|
+
set: (next) => {
|
|
169
|
+
current = next;
|
|
170
|
+
},
|
|
171
|
+
complete: (request, options) => current.complete(request, options),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** 服务提供的模型列表;不支持或出错时返回空数组 */
|
|
176
|
+
export async function listModels(env: Env = process.env, fetchImpl: typeof fetch = fetch): Promise<string[]> {
|
|
177
|
+
const kind = providerKind(env);
|
|
178
|
+
const info = providerInfo(env);
|
|
179
|
+
const base = (info.baseURL ?? "https://api.anthropic.com").replace(/\/$/, "");
|
|
180
|
+
const headers: Record<string, string> =
|
|
181
|
+
kind === "anthropic"
|
|
182
|
+
? { "x-api-key": env.ANTHROPIC_API_KEY ?? "", "anthropic-version": "2023-06-01" }
|
|
183
|
+
: (kind === "openai" ? env.OPENAI_API_KEY : env.OPENAI_COMPAT_API_KEY)
|
|
184
|
+
? { authorization: `Bearer ${kind === "openai" ? env.OPENAI_API_KEY : env.OPENAI_COMPAT_API_KEY}` }
|
|
185
|
+
: {};
|
|
186
|
+
try {
|
|
187
|
+
const res = await fetchImpl(kind === "anthropic" ? `${base}/v1/models?limit=100` : `${base}/models`, {
|
|
188
|
+
headers,
|
|
189
|
+
signal: AbortSignal.timeout(10_000),
|
|
190
|
+
});
|
|
191
|
+
if (!res.ok) return [];
|
|
192
|
+
const body = (await res.json()) as { data?: Array<{ id?: unknown }> };
|
|
193
|
+
return (body.data ?? []).flatMap((m) => (typeof m.id === "string" ? [m.id] : []));
|
|
194
|
+
} catch {
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function jsonObject(name: string, text: string): Record<string, unknown> {
|
|
200
|
+
let value: unknown;
|
|
201
|
+
try {
|
|
202
|
+
value = JSON.parse(text);
|
|
203
|
+
} catch {
|
|
204
|
+
throw new Error(`${name} must be a JSON object, got ${JSON.stringify(text)}`);
|
|
205
|
+
}
|
|
206
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${name} must be a JSON object, got ${text}`);
|
|
207
|
+
return value as Record<string, unknown>;
|
|
208
|
+
}
|
package/src/sessions.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// 会话索引:LogStore 接口只有 append/read,没有"列出会话",由发行版自己记一份。
|
|
2
|
+
// 只记顶层会话;子 Agent 的会话通过日志里的 child 引用找到。
|
|
3
|
+
|
|
4
|
+
import { appendFile, mkdir, readFile } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
export interface SessionEntry {
|
|
8
|
+
id: string;
|
|
9
|
+
cwd: string;
|
|
10
|
+
title: string;
|
|
11
|
+
at: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class SessionIndex {
|
|
15
|
+
readonly file: string;
|
|
16
|
+
|
|
17
|
+
constructor(file: string) {
|
|
18
|
+
this.file = file;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async add(entry: SessionEntry): Promise<void> {
|
|
22
|
+
await mkdir(path.dirname(this.file), { recursive: true });
|
|
23
|
+
await appendFile(this.file, JSON.stringify(entry) + "\n");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 最近使用的在前;同一个会话多次记录时取最后一次的时间、第一次的标题(之后的消息常常只是"继续") */
|
|
27
|
+
async list(cwd?: string): Promise<SessionEntry[]> {
|
|
28
|
+
let text: string;
|
|
29
|
+
try {
|
|
30
|
+
text = await readFile(this.file, "utf8");
|
|
31
|
+
} catch {
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
const latest = new Map<string, SessionEntry>();
|
|
35
|
+
for (const line of text.split("\n")) {
|
|
36
|
+
if (!line.trim()) continue;
|
|
37
|
+
try {
|
|
38
|
+
const e = JSON.parse(line) as SessionEntry;
|
|
39
|
+
const first = latest.get(e.id);
|
|
40
|
+
latest.delete(e.id);
|
|
41
|
+
latest.set(e.id, first ? { ...e, title: first.title } : e);
|
|
42
|
+
} catch {
|
|
43
|
+
// 末尾未写完的一行
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return [...latest.values()].filter((e) => !cwd || path.resolve(e.cwd) === path.resolve(cwd)).reverse();
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/skills.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// Skills:打包好的做事方法。一个目录就是一个 skill,入口是 SKILL.md(和 Claude Code、Agent Skills 的格式相同):
|
|
2
|
+
// ---
|
|
3
|
+
// name: pdf
|
|
4
|
+
// description: 读取、合并、拆分 PDF。处理 PDF 文件时使用
|
|
5
|
+
// ---
|
|
6
|
+
// 正文:具体步骤,可以引用同目录里的脚本、模板、参考资料
|
|
7
|
+
//
|
|
8
|
+
// 系统提示词里只列出每个 skill 的名字和描述;模型判断任务用得上时调用 skill 工具,才读入正文(渐进加载,省上下文)。
|
|
9
|
+
// 用户也可以用 /<skill 名> 直接要求使用某个 skill。
|
|
10
|
+
//
|
|
11
|
+
// 查找位置(同名时后面的覆盖前面的):
|
|
12
|
+
// ~/.claude/skills、$JADE_HOME/skills(用户层);
|
|
13
|
+
// 仓库根目录到工作目录每一级的 .claude/skills、.jade/skills(项目层)。
|
|
14
|
+
|
|
15
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
16
|
+
import os from "node:os";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
import type { Tool } from "uncarved";
|
|
19
|
+
import { projectDirs } from "./commands.ts";
|
|
20
|
+
|
|
21
|
+
export interface Skill {
|
|
22
|
+
name: string;
|
|
23
|
+
description: string;
|
|
24
|
+
/** skill 目录的绝对路径 */
|
|
25
|
+
dir: string;
|
|
26
|
+
layer: "user" | "project";
|
|
27
|
+
/** 前一个同名 skill 被它覆盖 */
|
|
28
|
+
overrides?: string;
|
|
29
|
+
/** 来自哪个插件 */
|
|
30
|
+
plugin?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const NAME = /^[a-z0-9][a-z0-9_-]*$/i;
|
|
34
|
+
/** 系统提示词里每个描述的上限 */
|
|
35
|
+
const MAX_DESCRIPTION = 400;
|
|
36
|
+
/** skill 工具列出的目录内文件数上限 */
|
|
37
|
+
const MAX_FILES = 60;
|
|
38
|
+
|
|
39
|
+
export async function loadSkills(opts: {
|
|
40
|
+
home: string;
|
|
41
|
+
root: string;
|
|
42
|
+
cwd: string;
|
|
43
|
+
/** 用户的主目录,读 ~/.claude/skills 用;测试时可以换掉 */
|
|
44
|
+
userHome?: string;
|
|
45
|
+
/** 插件带的 skills 目录,优先级低于同一层的 skills 目录 */
|
|
46
|
+
plugins?: { plugin: string; dir: string; layer: Skill["layer"] }[];
|
|
47
|
+
}): Promise<{ skills: Skill[]; warnings: string[] }> {
|
|
48
|
+
const fromPlugins = (layer: Skill["layer"]) => (opts.plugins ?? []).filter((p) => p.layer === layer);
|
|
49
|
+
const dirs: { dir: string; layer: Skill["layer"]; plugin?: string }[] = [
|
|
50
|
+
...fromPlugins("user"),
|
|
51
|
+
{ dir: path.join(opts.userHome ?? os.homedir(), ".claude", "skills"), layer: "user" },
|
|
52
|
+
{ dir: path.join(opts.home, "skills"), layer: "user" },
|
|
53
|
+
...fromPlugins("project"),
|
|
54
|
+
];
|
|
55
|
+
for (const d of projectDirs(opts.root, opts.cwd)) {
|
|
56
|
+
dirs.push({ dir: path.join(d, ".claude", "skills"), layer: "project" }, { dir: path.join(d, ".jade", "skills"), layer: "project" });
|
|
57
|
+
}
|
|
58
|
+
const out = new Map<string, Skill>();
|
|
59
|
+
const warnings: string[] = [];
|
|
60
|
+
const seen = new Set<string>();
|
|
61
|
+
for (const { dir, layer, plugin } of dirs) {
|
|
62
|
+
// JADE_HOME 就是 ~/.claude 之类的情况,同一个目录不读两次
|
|
63
|
+
if (seen.has(path.resolve(dir))) continue;
|
|
64
|
+
seen.add(path.resolve(dir));
|
|
65
|
+
let names: string[];
|
|
66
|
+
try {
|
|
67
|
+
names = (await readdir(dir)).filter((n) => !n.startsWith(".")).sort();
|
|
68
|
+
} catch {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
for (const n of names) {
|
|
72
|
+
const skillDir = path.join(dir, n);
|
|
73
|
+
let text: string;
|
|
74
|
+
try {
|
|
75
|
+
if (!(await stat(skillDir)).isDirectory()) continue;
|
|
76
|
+
text = await readFile(path.join(skillDir, "SKILL.md"), "utf8");
|
|
77
|
+
} catch {
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const { meta, body } = parseSkill(text);
|
|
81
|
+
const name = meta.name && NAME.test(meta.name) ? meta.name : n;
|
|
82
|
+
if (!NAME.test(name)) {
|
|
83
|
+
warnings.push(`skill ${skillDir} is skipped: the name may only contain letters, digits, - and _`);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const firstLine = body.split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").trim() ?? "";
|
|
87
|
+
const description = (meta.description || firstLine).trim();
|
|
88
|
+
if (!description) {
|
|
89
|
+
warnings.push(`skill ${skillDir} is skipped: SKILL.md has no description`);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const prev = out.get(name.toLowerCase());
|
|
93
|
+
out.set(name.toLowerCase(), {
|
|
94
|
+
name,
|
|
95
|
+
description: description.length > MAX_DESCRIPTION ? `${description.slice(0, MAX_DESCRIPTION)}…` : description,
|
|
96
|
+
dir: skillDir,
|
|
97
|
+
layer,
|
|
98
|
+
overrides: prev?.dir,
|
|
99
|
+
...(plugin ? { plugin } : {}),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return { skills: [...out.values()].sort((a, b) => a.name.localeCompare(b.name)), warnings };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** front matter 里的简单键值(支持引号和 YAML 的 > | 多行写法),以及正文 */
|
|
107
|
+
export function parseSkill(text: string): { meta: Record<string, string>; body: string } {
|
|
108
|
+
let body = text.replace(/^/, "");
|
|
109
|
+
const meta: Record<string, string> = {};
|
|
110
|
+
const fm = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(body);
|
|
111
|
+
if (fm) {
|
|
112
|
+
const lines = fm[1]!.split(/\r?\n/);
|
|
113
|
+
for (let i = 0; i < lines.length; i++) {
|
|
114
|
+
const m = /^([A-Za-z][\w-]*)\s*:\s*(.*?)\s*$/.exec(lines[i]!);
|
|
115
|
+
if (!m) continue;
|
|
116
|
+
let value = m[2]!;
|
|
117
|
+
if (/^[>|][+-]?$/.test(value)) {
|
|
118
|
+
// 多行:后面缩进的行都属于这个值
|
|
119
|
+
const parts: string[] = [];
|
|
120
|
+
while (i + 1 < lines.length && (/^\s+\S/.test(lines[i + 1]!) || lines[i + 1]!.trim() === "")) parts.push(lines[++i]!.trim());
|
|
121
|
+
value = parts.join(value.startsWith(">") ? " " : "\n").trim();
|
|
122
|
+
}
|
|
123
|
+
meta[m[1]!.toLowerCase()] = value.replace(/^(["'])(.*)\1$/, "$2");
|
|
124
|
+
}
|
|
125
|
+
body = body.slice(fm[0].length);
|
|
126
|
+
}
|
|
127
|
+
return { meta, body: body.trim() };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 系统提示词里的 skill 列表;没有 skill 时为 undefined */
|
|
131
|
+
export function skillsPrompt(skills: Skill[]): string | undefined {
|
|
132
|
+
if (skills.length === 0) return undefined;
|
|
133
|
+
return [
|
|
134
|
+
"# Skills",
|
|
135
|
+
"Skills are packaged instructions for specific kinds of tasks, installed by the user or shipped with the repository. " +
|
|
136
|
+
"When a task matches a skill's description, call the skill tool with its name before starting, then follow the instructions it returns. " +
|
|
137
|
+
"Files a skill refers to are relative to its directory, which the skill tool tells you.",
|
|
138
|
+
"",
|
|
139
|
+
...skills.map((s) => `- ${s.name}: ${s.description.replace(/\s+/g, " ")}`),
|
|
140
|
+
].join("\n");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** skill 工具:读入某个 skill 的正文,以及它目录里的文件 */
|
|
144
|
+
export function skillTool(skills: Skill[]): Tool {
|
|
145
|
+
const byName = new Map(skills.map((s) => [s.name.toLowerCase(), s]));
|
|
146
|
+
return {
|
|
147
|
+
name: "skill",
|
|
148
|
+
description:
|
|
149
|
+
"Load the instructions of a skill listed in the system prompt. Call it when a task matches the skill's description, then follow the instructions.",
|
|
150
|
+
inputSchema: {
|
|
151
|
+
type: "object",
|
|
152
|
+
properties: { name: { type: "string", enum: skills.map((s) => s.name), description: "the skill's name" } },
|
|
153
|
+
required: ["name"],
|
|
154
|
+
additionalProperties: false,
|
|
155
|
+
},
|
|
156
|
+
effect: "read",
|
|
157
|
+
concurrency: "safe",
|
|
158
|
+
idempotent: true,
|
|
159
|
+
async execute(input) {
|
|
160
|
+
const name = String((input as { name?: unknown }).name ?? "");
|
|
161
|
+
const skill = byName.get(name.toLowerCase());
|
|
162
|
+
if (!skill) return { content: `There is no skill named ${JSON.stringify(name)}. Available: ${skills.map((s) => s.name).join(", ")}.`, isError: true };
|
|
163
|
+
let text: string;
|
|
164
|
+
try {
|
|
165
|
+
text = await readFile(path.join(skill.dir, "SKILL.md"), "utf8");
|
|
166
|
+
} catch (err) {
|
|
167
|
+
return { content: `Could not read the skill: ${err instanceof Error ? err.message : String(err)}`, isError: true };
|
|
168
|
+
}
|
|
169
|
+
const files = (await listFiles(skill.dir)).filter((f) => f !== "SKILL.md");
|
|
170
|
+
const shown = files.slice(0, MAX_FILES);
|
|
171
|
+
return {
|
|
172
|
+
content: [
|
|
173
|
+
`Skill "${skill.name}" (${skill.layer === "project" ? "shipped with the repository" : "installed by the user"}).`,
|
|
174
|
+
`Its directory is ${skill.dir}; paths in the instructions are relative to it.`,
|
|
175
|
+
files.length ? `Files in the skill:\n${shown.map((f) => ` ${f}`).join("\n")}${files.length > shown.length ? `\n … ${files.length - shown.length} more` : ""}` : "",
|
|
176
|
+
"",
|
|
177
|
+
parseSkill(text).body,
|
|
178
|
+
]
|
|
179
|
+
.filter((l, i) => l !== "" || i === 3)
|
|
180
|
+
.join("\n"),
|
|
181
|
+
};
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function listFiles(dir: string): Promise<string[]> {
|
|
187
|
+
try {
|
|
188
|
+
const entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
|
189
|
+
return entries
|
|
190
|
+
.filter((e) => e.isFile())
|
|
191
|
+
.map((e) => path.relative(dir, path.join(e.parentPath, e.name)).split(path.sep).join("/"))
|
|
192
|
+
.filter((f) => !f.split("/").some((seg) => seg.startsWith(".") || seg === "node_modules" || seg === "__pycache__"))
|
|
193
|
+
.sort();
|
|
194
|
+
} catch {
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
}
|
package/src/sys.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// 跨运行时的进程、可执行文件查找和 glob:只用 Node 的标准库,Bun 和 Node ≥22.18 下走同一套代码。
|
|
2
|
+
|
|
3
|
+
import { spawn as nodeSpawn, spawnSync as nodeSpawnSync } from "node:child_process";
|
|
4
|
+
import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import picomatch from "picomatch";
|
|
7
|
+
|
|
8
|
+
/** jade 自己的版本号,src 和 dist 下都从包根目录的 package.json 读 */
|
|
9
|
+
export const VERSION: string = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
10
|
+
|
|
11
|
+
type Stdio = "pipe" | "ignore";
|
|
12
|
+
|
|
13
|
+
export interface Proc {
|
|
14
|
+
pid: number;
|
|
15
|
+
/** stdout 为 "pipe" 时才有;Node 的 Readable 可以直接 for await 读出 Uint8Array */
|
|
16
|
+
stdout: AsyncIterable<Uint8Array>;
|
|
17
|
+
stderr: AsyncIterable<Uint8Array>;
|
|
18
|
+
/** 进程退出时 resolve 退出码;被信号杀掉时为 null */
|
|
19
|
+
exited: Promise<number | null>;
|
|
20
|
+
kill(): void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface SpawnOptions {
|
|
24
|
+
cwd?: string;
|
|
25
|
+
stdout?: Stdio;
|
|
26
|
+
stderr?: Stdio;
|
|
27
|
+
/** POSIX 上自成进程组,便于连同子进程一起杀掉 */
|
|
28
|
+
detached?: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const EMPTY: AsyncIterable<Uint8Array> = { async *[Symbol.asyncIterator]() {} };
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 启动进程,等到确实启动了才返回。程序不存在(ENOENT)等启动错误会 reject,
|
|
35
|
+
* 调用方用 try/catch 判断"没装",和 Bun.spawn 同步抛错的用法一致
|
|
36
|
+
*/
|
|
37
|
+
export function spawn(cmd: string[], opts: SpawnOptions = {}): Promise<Proc> {
|
|
38
|
+
const child = nodeSpawn(cmd[0]!, cmd.slice(1), {
|
|
39
|
+
cwd: opts.cwd,
|
|
40
|
+
stdio: ["ignore", opts.stdout ?? "pipe", opts.stderr ?? "pipe"],
|
|
41
|
+
detached: opts.detached ?? false,
|
|
42
|
+
// Windows 上不弹出控制台窗口
|
|
43
|
+
windowsHide: true,
|
|
44
|
+
});
|
|
45
|
+
const exited = new Promise<number | null>((resolve) => child.once("exit", (code) => resolve(code)));
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
child.once("error", reject);
|
|
48
|
+
child.once("spawn", () => {
|
|
49
|
+
child.off("error", reject);
|
|
50
|
+
// 启动之后的错误(例如 kill 一个已经退出的进程)不应该变成未处理的异常
|
|
51
|
+
child.on("error", () => {});
|
|
52
|
+
resolve({
|
|
53
|
+
pid: child.pid!,
|
|
54
|
+
stdout: child.stdout ?? EMPTY,
|
|
55
|
+
stderr: child.stderr ?? EMPTY,
|
|
56
|
+
exited,
|
|
57
|
+
kill: () => void child.kill(),
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 运行一条命令,返回 stdout 文本和退出码;启动失败时 reject */
|
|
64
|
+
export async function run(cmd: string[], opts: { cwd?: string } = {}): Promise<{ code: number | null; stdout: string }> {
|
|
65
|
+
const proc = await spawn(cmd, { cwd: opts.cwd, stderr: "ignore" });
|
|
66
|
+
const [stdout, code] = await Promise.all([text(proc.stdout), proc.exited]);
|
|
67
|
+
return { code, stdout };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 同步运行,忽略输出和错误;用于退出前的清理 */
|
|
71
|
+
export function runSync(cmd: string[]): void {
|
|
72
|
+
nodeSpawnSync(cmd[0]!, cmd.slice(1), { stdio: "ignore", windowsHide: true });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function text(stream: AsyncIterable<Uint8Array>): Promise<string> {
|
|
76
|
+
const decoder = new TextDecoder();
|
|
77
|
+
let out = "";
|
|
78
|
+
for await (const chunk of stream) out += decoder.decode(chunk, { stream: true });
|
|
79
|
+
return out + decoder.decode();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 在 PATH 里找可执行文件,找不到返回 undefined。Windows 上按 PATHEXT 补扩展名;带路径分隔符时只检查那个文件 */
|
|
83
|
+
export function which(bin: string): string | undefined {
|
|
84
|
+
const win = process.platform === "win32";
|
|
85
|
+
const exts = win ? ["", ...(process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
|
|
86
|
+
const ok = (file: string) => {
|
|
87
|
+
try {
|
|
88
|
+
if (!statSync(file).isFile()) return false;
|
|
89
|
+
if (!win) accessSync(file, constants.X_OK);
|
|
90
|
+
return true;
|
|
91
|
+
} catch {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
const tryAll = (base: string) => {
|
|
96
|
+
for (const ext of exts) {
|
|
97
|
+
// Windows 上没有扩展名的文件不能直接执行(例如 npm 旁边那个给 Git Bash 用的 sh 脚本)
|
|
98
|
+
if (win && ext === "" && !path.extname(base)) continue;
|
|
99
|
+
if (ok(base + ext)) return base + ext;
|
|
100
|
+
}
|
|
101
|
+
return undefined;
|
|
102
|
+
};
|
|
103
|
+
if (bin.includes("/") || (win && bin.includes("\\"))) return tryAll(path.resolve(bin));
|
|
104
|
+
const dirs = (process.env.PATH ?? process.env.Path ?? "").split(path.delimiter).filter(Boolean);
|
|
105
|
+
for (const dir of dirs) {
|
|
106
|
+
const found = tryAll(path.join(dir.replace(/^"(.*)"$/, "$1"), bin));
|
|
107
|
+
if (found) return found;
|
|
108
|
+
}
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 编译 glob,返回匹配函数。路径用正斜杠、相对于搜索根目录。
|
|
114
|
+
* 和原先的 Bun.Glob#match 一致:* 也匹配点开头的文件,反斜杠是转义符而不是分隔符
|
|
115
|
+
*/
|
|
116
|
+
export function globMatcher(pattern: string): (rel: string) => boolean {
|
|
117
|
+
return picomatch(pattern, { dot: true, windows: false });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 找 npm 的 CLI 脚本,用当前的 node 运行它:Windows 上 npm 是 .cmd,不经过 shell 不能直接执行 */
|
|
121
|
+
export function npmCommand(): string[] | undefined {
|
|
122
|
+
const dirs = [path.dirname(process.execPath)];
|
|
123
|
+
const onPath = which(process.platform === "win32" ? "npm.cmd" : "npm");
|
|
124
|
+
if (onPath) dirs.push(path.dirname(onPath));
|
|
125
|
+
for (const dir of dirs) {
|
|
126
|
+
for (const cli of [path.join(dir, "node_modules", "npm", "bin", "npm-cli.js"), path.join(dir, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js")]) {
|
|
127
|
+
if (existsSync(cli)) return [process.execPath, cli];
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// POSIX 上 npm 本身就是可执行的脚本
|
|
131
|
+
if (onPath && process.platform !== "win32") return [onPath];
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|