@celljs/ta-secrets 0.0.0-stage → 4.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md ADDED
@@ -0,0 +1,22 @@
1
+ # Cell - Ta Secrets
2
+
3
+ A pi package that comes with Ta (on by default, off in Settings → Extensions): the vault. Tokens, passwords, keys and personal details go to Ta to use, not to the model. Design in `docs/design/ta-secrets.md`.
4
+
5
+ - **Kept**: values in the login keychain of macOS (service `Ta secrets`); elsewhere, or with `TA_SECRETS_STORE=file`, in `secrets/vault.json` of the agent directory, which only you read.
6
+ - **Names**: each has one (`GITHUB_TOKEN`); the model sees `$TA_SECRET_GITHUB_TOKEN`.
7
+ - **Keep secrets I send**: tokens, private keys, passwords of URLs and `password=…` in a message go into the vault before the model reads it, the message holding their names (off in Settings → Vault).
8
+ - **Personal details**: phone numbers, emails, ID numbers and bank cards (told by their check digits) go into the vault too, the model seeing a name and a masked hint (`138****5678`); where a tool's arguments (a file written, a form, a message) name one, Ta puts the detail in as it runs. Off in Settings → Vault.
9
+ - **Asked for**: Ta calls `request_secret({ name, purpose })` for a missing one; you type it in a dialog, not the conversation.
10
+ - **Used**: a bash command writes `"$TA_SECRET_GITHUB_TOKEN"`, and only that command gets the value, sourced from a file only you read, removed as it starts; the conversation keeps the command as written.
11
+ - **Only to its hosts**: a secret bound to hosts (tokens of GitHub, GitLab and Gitee are by default) is a placeholder in the command, whose HTTPS goes through Ta's proxy on this computer, which puts the value in (headers and URL) for those hosts alone; commands running git get tokens so too. Needs `openssl`.
12
+ - **SSH**: private keys are held by an ssh-agent of each command that may connect (ssh, scp, rsync, git), never a variable, ended with it.
13
+ - **Lately used**: which secrets each command was given, how, the command and the conversation, in Settings → Vault.
14
+ - **Wiped**: values in tool results and in what goes to the model (as written, base64, URL-encoded) become their names.
15
+
16
+ ## Data and calls
17
+
18
+ Package data (`@celljs/ta-secrets`): `entries` (`{ name, kind, note?, source, createdAt, usedAt?, uses? }[]`, no values), `capture` (`false`: what you send is not taken), `personal` (`false`: personal details are not taken), `uses` (the latest 100 uses, no values).
19
+
20
+ Methods of the host (`pi.host`), called by the web extension with `callHost`, none giving a value: `info()`, `list()`, `add({ name, value, kind?, note? })`, `remove(name)`, `capturing()`, `setCapturing(on)`, `capturingPersonal()`, `setCapturingPersonal(on)`, `uses()`.
21
+
22
+ Not yet: commands in a folder of a remote host (`ssh://`) do not get values.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # Cell - Ta Secrets
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ta 自带的 pi 包(默认开启,可在 设置 → 扩展 关闭):保险箱。Token、密码、密钥、手机号这类信息交给 Ta 用,但不交给模型。设计见 `docs/design/ta-secrets.md`。
4
+
5
+ - **存**:值在 macOS 的登录钥匙串里(服务名 `Ta secrets`);别的系统,或设了 `TA_SECRETS_STORE=file`,在 agent 目录的 `secrets/vault.json`(只有你能读)。
6
+ - **名字**:每条一个名字(`GITHUB_TOKEN`),模型看到的是 `$TA_SECRET_GITHUB_TOKEN`。
7
+ - **收起你发出的密钥**:消息里的 token、私钥、URL 里的密码、`password=…` 在模型读到之前收进保险箱,消息里换成名字(设置 → 保险箱 可关)。
8
+ - **个人信息**:手机号、邮箱、身份证号、银行卡(按校验位识别)也先收进保险箱,模型只看到名字和打码后的样子(`138****5678`);Ta 写文件、填表、发消息等任何工具的参数里用到名字时,执行那一刻填回真值。设置 → 保险箱 可关。
9
+ - **向你要**:缺一个时 Ta 调 `request_secret({ name, purpose })`,弹框让你输入,值不进对话。
10
+ - **用**:bash 命令里写 `"$TA_SECRET_GITHUB_TOKEN"`,Ta 只给这一条命令值(从只有你能读、随即删除的临时文件里读入);会话里存的是原命令。
11
+ - **只发往绑定的主机**:给密钥绑定主机后(GitHub、GitLab、Gitee 的 token 默认绑定),命令里拿到的只是占位,它的 HTTPS 经 Ta 本机的代理出去,代理只对这些主机把占位换成真值(请求头和 URL);运行 git 的命令也这样自动拿到 token。需要本机有 `openssl`。
12
+ - **SSH**:私钥由每条可能连 SSH 的命令(ssh、scp、rsync、git)自己的 ssh-agent 持有,不进环境变量,命令结束 agent 就关掉。
13
+ - **最近使用**:每次给出密钥都记下哪些、怎么给的、命令和对话,设置 → 保险箱 里能看到。
14
+ - **擦**:工具结果和发给模型的内容里出现的值(原文、base64、URL 编码)都换成名字。
15
+
16
+ ## 数据与调用
17
+
18
+ 包数据(`@celljs/ta-secrets`):`entries`(`{ name, kind, note?, source, createdAt, usedAt?, uses? }[]`,不含值)、`capture`(`false` 时不收起发出的密钥)、`personal`(`false` 时不收起个人信息)、`uses`(最近 100 次使用,不含值)。
19
+
20
+ 包宿主(`pi.host`)的方法,Web 扩展经 `callHost` 调用,都不返回值:`info()`、`list()`、`add({ name, value, kind?, note? })`、`remove(name)`、`capturing()`、`setCapturing(on)`、`capturingPersonal()`、`setCapturingPersonal(on)`、`uses()`。
21
+
22
+ 暂不支持:远程主机(`ssh://`)目录里的命令拿不到值。
@@ -0,0 +1,462 @@
1
+ // ../ta-protocol/esm/common/ta-extension-host.js
2
+ var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
3
+ var TA_HOST_EVENT = "ta:host";
4
+ var TaHostUtil;
5
+ (function(TaHostUtil2) {
6
+ TaHostUtil2.WAIT_MS = 1000;
7
+ function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
8
+ return new Promise((resolve) => {
9
+ let heard = false;
10
+ let answered = false;
11
+ const timer = setTimeout(() => resolve(undefined), waitMs);
12
+ const request = {
13
+ name,
14
+ heard: () => {
15
+ heard = true;
16
+ },
17
+ resolve: (answer) => {
18
+ answered = true;
19
+ clearTimeout(timer);
20
+ resolve(answer);
21
+ }
22
+ };
23
+ events.emit(TA_HOST_EVENT, request);
24
+ if (!heard && !answered) {
25
+ clearTimeout(timer);
26
+ resolve(undefined);
27
+ }
28
+ });
29
+ }
30
+ TaHostUtil2.reach = reach;
31
+ function marked(systemPrompt, mark) {
32
+ return role(systemPrompt).includes(mark);
33
+ }
34
+ TaHostUtil2.marked = marked;
35
+ function role(systemPrompt) {
36
+ if (!systemPrompt) {
37
+ return "";
38
+ }
39
+ const open = `<addendum>
40
+ `;
41
+ const start = systemPrompt.indexOf(open);
42
+ const context = systemPrompt.indexOf(`<project_context>
43
+ `);
44
+ if (start < 0 || context >= 0 && context < start) {
45
+ return "";
46
+ }
47
+ const end = systemPrompt.indexOf(`
48
+ </addendum>`, start);
49
+ return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
50
+ }
51
+ TaHostUtil2.role = role;
52
+ })(TaHostUtil || (TaHostUtil = {}));
53
+ var TA_ASK_ENTRY = "ta-ask";
54
+ var TaAskUtil;
55
+ (function(TaAskUtil2) {
56
+ const LENGTH = 120;
57
+ function entry(question) {
58
+ const line = question.replace(/\s+/g, " ").trim();
59
+ return { question: line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line };
60
+ }
61
+ TaAskUtil2.entry = entry;
62
+ function asking(entries) {
63
+ var _a;
64
+ for (let i = entries.length - 1;i >= 0; i--) {
65
+ const entry2 = entries[i];
66
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
67
+ return;
68
+ }
69
+ if (entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY) {
70
+ return read(entry2);
71
+ }
72
+ }
73
+ return;
74
+ }
75
+ TaAskUtil2.asking = asking;
76
+ function next(asked, entry2) {
77
+ var _a;
78
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
79
+ return;
80
+ }
81
+ return entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY ? read(entry2) : asked;
82
+ }
83
+ TaAskUtil2.next = next;
84
+ function read(found) {
85
+ var _a;
86
+ const question = (_a = found.data) === null || _a === undefined ? undefined : _a.question;
87
+ if (typeof question !== "string" || !question.trim()) {
88
+ return;
89
+ }
90
+ const at = found.timestamp ? Date.parse(found.timestamp) : Number.NaN;
91
+ return { question: entry(question).question, at: Number.isNaN(at) ? 0 : at };
92
+ }
93
+ })(TaAskUtil || (TaAskUtil = {}));
94
+
95
+ // web-src/command-prelude.ts
96
+ var CommandPrelude;
97
+ ((CommandPrelude) => {
98
+ function quote(value) {
99
+ return `'${value.replace(/'/g, `'\\''`)}'`;
100
+ }
101
+ CommandPrelude.quote = quote;
102
+ function usesGit(command) {
103
+ return /(^|[\s;&|(`])git\s+-?[A-Za-z]/.test(command);
104
+ }
105
+ CommandPrelude.usesGit = usesGit;
106
+ function usesSsh(command) {
107
+ return /(^|[\s;&|(`/])(ssh|scp|sftp|rsync|git)(\s|$)/.test(command);
108
+ }
109
+ CommandPrelude.usesSsh = usesSsh;
110
+ function gitHelper(name, user) {
111
+ return `!f() { test "$1" = get || return 0; printf 'username=%s\\npassword=%s\\n' ${quote(user)} "$TA_SECRET_${name}"; }; f`;
112
+ }
113
+ CommandPrelude.gitHelper = gitHelper;
114
+ function script(parts) {
115
+ const lines = [];
116
+ for (const [name, value] of parts.env) {
117
+ lines.push(`export TA_SECRET_${name}=${quote(value)}`);
118
+ }
119
+ if (parts.git.length) {
120
+ lines.push("ta_git=${GIT_CONFIG_COUNT:-0}");
121
+ const config = (key, value) => {
122
+ lines.push(`export "GIT_CONFIG_KEY_$ta_git"=${quote(key)} "GIT_CONFIG_VALUE_$ta_git"=${quote(value)}`, "ta_git=$((ta_git + 1))");
123
+ };
124
+ for (const one of parts.git) {
125
+ const key = `credential.https://${one.host}.helper`;
126
+ config(key, "");
127
+ config(key, gitHelper(one.name, one.user));
128
+ }
129
+ lines.push("export GIT_CONFIG_COUNT=$ta_git GIT_TERMINAL_PROMPT=0", "unset ta_git");
130
+ }
131
+ if (parts.proxy) {
132
+ const url = quote(parts.proxy.url);
133
+ const bundle = quote(parts.proxy.bundle);
134
+ lines.push(`export HTTPS_PROXY=${url} https_proxy=${url} HTTP_PROXY=${url} http_proxy=${url} NODE_USE_ENV_PROXY=1`, "export NO_PROXY='localhost,127.0.0.1,::1' no_proxy='localhost,127.0.0.1,::1'", `export SSL_CERT_FILE=${bundle} CURL_CA_BUNDLE=${bundle} REQUESTS_CA_BUNDLE=${bundle} NODE_EXTRA_CA_CERTS=${bundle} GIT_SSL_CAINFO=${bundle} DENO_CERT=${bundle}`, "unset ALL_PROXY all_proxy");
135
+ }
136
+ if (parts.keys.length) {
137
+ lines.push('eval "$(ssh-agent -s -t 1800)" >/dev/null');
138
+ for (const key of parts.keys) {
139
+ lines.push(`ssh-add -q ${quote(key)} </dev/null >/dev/null 2>&1`);
140
+ }
141
+ lines.push("trap 'ssh-agent -k >/dev/null 2>&1' EXIT");
142
+ }
143
+ lines.push("true");
144
+ return `${lines.join(`
145
+ `)}
146
+ `;
147
+ }
148
+ CommandPrelude.script = script;
149
+ })(CommandPrelude ||= {});
150
+
151
+ // web-src/secrets-protocol.ts
152
+ var NAME = "@celljs/ta-secrets";
153
+ var SECTION = "ta-secrets";
154
+ var REQUEST_TOOL = "request_secret";
155
+ var ENV_PREFIX = "TA_SECRET_";
156
+ var Keys;
157
+ ((Keys) => {
158
+ Keys.ENTRIES = "entries";
159
+ Keys.CAPTURE = "capture";
160
+ Keys.PERSONAL = "personal";
161
+ Keys.USES = "uses";
162
+ })(Keys ||= {});
163
+ var SecretNames;
164
+ ((SecretNames) => {
165
+ SecretNames.MAX = 48;
166
+ function normalize(name) {
167
+ return name.trim().replace(/^\$?\{?TA_SECRET_/i, "").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase().slice(0, SecretNames.MAX);
168
+ }
169
+ SecretNames.normalize = normalize;
170
+ function valid(name) {
171
+ return /^[A-Z0-9][A-Z0-9_]*$/.test(name) && name.length <= SecretNames.MAX;
172
+ }
173
+ SecretNames.valid = valid;
174
+ function env(name) {
175
+ return ENV_PREFIX + name;
176
+ }
177
+ SecretNames.env = env;
178
+ function handle(name) {
179
+ return `$${env(name)}`;
180
+ }
181
+ SecretNames.handle = handle;
182
+ function references(command) {
183
+ return [...new Set([...command.matchAll(/\bTA_SECRET_([A-Z0-9_]+)/g)].map((match) => match[1]))];
184
+ }
185
+ SecretNames.references = references;
186
+ function free(base, taken) {
187
+ const name = normalize(base) || "SECRET";
188
+ if (!taken.has(name)) {
189
+ return name;
190
+ }
191
+ for (let n = 2;; n++) {
192
+ const next = `${name.slice(0, SecretNames.MAX - String(n).length - 1)}_${n}`;
193
+ if (!taken.has(next)) {
194
+ return next;
195
+ }
196
+ }
197
+ }
198
+ SecretNames.free = free;
199
+ function looksSecret(value) {
200
+ if (/[()[\]{}<>]/.test(value)) {
201
+ return false;
202
+ }
203
+ return /[0-9]/.test(value) && /[A-Za-z]/.test(value) || value.length >= 20;
204
+ }
205
+ SecretNames.looksSecret = looksSecret;
206
+ function hosts(value) {
207
+ const items = Array.isArray(value) ? value : typeof value === "string" ? value.split(/[\s,;]+/) : [];
208
+ const hosts2 = items.map((item) => String(item).trim().toLowerCase().replace(/^[a-z]+:\/\//, "").replace(/^[^@/]*@/, "").replace(/\/.*$/, "")).filter((host) => /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+(:\d{1,5})?$/.test(host));
209
+ return [...new Set(hosts2)];
210
+ }
211
+ SecretNames.hosts = hosts;
212
+ function defaultHosts(name) {
213
+ return /GITHUB/.test(name) ? ["github.com", "api.github.com"] : /GITLAB/.test(name) ? ["gitlab.com"] : /GITEE/.test(name) ? ["gitee.com"] : [];
214
+ }
215
+ SecretNames.defaultHosts = defaultHosts;
216
+ function gitUser(entry, host) {
217
+ return entry.gitUser || (host === "gitlab.com" || host.startsWith("gitlab.") ? "oauth2" : "x-access-token");
218
+ }
219
+ SecretNames.gitUser = gitUser;
220
+ function privateKey(value) {
221
+ return /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*-----END [A-Z0-9 ]*PRIVATE KEY-----/.test(value);
222
+ }
223
+ SecretNames.privateKey = privateKey;
224
+ function uses(value) {
225
+ return Array.isArray(value) ? value.filter((use) => !!use && typeof use === "object" && typeof use.at === "number" && Array.isArray(use.names)) : [];
226
+ }
227
+ SecretNames.uses = uses;
228
+ function entries(value) {
229
+ if (!Array.isArray(value)) {
230
+ return [];
231
+ }
232
+ return value.map((entry) => entry && typeof entry === "object" && Array.isArray(entry.git) && !entry.hosts ? (({ git, ...rest }) => ({ ...rest, hosts: git }))(entry) : entry).filter((entry) => !!entry && typeof entry === "object" && typeof entry.name === "string" && valid(entry.name));
233
+ }
234
+ SecretNames.entries = entries;
235
+ })(SecretNames ||= {});
236
+
237
+ // ../ta-protocol/esm/common/language.js
238
+ var TaLanguageUtil;
239
+ (function(TaLanguageUtil2) {
240
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
241
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
242
+ function of(tag) {
243
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
244
+ if (/^zh(\b|-)/.test(said)) {
245
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
246
+ }
247
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
248
+ }
249
+ TaLanguageUtil2.of = of;
250
+ function server(env = typeof process === "undefined" ? {} : process.env) {
251
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
252
+ }
253
+ TaLanguageUtil2.server = server;
254
+ function pick(language, words) {
255
+ return words[of(language)];
256
+ }
257
+ TaLanguageUtil2.pick = pick;
258
+ function say(words) {
259
+ return words[server()];
260
+ }
261
+ TaLanguageUtil2.say = say;
262
+ function chinese(language) {
263
+ return of(language).startsWith("zh");
264
+ }
265
+ TaLanguageUtil2.chinese = chinese;
266
+ function cjk(language) {
267
+ return of(language) !== "en-US";
268
+ }
269
+ TaLanguageUtil2.cjk = cjk;
270
+ function list(language, items) {
271
+ return items.join(cjk(language) ? "、" : ", ");
272
+ }
273
+ TaLanguageUtil2.list = list;
274
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
275
+
276
+ // web-src/server-texts.ts
277
+ var SecretsServerTexts;
278
+ ((SecretsServerTexts) => {
279
+ function language(env = process.env) {
280
+ return TaLanguageUtil.of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
281
+ }
282
+ SecretsServerTexts.language = language;
283
+ function captured(names) {
284
+ const list = TaLanguageUtil.list(language(), names);
285
+ return TaLanguageUtil.say({
286
+ "zh-CN": `已把 ${list} 收进保险箱,Ta 只看到名字`,
287
+ "zh-TW": `已把 ${list} 收進保險箱,Ta 只看到名字`,
288
+ "en-US": `Kept ${list} in the vault: Ta sees only the name`,
289
+ "ja-JP": `${list} を金庫に保管しました。Ta には名前だけが見えます`
290
+ });
291
+ }
292
+ SecretsServerTexts.captured = captured;
293
+ function ask(name, purpose, hosts = []) {
294
+ const host = TaLanguageUtil.list(language(), hosts);
295
+ return hosts.length ? TaLanguageUtil.say({
296
+ "zh-CN": `Ta 需要 ${name}(只发往 ${host}):${purpose}`,
297
+ "zh-TW": `Ta 需要 ${name}(只發往 ${host}):${purpose}`,
298
+ "en-US": `Ta needs ${name} (sent to ${host} only): ${purpose}`,
299
+ "ja-JP": `Ta に ${name} が必要です(${host} にのみ送信):${purpose}`
300
+ }) : TaLanguageUtil.say({
301
+ "zh-CN": `Ta 需要 ${name}:${purpose}`,
302
+ "zh-TW": `Ta 需要 ${name}:${purpose}`,
303
+ "en-US": `Ta needs ${name}: ${purpose}`,
304
+ "ja-JP": `Ta に ${name} が必要です:${purpose}`
305
+ });
306
+ }
307
+ SecretsServerTexts.ask = ask;
308
+ function keyPlaceholder() {
309
+ return TaLanguageUtil.say({
310
+ "zh-CN": "私钥文件的路径,如 ~/.ssh/id_ed25519",
311
+ "zh-TW": "私鑰檔案的路徑,如 ~/.ssh/id_ed25519",
312
+ "en-US": "The path of the private key, as ~/.ssh/id_ed25519",
313
+ "ja-JP": "秘密鍵ファイルのパス(例:~/.ssh/id_ed25519)"
314
+ });
315
+ }
316
+ SecretsServerTexts.keyPlaceholder = keyPlaceholder;
317
+ function askPlaceholder() {
318
+ return TaLanguageUtil.say({
319
+ "zh-CN": "只存进保险箱,不进对话",
320
+ "zh-TW": "只存進保險箱,不進對話",
321
+ "en-US": "Goes into the vault, not the conversation",
322
+ "ja-JP": "金庫にだけ保管され、会話には入りません"
323
+ });
324
+ }
325
+ SecretsServerTexts.askPlaceholder = askPlaceholder;
326
+ })(SecretsServerTexts ||= {});
327
+
328
+ // web-src/extension.ts
329
+ var SHELLS = { bash: "command" };
330
+ function activate(pi) {
331
+ let reached;
332
+ const vault = () => reached ??= TaHostUtil.reach(pi.events, NAME).then((found) => found?.service?.vault);
333
+ pi.on("session_start", () => {
334
+ vault();
335
+ });
336
+ pi.on("before_agent_start", async (event) => {
337
+ const found = await vault();
338
+ if (found) {
339
+ event.systemPromptOptions.sections = { ...event.systemPromptOptions.sections, [SECTION]: await found.prompt() };
340
+ }
341
+ });
342
+ pi.on("input", async (event, ctx) => {
343
+ const found = await vault();
344
+ if (!found || !event.text) {
345
+ return { action: "continue" };
346
+ }
347
+ const { text, names } = await found.capture(event.text);
348
+ if (names.length) {
349
+ ctx.ui.notify(SecretsServerTexts.captured(names), "info");
350
+ }
351
+ return text === event.text ? { action: "continue" } : { action: "transform", text, images: event.images };
352
+ });
353
+ pi.on("tool_call", async (event, ctx) => {
354
+ const field = SHELLS[event.toolName];
355
+ if (!field) {
356
+ if (JSON.stringify(event.input ?? {}).includes("TA_SECRET_")) {
357
+ await (await vault())?.fill(event.input, event.toolName, ctx.sessionManager?.getSessionName?.());
358
+ }
359
+ return;
360
+ }
361
+ const command = event.input[field];
362
+ if (typeof command !== "string" || !command.includes("TA_SECRET_") && !CommandPrelude.usesSsh(command)) {
363
+ return;
364
+ }
365
+ const found = await vault();
366
+ const prepared = await found?.prepare(command, { cwd: ctx.cwd, conversation: ctx.sessionManager?.getSessionName?.() });
367
+ if (prepared?.block) {
368
+ return { block: true, reason: prepared.block };
369
+ }
370
+ if (prepared?.prelude) {
371
+ event.input[field] = prepared.prelude + command;
372
+ }
373
+ return;
374
+ });
375
+ pi.on("tool_result", async (event) => {
376
+ const found = await vault();
377
+ const scrubber = await found?.scrubber();
378
+ if (!scrubber || scrubber.empty) {
379
+ return;
380
+ }
381
+ const content = scrubber.value(event.content);
382
+ const details = scrubber.value(event.details);
383
+ const structuredContent = scrubber.value(event.structuredContent);
384
+ if (content === event.content && details === event.details && structuredContent === event.structuredContent) {
385
+ return;
386
+ }
387
+ return { content, details, ...event.structuredContent !== undefined ? { structuredContent } : {} };
388
+ });
389
+ pi.on("context", async (event) => {
390
+ const found = await vault();
391
+ const scrubber = await found?.scrubber();
392
+ if (!scrubber || scrubber.empty) {
393
+ return;
394
+ }
395
+ const messages = scrubber.value(event.messages);
396
+ return messages === event.messages ? undefined : { messages };
397
+ });
398
+ pi.registerTool({
399
+ name: REQUEST_TOOL,
400
+ label: "Ask for a secret",
401
+ description: "Ask the user for a secret the vault lacks (a token, a password, a key, a personal detail such as a phone number): they type it into Ta, it is kept in the vault, and you get its name, $TA_SECRET_<NAME>, to use in bash commands. You never see the value. Use it instead of asking for a secret in the chat.",
402
+ promptSnippet: "Ask the user for a secret, kept in the vault, used by its name",
403
+ parameters: {
404
+ type: "object",
405
+ properties: {
406
+ name: { type: "string", description: "Its name: upper case, digits and _, as GITHUB_TOKEN or DEPLOY_SSH_KEY." },
407
+ purpose: { type: "string", description: 'What it is for, in a short line the user reads: "to push to github.com/acme/app".' },
408
+ kind: {
409
+ type: "string",
410
+ enum: ["credential", "personal", "ssh_key"],
411
+ description: "credential (default): a token, a password, a key; personal: a detail of the user; ssh_key: a private key of SSH, which the user gives as the path of its file."
412
+ },
413
+ hosts: {
414
+ type: "string",
415
+ description: 'The hosts it may go to, as "api.example.com" or "github.com, api.github.com": it then reaches only them (through the proxy of the vault; git over https gets it there by itself). Give them whenever the secret is for a service of the network.'
416
+ }
417
+ },
418
+ required: ["name", "purpose"]
419
+ },
420
+ execute: async (_id, params, _signal, _update, ctx) => {
421
+ const found = await vault();
422
+ if (!found) {
423
+ throw new Error("The vault needs the Ta service.");
424
+ }
425
+ if (!ctx.hasUI) {
426
+ throw new Error("There is no one to ask here: the user adds secrets in Ta, Settings, Vault.");
427
+ }
428
+ const name = SecretNames.normalize(String(params.name ?? ""));
429
+ if (!SecretNames.valid(name)) {
430
+ throw new Error("Give a name of letters, digits and _, as GITHUB_TOKEN.");
431
+ }
432
+ const purpose = String(params.purpose ?? "").trim().slice(0, 200);
433
+ const key = params.kind === "ssh_key";
434
+ const hosts = key ? [] : SecretNames.hosts(params.hosts);
435
+ const value = await ctx.ui.input(SecretsServerTexts.ask(name, purpose, hosts), key ? SecretsServerTexts.keyPlaceholder() : SecretsServerTexts.askPlaceholder()).catch(() => {
436
+ return;
437
+ });
438
+ if (!value?.trim()) {
439
+ throw new Error(`The user did not give ${name}.`);
440
+ }
441
+ if (key) {
442
+ await found.importKey(name, value, purpose);
443
+ return {
444
+ content: [
445
+ {
446
+ type: "text",
447
+ text: `Kept in the vault as the SSH key ${name}: ssh, scp, rsync and git over SSH get it by themselves. Do not name it.`
448
+ }
449
+ ],
450
+ details: { name }
451
+ };
452
+ }
453
+ await found.add({ name, value: value.trim(), kind: params.kind === "personal" ? "personal" : "credential", note: purpose, source: "asked", hosts });
454
+ const handle = SecretNames.handle(name);
455
+ const how = hosts.length ? ` It reaches only ${hosts.join(", ")}: use "${handle}" in a header or a query of a request to them (through Ta's proxy); git over https gets it there by itself.` : ` Use it in bash commands as "${handle}".`;
456
+ return { content: [{ type: "text", text: `Kept in the vault as ${handle}.${how}` }], details: { name } };
457
+ }
458
+ });
459
+ }
460
+ export {
461
+ activate as default
462
+ };