@operad-io/access-match 0.1.1 → 0.2.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/src/outward.ts ADDED
@@ -0,0 +1,302 @@
1
+ /**
2
+ * Outward writes: what leaves operad (a message, mail or post, a push, or a
3
+ * call to an outside service), the target a person is shown, and the guard a
4
+ * background run uses before the write. The lists and target shapes are in
5
+ * `REFERENCE.md` and ADR 0025.
6
+ */
7
+
8
+ import { messageOf, oneLine } from "@operad-io/engine";
9
+ import type { Actor, AskAnswer, AskRequest, FlowDefinition, OutwardTargets, OutwardWrite, OutwardWrites } from "@operad-io/engine";
10
+ import { baseName, levels, scan, findDenied, parseRule, type Part } from "./command.ts";
11
+ import { appendTargetGrant, targetGrantFor, type TargetGrant } from "./target-grants.ts";
12
+
13
+ /** The choice that lets one outward write through. */
14
+ export const OUTWARD_SEND_ONCE = "send_once";
15
+
16
+ /** The choice that refuses one outward write. */
17
+ export const OUTWARD_REJECT_ONCE = "reject_once";
18
+
19
+ /** The choice that allows this target for this flow definition from now on. */
20
+ export const OUTWARD_ALLOW_TARGET = "allow_target";
21
+
22
+ /** What a background run asks before an outward write. */
23
+ export interface OutwardQuestionOptions {
24
+ /** How long the step waits for an answer; the kernel's own default when absent. */
25
+ readonly graceSecs?: number | undefined;
26
+ /** What happens when the grace passes; a step that cannot wait asks with `reject_once`. */
27
+ readonly onTimeout?: "waiting" | "reject_once" | undefined;
28
+ /** Offer the choice that records a grant for this flow and target. */
29
+ readonly allowTarget?: boolean | undefined;
30
+ }
31
+
32
+ /** The words that name what is about to leave. */
33
+ const ACTION: Readonly<Record<OutwardWrite["kind"], string>> = {
34
+ channel: "Send this message to",
35
+ mail: "Send this mail to",
36
+ post: "Send this post to",
37
+ repository: "Push to",
38
+ service: "Call",
39
+ command: "Run this outward command on",
40
+ };
41
+
42
+ /**
43
+ * The question about one outward write. It names the target and carries the
44
+ * whole content, so the pending item is also the draft (ADR 0025 D10).
45
+ */
46
+ export function outwardQuestion(write: OutwardWrite, options: OutwardQuestionOptions = {}): AskRequest {
47
+ const target = oneLine(write.target);
48
+ const head = `${ACTION[write.kind]} ${target}?`;
49
+ const content = write.content?.trim();
50
+ const prompt = content === undefined || content.length === 0 ? head : `${head}\n\n${content}`;
51
+ const choices = options.allowTarget === true
52
+ ? [OUTWARD_SEND_ONCE, OUTWARD_ALLOW_TARGET, OUTWARD_REJECT_ONCE]
53
+ : [OUTWARD_SEND_ONCE, OUTWARD_REJECT_ONCE];
54
+ return {
55
+ prompt,
56
+ choices,
57
+ choiceInfo: {
58
+ [OUTWARD_SEND_ONCE]: { label: "Send once", hint: "Make this write once.", role: "primary" },
59
+ ...(options.allowTarget === true
60
+ ? { [OUTWARD_ALLOW_TARGET]: { label: "Always for this flow and target", hint: "Do not ask again for this target unless the flow changes." } }
61
+ : {}),
62
+ [OUTWARD_REJECT_ONCE]: { label: "Reject", hint: "Do not make this write." },
63
+ },
64
+ ...(options.graceSecs === undefined ? {} : { graceSecs: options.graceSecs }),
65
+ ...(options.onTimeout === undefined ? {} : { onTimeout: options.onTimeout }),
66
+ };
67
+ }
68
+
69
+ /** Whether a target is on the profile's outward allowlist, or is an owner channel. */
70
+ export function outwardAllowed(profile: unknown, write: OutwardWrite): boolean {
71
+ if (write.owner === true) return true;
72
+ const record = typeof profile === "object" && profile !== null && !Array.isArray(profile) ? profile : {};
73
+ const allow = Reflect.get(record, "outwardAllow");
74
+ if (!Array.isArray(allow)) return false;
75
+ const target = write.target.trim();
76
+ return allow.some((entry) => typeof entry === "string" && entry.trim() === target);
77
+ }
78
+
79
+ /** What `guardOutward` needs of the step that makes the write. */
80
+ export interface OutwardGuardContext {
81
+ readonly access: unknown;
82
+ /** `ctx.ask` of the step. */
83
+ readonly ask: (request: AskRequest) => Promise<AskAnswer>;
84
+ /** Whether a person's message in this chat started the run. */
85
+ readonly personStarted: boolean;
86
+ /** What happens when the grace passes; absent keeps the kernel's `waiting`. */
87
+ readonly onTimeout?: "waiting" | "reject_once" | undefined;
88
+ /** The operad home where target grants are kept. */
89
+ readonly home?: string | undefined;
90
+ /** The flow whose definition a target grant is bound to. */
91
+ readonly flow?: FlowDefinition | undefined;
92
+ /** The clock of the answer's time; defaults to `Date.now`. */
93
+ readonly now?: (() => number) | undefined;
94
+ /** Reports a grant that could not be written; the write still goes once. */
95
+ readonly onLog?: ((message: string) => void) | undefined;
96
+ }
97
+
98
+ /**
99
+ * Whether one outward write may go ahead: a person-started run, a target
100
+ * on the allowlist, and a target grant for this flow definition do not ask;
101
+ * every other background write asks, and only `send_once` or
102
+ * `allow_target` lets it through. The chat's exact-call `allow_always` is not
103
+ * consulted (ADR 0025 D3, D10 and D12).
104
+ */
105
+ export async function guardOutward(
106
+ ctx: OutwardGuardContext,
107
+ write: OutwardWrite,
108
+ ): Promise<boolean> {
109
+ // A chat at full asks nothing outward; its deny rules are checked elsewhere.
110
+ if (typeof ctx.access === "object" && ctx.access !== null && Reflect.get(ctx.access, "level") === "full") return true;
111
+ if (ctx.personStarted || outwardAllowed(ctx.access, write)) return true;
112
+ let grant: TargetGrant | undefined;
113
+ if (ctx.home !== undefined && ctx.flow !== undefined) {
114
+ try {
115
+ grant = await targetGrantFor(ctx.home, ctx.flow, write.target);
116
+ } catch (error) {
117
+ ctx.onLog?.(
118
+ `the target grants could not be read: ${messageOf(error)}; this write asks`,
119
+ );
120
+ }
121
+ }
122
+ if (grant !== undefined) return true;
123
+ const allowTarget = ctx.home !== undefined && ctx.flow !== undefined;
124
+ const answer = await ctx.ask(
125
+ outwardQuestion(write, {
126
+ ...(ctx.onTimeout === undefined ? {} : { onTimeout: ctx.onTimeout }),
127
+ ...(allowTarget ? { allowTarget: true } : {}),
128
+ }),
129
+ );
130
+ if (answer.rejected === true) return false;
131
+ if (answer.choice === OUTWARD_ALLOW_TARGET && ctx.home !== undefined && ctx.flow !== undefined) {
132
+ const by: Actor = answer.actor ?? { via: "unknown", id: "unknown" };
133
+ try {
134
+ await appendTargetGrant(ctx.home, ctx.flow, write, by, (ctx.now ?? Date.now)());
135
+ } catch (error) {
136
+ ctx.onLog?.(
137
+ `the target grant could not be written: ${messageOf(error)}; this write runs once`,
138
+ );
139
+ }
140
+ return true;
141
+ }
142
+ return answer.choice === OUTWARD_SEND_ONCE;
143
+ }
144
+
145
+
146
+ /** The chat clients whose message is a person's message in that chat. */
147
+ const PERSON_MESSAGE_SOURCES = new Set(["ios", "telegram", "cli", "tui", "other"]);
148
+
149
+ /**
150
+ * Whether a run was started by a person writing in its chat. A missing
151
+ * trigger is a run a person started by hand; a message from one of the chat's
152
+ * own clients is a person's message; every other event is a background run.
153
+ */
154
+ export function personStarted(trigger: unknown): boolean {
155
+ if (trigger === undefined || trigger === null) return true;
156
+ if (typeof trigger !== "object" || Array.isArray(trigger)) return false;
157
+ const record = trigger as Record<string, unknown>;
158
+ return (
159
+ record["type"] === "message" &&
160
+ typeof record["source"] === "string" &&
161
+ PERSON_MESSAGE_SOURCES.has(record["source"])
162
+ );
163
+ }
164
+
165
+ function writesOf(value: OutwardWrites): readonly OutwardWrite[] {
166
+ if (value === undefined) return [];
167
+ return Array.isArray(value) ? value : [value as OutwardWrite];
168
+ }
169
+
170
+ /**
171
+ * The outward writes a step or action declares for one call. A declaration
172
+ * that says it reaches outside but names no target counts the whole call as
173
+ * one outward write: nothing can be allowlisted, so it asks.
174
+ */
175
+ export function declaredOutward(
176
+ declaration: { readonly reachesOutside?: boolean | undefined; readonly outward?: OutwardTargets | undefined },
177
+ input: unknown,
178
+ ): readonly OutwardWrite[] {
179
+ if (declaration.outward !== undefined) return writesOf(declaration.outward(input));
180
+ if (declaration.reachesOutside !== true) return [];
181
+ const content = typeof input === "string" ? input : JSON.stringify(input) ?? String(input);
182
+ return [{ kind: "command", target: content, content }];
183
+ }
184
+
185
+ /** The outward writes of one shell command that matches the profile's `outwardCommands`. */
186
+ export function outwardCommandWrites(profile: unknown, command: string): readonly OutwardWrite[] {
187
+ const record = typeof profile === "object" && profile !== null && !Array.isArray(profile) ? profile : {};
188
+ const rules = Array.isArray(Reflect.get(record, "outwardCommands"))
189
+ ? (Reflect.get(record, "outwardCommands") as unknown[]).filter((entry): entry is string => typeof entry === "string")
190
+ : [];
191
+ if (rules.length === 0) return [];
192
+ const parsed = rules.map((text) => parseRule(text)).filter((rule) => rule !== undefined);
193
+ const { parts } = scan(command);
194
+ const writes: OutwardWrite[] = [];
195
+ for (const part of parts) {
196
+ if (findDenied(parsed, [part]) === undefined) continue;
197
+ const write = commandWrite(part);
198
+ if (write === undefined) continue;
199
+ if (writes.some((found) => found.target === write.target && found.content === write.content)) continue;
200
+ writes.push(write);
201
+ }
202
+ return writes;
203
+ }
204
+
205
+ function wordsOf(part: Part): readonly string[] {
206
+ return levels(part.words).at(-1) ?? part.words;
207
+ }
208
+
209
+ function nonOptions(args: readonly string[]): readonly string[] {
210
+ const found: string[] = [];
211
+ let options = true;
212
+ for (const arg of args) {
213
+ if (options && arg === "--") {
214
+ options = false;
215
+ continue;
216
+ }
217
+ if (options && arg.startsWith("-")) continue;
218
+ found.push(arg);
219
+ }
220
+ return found;
221
+ }
222
+
223
+ function branchOf(ref: string): string {
224
+ const colon = ref.indexOf(":");
225
+ const name = colon === -1 ? ref : ref.slice(colon + 1);
226
+ return name.replace(/^refs\/heads\//, "");
227
+ }
228
+
229
+ function remoteAndBranch(args: readonly string[]): { readonly remote: string | undefined; readonly branch: string | undefined } {
230
+ const operands = nonOptions(args);
231
+ return { remote: operands[0], branch: operands[1] === undefined ? undefined : branchOf(operands[1]) };
232
+ }
233
+
234
+ function curlIsWrite(args: readonly string[]): boolean {
235
+ for (let index = 0; index < args.length; index += 1) {
236
+ const arg = args[index] ?? "";
237
+ if (["-d", "--data", "--data-raw", "--data-binary", "--data-urlencode", "-F", "--form", "-T", "--upload-file"].includes(arg)) {
238
+ return true;
239
+ }
240
+ if (/^-(?:d|F|T)\S/.test(arg) || /^--(?:data|form|upload-file)(?:=|$)/.test(arg)) return true;
241
+ if (arg === "-X" || arg === "--request") {
242
+ const method = (args[index + 1] ?? "").toUpperCase();
243
+ if (method !== "" && method !== "GET" && method !== "HEAD" && method !== "OPTIONS") return true;
244
+ index += 1;
245
+ continue;
246
+ }
247
+ const inline = /^--request=(.*)$/.exec(arg) ?? /^-X(.*)$/.exec(arg);
248
+ if (inline !== null) {
249
+ const method = (inline[1] ?? "").toUpperCase();
250
+ if (method !== "" && method !== "GET" && method !== "HEAD" && method !== "OPTIONS") return true;
251
+ }
252
+ }
253
+ return false;
254
+ }
255
+
256
+ function urlOf(args: readonly string[]): string | undefined {
257
+ return args.find((arg) => /^https?:\/\//i.test(arg));
258
+ }
259
+
260
+ function commandWrite(part: Part): OutwardWrite | undefined {
261
+ const words = wordsOf(part);
262
+ const program = baseName(words.at(0) ?? "");
263
+ const args = words.slice(1);
264
+
265
+ if (program === "git" && args[0] === "push") {
266
+ const { remote, branch } = remoteAndBranch(args.slice(1));
267
+ const target = remote === undefined ? part.text : branch === undefined ? remote : `${remote}/${branch}`;
268
+ return { kind: "repository", target, content: part.text };
269
+ }
270
+ if (program === "gh") {
271
+ const target = part.text;
272
+ return { kind: "service", target, content: part.text };
273
+ }
274
+ if (program === "curl") {
275
+ if (!curlIsWrite(args)) return undefined;
276
+ const target = urlOf(args) ?? part.text;
277
+ return { kind: "service", target, content: part.text };
278
+ }
279
+ if (program === "wget") {
280
+ if (!args.some((arg) => /^--(?:post-data|post-file|method|body-data|body-file)/.test(arg))) return undefined;
281
+ const target = urlOf(args) ?? part.text;
282
+ return { kind: "service", target, content: part.text };
283
+ }
284
+ if (program === "mail" || program === "mailx" || program === "sendmail") {
285
+ const recipients = nonOptions(args).filter((arg) => !arg.startsWith("<"));
286
+ const target = recipients.length === 0 ? part.text : recipients.join(", ");
287
+ return { kind: "mail", target, content: part.text };
288
+ }
289
+ return { kind: "command", target: part.text, content: part.text };
290
+ }
291
+
292
+ /** The outward writes of one call to a step or action, for a plugin that guards itself. */
293
+ export async function guardDeclaredOutward(
294
+ ctx: OutwardGuardContext,
295
+ declaration: { readonly reachesOutside?: boolean | undefined; readonly outward?: OutwardTargets | undefined },
296
+ input: unknown,
297
+ ): Promise<boolean> {
298
+ for (const write of declaredOutward(declaration, input)) {
299
+ if (!(await guardOutward(ctx, write))) return false;
300
+ }
301
+ return true;
302
+ }
package/src/readonly.ts CHANGED
@@ -2,20 +2,28 @@
2
2
  * The commands a read-only working directory lets run. Anything not recognised
3
3
  * here is not read-only: the allowlist is the rule, so a new way to write a file
4
4
  * never needs a new pattern. A command is read-only only when every part of it
5
- * (split at `|`, `;`, `&&`, `||`, `&`, newlines) is, and it has no output
6
- * redirection, no substitution and no inline code.
5
+ * (split at `|`, `;`, `&&`, `||`, `&`, newlines) is, and it has no redirection
6
+ * that writes a file, no substitution and no inline code.
7
7
  */
8
8
 
9
9
  import { scan, baseName } from "./command.ts";
10
10
 
11
11
  /** Programs that only read, whatever their arguments (the ones with a writing option are checked below). */
12
- const PLAIN = new Set(["ls", "cat", "head", "tail", "wc", "grep", "rg", "pwd", "stat", "file", "du", "tree", "which", "true"]);
12
+ const PLAIN = new Set([
13
+ "ls", "cat", "head", "tail", "wc", "grep", "rg", "pwd", "stat", "file", "du", "tree", "which", "true",
14
+ "cd", "echo", "printf", "sort", "cut", "tr", "basename", "dirname", "realpath", "readlink", "date", "jq", "diff", "cmp",
15
+ ]);
13
16
 
14
17
  /** Options of an otherwise reading program that write or run something. */
15
18
  const WRITING_OPTIONS: Readonly<Record<string, RegExp>> = {
16
19
  tree: /^-[a-zA-Z]*o|^--output/,
17
20
  rg: /^--pre(=|$)|^--hostname-bin|^--search-zip$|^-z$/,
18
21
  grep: /^--output/,
22
+ printf: /^-[^-]*v/,
23
+ sort: /^-[^-]*o|^--output|^--compress-program(=|$)/,
24
+ date: /^-[^-]*s|^--set/,
25
+ jq: /^-[^-]*i|^--in-place|^--output/,
26
+ diff: /^-[^-]*o|^--output/,
19
27
  };
20
28
 
21
29
  const GIT_READ = new Set(["status", "log", "diff", "show", "blame", "rev-parse", "ls-files", "ls-tree", "shortlog", "describe", "cat-file", "grep"]);
@@ -23,25 +31,79 @@ const GIT_WRITING_OPTION = /^--output|^--ext-diff|^--textconv|^-o$|^--open-files
23
31
  const FIND_WRITING = new Set(["-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls"]);
24
32
  const SED_SCRIPT = /^\d*(?:,(?:\d+|\$))?p$/;
25
33
 
34
+ /** A redirection that writes nowhere: to `/dev/null`, or one file descriptor onto another. */
35
+ const HARMLESS_FD_DUP = new Set(["2>&1", "1>&2"]);
36
+ const OUTPUT_REDIRECT = /^(?:(\d+|&)?)(>>?)(.*)$/;
37
+ const INPUT_REDIRECT = new Set(["<", "<<", "<<<"]);
38
+
39
+ /**
40
+ * The words without the redirections that write nowhere, or undefined when one
41
+ * of them writes a file. A separated `> /dev/null` is two words; a glued
42
+ * `2>/dev/null` is one.
43
+ */
44
+ function withoutWritingRedirections(words: readonly string[]): readonly string[] | undefined {
45
+ const rest: string[] = [];
46
+ for (let index = 0; index < words.length; index += 1) {
47
+ const word = words[index] ?? "";
48
+ if (!word.includes(">")) {
49
+ // An input redirect reads a file; it writes nothing. Drop it and its target.
50
+ if (INPUT_REDIRECT.has(word)) index += 1;
51
+ else if (word.startsWith("<") && !word.startsWith("<(")) continue;
52
+ else rest.push(word);
53
+ continue;
54
+ }
55
+ if (HARMLESS_FD_DUP.has(word)) continue;
56
+ const match = OUTPUT_REDIRECT.exec(word);
57
+ if (match === null) return undefined;
58
+ const glued = match[3] ?? "";
59
+ if (glued.startsWith("&")) return undefined;
60
+ const target = glued.length > 0 ? glued : words[index + 1];
61
+ if (target === undefined) return undefined;
62
+ if (glued.length === 0) index += 1;
63
+ if (target !== "/dev/null") return undefined;
64
+ }
65
+ return rest;
66
+ }
67
+
26
68
  function gitIsReadOnly(words: readonly string[]): boolean {
27
- const sub = words[1];
69
+ // The options before the subcommand that read: `-C <dir>` chooses the
70
+ // directory, and `--no-pager` only stops git from running a pager. The
71
+ // directory stays in the words, so the path rules still check it.
72
+ let index = 1;
73
+ while (index < words.length) {
74
+ const word = words[index] ?? "";
75
+ if (word === "--no-pager") {
76
+ index += 1;
77
+ continue;
78
+ }
79
+ if (word === "-C") {
80
+ if (words[index + 1] === undefined) return false;
81
+ index += 2;
82
+ continue;
83
+ }
84
+ break;
85
+ }
86
+ const sub = words[index];
28
87
  if (sub === undefined || sub.startsWith("-")) return false;
29
- const rest = words.slice(2);
88
+ const rest = words.slice(index + 1);
30
89
  if (sub === "branch") return rest.every((word) => ["--list", "-a", "-r", "-v", "-vv", "--show-current"].includes(word));
31
90
  if (!GIT_READ.has(sub)) return false;
32
91
  return !rest.some((word) => GIT_WRITING_OPTION.test(word));
33
92
  }
34
93
 
35
94
  function partIsReadOnly(words: readonly string[]): boolean {
36
- const first = words[0];
95
+ const plain = withoutWritingRedirections(words);
96
+ if (plain === undefined) return false;
97
+ const first = plain[0];
37
98
  if (first === undefined) return true;
38
99
  const program = baseName(first);
39
- const args = words.slice(1);
40
- if (words.some((word) => word.includes(">"))) return false;
100
+ const args = plain.slice(1);
101
+ if (program === "env") return args.length === 0;
102
+ if (program === "uniq") return args.filter((word) => !word.startsWith("-")).length <= 1;
41
103
  if (PLAIN.has(program)) return !args.some((word) => WRITING_OPTIONS[program]?.test(word) === true);
42
104
  switch (program) {
43
105
  case "git":
44
- return gitIsReadOnly(words);
106
+ return gitIsReadOnly(plain);
45
107
  case "find":
46
108
  return !args.some((word) => FIND_WRITING.has(word));
47
109
  case "sed": {
package/src/summary.ts CHANGED
@@ -33,6 +33,12 @@ export interface SummaryOptions {
33
33
  readonly env?: Readonly<Record<string, string | undefined>> | undefined;
34
34
  /** A command keeps its line breaks (still cut at 500 characters), for a log that shows its first line. */
35
35
  readonly keepLines?: boolean | undefined;
36
+ /**
37
+ * The text is for a question a person answers, so a command the log would
38
+ * hide is shown in full instead: line breaks kept, cut at 500 characters,
39
+ * secret values still masked. A log leaves this unset.
40
+ */
41
+ readonly forQuestion?: boolean | undefined;
36
42
  }
37
43
 
38
44
  /** Keys that hold the main argument of a tool, in the order they are tried. */
@@ -98,6 +104,165 @@ function withoutAssignmentValues(command: string): string {
98
104
  return out + command.slice(at);
99
105
  }
100
106
 
107
+ /** Where one shell word ends, and whether it was read to its end. */
108
+ interface WordEnd {
109
+ readonly end: number;
110
+ readonly complete: boolean;
111
+ }
112
+
113
+ /** The index after the `)` that closes the `(` at `open`, or undefined when it is left open. */
114
+ function afterParen(command: string, open: number): number | undefined {
115
+ let depth = 0;
116
+ let i = open;
117
+ while (i < command.length) {
118
+ const c = command.charAt(i);
119
+ if (c === "\\") {
120
+ i += 2;
121
+ continue;
122
+ }
123
+ if (c === "'") {
124
+ const close = command.indexOf("'", i + 1);
125
+ if (close < 0) return undefined;
126
+ i = close + 1;
127
+ continue;
128
+ }
129
+ if (c === '"') {
130
+ i += 1;
131
+ while (i < command.length && command.charAt(i) !== '"') i += command.charAt(i) === "\\" ? 2 : 1;
132
+ if (i >= command.length) return undefined;
133
+ i += 1;
134
+ continue;
135
+ }
136
+ if (c === "`") {
137
+ i += 1;
138
+ while (i < command.length && command.charAt(i) !== "`") i += command.charAt(i) === "\\" ? 2 : 1;
139
+ if (i >= command.length) return undefined;
140
+ i += 1;
141
+ continue;
142
+ }
143
+ if (c === "(") depth += 1;
144
+ else if (c === ")" && --depth === 0) return i + 1;
145
+ i += 1;
146
+ }
147
+ return undefined;
148
+ }
149
+
150
+ /** The index after the `}` that closes the `{` at `open`, or undefined when it is left open. */
151
+ function afterBrace(command: string, open: number): number | undefined {
152
+ let depth = 0;
153
+ let i = open;
154
+ while (i < command.length) {
155
+ const c = command.charAt(i);
156
+ if (c === "\\") {
157
+ i += 2;
158
+ continue;
159
+ }
160
+ if (c === "'") {
161
+ const close = command.indexOf("'", i + 1);
162
+ if (close < 0) return undefined;
163
+ i = close + 1;
164
+ continue;
165
+ }
166
+ if (c === '"') {
167
+ i += 1;
168
+ while (i < command.length && command.charAt(i) !== '"') i += command.charAt(i) === "\\" ? 2 : 1;
169
+ if (i >= command.length) return undefined;
170
+ i += 1;
171
+ continue;
172
+ }
173
+ if (c === "{") depth += 1;
174
+ else if (c === "}" && --depth === 0) return i + 1;
175
+ i += 1;
176
+ }
177
+ return undefined;
178
+ }
179
+
180
+ /**
181
+ * Where the shell word at `start` ends, skipping quotes and the substitutions
182
+ * whose contents may hold spaces. `complete` is false when a quote or
183
+ * substitution is left open, or a backslash ends the command.
184
+ */
185
+ function wordEnd(command: string, start: number): WordEnd {
186
+ let i = start;
187
+ while (i < command.length) {
188
+ const c = command.charAt(i);
189
+ if (/\s/.test(c)) return { end: i, complete: true };
190
+ if (c === "\\") {
191
+ if (i + 1 >= command.length) return { end: command.length, complete: false };
192
+ i += 2;
193
+ continue;
194
+ }
195
+ if (c === "'") {
196
+ const close = command.indexOf("'", i + 1);
197
+ if (close < 0) return { end: command.length, complete: false };
198
+ i = close + 1;
199
+ continue;
200
+ }
201
+ if (c === '"') {
202
+ i += 1;
203
+ while (i < command.length && command.charAt(i) !== '"') i += command.charAt(i) === "\\" ? 2 : 1;
204
+ if (i >= command.length) return { end: command.length, complete: false };
205
+ i += 1;
206
+ continue;
207
+ }
208
+ if (c === "`") {
209
+ i += 1;
210
+ while (i < command.length && command.charAt(i) !== "`") i += command.charAt(i) === "\\" ? 2 : 1;
211
+ if (i >= command.length) return { end: command.length, complete: false };
212
+ i += 1;
213
+ continue;
214
+ }
215
+ if ((c === "$" || c === "<" || c === ">") && command.charAt(i + 1) === "(") {
216
+ const after = afterParen(command, i + 1);
217
+ if (after === undefined) return { end: command.length, complete: false };
218
+ i = after;
219
+ continue;
220
+ }
221
+ if (c === "$" && command.charAt(i + 1) === "{") {
222
+ const after = afterBrace(command, i + 1);
223
+ if (after === undefined) return { end: command.length, complete: false };
224
+ i = after;
225
+ continue;
226
+ }
227
+ i += 1;
228
+ }
229
+ return { end: i, complete: true };
230
+ }
231
+
232
+ /**
233
+ * A command the log hides, with the values of its leading assignments masked
234
+ * as far as they can be read. An assignment whose value holds a construct the
235
+ * reader does not understand stays as written, so a person still sees what
236
+ * runs; an assignment whose quote is left open is masked to the command's end.
237
+ */
238
+ function questionCommand(command: string): string {
239
+ let out = "";
240
+ let at = 0;
241
+ let i = 0;
242
+ while (i < command.length) {
243
+ while (i < command.length && /\s/.test(command.charAt(i))) i += 1;
244
+ if (i >= command.length) break;
245
+ const word = wordEnd(command, i);
246
+ const text = command.slice(i, word.end);
247
+ const name = /^[A-Za-z_][A-Za-z0-9_]*=/.exec(text);
248
+ if (name === null) break;
249
+ const valueAt = i + name[0].length;
250
+ if (!word.complete) {
251
+ out += `${command.slice(at, valueAt)}${MASK}`;
252
+ at = command.length;
253
+ break;
254
+ }
255
+ if (NOT_UNDERSTOOD.some((mark) => text.includes(mark))) {
256
+ i = word.end;
257
+ continue;
258
+ }
259
+ out += `${command.slice(at, valueAt)}${MASK}`;
260
+ at = word.end;
261
+ i = word.end;
262
+ }
263
+ return out + command.slice(at);
264
+ }
265
+
101
266
  /** The values in a secret store, so a log can mask them. A store that cannot be read has none. */
102
267
  export async function secretValuesOf(store: {
103
268
  names(): Promise<readonly string[]>;
@@ -137,6 +302,11 @@ function linesOf(text: string, limit: number): string {
137
302
  return flat.length <= limit ? flat : `${flat.slice(0, limit - 1)}…`;
138
303
  }
139
304
 
305
+ /** The command exactly as written, cut at the limit with the cut marked. */
306
+ function verbatim(text: string, limit: number): string {
307
+ return text.length <= limit ? text : `${text.slice(0, limit - 1)}…`;
308
+ }
309
+
140
310
  /**
141
311
  * The summary of one tool call, or undefined when the tool has no main
142
312
  * argument. `bash` shows its command (500 characters, one line), the file tools
@@ -162,7 +332,11 @@ export function summarizeCall(
162
332
  if (tool === "bash") {
163
333
  const command = input["command"];
164
334
  if (typeof command === "string") {
165
- text = withoutAssignmentValues(command);
335
+ const readable = withoutAssignmentValues(command);
336
+ // A question never says the command could not be read: the person must
337
+ // see what they are asked to approve, though a literal leading assignment
338
+ // value stays masked.
339
+ text = options.forQuestion === true && readable === COMMAND_NOT_SHOWN ? questionCommand(command) : readable;
166
340
  limit = COMMAND_SUMMARY_CHARS;
167
341
  }
168
342
  } else {
@@ -176,6 +350,7 @@ export function summarizeCall(
176
350
  }
177
351
  if (text === undefined || text.trim().length === 0) return undefined;
178
352
  const masked = withoutSecretValues(text, options);
353
+ if (options.forQuestion === true && tool === "bash") return verbatim(masked, limit);
179
354
  return options.keepLines === true && tool === "bash" ? linesOf(masked, limit) : oneLine(masked, limit);
180
355
  }
181
356