@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
@@ -59,7 +59,7 @@ export declare function removePlugin(name: string, pluginsDir: string): Promise<
59
59
  export declare function readRecords(pluginsDir: string): Promise<Record<string, InstallRecord>>;
60
60
  /** $JADE_HOME/plugins.json:只有用户层能停用插件,仓库不能停用用户的插件或内置插件 */
61
61
  export interface PluginSettings {
62
- /** 停用的插件:内置插件的 id(jade/web),或者插件的目录名 */
62
+ /** 停用的插件的 id:内置插件(jade/web)或第三方插件(plugin.json 的 id) */
63
63
  disabled: string[];
64
64
  }
65
65
  export declare function readPluginSettings(home: string): Promise<PluginSettings>;
@@ -1,6 +1,10 @@
1
1
  import type { Choice } from "../ui/screen.ts";
2
- import { type Awaitable, type Plugin, type TrustStore } from "uncarved";
2
+ import { type Awaitable, type Message, type Plugin, type TrustStore, type Usage } from "uncarved";
3
3
  import type { RunCommand } from "../tools/shell.ts";
4
+ import type { Checkpoint } from "../tools/checkpoint.ts";
5
+ import type { ProviderDef } from "../provider.ts";
6
+ /** 插件提供的模型服务,见 provider.ts 的 ProviderDef */
7
+ export type PluginProvider = ProviderDef;
4
8
  export declare const JADE_VERSION: string;
5
9
  export type PluginLayer = "user" | "project";
6
10
  /** jade 创建插件实例时传给工厂函数的参数 */
