viewable-one 0.12.6 → 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.
@@ -68,9 +68,330 @@ export function readsOnly(name, args = {}, hints) {
68
68
  return false;
69
69
  return !callVerbs(name, args).some((verb) => verb !== "read");
70
70
  }
71
- export function writeRisk(provider, name, args = {}, hints) {
71
+ // AN AUTOMATION'S READS (ruling #5495): setting an automation is the
72
+ // person's yes for the reads it needs, label or not (a person's own server
73
+ // rarely labels its tools). A write still asks: anything below that may
74
+ // change something is never an automation read, allowed once or not.
75
+ // The words that run a statement the call carries ("sql_exec_tool",
76
+ // "run_query"): the call does what its statement does. Only a tool whose
77
+ // name also says what it runs is one (a "run_agent" runs no SQL), and only
78
+ // an argument named for its statement carries it (#6628 judge review).
79
+ const STATEMENTS = new Set(["run", "exec", "execute"]);
80
+ const SQL_OBJECTS = new Set(["sql", "query", "queries", "statement", "statements"]);
81
+ const SQL_KEY = /(?:^|_)(?:sql|query|statement|stmt)$/;
82
+ // An argument named only for SQL holds SQL whatever word it starts with, so
83
+ // on any tool it runs unattended only when it is a SQL read; a statement it
84
+ // cannot read asks (allowlist, #6628 lead recheck). On a tool whose own name
85
+ // says it runs SQL ("query", "read_query"), a "query" argument is SQL the same
86
+ // way, even if that tool sometimes takes plain words: safety over an extra ask.
87
+ // Elsewhere a "query" can be search words: one that starts like no statement
88
+ // still asks when it holds a write word or a side-effect function anywhere
89
+ // (SQL Server runs "if 1=1 drop table sales" with no semicolon).
90
+ const SQL_ONLY_KEY = /(?:^|_)(?:sqls?|statements?|stmts?)$/;
91
+ // SQL is read the same way by every database only when it holds no comment,
92
+ // no dollar quote, no backticked name and no backslash: databases nest block
93
+ // comments or not, take "//" or "#" as a comment or not, allow "$" inside a
94
+ // name or not, escape a quote with a backslash or not. Masking cannot match
95
+ // them all, so a text holding any of these is never an unattended read: it
96
+ // asks (#6628 lead review). So does a bracket: SQL Server reads [a'b] as a
97
+ // name, ODBC reads {call p()} as a call (#6628 lead decision); so does a
98
+ // triple quote (BigQuery's ''' strings) and "&" (Postgres U&"..." names spell
99
+ // a function in escapes, judge recheck at be6f8fd2b). What is left
100
+ // is masked once, from the left.
101
+ const SQL_UNSURE = /\/\*|--|#|\/\/|`|\$|\\|\[|\{|'''|"""|&/;
102
+ const QUOTED = /'(?:[^']|'')*'?|"(?:[^"]|"")*"?/g;
103
+ function bareSql(text) {
104
+ return text.replace(QUOTED, (part) => (part.startsWith("'") ? " '' "
105
+ // A quoted name is still that name to the database ("setval"(...) is setval):
106
+ // kept, with anything that is not a name character made inert.
107
+ : ` ${part.slice(1, part.endsWith('"') && part.length > 1 ? -1 : undefined).replace(/""/g, '"').replace(/[^\w$]/g, "_")} `));
108
+ }
109
+ // The words a statement starts with. A text that starts with none is not SQL.
110
+ // Words that also start plain sentences ("start", "import") count only with
111
+ // the word that makes them a statement.
112
+ const STATEMENT_WORDS = "select|with|show|describe|desc|explain|insert|update|delete|merge|upsert|replace|drop|undrop|create|alter|truncate|rename|grant|revoke|copy|put|remove|call|exec|execute|comment|set|unset|use|begin|commit|rollback|vacuum|refresh|lock|do"
113
+ + "|reindex|cluster|analyze|analyse|checkpoint|reset|notify|listen|unlisten|prepare|deallocate|savepoint|abort|reassign|shutdown|flush|attach|detach|pragma|declare"
114
+ // MySQL 8 reads a lone RESTART as a server restart; "Restart the report" is a sentence.
115
+ + "|restart(?=\\s*$)"
116
+ + "|start\\s+transaction|load\\s+(?:data|extension|index|xml|(?='))|import\\s+(?:foreign|table|into|database)|(?:un)?install\\s+(?:plugin|component)|security\\s+label"
117
+ + "|values(?=\\s*\\()|table(?=\\s+[\\w.\"]+\\s*;?\\s*$)"
118
+ + "|kill\\s+(?:query|connection|\\d+)|optimize\\s+table|repair\\s+table|discard\\s+(?:all|plans|sequences|temp|temporary)|purge\\s+(?:binary|master)";
119
+ const SQL_STARTS = new RegExp(`^[\\s(]*(?:${STATEMENT_WORDS})(?!\\w)`, "i");
120
+ // Where a statement may start once some database drops a comment: after a
121
+ // semicolon, a line end or any comment mark (MySQL runs "/*!50000 ... */").
122
+ // With one of the characters above, a text with a statement start at any of
123
+ // them is SQL that may write (a comment before "refresh" leaves no start at
124
+ // the front, #6628 lead recheck); a sentence that holds "#" or "$" is not.
125
+ const SQL_BREAKS = /;|\r|\n|\/\*!?\d*|\*\/|--|#|\/\/|\\/;
126
+ // The statements that only read. SHOW names what it lists, so "Show revenue,
127
+ // then email it" is not one.
128
+ const SQL_READ = /^[\s(]*(?:select|with|explain|describe|desc|show\s+(?:terse\s+)?(?:[a-z]+\s+)?(?:tables|views|schemas|databases|columns|warehouses|objects|functions|procedures|stages|roles|grants|users|parameters|sequences|indexes|semantic\s+views))\b|^[\s(]*(?:values\s*\(|table\s)/i;
129
+ // A word that changes something, for text that does not start like SQL
130
+ // ("if 1=1 drop table sales" under a search): it asks. The read rule below
131
+ // does not use it; a function of the same name is not one.
132
+ // The statements that run a server's admin work, for the same text (a
133
+ // search, a filter): "dbcc freeproccache", "1=1 shutdown with nowait".
134
+ const SQL_ADMIN = /\b(?:dbcc|reconfigure|shutdown|waitfor|raiserror|kill\s+(?:\d|query|connection)|(?:backup|restore|dump|load|mount|unmount)\s+(?:database|log|table|tran|transaction|all|filelistonly|headeronly|verifyonly)|deny\s+(?:select|insert|update|delete|exec|execute|all|control|alter|view)|bulk\s+insert|(?:dis|en)able\s+trigger|(?:sp|xp)_\w+)\b/i;
135
+ const SQL_WRITE = /\b(?:insert|update|delete|merge|upsert|drop|undrop|create|alter|truncate|rename|grant|revoke|copy|put|remove|call|exec|execute|into|lock|vacuum|refresh)\b(?!\s*\()|\bfor\s+(?:no\s+)?(?:key\s+)?share\b/i;
136
+ // A function a SELECT can call that changes something (a sequence, a
137
+ // session, a file, a lock, another database): the call is a write however it
138
+ // is wrapped. A list cannot be complete, so the database role the person
139
+ // connects with stays the real limit; these are the common ones.
140
+ const SQL_SIDE_EFFECTS = /(?:^|[^\w$])(?:nextval|txid_current|pg_current_xact_id|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_promote|pg_(?:create|drop|copy|file|write|replication|logical|advisory|try_advisory|import|export)\w*|pg_notify|pg_sleep\w*|pg_stat_reset\w*|pg_signal_backend|pg_backup_start|pg_start_backup|pg_wal_replay_pause|pg_truncate_visibility_map|brin_summarize_new_values|gin_clean_pending_list|pg_prewarm|pg_backup_stop|pg_stop_backup|pg_wal_replay_resume|pg_stat_statements_reset|lo_\w+|dblink\w*|query_to_xml\w*|table_to_xml\w*|system\$\w+|sp_\w+|xp_\w+|sleep|benchmark|load_file|get_lock|release_lock)\s*\(/i;
141
+ // THE READ RULE (#6628 lead decision): a closed allow list, not a list of
142
+ // writes. The same text means different things in different databases
143
+ // ("select 1 shutdown" is an alias in Postgres and a server stop in SQL
144
+ // Server, which needs no semicolon), so a SQL text is an unattended read only
145
+ // when, once masked, it is one statement that starts as a read and every bare
146
+ // word is a read keyword below or a word no supported database reserves
147
+ // (Postgres, MySQL, SQL Server and Sybase, Snowflake, BigQuery, SQLite). Their
148
+ // reserved-word lists are published and closed; the words that write are not.
149
+ // A name nobody reserves (a table, a column, "status", "name") is fine.
150
+ const SQL_READ_WORDS = new Set(("select from where join inner left right full outer cross natural lateral straight_join semi anti on using as and or not in is null like ilike rlike regexp glob similar " +
151
+ "between group by order having limit offset first next last only rows row ties union intersect except minus all distinct distinctrow case when then else end " +
152
+ "with recursive asc desc nulls true false unknown cast try_cast convert try_convert coalesce nullif over partition window range groups unbounded preceding following " +
153
+ "current filter within qualify sample tablesample pivot unpivot exists any some escape collate interval values top percent dual of to at zone extract leading " +
154
+ "trailing both separator match div mod xor isnull notnull overlaps symmetric asymmetric unnest array struct ignore respect exclude contains rollup cube grouping sets " +
155
+ "explain describe show tables views schemas databases columns terse objects functions procedures stages roles grants users parameters sequences indexes semantic warehouses " +
156
+ "current_date current_time current_timestamp current_user current_role current_catalog current_schema session_user system_user user localtime localtimestamp " +
157
+ "utc_date utc_time utc_timestamp lag lead rank dense_rank row_number ntile first_value last_value nth_value percent_rank cume_dist json_table " +
158
+ "char character varchar varcharacter nchar nvarchar national varying int integer int1 int2 int3 int4 int8 smallint tinyint mediumint middleint bigint dec decimal " +
159
+ "numeric float float4 float8 double precision real binary varbinary blob tinyblob mediumblob longblob text tinytext mediumtext longtext long unsigned signed boolean " +
160
+ "date time timestamp year_month day_hour day_minute day_second hour_minute hour_second minute_second day_microsecond hour_microsecond minute_microsecond second_microsecond " +
161
+ "account organization issue connection key keys file public plan rule option index schema table column database view function statistics identity query action").split(" "));
162
+ // Reserved words that are also read functions, allowed only as a call ("if(a, b, c)", "replace(name, 'a', 'b')").
163
+ const SQL_READ_CALLS = new Set(["if", "replace", "repeat", "truncate"]);
164
+ // Every word a supported database reserves, and every word a statement starts
165
+ // with there (SQL Server starts DISABLE, ENABLE, RECEIVE, SEND, THROW, MOVE
166
+ // and GET statements with words it does not reserve).
167
+ const SQL_RESERVED = new Set((
168
+ // SQL Server and Sybase
169
+ "add all alter and any as asc authorization backup begin between break browse bulk by cascade case check checkpoint close clustered coalesce collate column commit " +
170
+ "compute constraint contains containstable continue convert create cross current current_date current_time current_timestamp current_user cursor database dbcc " +
171
+ "deallocate declare default delete deny desc disk distinct distributed double drop dump else end errlvl escape except exec execute exists exit external fetch file " +
172
+ "fillfactor for foreign freetext freetexttable from full function goto grant group having holdlock identity identity_insert identitycol if in index inner insert " +
173
+ "intersect into is join key kill left like lineno load merge national nocheck nonclustered not null nullif of off offsets on open opendatasource openquery openrowset " +
174
+ "openxml option or order outer over percent pivot plan precision primary print proc procedure public raiserror read readtext reconfigure references replication restore " +
175
+ "restrict return revert revoke right rollback rowcount rowguidcol rule save schema securityaudit select semantickeyphrasetable semanticsimilaritydetailstable " +
176
+ "semanticsimilaritytable session_user set setuser shutdown some statistics system_user table tablesample textsize then to top tran transaction trigger truncate " +
177
+ "try_convert tsequal union unique unpivot update updatetext use user values varying view waitfor when where while with within writetext " +
178
+ "disable enable receive send throw move get mirror remirror unmirror mount unmount modify online offline quiesce reorg install remove lock prepare dump " +
179
+ // MySQL
180
+ "accessible analyze asensitive before bigint binary blob both call change char character condition cube cume_dist databases day_hour day_microsecond day_minute " +
181
+ "day_second dec decimal delayed dense_rank describe deterministic distinctrow div dual each elseif empty enclosed escaped explain first_value float float4 float8 force " +
182
+ "fulltext generated groups grouping high_priority hour_microsecond hour_minute hour_second ignore infile inout insensitive int int1 int2 int3 int4 int8 integer interval " +
183
+ "io_after_gtids io_before_gtids iterate json_table keys lag last_value lateral lead leading leave limit linear lines localtime localtimestamp long longblob longtext loop " +
184
+ "low_priority master_bind master_ssl_verify_server_cert match maxvalue mediumblob mediumint mediumtext middleint minute_microsecond minute_second mod modifies natural " +
185
+ "no_write_to_binlog nth_value ntile numeric optimize optimizer_costs optionally out outfile partition percent_rank purge range rank reads read_write real recursive regexp " +
186
+ "release rename repeat replace require resignal rlike row rows row_number schemas second_microsecond sensitive separator show signal smallint spatial specific sql " +
187
+ "sqlexception sqlstate sqlwarning sql_big_result sql_calc_found_rows sql_small_result ssl starting stored straight_join system terminated tinyblob tinyint tinytext " +
188
+ "trailing true undo unlock unsigned usage using utc_date utc_time utc_timestamp varbinary varchar varcharacter virtual window write xor year_month zerofill false " +
189
+ // Postgres
190
+ "analyse array asymmetric cast collation concurrently current_catalog current_role current_schema deferrable do freeze ilike initially isnull notnull offset only " +
191
+ "overlaps placing returning similar symmetric variadic verbose " +
192
+ // Snowflake
193
+ "account connect connection gscluster increment issue minus organization qualify sample start try_cast whenever " +
194
+ // BigQuery
195
+ "assert_rows_modified at contains define enum exclude extract following hash lookup new no nulls preceding proto respect struct treat unbounded unnest " +
196
+ // SQLite
197
+ "abort action after always attach autoincrement conflict deferred detach exclusive fail filter first glob immediate indexed instead last materialized nothing " +
198
+ "others pragma query raise reindex savepoint temp temporary ties vacuum without " +
199
+ // The statement words above (a word that starts a statement is never a plain name here)
200
+ "copy put upsert undrop refresh reset unset notify listen unlisten reassign flush cluster security import restart").split(" "));
201
+ // Every run of letters, also one glued to a number: SQL Server and MySQL
202
+ // read "1delete" as 1 then DELETE, and "0x1shutdown" as 0x1 then SHUTDOWN
203
+ // (judge recheck at be6f8fd2b). A name like "drop1" asks: the safe side.
204
+ const SQL_WORDS = /[a-z_]+/gi;
205
+ // FETCH reads only as "fetch first/next n rows only"; alone it is a cursor statement.
206
+ const SQL_FETCH_CLAUSE = /\bfetch\s+(?:first|next)\s+(?:\w+\s+)?rows?\s+(?:only|with\s+ties)\b/gi;
207
+ /** Whether masked SQL holds only read words: each reserved word is a read
208
+ * keyword, or a read function written as a call. END only closes a CASE
209
+ * ("end conversation" is a SQL Server statement), and a system procedure
210
+ * name (sp_, xp_) is never a read word. */
211
+ function readWordsOnly(masked) {
212
+ const text = masked.replace(SQL_FETCH_CLAUSE, " ");
213
+ let cases = 0;
214
+ for (const found of text.matchAll(SQL_WORDS)) {
215
+ const word = found[0].toLowerCase();
216
+ if (/^(?:sp|xp)_/.test(word))
217
+ return false;
218
+ if (word === "case")
219
+ cases += 1;
220
+ if (word === "end" && cases-- <= 0)
221
+ return false;
222
+ if (!SQL_RESERVED.has(word) || SQL_READ_WORDS.has(word))
223
+ continue;
224
+ if (SQL_READ_CALLS.has(word) && /^\s*\(/.test(text.slice((found.index ?? 0) + word.length)))
225
+ continue;
226
+ return false;
227
+ }
228
+ return true;
229
+ }
230
+ // A plain value beside a statement (a project id, a database name, "10"):
231
+ // one word of letters, digits, "_", "-" or "." that names no statement word.
232
+ const PLAIN_VALUE = /^(?!.*--)[A-Za-z0-9_.-]+$/;
233
+ /** Quoted text and quoted names masked to a placeholder: neither is a keyword. */
234
+ function maskedWords(text) {
235
+ return text.replace(QUOTED, " q ");
236
+ }
237
+ /** What a text is as SQL: "read" when it passes the read rule above, "write"
238
+ * when it is SQL that does not (it may change something), null when it is
239
+ * not SQL at all. Functions a person defined are the database role's limit:
240
+ * SQL_SIDE_EFFECTS names the common built-in ones. */
241
+ function sqlKind(text) {
242
+ if (SQL_UNSURE.test(text))
243
+ return text.split(SQL_BREAKS).some((part) => SQL_STARTS.test(part)) ? "write" : null;
244
+ const bare = bareSql(text);
245
+ const statements = bare.split(";").filter((part) => part.trim() !== "");
246
+ if (!statements.some((part) => SQL_STARTS.test(part)))
247
+ return null;
248
+ return statements.length === 1 && SQL_READ.test(statements[0]) && readWordsOnly(maskedWords(text)) && !SQL_SIDE_EFFECTS.test(bare) ? "read" : "write";
249
+ }
250
+ const RISKS = [MONEY, SENDING, DELETING, PUBLISHING, MERGING, DEPLOYING];
251
+ /** An argument name in lower snake case ("projectId" and "ProjectID" are "project_id"). */
252
+ function snakeKey(name) {
253
+ return name.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
254
+ }
255
+ /** Every text a call is given with the name of the argument that holds it,
256
+ * however deep (a statement may sit in a list or an object). Bounded, so a
257
+ * huge or looping value cannot hang the check. */
258
+ function argTexts(value, key = "", depth = 0) {
259
+ if (typeof value === "string")
260
+ return [{ key, text: value }];
261
+ if (value === null || typeof value !== "object")
262
+ return [];
263
+ // Past the walk limit the texts are not read, so the call is not a read.
264
+ if (depth > 4)
265
+ return [{ key, text: "", deep: true }];
266
+ // A nested object keeps the names above it ({query: {text}} is "query.text").
267
+ return Object.entries(value).flatMap(([name, item]) => argTexts(item, Array.isArray(value) ? key
268
+ : [key, snakeKey(name)].filter(Boolean).join("."), depth + 1));
269
+ }
270
+ // The only arguments that may sit beside a SQL read, each a plain top-level
271
+ // value that names where or how much to read, never what to run. A closed
272
+ // list, so no new spelling of a statement argument ("querytext", "SQLText",
273
+ // "q") can slip in beside the read (lead decision at e7cb0d15c). Add a key
274
+ // only when a real read needs it: project_id (Supabase execute_sql), database,
275
+ // schema and warehouse (Snowflake), limit (read_query).
276
+ const SQL_CONTEXT_KEYS = new Set(["project_id", "project", "database", "db", "schema", "warehouse", "catalog", "role", "limit", "max_rows", "timeout", "format"]);
277
+ // What a plain sentence does not have: a FROM clause, a semicolon, a star, a
278
+ // bracket, a VALUES or TABLE start, or a SELECT followed by a number, a quote
279
+ // or a sign ("select 1"). "describe our pricing" and "Select a plan" are English.
280
+ const SQL_SYNTAX = /\bfrom\b|;|\*|\(|^\s*(?:values|table)\b|\bselect\s*[\d'"@$+-]/i;
281
+ /** Whether a text is SQL that reads, for the SQL path. On a tool named for SQL
282
+ * any text that reads counts; elsewhere a text counts only under a SQL-named
283
+ * argument, or when it also has SQL syntax, so "explain the outage" or
284
+ * "Select a plan" in a search runs as before. */
285
+ function holdsSql(key, text, runsSql) {
286
+ return sqlKind(text) === "read" && (runsSql || keyNamed(SQL_ONLY_KEY, key) || SQL_SYNTAX.test(text));
287
+ }
288
+ /** Whether the call, which holds SQL, has the one shape that runs unasked:
289
+ * exactly one top-level argument holds SQL, it is a string and it reads, and
290
+ * every other argument is a top-level plain value under a context key. A
291
+ * second SQL argument, any other key, and any list or object (even of
292
+ * numbers) ask. Shape and key list only, no app is named (#4419). */
293
+ function closedSqlShape(args, runsSql) {
294
+ const holders = Object.entries(args).filter(([name, value]) => argTexts(value, snakeKey(name), 1).some(({ key, text }) => holdsSql(key, text, runsSql)));
295
+ if (holders.length !== 1 || typeof holders[0][1] !== "string")
296
+ return false;
297
+ return Object.entries(args).every(([name, value]) => name === holders[0][0]
298
+ || (SQL_CONTEXT_KEYS.has(snakeKey(name)) && (typeof value === "number" || typeof value === "boolean"
299
+ || (typeof value === "string" && PLAIN_VALUE.test(value.trim()) && readWordsOnly(value)))));
300
+ }
301
+ /** Whether any name on an argument's path matches `rule`. */
302
+ function keyNamed(rule, key) {
303
+ return key.split(".").some((part) => rule.test(part));
304
+ }
305
+ /** Whether a call from an automation only reads, so it runs with no ask
306
+ * (ruling #5495). Never when the tool says it writes or destroys, the call
307
+ * carries a risk word or an archive flag, any word names a create, edit or
308
+ * other change, or any text is SQL that may change something. Then: a tool
309
+ * that runs SQL ("sql_exec_tool") reads only when its statement argument
310
+ * holds a SQL read; one whose words name a read ("query", "list_tables")
311
+ * reads; one whose words name nothing reads only once `allowed`, the
312
+ * person's own Allow of this tool in this automation, and only while what
313
+ * it is asked carries no risk word. Generic: no app is named (#4419). */
314
+ export function automationReads(name, args = {}, hints, allowed = false) {
315
+ if (hints?.readOnlyHint === false || hints?.destructiveHint === true)
316
+ return false;
317
+ if (args.archived === true || args.in_trash === true)
318
+ return false;
319
+ // The words writeRisk reads, so a call it calls money, sending, deleting,
320
+ // publishing, merging or deploying is never a read here either.
321
+ if (RISKS.some((risk) => risk.test(`${name.replace(/([a-z])([A-Z])/g, "$1_$2")} ${actionTexts(args).join(" ")}`.toLowerCase())))
322
+ return false;
323
+ const words = [name, ...actionTexts(args)].join(" ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/);
324
+ const statement = words.some((word) => STATEMENTS.has(word));
325
+ const verbs = words.filter((word) => !STATEMENTS.has(word)).map(verbOf);
326
+ if (verbs.some((verb) => verb === "change" || verb === "plain"))
327
+ return false;
328
+ const given = argTexts(args);
329
+ if (given.some(({ deep }) => deep))
330
+ return false;
331
+ if (given.some(({ text }) => sqlKind(text) === "write"))
332
+ return false;
333
+ const runsSql = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).some((word) => SQL_OBJECTS.has(word));
334
+ // The SQL path: a tool named for SQL, or any call that holds SQL text under
335
+ // any name (found by content, not by name) or has a sql/statement/stmt
336
+ // argument. With a SQL read in it, the call runs only in the closed shape
337
+ // above. A SQL-named tool with no SQL read in it runs only with no text at all.
338
+ const hasSqlRead = given.some(({ key, text }) => holdsSql(key, text, runsSql));
339
+ if (hasSqlRead || given.some(({ key }) => keyNamed(SQL_ONLY_KEY, key))) {
340
+ if (!closedSqlShape(args, runsSql))
341
+ return false;
342
+ }
343
+ else if (runsSql && given.some(({ text }) => text.trim() !== ""))
344
+ return false;
345
+ if (given.some(({ text }) => sqlKind(text) === null
346
+ && [text, bareSql(text)].some((form) => SQL_WRITE.test(form) || SQL_ADMIN.test(form) || SQL_SIDE_EFFECTS.test(form))))
347
+ return false;
348
+ if (statement) {
349
+ return runsSql && given.some(({ key, text }) => keyNamed(SQL_KEY, key) && sqlKind(text) === "read");
350
+ }
351
+ if (verbs.includes("read"))
352
+ return true;
353
+ // Allowed once, the tool is still asked in words each run, and those words
354
+ // say what it does: a risk word ("remove the stale rows") or a change word
355
+ // ("update every sales row") asks again.
356
+ return allowed && !given.some(({ text }) => sqlKind(text) === null && (RISKS.some((risk) => risk.test(text.toLowerCase())) || ["change", "plain"].includes(verbOf(text))));
357
+ }
358
+ /** Whether a tool is named for running SQL ("execute_sql", "run_query"): what
359
+ * a read-only turn may offer, since only the statement it is sent says whether
360
+ * the call reads (sentSql); every call there is still checked by it (#6797). */
361
+ export function runsSqlStatements(name) {
362
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).some((word) => SQL_OBJECTS.has(word));
363
+ }
364
+ /** What the SQL a call sends does, judged by the statement itself and never
365
+ * by the tool's labels (#6797): "read" when it has the one closed shape an
366
+ * automation's read runs in (automationReads, #6628; the tool's own hints
367
+ * are not passed, so a destructive label never turns a count into a change),
368
+ * "write" when any text under it is SQL that may change
369
+ * something, null when the call carries no SQL (or SQL that reads in some
370
+ * other shape, which no word here claims). Generic: no app is named (#4419). */
371
+ export function sentSql(name, args = {}) {
372
+ const runsSql = runsSqlStatements(name);
373
+ const given = argTexts(args).filter(({ key, text }) => sqlKind(text) !== null && (runsSql || keyNamed(SQL_ONLY_KEY, key) || SQL_SYNTAX.test(text)));
374
+ if (given.some(({ text }) => sqlKind(text) === "write"))
375
+ return "write";
376
+ return given.length > 0 && automationReads(name, args) ? "read" : null;
377
+ }
378
+ /** Whether a call has the shape `rule` names (CallRule in catalog.d.mts). */
379
+ export function callMatches(rule, name, args = {}) {
380
+ if (rule.tools && !rule.tools.includes(name))
381
+ return false;
382
+ if (rule.name !== undefined && !new RegExp(rule.name).test(name))
383
+ return false;
384
+ if (rule.words !== undefined && !new RegExp(rule.words).test(`${name} ${actionTexts(args).join(" ")}`.toLowerCase()))
385
+ return false;
386
+ for (const [arg, values] of Object.entries(rule.args ?? {})) {
387
+ if (!values.some((value) => value === null ? args[arg] === undefined : args[arg] === value))
388
+ return false;
389
+ }
390
+ return !rule.flags || rule.flags.some((flag) => args[flag] === true);
391
+ }
392
+ export function writeRisk(app, name, args = {}, hints) {
72
393
  const words = `${name.replace(/([a-z])([A-Z])/g, "$1_$2")} ${actionTexts(args).join(" ")}`.toLowerCase();
73
- if (provider === "stripe" || MONEY.test(words))
394
+ if (app?.money === true || MONEY.test(words))
74
395
  return "money";
75
396
  if (SENDING.test(words))
76
397
  return "sending";
@@ -94,20 +415,28 @@ export function writeRisk(provider, name, args = {}, hints) {
94
415
  if (callVerbs(name, args).every((verb) => verb === "plain"))
95
416
  return null;
96
417
  }
97
- // A small reviewed list. Any other is open-ended.
98
- if (provider === "linear" && ["create_issue", "update_issue", "save_issue"].includes(name))
99
- return null;
100
- if (provider === "notion" && ["notion-create-pages", "create_pages"].includes(name))
101
- return null;
102
- if (provider === "notion" && ["notion-update-page", "update_page"].includes(name)
103
- && [undefined, "insert_content", "update_properties", "replace_content_range"].includes(args.command))
104
- return null;
105
- if (provider === "github" && (name === "add_issue_comment" || (name === "issue_write" && ["create", "update"].includes(String(args.method)))))
106
- return null;
107
- if (["jira", "atlassian"].includes(provider) && ["createJiraIssue", "editJiraIssue"].includes(name))
418
+ // The app's own reviewed writes, from its catalog row. Any other is open-ended.
419
+ if (app?.reviewed?.some((rule) => callMatches(rule, name, args)))
108
420
  return null;
109
421
  return "open-ended";
110
422
  }
423
+ // A generic action whose effect its own name does not say ("exec", "run"):
424
+ // it may read or change, so its ask names neither (#6795).
425
+ const USES = new Set(["exec", "execute", "run", "invoke", "call", "eval", "evaluate"]);
426
+ /** What an asked call does, in the words its question uses (#6795): it only
427
+ * reads by its own verbs, it names a change, or it is a generic action (or
428
+ * has no verb) that says neither. Generic: no app is named (#4419). */
429
+ export function callKind(name, args = {}) {
430
+ // A tool that runs a statement is judged by the statement it was sent, not
431
+ // by its name or its destructive label (#6797).
432
+ const sql = sentSql(name, args);
433
+ if (sql)
434
+ return sql === "read" ? "read" : "change";
435
+ if (callVerbs(name, args).every((verb) => verb === "read"))
436
+ return "read";
437
+ const words = [name, ...actionTexts(args)].flatMap((text) => text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/));
438
+ return words.some((word) => PLAIN.has(word) || (CHANGES.has(word) && !USES.has(word))) ? "change" : "use";
439
+ }
111
440
  /** The one line under the ask that says why it asks every time, or "" when
112
441
  * there is no plainer reason than the ask's own "Asks every time": a tool
113
442
  * that only flags itself destructive names no act of its own (#4571). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "viewable-one",
3
- "version": "0.12.6",
3
+ "version": "0.12.8",
4
4
  "description": "Run coding agents from the Viewable board. Connects your machine to app.viewable.one, launches a session in its own worktree when you press Run, and streams what it does back to the canvas.",
5
5
  "keywords": [
6
6
  "mcp",
package/spawn-runner.mjs CHANGED
@@ -15,6 +15,7 @@
15
15
  import { newRunnerId, pollOnce, settingsFromEnv, watch } from "./lib/runner.mjs";
16
16
  import { AGENTS } from "./lib/agents.mjs";
17
17
  import { makeAgentProbe } from "./lib/detect.mjs";
18
+ import { makeChoiceMark } from "./lib/agent-selection.mjs";
18
19
  import { platformMark } from "./lib/platform.mjs";
19
20
  import { mergeWorktree, deleteWorktree } from "./lib/worktree.mjs";
20
21
 
@@ -132,9 +133,12 @@ async function main() {
132
133
  // hand-started runner has to say it too or a session started this way
133
134
  // would be handed the wrong shell.
134
135
  const platform = platformMark();
136
+ // The programs chosen for this folder (#6704), as the daemon says them.
137
+ const chosen = makeChoiceMark({ folders: () => [root], log: say });
138
+ await chosen.refresh();
135
139
  await watch(
136
140
  root,
137
- { ...settings, markExtra: () => ({ ...platform, ...probe.mark() }), refreshAgents: () => probe.once() },
141
+ { ...settings, markExtra: () => ({ ...platform, ...probe.mark(), ...chosen.mark() }), refreshAgents: () => probe.once() },
138
142
  { signal: controller.signal, log: say },
139
143
  );
140
144
  return;