viewable-one 0.12.7 → 0.12.9

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,6 +68,423 @@ export function readsOnly(name, args = {}, hints) {
68
68
  return false;
69
69
  return !callVerbs(name, args).some((verb) => verb !== "read");
70
70
  }
71
+ /** Whether a call says it changes something: its label (not read-only, or
72
+ * destructive) or a change verb in its name or an action. A call with no
73
+ * label and no verb ("customer_info") says nothing, and a read verb says it
74
+ * reads. Unlike readsOnly, which treats an unlabelled call as a write for
75
+ * safety, this asks whether the call itself claims a change (#7526). */
76
+ export function namesAChange(name, args = {}, hints) {
77
+ if (readsOnly(name, args, hints))
78
+ return false;
79
+ if (hints?.readOnlyHint === false || hints?.destructiveHint === true)
80
+ return true;
81
+ return callVerbs(name, args).some((verb) => verb === "plain" || verb === "change");
82
+ }
83
+ // AN AUTOMATION'S READS (ruling #5495): setting an automation is the
84
+ // person's yes for the reads it needs, label or not (a person's own server
85
+ // rarely labels its tools). A write still asks: anything below that may
86
+ // change something is never an automation read, allowed once or not.
87
+ // The words that run a statement the call carries ("sql_exec_tool",
88
+ // "run_query"): the call does what its statement does. Only a tool whose
89
+ // name also says what it runs is one (a "run_agent" runs no SQL), and only
90
+ // an argument named for its statement carries it (#6628 judge review).
91
+ const STATEMENTS = new Set(["run", "exec", "execute"]);
92
+ const SQL_OBJECTS = new Set(["sql", "query", "queries", "statement", "statements"]);
93
+ const SQL_KEY = /(?:^|_)(?:sql|query|statement|stmt)$/;
94
+ // An argument named only for SQL holds SQL whatever word it starts with, so
95
+ // on any tool it runs unattended only when it is a SQL read; a statement it
96
+ // cannot read asks (allowlist, #6628 lead recheck). On a tool whose own name
97
+ // says it runs SQL ("query", "read_query"), a "query" argument is SQL the same
98
+ // way, even if that tool sometimes takes plain words: safety over an extra ask.
99
+ // Elsewhere a "query" can be search words: one that starts like no statement
100
+ // still asks when it holds a write word or a side-effect function anywhere
101
+ // (SQL Server runs "if 1=1 drop table sales" with no semicolon).
102
+ const SQL_ONLY_KEY = /(?:^|_)(?:sqls?|statements?|stmts?)$/;
103
+ // SQL is read the same way by every database only when it holds no comment,
104
+ // no dollar quote, no backticked name and no backslash: databases nest block
105
+ // comments or not, take "//" or "#" as a comment or not, allow "$" inside a
106
+ // name or not, escape a quote with a backslash or not. Masking cannot match
107
+ // them all, so a text holding any of these is never an unattended read: it
108
+ // asks (#6628 lead review). So does a bracket: SQL Server reads [a'b] as a
109
+ // name, ODBC reads {call p()} as a call (#6628 lead decision); so does a
110
+ // triple quote (BigQuery's ''' strings) and "&" (Postgres U&"..." names spell
111
+ // a function in escapes, judge recheck at be6f8fd2b). What is left
112
+ // is masked once, from the left.
113
+ const SQL_UNSURE = /\/\*|--|#|\/\/|`|\$|\\|\[|\{|'''|"""|&/;
114
+ const QUOTED = /'(?:[^']|'')*'?|"(?:[^"]|"")*"?/g;
115
+ function bareSql(text) {
116
+ return text.replace(QUOTED, (part) => (part.startsWith("'") ? " '' "
117
+ // A quoted name is still that name to the database ("setval"(...) is setval):
118
+ // kept, with anything that is not a name character made inert.
119
+ : ` ${part.slice(1, part.endsWith('"') && part.length > 1 ? -1 : undefined).replace(/""/g, '"').replace(/[^\w$]/g, "_")} `));
120
+ }
121
+ // The words a statement starts with. A text that starts with none is not SQL.
122
+ // Words that also start plain sentences ("start", "import") count only with
123
+ // the word that makes them a statement.
124
+ 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"
125
+ + "|reindex|cluster|analyze|analyse|checkpoint|reset|notify|listen|unlisten|prepare|deallocate|savepoint|abort|reassign|shutdown|flush|attach|detach|pragma|declare"
126
+ // MySQL 8 reads a lone RESTART as a server restart; "Restart the report" is a sentence.
127
+ + "|restart(?=\\s*$)"
128
+ + "|start\\s+transaction|load\\s+(?:data|extension|index|xml|(?='))|import\\s+(?:foreign|table|into|database)|(?:un)?install\\s+(?:plugin|component)|security\\s+label"
129
+ + "|values(?=\\s*\\()|table(?=\\s+[\\w.\"]+\\s*;?\\s*$)"
130
+ + "|kill\\s+(?:query|connection|\\d+)|optimize\\s+table|repair\\s+table|discard\\s+(?:all|plans|sequences|temp|temporary)|purge\\s+(?:binary|master)";
131
+ const SQL_STARTS = new RegExp(`^[\\s(]*(?:${STATEMENT_WORDS})(?!\\w)`, "i");
132
+ // Where a statement may start once some database drops a comment: after a
133
+ // semicolon, a line end or any comment mark (MySQL runs "/*!50000 ... */").
134
+ // With one of the characters above, a text with a statement start at any of
135
+ // them is SQL that may write (a comment before "refresh" leaves no start at
136
+ // the front, #6628 lead recheck); a sentence that holds "#" or "$" is not.
137
+ const SQL_BREAKS = /;|\r|\n|\/\*!?\d*|\*\/|--|#|\/\/|\\/;
138
+ // The statements that only read. SHOW names what it lists, so "Show revenue,
139
+ // then email it" is not one.
140
+ 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;
141
+ // A word that changes something, for text that does not start like SQL
142
+ // ("if 1=1 drop table sales" under a search): it asks. The read rule below
143
+ // does not use it; a function of the same name is not one.
144
+ // The statements that run a server's admin work, for the same text (a
145
+ // search, a filter): "dbcc freeproccache", "1=1 shutdown with nowait".
146
+ 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;
147
+ 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;
148
+ // A function a SELECT can call that changes something (a sequence, a
149
+ // session, a file, a lock, another database): the call is a write however it
150
+ // is wrapped. A list cannot be complete, so the database role the person
151
+ // connects with stays the real limit; these are the common ones. Reading a
152
+ // server file or a sequence's counter, and the common extensions that run a
153
+ // job, keep a secret, queue a message or reach the web (cron., vault., pgmq.,
154
+ // net., http*) are on it too (#8071).
155
+ const SQL_SIDE_EFFECTS = /(?:^|[^\w$])(?:currval|pg_read_\w*|pg_ls_\w*|pg_stat_file|(?:cron|vault|net|pgmq)\s*\.\s*\w+|http\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;
156
+ // THE READ RULE (#6628 lead decision): a closed allow list, not a list of
157
+ // writes. The same text means different things in different databases
158
+ // ("select 1 shutdown" is an alias in Postgres and a server stop in SQL
159
+ // Server, which needs no semicolon), so a SQL text is an unattended read only
160
+ // when, once masked, it is one statement that starts as a read and every bare
161
+ // word is a read keyword below or a word no supported database reserves
162
+ // (Postgres, MySQL, SQL Server and Sybase, Snowflake, BigQuery, SQLite). Their
163
+ // reserved-word lists are published and closed; the words that write are not.
164
+ // A name nobody reserves (a table, a column, "status", "name") is fine.
165
+ 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 " +
166
+ "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 " +
167
+ "with recursive asc desc nulls true false unknown cast try_cast convert try_convert coalesce nullif over partition window range groups unbounded preceding following " +
168
+ "current filter within qualify sample tablesample pivot unpivot exists any some escape collate interval values top percent dual of to at zone extract leading " +
169
+ "trailing both separator match div mod xor isnull notnull overlaps symmetric asymmetric unnest array struct ignore respect exclude contains rollup cube grouping sets " +
170
+ "explain describe show tables views schemas databases columns terse objects functions procedures stages roles grants users parameters sequences indexes semantic warehouses " +
171
+ "current_date current_time current_timestamp current_user current_role current_catalog current_schema session_user system_user user localtime localtimestamp " +
172
+ "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 " +
173
+ "char character varchar varcharacter nchar nvarchar national varying int integer int1 int2 int3 int4 int8 smallint tinyint mediumint middleint bigint dec decimal " +
174
+ "numeric float float4 float8 double precision real binary varbinary blob tinyblob mediumblob longblob text tinytext mediumtext longtext long unsigned signed boolean " +
175
+ "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 " +
176
+ "account organization issue connection key keys file public plan rule option index schema table column database view function statistics identity query action").split(" "));
177
+ // Reserved words that are also read functions, allowed only as a call ("if(a, b, c)", "replace(name, 'a', 'b')").
178
+ const SQL_READ_CALLS = new Set(["if", "replace", "repeat", "truncate"]);
179
+ // Every word a supported database reserves, and every word a statement starts
180
+ // with there (SQL Server starts DISABLE, ENABLE, RECEIVE, SEND, THROW, MOVE
181
+ // and GET statements with words it does not reserve).
182
+ const SQL_RESERVED = new Set((
183
+ // SQL Server and Sybase
184
+ "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 " +
185
+ "compute constraint contains containstable continue convert create cross current current_date current_time current_timestamp current_user cursor database dbcc " +
186
+ "deallocate declare default delete deny desc disk distinct distributed double drop dump else end errlvl escape except exec execute exists exit external fetch file " +
187
+ "fillfactor for foreign freetext freetexttable from full function goto grant group having holdlock identity identity_insert identitycol if in index inner insert " +
188
+ "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 " +
189
+ "openxml option or order outer over percent pivot plan precision primary print proc procedure public raiserror read readtext reconfigure references replication restore " +
190
+ "restrict return revert revoke right rollback rowcount rowguidcol rule save schema securityaudit select semantickeyphrasetable semanticsimilaritydetailstable " +
191
+ "semanticsimilaritytable session_user set setuser shutdown some statistics system_user table tablesample textsize then to top tran transaction trigger truncate " +
192
+ "try_convert tsequal union unique unpivot update updatetext use user values varying view waitfor when where while with within writetext " +
193
+ "disable enable receive send throw move get mirror remirror unmirror mount unmount modify online offline quiesce reorg install remove lock prepare dump " +
194
+ // MySQL
195
+ "accessible analyze asensitive before bigint binary blob both call change char character condition cube cume_dist databases day_hour day_microsecond day_minute " +
196
+ "day_second dec decimal delayed dense_rank describe deterministic distinctrow div dual each elseif empty enclosed escaped explain first_value float float4 float8 force " +
197
+ "fulltext generated groups grouping high_priority hour_microsecond hour_minute hour_second ignore infile inout insensitive int int1 int2 int3 int4 int8 integer interval " +
198
+ "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 " +
199
+ "low_priority master_bind master_ssl_verify_server_cert match maxvalue mediumblob mediumint mediumtext middleint minute_microsecond minute_second mod modifies natural " +
200
+ "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 " +
201
+ "release rename repeat replace require resignal rlike row rows row_number schemas second_microsecond sensitive separator show signal smallint spatial specific sql " +
202
+ "sqlexception sqlstate sqlwarning sql_big_result sql_calc_found_rows sql_small_result ssl starting stored straight_join system terminated tinyblob tinyint tinytext " +
203
+ "trailing true undo unlock unsigned usage using utc_date utc_time utc_timestamp varbinary varchar varcharacter virtual window write xor year_month zerofill false " +
204
+ // Postgres
205
+ "analyse array asymmetric cast collation concurrently current_catalog current_role current_schema deferrable do freeze ilike initially isnull notnull offset only " +
206
+ "overlaps placing returning similar symmetric variadic verbose " +
207
+ // Snowflake
208
+ "account connect connection gscluster increment issue minus organization qualify sample start try_cast whenever " +
209
+ // BigQuery
210
+ "assert_rows_modified at contains define enum exclude extract following hash lookup new no nulls preceding proto respect struct treat unbounded unnest " +
211
+ // SQLite
212
+ "abort action after always attach autoincrement conflict deferred detach exclusive fail filter first glob immediate indexed instead last materialized nothing " +
213
+ "others pragma query raise reindex savepoint temp temporary ties vacuum without " +
214
+ // The statement words above (a word that starts a statement is never a plain name here)
215
+ "copy put upsert undrop refresh reset unset notify listen unlisten reassign flush cluster security import restart").split(" "));
216
+ // Every run of letters, also one glued to a number: SQL Server and MySQL
217
+ // read "1delete" as 1 then DELETE, and "0x1shutdown" as 0x1 then SHUTDOWN
218
+ // (judge recheck at be6f8fd2b). A name like "drop1" asks: the safe side.
219
+ const SQL_WORDS = /[a-z_]+/gi;
220
+ // FETCH reads only as "fetch first/next n rows only"; alone it is a cursor statement.
221
+ const SQL_FETCH_CLAUSE = /\bfetch\s+(?:first|next)\s+(?:\w+\s+)?rows?\s+(?:only|with\s+ties)\b/gi;
222
+ /** Whether masked SQL holds only read words: each reserved word is a read
223
+ * keyword, or a read function written as a call. END only closes a CASE
224
+ * ("end conversation" is a SQL Server statement), and a system procedure
225
+ * name (sp_, xp_) is never a read word. */
226
+ function readWordsOnly(masked) {
227
+ const text = masked.replace(SQL_FETCH_CLAUSE, " ");
228
+ let cases = 0;
229
+ for (const found of text.matchAll(SQL_WORDS)) {
230
+ const word = found[0].toLowerCase();
231
+ if (/^(?:sp|xp)_/.test(word))
232
+ return false;
233
+ if (word === "case")
234
+ cases += 1;
235
+ if (word === "end" && cases-- <= 0)
236
+ return false;
237
+ if (!SQL_RESERVED.has(word) || SQL_READ_WORDS.has(word))
238
+ continue;
239
+ if (SQL_READ_CALLS.has(word) && /^\s*\(/.test(text.slice((found.index ?? 0) + word.length)))
240
+ continue;
241
+ return false;
242
+ }
243
+ return true;
244
+ }
245
+ // A plain value beside a statement (a project id, a database name, "10"):
246
+ // one word of letters, digits, "_", "-" or "." that names no statement word.
247
+ const PLAIN_VALUE = /^(?!.*--)[A-Za-z0-9_.-]+$/;
248
+ /** Quoted text and quoted names masked to a placeholder: neither is a keyword. */
249
+ function maskedWords(text) {
250
+ return text.replace(QUOTED, " q ");
251
+ }
252
+ /** What a text is as SQL: "read" when it passes the read rule above, "write"
253
+ * when it is SQL that does not (it may change something), null when it is
254
+ * not SQL at all. Functions a person defined are the database role's limit:
255
+ * SQL_SIDE_EFFECTS names the common built-in ones. */
256
+ function sqlKind(text) {
257
+ if (SQL_UNSURE.test(text))
258
+ return text.split(SQL_BREAKS).some((part) => SQL_STARTS.test(part)) ? "write" : null;
259
+ const bare = bareSql(text);
260
+ const statements = bare.split(";").filter((part) => part.trim() !== "");
261
+ if (!statements.some((part) => SQL_STARTS.test(part)))
262
+ return null;
263
+ return statements.length === 1 && SQL_READ.test(statements[0]) && readWordsOnly(maskedWords(text)) && !SQL_SIDE_EFFECTS.test(bare) ? "read" : "write";
264
+ }
265
+ const RISKS = [MONEY, SENDING, DELETING, PUBLISHING, MERGING, DEPLOYING];
266
+ /** An argument name in lower snake case ("projectId" and "ProjectID" are "project_id"). */
267
+ function snakeKey(name) {
268
+ return name.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
269
+ }
270
+ /** Every text a call is given with the name of the argument that holds it,
271
+ * however deep (a statement may sit in a list or an object). Bounded, so a
272
+ * huge or looping value cannot hang the check. */
273
+ function argTexts(value, key = "", depth = 0) {
274
+ if (typeof value === "string")
275
+ return [{ key, text: value }];
276
+ if (value === null || typeof value !== "object")
277
+ return [];
278
+ // Past the walk limit the texts are not read, so the call is not a read.
279
+ if (depth > 4)
280
+ return [{ key, text: "", deep: true }];
281
+ // A nested object keeps the names above it ({query: {text}} is "query.text").
282
+ return Object.entries(value).flatMap(([name, item]) => argTexts(item, Array.isArray(value) ? key
283
+ : [key, snakeKey(name)].filter(Boolean).join("."), depth + 1));
284
+ }
285
+ // The only arguments that may sit beside a SQL read, each a plain top-level
286
+ // value that names where or how much to read, never what to run. A closed
287
+ // list, so no new spelling of a statement argument ("querytext", "SQLText",
288
+ // "q") can slip in beside the read (lead decision at e7cb0d15c). Add a key
289
+ // only when a real read needs it: project_id (Supabase execute_sql), database,
290
+ // schema and warehouse (Snowflake), limit (read_query).
291
+ const SQL_CONTEXT_KEYS = new Set(["project_id", "project", "database", "db", "schema", "warehouse", "catalog", "role", "limit", "max_rows", "timeout", "format"]);
292
+ // What a plain sentence does not have: a FROM clause, a semicolon, a star, a
293
+ // bracket, a VALUES or TABLE start, or a SELECT followed by a number, a quote
294
+ // or a sign ("select 1"). "describe our pricing" and "Select a plan" are English.
295
+ const SQL_SYNTAX = /\bfrom\b|;|\*|\(|^\s*(?:values|table)\b|\bselect\s*[\d'"@$+-]/i;
296
+ /** Whether a text is SQL that reads, for the SQL path. On a tool named for SQL
297
+ * any text that reads counts; elsewhere a text counts only under a SQL-named
298
+ * argument, or when it also has SQL syntax, so "explain the outage" or
299
+ * "Select a plan" in a search runs as before. */
300
+ function holdsSql(key, text, runsSql) {
301
+ return sqlKind(text) === "read" && (runsSql || keyNamed(SQL_ONLY_KEY, key) || SQL_SYNTAX.test(text));
302
+ }
303
+ /** Whether the call, which holds SQL, has the one shape that runs unasked:
304
+ * exactly one top-level argument holds SQL, it is a string and it reads, and
305
+ * every other argument is a top-level plain value under a context key. A
306
+ * second SQL argument, any other key, and any list or object (even of
307
+ * numbers) ask. Shape and key list only, no app is named (#4419). */
308
+ function closedSqlShape(args, runsSql) {
309
+ const holders = Object.entries(args).filter(([name, value]) => argTexts(value, snakeKey(name), 1).some(({ key, text }) => holdsSql(key, text, runsSql)));
310
+ if (holders.length !== 1 || typeof holders[0][1] !== "string")
311
+ return false;
312
+ return Object.entries(args).every(([name, value]) => name === holders[0][0]
313
+ || (SQL_CONTEXT_KEYS.has(snakeKey(name)) && (typeof value === "number" || typeof value === "boolean"
314
+ || (typeof value === "string" && PLAIN_VALUE.test(value.trim()) && readWordsOnly(value)))));
315
+ }
316
+ /** Whether any name on an argument's path matches `rule`. */
317
+ function keyNamed(rule, key) {
318
+ return key.split(".").some((part) => rule.test(part));
319
+ }
320
+ /** Whether a call from an automation only reads, so it runs with no ask
321
+ * (ruling #5495). Never when the tool says it writes or destroys, the call
322
+ * carries a risk word or an archive flag, any word names a create, edit or
323
+ * other change, or any text is SQL that may change something. Then: a tool
324
+ * that runs SQL ("sql_exec_tool") reads only when its statement argument
325
+ * holds a SQL read; one whose words name a read ("query", "list_tables")
326
+ * reads; one whose words name nothing reads only once `allowed`, the
327
+ * person's own Allow of this tool in this automation, and only while what
328
+ * it is asked carries no risk word. Generic: no app is named (#4419). */
329
+ export function automationReads(name, args = {}, hints, allowed = false) {
330
+ if (hints?.readOnlyHint === false || hints?.destructiveHint === true)
331
+ return false;
332
+ if (args.archived === true || args.in_trash === true)
333
+ return false;
334
+ // The words writeRisk reads, so a call it calls money, sending, deleting,
335
+ // publishing, merging or deploying is never a read here either.
336
+ if (RISKS.some((risk) => risk.test(`${name.replace(/([a-z])([A-Z])/g, "$1_$2")} ${actionTexts(args).join(" ")}`.toLowerCase())))
337
+ return false;
338
+ const words = [name, ...actionTexts(args)].join(" ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/);
339
+ const statement = words.some((word) => STATEMENTS.has(word));
340
+ const verbs = words.filter((word) => !STATEMENTS.has(word)).map(verbOf);
341
+ if (verbs.some((verb) => verb === "change" || verb === "plain"))
342
+ return false;
343
+ const given = argTexts(args);
344
+ if (given.some(({ deep }) => deep))
345
+ return false;
346
+ if (given.some(({ text }) => sqlKind(text) === "write"))
347
+ return false;
348
+ const runsSql = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).some((word) => SQL_OBJECTS.has(word));
349
+ // The SQL path: a tool named for SQL, or any call that holds SQL text under
350
+ // any name (found by content, not by name) or has a sql/statement/stmt
351
+ // argument. With a SQL read in it, the call runs only in the closed shape
352
+ // above. A SQL-named tool with no SQL read in it runs only with no text at all.
353
+ const hasSqlRead = given.some(({ key, text }) => holdsSql(key, text, runsSql));
354
+ if (hasSqlRead || given.some(({ key }) => keyNamed(SQL_ONLY_KEY, key))) {
355
+ if (!closedSqlShape(args, runsSql))
356
+ return false;
357
+ }
358
+ else if (runsSql && given.some(({ text }) => text.trim() !== ""))
359
+ return false;
360
+ if (given.some(({ text }) => sqlKind(text) === null
361
+ && [text, bareSql(text)].some((form) => SQL_WRITE.test(form) || SQL_ADMIN.test(form) || SQL_SIDE_EFFECTS.test(form))))
362
+ return false;
363
+ if (statement) {
364
+ return runsSql && given.some(({ key, text }) => keyNamed(SQL_KEY, key) && sqlKind(text) === "read");
365
+ }
366
+ if (verbs.includes("read"))
367
+ return true;
368
+ // Allowed once, the tool is still asked in words each run, and those words
369
+ // say what it does: a risk word ("remove the stale rows") or a change word
370
+ // ("update every sales row") asks again.
371
+ return allowed && !given.some(({ text }) => sqlKind(text) === null && (RISKS.some((risk) => risk.test(text.toLowerCase())) || ["change", "plain"].includes(verbOf(text))));
372
+ }
373
+ /** Whether a tool is named for running SQL ("execute_sql", "run_query"): what
374
+ * a read-only turn may offer, since only the statement it is sent says whether
375
+ * the call reads (sentSql); every call there is still checked by it (#6797). */
376
+ export function runsSqlStatements(name) {
377
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).some((word) => SQL_OBJECTS.has(word));
378
+ }
379
+ /** What the SQL a call sends does, judged by the statement itself and never
380
+ * by the tool's labels (#6797): "read" when it has the one closed shape an
381
+ * automation's read runs in (automationReads, #6628; the tool's own hints
382
+ * are not passed, so a destructive label never turns a count into a change),
383
+ * "write" when any text under it is SQL that may change
384
+ * something, null when the call carries no SQL (or SQL that reads in some
385
+ * other shape, which no word here claims). Generic: no app is named (#4419). */
386
+ export function sentSql(name, args = {}) {
387
+ const runsSql = runsSqlStatements(name);
388
+ const given = argTexts(args).filter(({ key, text }) => sqlKind(text) !== null && (runsSql || keyNamed(SQL_ONLY_KEY, key) || SQL_SYNTAX.test(text)));
389
+ if (given.some(({ text }) => sqlKind(text) === "write"))
390
+ return "write";
391
+ return given.length > 0 && automationReads(name, args) ? "read" : null;
392
+ }
393
+ // ALLOW FOR THIS BOARD (#6771, #8071): a saved yes means no card at all, so a
394
+ // tool that runs whatever it is given (a SQL tool) is covered only while every
395
+ // text it is given is a plain value or a SQL read under two rules at once: the
396
+ // read rule above, and a word scan over the raw text, quoted strings included
397
+ // ("select cron.schedule('j', '* * * * *', 'delete from orders')" hides its
398
+ // write in a string). A function call reads only when it is a built-in read
399
+ // listed below: one the person wrote ("select delete_all_orders()") or an
400
+ // extension's asks. Automations keep the shorter list of side effects above
401
+ // (ruling #5495), so their reads do not start to ask. A false alarm only asks.
402
+ const BOARD_WRITE_WORDS = /\b(into|insert|update|upsert|delete|drop|truncate|alter|create|replace|rename|grant|revoke|merge|copy|call|do|execute|prepare|set|reset|refresh|vacuum|analyze|reindex|cluster|comment|lock|listen|notify|discard|begin|commit|rollback|setval|nextval|currval|set_config|dblink\w*|lo_\w+|pg_(sleep|terminate_backend|cancel_backend|reload_conf|rotate_logfile|read_\w+|ls_\w+|stat_file|advisory_\w+|switch_wal\w*|create_\w+|drop_\w+))\b|\bfor\s+(update|share|no\s+key\s+update|key\s+share)\b/i;
403
+ // The built-in functions that only read, by full name: no prefix family, since
404
+ // anyone may name a function "pg_get_cleanup" (box review of f0e2d1f2a). A
405
+ // function the person wrote with a listed name and other argument types could
406
+ // still be picked by the database; its role stays the last limit there.
407
+ const BOARD_READ_CALLS = new Set(("count sum avg min max array_agg string_agg json_agg jsonb_agg json_object_agg jsonb_object_agg bool_and bool_or every stddev stddev_pop stddev_samp " +
408
+ "variance var_pop var_samp percentile_cont percentile_disc mode corr covar_pop covar_samp group_concat listagg any_value median approx_count_distinct " +
409
+ "lower upper length char_length character_length octet_length bit_length substr btrim ltrim rtrim concat concat_ws left right replace repeat " +
410
+ "strpos instr locate reverse split_part lpad rpad initcap format to_char to_number md5 regexp_replace regexp_match regexp_matches regexp_like " +
411
+ "regexp_substr regexp_split_to_array starts_with string_to_array array_to_string translate ascii chr quote_ident quote_literal quote_nullable encode decode " +
412
+ "now date_trunc date_part age to_date to_timestamp make_date make_time make_timestamp make_interval date_add date_sub datediff dateadd timestampdiff " +
413
+ "timestampadd date_format clock_timestamp statement_timestamp transaction_timestamp justify_days justify_hours justify_interval isfinite timezone " +
414
+ "date year month day hour minute second week quarter dayofweek dayofmonth dayofyear abs round ceil ceiling floor trunc power pow sqrt cbrt exp ln log log10 " +
415
+ "sign pi degrees radians width_bucket random to_json to_jsonb row_to_json array_to_json json_build_object jsonb_build_object json_build_array " +
416
+ "jsonb_build_array json_object jsonb_object json_extract_path jsonb_extract_path json_extract_path_text jsonb_extract_path_text json_array_length " +
417
+ "jsonb_array_length json_typeof jsonb_typeof json_object_keys jsonb_object_keys json_array_elements jsonb_array_elements json_array_elements_text " +
418
+ "jsonb_array_elements_text json_each jsonb_each json_each_text jsonb_each_text jsonb_path_query jsonb_path_exists jsonb_pretty jsonb_strip_nulls " +
419
+ "json_extract json_value json_query array_length cardinality array_position array_positions array_upper array_lower array_dims unnest generate_series " +
420
+ "generate_subscripts lag lead rank dense_rank row_number ntile first_value last_value nth_value percent_rank cume_dist " +
421
+ "format_type to_regclass to_regtype obj_description col_description version current_setting current_database current_schemas " +
422
+ "pg_typeof pg_size_pretty pg_size_bytes pg_database_size pg_total_relation_size pg_relation_size pg_table_size pg_indexes_size pg_column_size " +
423
+ "pg_tablespace_size pg_is_in_recovery pg_backend_pid pg_current_wal_lsn pg_postmaster_start_time pg_conf_load_time pg_has_role " +
424
+ "pg_get_viewdef pg_get_functiondef pg_get_function_arguments pg_get_function_identity_arguments pg_get_function_result pg_get_indexdef " +
425
+ "pg_get_constraintdef pg_get_triggerdef pg_get_ruledef pg_get_expr pg_get_serial_sequence pg_get_userbyid pg_get_keywords pg_get_partkeydef " +
426
+ "pg_stat_get_numscans pg_stat_get_tuples_returned pg_stat_get_tuples_fetched pg_stat_get_tuples_inserted pg_stat_get_tuples_updated " +
427
+ "pg_stat_get_tuples_deleted pg_stat_get_live_tuples pg_stat_get_dead_tuples pg_stat_get_last_vacuum_time pg_stat_get_last_analyze_time " +
428
+ "pg_table_is_visible pg_type_is_visible pg_function_is_visible has_table_privilege has_schema_privilege has_database_privilege " +
429
+ "has_column_privilege has_function_privilege has_sequence_privilege has_any_column_privilege").split(" "));
430
+ // Words that may open a bracket and are never a function: Postgres reserves
431
+ // them, or bars them as function names ("in (", "as (", "exists (",
432
+ // "cast(", "numeric(10, 2)"). An everyday word ("first", "filter") may name
433
+ // a function someone wrote, so it is not here.
434
+ const BOARD_BRACKET_WORDS = new Set(("select in exists as values any all some on from where and or not when then else case having by union intersect " +
435
+ "except with between distinct array row interval cast coalesce nullif extract greatest least position substring trim overlay lateral using " +
436
+ "numeric decimal dec char character varchar nchar float time timestamp bit varying int integer smallint bigint real boolean precision group window").split(" "));
437
+ // Words that open a bracket only after a call's own closing one: "count(*) filter (where ...)", "over (partition by ...)".
438
+ const BOARD_AFTER_CALL_WORDS = new Set(["over", "filter"]);
439
+ // Whatever stands right before a bracket, in any script: a name ends at a
440
+ // space, a bracket, a comma or an operator, so "public.清空订单(" is one name.
441
+ const SQL_CALLS = /([^\s(),;'"+\-*/<>=!|&%^~:[\]{}@#?]*)\s*\(/gu;
442
+ /** Whether every call in a SQL read is a listed read; only pg_catalog may name
443
+ * one. A quoted name before a bracket ("any"(1)) may be any function: it asks. */
444
+ function callsOnlyRead(text) {
445
+ // Strings and quoted names in one pass from the left (QUOTED), so a quote
446
+ // inside one never opens the other ("x'y" is a name; box review of 059bf1a7e).
447
+ const unquoted = text.replace(QUOTED, (part) => (part.startsWith("'") ? " '' " : ' "q" '));
448
+ if (/"\s*\(/.test(unquoted))
449
+ return false;
450
+ const bare = unquoted.replace(/\s*\.\s*/g, ".");
451
+ for (const found of bare.matchAll(SQL_CALLS)) {
452
+ if (found[1] === "")
453
+ continue;
454
+ const parts = found[1].toLowerCase().split(".");
455
+ if (parts.length > 2 || (parts.length === 2 && parts[0] !== "pg_catalog"))
456
+ return false;
457
+ const name = parts[parts.length - 1];
458
+ if (BOARD_READ_CALLS.has(name))
459
+ continue;
460
+ if (parts.length === 1 && BOARD_BRACKET_WORDS.has(name))
461
+ continue;
462
+ if (parts.length === 1 && BOARD_AFTER_CALL_WORDS.has(name) && bare.slice(0, found.index).trimEnd().endsWith(")"))
463
+ continue;
464
+ return false;
465
+ }
466
+ return true;
467
+ }
468
+ /** Whether one text may run under Allow for this board: blank, a plain value
469
+ * that names no statement word ("abcd1234", "events_daily"), or one SQL
470
+ * read by both rules above whose calls are all listed reads. Free text, a
471
+ * comment and anything unsure ask. */
472
+ function boardText(text) {
473
+ const value = text.trim();
474
+ if (value === "")
475
+ return true;
476
+ if (PLAIN_VALUE.test(value))
477
+ return readWordsOnly(value) && sqlKind(value) !== "write";
478
+ return sqlKind(text) === "read" && !BOARD_WRITE_WORDS.test(text) && callsOnlyRead(text);
479
+ }
480
+ /** Whether every text a call is given, at any depth, may run under Allow for
481
+ * this board (see above): the one check the server makes for the card's
482
+ * offer, the saved yes and the run itself (#8071). A value past the walk
483
+ * limit asks. Generic: no app is named (#4419). */
484
+ export function boardMayRun(args = {}) {
485
+ const given = argTexts(args);
486
+ return !given.some(({ deep }) => deep) && given.every(({ text }) => boardText(text));
487
+ }
71
488
  /** Whether a call has the shape `rule` names (CallRule in catalog.d.mts). */
72
489
  export function callMatches(rule, name, args = {}) {
73
490
  if (rule.tools && !rule.tools.includes(name))
@@ -113,6 +530,23 @@ export function writeRisk(app, name, args = {}, hints) {
113
530
  return null;
114
531
  return "open-ended";
115
532
  }
533
+ // A generic action whose effect its own name does not say ("exec", "run"):
534
+ // it may read or change, so its ask names neither (#6795).
535
+ const USES = new Set(["exec", "execute", "run", "invoke", "call", "eval", "evaluate"]);
536
+ /** What an asked call does, in the words its question uses (#6795): it only
537
+ * reads by its own verbs, it names a change, or it is a generic action (or
538
+ * has no verb) that says neither. Generic: no app is named (#4419). */
539
+ export function callKind(name, args = {}) {
540
+ // A tool that runs a statement is judged by the statement it was sent, not
541
+ // by its name or its destructive label (#6797).
542
+ const sql = sentSql(name, args);
543
+ if (sql)
544
+ return sql === "read" ? "read" : "change";
545
+ if (callVerbs(name, args).every((verb) => verb === "read"))
546
+ return "read";
547
+ const words = [name, ...actionTexts(args)].flatMap((text) => text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/));
548
+ return words.some((word) => PLAIN.has(word) || (CHANGES.has(word) && !USES.has(word))) ? "change" : "use";
549
+ }
116
550
  /** The one line under the ask that says why it asks every time, or "" when
117
551
  * there is no plainer reason than the ask's own "Asks every time": a tool
118
552
  * 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.7",
3
+ "version": "0.12.9",
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;