@uncarved/jade 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/README.md +204 -198
  2. package/bin/jade.js +23 -0
  3. package/dist/commands.d.ts +20 -0
  4. package/dist/commands.js +20 -0
  5. package/dist/commands.js.map +1 -1
  6. package/dist/distro.d.ts +43 -6
  7. package/dist/distro.js +198 -48
  8. package/dist/distro.js.map +1 -1
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.js +2 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/main.js +436 -300
  13. package/dist/main.js.map +1 -1
  14. package/dist/plugin-cli.d.ts +1 -1
  15. package/dist/plugin-cli.js +79 -36
  16. package/dist/plugin-cli.js.map +1 -1
  17. package/dist/plugins/budget.d.ts +2 -2
  18. package/dist/plugins/budget.js +2 -2
  19. package/dist/plugins/budget.js.map +1 -1
  20. package/dist/plugins/builtins.js +6 -3
  21. package/dist/plugins/builtins.js.map +1 -1
  22. package/dist/plugins/checks.d.ts +2 -1
  23. package/dist/plugins/checks.js +25 -5
  24. package/dist/plugins/checks.js.map +1 -1
  25. package/dist/plugins/compact.js +45 -1
  26. package/dist/plugins/compact.js.map +1 -1
  27. package/dist/plugins/core.d.ts +5 -0
  28. package/dist/plugins/core.js +39 -0
  29. package/dist/plugins/core.js.map +1 -1
  30. package/dist/plugins/host.d.ts +52 -0
  31. package/dist/plugins/host.js +115 -0
  32. package/dist/plugins/host.js.map +1 -0
  33. package/dist/plugins/install.d.ts +1 -1
  34. package/dist/plugins/loader.d.ts +238 -10
  35. package/dist/plugins/loader.js +175 -21
  36. package/dist/plugins/loader.js.map +1 -1
  37. package/dist/plugins/policy.d.ts +2 -0
  38. package/dist/plugins/policy.js +17 -1
  39. package/dist/plugins/policy.js.map +1 -1
  40. package/dist/plugins/prompts.d.ts +6 -1
  41. package/dist/plugins/prompts.js +103 -15
  42. package/dist/plugins/prompts.js.map +1 -1
  43. package/dist/plugins/repeats.d.ts +7 -0
  44. package/dist/plugins/repeats.js +74 -13
  45. package/dist/plugins/repeats.js.map +1 -1
  46. package/dist/plugins/review.d.ts +2 -0
  47. package/dist/plugins/review.js +41 -3
  48. package/dist/plugins/review.js.map +1 -1
  49. package/dist/plugins/sessions.d.ts +7 -0
  50. package/dist/plugins/sessions.js +110 -0
  51. package/dist/plugins/sessions.js.map +1 -0
  52. package/dist/provider.d.ts +56 -2
  53. package/dist/provider.js +73 -7
  54. package/dist/provider.js.map +1 -1
  55. package/dist/session-lifecycle.d.ts +61 -0
  56. package/dist/session-lifecycle.js +167 -0
  57. package/dist/session-lifecycle.js.map +1 -0
  58. package/dist/session-scope.d.ts +53 -0
  59. package/dist/session-scope.js +116 -0
  60. package/dist/session-scope.js.map +1 -0
  61. package/dist/sessions.d.ts +6 -0
  62. package/dist/sessions.js +20 -0
  63. package/dist/sessions.js.map +1 -1
  64. package/dist/sys.d.ts +4 -1
  65. package/dist/sys.js +18 -1
  66. package/dist/sys.js.map +1 -1
  67. package/dist/tools/ask.d.ts +11 -0
  68. package/dist/tools/ask.js +62 -0
  69. package/dist/tools/ask.js.map +1 -0
  70. package/dist/tools/fs.d.ts +4 -0
  71. package/dist/tools/fs.js +53 -12
  72. package/dist/tools/fs.js.map +1 -1
  73. package/dist/tools/grep.js +3 -2
  74. package/dist/tools/grep.js.map +1 -1
  75. package/dist/tools/shell.js +5 -1
  76. package/dist/tools/shell.js.map +1 -1
  77. package/dist/tools/task.d.ts +6 -2
  78. package/dist/tools/task.js +36 -8
  79. package/dist/tools/task.js.map +1 -1
  80. package/dist/tools/web.d.ts +33 -3
  81. package/dist/tools/web.js +351 -143
  82. package/dist/tools/web.js.map +1 -1
  83. package/dist/ui/configure.js +91 -22
  84. package/dist/ui/configure.js.map +1 -1
  85. package/dist/ui/diff.d.ts +1 -1
  86. package/dist/ui/diff.js +1 -2
  87. package/dist/ui/diff.js.map +1 -1
  88. package/dist/ui/editor.d.ts +8 -0
  89. package/dist/ui/editor.js +50 -1
  90. package/dist/ui/editor.js.map +1 -1
  91. package/dist/ui/markdown.d.ts +6 -1
  92. package/dist/ui/markdown.js +57 -19
  93. package/dist/ui/markdown.js.map +1 -1
  94. package/dist/ui/render.d.ts +9 -10
  95. package/dist/ui/render.js +35 -72
  96. package/dist/ui/render.js.map +1 -1
  97. package/dist/ui/renderers.d.ts +8 -0
  98. package/dist/ui/renderers.js +169 -0
  99. package/dist/ui/renderers.js.map +1 -0
  100. package/dist/ui/screen.d.ts +22 -2
  101. package/dist/ui/screen.js +104 -15
  102. package/dist/ui/screen.js.map +1 -1
  103. package/dist/ui/transcript.d.ts +13 -0
  104. package/dist/ui/transcript.js +105 -15
  105. package/dist/ui/transcript.js.map +1 -1
  106. package/dist/ui/tui.d.ts +2 -0
  107. package/dist/ui/tui.js +309 -58
  108. package/dist/ui/tui.js.map +1 -1
  109. package/dist/update.d.ts +53 -0
  110. package/dist/update.js +255 -0
  111. package/dist/update.js.map +1 -0
  112. package/package.json +6 -5
  113. package/src/commands.ts +24 -0
  114. package/src/distro.ts +228 -51
  115. package/src/index.ts +2 -0
  116. package/src/main.ts +413 -292
  117. package/src/plugin-cli.ts +73 -34
  118. package/src/plugins/budget.ts +4 -4
  119. package/src/plugins/builtins.ts +6 -3
  120. package/src/plugins/checks.ts +25 -6
  121. package/src/plugins/compact.ts +40 -1
  122. package/src/plugins/core.ts +40 -0
  123. package/src/plugins/host.ts +146 -0
  124. package/src/plugins/install.ts +1 -1
  125. package/src/plugins/loader.ts +379 -23
  126. package/src/plugins/policy.ts +17 -1
  127. package/src/plugins/prompts.ts +108 -15
  128. package/src/plugins/repeats.ts +75 -14
  129. package/src/plugins/review.ts +40 -3
  130. package/src/plugins/sessions.ts +109 -0
  131. package/src/provider.ts +109 -10
  132. package/src/session-lifecycle.ts +194 -0
  133. package/src/session-scope.ts +135 -0
  134. package/src/sessions.ts +17 -0
  135. package/src/sys.ts +18 -1
  136. package/src/tools/ask.ts +72 -0
  137. package/src/tools/fs.ts +53 -12
  138. package/src/tools/grep.ts +3 -2
  139. package/src/tools/shell.ts +5 -1
  140. package/src/tools/task.ts +51 -11
  141. package/src/tools/web.ts +370 -140
  142. package/src/ui/configure.ts +90 -27
  143. package/src/ui/diff.ts +1 -2
  144. package/src/ui/editor.ts +50 -1
  145. package/src/ui/markdown.ts +258 -219
  146. package/src/ui/render.ts +35 -57
  147. package/src/ui/renderers.ts +183 -0
  148. package/src/ui/screen.ts +113 -19
  149. package/src/ui/transcript.ts +109 -16
  150. package/src/ui/tui.tsx +353 -58
  151. package/src/update.ts +262 -0