@@ -16,10 +20,135 @@ export interface JadePluginContext {
16
20
  /** 插件自己的目录 */
17
21
  dir: string;
18
22
  layer: PluginLayer;
19
- /** 同 uncarved 的 definePlugin:补上 kernel 和 hooks 用到的 needs。项目层插件通常 import 不到 uncarved,用这个 */
20
- definePlugin: <T extends JadePluginDraft>(draft: T) => T & JadePlugin;
23
+ /**
24
+ * 同 uncarved 的 definePlugin:补上 kernel 和 hooks 用到的 needs,另外 id、version 不写时用 plugin.json 里的。
25
+ * 项目层插件通常 import 不到 uncarved,用这个
26
+ */
27
+ definePlugin: <T extends ContextPluginDraft>(draft: T) => T & JadePlugin;
21
28
  /** 用 jade 的 shell 执行命令,超时或中断时连同子进程一起结束;找不到 shell 时没有 */
22
29
  run?: RunCommand;
30
+ /**
31
+ * 用当前配置的模型发一次请求:不带工具,不记进会话,和会话共用限速和重试;用户切换模型后用新的。
32
+ * 返回回复的文字;onText 收到流式输出的片段,拿到想要的内容后可以用 signal 中止
33
+ */
34
+ complete(req: CompleteRequest, signal: AbortSignal): Promise<CompleteResult>;
35
+ /** 设置状态栏上本插件的那一段文字(一行,过长时截断,窗口窄时先被去掉);undefined 去掉 */
36
+ status(text: string | undefined): void;
37
+ /** 文件快照:写文件的工具写之前记下原内容,/undo 据此恢复。见 FileCheckpoints */
38
+ checkpoints: FileCheckpoints;
39
+ /** 终端界面的输入框(见 InputControl)。只给用户层插件;非交互运行(-p)时没有 */
40
+ input?: InputControl;
41
+ /**
42
+ * 替用户提交一行,和在输入框里按回车一样:/ 开头的是命令;模型正忙时排队。
43
+ * 对话里会注明是哪个插件发的。只给用户层插件(它能替用户说话);非交互运行(-p)时没有
44
+ */
45
+ send?(text: string): void;
46
+ /**
47
+ * 这套实例的会话结束(换会话、重新加载、退出)时中止,在 dispose 之前。
48
+ * 工厂函数里开的定时器、监听可以挂在它上面关掉:ctx.signal.addEventListener("abort", () => clearInterval(timer))
49
+ */
50
+ signal: AbortSignal;
51
+ }
52
+ /** 宿主这边的输入框:多了一个参数,是调用的插件的 id(宿主据此提示过期的调用) */
53
+ export interface HostInput {
54
+ text(plugin?: string): string;
55
+ insert(text: string, plugin?: string): void;
56
+ set(text: string, plugin?: string): void;
57
+ }
58
+ /** 输入框里用户还没提交的文字 */
59
+ export interface InputControl {
60
+ /** 现在的文字 */
61
+ text(): string;
62
+ /** 在光标处插入,光标移到插入的文字后面 */
63
+ insert(text: string): void;
64
+ /** 换掉全部文字,光标放到末尾;空字符串清空 */
65
+ set(text: string): void;
66
+ }
67
+ /**
68
+ * 一个工具在对话里怎么显示,不影响发给模型的内容。只能为本插件 tools 里的工具注册:
69
+ * 别的工具(jade 自己的、MCP 的、别的插件的)的显示,特别是审批时的预览,插件改不了。
70
+ * 每个函数都可以不写;返回 undefined 或出错时用 jade 默认的显示(出错时提示一次)
71
+ */
72
+ export interface ToolRenderer {
73
+ tool: string;
74
+ /** 调用行 "● 工具名(…)" 括号里的摘要,只显示第一行;默认是 path 参数或参数的 JSON */
75
+ summary?(input: unknown): string | undefined;
76
+ /** 摘要省略了的参数(例如很长的命令),点击调用行展开后显示在最前面,可以多行;默认没有 */
77
+ details?(input: unknown): string | undefined;
78
+ /** 请用户批准时显示的预览,可以多行、带 ANSI 颜色;默认是参数的 JSON */
79
+ preview?(input: unknown): Awaitable<string | undefined>;
80
+ /**
81
+ * 工具执行之前同步调用(例如记下修改前的文件,好在结果里显示 diff),返回值交给 result 的 before。
82
+ * 用户拒绝的调用、重新显示的历史不调用
83
+ */
84
+ before?(input: unknown): unknown;
85
+ /**
86
+ * 结果:line 接在调用行的 "⎿ " 后面(一行),details 是点击展开后的内容(可以多行);
87
+ * 默认显示结果文字的第一行,多出的行折叠起来
88
+ */
89
+ result?(r: {
90
+ input: unknown;
91
+ text: string;
92
+ isError: boolean;
93
+ before?: unknown;
94
+ }): {
95
+ line: string;
96
+ details?: string;
97
+ } | undefined;
98
+ }
99
+ /** 插件 dispose 的时限:超过了不再等,显示警告 */
100
+ export declare const DISPOSE_TIMEOUT_MS = 5000;
101
+ /** "ctrl+<字母>" 或 "alt+<字母或数字>" */
102
+ export declare const KEY_SPEC: RegExp;
103
+ /**
104
+ * jade 自己用的键,插件不能用:编辑(ctrl+a/e/d/w/u/k,alt+f)、搜索历史(ctrl+r)、重画(ctrl+l)、展开(ctrl+o)、
105
+ * 中断和退出(ctrl+c),以及终端里等同于退格、Tab、回车的 ctrl+h/i/j/m
106
+ */
107
+ export declare const RESERVED_KEYS: ReadonlySet<string>;
108
+ /** 插件的快捷键:输入框有焦点时按下(模型工作时也算)调用 run;弹出对话框时不响应 */
109
+ export interface PluginKey {
110
+ /** 见 KEY_SPEC;不分大小写,不能是 RESERVED_KEYS 里的 */
111
+ key: string;
112
+ /** /help 里显示 */
113
+ description?: string;
114
+ /**
115
+ * 出错时在对话里显示警告。要改输入框、发消息用插件上下文的 input、send。
116
+ * key 是按下的键,规范成小写(例如 "ctrl+g");换会话、退出时 signal 中止。
117
+ * 上一次还没执行完时再按,会再调用一次(切换式的键要自己记住状态)
118
+ */
119
+ run(ctx: {
120
+ key: string;
121
+ sessionId: string;
122
+ signal: AbortSignal;
123
+ }): Awaitable<void>;
124
+ }
125
+ /**
126
+ * 文件快照,按会话存放,不进日志。jade/fs 的写文件工具和 jade/undo 都只用这个接口:
127
+ * 第三方插件的工具写文件前也调用 save,/undo 就能撤销它的修改
128
+ */
129
+ export interface FileCheckpoints {
130
+ /**
131
+ * 写文件之前调用(用工具调用的 ctx.sessionId、ctx.toolUseId)。path 是绝对路径;before 是原内容,null 表示文件原本不存在;
132
+ * afterHash 是写入后内容(UTF-8)的 sha256 十六进制,撤销前用它判断文件之后有没有被别人改过
133
+ */
134
+ save(sessionId: string, cp: Omit<Checkpoint, "at">): Promise<void>;
135
+ /** 会话的全部快照,最新的在前 */
136
+ list(sessionId: string): Promise<Checkpoint[]>;
137
+ /** 文件现在的内容还是不是这次写入后的样子 */
138
+ unchangedSince(cp: Checkpoint): Promise<boolean>;
139
+ /** 把文件恢复成 before(before 为 null 时删掉文件) */
140
+ restore(cp: Checkpoint): Promise<void>;
141
+ }
142
+ export interface CompleteRequest {
143
+ system?: string;
144
+ prompt: string;
145
+ onText?(delta: string): void;
146
+ }
147
+ export interface CompleteResult {
148
+ text: string;
149
+ /** 实际回复的模型 */
150
+ model: string;
151
+ usage?: Usage;
23
152
  }
