@uncarved/jade 0.3.1 → 0.4.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.
Files changed (199) hide show
  1. package/dist/api.d.ts +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/host.d.ts +2 -0
  4. package/dist/host.js +39 -5
  5. package/dist/host.js.map +1 -1
  6. package/dist/remote.js +5 -0
  7. package/dist/remote.js.map +1 -1
  8. package/dist/session.d.ts +7 -0
  9. package/dist/session.js +482 -27
  10. package/dist/session.js.map +1 -1
  11. package/package.json +4 -4
  12. package/plugins/approval/index.ts +36 -14
  13. package/plugins/approval/policy.ts +15 -10
  14. package/plugins/approval/review.ts +9 -5
  15. package/plugins/checks/checks.ts +10 -7
  16. package/plugins/checks/index.ts +13 -13
  17. package/plugins/checks/plugin.json +1 -1
  18. package/plugins/checks/project.ts +37 -38
  19. package/plugins/commands/index.ts +27 -3
  20. package/plugins/compact/compact.ts +13 -5
  21. package/plugins/compact/index.ts +20 -3
  22. package/plugins/compact/style.ts +13 -14
  23. package/plugins/completions/index.ts +35 -0
  24. package/plugins/completions/plugin.json +7 -0
  25. package/plugins/copy/index.ts +46 -0
  26. package/plugins/copy/plugin.json +7 -0
  27. package/plugins/editor/index.ts +10 -4
  28. package/plugins/fs/diff.ts +7 -6
  29. package/plugins/fs/fs.ts +8 -4
  30. package/plugins/fs/grep.ts +42 -9
  31. package/plugins/fs/index.ts +2 -7
  32. package/plugins/fs/plugin.json +1 -1
  33. package/plugins/fs/renderers.ts +16 -15
  34. package/plugins/fs/style.ts +16 -15
  35. package/plugins/hooks/index.ts +3 -2
  36. package/plugins/keys/index.ts +5 -1
  37. package/plugins/mcp/index.ts +197 -78
  38. package/plugins/mcp/install.ts +5 -3
  39. package/plugins/mcp/mcp.ts +163 -11
  40. package/plugins/mcp/plugin.json +2 -1
  41. package/plugins/mcp/project.ts +47 -50
  42. package/plugins/memory/index.ts +4 -4
  43. package/plugins/memory/style.ts +13 -14
  44. package/plugins/mentions/candidates.ts +67 -0
  45. package/plugins/mentions/index.ts +12 -5
  46. package/plugins/mentions/plugin.json +1 -1
  47. package/plugins/mentions/style.ts +13 -14
  48. package/plugins/models/configure.ts +10 -9
  49. package/plugins/models/index.ts +27 -1
  50. package/plugins/modes/index.ts +13 -2
  51. package/plugins/print/index.ts +7 -4
  52. package/plugins/prompts/index.ts +0 -0
  53. package/plugins/renderers/index.ts +10 -5
  54. package/plugins/repeats/index.ts +8 -8
  55. package/plugins/schedule/index.ts +2 -0
  56. package/plugins/screenshot/browser.ts +10 -0
  57. package/plugins/sessions/index.ts +48 -2
  58. package/plugins/shell/index.ts +20 -25
  59. package/plugins/shell/plugin.json +1 -2
  60. package/plugins/shell/renderers.ts +9 -7
  61. package/plugins/shell/shell.ts +3 -1
  62. package/plugins/skills/index.ts +28 -19
  63. package/plugins/skills/project.ts +12 -7
  64. package/plugins/steer/index.ts +5 -4
  65. package/plugins/task/index.ts +80 -50
  66. package/plugins/task/plugin.json +6 -2
  67. package/plugins/task/style.ts +13 -14
  68. package/plugins/task/subagent.ts +67 -184
  69. package/plugins/todo/index.ts +39 -9
  70. package/plugins/tools/index.ts +9 -2
  71. package/plugins/tui/frontend.ts +139 -89
  72. package/plugins/tui/index.ts +2 -3
  73. package/plugins/tui/mentions.ts +11 -80
  74. package/plugins/tui/plugin.json +1 -1
  75. package/plugins/tui/screen.ts +55 -5
  76. package/plugins/tui/transcript.ts +17 -7
  77. package/plugins/tui/tui.ts +337 -101
  78. package/plugins/tui/vendor.ts +1 -1
  79. package/plugins/undo/checkpoint.ts +5 -3
  80. package/plugins/undo/index.ts +43 -14
  81. package/plugins/undo/style.ts +13 -14
  82. package/plugins/web/index.ts +7 -18
  83. package/plugins/web/plugin.json +1 -1
  84. package/plugins-dist/approval/index.js +363 -418
  85. package/plugins-dist/approval/policy.js +391 -508
  86. package/plugins-dist/approval/review.js +132 -158
  87. package/plugins-dist/approval/schema.js +50 -55
  88. package/plugins-dist/ask/index.js +115 -129
  89. package/plugins-dist/budget/index.js +27 -31
  90. package/plugins-dist/checks/checks.js +293 -329
  91. package/plugins-dist/checks/index.js +119 -139
  92. package/plugins-dist/checks/plugin.json +2 -1
  93. package/plugins-dist/checks/project.js +57 -65
  94. package/plugins-dist/commands/index.js +47 -29
  95. package/plugins-dist/compact/compact.js +233 -249
  96. package/plugins-dist/compact/index.js +98 -95
  97. package/plugins-dist/compact/style.js +9 -14
  98. package/plugins-dist/completions/index.js +30 -0
  99. package/plugins-dist/completions/plugin.json +9 -0
  100. package/plugins-dist/continue/index.js +40 -52
  101. package/plugins-dist/copy/index.js +40 -0
  102. package/plugins-dist/copy/plugin.json +9 -0
  103. package/plugins-dist/cost/index.js +98 -115
  104. package/plugins-dist/custom-commands/index.js +55 -72
  105. package/plugins-dist/editor/index.js +64 -72
  106. package/plugins-dist/fs/diff.js +111 -124
  107. package/plugins-dist/fs/fs.js +426 -469
  108. package/plugins-dist/fs/grep.js +262 -253
  109. package/plugins-dist/fs/index.js +20 -34
  110. package/plugins-dist/fs/plugin.json +1 -2
  111. package/plugins-dist/fs/renderers.js +100 -112
  112. package/plugins-dist/fs/style.js +11 -15
  113. package/plugins-dist/fs/sys.js +31 -43
  114. package/plugins-dist/hooks/index.js +107 -127
  115. package/plugins-dist/keys/index.js +27 -31
  116. package/plugins-dist/mcp/index.js +271 -199
  117. package/plugins-dist/mcp/install.js +123 -137
  118. package/plugins-dist/mcp/mcp.js +638 -577
  119. package/plugins-dist/mcp/plugin.json +3 -1
  120. package/plugins-dist/mcp/project.js +98 -115
  121. package/plugins-dist/memory/index.js +83 -88
  122. package/plugins-dist/memory/memory.js +111 -128
  123. package/plugins-dist/memory/style.js +9 -14
  124. package/plugins-dist/mentions/attach.js +91 -99
  125. package/plugins-dist/mentions/candidates.js +49 -0
  126. package/plugins-dist/mentions/index.js +71 -81
  127. package/plugins-dist/mentions/plugin.json +2 -1
  128. package/plugins-dist/mentions/style.js +9 -14
  129. package/plugins-dist/models/config.js +29 -43
  130. package/plugins-dist/models/configure.js +392 -473
  131. package/plugins-dist/models/context.js +14 -22
  132. package/plugins-dist/models/index.js +182 -189
  133. package/plugins-dist/models/provider.js +243 -307
  134. package/plugins-dist/models/saved.js +59 -71
  135. package/plugins-dist/modes/index.js +138 -165
  136. package/plugins-dist/plugins/index.js +34 -34
  137. package/plugins-dist/print/index.js +192 -175
  138. package/plugins-dist/prompts/index.js +81 -89
  139. package/plugins-dist/prompts/notes.js +31 -37
  140. package/plugins-dist/prompts/prompts.js +155 -193
  141. package/plugins-dist/prompts/results.js +40 -53
  142. package/plugins-dist/prompts/sys.js +39 -50
  143. package/plugins-dist/renderers/index.js +32 -32
  144. package/plugins-dist/repeats/index.js +131 -174
  145. package/plugins-dist/schedule/cron.js +49 -56
  146. package/plugins-dist/schedule/index.js +229 -247
  147. package/plugins-dist/schedule/store.js +93 -109
  148. package/plugins-dist/scratch/index.js +12 -18
  149. package/plugins-dist/screenshot/browser.js +136 -154
  150. package/plugins-dist/screenshot/index.js +37 -46
  151. package/plugins-dist/screenshot/sys.js +53 -65
  152. package/plugins-dist/screenshot/tool.js +98 -126
  153. package/plugins-dist/sessions/index.js +149 -117
  154. package/plugins-dist/shell/index.js +115 -135
  155. package/plugins-dist/shell/plugin.json +1 -2
  156. package/plugins-dist/shell/renderers.js +28 -33
  157. package/plugins-dist/shell/service.js +17 -23
  158. package/plugins-dist/shell/shell.js +307 -362
  159. package/plugins-dist/shell/sys.js +64 -79
  160. package/plugins-dist/skills/index.js +193 -211
  161. package/plugins-dist/skills/install.js +122 -149
  162. package/plugins-dist/skills/project.js +65 -73
  163. package/plugins-dist/skills/skills.js +135 -171
  164. package/plugins-dist/steer/index.js +108 -125
  165. package/plugins-dist/suggest/index.js +235 -259
  166. package/plugins-dist/task/index.js +130 -117
  167. package/plugins-dist/task/plugin.json +5 -2
  168. package/plugins-dist/task/style.js +9 -14
  169. package/plugins-dist/task/subagent.js +156 -279
  170. package/plugins-dist/todo/index.js +79 -63
  171. package/plugins-dist/tools/index.js +36 -42
  172. package/plugins-dist/tui/editor.js +145 -160
  173. package/plugins-dist/tui/frontend.js +639 -678
  174. package/plugins-dist/tui/history.js +34 -37
  175. package/plugins-dist/tui/index.js +16 -18
  176. package/plugins-dist/tui/markdown.js +203 -247
  177. package/plugins-dist/tui/mascot.js +266 -355
  178. package/plugins-dist/tui/mentions.js +67 -144
  179. package/plugins-dist/tui/plugin.json +1 -2
  180. package/plugins-dist/tui/render.js +35 -45
  181. package/plugins-dist/tui/screen.js +197 -180
  182. package/plugins-dist/tui/transcript.js +436 -468
  183. package/plugins-dist/tui/tui.js +1554 -1656
  184. package/plugins-dist/undo/checkpoint.js +95 -118
  185. package/plugins-dist/undo/index.js +185 -192
  186. package/plugins-dist/undo/snapshot.js +83 -99
  187. package/plugins-dist/undo/style.js +9 -14
  188. package/plugins-dist/update/index.js +26 -28
  189. package/plugins-dist/web/env.js +55 -68
  190. package/plugins-dist/web/index.js +80 -110
  191. package/plugins-dist/web/plugin.json +1 -2
  192. package/plugins-dist/web/renderers.js +4 -5
  193. package/plugins-dist/web/web.js +514 -593
  194. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  195. package/sdk/python/jade_plugin.py +9 -2
  196. package/src/api.ts +1 -1
  197. package/src/host.ts +39 -4
  198. package/src/remote.ts +6 -1
  199. package/src/session.ts +489 -34