package/src/provider.ts CHANGED
@@ -182,6 +182,75 @@ export const PROVIDER_KINDS: readonly ProviderKind[] = ["openai-compat", "openai
182
182
 
183
183
  type Env = Record<string, string | undefined>;
184
184
 
185
+ export const isBuiltinKind = (kind: string): kind is ProviderKind => (PROVIDER_KINDS as readonly string[]).includes(kind);
186
+
187
+ /** 插件提供的模型服务(JadePlugin.providers),用 JADE_PROVIDER=<kind> 选择 */
188
+ export interface ProviderDef {
189
+ /** JADE_PROVIDER 的值:字母、数字、-、_,不能和内置的 openai-compat、openai、anthropic 重名 */
190
+ kind: string;
191
+ /** 当前配置的模型名(状态栏、/model 显示,上下文窗口按它推断);env 是 jade 的环境变量(含 $JADE_HOME/.env) */
192
+ model(env: Env): string;
193
+ /** 系统提示词里告诉模型它经什么服务运行,例如 "the Foo API at api.foo.com";不给时是 "the <kind> provider" */
194
+ via?(env: Env): string;
195
+ /** 按 env 创建 Provider(uncarved 的接口);缺配置时抛错,信息直接显示给用户。jade 在外面包一层重试和限速 */
196
+ create(env: Env): Provider | Promise<Provider>;
197
+ /** /model 里列出可选的模型;不给时 /model 不能列出模型 */
198
+ listModels?(env: Env): Promise<string[]>;
199
+ /** 服务的配置项:/model 添加这个服务时依次询问,写进 $JADE_HOME/.env;不给时只能手动写 .env */
200
+ settings?: ProviderSetting[];
201
+ }
202
+
203
+ /** 插件服务的一个配置项,对应一个环境变量 */
204
+ export interface ProviderSetting {
205
+ /** 环境变量名,大写字母、数字、_,例如 "FOO_API_KEY";不能是 JADE_ 开头的 */
206
+ env: string;
207
+ /** /model 里显示的名字,例如 "API key" */
208
+ label: string;
209
+ /** 输入时遮住(密钥);留空时沿用已有的值 */
210
+ secret?: boolean;
211
+ /** 这一项是模型名:/model 从 listModels 里选、换模型时只改它。最多一项 */
212
+ model?: boolean;
213
+ /** 不能为空 */
214
+ required?: boolean;
215
+ /** 输入框里的提示文字 */
216
+ placeholder?: string;
217
+ }
218
+
219
+ export const SETTING_ENV = /^[A-Z][A-Z0-9_]*$/;
220
+
221
+ export const PROVIDER_KIND = /^[a-z0-9][a-z0-9_-]*$/i;
222
+
223
+ /** 插件注册的服务;只在启动时注册一次,整个进程共用 */
224
+ const plugged = new Map<string, { plugin: string; def: ProviderDef }>();
225
+
226
+ /** 注册插件提供的服务;返回要告诉用户的问题(名字不合法、和内置的或先注册的重名) */
227
+ export function registerProviders(list: { plugin: string; def: ProviderDef }[]): string[] {
228
+ const warnings: string[] = [];
229
+ for (const { plugin, def } of list) {
230
+ const kind = def.kind;
231
+ const taken = plugged.get(kind);
232
+ if (isBuiltinKind(kind)) warnings.push(`plugin ${plugin}: provider ${kind} is ignored: it is a built-in provider`);
233
+ else if (taken) warnings.push(`plugin ${plugin}: provider ${kind} is ignored: plugin ${taken.plugin} already provides it`);
234
+ else plugged.set(kind, { plugin, def });
235
+ }
236
+ return warnings;
237
+ }
238
+
239
+ /** JADE_PROVIDER 选的服务由哪个插件提供;内置的或没有插件提供时 undefined */
240
+ export function pluginProvider(kind: string): { plugin: string; def: ProviderDef } | undefined {
241
+ return plugged.get(kind);
242
+ }
243
+
244
+ /** 注册了的插件服务,按注册顺序 */
245
+ export function pluginProviders(): { plugin: string; def: ProviderDef }[] {
246
+ return [...plugged.values()];
247
+ }
248
+
249
+ /** 测试用 */
250
+ export function clearProviders(): void {
251
+ plugged.clear();
252
+ }
253
+
185
254
  /** JADE_EFFORT 可取的值;openai-compat 没有统一的字段,用 OPENAI_COMPAT_EXTRA_BODY 自己设 */
186
255
  export const EFFORTS: Record<ProviderKind, readonly string[] | undefined> = {
187
256
  anthropic: ["low", "medium", "high", "xhigh", "max"],
@@ -216,7 +285,8 @@ export function idleTimeoutFromEnv(env: Env = process.env): number | undefined {
216
285
  */
217
286
  export function visionFromEnv(env: Env = process.env): boolean {
218
287
  const text = env.JADE_VISION?.trim().toLowerCase();
219
- if (!text) return providerKind(env) !== "openai-compat";
288
+ // 插件的服务也算不能看:不知道它的模型支不支持
289
+ if (!text) return providerKind(env) === "openai" || providerKind(env) === "anthropic";
220
290
  if (["1", "true", "on", "yes"].includes(text)) return true;
221
291
  if (["0", "false", "off", "no"].includes(text)) return false;
222
292
  throw new Error(`JADE_VISION must be on or off, got ${JSON.stringify(env.JADE_VISION)}`);
@@ -227,6 +297,8 @@ export function effortFromEnv(env: Env = process.env): string | undefined {
227
297
  const effort = env.JADE_EFFORT;
228
298
  if (!effort) return undefined;
229
299
  const kind = providerKind(env);
300
+ // 插件的服务自己从 env 里读、自己检查
301
+ if (!isBuiltinKind(kind)) return effort;
230
302
  const allowed = EFFORTS[kind];
231
303
  if (!allowed) throw new Error(`JADE_EFFORT is not supported for the ${kind} provider; set it in OPENAI_COMPAT_EXTRA_BODY instead`);
232
304
  if (!allowed.includes(effort)) throw new Error(`JADE_EFFORT must be one of ${allowed.join(", ")} for the ${kind} provider, got ${JSON.stringify(effort)}`);
@@ -234,21 +306,20 @@ export function effortFromEnv(env: Env = process.env): string | undefined {
234
306
  }
235
307
 
236
308
  /** JADE_PROVIDER 指定时用它;否则按 OPENAI_API_KEY、OPENAI_COMPAT_BASE_URL、ANTHROPIC_API_KEY 的顺序 */
237
- export function providerKind(env: Env = process.env): ProviderKind {
309
+ /**
310
+ * 当前配置的服务:内置的三种之一,或者 JADE_PROVIDER 写的插件服务的名字。
311
+ * 写了没有插件提供的名字时也原样返回(插件可能还没加载),创建 provider 时才报错
312
+ */
313
+ export function providerKind(env: Env = process.env): string {
238
314
  const named = env.JADE_PROVIDER;
239
- if (named) {
240
- if (!(PROVIDER_KINDS as readonly string[]).includes(named)) {
241
- throw new Error(`JADE_PROVIDER must be one of ${PROVIDER_KINDS.join(", ")}, got ${JSON.stringify(named)}`);
242
- }
243
- return named as ProviderKind;
244
- }
315
+ if (named) return named;
245
316
  if (env.OPENAI_API_KEY) return "openai";
246
317
  if (env.OPENAI_COMPAT_BASE_URL) return "openai-compat";
247
318
  return "anthropic";
248
319
  }
249
320
 
250
321
  export interface ProviderInfo {
251
- kind: ProviderKind;
322
+ kind: string;
252
323
  model: string;
253
324
  baseURL?: string;
254
325
  }
@@ -258,7 +329,17 @@ export function providerInfo(env: Env = process.env): ProviderInfo {
258
329
  const kind = providerKind(env);
259
330
  if (kind === "openai") return { kind, model: env.OPENAI_MODEL ?? "gpt-5", baseURL: env.OPENAI_BASE_URL ?? "https://api.openai.com/v1" };
260
331
  if (kind === "openai-compat") return { kind, model: env.OPENAI_COMPAT_MODEL ?? "", baseURL: env.OPENAI_COMPAT_BASE_URL };
261
- return { kind, model: env.ANTHROPIC_MODEL ?? "claude-opus-5-5", baseURL: env.ANTHROPIC_BASE_URL };
332
+ if (kind === "anthropic") return { kind, model: env.ANTHROPIC_MODEL ?? "claude-opus-5-5", baseURL: env.ANTHROPIC_BASE_URL };
333
+ return { kind, model: pluginModel(kind, env) };
334
+ }
335
+
336
+ /** 插件服务的模型名;插件还没注册或出错时为空 */
337
+ function pluginModel(kind: string, env: Env): string {
338
+ try {
339
+ return String(plugged.get(kind)?.def.model(env) ?? "");
340
+ } catch {
341
+ return "";
342
+ }
262
343
  }
263
344
 
264
345
  /**
@@ -276,6 +357,20 @@ export function providerInfo(env: Env = process.env): ProviderInfo {
276
357
  */
277
358
  export async function providerFromEnv(env: Env = process.env): Promise<Provider> {
278
359
  const kind = providerKind(env);
360
+ if (!isBuiltinKind(kind)) {
361
+ const found = plugged.get(kind);
362
+ if (!found) {
363
+ const all = [...PROVIDER_KINDS, ...plugged.keys()];
364
+ throw new Error(`JADE_PROVIDER must be one of ${all.join(", ")}, got ${JSON.stringify(kind)} (no plugin provides it)`);
365
+ }
366
+ // 限速、空闲超时这些 jade 自己的设置写错时同样在这里报错。空闲超时只对 OpenAI 和 OpenAI 兼容服务生效(见 README),
367
+ // 插件的服务要用的话自己从 env 读
368
+ rpmFromEnv(env);
369
+ idleTimeoutFromEnv(env);
370
+ const made = await found.def.create(env);
371
+ if (!made || typeof made.complete !== "function") throw new Error(`plugin ${found.plugin}: provider ${kind} must return an object with a complete function`);
372
+ return made;
373
+ }
279
374
  const maxTokens = env.JADE_MAX_TOKENS ? parseTokens("JADE_MAX_TOKENS", env.JADE_MAX_TOKENS) : undefined;
280
375
  const effort = effortFromEnv(env);
281
376
  // 写错时在这里就报错,不等到第一次请求
@@ -334,6 +429,10 @@ export function switchable(initial: Provider): SwitchableProvider {
334
429
  /** 服务提供的模型列表;不支持或出错时返回空数组 */
335
430
  export async function listModels(env: Env = process.env, fetchImpl: typeof fetch = fetch): Promise<string[]> {
336
431
  const kind = providerKind(env);
432
+ if (!isBuiltinKind(kind)) {
433
+ const list = plugged.get(kind)?.def.listModels;
434
+ return list ? list(env).then((m) => (Array.isArray(m) ? m.filter((x) => typeof x === "string") : []), () => []) : [];
435
+ }
337
436
  const info = providerInfo(env);
338
437
  const base = (info.baseURL ?? "https://api.anthropic.com").replace(/\/$/, "");
339
438
  const headers: Record<string, string> =
@@ -0,0 +1,194 @@
1
+ // 会话的生命周期:开始、离开、换会话(/clear、/resume)、重新加载、退出。每个会话一套插件实例(SessionScope)和一个运行时。
2
+ //
3
+ // 换会话是事务(docs/design/jade-plugin-lifecycle.md 第 5 节):
4
+ // 1. prepare:新的一套在 preparing 里创建,工厂函数这时运行;
5
+ // 2. 打开新的运行时;失败就回滚:只收掉新的一套,当前的一套一直是 active,不用恢复任何东西;
6
+ // 3. commit:关闭旧的一套(ctx.signal 中止),会话收尾(detach),换成新的,激活新的;旧的一套在后台 dispose。
7
+ // 退出前 settled() 等所有后台 dispose 完成。
8
+ //
9
+ // 这里不碰界面:清屏、状态栏的会话号、提示由调用方(main.ts)在每一步之后做。
10
+
11
+ import type { Plugin, Runtime } from "uncarved";
12
+ import type { Jade } from "./distro.ts";
13
+ import type { SessionScope } from "./session-scope.ts";
14
+
15
+ export interface LifecycleDeps<Mode> {
16
+ /** 创建一套新的插件实例,挂在一个 preparing 的作用域上 */
17
+ prepare(mode: Mode | undefined): Promise<SessionScope>;
18
+ /** 打开运行时:有 id 时恢复那个会话,没有时开始新会话 */
19
+ open(plugins: Plugin[], id?: string): Promise<Runtime>;
20
+ /** 离开会话之后调用:会话没用过就删掉它的日志;返回是否删掉了 */
21
+ discard(sessionId: string): Promise<boolean>;
22
+ /** 要告诉用户的问题(插件 dispose 出错、超时等) */
23
+ warn(list: string[]): void;
24
+ /** 会话收尾失败:仍然继续离开 */
25
+ error(err: unknown): void;
26
+ }
27
+
28
+ /** 当前会话:一起换 */
29
+ export interface Current {
30
+ scope: SessionScope;
31
+ jade: Jade;
32
+ rt: Runtime;
33
+ sessionId: string;
34
+ }
35
+
36
+ export class SessionLifecycle<Mode = string> {
37
+ readonly #deps: LifecycleDeps<Mode>;
38
+ #scope: SessionScope;
39
+ #rt: Runtime | undefined;
40
+ #sessionId = "";
41
+ /**
42
+ * 当前会话已经离开(当前的一套已关闭、会话已收尾)。正常时离开后马上换成新的;
43
+ * 只有 reload 收尾之后两次打开都失败时会停在这里,之后 leave 不再收尾一次,reload、switchTo 可以再试
44
+ */
45
+ #left = false;
46
+ /** 后台进行中的 dispose:换会话时不等它(新会话已经能用了),退出前等完(各自限时,见 DISPOSE_TIMEOUT_MS) */
47
+ readonly #disposals = new Set<Promise<void>>();
48
+
49
+ private constructor(deps: LifecycleDeps<Mode>, scope: SessionScope) {
50
+ this.#deps = deps;
51
+ this.#scope = scope;
52
+ }
53
+
54
+ /**
55
+ * 启动的第一步:创建第一套插件实例(还没激活)。之后宿主可以先读 jade(命令、警告、服务),再调用 begin 打开会话
56
+ */
57
+ static async prepare<Mode>(deps: LifecycleDeps<Mode>, mode?: Mode): Promise<SessionLifecycle<Mode>> {
58
+ return new SessionLifecycle(deps, await deps.prepare(mode));
59
+ }
60
+
61
+ get scope(): SessionScope {
62
+ return this.#scope;
63
+ }
64
+
65
+ get jade(): Jade {
66
+ return this.#scope.jade;
67
+ }
68
+
69
+ /** 当前会话;begin 之前不能用 */
70
+ get current(): Current {
71
+ if (!this.#rt) throw new Error("the session has not begun");
72
+ return { scope: this.#scope, jade: this.#scope.jade, rt: this.#rt, sessionId: this.#sessionId };
73
+ }
74
+
75
+ /** 启动的第二步:打开第一个会话并激活插件。失败时收掉这套实例再抛出 */
76
+ async begin(id?: string): Promise<Current> {
77
+ try {
78
+ this.#commit(this.#scope, await this.#deps.open(this.jade.plugins, id));
79
+ } catch (err) {
80
+ this.jade.shutdown();
81
+ this.#deps.warn(await this.#scope.dispose());
82
+ throw err;
83
+ }
84
+ return this.current;
85
+ }
86
+
87
+ /**
88
+ * 离开当前会话但保留它(退出、换会话时):先关闭作用域(进行中的快捷键、插件的 ctx.signal 中止),再会话收尾。
89
+ * 会话收尾(session.detached 的 hook)用的还是这套实例,之后才在后台 dispose。返回会话是否保留了下来
90
+ */
91
+ async leave(reason = "the session ended"): Promise<boolean> {
92
+ if (this.#left) return true;
93
+ const { sessionId } = this.current;
94
+ if (!(await this.#detach(reason))) return true;
95
+ try {
96
+ return !(await this.#deps.discard(sessionId));
97
+ } catch (err) {
98
+ this.#deps.error(err);
99
+ return true;
100
+ }
101
+ }
102
+
103
+ /** 当前会话是否已经离开(reload 收尾后没能打开会话时);这时要 switchTo 或 reload 才能继续 */
104
+ get left(): boolean {
105
+ return this.#left;
106
+ }
107
+
108
+ /**
109
+ * 换成另一个会话:id 为空时开始新会话(/clear),否则恢复它(/resume)。
110
+ * 打开失败时回滚并抛出,当前会话不受影响;成功时返回旧会话的 id 和它是否保留了下来
111
+ */
112
+ async switchTo(id: string | undefined, mode: Mode | undefined): Promise<{ previous: string; kept: boolean }> {
113
+ // 同一个会话不能同时由两个运行时打开:先打开再收尾旧的,会把 session.detached 写进新运行时正在用的日志
114
+ // (没用过的会话还会被 discard 删掉)。内置的 /resume 已经挡住,这里挡住插件直接调用 session.resume
115
+ if (id !== undefined && id === this.#sessionId && !this.#left) throw new Error(`${id} is the current session`);
116
+ const next = await this.#deps.prepare(mode);
117
+ let rt: Runtime;
118
+ try {
119
+ rt = await this.#deps.open(next.jade.plugins, id);
120
+ } catch (err) {
121
+ // 回滚:新的一套从没激活过,收掉它就行;当前的一套一直是 active
122
+ next.jade.shutdown();
123
+ this.#deps.warn(await next.dispose());
124
+ throw err;
125
+ }
126
+ const previous = this.#sessionId;
127
+ const kept = await this.leave();
128
+ this.#commit(next, rt);
129
+ return { previous, kept };
130
+ }
131
+
132
+ /**
133
+ * 用新的插件实例继续当前会话:工具和系统提示词按现在的配置重新生成,对话内容不变。
134
+ * 同一个会话要先 detach 才能用新的实例恢复,所以先关掉当前的一套;恢复失败时改为开始新会话,返回那个错误。
135
+ * 新会话也开不了时抛出:这时当前会话已经离开(left),可以再 reload、switchTo;leave 不会再收尾一次
136
+ */
137
+ async reload(mode: Mode | undefined): Promise<{ error?: unknown }> {
138
+ const next = await this.#deps.prepare(mode);
139
+ const { sessionId } = this.current;
140
+ if (!this.#left) await this.#detach("the session was reloaded");
141
+ let error: unknown;
142
+ let opened: Runtime;
143
+ try {
144
+ opened = await this.#deps.open(next.jade.plugins, sessionId);
145
+ } catch (err) {
146
+ error = err;
147
+ try {
148
+ opened = await this.#deps.open(next.jade.plugins);
149
+ } catch (again) {
150
+ next.jade.shutdown();
151
+ this.#deps.warn(await next.dispose());
152
+ throw again;
153
+ }
154
+ }
155
+ this.#commit(next, opened);
156
+ return error === undefined ? {} : { error };
157
+ }
158
+
159
+ /** 退出前:等后台的 dispose 都完成 */
160
+ async settled(): Promise<void> {
161
+ await Promise.all(this.#disposals);
162
+ }
163
+
164
+ #commit(scope: SessionScope, rt: Runtime) {
165
+ this.#scope = scope;
166
+ this.#rt = rt;
167
+ this.#sessionId = rt.state.sessionId;
168
+ this.#left = false;
169
+ scope.activate();
170
+ }
171
+
172
+ /** 离开当前会话:关闭当前的一套,会话收尾,在后台 dispose。返回收尾是否成功(失败时已经报告) */
173
+ async #detach(reason: string): Promise<boolean> {
174
+ const { scope, rt } = this.current;
175
+ this.#left = true;
176
+ scope.close(reason);
177
+ scope.jade.shutdown();
178
+ try {
179
+ await rt.detach();
180
+ return true;
181
+ } catch (err) {
182
+ this.#deps.error(err);
183
+ return false;
184
+ } finally {
185
+ this.#disposeInBackground(scope);
186
+ }
187
+ }
188
+
189
+ #disposeInBackground(scope: SessionScope) {
190
+ const done = scope.dispose().then((w) => this.#deps.warn(w));
191
+ this.#disposals.add(done);
192
+ void done.finally(() => this.#disposals.delete(done));
193
+ }
194
+ }
@@ -0,0 +1,135 @@
1
+ // 会话级的插件作用域(SessionScope):一套插件实例,加上绑定到这套实例的 ctx.status、ctx.input、ctx.send、ctx.signal。
2
+ //
3
+ // preparing ──activate──▶ active ──close──▶ closing ──dispose──▶ closed
4
+ // └──────────────────close──────────────────┘
5
+ //
6
+ // 换会话是一个事务:先在 preparing 里创建新的一套(工厂函数这时运行),成功了才关闭旧的、激活新的;
7
+ // 失败了只关闭新的,旧的一直是 active,不用恢复任何东西。见 docs/design/jade-plugin-lifecycle.md 第 3.2、5 节。
8
+
9
+ import type { Jade } from "./distro.ts";
10
+
11
+ export type ScopeState = "preparing" | "active" | "closing" | "closed";
12
+
13
+ /** 宿主的界面:作用域经它显示状态栏、改输入框、替用户发送、提示问题 */
14
+ export interface ScopeHost {
15
+ /** 换掉状态栏上插件的段落(按插件的 id) */
16
+ showStatus(segments: { plugin: string; text: string }[]): void;
17
+ /** 终端界面的输入框;-p 时没有 */
18
+ input?: { text(): string; insert(text: string): void; set(text: string): void };
19
+ /** 替用户提交一行;-p 时没有 */
20
+ send?(plugin: string, text: string): void;
21
+ warn(text: string): void;
22
+ /** 状态栏一段的整理(去掉控制字符、截断);返回空字符串表示去掉 */
23
+ tidy?(text: string): string;
24
+ }
25
+
26
+ export class SessionScope {
27
+ #state: ScopeState = "preparing";
28
+ readonly #host: ScopeHost;
29
+ readonly #abort = new AbortController();
30
+ /** 插件设置的状态栏段落;preparing 时先存着,activate 时显示 */
31
+ readonly #status = new Map<string, string>();
32
+ /** 已经提示过过期调用的插件,每个只提示一次 */
33
+ readonly #warned = new Set<string>();
34
+ #jade: Jade | undefined;
35
+ #disposing: Promise<string[]> | undefined;
36
+
37
+ constructor(host: ScopeHost) {
38
+ this.#host = host;
39
+ }
40
+
41
+ get state(): ScopeState {
42
+ return this.#state;
43
+ }
44
+
45
+ /** 关闭时中止:交给插件的 ctx.signal、快捷键的 signal 都是它 */
46
+ get signal(): AbortSignal {
47
+ return this.#abort.signal;
48
+ }
49
+
50
+ /** 这个作用域的插件实例;attach 之前不能用 */
51
+ get jade(): Jade {
52
+ if (!this.#jade) throw new Error("the session scope has no plugins yet");
53
+ return this.#jade;
54
+ }
55
+
56
+ /** 交给 createJade 的回调:插件的 ctx 都经过这里,按作用域的状态决定是否生效 */
57
+ get hooks() {
58
+ const host = this.#host;
59
+ return {
60
+ signal: this.signal,
61
+ onStatus: (plugin: string, text: string | undefined) => this.#setStatus(plugin, text),
62
+ input: host.input && {
63
+ text: (plugin?: string) => (this.#live(plugin, "ctx.input") ? host.input!.text() : ""),
64
+ insert: (text: string, plugin?: string) => void (this.#live(plugin, "ctx.input") && host.input!.insert(String(text))),
65
+ set: (text: string, plugin?: string) => void (this.#live(plugin, "ctx.input") && host.input!.set(String(text))),
66
+ },
67
+ send: host.send && ((plugin: string, text: string) => void (this.#live(plugin, "ctx.send") && host.send!(plugin, text))),
68
+ };
69
+ }
70
+
71
+ /** 创建好插件实例后挂上 */
72
+ attach(jade: Jade): void {
73
+ this.#jade = jade;
74
+ }
75
+
76
+ /** preparing → active:显示插件在准备期间设置的状态 */
77
+ activate(): void {
78
+ if (this.#state !== "preparing") throw new Error(`cannot activate the session scope: it is ${this.#state}`);
79
+ this.#state = "active";
80
+ this.#show();
81
+ }
82
+
83
+ /**
84
+ * → closing:中止 signal(进行中的快捷键等随之中止),之后 ctx.status、ctx.input、ctx.send 不再生效;
85
+ * dispose 完成(closed)之后还调用的才提示,那是插件忘了在 dispose 里停掉的定时器、监听。
86
+ * 不清状态栏:接着激活的作用域会换掉它;回滚时没激活过,也就没显示过
87
+ */
88
+ close(reason: string): void {
89
+ if (this.#state === "closing" || this.#state === "closed") return;
90
+ this.#state = "closing";
91
+ this.#abort.abort(new Error(reason));
92
+ }
93
+
94
+ /** 调用插件的 dispose(见 Jade.dispose),→ closed。先 close;只执行一次,返回要告诉用户的问题 */
95
+ dispose(): Promise<string[]> {
96
+ this.close("the session ended");
97
+ return (this.#disposing ??= (this.#jade ? this.#jade.dispose() : Promise.resolve([])).then((warnings) => {
98
+ this.#state = "closed";
99
+ return warnings;
100
+ }));
101
+ }
102
+
103
+ #setStatus(plugin: string, text: string | undefined) {
104
+ const line = text === undefined ? "" : (this.#host.tidy ?? ((t: string) => t.trim()))(String(text));
105
+ if (this.#state === "closing" || this.#state === "closed") {
106
+ // closing 时插件还没轮到 dispose(会话收尾还在进行),定时器再触发一次是正常的;dispose 里去掉自己的段落也正常
107
+ if (line && this.#state === "closed") this.#stale(plugin, "ctx.status", "after its session ended");
108
+ return;
109
+ }
110
+ if (line) this.#status.set(plugin, line);
111
+ else this.#status.delete(plugin);
112
+ if (this.#state === "active") this.#show();
113
+ }
114
+
115
+ #show() {
116
+ this.#host.showStatus([...this.#status].map(([plugin, text]) => ({ plugin, text })));
117
+ }
118
+
119
+ /** 是否 active。preparing 和 closed 时提示一次;closing 时插件还没轮到 dispose,不提示 */
120
+ #live(plugin: string | undefined, what: string): boolean {
121
+ if (this.#state === "active") return true;
122
+ if (this.#state === "preparing") this.#stale(plugin, what, "before its session started");
123
+ else if (this.#state === "closed") this.#stale(plugin, what, "after its session ended");
124
+ return false;
125
+ }
126
+
127
+ #stale(plugin: string | undefined, what: string, when: string) {
128
+ const key = plugin ?? "";
129
+ if (this.#warned.has(key)) return;
130
+ this.#warned.add(key);
131
+ const who = plugin ? `plugin ${plugin}` : "a plugin";
132
+ const fix = when.startsWith("after") ? "; stop timers and listeners in dispose, or when ctx.signal aborts" : "";
133
+ this.#host.warn(`${who} used ${what} ${when}, so it was ignored${fix}`);
134
+ }
135
+ }
package/src/sessions.ts CHANGED
@@ -59,3 +59,20 @@ export async function discardIfEmpty(store: LogStore & { dir: string }, sessionI
59
59
  await rm(path.join(store.dir, `${sessionId}.jsonl`), { force: true });
60
60
  return true;
61
61
  }
62
+
63
+ /** id 等于 arg 或以它开头的唯一一个会话;都不是时原样返回,交给 Runtime.resume 去找 */
64
+ export function matchSession(entries: { id: string }[], arg: string): string {
65
+ const hits = entries.filter((s) => s.id.startsWith(arg));
66
+ return hits.find((s) => s.id === arg)?.id ?? (hits.length === 1 ? hits[0]!.id : arg);
67
+ }
68
+
69
+ /** 显示用的相对时间 */
70
+ export function ago(iso: string, now = Date.now()): string {
71
+ const s = (now - Date.parse(iso)) / 1000;
72
+ if (!Number.isFinite(s)) return iso;
73
+ if (s < 60) return "just now";
74
+ if (s < 3600) return `${Math.floor(s / 60)} min ago`;
75
+ if (s < 86400) return `${Math.floor(s / 3600)} h ago`;
76
+ if (s < 86400 * 7) return `${Math.floor(s / 86400)} d ago`;
77
+ return iso.slice(0, 10);
78
+ }
package/src/sys.ts CHANGED
@@ -82,8 +82,25 @@ export async function text(stream: AsyncIterable<Uint8Array>): Promise<string> {
82
82
  return out + decoder.decode();
83
83
  }
84
84
 
85
- /** 在 PATH 里找可执行文件,找不到返回 undefined。Windows 上按 PATHEXT 补扩展名;带路径分隔符时只检查那个文件 */
85
+ /** which 的结果,按 PATH 和 PATHEXT 记;找不到的过一会儿再查(会话中途装上的工具能用上) */
86
+ const found = new Map<string, { file: string | undefined; at: number }>();
87
+ const MISS_TTL_MS = 30_000;
88
+
89
+ /**
90
+ * 在 PATH 里找可执行文件,找不到返回 undefined。Windows 上按 PATHEXT 补扩展名;带路径分隔符时只检查那个文件。
91
+ * 结果会记住:编辑后检查每批修改都要找 ruff、go,每次同步扫一遍 PATH 要几毫秒,期间事件循环停住
92
+ */
86
93
  export function which(bin: string): string | undefined {
94
+ if (bin.includes("/") || (process.platform === "win32" && bin.includes("\\"))) return lookup(bin);
95
+ const key = `${bin}\0${process.env.PATH ?? process.env.Path ?? ""}\0${process.env.PATHEXT ?? ""}`;
96
+ const hit = found.get(key);
97
+ if (hit && (hit.file !== undefined || Date.now() - hit.at < MISS_TTL_MS)) return hit.file;
98
+ const file = lookup(bin);
99
+ found.set(key, { file, at: Date.now() });
100
+ return file;
101
+ }
102
+
103
+ function lookup(bin: string): string | undefined {
87
104
  const win = process.platform === "win32";
88
105
  const exts = win ? ["", ...(process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
89
106
  const ok = (file: string) => {
@@ -0,0 +1,72 @@
1
+ // ask_user 工具:模型拿不准、而答案会改变它要做的事时,先问用户再动手。
2
+ //
3
+ // 每个问题给几个选项让用户选,也可以自己输入回答。怎么显示由宿主决定(ask);
4
+ // 不能交互(-p、非终端)时直接返回"用户不在",让模型按合理的假设继续并说明假设。
5
+
6
+ import type { Tool } from "uncarved";
7
+
8
+ export interface Question {
9
+ question: string;
10
+ options: { label: string; description?: string }[];
11
+ }
12
+
13
+ /** 宿主问用户:每个问题一个回答;用户取消时返回 undefined */
14
+ export type AskUser = (questions: Question[], signal: AbortSignal) => Promise<string[] | undefined>;
15
+
16
+ const MAX_QUESTIONS = 4;
17
+
18
+ export function askUserTool(ask: AskUser): Tool {
19
+ return {
20
+ name: "ask_user",
21
+ description:
22
+ "Ask the user one to four questions and wait for the answers. Use it before starting work when the request is ambiguous in a way that changes what you would do " +
23
+ "(scope, approach, a trade-off or preference only the user can decide). Do not ask about things you can find out from the code, docs or tools, " +
24
+ "or that have a sensible default (pick it and say so). Each question offers 2-4 options; the user can also type their own answer. " +
25
+ "Put your recommended option first.",
26
+ inputSchema: {
27
+ type: "object",
28
+ properties: {
29
+ questions: {
30
+ type: "array",
31
+ items: {
32
+ type: "object",
33
+ properties: {
34
+ question: { type: "string", description: "The complete question, ending with a question mark" },
35
+ options: {
36
+ type: "array",
37
+ items: {
38
+ type: "object",
39
+ properties: {
40
+ label: { type: "string", description: "1-5 words" },
41
+ description: { type: "string", description: "What choosing it means, trade-offs" },
42
+ },
43
+ required: ["label"],
44
+ additionalProperties: false,
45
+ },
46
+ },
47
+ },
48
+ required: ["question", "options"],
49
+ additionalProperties: false,
50
+ },
51
+ },
52
+ },
53
+ required: ["questions"],
54
+ additionalProperties: false,
55
+ },
56
+ // 不碰文件和进程:所有模式(包括 plan)都不用批准
57
+ effect: "read",
58
+ concurrency: "exclusive",
59
+ idempotent: false,
60
+ async execute(input, ctx) {
61
+ const { questions } = input as { questions: Question[] };
62
+ if (questions.length === 0 || questions.length > MAX_QUESTIONS) return { content: `questions must have 1-${MAX_QUESTIONS} items`, isError: true };
63
+ const bad = questions.find((q) => q.options.length < 2 || q.options.length > 4);
64
+ if (bad) return { content: `each question needs 2-4 options ("${bad.question}" has ${bad.options.length})`, isError: true };
65
+ const answers = await ask(questions, ctx.signal);
66
+ if (answers === undefined) {
67
+ return { content: "The user dismissed the questions without answering. Do not ask again: proceed with your best judgment and state your assumptions, or end your turn." };
68
+ }
69
+ return { content: questions.map((q, i) => `Q: ${q.question}\nA: ${answers[i] ?? "(no answer)"}`).join("\n\n") };
70
+ },
71
+ };
72
+ }