24
153
  /** 斜杠命令和用户交互用的界面。非交互运行(-p)时 select / input 直接返回 undefined */
25
154
  export interface CommandUI {
@@ -34,6 +163,7 @@ export interface CommandUI {
34
163
  input(title: string, opts?: {
35
164
  initial?: string;
36
165
  placeholder?: string;
166
+ mask?: boolean;
37
167
  }): Promise<string | undefined>;
38
168
  }
39
169
  export interface PluginCommandContext {
@@ -46,6 +176,39 @@ export interface PluginCommandContext {
46
176
  ui: CommandUI;
47
177
  /** 附在用户下一条消息前面告诉模型的话,例如"用户删掉了某条记忆" */
48
178
  note(text: string): void;
179
+ /** 操作会话(见 SessionControl);instant 的命令在模型工作时执行,没有这个字段 */
180
+ session?: SessionControl;
181
+ }
182
+ /** 这个目录里的一个会话(会话索引里的一项) */
183
+ export interface SessionSummary {
184
+ id: string;
185
+ /** 第一条消息的开头 */
186
+ title: string;
187
+ /** 最近一次使用的时间(ISO) */
188
+ at: string;
189
+ }
190
+ /**
191
+ * 斜杠命令操作会话用的接口,jade 自己的 /clear、/resume、/retry、/undo 也只用它。
192
+ * 换会话之后它指向新的会话:之后的 messages()、record() 都是新会话的
193
+ */
194
+ export interface SessionControl {
195
+ /** 当前会话的消息(拷贝) */
196
+ messages(): Message[];
197
+ /** 写一项派生数据进日志(derived.recorded),恢复会话后仍在。key 只能是插件的 id 或以 "<id>/" 开头 */
198
+ record(key: string, value: unknown): Promise<void>;
199
+ /** 这个工作目录里的会话,最近用过的在前 */
200
+ list(): Promise<SessionSummary[]>;
201
+ /** 开始新会话,当前的保留、可以恢复 */
202
+ clear(): Promise<void>;
203
+ /** 换到会话 id;恢复失败时留在当前会话并显示原因 */
204
+ resume(id: string): Promise<void>;
205
+ /** 上一次请求在模型回复之前就失败了时重新请求,不用再发消息;没有可重试的返回 false */
206
+ retry(): Promise<boolean>;
207
+ /**
208
+ * 用新的插件实例继续当前会话,对话内容不变:工具和系统提示词按现在的配置重新生成(例如改了 $JADE_HOME/.env 之后)。
209
+ * 调用它的插件实例随之被换掉,之后不要再用它的状态
210
+ */
211
+ reload(): Promise<void>;
49
212
  }
50
213
  /** 字符串:显示给用户;{ prompt }:作为用户消息发给模型;不返回:什么也不做 */
51
214
  export type PluginCommandResult = string | {
@@ -67,26 +230,51 @@ export interface PluginCommand {
67
230
  /** jade 的插件:内核的 Plugin,外加 jade 认识的扩展字段 */
68
231
  export interface JadePlugin extends Plugin {
69
232
  commands?: PluginCommand[];
233
+ /** 快捷键,见 PluginKey;和排在前面的插件用了同一个键时忽略 */
234
+ keys?: PluginKey[];
235
+ /** 本插件的工具在对话里怎么显示,见 ToolRenderer */
236
+ renderers?: ToolRenderer[];
70
237
  /**
71
- * 代替的内置插件的 id(例如 "jade/web"):被代替的内置插件不再加载,它的工具名可以由本插件提供。
72
- * jade/policy 不能代替
238
+ * jade 不再用这个实例时调用一次:换会话(/clear、/resume)、重新加载、退出,以及创建了却没用上的实例(例如按 id 停用的)。
239
+ * 在会话的收尾(session.detached 的 hook)之后。停掉定时器、关掉连接和监听;
240
+ * 之后 ctx.status、ctx.input、ctx.send 不再起作用。限时 DISPOSE_TIMEOUT_MS,出错或超时只显示警告
73
241
  */
74
- replaces?: string[];
242
+ dispose?(): Awaitable<void>;
75
243
  }
76
244
  /** definePlugin 的输入:kernel、needs 可以省略 */
77
245
  export type JadePluginDraft = Omit<JadePlugin, "kernel" | "needs"> & {
78
246
  kernel?: string;
79
247
  needs?: string[];
80
248
  };
249
+ /** 插件上下文里 definePlugin 的输入:id、version 也可以省略,用 plugin.json 里的 */
250
+ export type ContextPluginDraft = Omit<JadePluginDraft, "id" | "version"> & {
251
+ id?: string;
252
+ version?: string;
253
+ };
81
254
  export type JadePluginFactory = (ctx: JadePluginContext) => Awaitable<JadePlugin>;
82
- /** 宿主(createJade)提供的那部分上下文 */
83
- export type HostContext = Omit<JadePluginContext, "dir" | "layer">;
84
- /** plugin.json,可以没有 */
255
+ /** 宿主(createJade)提供的那部分上下文;status、send 由加载器按插件的 id 转给宿主,input、send 只转给用户层插件 */
256
+ export type HostContext = Omit<JadePluginContext, "dir" | "layer" | "status" | "send" | "definePlugin" | "input"> & {
257
+ definePlugin: <T extends JadePluginDraft>(draft: T) => T & JadePlugin;
258
+ status(plugin: string, text: string | undefined): void;
259
+ send?(plugin: string, text: string): void;
260
+ input?: HostInput;
261
+ };
262
+ /** plugin.json;只带内容的插件可以没有 */
85
263
  export interface PluginJson {
264
+ /**
265
+ * 插件的 id,全局唯一,建议 "作者/名字"。有代码的插件必须写:jade 不执行代码就能认出插件(按 id 停用、检查重复),
266
+ * 插件实例的 id 必须和它相同。只带内容的插件不写时用目录名
267
+ */
268
+ id?: string;
86
269
  /** jade plugin add 安装时用作目录名;/plugins 显示 */
87
270
  name?: string;
88
271
  version?: string;
89
272
  description?: string;
273
+ /**
274
+ * 代替的内置插件的 id(例如 ["jade/web"]):被代替的内置插件不再加载,它的工具名可以由本插件提供。
275
+ * 写在清单里,不执行代码就能知道;jade/policy 不能代替。只有带代码的插件可以写
276
+ */
277
+ replaces?: string[];
90
278
  /** 进程内插件的入口,默认依次找 index.ts、index.js、index.mjs */
91
279
  entry?: string;
92
280
  /** 进程外插件的启动命令;"./"、"../" 开头的相对于插件目录 */
@@ -114,9 +302,13 @@ export interface PluginBundle {
114
302
  }
115
303
  /** 不执行代码就能知道的插件信息 */
116
304
  export interface PluginInfo {
305
+ /** plugin.json 的 id;只带内容的插件可以没有(用目录名,见 pluginId) */
306
+ id?: string;
117
307
  name?: string;
118
308
  version?: string;
119
309
  description?: string;
310
+ /** plugin.json 的 replaces */
311
+ replaces?: string[];
120
312
  /** module:TS/JS 模块;process:plugin.json 写了 command;content:没有代码,只有 skills、命令、MCP 配置 */
121
313
  kind: "module" | "process" | "content";
122
314
  /** module 的入口文件(相对于插件目录) */
@@ -130,13 +322,30 @@ export interface FoundPlugin {
130
322
  dir: string;
131
323
  layer: PluginLayer;
132
324
  }
325
+ /** 读过清单、确定了 id 的插件,还没有执行它的代码 */
326
+ export interface ResolvedPlugin extends FoundPlugin {
327
+ id: string;
328
+ info: PluginInfo;
329
+ }
133
330
  export interface LoadedPlugin extends FoundPlugin {
331
+ /** 插件的 id(plugin.json 的 id;只带内容的插件没写时是目录名)。实例的 id 必须和它相同 */
332
+ id: string;
134
333
  kind: PluginInfo["kind"];
135
334
  /** 模块入口(相对于插件目录),或者进程外插件的启动命令;只有内容的插件为空字符串 */
136
335
  entry: string;
137
336
  info: PluginInfo;
138
337
  /** 创建一套实例,每个会话调用一次;进程外插件只有一个进程,每次返回同一个对象。只有内容的插件没有 */
139
338
  create?(host: HostContext): Promise<JadePlugin>;
339
+ /**
340
+ * 进程外插件:这一套实例的快捷键和命令,按 initialize 回复里的清单生成、绑定到这一套的 ctx。
341
+ * 进程(create 返回的对象)在会话之间共用,所以它们不挂在进程对象上,见 docs/design/jade-plugin-lifecycle.md 第 6 节
342
+ */
343
+ adapters?(host: HostContext): Pick<JadePlugin, "keys" | "commands">;
344
+ /**
345
+ * 插件模块导出的模型服务(export const providers),用 JADE_PROVIDER=<kind> 选择;只认用户层的,项目层的读出来只为提示。
346
+ * 不属于哪套插件实例:加载时就读到,启动时注册一次,所有会话共用。还没检查,见 collectProviders
347
+ */
348
+ providers?: unknown;
140
349
  /** 进程外插件:结束进程 */
141
350
  close?(): Promise<void>;
142
351
  /** 进程外插件的状态:退出信息和最近的 stderr */
@@ -172,11 +381,30 @@ export declare function discoverPlugins(opts: {
172
381
  root: string;
173
382
  cwd: string;
174
383
  }): Promise<FoundPlugin[]>;
175
- export declare function loadPlugin(found: FoundPlugin, opts: LoadOptions): Promise<LoadedPlugin>;
384
+ /**
385
+ * 读插件的清单,确定 id,不执行代码:去掉按 id 停用的、id 重复的(排在后面的跳过)、用了内置插件 id 的。
386
+ * 清单读不了的放进 broken,由宿主报告
387
+ */
388
+ export declare function resolvePlugins(found: FoundPlugin[], disabled: ReadonlySet<string>): Promise<{
389
+ plugins: ResolvedPlugin[];
390
+ broken: {
391
+ found: FoundPlugin;
392
+ error: unknown;
393
+ }[];
394
+ warnings: string[];
395
+ }>;
396
+ /** 插件的 id:plugin.json 的 id;只带内容的插件没写时用目录名 */
397
+ export declare function pluginId(found: FoundPlugin, info: PluginInfo): string;
398
+ /** 加载插件:读清单(宿主已经用 resolvePlugins 读过时直接用),项目层的先请用户确认,然后 import 模块或启动进程 */
399
+ export declare function loadPlugin(found: FoundPlugin & {
400
+ info?: PluginInfo;
401
+ }, opts: LoadOptions): Promise<LoadedPlugin>;
176
402
  /**
177
403
  * 读插件目录,不执行其中的代码:jade plugin add 用它检查和命名,loadPlugin 用它决定怎么加载。
178
404
  * 什么都提供不了的目录抛出错误
179
405
  */
180
406
  export declare function inspectPlugin(dir: string): Promise<PluginInfo>;
407
+ /** 插件 id:几段字母、数字和 . _ - @,用 / 分隔 */
408
+ export declare const PLUGIN_ID: RegExp;
181
409
  /** 斜杠命令名:字母数字开头,之后可以有 - 和 _ */
182
410
  export declare const COMMAND_NAME: RegExp;
@@ -4,7 +4,7 @@
4
4
  // 一个目录就是一个插件,两种形式:
5
5
  // - 进程内:TypeScript / JavaScript 模块,默认导出插件对象,或者返回插件对象的工厂函数(每个会话调用一次);
6
6
  // - 进程外:plugin.json 里写了 command,jade 启动这个进程,经 stdio 用 JSON-RPC 通信(@uncarved/plugin-stdio),
7
- // 可以用任何语言编写,只能提供 hook。
7
+ // 可以用任何语言编写,可以提供 hook、斜杠命令和快捷键。
8
8
  // 两种形式之外(或者没有代码时),插件目录还可以带上内容:skills/、commands/、mcp.json(或 .mcp.json),
9
9
  // 和 jade 自己的 skills、自定义命令、MCP 配置格式相同。也认 Claude Code 插件的 .claude-plugin/plugin.json。
10
10
  // 项目层插件随仓库分发,首次加载和内容变化后要用户确认(宪法 7.1);用户层插件是用户自己装的,不再确认。
@@ -25,6 +25,15 @@ import { spawnPlugin } from "@uncarved/plugin-stdio";
25
25
  import { definePlugin, loadProjectPluginFactory } from "uncarved";
26
26
  import { projectDirs } from "../commands.js";
27
27
  export const JADE_VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
28
+ /** 插件 dispose 的时限:超过了不再等,显示警告 */
29
+ export const DISPOSE_TIMEOUT_MS = 5000;
30
+ /** "ctrl+<字母>" 或 "alt+<字母或数字>" */
31
+ export const KEY_SPEC = /^(ctrl\+[a-z]|alt\+[a-z0-9])$/;
32
+ /**
33
+ * jade 自己用的键,插件不能用:编辑(ctrl+a/e/d/w/u/k,alt+f)、搜索历史(ctrl+r)、重画(ctrl+l)、展开(ctrl+o)、
34
+ * 中断和退出(ctrl+c),以及终端里等同于退格、Tab、回车的 ctrl+h/i/j/m
35
+ */
36
+ export const RESERVED_KEYS = new Set([..."acdehijklmoruw"].map((c) => `ctrl+${c}`).concat("alt+f"));
28
37
  const ENTRIES = ["index.ts", "index.js", "index.mjs"];
29
38
  const STDERR_LINES = 20;
30
39
  /** 用户层在前;项目层从仓库根目录往下,同名目录近的覆盖远的 */
@@ -51,28 +60,74 @@ async function scan(root, layer, out) {
51
60
  out.set(`${layer}:${name}`, { name, dir, layer });
52
61
  }
53
62
  }
63
+ /**
64
+ * 读插件的清单,确定 id,不执行代码:去掉按 id 停用的、id 重复的(排在后面的跳过)、用了内置插件 id 的。
65
+ * 清单读不了的放进 broken,由宿主报告
66
+ */
67
+ export async function resolvePlugins(found, disabled) {
68
+ const read = await Promise.all(found.map((f) => inspectPlugin(f.dir).then((info) => ({ f, info }), (error) => ({ f, error }))));
69
+ const plugins = [];
70
+ const broken = [];
71
+ const warnings = [];
72
+ const seen = new Map();
73
+ for (const r of read) {
74
+ if (!("info" in r)) {
75
+ broken.push({ found: r.f, error: r.error });
76
+ continue;
77
+ }
78
+ const id = pluginId(r.f, r.info);
79
+ if (disabled.has(id))
80
+ continue;
81
+ // jade、jade/… 留给内置插件:会话里记的键按 id 划分;代替内置插件用 plugin.json 的 replaces
82
+ if (id === "jade" || id.startsWith("jade/")) {
83
+ warnings.push(`plugin ${r.f.dir} is skipped: the id ${id} is reserved for jade's built-in plugins (use "replaces" in plugin.json to stand in for one)`);
84
+ continue;
85
+ }
86
+ const first = seen.get(id);
87
+ if (first) {
88
+ warnings.push(`plugin ${r.f.dir} is skipped: plugin ${first.dir} already has the id ${id}`);
89
+ continue;
90
+ }
91
+ seen.set(id, r.f);
92
+ plugins.push({ ...r.f, id, info: r.info });
93
+ }
94
+ return { plugins, broken, warnings };
95
+ }
96
+ /** 插件的 id:plugin.json 的 id;只带内容的插件没写时用目录名 */
97
+ export function pluginId(found, info) {
98
+ return info.id ?? found.name;
99
+ }
100
+ /** 加载插件:读清单(宿主已经用 resolvePlugins 读过时直接用),项目层的先请用户确认,然后 import 模块或启动进程 */
54
101
  export async function loadPlugin(found, opts) {
55
- const info = await inspectPlugin(found.dir);
102
+ const info = found.info ?? (await inspectPlugin(found.dir));
103
+ const base = { name: found.name, dir: found.dir, layer: found.layer, id: pluginId(found, info) };
56
104
  if (info.kind === "process")
57
- return loadProcess(found, info, opts);
105
+ return loadProcess(base, info, opts);
58
106
  if (info.kind === "content")
59
- return { ...found, kind: "content", entry: "", info };
107
+ return { ...base, kind: "content", entry: "", info };
60
108
  const entry = info.entry;
61
- const ctx = (host) => ({ ...host, dir: found.dir, layer: found.layer });
109
+ const ctx = (host) => pluginContext(base, info, host);
62
110
  if (found.layer === "project") {
63
111
  // 内核负责:先哈希整个目录、确认,再 import;检查 import 不越出插件目录
64
112
  const make = await loadProjectPluginFactory(found.dir, { trust: opts.trust, confirm: opts.confirm, entry });
65
- return { ...found, kind: "module", entry, info, create: async (host) => (await make(ctx(host))) };
113
+ // 内核刚 import 过入口模块:用和它相同的 URL 再 import 只取缓存,不会再执行。
114
+ // 项目层插件导出的 providers 不认,读出来是为了提示用户(见 collectProviders),而不是静默忽略
115
+ const root = path.resolve(found.dir);
116
+ const rel = path.relative(root, path.resolve(root, entry)).split(path.sep).join("/");
117
+ const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(path.join(root, rel)).href)));
118
+ return { ...base, kind: "module", entry, info, providers: mod.providers, create: async (host) => (await make(ctx(host))) };
66
119
  }
67
120
  const file = path.resolve(found.dir, entry);
68
- const exported = (await import(__rewriteRelativeImportExtension(pathToFileURL(file).href))).default;
121
+ const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(file).href)));
122
+ const exported = mod.default;
69
123
  if (typeof exported !== "function" && !isPlugin(exported))
70
124
  throw new Error("default export is neither a plugin nor a function returning one");
71
125
  return {
72
- ...found,
126
+ ...base,
73
127
  kind: "module",
74
128
  entry,
75
129
  info,
130
+ providers: mod.providers,
76
131
  async create(host) {
77
132
  const made = typeof exported === "function" ? await exported(ctx(host)) : exported;
78
133
  if (!isPlugin(made))
@@ -81,6 +136,27 @@ export async function loadPlugin(found, opts) {
81
136
  },
82
137
  };
83
138
  }
139
+ /** 宿主给的上下文换成某个插件的:输入框和替用户发送只给用户层插件;definePlugin 补上清单里的 id、version */
140
+ function pluginContext(found, info, { input, send, definePlugin, ...host }) {
141
+ return {
142
+ ...host,
143
+ ...(found.layer === "user"
144
+ ? {
145
+ input: input && { text: () => input.text(found.id), insert: (text) => input.insert(text, found.id), set: (text) => input.set(text, found.id) },
146
+ send: send && ((text) => send(found.id, text)),
147
+ }
148
+ : {}),
149
+ definePlugin: (draft) => {
150
+ const version = draft.version ?? info.version;
151
+ if (version === undefined)
152
+ throw new Error('the plugin has no version: add "version" to plugin.json');
153
+ return definePlugin({ ...draft, id: draft.id ?? found.id, version });
154
+ },
155
+ dir: found.dir,
156
+ layer: found.layer,
157
+ status: (text) => host.status(found.id, text),
158
+ };
159
+ }
84
160
  async function loadProcess(found, info, opts) {
85
161
  const json = info.json;
86
162
  // Windows 上相对路径的命令按 jade 的工作目录查找,而不是子进程的,所以先换成绝对路径
@@ -104,12 +180,21 @@ async function loadProcess(found, info, opts) {
104
180
  status.stderr.splice(0, Math.max(0, status.stderr.length - STDERR_LINES));
105
181
  },
106
182
  });