@@ -1,136 +1,168 @@
1
- // jade/sessions:/clear、/resume、/retry,以及 /resume 用的会话索引。
2
- // 索引是 $JADE_HOME/state/sessions.jsonl,每行 { id, cwd, title, at }:会话在本进程里第一次收到消息时追加一行。
3
- // 读的时候按 id 合并:标题取最早的一行,时间取最晚的一行;目录按 cwdKey 比较。
4
1
  import { appendFile, mkdir, readFile } from "node:fs/promises";
5
2
  import path from "node:path";
6
3
  import { definePlugin } from "@uncarved/jade-api";
7
4
  const TITLE_CHARS = 80;
8
- /** 比较目录用的键:绝对路径、去掉末尾的分隔符;Windows 上不分大小写 */
9
5
  export function cwdKey(cwd) {
10
- const p = path.resolve(cwd);
11
- return process.platform === "win32" ? p.toLowerCase() : p;
6
+ const p = path.resolve(cwd);
7
+ return process.platform === "win32" ? p.toLowerCase() : p;
12
8
  }
13
- /** 索引里的全部会话按目录分组,键是 cwdKey;每组最近用过的在前 */
14
9
  export async function listAllSessions(file) {
15
- let text = "";
10
+ let text = "";
11
+ try {
12
+ text = await readFile(file, "utf8");
13
+ } catch {
14
+ return new Map;
15
+ }
16
+ const byId = new Map;
17
+ for (const line of text.split(`
18
+ `)) {
19
+ if (!line.trim())
20
+ continue;
21
+ let e;
16
22
  try {
17
- text = await readFile(file, "utf8");
23
+ e = JSON.parse(line);
24
+ } catch {
25
+ continue;
18
26
  }
19
- catch {
20
- return new Map();
21
- }
22
- const byId = new Map();
23
- for (const line of text.split("\n")) {
24
- if (!line.trim())
25
- continue;
26
- let e;
27
- try {
28
- e = JSON.parse(line);
29
- }
30
- catch {
31
- continue; // 写到一半的行
32
- }
33
- if (typeof e?.id !== "string" || typeof e.cwd !== "string" || typeof e.at !== "string")
34
- continue;
35
- const seen = byId.get(e.id);
36
- byId.set(e.id, seen ? { ...seen, at: e.at > seen.at ? e.at : seen.at } : e);
37
- }
38
- const byCwd = new Map();
39
- for (const s of byId.values()) {
40
- const key = cwdKey(s.cwd);
41
- const group = byCwd.get(key);
42
- if (group)
43
- group.push(s);
44
- else
45
- byCwd.set(key, [s]);
46
- }
47
- for (const group of byCwd.values())
48
- group.sort((a, b) => b.at.localeCompare(a.at));
49
- return byCwd;
27
+ if (typeof e?.id !== "string" || typeof e.cwd !== "string" || typeof e.at !== "string")
28
+ continue;
29
+ const seen = byId.get(e.id);
30
+ byId.set(e.id, seen ? { ...seen, at: e.at > seen.at ? e.at : seen.at } : e);
31
+ }
32
+ const byCwd = new Map;
33
+ for (const s of byId.values()) {
34
+ const key = cwdKey(s.cwd);
35
+ const group = byCwd.get(key);
36
+ if (group)
37
+ group.push(s);
38
+ else
39
+ byCwd.set(key, [s]);
40
+ }
41
+ for (const group of byCwd.values())
42
+ group.sort((a, b) => b.at.localeCompare(a.at));
43
+ return byCwd;
50
44
  }
