viewable-one 0.12.7 → 0.12.8

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.
@@ -0,0 +1,282 @@
1
+ // A REFUSAL STOPS THE RUN; IT NEVER SENDS IT TO ANOTHER LOGIN (#6995).
2
+ //
3
+ // A computer run asked for a Supabase user count. Its read-only key was
4
+ // refused, so it ran the count through the Supabase CLI's own login, which
5
+ // has full rights to the database. A narrow key is the person's choice of how
6
+ // much the run may do; a stronger login that happens to sit on the same
7
+ // computer is not a second door to the same data.
8
+ //
9
+ // This file is the one list of those other logins, and every door that can
10
+ // hold a run back reads it:
11
+ // - the words every run is told (conversationRules.mjs `refusalRule`, in the
12
+ // idea preamble and the chat turn's prefix, for every engine);
13
+ // - Claude Code's deny rules (`CLAUDE_OTHER_LOGIN_TOOLS`, in agents.mjs's
14
+ // --disallowedTools and the ACP adapter's `disallowedTools`), checked
15
+ // before any permission prompt, so neither the allowlist's `Bash(npx:*)`
16
+ // nor "Allow for this run" can let one through;
17
+ // - the shared permission asker (permissionAsk.mjs), which refuses
18
+ // `usesAnotherLogin` commands before any question, remembered rule or
19
+ // "Allow for this run": Claude's prompts, ACP's and Codex's sandbox
20
+ // escalations all land there;
21
+ // - opencode's own config (`OPENCODE_OTHER_LOGIN_RULES`, agents.mjs
22
+ // prepareWorkspace), since `--auto` approves everything it does not deny.
23
+ //
24
+ // WHAT IT DOES NOT STOP, said plainly so nobody repeats it as a fence: a
25
+ // command the allowlist already lets through without asking can still reach
26
+ // one through a script (`node -e`, `npm run <script>`, a `cat` of a token file
27
+ // spelled some new way). The words cover those. The child's environment is
28
+ // already an allowlist (child.mjs `childEnv`), so a token exported in the
29
+ // person's shell (SUPABASE_ACCESS_TOKEN, GH_TOKEN) is not handed to the run.
30
+ //
31
+ // WHAT COUNTS. A command-line tool that signs in with a stored login of its
32
+ // own and reaches the data a connected app's key was meant to bound (the
33
+ // Supabase CLI), and the stores that hand out a saved secret (the macOS
34
+ // keychain, the Linux keyring, password managers, git's credential helpers,
35
+ // `gh auth token`). A tool is judged where it RUNS, at a command's start, so
36
+ // a commit message or a folder named `supabase` is not refused.
37
+
38
+ /** Command-line tools that use a stored login of their own. */
39
+ const LOGIN_TOOLS = ["supabase"];
40
+
41
+ /** Password managers: every call hands out or unlocks saved secrets. */
42
+ const PASSWORD_MANAGERS = new Set(["op", "bw", "lpass"]);
43
+
44
+ /** The macOS keychain subcommands that print a saved secret. */
45
+ const KEYCHAIN_READS = new Set(["find-generic-password", "find-internet-password", "find-key", "dump-keychain", "export"]);
46
+
47
+ /** Token files a login tool keeps on disk, matched anywhere in a command:
48
+ * `cat`, `head`, `node -e` or a redirection that names one is refused. Each
49
+ * is written with `/`; a `\\` (Windows) is matched too. */
50
+ const TOKEN_FILE_PATHS = [".supabase/access-token"];
51
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
52
+ const TOKEN_FILES = new RegExp(TOKEN_FILE_PATHS.map((path) => path.split("/").map(escapeRegExp).join("[\\\\/]")).join("|"), "i");
53
+
54
+ /** Words that run the command after them. Each may take flags first; the
55
+ * flags listed take a value, which is skipped too. */
56
+ const WRAPPERS = new Map([
57
+ ["env", new Set(["-u", "-C", "--unset", "--chdir"])],
58
+ ["sudo", new Set(["-u", "-g", "-h", "-p", "-C", "-U", "-r", "-t", "-D"])],
59
+ ["doas", new Set(["-u", "-C"])],
60
+ ["command", new Set()], ["exec", new Set(["-a"])], ["builtin", new Set()], ["noglob", new Set()],
61
+ ["nohup", new Set()], ["time", new Set(["-f", "-o"])], ["nice", new Set(["-n"])],
62
+ ["xargs", new Set(["-I", "-n", "-P", "-L", "-d", "-E", "-s", "-a"])],
63
+ ["arch", new Set()], ["caffeinate", new Set(["-t", "-w"])], ["stdbuf", new Set()],
64
+ ["timeout", new Set(["-s", "-k", "--signal", "--kill-after"])],
65
+ // Shell keywords that start a command after them.
66
+ ["if", new Set()], ["then", new Set()], ["else", new Set()], ["elif", new Set()], ["do", new Set()],
67
+ ["while", new Set()], ["until", new Set()], ["!", new Set()],
68
+ ]);
69
+ /** Wrappers whose first plain word is a value, not the command. */
70
+ const FIRST_WORD_IS_VALUE = new Set(["timeout"]);
71
+
72
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
73
+
74
+ /** Package runners: `npx supabase`, `npm exec supabase`, `pnpm dlx supabase`. */
75
+ const PACKAGE_RUNNERS = new Map([
76
+ ["npx", null], ["bunx", null], ["pnpx", null],
77
+ ["npm", new Set(["exec", "x"])], ["pnpm", new Set(["dlx", "exec"])], ["yarn", new Set(["dlx", "exec"])], ["bun", new Set(["x"])],
78
+ ]);
79
+
80
+ /** A program's name as the shell finds it: no folder, no Windows suffix, any
81
+ * case (a Mac's disk does not tell `Supabase` from `supabase`). */
82
+ const programOf = (word) => String(word ?? "").split(/[\\/]/).pop().toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/, "");
83
+
84
+ /** A package word without its version: `supabase@latest` is `supabase`. */
85
+ const packageOf = (word) => {
86
+ const name = String(word ?? "").replace(/^--package=/, "");
87
+ const at = name.indexOf("@", 1);
88
+ return (at > 0 ? name.slice(0, at) : name).toLowerCase();
89
+ };
90
+
91
+ /** A shell line as commands, each a list of words with quotes removed, and
92
+ * the command substitutions inside double quotes (`"$(...)"`, `` "`...`" ``),
93
+ * which still run. Separators (`;`, `&`, `|`, newline, parentheses, braces,
94
+ * backticks, `$(`) end a command only outside quotes; a quoted word stays one
95
+ * word, and single quotes hide a `$(` (it is literal text there). A
96
+ * redirection is not a word: `2>/dev/null supabase` runs `supabase`, so the
97
+ * fd number, the operator and its target are dropped. */
98
+ function commandsOf(line) {
99
+ const commands = [];
100
+ const substitutions = [];
101
+ let words = [];
102
+ let word = "";
103
+ let inWord = false;
104
+ let quote = null;
105
+ let target = false; // the next word is a redirection's target
106
+ const endWord = () => {
107
+ if (inWord && !target) words.push(word);
108
+ if (inWord) target = false;
109
+ word = "";
110
+ inWord = false;
111
+ };
112
+ const endCommand = () => { endWord(); target = false; if (words.length > 0) commands.push(words); words = []; };
113
+ for (let i = 0; i < line.length; i += 1) {
114
+ const c = line[i];
115
+ if (quote === "'") { if (c === "'") quote = null; else word += c; continue; }
116
+ if (quote === "\"") {
117
+ if (c === "\"") quote = null;
118
+ else if (c === "\\" && i + 1 < line.length) word += line[++i];
119
+ else {
120
+ if (c === "`" || (c === "$" && line[i + 1] === "(")) substitutions.push(line.slice(i + (c === "`" ? 1 : 2)));
121
+ word += c;
122
+ }
123
+ continue;
124
+ }
125
+ if (c === "\\") { if (i + 1 < line.length) { word += line[++i]; inWord = true; } continue; }
126
+ if (c === "'" || c === "\"") { quote = c; inWord = true; continue; }
127
+ if (c === "\n" || c === "\r") { endCommand(); continue; }
128
+ if (/\s/.test(c)) { endWord(); continue; }
129
+ if (c === "$" && line[i + 1] === "(") { endCommand(); i += 1; continue; }
130
+ if ((c === "<" || c === ">") && line[i + 1] !== "(") {
131
+ // `2>`, `&>`, `>>`, `<<<`, `>&1`, `>|`: a digit-only word before it is
132
+ // its fd, never a word of the command.
133
+ if (/^\d*$/.test(word) && !target) { word = ""; inWord = false; } else endWord();
134
+ while (i + 1 < line.length && "<>&|".includes(line[i + 1])) i += 1;
135
+ target = true;
136
+ continue;
137
+ }
138
+ if (";&|(){}`<>".includes(c)) { endCommand(); continue; }
139
+ word += c;
140
+ inWord = true;
141
+ }
142
+ endCommand();
143
+ return { commands, substitutions };
144
+ }
145
+
146
+ /** Whether one call of a program, with its words, reaches another login. */
147
+ function callUsesLogin(program, rest) {
148
+ if (LOGIN_TOOLS.includes(program) || PASSWORD_MANAGERS.has(program)) return true;
149
+ if (program.startsWith("git-credential")) return true;
150
+ if (program === "security") return KEYCHAIN_READS.has(rest[0]);
151
+ if (program === "secret-tool") return rest[0] === "lookup" || rest[0] === "search";
152
+ if (program === "git") {
153
+ // git's own options come before the subcommand; -c and -C take a value.
154
+ let i = 0;
155
+ while (i < rest.length && rest[i].startsWith("-")) i += rest[i] === "-c" || rest[i] === "-C" ? 2 : 1;
156
+ const sub = rest[i] ?? "";
157
+ return sub === "credential" || sub.startsWith("credential-");
158
+ }
159
+ if (program === "gh") {
160
+ const plain = rest.filter((w) => !w.startsWith("-"));
161
+ if (plain[0] !== "auth") return false;
162
+ return plain[1] === "token" || (plain[1] === "status" && rest.some((w) => w === "-t" || w === "--show-token"));
163
+ }
164
+ return false;
165
+ }
166
+
167
+ /** Whether a package runner's words start a login tool. */
168
+ function packageRunUsesLogin(words, depth) {
169
+ for (let i = 0; i < words.length; i += 1) {
170
+ const w = words[i];
171
+ if (w === "--") continue;
172
+ if (w === "-p" || w === "--package") { if (LOGIN_TOOLS.includes(packageOf(words[i + 1]))) return true; i += 1; continue; }
173
+ if (w.startsWith("--package=")) { if (LOGIN_TOOLS.includes(packageOf(w))) return true; continue; }
174
+ if (w === "-c" || w === "--call") return usesAnotherLogin(words[i + 1] ?? "", depth + 1);
175
+ if (w.startsWith("-")) continue;
176
+ return LOGIN_TOOLS.includes(packageOf(w)) || LOGIN_TOOLS.includes(programOf(w));
177
+ }
178
+ return false;
179
+ }
180
+
181
+ /** Whether one command (its words) reaches another login. */
182
+ function commandUsesLogin(words, depth) {
183
+ let i = 0;
184
+ for (;;) {
185
+ const w = words[i];
186
+ if (w === undefined) return false;
187
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) { i += 1; continue; }
188
+ const wrapper = WRAPPERS.get(programOf(w));
189
+ if (!wrapper) break;
190
+ i += 1;
191
+ while (words[i]?.startsWith("-") && words[i] !== "-") i += wrapper.has(words[i]) ? 2 : 1;
192
+ if (FIRST_WORD_IS_VALUE.has(programOf(w)) && words[i] !== undefined) i += 1;
193
+ }
194
+ const program = programOf(words[i]);
195
+ const rest = words.slice(i + 1);
196
+ if (SHELLS.has(program)) {
197
+ const flag = rest.findIndex((w) => /^-[A-Za-z]*c[A-Za-z]*$/.test(w));
198
+ return flag >= 0 && usesAnotherLogin(rest[flag + 1] ?? "", depth + 1);
199
+ }
200
+ if (program === "eval") return usesAnotherLogin(rest.join(" "), depth + 1);
201
+ if (PACKAGE_RUNNERS.has(program)) {
202
+ const subs = PACKAGE_RUNNERS.get(program);
203
+ if (subs === null) return packageRunUsesLogin(rest, depth);
204
+ return subs.has(rest[0]) && packageRunUsesLogin(rest.slice(1), depth);
205
+ }
206
+ return callUsesLogin(program, rest);
207
+ }
208
+
209
+ /** Whether a shell command reaches another login or a saved secret, at any
210
+ * command in the line, inside `sh -c`, `eval`, a package runner or a `$( )`.
211
+ * Anything it cannot read for sure (too deeply nested) counts as a yes. */
212
+ export function usesAnotherLogin(command, depth = 0) {
213
+ const line = String(command ?? "");
214
+ if (depth > 4) return true;
215
+ if (TOKEN_FILES.test(line)) return true;
216
+ const { commands, substitutions } = commandsOf(line);
217
+ if (commands.some((words) => commandUsesLogin(words, depth))) return true;
218
+ // A substitution inside double quotes still runs: "$(supabase ...)".
219
+ return substitutions.some((rest) => usesAnotherLogin(rest, depth + 1));
220
+ }
221
+
222
+ /** What the agent reads when the asker refuses one, naming the board's ask
223
+ * in that engine's own words (`ask_user` for Claude Code and ACP,
224
+ * `mcp__glytch__ask_user` for Codex), the way refusalRule does. It shuts the
225
+ * other doors and sends the run to ask with the reason. */
226
+ export const otherLoginDenied = (ask = "ask_user") =>
227
+ "Refused: this uses another login, token or saved key on this computer. A run never gets round a refusal that way. " +
228
+ `Stop this part of the task and ask the person on the board with ${ask}: say what was refused and why ` +
229
+ "(the error you got), and what they could change. Do not try another login, CLI, token or key.";
230
+
231
+ /** Claude Code deny rules for the same tools. A deny rule is checked before
232
+ * any allow rule or prompt, so it holds where `Bash(npx:*)`, `Bash(npm:*)`
233
+ * and `Bash(git:*)` on the allowlist would otherwise let the call run with no
234
+ * question, and so never reach usesAnotherLogin. The `:*` rules are prefix
235
+ * rules every Claude Code reads. The `*` rules are wildcards (Claude Code
236
+ * 2.1.316 reads them, "Use * for wildcards"; an older one matches nothing
237
+ * with them): they catch the package named by a flag (`npx --package
238
+ * supabase supabase`, `npx -y -p supabase@2 supabase`), a version, a script
239
+ * (`npx -c 'supabase ...'`) and flags before the name. They need the name as
240
+ * its own word, so `npx vitest run supabase/functions/x.test.mjs` and
241
+ * `npx eslint supabase` still run. `npm exec` and `npm x` are barred whenever
242
+ * they name the tool at all: a run uses npx for its own tools. */
243
+ /** git's credential subcommand and the helpers that print a saved login. */
244
+ const GIT_CREDENTIAL_WORDS = ["credential fill", "credential approve", "credential reject", "credential capability",
245
+ ...["osxkeychain", "manager", "manager-core", "store", "cache", "libsecret", "wincred"].map((helper) => `credential-${helper}`)];
246
+
247
+ export const CLAUDE_OTHER_LOGIN_TOOLS = [
248
+ ...LOGIN_TOOLS.flatMap((tool) => [
249
+ `Bash(${tool}:*)`,
250
+ `Bash(npx ${tool}:*)`, `Bash(npx -y ${tool}:*)`, `Bash(npx --yes ${tool}:*)`, `Bash(npx ${tool}@latest:*)`,
251
+ `Bash(npm exec ${tool}:*)`, `Bash(npm exec -- ${tool}:*)`, `Bash(npm x ${tool}:*)`,
252
+ `Bash(npx ${tool}*)`, `Bash(npx -* ${tool})`, `Bash(npx -* ${tool} *)`, `Bash(npx -* ${tool}@*)`,
253
+ `Bash(npx *-p ${tool}*)`, `Bash(npx *--package ${tool}*)`, `Bash(npx *--package=${tool}*)`,
254
+ `Bash(npx *-c *${tool}*)`, `Bash(npx *--call *${tool}*)`,
255
+ `Bash(npm exec *${tool}*)`, `Bash(npm x *${tool}*)`,
256
+ ]),
257
+ // git's own options first (`git -c core.pager=cat credential fill`, `git -C
258
+ // <dir> credential fill`) still match Bash(git:*), so the subcommands and
259
+ // helpers are named after any options. A commit message would have to say
260
+ // "credential fill" to be caught.
261
+ "Bash(git credential:*)",
262
+ ...GIT_CREDENTIAL_WORDS.flatMap((word) => [`Bash(git ${word}:*)`, `Bash(git * ${word}*)`]),
263
+ // A shell read of a token file (`cat`, `head`, `node -e`) is on the
264
+ // allowlist too: deny any command that names one.
265
+ ...TOKEN_FILE_PATHS.flatMap((path) => [`Bash(*${path}*)`, `Bash(*${path.replaceAll("/", "\\")}*)`]),
266
+ "Read(~/.supabase/**)",
267
+ ];
268
+
269
+ /** opencode's own deny rules (its `permission.bash` patterns), for the same
270
+ * tools: `--auto` approves everything that is not denied. */
271
+ export const OPENCODE_OTHER_LOGIN_RULES = Object.fromEntries([
272
+ ...LOGIN_TOOLS.flatMap((tool) => [tool, `${tool} *`, `npx ${tool}*`, `npx -y ${tool}*`, `npm exec ${tool}*`]),
273
+ ...[...PASSWORD_MANAGERS].flatMap((tool) => [tool, `${tool} *`]),
274
+ ...LOGIN_TOOLS.flatMap((tool) => [`npx -* ${tool}`, `npx -* ${tool} *`, `npx -* ${tool}@*`, `npx *-p ${tool}*`, `npx *--package ${tool}*`,
275
+ `npx *--package=${tool}*`, `npx *-c *${tool}*`, `npm exec *${tool}*`, `npm x *${tool}*`]),
276
+ "security find-*", "security dump-keychain*", "security export*",
277
+ "secret-tool lookup*", "secret-tool search*",
278
+ "gh auth token*", "gh auth status *--show-token*", "gh auth status *-t*",
279
+ "git credential*", "git-credential*",
280
+ ...GIT_CREDENTIAL_WORDS.map((word) => `git * ${word}*`),
281
+ ...TOKEN_FILE_PATHS.flatMap((path) => [`*${path}*`, `*${path.replaceAll("/", "\\")}*`]),
282
+ ].map((pattern) => [pattern, "deny"]));
@@ -1,5 +1,6 @@
1
- import { writeRisk, riskReason } from "./writePolicy.mjs";
1
+ import { writeRisk, riskReason, automationReads } from "./writePolicy.mjs";
2
2
  import { appInputsText } from "./codexToolInputs.mjs";