183
+ if (proc.id !== found.id) {
184
+ await proc.close().catch(() => { });
185
+ throw new Error(`its id ${JSON.stringify(proc.id)} (from initialize) does not match "id" in plugin.json (${found.id})`);
186
+ }
107
187
  const loaded = {
108
188
  ...found,
109
189
  kind: "process",
110
190
  entry: shown,
111
191
  info,
192
+ // 原样返回:内核只认 spawnPlugin 返回的那个项目层插件对象(宪法 7.1);这个对象在会话之间共用,不往上挂会话的东西
112
193
  create: async () => proc,
194
+ adapters: (host) => ({
195
+ commands: proc.manifest.commands === undefined ? undefined : processCommands(proc),
196
+ keys: proc.manifest.keys === undefined ? undefined : processKeys(proc, pluginContext(found, info, host)),
197
+ }),
113
198
  close: () => proc.close(),
114
199
  process: status,
115
200
  };
@@ -126,6 +211,57 @@ async function loadProcess(found, info, opts) {
126
211
  });
127
212
  return loaded;
128
213
  }
214
+ /**
215
+ * 进程外插件在 initialize 的回复里声明的斜杠命令。执行时发 jade/command { name, args, sessionId, cwd },
216
+ * 回复 { text } 显示给用户,{ prompt } 作为用户消息发给模型,{} 什么都不做。
217
+ * 名字等字段不对的由 createExtensions 统一提示
218
+ */
219
+ function processCommands(proc) {
220
+ // 不是数组时当作一个没有名字的命令,好让 createExtensions 提示
221
+ const list = (Array.isArray(proc.manifest.commands) ? proc.manifest.commands : [{}]);
222
+ const str = (v) => (typeof v === "string" ? v : undefined);
223
+ return list.map((c) => {
224
+ const name = c && typeof c === "object" ? c.name : undefined;
225
+ return {
226
+ name: name,
227
+ description: str(c?.description),
228
+ args: str(c?.args),
229
+ instant: c?.instant === true,
230
+ run: async (args, ctx) => {
231
+ const reply = (await proc.request("jade/command", { name, args, sessionId: ctx.sessionId, cwd: ctx.cwd }, ctx.signal));
232
+ if (typeof reply?.prompt === "string")
233
+ return { prompt: reply.prompt };
234
+ if (typeof reply?.text === "string")
235
+ return reply.text;
236
+ return undefined;
237
+ },
238
+ };
239
+ });
240
+ }
241
+ /**
242
+ * 进程外插件在 initialize 的回复里声明的快捷键。按下时发 jade/key { key, sessionId }(key 是规范成小写的键名,
243
+ * 换会话、退出时发 $/cancel 取消),用户层插件还带上输入框的内容 text;
244
+ * 用户层插件可以回复 { set } 替换输入框、{ insert } 在光标处插入、{ send } 替用户发送,项目层插件的这些字段不起作用。
245
+ * 键名等字段不对的由 createExtensions 统一提示
246
+ */
247
+ function processKeys(proc, ctx) {
248
+ // 不是数组时当作一个没有键名的快捷键,好让 createExtensions 提示
249
+ const list = (Array.isArray(proc.manifest.keys) ? proc.manifest.keys : [{}]);
250
+ return list.map((k) => ({
251
+ key: (k && typeof k === "object" ? k.key : undefined),
252
+ description: typeof k?.description === "string" ? k.description : undefined,
253
+ run: async ({ key, sessionId, signal }) => {
254
+ const { input, send } = ctx;
255
+ const reply = (await proc.request("jade/key", { key, sessionId, ...(input ? { text: input.text() } : {}) }, signal));
256
+ if (typeof reply?.set === "string")
257
+ input?.set(reply.set);
258
+ if (typeof reply?.insert === "string")
259
+ input?.insert(reply.insert);
260
+ if (typeof reply?.send === "string")
261
+ send?.(reply.send);
262
+ },
263
+ }));
264
+ }
129
265
  /**
130
266
  * 读插件目录,不执行其中的代码:jade plugin add 用它检查和命名,loadPlugin 用它决定怎么加载。
131
267
  * 什么都提供不了的目录抛出错误
@@ -170,15 +306,27 @@ export async function inspectPlugin(dir) {
170
306
  if (claude?.agents !== undefined || (await isDir(path.join(dir, "agents"))))
171
307
  bundle.unsupported.push("agents");
172
308
  const meta = {
309
+ id: json.id,
173
310
  name: str(json.name) ?? str(claude?.name) ?? str(pkg.name)?.replace(/^@[^/]+\//, ""),
174
311
  version: str(json.version) ?? str(claude?.version) ?? str(pkg.version),
175
312
  description: str(json.description) ?? str(claude?.description) ?? str(pkg.description),
313
+ replaces: json.replaces,
314
+ };
315
+ const needsId = () => {
316
+ if (json.id === undefined)
317
+ throw new Error('plugin.json: "id" is required for plugins with code, e.g. { "id": "me/my-plugin", "version": "1.0.0" }');
176
318
  };
177
- if (json.command !== undefined)
319
+ if (json.command !== undefined) {
320
+ needsId();
178
321
  return { ...meta, kind: "process", json, bundle };
322
+ }
179
323
  const entry = json.entry ?? (await firstFile(dir, ENTRIES));
180
- if (entry)
324
+ if (entry) {
325
+ needsId();
181
326
  return { ...meta, kind: "module", entry, json, bundle };
327
+ }
328
+ if (json.replaces !== undefined)
329
+ throw new Error('plugin.json: "replaces" needs a plugin with code: the plugin stands in for the built-in plugin it replaces');
182
330
  if (bundle.skills.length || bundle.commands.length || bundle.mcp)
183
331
  return { ...meta, kind: "content", json, bundle };
184
332
  throw new Error(`no ${ENTRIES.join(", ")}, no plugin.json, and no skills/, commands/ or mcp.json`);
@@ -224,17 +372,21 @@ async function readPluginJson(dir) {
224
372
  const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
225
373
  const problem = typeof json !== "object" || json === null || Array.isArray(json)
226
374
  ? "must be an object"
227
- : json.entry !== undefined && typeof json.entry !== "string"
228
- ? '"entry" must be a string'
229
- : json.command !== undefined && (typeof json.command !== "string" || !json.command)
230
- ? '"command" must be a non-empty string'
231
- : json.args !== undefined && !strings(json.args)
232
- ? '"args" must be an array of strings'
233
- : json.env !== undefined && (typeof json.env !== "object" || json.env === null || !Object.values(json.env).every((v) => typeof v === "string"))
234
- ? '"env" must map names to strings'
235
- : json.entry !== undefined && json.command !== undefined
236
- ? 'use either "entry" (in-process) or "command" (separate process), not both'
237
- : undefined;
375
+ : json.id !== undefined && (typeof json.id !== "string" || !PLUGIN_ID.test(json.id))
376
+ ? '"id" must be letters, digits, and . _ - @, in parts separated by /, e.g. "me/my-plugin"'
377
+ : json.replaces !== undefined && !strings(json.replaces)
378
+ ? '"replaces" must be an array of built-in plugin ids, e.g. ["jade/web"]'
379
+ : json.entry !== undefined && typeof json.entry !== "string"
380
+ ? '"entry" must be a string'
381
+ : json.command !== undefined && (typeof json.command !== "string" || !json.command)
382
+ ? '"command" must be a non-empty string'
383
+ : json.args !== undefined && !strings(json.args)
384
+ ? '"args" must be an array of strings'
385
+ : json.env !== undefined && (typeof json.env !== "object" || json.env === null || !Object.values(json.env).every((v) => typeof v === "string"))
386
+ ? '"env" must map names to strings'
387
+ : json.entry !== undefined && json.command !== undefined
388
+ ? 'use either "entry" (in-process) or "command" (separate process), not both'
389
+ : undefined;
238
390
  if (problem)
239
391
  throw new Error(`plugin.json: ${problem}`);
240
392
  return json;
@@ -248,6 +400,8 @@ async function firstFile(dir, names) {
248
400
  function isPlugin(v) {
249
401
  return typeof v === "object" && v !== null && typeof v.id === "string";
250
402
  }
403
+ /** 插件 id:几段字母、数字和 . _ - @,用 / 分隔 */
404
+ export const PLUGIN_ID = /^[\w.@-]+(\/[\w.@-]+)*$/;
251
405
  /** 斜杠命令名:字母数字开头,之后可以有 - 和 _ */
252
406
  export const COMMAND_NAME = /^[a-z0-9][a-z0-9_-]*$/i;
253
407
  //# sourceMappingURL=loader.js.map