51
- /** 索引里 cwd 下的会话,最近用过的在前 */
52
45
  export async function listSessions(file, cwd) {
53
- return (await listAllSessions(file)).get(cwdKey(cwd)) ?? [];
46
+ return (await listAllSessions(file)).get(cwdKey(cwd)) ?? [];
54
47
  }
55
- /** 多久以前,例如 "5m ago" */
56
48
  export function ago(iso, now = Date.now()) {
57
- const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));
58
- if (s < 60)
59
- return "just now";
60
- if (s < 3600)
61
- return `${Math.floor(s / 60)}m ago`;
62
- if (s < 86400)
63
- return `${Math.floor(s / 3600)}h ago`;
64
- return `${Math.floor(s / 86400)}d ago`;
49
+ const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));
50
+ if (s < 60)
51
+ return "just now";
52
+ if (s < 3600)
53
+ return `${Math.floor(s / 60)}m ago`;
54
+ if (s < 86400)
55
+ return `${Math.floor(s / 3600)}h ago`;
56
+ return `${Math.floor(s / 86400)}d ago`;
65
57
  }
66
58
  function titleOf(input) {
67
- if (input.kind !== "message")
68
- return undefined;
69
- const text = input.content.flatMap((b) => (b.kind === "text" && b.origin.by === "user" ? [b.text] : [])).join(" ").replace(/\s+/g, " ").trim();
70
- if (!text)
71
- return undefined;
72
- return text.length > TITLE_CHARS ? `${text.slice(0, TITLE_CHARS)}…` : text;
59
+ if (input.kind !== "message")
60
+ return;
61
+ const text = input.content.flatMap((b) => b.kind === "text" && b.origin.by === "user" ? [b.text] : []).join(" ").replace(/\s+/g, " ").trim();
62
+ if (!text)
63
+ return;
64
+ return text.length > TITLE_CHARS ? `${text.slice(0, TITLE_CHARS)}…` : text;
73
65
  }