3
+ import { otherLoginDenied, usesAnotherLogin } from "./otherLogins.mjs";
3
4
  // ASK IN THE IDEA (issue #478, rulings #470 #468 #417 #418).
4
5
  //
5
6
  // A coding agent on the person's computer works from a list of things it may
@@ -662,6 +663,20 @@ export const CLICK_AND_SCREEN_DENIED = "I can't press buttons inside other apps.
662
663
  const CLICK_AND_SCREEN_WORD = new RegExp(`(?:^|[\\s;&|()\`'"=])(?:[^\\s;&|()\`'"]*/)?(?:${CLICK_AND_SCREEN_COMMANDS.join("|")})(?=$|[\\s;&|()\`'"])`);
663
664
  export const drivesAnotherApp = (command) => CLICK_AND_SCREEN_WORD.test(String(command ?? ""));
664
665
 
666
+ /** The run card's line for an app read an automation's run made with no
667
+ * question (#6955): it says the automation was the yes and, as the server's
668
+ * receipt does for the same read (integrations `read: true`, #6628), never
669
+ * calls it a change. The tool reads as the question names it. The app is the
670
+ * engine's server key ("argos", "google_calendar"), so it reads as a name,
671
+ * each word capitalised ("Argos", "Google Calendar"); a key that already has
672
+ * a capital ("GitHub") stays as it is. */
673
+ const appWords = (app) => {
674
+ const key = String(app);
675
+ return /[A-Z]/.test(key) ? key : key.split(/[-_\s]+/).filter(Boolean).map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
676
+ };
677
+ export const automationReadWords = (app, tool) =>
678
+ `Read ${String(tool).replaceAll("_", " ")} in ${appWords(app)} without asking: setting the automation was your yes. Nothing was changed.`;
679
+
665
680
  /** Build the asker for one run.
666
681
  *
667
682
  * `ask({ toolName, input, signal })` resolves to `{behavior: "allow"}` or
@@ -680,9 +695,12 @@ export const drivesAnotherApp = (command) => CLICK_AND_SCREEN_WORD.test(String(c
680
695
  * fromId the idea the run belongs to
681
696
  * poll the run's answer poll, so the permission question's answer is
682
697
  * not also typed into the conversation (`claim`)
698
+ * askTool the engine's own name for the board's ask_user, for the words
699
+ * a refused other login hands back (#6995)
683
700
  */
