@tenonai/yew 0.0.0-stage → 1.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 (133) hide show
  1. package/CHANGELOG.md +296 -0
  2. package/LICENSE +21 -0
  3. package/README.md +55 -2
  4. package/THIRD-PARTY-NOTICES.md +122 -0
  5. package/bin/yew.js +9 -0
  6. package/dist/cli/app.js +198 -0
  7. package/dist/cli/export.js +57 -0
  8. package/dist/cli/io.js +65 -0
  9. package/dist/cli/key.js +113 -0
  10. package/dist/cli/main.js +44 -0
  11. package/dist/cli/mcp.js +76 -0
  12. package/dist/cli/remote.js +116 -0
  13. package/dist/cli/run.js +72 -0
  14. package/dist/cli/schedule.js +123 -0
  15. package/dist/cli/send.js +126 -0
  16. package/dist/cli/serve.js +301 -0
  17. package/dist/cli/service.js +241 -0
  18. package/dist/cli/system.js +44 -0
  19. package/dist/remote/access.js +107 -0
  20. package/dist/remote/connector.js +278 -0
  21. package/dist/remote/identity.js +71 -0
  22. package/dist/remote/noise.js +287 -0
  23. package/dist/remote/protocol.js +51 -0
  24. package/dist/remote/push.js +37 -0
  25. package/dist/server/agent/compaction.js +242 -0
  26. package/dist/server/agent/context.js +119 -0
  27. package/dist/server/agent/held.js +48 -0
  28. package/dist/server/agent/helper.js +122 -0
  29. package/dist/server/agent/mailroom.js +510 -0
  30. package/dist/server/agent/prompt.js +268 -0
  31. package/dist/server/agent/runner.js +1159 -0
  32. package/dist/server/artifacts.js +216 -0
  33. package/dist/server/budget.js +88 -0
  34. package/dist/server/data-export.js +105 -0
  35. package/dist/server/data-usage.js +143 -0
  36. package/dist/server/db/database.js +49 -0
  37. package/dist/server/db/migrations.js +347 -0
  38. package/dist/server/errors.js +16 -0
  39. package/dist/server/events.js +17 -0
  40. package/dist/server/export.js +378 -0
  41. package/dist/server/folder-picker.js +32 -0
  42. package/dist/server/from-jig.js +98 -0
  43. package/dist/server/http/agents.js +78 -0
  44. package/dist/server/http/api.js +468 -0
  45. package/dist/server/http/app.js +111 -0
  46. package/dist/server/http/artifacts.js +53 -0
  47. package/dist/server/http/data.js +54 -0
  48. package/dist/server/http/devices.js +47 -0
  49. package/dist/server/http/events.js +134 -0
  50. package/dist/server/http/idempotency.js +53 -0
  51. package/dist/server/http/input.js +106 -0
  52. package/dist/server/http/mail.js +52 -0
  53. package/dist/server/http/mcp.js +134 -0
  54. package/dist/server/http/notes.js +91 -0
  55. package/dist/server/http/problem.js +55 -0
  56. package/dist/server/http/providers.js +131 -0
  57. package/dist/server/http/schedules.js +58 -0
  58. package/dist/server/http/search.js +42 -0
  59. package/dist/server/http/security.js +168 -0
  60. package/dist/server/http/skills.js +53 -0
  61. package/dist/server/http/system.js +26 -0
  62. package/dist/server/ids.js +30 -0
  63. package/dist/server/keys.js +51 -0
  64. package/dist/server/mail/envelope.js +152 -0
  65. package/dist/server/mail/post.js +603 -0
  66. package/dist/server/mail/store.js +279 -0
  67. package/dist/server/manage.js +601 -0
  68. package/dist/server/mcp-builtin.js +179 -0
  69. package/dist/server/mcp-config.js +305 -0
  70. package/dist/server/mcp-oauth.js +448 -0
  71. package/dist/server/mcp.js +668 -0
  72. package/dist/server/model/gateway.js +410 -0
  73. package/dist/server/paths.js +34 -0
  74. package/dist/server/permissions/engine.js +249 -0
  75. package/dist/server/permissions/paths.js +93 -0
  76. package/dist/server/permissions/shell.js +635 -0
  77. package/dist/server/push.js +345 -0
  78. package/dist/server/reveal.js +36 -0
  79. package/dist/server/runtime.js +17 -0
  80. package/dist/server/schedules.js +356 -0
  81. package/dist/server/settings.js +80 -0
  82. package/dist/server/skills.js +262 -0
  83. package/dist/server/store.js +1077 -0
  84. package/dist/server/tools/files.js +318 -0
  85. package/dist/server/tools/html.js +221 -0
  86. package/dist/server/tools/jobs.js +38 -0
  87. package/dist/server/tools/mail.js +680 -0
  88. package/dist/server/tools/match.js +81 -0
  89. package/dist/server/tools/misc.js +253 -0
  90. package/dist/server/tools/process.js +128 -0
  91. package/dist/server/tools/read-state.js +40 -0
  92. package/dist/server/tools/registry.js +43 -0
  93. package/dist/server/tools/search.js +175 -0
  94. package/dist/server/tools/shell.js +124 -0
  95. package/dist/server/tools/types.js +43 -0
  96. package/dist/server/tools/web-search.js +198 -0
  97. package/dist/server/tools/web.js +240 -0
  98. package/dist/shared/cron.js +105 -0
  99. package/dist/shared/mcp-presets.js +170 -0
  100. package/dist/shared/messages.js +45 -0
  101. package/dist/shared/policy.js +42 -0
  102. package/dist/shared/types.js +34 -0
  103. package/dist/shared/version.js +8 -0
  104. package/mcp-builtin/package-lock.json +3398 -0
  105. package/mcp-builtin/package.json +14 -0
  106. package/mcp-builtin/presets/gitee/package-lock.json +105 -0
  107. package/mcp-builtin/presets/gitee/package.json +10 -0
  108. package/mcp-builtin/presets/notion/package-lock.json +2243 -0
  109. package/mcp-builtin/presets/notion/package.json +10 -0
  110. package/mcp-builtin/presets/sentry/package-lock.json +28 -0
  111. package/mcp-builtin/presets/sentry/package.json +10 -0
  112. package/package.json +75 -5
  113. package/web/dist/THIRD-PARTY-NOTICES.txt +1944 -0
  114. package/web/dist/assets/index-B9oWPSod.css +1 -0
  115. package/web/dist/assets/index-C5qBMzFX.js +68 -0
  116. package/web/dist/icons/app-icon.png +0 -0
  117. package/web/dist/icons/apple-touch-icon.png +0 -0
  118. package/web/dist/icons/favicon-16.png +0 -0
  119. package/web/dist/icons/favicon-32.png +0 -0
  120. package/web/dist/icons/favicon-64.png +0 -0
  121. package/web/dist/icons/tenon-mark.svg +1 -0
  122. package/web/dist/icons/yew-mark.svg +1 -0
  123. package/web/dist/index.html +18 -0
  124. package/web/dist/mascot/gift.webp +0 -0
  125. package/web/dist/mascot/greeting.webp +0 -0
  126. package/web/dist/mascot/happy.webp +0 -0
  127. package/web/dist/mascot/lost.webp +0 -0
  128. package/web/dist/mascot/shush.webp +0 -0
  129. package/web/dist/mascot/sleepy.webp +0 -0
  130. package/web/dist/mascot/sorry.webp +0 -0
  131. package/web/dist/mascot/thinking.webp +0 -0
  132. package/web/dist/mascot/waking.webp +0 -0
  133. package/web/dist/mascot/writing.webp +0 -0
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Finding the text an edit replaces. Exact match first; if that finds nothing, a second pass ignores
3
+ * differences models often introduce: trailing spaces, curly quotes, long dashes and special spaces
4
+ * (after pi's edit tool, prior-art 4.2). Either way the match must be unique.
5
+ */
6
+ const CHAR_MAP = {
7
+ "‘": "'",
8
+ "’": "'",
9
+ "‚": "'",
10
+ "‛": "'",
11
+ "“": '"',
12
+ "”": '"',
13
+ "„": '"',
14
+ "‟": '"',
15
+ "‐": "-",
16
+ "‑": "-",
17
+ "‒": "-",
18
+ "–": "-",
19
+ "—": "-",
20
+ "―": "-",
21
+ " ": " ",
22
+ " ": " ",
23
+ " ": " ",
24
+ " ": " ",
25
+ };
26
+ export function countOccurrences(haystack, needle) {
27
+ if (needle.length === 0)
28
+ return 0;
29
+ let count = 0;
30
+ let index = haystack.indexOf(needle);
31
+ while (index >= 0) {
32
+ count++;
33
+ index = haystack.indexOf(needle, index + needle.length);
34
+ }
35
+ return count;
36
+ }
37
+ /** Normalized text plus, for each of its characters, the index of the original character. */
38
+ function normalize(text) {
39
+ const out = [];
40
+ const map = [];
41
+ let i = 0;
42
+ while (i < text.length) {
43
+ const c = text[i];
44
+ if (c === " " || c === "\t") {
45
+ let j = i;
46
+ while (j < text.length && (text[j] === " " || text[j] === "\t"))
47
+ j++;
48
+ // Whitespace at the end of a line is dropped.
49
+ if (j === text.length || text[j] === "\n" || text[j] === "\r") {
50
+ i = j;
51
+ continue;
52
+ }
53
+ }
54
+ out.push(CHAR_MAP[c] ?? (/[ - ]/.test(c) ? " " : c));
55
+ map.push(i);
56
+ i++;
57
+ }
58
+ return { text: out.join(""), map };
59
+ }
60
+ export function findUnique(content, needle) {
61
+ const exact = countOccurrences(content, needle);
62
+ if (exact === 1) {
63
+ const start = content.indexOf(needle);
64
+ return { ok: true, start, end: start + needle.length };
65
+ }
66
+ if (exact > 1)
67
+ return { ok: false, reason: "ambiguous", count: exact };
68
+ const hay = normalize(content);
69
+ const pin = normalize(needle).text;
70
+ if (pin.trim().length === 0)
71
+ return { ok: false, reason: "not_found" };
72
+ const count = countOccurrences(hay.text, pin);
73
+ if (count === 0)
74
+ return { ok: false, reason: "not_found" };
75
+ if (count > 1)
76
+ return { ok: false, reason: "ambiguous", count };
77
+ const at = hay.text.indexOf(pin);
78
+ const start = hay.map[at];
79
+ const last = hay.map[at + pin.length - 1];
80
+ return { ok: true, start, end: last + 1 };
81
+ }
@@ -0,0 +1,253 @@
1
+ import { questionsOf, } from "../../shared/types.js";
2
+ import { invalid } from "../errors.js";
3
+ import { str, ToolInputError, text } from "./types.js";
4
+ const STATUSES = ["pending", "in_progress", "done"];
5
+ export const todoTool = {
6
+ name: "todo",
7
+ description: "Keep this session's task list, which the person sees next to the conversation. Send the whole list each time; mark one item in_progress while you work on it and done when finished.",
8
+ parameters: {
9
+ type: "object",
10
+ properties: {
11
+ items: {
12
+ type: "array",
13
+ maxItems: 50,
14
+ items: {
15
+ type: "object",
16
+ properties: {
17
+ text: { type: "string" },
18
+ status: { type: "string", enum: [...STATUSES] },
19
+ },
20
+ required: ["text", "status"],
21
+ additionalProperties: false,
22
+ },
23
+ },
24
+ },
25
+ required: ["items"],
26
+ additionalProperties: false,
27
+ },
28
+ readOnly: false,
29
+ needsFolder: false,
30
+ subject() {
31
+ return { kind: "none" };
32
+ },
33
+ async run(args, ctx) {
34
+ const items = args.items;
35
+ if (!Array.isArray(items) || items.length > 50)
36
+ throw new ToolInputError("items must be a list of at most 50.");
37
+ const todos = items.map((item) => {
38
+ if (!item || typeof item !== "object" || Array.isArray(item))
39
+ throw new ToolInputError("Each item needs text and status.");
40
+ const record = item;
41
+ const status = record.status;
42
+ if (typeof record.text !== "string" || !STATUSES.includes(status)) {
43
+ throw new ToolInputError("Each item needs text and a status of pending, in_progress or done.");
44
+ }
45
+ return { text: record.text.slice(0, 500), status: status };
46
+ });
47
+ ctx.setTodos(todos);
48
+ const marks = { pending: "[ ]", in_progress: "[~]", done: "[x]" };
49
+ const list = todos.map((todo) => `${marks[todo.status]} ${todo.text}`).join("\n");
50
+ return { content: [text(list ? `Task list updated:\n${list}` : "Task list cleared.")] };
51
+ },
52
+ };
53
+ const MAX_QUESTIONS = 4;
54
+ const MAX_OPTIONS = 6;
55
+ /**
56
+ * The questions of an ask_user call. Calls written before a card could hold several questions (one
57
+ * question with plain options) are read the same way.
58
+ */
59
+ export function parseQuestions(args) {
60
+ if (args.questions === undefined && typeof args.question === "string") {
61
+ return parseQuestions({
62
+ questions: [{ question: args.question, options: args.options ?? [] }],
63
+ });
64
+ }
65
+ const list = args.questions;
66
+ if (!Array.isArray(list) || list.length === 0) {
67
+ throw new ToolInputError("questions must list at least one question.");
68
+ }
69
+ if (list.length > MAX_QUESTIONS) {
70
+ throw new ToolInputError(`Ask at most ${MAX_QUESTIONS} questions at once.`);
71
+ }
72
+ return list.map((raw, index) => {
73
+ const item = (raw && typeof raw === "object" ? raw : {});
74
+ const question = typeof item.question === "string" ? item.question.trim() : "";
75
+ if (!question)
76
+ throw new ToolInputError(`Question ${index + 1} is empty.`);
77
+ const rawOptions = Array.isArray(item.options) ? item.options : [];
78
+ if (rawOptions.length > MAX_OPTIONS) {
79
+ throw new ToolInputError(`Question ${index + 1} has more than ${MAX_OPTIONS} options.`);
80
+ }
81
+ const options = rawOptions.map((option) => {
82
+ const fields = (typeof option === "string" ? { label: option } : option);
83
+ const label = typeof fields?.label === "string" ? fields.label.trim() : "";
84
+ if (!label)
85
+ throw new ToolInputError(`An option of question ${index + 1} has no label.`);
86
+ const detail = typeof fields.detail === "string" ? fields.detail.trim() : "";
87
+ return detail ? { label: label.slice(0, 200), detail: detail.slice(0, 500) } : { label };
88
+ });
89
+ let recommended;
90
+ if (item.recommended !== undefined) {
91
+ const value = item.recommended;
92
+ if (!Number.isInteger(value) || value < 1 || value > options.length) {
93
+ throw new ToolInputError(`recommended of question ${index + 1} must name one of its options.`);
94
+ }
95
+ recommended = value - 1;
96
+ }
97
+ const header = typeof item.header === "string" ? item.header.trim().slice(0, 24) : "";
98
+ return {
99
+ question: question.slice(0, 2000),
100
+ ...(header ? { header } : {}),
101
+ ...(options.length > 0 ? { options } : {}),
102
+ ...(recommended === undefined ? {} : { recommended }),
103
+ ...(item.multiple === true && options.length > 1 ? { multiple: true } : {}),
104
+ };
105
+ });
106
+ }
107
+ /**
108
+ * Checks the person's answer against the questions and writes it as the session reads it: the options
109
+ * picked, then their own words. Several questions get one line each.
110
+ */
111
+ export function settleAnswer(request, answer) {
112
+ const questions = questionsOf(request);
113
+ if (!answer.answers) {
114
+ const words = answer.answer?.trim();
115
+ if (!words)
116
+ throw invalid("The answer is empty.", "answer");
117
+ return { text: words };
118
+ }
119
+ if (answer.answers.length !== questions.length)
120
+ throw invalid("Answer every question.", "answers");
121
+ const answers = [];
122
+ const parts = questions.map((question, index) => {
123
+ const given = answer.answers?.[index];
124
+ const options = question.options ?? [];
125
+ const choices = [...new Set(given.choices)];
126
+ if (choices.some((choice) => !Number.isInteger(choice) || choice < 0 || choice >= options.length)) {
127
+ throw invalid("An answer picks an option that does not exist.", "answers");
128
+ }
129
+ if (!question.multiple && choices.length > 1) {
130
+ throw invalid("Pick one option for this question.", "answers");
131
+ }
132
+ const words = given.text?.trim() ?? "";
133
+ if (choices.length === 0 && !words)
134
+ throw invalid("Answer every question.", "answers");
135
+ answers.push({ choices, ...(words ? { text: words } : {}) });
136
+ const labels = choices.map((choice) => options[choice].label).join(", ");
137
+ return labels && words ? `${labels}; ${words}` : labels || words;
138
+ });
139
+ const text = questions.length === 1
140
+ ? parts[0]
141
+ : parts
142
+ .map((part, index) => `${index + 1}. ${questions[index]?.question} → ${part}`)
143
+ .join("\n");
144
+ return { text, answers };
145
+ }
146
+ export const askUserTool = {
147
+ name: "ask_user",
148
+ description: "Ask the person and wait for the answer; it waits for them in the approval center. Use it when you cannot go on without an answer only they can give. Up to 4 questions at once; options and a recommendation are optional, and the person can always answer in their own words.",
149
+ parameters: {
150
+ type: "object",
151
+ properties: {
152
+ questions: {
153
+ type: "array",
154
+ minItems: 1,
155
+ maxItems: MAX_QUESTIONS,
156
+ items: {
157
+ type: "object",
158
+ properties: {
159
+ question: {
160
+ type: "string",
161
+ description: "The question, understandable on its own.",
162
+ },
163
+ header: {
164
+ type: "string",
165
+ description: "A tag of one to three words shown before it, such as its topic.",
166
+ },
167
+ options: {
168
+ type: "array",
169
+ minItems: 2,
170
+ maxItems: MAX_OPTIONS,
171
+ items: {
172
+ type: "object",
173
+ properties: {
174
+ label: { type: "string", description: "A few words." },
175
+ detail: {
176
+ type: "string",
177
+ description: "What this choice means or leads to, in a short sentence.",
178
+ },
179
+ },
180
+ required: ["label"],
181
+ additionalProperties: false,
182
+ },
183
+ },
184
+ recommended: {
185
+ type: "integer",
186
+ minimum: 1,
187
+ description: "The option you recommend, counting from 1.",
188
+ },
189
+ multiple: {
190
+ type: "boolean",
191
+ description: "The person may pick more than one option.",
192
+ },
193
+ },
194
+ required: ["question"],
195
+ additionalProperties: false,
196
+ },
197
+ },
198
+ },
199
+ required: ["questions"],
200
+ additionalProperties: false,
201
+ },
202
+ readOnly: false,
203
+ needsFolder: false,
204
+ subject() {
205
+ return { kind: "none" };
206
+ },
207
+ async run(args, ctx) {
208
+ const questions = parseQuestions(args);
209
+ const answer = await ctx.ask({ questions });
210
+ return {
211
+ content: [
212
+ text(questions.length === 1
213
+ ? `The person answered: ${answer}`
214
+ : `The person answered:\n${answer}`),
215
+ ],
216
+ };
217
+ },
218
+ };
219
+ /** Hands a task to a helper and returns its answer (blueprint 6.11, item 43). */
220
+ export const delegateTool = {
221
+ name: "delegate",
222
+ description: "Give a self-contained task to a helper that works in a context of its own and returns only its answer. It can read files, search, fetch pages and run commands that change nothing; it cannot change anything or ask the person. Several delegate calls in one step run at the same time. Use it for searches and investigations whose details you do not need to keep, so your own context stays short.",
223
+ parameters: {
224
+ type: "object",
225
+ properties: {
226
+ task: {
227
+ type: "string",
228
+ description: "What to find out and what to report. The helper sees nothing of this conversation, so include what it needs to know.",
229
+ },
230
+ },
231
+ required: ["task"],
232
+ additionalProperties: false,
233
+ },
234
+ // It only looks, so several run at once; each of its own calls is checked as it goes.
235
+ readOnly: true,
236
+ needsFolder: false,
237
+ subject: () => ({ kind: "none" }),
238
+ async run(args, ctx) {
239
+ const task = str(args, "task", true).trim();
240
+ if (!task)
241
+ throw new ToolInputError("The task is empty.");
242
+ const result = await ctx.helper(task);
243
+ const note = result.stopped
244
+ ? `[The helper stopped before it finished: ${result.stopped}. Above is what it had.]`
245
+ : "";
246
+ const answer = [result.text, note].filter(Boolean).join("\n\n") || "(The helper gave no answer.)";
247
+ return {
248
+ content: [{ type: "text", text: answer }],
249
+ detail: { calls: result.calls, ...(result.stopped ? { stopped: result.stopped } : {}) },
250
+ ...(result.stopped && !result.text ? { isError: true } : {}),
251
+ };
252
+ },
253
+ };
@@ -0,0 +1,128 @@
1
+ import { spawn } from "node:child_process";
2
+ import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { newId } from "../ids.js";
5
+ export const MAX_LINES = 2000;
6
+ export const MAX_BYTES = 50 * 1024;
7
+ /**
8
+ * Keeps the tail of a command's output (2000 lines or 50 KB, prior-art 4.2). Once the output grows past
9
+ * that, everything is also written to a log file, so nothing is lost and the model can read it.
10
+ */
11
+ export class OutputTail {
12
+ #tail = "";
13
+ #total = 0;
14
+ #file = null;
15
+ #dir;
16
+ #buffered = "";
17
+ constructor(dir) {
18
+ this.#dir = dir;
19
+ }
20
+ push(chunk) {
21
+ this.#total += Buffer.byteLength(chunk);
22
+ this.#tail += chunk;
23
+ if (this.#file) {
24
+ appendFileSync(this.#file, chunk);
25
+ }
26
+ else {
27
+ this.#buffered += chunk;
28
+ if (Buffer.byteLength(this.#buffered) > MAX_BYTES) {
29
+ mkdirSync(this.#dir, { recursive: true, mode: 0o700 });
30
+ this.#file = join(this.#dir, `${newId()}.log`);
31
+ writeFileSync(this.#file, this.#buffered, { mode: 0o600 });
32
+ this.#buffered = "";
33
+ }
34
+ }
35
+ if (this.#tail.length > MAX_BYTES * 2)
36
+ this.#tail = this.#tail.slice(-MAX_BYTES * 2);
37
+ }
38
+ get file() {
39
+ return this.#file;
40
+ }
41
+ /** The kept tail, cut at a line boundary, with a note when output was dropped. */
42
+ render() {
43
+ let text = this.#tail;
44
+ let truncated = this.#file !== null;
45
+ let lines = text.split("\n");
46
+ if (lines.length > MAX_LINES) {
47
+ lines = lines.slice(-MAX_LINES);
48
+ truncated = true;
49
+ }
50
+ text = lines.join("\n");
51
+ while (Buffer.byteLength(text) > MAX_BYTES) {
52
+ const cut = text.indexOf("\n");
53
+ text = cut < 0 ? text.slice(-MAX_BYTES) : text.slice(cut + 1);
54
+ truncated = true;
55
+ }
56
+ if (!truncated)
57
+ return text;
58
+ const where = this.#file ? ` The full output (${this.#total} bytes) is in ${this.#file}.` : "";
59
+ return `[Earlier output was cut; showing the last part.${where}]\n${text}`;
60
+ }
61
+ }
62
+ /** Provider keys Yew keeps out of commands' environment (AGENTS.md: keys stay in the keychain). */
63
+ const KEY_VARIABLES = /^(ANTHROPIC|OPENAI|DEEPSEEK|GEMINI|GOOGLE|GROQ|MISTRAL|MOONSHOT|KIMI|ZAI|ZHIPU|MINIMAX|DASHSCOPE|QWEN|XIAOMI|MIMO|OPENROUTER|XAI|TOGETHER|FIREWORKS|CEREBRAS|HF|HUGGINGFACE|NVIDIA|BASETEN|VERCEL_AI_GATEWAY|AZURE_OPENAI)_API_KEY$/;
64
+ export function commandEnvironment(sessionId) {
65
+ const env = {};
66
+ for (const [name, value] of Object.entries(process.env)) {
67
+ if (!KEY_VARIABLES.test(name))
68
+ env[name] = value;
69
+ }
70
+ return {
71
+ ...env,
72
+ YEW_SESSION: sessionId,
73
+ NO_COLOR: "1",
74
+ PAGER: "cat",
75
+ GIT_PAGER: "cat",
76
+ GIT_TERMINAL_PROMPT: "0",
77
+ };
78
+ }
79
+ /**
80
+ * Runs a command with the user's login shell in its own process group, so stopping it ends every
81
+ * process it started. Stopping freezes the group first, so `a; b` cannot slip into `b` while it is
82
+ * being ended (pi's approach on macOS, prior-art 4.2), then sends SIGTERM and, 3 seconds later, SIGKILL.
83
+ */
84
+ export function startCommand(options) {
85
+ const shell = process.env.SHELL || "/bin/zsh";
86
+ const child = spawn(shell, ["-lc", options.command], {
87
+ cwd: options.cwd,
88
+ env: commandEnvironment(options.sessionId),
89
+ detached: true,
90
+ stdio: ["ignore", "pipe", "pipe"],
91
+ });
92
+ const output = new OutputTail(options.logDir);
93
+ const onData = (data) => {
94
+ const chunk = data.toString("utf8");
95
+ output.push(chunk);
96
+ options.onOutput?.(chunk);
97
+ };
98
+ child.stdout?.on("data", onData);
99
+ child.stderr?.on("data", onData);
100
+ const done = new Promise((resolve) => {
101
+ child.on("error", (error) => {
102
+ output.push(`\n${error.message}\n`);
103
+ resolve({ exitCode: null, signal: null });
104
+ });
105
+ child.on("close", (exitCode, signal) => resolve({ exitCode, signal }));
106
+ });
107
+ let stopping = false;
108
+ const stop = () => {
109
+ if (stopping || child.exitCode !== null || child.pid === undefined)
110
+ return;
111
+ stopping = true;
112
+ const group = -child.pid;
113
+ const send = (signal) => {
114
+ try {
115
+ process.kill(group, signal);
116
+ }
117
+ catch {
118
+ // Already gone.
119
+ }
120
+ };
121
+ send("SIGSTOP");
122
+ send("SIGTERM");
123
+ send("SIGCONT");
124
+ const timer = setTimeout(() => send("SIGKILL"), 3000);
125
+ void done.then(() => clearTimeout(timer));
126
+ };
127
+ return { child, output, done, stop };
128
+ }
@@ -0,0 +1,40 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ /**
4
+ * What a session has read, so write and edit can refuse to overwrite a file the session has not seen
5
+ * or that changed since (Gemini CLI's check, prior-art 4.2): compare modification time and size first,
6
+ * and the content hash only when those differ.
7
+ */
8
+ export class ReadState {
9
+ #seen = new Map();
10
+ record(path, content) {
11
+ const stat = statSync(path);
12
+ this.#seen.set(path, { mtimeMs: stat.mtimeMs, size: stat.size, hash: hash(content) });
13
+ }
14
+ /** null when the file is safe to change; otherwise why not. */
15
+ check(path) {
16
+ const seen = this.#seen.get(path);
17
+ if (!seen)
18
+ return "Read the file before changing it.";
19
+ let stat;
20
+ try {
21
+ stat = statSync(path);
22
+ }
23
+ catch {
24
+ return "The file no longer exists. Read the folder again before changing it.";
25
+ }
26
+ if (stat.mtimeMs === seen.mtimeMs && stat.size === seen.size)
27
+ return null;
28
+ if (hash(readFileSync(path)) === seen.hash) {
29
+ this.#seen.set(path, { ...seen, mtimeMs: stat.mtimeMs, size: stat.size });
30
+ return null;
31
+ }
32
+ return "The file changed after you read it. Read it again before changing it.";
33
+ }
34
+ forget(path) {
35
+ this.#seen.delete(path);
36
+ }
37
+ }
38
+ function hash(content) {
39
+ return createHash("sha256").update(content).digest("hex");
40
+ }
@@ -0,0 +1,43 @@
1
+ import { editTool, readTool, writeTool } from "./files.js";
2
+ import { checkDecisionTool, finishTaskTool, listCardsTool, listSessionsTool, manageYewTool, openSessionTool, postCardTool, sendLetterTool, updateCardTool, withdrawCardTool, } from "./mail.js";
3
+ import { askUserTool, delegateTool, todoTool } from "./misc.js";
4
+ import { globTool, grepTool } from "./search.js";
5
+ import { shellJobTool, shellTool } from "./shell.js";
6
+ import { webFetchTool } from "./web.js";
7
+ export const ALL_TOOLS = [
8
+ readTool,
9
+ writeTool,
10
+ editTool,
11
+ globTool,
12
+ grepTool,
13
+ shellTool,
14
+ shellJobTool,
15
+ todoTool,
16
+ askUserTool,
17
+ webFetchTool,
18
+ listSessionsTool,
19
+ sendLetterTool,
20
+ checkDecisionTool,
21
+ openSessionTool,
22
+ finishTaskTool,
23
+ manageYewTool,
24
+ postCardTool,
25
+ updateCardTool,
26
+ withdrawCardTool,
27
+ listCardsTool,
28
+ delegateTool,
29
+ ];
30
+ /**
31
+ * Sessions without a working folder are chats: no file or shell tools (blueprint, principle 1). Some
32
+ * tools depend on the session's place: card tools for the main conversation, finish_task for tasks.
33
+ */
34
+ export function toolsFor(session, tools = ALL_TOOLS, roles = { canPostCards: false, canOrganize: false }) {
35
+ return tools.filter((tool) => (session.cwd !== null || !tool.needsFolder) && (tool.offered?.(session, roles) ?? true));
36
+ }
37
+ export function specs(tools) {
38
+ return tools.map((tool) => ({
39
+ name: tool.name,
40
+ description: tool.description,
41
+ parameters: tool.parameters,
42
+ }));
43
+ }