66
+ function userText(input) {
67
+ if (input.kind !== "message")
68
+ return "";
69
+ return input.content.flatMap((b) => b.kind === "text" && b.origin.by === "user" ? [b.text] : []).join(`
70
+ `).trim();
71
+ }
72
+ const oneLine = (text) => {
73
+ const one = text.replace(/\s+/g, " ");
74
+ return one.length > TITLE_CHARS ? `${one.slice(0, TITLE_CHARS)}…` : one;
75
+ };
76
+ let input;
74
77
  export default definePlugin({
75
- process(ctx) {
76
- const file = path.join(ctx.home, "state", "sessions.jsonl");
77
- ctx.provide("sessions@1", { list: (cwd) => listSessions(file, cwd) });
78
- const commands = ctx.require("commands@1");
79
- commands.register({
80
- name: "clear",
81
- description: "start a new session (the current one stays resumable)",
82
- async run(_args, c) {
83
- const previous = c.sessions.current;
84
- await c.sessions.open();
85
- return previous && previous.state.messages.length > 0 ? `Started a new session. Resume the previous one with /resume or: jade --resume ${previous.id}` : "Started a new session.";
86
- },
87
- });
88
- commands.register({
89
- name: "resume",
90
- args: "[session id]",
91
- description: "continue an earlier session in this directory",
92
- async run(args, c) {
93
- let id = args.trim() || undefined;
94
- if (!id) {
95
- const all = (await listSessions(file, ctx.cwd)).filter((s) => s.id !== c.sessions.current?.id).slice(0, 50);
96
- if (all.length === 0)
97
- return "No other sessions in this directory.";
98
- id = await c.ui.select({ title: "Resume which session?", options: all.map((s) => ({ label: s.title || "(untitled)", value: s.id, hint: `${ago(s.at)} · ${s.id}` })) }, c.signal);
99
- if (!id)
100
- return;
101
- }
102
- // 前端在会话换掉之后重新显示它的对话
103
- await c.sessions.open({ resume: id });
104
- },
105
- });
106
- commands.register({
107
- name: "retry",
108
- description: "ask the model again after a failed request",
109
- async run(_args, c) {
110
- const s = c.sessions.current;
111
- if (!s || s.state.messages.at(-1)?.role !== "user")
112
- return "Nothing to retry: the last request did not fail before the model answered.";
113
- await s.send({ kind: "retry" });
114
- },
115
- });
116
- },
117
- session(ctx) {
118
- const file = path.join(ctx.home, "state", "sessions.jsonl");
119
- let indexed = false;
120
- ctx.kernel.hook({
121
- kind: "observe",
122
- point: "event",
123
- fn: async (e) => {
124
- if (indexed || e.type !== "input.received")
125
- return;
126
- const title = titleOf(e.data);
127
- if (title === undefined)
128
- return;
129
- indexed = true;
130
- const entry = { id: ctx.session.id, cwd: path.resolve(ctx.cwd), title, at: new Date().toISOString() };
131
- await mkdir(path.dirname(file), { recursive: true });
132
- await appendFile(file, `${JSON.stringify(entry)}\n`);
133
- },
78
+ process(ctx) {
79
+ const file = path.join(ctx.home, "state", "sessions.jsonl");
80
+ ctx.provide("sessions@1", { list: (cwd) => listSessions(file, cwd) });
81
+ const commands = ctx.require("commands@1");
82
+ commands.register({
83
+ name: "clear",
84
+ description: "start a new session (the current one stays resumable)",
85
+ async run(_args, c) {
86
+ const previous = c.sessions.current;
87
+ await c.sessions.open();
88
+ return previous && previous.state.messages.length > 0 ? `Started a new session. Resume the previous one with /resume or: jade --resume ${previous.id}` : "Started a new session.";
89
+ }
90
+ });
91
+ commands.register({
92
+ name: "resume",
93
+ args: "[session id]",
94
+ description: "continue an earlier session in this directory",
95
+ async run(args, c) {
96
+ let id = args.trim() || undefined;
97
+ if (!id) {
98
+ const all = (await listSessions(file, ctx.cwd)).filter((s) => s.id !== c.sessions.current?.id).slice(0, 50);
99
+ if (all.length === 0)
100
+ return "No other sessions in this directory.";
101
+ id = await c.ui.select({ title: "Resume which session?", options: all.map((s) => ({ label: s.title || "(untitled)", value: s.id, hint: `${ago(s.at)} · ${s.id}` })) }, c.signal);
102
+ if (!id)
103
+ return;
104
+ }
105
+ await c.sessions.open({ resume: id });
106
+ }
107
+ });
108
+ commands.register({
109
+ name: "rewind",
110
+ description: "go back to before one of your messages, in a copy of this session (files stay as they are; to restore them, /undo in the session before rewinding)",
111
+ async run(_args, c) {
112
+ const s = c.sessions.current;
113
+ if (!s)
114
+ return "There is no open session.";
115
+ const sent = (await s.history()).flatMap((e) => {
116
+ const text = e.type === "input.received" ? userText(e.data) : "";
117
+ return text ? [{ seq: e.seq, text }] : [];
134
118
  });
135
- },
119
+ if (sent.length === 0)
120
+ return "Nothing to rewind to: you have not sent a message in this session.";
121
+ const recent = sent.slice(-50).reverse();
122
+ const picked = await c.ui.select({
123
+ title: "Rewind to before which message?",
124
+ options: recent.map((m, i) => ({ label: oneLine(m.text), value: String(m.seq), hint: i === 0 ? "your last message" : `${i + 1} messages ago` }))
125
+ }, c.signal);
126
+ const to = recent.find((m) => String(m.seq) === picked);
127
+ if (!to)
128
+ return;
129
+ await c.sessions.open({ fork: { session: s.id, before: to.seq } });
130
+ input?.set(to.text);
131
+ return `Rewound to before that message${input ? "; it is back in the input" : ""}. Files were not changed; to restore them, run /undo in the session before rewinding: jade --resume ${s.id}`;
132
+ }
133
+ });
134
+ commands.register({
135
+ name: "retry",
136
+ description: "ask the model again after a failed request",
137
+ async run(_args, c) {
138
+ const s = c.sessions.current;
139
+ if (!s || s.state.messages.at(-1)?.role !== "user")
140
+ return "Nothing to retry: the last request did not fail before the model answered.";
141
+ await s.send({ kind: "retry" });
142
+ }
143
+ });
144
+ },
145
+ session(ctx) {
146
+ if (ctx.session.parent)
147
+ return;
148
+ input = ctx.input;
149
+ const file = path.join(ctx.home, "state", "sessions.jsonl");
150
+ let indexed = false;
151
+ ctx.kernel.hook({
152
+ kind: "observe",
153
+ point: "event",
154
+ fn: async (e) => {
155
+ if (indexed || e.type !== "input.received")
156
+ return;
157
+ const title = titleOf(e.data);
158
+ if (title === undefined)
159
+ return;
160
+ indexed = true;
161
+ const entry = { id: ctx.session.id, cwd: path.resolve(ctx.cwd), title, at: new Date().toISOString() };
162
+ await mkdir(path.dirname(file), { recursive: true });
163
+ await appendFile(file, `${JSON.stringify(entry)}
164
+ `);
165
+ }
166
+ });
167
+ }
136
168
  });
@@ -1,148 +1,128 @@
1
- // jade/shell:bash 工具,以及后台命令的 bash_output、kill_shell;shell@1 给其他插件执行命令。
2
- // 后台命令自己结束时告诉用户,并给模型留一句说明(不用它一直轮询);/shells 给用户看和停掉后台命令。
3
1
  import { definePlugin } from "@uncarved/jade-api";
4
2
  import { shellRenderers } from "./renderers.js";
5
3
  import { shellService } from "./service.js";
6
4
  import { shellTools } from "./shell.js";
7
- /** 打开着的会话 → 它的后台命令(/shells 用) */
8
- const sessions = new Map();
5
+ const sessions = new Map;
9
6
  const firstLine = (command) => {
10
- const line = command.split("\n")[0];
11
- return line.length > 80 ? `${line.slice(0, 80)}…` : line;
7
+ const line = command.split(`
8
+ `)[0];
9
+ return line.length > 80 ? `${line.slice(0, 80)}…` : line;
12
10
  };
13
- /** /sh 的时限:用户自己看着它跑(登录、安装),给到 bash 工具的上限;不想等就按 esc */
14
- const SH_TIMEOUT_MS = 600_000;
15
- /** 边跑边显示的输出最多留这么多个字符(前端只显示末尾几行) */
11
+ const SH_TIMEOUT_MS = 600000;
16
12
  const SH_LIVE_CHARS = 4000;
17
- /** /sh 的结果收起时那一行最多这么多个字符 */
18
13
  const SH_SUMMARY = 160;
19
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色
20
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
21
- /** 失败的红色,其余的灰色 */
22
- const shade = (failed, s) => (colors ? (failed ? `\x1b[31m${s}\x1b[39m` : `\x1b[2m${s}\x1b[22m`) : s);
14
+ const shade = (failed, text) => ({ text, style: failed ? "error" : "dim" });
23
15
  export default definePlugin({
24
- process(ctx) {
25
- // 显示方式和会话无关,登记一次留到进程结束;没有 renderers@1(例如 print)时用前端的默认显示
26
- const renderers = ctx.service("renderers@1");
27
- if (renderers)
28
- for (const r of shellRenderers)
29
- renderers.tool(r);
30
- // shell@1:找 shell 和杀进程树只有一份(见 service.ts)
31
- const shell = shellService(typeof ctx.config.shell === "string" ? { shell: ctx.config.shell } : {});
32
- ctx.provide("shell@1", shell);
33
- const commands = ctx.service("commands@1");
34
- // 用户自己执行一条命令(前端里 !<命令> 是它的简写):不经过模型和审批。
35
- // 输出显示给用户;会话里已经有对话时,结果作为用户的消息发给模型,它接着做(例如它让用户先 npm login);
36
- // 还没有对话、或用户按 esc 停掉时不开始一轮,只给模型留一句说明,下一次请求时它能看到
37
- commands?.register({
38
- name: "sh",
39
- args: "<command>",
40
- description: "run a shell command yourself (short form: !<command>); then the agent continues with its output",
41
- // 不是 instant:和消息一样排队,前端才把它当作正在做的事(esc 能停掉它)
42
- async run(args, { sessions: manager, signal, print, progress }) {
43
- const command = args.trim();
44
- if (!command)
45
- return "Usage: /sh <command>, or !<command>";
46
- if (!shell.executable)
47
- return shell.unavailable;
48
- // 边跑边显示输出(npm login 这类要看着它的提示);被 esc 停掉时,已经输出的也留下来
49
- let live = "";
50
- let r;
51
- let stopped = false;
52
- try {
53
- r = await shell.run(command, {
54
- cwd: ctx.cwd,
55
- timeoutMs: SH_TIMEOUT_MS,
56
- signal,
57
- onOutput(text) {
58
- live = (live + text).slice(-SH_LIVE_CHARS);
59
- progress?.(live);
60
- },
61
- });
62
- }
63
- catch (e) {
64
- if (!signal.aborted)
65
- throw e;
66
- stopped = true;
67
- r = { code: null, output: live.trimEnd(), timedOut: false };
68
- }
69
- const status = stopped ? "stopped by the user" : r.timedOut ? `timed out after ${SH_TIMEOUT_MS / 1000}s` : `exit code ${r.code}`;
70
- // 和 bash 工具的结果一个样子:一行摘要,完整输出折叠起来
71
- const lines = r.output ? r.output.split("\n") : [];
72
- const failed = r.code !== 0;
73
- const first = failed ? `${status}${lines.length ? ` · ${lines[0]}` : ""}` : (lines[0] ?? "(no output)");
74
- const more = lines.length > 1 ? ` (+${lines.length - 1} lines)` : "";
75
- const folded = lines.length > 1 || first.length > SH_SUMMARY;
76
- print(shade(failed, `⎿ ${first.length > SH_SUMMARY ? `${first.slice(0, SH_SUMMARY)}…` : first}${more}`), folded ? { details: r.output.replace(/^/gm, " ") } : undefined);
77
- const session = manager.current;
78
- if (!stopped && session && session.state.messages.length > 0)
79
- return { prompt: `I ran this shell command myself (${status}):\n$ ${command}\n${r.output}` };
80
- if (session)
81
- ctx.service("prompts@1")?.note(session.id, `The user ran this shell command themselves (${status}):\n$ ${command}\n${r.output}`);
82
- },
83
- });
84
- commands?.register({
85
- name: "shells",
86
- args: "[kill <id>]",
87
- description: "list the background commands the agent started, or stop one",
88
- instant: true,
89
- async run(args, { sessions: manager }) {
90
- const shells = manager.current && sessions.get(manager.current.id);
91
- const [verb, id] = args.trim().split(/\s+/);
92
- if (verb === "kill" && id)
93
- return shells && (await shells.kill(id)) ? `Stopped ${id}.` : `There is no background command ${id}.`;
94
- const all = shells?.list() ?? [];
95
- if (all.length === 0)
96
- return "No background commands.";
97
- return all.map((b) => `${b.id} ${b.status} ${firstLine(b.command)}`).join("\n");
98
- },
99
- });
100
- },
101
- async session(ctx) {
102
- const shell = typeof ctx.config.shell === "string" ? ctx.config.shell : undefined;
103
- const id = ctx.session.id;
104
- const { tools, executable, unavailable, shutdown, list, kill } = shellTools({
105
- cwd: ctx.cwd,
106
- ...(shell ? { shell } : {}),
107
- onExit(bg) {
108
- const what = `Background shell ${bg.id} (${firstLine(bg.command)}) exited with code ${bg.exitCode}`;
109
- ctx.service("ui@1")?.notify(what, bg.exitCode === 0 ? "info" : "warning");
110
- ctx.service("prompts@1")?.note(id, `${what}. Read its remaining output with bash_output.`);
111
- },
112
- });
113
- sessions.set(id, { list, kill });
114
- // 嵌套 Agent 的 bash:只收命令和时限,不能在后台跑。它不是只读工具,哪些命令能执行由使用方把关
115
- // (jade/task 按审批规则只放行只读的命令,下面的说明文字是按这个写的)
116
- const bash = tools.find((t) => t.name === "bash");
16
+ process(ctx) {
17
+ const renderers = ctx.service("renderers@1");
18
+ if (renderers)
19
+ for (const r of shellRenderers)
20
+ renderers.tool(r);
21
+ const shell = shellService(typeof ctx.config.shell === "string" ? { shell: ctx.config.shell } : {});
22
+ ctx.provide("shell@1", shell);
23
+ const commands = ctx.service("commands@1");
24
+ commands?.register({
25
+ name: "sh",
26
+ args: "<command>",
27
+ description: "run a shell command yourself (short form: !<command>); then the agent continues with its output",
28
+ prefix: "!",
29
+ prefixHint: "shell command · you run it, not the agent",
30
+ async run(args, { sessions: manager, signal, print, progress }) {
31
+ const command = args.trim();
32
+ if (!command)
33
+ return "Usage: /sh <command>, or !<command>";
34
+ if (!shell.executable)
35
+ return shell.unavailable;
36
+ let live = "";
37
+ let r;
38
+ let stopped = false;
117
39
  try {
118
- if (bash) {
119
- ctx.service("tools@1")?.register({
120
- ...bash,
121
- description: "Run a read-only shell command in the working directory (for example git log, git diff, git status, ls, rg) and return its exit code and output. " +
122
- "Commands that could change anything, or that touch paths outside the working directory, are refused.",
123
- inputSchema: { type: "object", properties: { command: { type: "string" }, timeout_ms: { type: "integer" } }, required: ["command"], additionalProperties: false },
124
- execute: (input, c) => bash.execute({ command: input.command, timeout_ms: input.timeout_ms }, c),
125
- });
40
+ r = await shell.run(command, {
41
+ cwd: ctx.cwd,
42
+ timeoutMs: SH_TIMEOUT_MS,
43
+ signal,
44
+ onOutput(text) {
45
+ live = (live + text).slice(-SH_LIVE_CHARS);
46
+ progress?.(live);
126
47
  }
48
+ });
49
+ } catch (e) {
50
+ if (!signal.aborted)
51
+ throw e;
52
+ stopped = true;
53
+ r = { code: null, output: live.trimEnd(), timedOut: false };
127
54
  }
128
- catch {
129
- // jade/tools 被隔离时它的服务已失效:嵌套 Agent 没有 bash,主会话的照常
130
- }
131
- if (unavailable)
132
- ctx.service("ui@1")?.notify(unavailable, "warning");
133
- for (const tool of tools)
134
- ctx.kernel.tool(tool);
135
- if (executable) {
136
- const lines = [`- Shell for the bash tool: ${executable} (POSIX syntax, also on Windows)`];
137
- // 模型常用 xdg-open、open 打开文件,Git Bash 里没有;start 是 Git 自带的 /usr/bin/start
138
- if (process.platform === "win32")
139
- lines.push('- To open a file or URL for the user, run: start "" <path-or-url> (xdg-open and open do not exist)');
140
- ctx.service("prompts@1")?.add({ text: lines.join("\n") });
141
- }
142
- // 会话关闭(换会话、退出)时杀掉还在运行的后台命令
143
- await ctx.effect(() => () => {
144
- sessions.delete(id);
145
- shutdown();
146
- });
147
- },
55
+ const status = stopped ? "stopped by the user" : r.timedOut ? `timed out after ${SH_TIMEOUT_MS / 1000}s` : `exit code ${r.code}`;
56
+ const lines = r.output ? r.output.split(`
57
+ `) : [];
58
+ const failed = r.code !== 0;
59
+ const first = failed ? `${status}${lines.length ? ` · ${lines[0]}` : ""}` : lines[0] ?? "(no output)";
60
+ const more = lines.length > 1 ? ` (+${lines.length - 1} lines)` : "";
61
+ const folded = lines.length > 1 || first.length > SH_SUMMARY;
62
+ print(shade(failed, `⎿ ${first.length > SH_SUMMARY ? `${first.slice(0, SH_SUMMARY)}…` : first}${more}`), folded ? { details: r.output.replace(/^/gm, " ") } : undefined);
63
+ const session = manager.current;
64
+ if (!stopped && session && session.state.messages.length > 0)
65
+ return { prompt: `I ran this shell command myself (${status}):
66
+ $ ${command}
67
+ ${r.output}` };
68
+ if (session)
69
+ ctx.service("prompts@1")?.note(session.id, `The user ran this shell command themselves (${status}):
70
+ $ ${command}
71
+ ${r.output}`);
72
+ }
73
+ });
74
+ commands?.register({
75
+ name: "shells",
76
+ args: "[kill <id>]",
77
+ description: "list the background commands the agent started, or stop one",
78
+ instant: true,
79
+ async run(args, { sessions: manager }) {
80
+ const shells = manager.current && sessions.get(manager.current.id);
81
+ const [verb, id] = args.trim().split(/\s+/);
82
+ if (verb === "kill" && id)
83
+ return shells && await shells.kill(id) ? `Stopped ${id}.` : `There is no background command ${id}.`;
84
+ const all = shells?.list() ?? [];
85
+ if (all.length === 0)
86
+ return "No background commands.";
87
+ return all.map((b) => `${b.id} ${b.status} ${firstLine(b.command)}`).join(`
88
+ `);
89
+ }
90
+ });
91
+ },
92
+ async session(ctx) {
93
+ const shell = typeof ctx.config.shell === "string" ? ctx.config.shell : undefined;
94
+ const id = ctx.session.id;
95
+ const { tools, executable, unavailable, shutdown, list, kill } = shellTools({
96
+ cwd: ctx.cwd,
97
+ ...shell ? { shell } : {},
98
+ onExit(bg) {
99
+ const what = `Background shell ${bg.id} (${firstLine(bg.command)}) exited with code ${bg.exitCode}`;
100
+ ctx.service("ui@1")?.notify(what, bg.exitCode === 0 ? "info" : "warning");
101
+ ctx.service("prompts@1")?.note(id, `${what}. Read its remaining output with bash_output.`);
102
+ }
103
+ });
104
+ sessions.set(id, { list, kill });
105
+ const child = ctx.session.parent !== undefined;
106
+ const foreground = (t) => t.name !== "bash" ? t : {
107
+ ...t,
108
+ inputSchema: { type: "object", properties: { command: { type: "string" }, timeout_ms: { type: "integer" } }, required: ["command"], additionalProperties: false },
109
+ execute: (input, c) => t.execute({ command: input.command, timeout_ms: input.timeout_ms }, c)
110
+ };
111
+ if (unavailable && !child)
112
+ ctx.service("ui@1")?.notify(unavailable, "warning");
113
+ for (const tool of tools)
114
+ if (!(child && (tool.name === "bash_output" || tool.name === "kill_shell")))
115
+ ctx.kernel.tool(child ? foreground(tool) : tool);
116
+ if (executable) {
117
+ const lines = [`- Shell for the bash tool: ${executable} (POSIX syntax, also on Windows)`];
118
+ if (process.platform === "win32")
119
+ lines.push('- To open a file or URL for the user, run: start "" <path-or-url> (xdg-open and open do not exist)');
120
+ ctx.service("prompts@1")?.add({ text: lines.join(`
121
+ `) });
122
+ }
123
+ await ctx.effect(() => () => {
124
+ sessions.delete(id);
125
+ shutdown();
126
+ });
127
+ }
148
128
  });
@@ -10,8 +10,7 @@
10
10
  "ui@1",
11
11
  "prompts@1",
12
12
  "renderers@1",
13
- "commands@1",
14
- "tools@1"
13
+ "commands@1"
15
14
  ],
16
15
  "config": {
17
16
  "shell": {
@@ -1,40 +1,35 @@
1
- // bash、bash_output、kill_shell 在对话和审批里怎么显示(登记到 renderers@1)。从旧 jade 的 ui/renderers.ts 移植。
2
- //
3
- // 运行中的输出不登记 progress:bash 推送的是 { kind, stream, text },前端对 { text } 形式的进度默认逐行显示,
4
- // 正是想要的;自己写 progress 反而只能把一次推送(可能是好几行、半行)显示成一行。
5
- // 截断和颜色从旧 jade 的 ui/render.ts、ui/screen.ts 复制:插件之间不共享代码,fs 插件也有一份
6
- const clip = (s, n) => (s.length > n ? s.slice(0, n) + "…" : s);
7
- // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色,见 https://no-color.org
8
- const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
9
- const dim = (s) => (colors ? `\x1b[2m${s.replaceAll("\x1b[22m", "\x1b[22m\x1b[2m")}\x1b[22m` : s);
10
- const args = (input) => (input !== null && typeof input === "object" ? input : {});
1
+ const clip = (s, n) => s.length > n ? s.slice(0, n) + "…" : s;
2
+ const dim = (text) => ({ text, style: "dim" });
3
+ const joinLines = (rows) => rows.flatMap((r, i) => i ? [`
4
+ `, r] : [r]);
5
+ const args = (input) => input !== null && typeof input === "object" ? input : {};
11
6
  const command = (input) => String(args(input).command ?? "");
12
- /** 摘要最多这么多个字符 */
13
7
  const MAX_SUMMARY = 120;
14
- /** 预览里的多行文字:每行前面加上标记,最多 max 行 */
15
8
  function marked(s, mark, max = 30) {
16
- const all = s.split("\n");
17
- const shown = all.slice(0, max).map((l) => `${mark} ${l}`);
18
- if (all.length > max)
19
- shown.push(dim(` … ${all.length - max} more lines`));
20
- return shown.join("\n");
9
+ const all = s.split(`
10
+ `);
11
+ const shown = all.slice(0, max).map((l) => `${mark} ${l}`);
12
+ if (all.length > max)
13
+ shown.push(dim(` … ${all.length - max} more lines`));
14
+ return joinLines(shown);
21
15
  }
22
16
  export const shellRenderers = [
23
- {
24
- tool: "bash",
25
- summary: (input) => clip(command(input).split("\n")[0], MAX_SUMMARY),
26
- // 摘要省略了内容时(多行或很长的命令),展开后先显示完整的命令
27
- details: (input) => {
28
- const lines = command(input).split("\n");
29
- if (lines.length === 1 && lines[0].length <= MAX_SUMMARY)
30
- return undefined;
31
- const shown = lines.slice(0, 200).map((l, i) => dim(`${i === 0 ? "$" : " "} ${l}`));
32
- if (lines.length > 200)
33
- shown.push(dim(`… ${lines.length - 200} more lines`));
34
- return shown.join("\n");
35
- },
36
- preview: (input) => marked(command(input), "$"),
17
+ {
18
+ tool: "bash",
19
+ summary: (input) => clip(command(input).split(`
20
+ `)[0], MAX_SUMMARY),
21
+ details: (input) => {
22
+ const lines = command(input).split(`
23
+ `);
24
+ if (lines.length === 1 && lines[0].length <= MAX_SUMMARY)
25
+ return;
26
+ const shown = lines.slice(0, 200).map((l, i) => dim(`${i === 0 ? "$" : " "} ${l}`));
27
+ if (lines.length > 200)
28
+ shown.push(dim(`… ${lines.length - 200} more lines`));
29
+ return joinLines(shown);
37
30
  },
38
- { tool: "bash_output", summary: (input) => String(args(input).id ?? "") },
39
- { tool: "kill_shell", summary: (input) => String(args(input).id ?? "") },
31
+ preview: (input) => marked(command(input), "$")
32
+ },
33
+ { tool: "bash_output", summary: (input) => String(args(input).id ?? "") },
34
+ { tool: "kill_shell", summary: (input) => String(args(input).id ?? "") }
40
35
  ];