684
701
  export function createPermissionAsker({
685
- folder, cwd, session, boardId, fromId, env, callTool = hostedCallTool, poll, log = () => {}, pollMs = 2000,
702
+ folder, cwd, session, boardId, fromId, env, callTool = hostedCallTool, poll, log = () => {}, pollMs = 2000, automation = false,
703
+ askTool = "ask_user",
686
704
  }) {
687
705
  const folderName = basename(folder) || folder;
688
706
  const scopedCallTool = (name, args, options) => callTool(name, args, { ...options, sessionBoardId: boardId });
@@ -693,12 +711,28 @@ export function createPermissionAsker({
693
711
  // second command's ask that was waiting beside the one answered.
694
712
  const runAllowed = new AbortController();
695
713
  const coveredByRun = (toolName, question) => !question && toolName === "Bash" && runAllowed.signal.aborted;
714
+ /** Whether a call of `tool` is a read made inside an automation's run, so it
715
+ * needs no question (ruling #5495): the same rule the server runs
716
+ * (writePolicy.automationReads), and only when `hints`, the app's own labels
717
+ * for the tool as the engine reports them (Codex's inventory), say
718
+ * read-only (#6955). With no labels the computer cannot tell a read from a
719
+ * write, so Claude's and ACP's requests, which carry none, always ask. The
720
+ * server's own rule keeps its label-less reads: it holds the tool's labels
721
+ * and the person's Allow list, which the computer has neither of. */
722
+ const readInAutomation = (tool, input, hints) => automation && hints?.readOnlyHint === true
723
+ && automationReads(tool, input && typeof input === "object" ? input : {}, hints);
696
724
  const ask = async ({ toolName, input: asked = {}, signal, question }) => {
697
725
  if (signal?.aborted) return null;
698
726
  if (!question && toolName === "Bash" && drivesAnotherApp(asked.command)) {
699
727
  log("permission: a command that drives another app is refused (#4204)");
700
728
  return { behavior: "deny", message: CLICK_AND_SCREEN_DENIED };
701
729
  }
730
+ // Another login, token or saved key (#6995): refused before any question,
731
+ // remembered rule or "Allow for this run", so a refusal is never got round.
732
+ if (!question && toolName === "Bash" && usesAnotherLogin(asked.command)) {
733
+ log("permission: a command that uses another login is refused (#6995)");
734
+ return { behavior: "deny", message: otherLoginDenied(askTool) };
735
+ }
702
736
  // A Claude command carries no working folder: it runs in the shell the run
703
737
  // started in (a worktree, not the linked folder itself) and wherever its
704
738
  // allowed `cd`s moved it, so its paths and links are judged there (#3759,
@@ -787,5 +821,8 @@ export function createPermissionAsker({
787
821
  if (delay > 0) await sleepFor(delay, waitSignal);
788
822
  }
789
823
  };
824
+ // Codex hands over the app, the tool and the tool's labels apart, so the
825
+ // boundary between app and tool is never guessed. The only door that skips.
826
+ ask.appRead = (app, name, input, hints) => readInAutomation(name, input, hints);
790
827
  return ask;
791
828
  }
@@ -15,8 +15,7 @@ import * as runnerApiModule from "./runnerApi.mjs";
15
15
  import { callTool as hostedCallToolDefault } from "./hosted.mjs";
16
16
  import { runnerMcpUrlFrom } from "./mcpjson.mjs";
17
17
  import { hostedConfig, hostedToken } from "./auth.mjs";
18
- import { computerAppsOffRule, otherAppsRule } from "./conversationRules.mjs";
19
- import { acceptsMessages, agentFor, commandFor, isPersistentRequest, preambleFor } from "./agents.mjs";
18
+ import { acceptsMessages, agentFor, chatRulesFor, commandFor, isPersistentRequest, preambleFor } from "./agents.mjs";
20
19
  import { getRepoMap, formatRepoPrimer } from "./repomap.mjs";
21
20
  import { buildAttemptsSectionFromRows } from "./compose.mjs";
22
21
  import { imageInspectionInstruction } from "./imageAttachments.mjs";
@@ -84,7 +83,9 @@ export async function executeRequest(project, run, settings, log, timing, receip
84
83
  // and its `runnerApi` calls, not a signal file).
85
84
  const isChat = isChatTurn(request);
86
85
 
87
- const ctx = { eventSeq: run.event_seq, project, root, id, request, isChat, runnerApi, hostedEnv, rowsOpts, session, claimedAt, boardId, settings, log };
86
+ // A run an automation filed carries its `schedule_id` (the claimed row is the whole `runs` row).
87
+ const fromAutomation = typeof run.schedule_id === "string" && run.schedule_id !== "";
88
+ const ctx = { eventSeq: run.event_seq, project, root, id, request, isChat, fromAutomation, runnerApi, hostedEnv, rowsOpts, session, claimedAt, boardId, settings, log };
88
89
  const admitted = await admitRequest(ctx, preparation);
89
90
  if ("patch" in admitted) return finish(admitted.patch);
90
91
  const prepared = await prepareRun(ctx, admitted, receipt, preparation);
@@ -171,13 +172,15 @@ function makePlanRun({ project, root, id, request, isChat, runnerApi, hostedEnv,
171
172
  const repoPrimer = formatRepoPrimer(repoMap, attemptsSection ? attemptsSection.length : 0);
172
173
  // chat turn, difference 1: NO IDEA PREAMBLE. The app composes the persona,
173
174
  // room context and message; instructions such as "call report before you
174
- // finish" do not belong in chat. Only the other-apps rule and, when
175
- // needed, the apps-off rule are added for Claude Code and Codex, so the reply can offer Manage agent.
175
+ // finish" do not belong in chat. Only the rules every run keeps are added
176
+ // (agents.mjs chatRulesFor): a refusal stops and asks, for every engine
177
+ // (#6995), and for Claude Code and Codex the other-apps rule and, when
178
+ // needed, the apps-off rule, so the reply can offer Manage agent.
176
179
  let text = request.planMode === "draft"
177
180
  ? `Investigate the request using read-only research, then return an actionable implementation plan in your final response. Structure the response as a report: keep resolved or contextual findings in their own sections; put actionable work under a \`## Implementation plan\` heading with one \`### Step N: ...\` or \`### Issue X: ...\` heading per top-level item; put numbered substeps under a \`**Steps:**\` label; and label checks and open decisions clearly. Do not implement anything, use tools to modify files, or ask for permission to implement. The human will edit and approve or reject your final plan on the board.\n\n${String(request.prompt)}`
178
181
  : `${isChat ? "" : preambleFor(agent, { ...(made.isolated ? {} : { workplace: IN_PLACE_WORKPLACE }), computerApps: request.computerApps === true })}${String(request.prompt)}`;
179
- if (isChat && request.planMode !== "draft" && ["claude", "codex"].includes(agent)) {
180
- text = `${otherAppsRule()}${request.computerApps === true ? "" : computerAppsOffRule()}${text}`;
182
+ if (isChat && request.planMode !== "draft") {
183
+ text = `${chatRulesFor(agent, { computerApps: request.computerApps === true })}${text}`;
181
184
  }
182
185
  if (request.planMode === "execute") text += `\n\nHUMAN-APPROVED IMPLEMENTATION PLAN\nFollow this exact plan, including the human's edits. Ask the human about any material scope change before implementing it.\n\n${request.approvedPlan}`;
183
186
  if (note) text = `${text}\n\n${note}`;
@@ -38,7 +38,7 @@ export function resumeNotes(request) {
38
38
 
39
39
  /** Spawn the run's process and see it through to its receipt. */
40
40
  export async function startRun(ctx, state, { timing, receipt, preparation, finish }) {
41
- const { root, id, request, isChat, runnerApi, rowsOpts, hostedEnv, session, boardId, settings, log } = ctx;
41
+ const { root, id, request, isChat, fromAutomation, runnerApi, rowsOpts, hostedEnv, session, boardId, settings, log } = ctx;
42
42
  const { referenceImages, from, agent, made, useStreaming, boardToken, childMcpUrl, hostedCallTool, isPersistent, maxMs, resumeTreeGone, resumeSessionId, planRun } = state;
43
43
  const { TREE_GONE_NOTE, NOT_FOUND_NOTE } = resumeNotes(request);
44
44
  const plan = await planRun({ resumeId: resumeSessionId, note: resumeTreeGone ? TREE_GONE_NOTE : null });
@@ -96,9 +96,9 @@ export async function startRun(ctx, state, { timing, receipt, preparation, finis
96
96
  // (it stays read-only).
97
97
  const askPermission = boardToken && request.planMode !== "draft" && (useStreaming || agentFor(agent) === "codex" || chosen.spec?.protocol === "acp")
98
98
  ? createPermissionAsker({
99
- folder: root, cwd: made.cwd, agentLabel: AGENTS[agentFor(agent)]?.label ?? "The agent", session, boardId, fromId: from, env: hostedEnv,
99
+ folder: root, cwd: made.cwd, agentLabel: AGENTS[agentFor(agent)]?.label ?? "The agent", session, boardId, fromId: from, env: hostedEnv, automation: fromAutomation === true,
100
100
  callTool: hostedCallTool, poll: rowsPoll, log: (message) => log(`[${id}] ${message}`),
101
- pollMs: settings.permissionPollMs ?? 2000,
101
+ pollMs: settings.permissionPollMs ?? 2000, askTool: AGENTS[agentFor(agent)]?.boardTool("ask_user"),
102
102
  })
103
103
  : undefined;
104
104