replicas-engine 0.1.932 → 0.1.934

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.
@@ -1109,9 +1109,12 @@ var createChatRequestSchema = z3.object({
1109
1109
  title: z3.string().min(1).optional(),
1110
1110
  parentChatId: z3.string().uuid().optional(),
1111
1111
  forkSourceChatId: z3.string().uuid().optional(),
1112
+ sideChat: z3.boolean().optional(),
1112
1113
  clientRequestId: z3.string().min(1).max(128).optional()
1113
1114
  }).refine((request) => request.provider === "relay" || request.relayBaseProvider === void 0, {
1114
1115
  message: "relayBaseProvider is only valid for Relay chats"
1116
+ }).refine((request) => !request.sideChat || request.forkSourceChatId !== void 0 && request.parentChatId === request.forkSourceChatId, {
1117
+ message: "A side chat must fork its parent chat"
1115
1118
  });
1116
1119
  var spawnRelaySubagentRequestSchema = z3.object({
1117
1120
  provider: z3.enum(VALID_AGENT_PROVIDERS),
@@ -1931,7 +1934,7 @@ var chatForkInfoSchema = z8.object({
1931
1934
  provider: z8.enum(VALID_AGENT_PROVIDERS),
1932
1935
  title: z8.string()
1933
1936
  }),
1934
- trigger: z8.enum(["manual", "auto"]),
1937
+ trigger: z8.enum(["manual", "auto", "side"]),
1935
1938
  reason: quotaLimitKindSchema.optional(),
1936
1939
  state: z8.enum(["preparing", "ready", "failed"]),
1937
1940
  error: z8.string().optional(),
@@ -2059,6 +2062,313 @@ function normalizeBackgroundTaskStatus(status) {
2059
2062
  // ../shared/src/display-message/constants.ts
2060
2063
  var USER_MESSAGE_MATCH_GRACE_PERIOD_MS = 3e4;
2061
2064
 
2065
+ // ../shared/src/shell-commands.ts
2066
+ var SHELL_OPAQUE = "\0";
2067
+ var MAX_DEPTH = 8;
2068
+ var OPERATOR = /&&|\|\||;;|\|&|<<<|<<-|<<|&>>|&>|>>|>&|>\||<&|<>|[;&|()<>]/y;
2069
+ var NAME = /[A-Za-z_]\w*/y;
2070
+ var SHELLS = /* @__PURE__ */ new Set(["sh", "bash", "zsh", "dash", "ksh"]);
2071
+ var PREFIX_WORDS = /* @__PURE__ */ new Set(["!", "{", "}", "if", "then", "else", "elif", "fi", "do", "done", "while", "until", "time", "exec", "command", "builtin", "nohup"]);
2072
+ var WRAPPER_VALUE_OPTIONS = {
2073
+ env: /^(?:-[uCS]|--(?:unset|chdir|split-string))$/,
2074
+ sudo: /^(?:-[ugCpUrhDRT]|--(?:user|group|close-from|prompt|other-user|role|type|host|chdir|command-timeout))$/,
2075
+ nice: /^(?:-n|--adjustment)$/,
2076
+ timeout: /^(?:-[sk]|--(?:signal|kill-after))$/
2077
+ };
2078
+ var ANSI_C_ESCAPES = { n: "\n", t: " ", r: "\r", a: "\x07", b: "\b", e: "\x1B", E: "\x1B", f: "\f", v: "\v" };
2079
+ function parseShellScript(script, cwd) {
2080
+ const scope = { src: script, vars: /* @__PURE__ */ new Map(), dir: cwd, commands: [], depth: 0 };
2081
+ parseUntil(scope, 0, false);
2082
+ return scope.commands;
2083
+ }
2084
+ function resolveShellPath(dir, path) {
2085
+ if (path.includes(SHELL_OPAQUE) || path.startsWith("~")) return null;
2086
+ if (!path.startsWith("/") && dir === null) return null;
2087
+ const parts = [];
2088
+ for (const part of (path.startsWith("/") ? path : `${dir}/${path}`).split("/")) {
2089
+ if (part === "..") parts.pop();
2090
+ else if (part && part !== ".") parts.push(part);
2091
+ }
2092
+ return `/${parts.join("/")}`;
2093
+ }
2094
+ function stripCommandPrefixes(words) {
2095
+ const assignments = [];
2096
+ let k = 0;
2097
+ while (k < words.length) {
2098
+ const word = words[k];
2099
+ if (/^[A-Za-z_]\w*=/.test(word)) assignments.push(word);
2100
+ else if (WRAPPER_VALUE_OPTIONS[word]) {
2101
+ while (words[k + 1]?.startsWith("-")) k += WRAPPER_VALUE_OPTIONS[word].test(words[k + 1]) ? 2 : 1;
2102
+ if (word === "timeout") k++;
2103
+ } else if (!PREFIX_WORDS.has(word)) break;
2104
+ k++;
2105
+ }
2106
+ return { argv: words.slice(k), assignments };
2107
+ }
2108
+ function indexOrEnd(src, search, from) {
2109
+ const index = src.indexOf(search, from);
2110
+ return index < 0 ? src.length : index;
2111
+ }
2112
+ function decodeAnsiC(text2) {
2113
+ return text2.replace(/\\(x[0-9a-fA-F]{1,2}|u[0-9a-fA-F]{1,4}|[0-7]{1,3}|[\s\S])/g, (_match, escape) => {
2114
+ if (escape[0] === "x" || escape[0] === "u") return String.fromCharCode(parseInt(escape.slice(1), 16));
2115
+ if (/^[0-7]/.test(escape)) return String.fromCharCode(parseInt(escape, 8));
2116
+ return ANSI_C_ESCAPES[escape] ?? escape;
2117
+ });
2118
+ }
2119
+ function staticOutput(argv, stdin) {
2120
+ const [name, ...args] = argv;
2121
+ if (name === "cat") return args.length === 0 || args.length === 1 && args[0] === "-" ? stdin : void 0;
2122
+ if (name === "echo") {
2123
+ let newline = true;
2124
+ let escapes = false;
2125
+ while (/^-[neE]+$/.test(args[0] ?? "")) {
2126
+ const flags = args.shift() ?? "";
2127
+ if (flags.includes("n")) newline = false;
2128
+ if (flags.includes("e")) escapes = true;
2129
+ }
2130
+ const text2 = args.join(" ");
2131
+ return (escapes ? decodeAnsiC(text2) : text2) + (newline ? "\n" : "");
2132
+ }
2133
+ if (name === "printf" && args.length > 0) {
2134
+ const format = decodeAnsiC(args[0]);
2135
+ if (/%(?![s%])/.test(format)) return void 0;
2136
+ const values = args.slice(1);
2137
+ let output = "";
2138
+ let next = 0;
2139
+ do {
2140
+ output += format.replace(/%([s%])/g, (_match, directive) => directive === "%" ? "%" : values[next++] ?? "");
2141
+ } while (format.includes("%s") && next < values.length);
2142
+ return output;
2143
+ }
2144
+ return void 0;
2145
+ }
2146
+ function commandStdin(raw) {
2147
+ const heredoc = raw.heredocs.at(-1);
2148
+ if (heredoc) return heredoc.body;
2149
+ const input = raw.redirects.findLast(({ op }) => op === "<<<" || op === "<" || op === "0<");
2150
+ if (input) return input.op === "<<<" ? `${input.target}
2151
+ ` : SHELL_OPAQUE;
2152
+ if (raw.pipeFrom) return staticOutput(stripCommandPrefixes(raw.pipeFrom.words).argv, commandStdin(raw.pipeFrom)) ?? SHELL_OPAQUE;
2153
+ return void 0;
2154
+ }
2155
+ function assign(scope, assignments) {
2156
+ for (const assignment of assignments) {
2157
+ const separator = assignment.indexOf("=");
2158
+ scope.vars.set(assignment.slice(0, separator), assignment.slice(separator + 1));
2159
+ }
2160
+ }
2161
+ function emit(scope, raw) {
2162
+ const { argv, assignments } = stripCommandPrefixes(raw.words);
2163
+ if (argv.length === 0) {
2164
+ assign(scope, assignments);
2165
+ return;
2166
+ }
2167
+ const stdin = commandStdin(raw);
2168
+ const output = staticOutput(argv, stdin) ?? SHELL_OPAQUE;
2169
+ const stdinFile = raw.redirects.findLast(({ op }) => op === "<" || op === "0<");
2170
+ const name = argv[0].split("/").pop() ?? "";
2171
+ const flag = SHELLS.has(name) ? argv.findIndex((arg, index) => index > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(arg)) : -1;
2172
+ const script = flag > 0 ? argv[flag + 1] : SHELLS.has(name) && argv.length === 1 && stdin !== SHELL_OPAQUE ? stdin : name === "eval" ? argv.slice(1).join(" ") : void 0;
2173
+ const truncated = script !== void 0 && scope.depth >= MAX_DEPTH;
2174
+ scope.commands.push({
2175
+ argv,
2176
+ dir: scope.dir,
2177
+ stdin,
2178
+ afterAnd: raw.afterAnd,
2179
+ stdinFile: stdinFile ? resolveShellPath(scope.dir, stdinFile.target) : null,
2180
+ writes: raw.redirects.flatMap(({ op, target }) => /^(?:1?>|1?>\||1?>>|&>|&>>|>&)$/.test(op) && !/^(?:\d+|-)$/.test(target) ? [{ path: resolveShellPath(scope.dir, target), content: output, append: op.endsWith(">>") }] : []),
2181
+ wrapper: script !== void 0,
2182
+ truncated
2183
+ });
2184
+ if (name === "cd" || name === "pushd" || name === "popd") {
2185
+ scope.dir = name !== "popd" && argv[1] && argv[1] !== "-" ? resolveShellPath(scope.dir, argv[1]) : null;
2186
+ } else if (["export", "declare", "local", "readonly"].includes(name)) {
2187
+ assign(scope, argv.slice(1).filter((arg) => /^[A-Za-z_]\w*=/.test(arg)));
2188
+ }
2189
+ if (script && !truncated) parseUntil({ src: script, vars: name === "eval" ? scope.vars : /* @__PURE__ */ new Map(), dir: scope.dir, commands: scope.commands, depth: scope.depth + 1 }, 0, false);
2190
+ }
2191
+ function readHeredocBodies(scope, heredocs, start) {
2192
+ const { src } = scope;
2193
+ let position = start;
2194
+ for (const heredoc of heredocs) {
2195
+ const lines = [];
2196
+ while (position < src.length) {
2197
+ const end = indexOrEnd(src, "\n", position);
2198
+ const line = heredoc.strip ? src.slice(position, end).replace(/^\t+/, "") : src.slice(position, end);
2199
+ position = end + 1;
2200
+ if (line === heredoc.delimiter) break;
2201
+ lines.push(line);
2202
+ }
2203
+ heredoc.body = lines.length > 0 ? `${lines.join("\n")}
2204
+ ` : "";
2205
+ if (heredoc.expand) heredoc.body = readDoubleQuoted({ ...scope, src: heredoc.body }, 0, null).value;
2206
+ }
2207
+ return Math.min(position, src.length);
2208
+ }
2209
+ function readDoubleQuoted(scope, start, terminator) {
2210
+ const { src } = scope;
2211
+ let value = "";
2212
+ let i = start;
2213
+ while (i < src.length && src[i] !== terminator) {
2214
+ const c = src[i];
2215
+ if (c === "\\" && i + 1 < src.length) {
2216
+ const next = src[i + 1];
2217
+ if (next === "\n") i += 2;
2218
+ else if ("$`\\".includes(next) || next === terminator) {
2219
+ value += next;
2220
+ i += 2;
2221
+ } else {
2222
+ value += c;
2223
+ i++;
2224
+ }
2225
+ } else if (c === "$" || c === "`") {
2226
+ const expansion = readExpansion(scope, i, true);
2227
+ value += expansion.value;
2228
+ i = expansion.end;
2229
+ } else {
2230
+ value += c;
2231
+ i++;
2232
+ }
2233
+ }
2234
+ return { value, end: i };
2235
+ }
2236
+ function substitute(scope, src, start, closeParen) {
2237
+ const child = { src, vars: new Map(scope.vars), dir: scope.dir, commands: [], depth: scope.depth + 1 };
2238
+ const end = parseUntil(child, start, closeParen);
2239
+ scope.commands.push(...child.commands);
2240
+ const [only] = child.commands;
2241
+ const output = child.commands.length === 1 ? staticOutput(only.argv, only.stdin) : void 0;
2242
+ return { value: output?.replace(/\n+$/, "") ?? SHELL_OPAQUE, end };
2243
+ }
2244
+ function readExpansion(scope, i, inDouble) {
2245
+ const { src } = scope;
2246
+ if (src[i] === "`") {
2247
+ let inner = "";
2248
+ let j = i + 1;
2249
+ while (j < src.length && src[j] !== "`") {
2250
+ if (src[j] === "\\" && "$`\\".includes(src[j + 1] ?? "")) {
2251
+ inner += src[j + 1];
2252
+ j += 2;
2253
+ } else inner += src[j++];
2254
+ }
2255
+ return { value: substitute(scope, inner, 0, false).value, end: j + 1 };
2256
+ }
2257
+ const next = src[i + 1];
2258
+ if (next === "(") return substitute(scope, src, i + 2, true);
2259
+ if (next === "{") {
2260
+ const end = indexOrEnd(src, "}", i + 2);
2261
+ return { value: scope.vars.get(src.slice(i + 2, end)) ?? SHELL_OPAQUE, end: end + 1 };
2262
+ }
2263
+ if (next === "'" && !inDouble) {
2264
+ let j = i + 2;
2265
+ while (j < src.length && src[j] !== "'") j += src[j] === "\\" ? 2 : 1;
2266
+ return { value: decodeAnsiC(src.slice(i + 2, j)), end: j + 1, quoted: true };
2267
+ }
2268
+ if (next === '"' && !inDouble) {
2269
+ const { value, end } = readDoubleQuoted(scope, i + 2, '"');
2270
+ return { value, end: end + 1, quoted: true };
2271
+ }
2272
+ NAME.lastIndex = i + 1;
2273
+ const name = NAME.exec(src)?.[0];
2274
+ if (name) return { value: scope.vars.get(name) ?? SHELL_OPAQUE, end: i + 1 + name.length };
2275
+ if (next && /[0-9@*#?$!-]/.test(next)) return { value: SHELL_OPAQUE, end: i + 2 };
2276
+ return { value: "$", end: i + 1 };
2277
+ }
2278
+ function parseUntil(scope, start, closeParen) {
2279
+ const { src } = scope;
2280
+ let i = start;
2281
+ let line = [];
2282
+ let current = { words: [], redirects: [], heredocs: [], afterAnd: false };
2283
+ let pendingHeredocs = [];
2284
+ let word = null;
2285
+ let quoted = false;
2286
+ let redirect = null;
2287
+ let parens = 0;
2288
+ const append = (text2, isQuoted = false) => {
2289
+ word = (word ?? "") + text2;
2290
+ quoted ||= isQuoted;
2291
+ };
2292
+ const endWord = () => {
2293
+ if (word === null) return;
2294
+ if (redirect === "<<" || redirect === "<<-") {
2295
+ const heredoc = { strip: redirect === "<<-", delimiter: word, expand: !quoted, body: "" };
2296
+ current.heredocs.push(heredoc);
2297
+ pendingHeredocs.push(heredoc);
2298
+ } else if (redirect) {
2299
+ current.redirects.push({ op: redirect, target: word });
2300
+ } else {
2301
+ current.words.push(word);
2302
+ }
2303
+ word = null;
2304
+ quoted = false;
2305
+ redirect = null;
2306
+ };
2307
+ const endCommand = (op) => {
2308
+ endWord();
2309
+ const done = current;
2310
+ current = { words: [], redirects: [], heredocs: [], pipeFrom: op === "|" || op === "|&" ? done : void 0, afterAnd: op === "&&" };
2311
+ if (done.words.length > 0 || done.redirects.length > 0 || done.heredocs.length > 0) line.push(done);
2312
+ };
2313
+ const flush = () => {
2314
+ endCommand();
2315
+ for (const raw of line) emit(scope, raw);
2316
+ line = [];
2317
+ };
2318
+ while (i < src.length) {
2319
+ const c = src[i];
2320
+ if (c === "\\") {
2321
+ if (src[i + 1] !== "\n") append(src[i + 1] ?? "", true);
2322
+ i += 2;
2323
+ } else if (c === "'") {
2324
+ const end = indexOrEnd(src, "'", i + 1);
2325
+ append(src.slice(i + 1, end), true);
2326
+ i = end + 1;
2327
+ } else if (c === '"') {
2328
+ const { value, end } = readDoubleQuoted(scope, i + 1, '"');
2329
+ append(value, true);
2330
+ i = end + 1;
2331
+ } else if (c === "$" || c === "`") {
2332
+ const expansion = readExpansion(scope, i, false);
2333
+ append(expansion.value, expansion.quoted);
2334
+ i = expansion.end;
2335
+ } else if (c === "#" && word === null) {
2336
+ i = indexOrEnd(src, "\n", i);
2337
+ } else if (c === "\n") {
2338
+ endWord();
2339
+ i = readHeredocBodies(scope, pendingHeredocs, i + 1);
2340
+ pendingHeredocs = [];
2341
+ flush();
2342
+ } else if (c === " " || c === " " || c === "\r") {
2343
+ endWord();
2344
+ i++;
2345
+ } else if (c === ")" && parens === 0 && closeParen) {
2346
+ flush();
2347
+ return i + 1;
2348
+ } else {
2349
+ OPERATOR.lastIndex = i;
2350
+ const op = OPERATOR.exec(src)?.[0];
2351
+ if (!op) {
2352
+ append(c);
2353
+ i++;
2354
+ continue;
2355
+ }
2356
+ const fd = /[<>]/.test(op) && !quoted && /^\d+$/.test(word ?? "") ? word : null;
2357
+ if (fd !== null) word = null;
2358
+ endWord();
2359
+ i += op.length;
2360
+ if (/[<>]/.test(op)) redirect = `${fd ?? ""}${op}`;
2361
+ else {
2362
+ if (op === "(") parens++;
2363
+ if (op === ")") parens = Math.max(0, parens - 1);
2364
+ endCommand(op);
2365
+ }
2366
+ }
2367
+ }
2368
+ flush();
2369
+ return i;
2370
+ }
2371
+
2062
2372
  // ../shared/src/display-message/parsers/utils.ts
2063
2373
  var INTERRUPTED_MESSAGE_REGEX = /^\[Request interrupted by user.*\]$/;
2064
2374
  function userMessageImages(value) {
@@ -2204,61 +2514,11 @@ ${operation.diff}` : ""}`).join("\n\n");
2204
2514
  if (message.type === "interruption") return { kind: "error", title: "Agent stopped", summary: "", content: "" };
2205
2515
  return { kind: "error", title: "Agent error", summary: "", content: message.message };
2206
2516
  }
2207
- function unquoteShellArg(value) {
2208
- const trimmed = value.trim();
2209
- if (trimmed.length < 2) return trimmed;
2210
- if (trimmed[0] === "'" && trimmed[trimmed.length - 1] === "'") {
2211
- return trimmed.slice(1, -1).replace(/'\\''/g, "'");
2212
- }
2213
- if (trimmed[0] === '"' && trimmed[trimmed.length - 1] === '"') {
2214
- return trimmed.slice(1, -1).replace(/\\(["\\$`])/g, "$1");
2215
- }
2216
- return trimmed;
2217
- }
2218
- function shellPayload(command) {
2219
- const match = command.trim().match(/^(?:\S*\/)?(?:ba|z|c|fi)?sh\s+-(?:[a-zA-Z]*c[a-zA-Z]*|c)\s+([\s\S]+)$/);
2220
- return match ? unquoteShellArg(match[1]) : command.trim();
2221
- }
2222
- function splitShellWords(command) {
2223
- const words = [];
2224
- let word = "";
2225
- let quote = null;
2226
- let escaped = false;
2227
- for (const char of command) {
2228
- if (escaped) {
2229
- word += char;
2230
- escaped = false;
2231
- continue;
2232
- }
2233
- if (char === "\\" && quote !== "'") {
2234
- escaped = true;
2235
- continue;
2236
- }
2237
- if (quote) {
2238
- if (char === quote) quote = null;
2239
- else word += char;
2240
- continue;
2241
- }
2242
- if (char === '"' || char === "'") {
2243
- quote = char;
2244
- continue;
2245
- }
2246
- if (/\s/.test(char)) {
2247
- if (word) {
2248
- words.push(word);
2249
- word = "";
2250
- }
2251
- continue;
2252
- }
2253
- word += char;
2254
- }
2255
- if (word) words.push(word);
2256
- return words;
2257
- }
2258
2517
  function commandWords(command) {
2259
- const payload = shellPayload(command);
2260
- if (!payload || /[;|<>]|&&/.test(payload)) return null;
2261
- return splitShellWords(payload);
2518
+ const commands = parseShellScript(command, null).filter(({ wrapper }) => !wrapper);
2519
+ if (commands.length !== 1) return null;
2520
+ const [{ argv, stdin, stdinFile, writes }] = commands;
2521
+ return stdin === void 0 && !stdinFile && writes.length === 0 ? argv.map((word) => word.replaceAll(SHELL_OPAQUE, "\u2026")) : null;
2262
2522
  }
2263
2523
  function skillNamesFromCommand(command) {
2264
2524
  const words = commandWords(command);
@@ -6638,6 +6898,7 @@ function createProviderSlashCommand(provider, name, description, argumentHint) {
6638
6898
  providers: [provider]
6639
6899
  };
6640
6900
  }
6901
+ var SIDE_CHAT_COMMANDS = ["/btw", "/side"];
6641
6902
  var SLASH_COMMANDS = [
6642
6903
  {
6643
6904
  command: "/plan",
@@ -6666,7 +6927,13 @@ var SLASH_COMMANDS = [
6666
6927
  command: "/compact",
6667
6928
  description: "Compact the conversation context.",
6668
6929
  providers: ["codex", "muse"]
6669
- }
6930
+ },
6931
+ ...SIDE_CHAT_COMMANDS.map((command) => ({
6932
+ command,
6933
+ description: "Open a side chat about this chat without interrupting it.",
6934
+ argumentHint: "[question]",
6935
+ providers: [...VALID_AGENT_PROVIDERS]
6936
+ }))
6670
6937
  ];
6671
6938
  function mergeSlashCommands(...commandGroups) {
6672
6939
  const seen = /* @__PURE__ */ new Set();
@@ -7056,6 +7323,120 @@ var CLAUDE_AUTH_ENV_KEYS_BY_METHOD = {
7056
7323
  };
7057
7324
 
7058
7325
  // ../shared/src/routes/command-protection.ts
7326
+ import { z as z10 } from "zod";
7327
+
7328
+ // ../shared/src/git-invocations.ts
7329
+ var COMMIT_VALUE_OPTIONS = /* @__PURE__ */ new Set(["message", "file", "trailer", "reuse-message", "reedit-message", "fixup", "squash", "template", "author", "date", "cleanup", "pathspec-from-file"]);
7330
+ function findGitInvocations(commands) {
7331
+ return commands.flatMap((command) => {
7332
+ const { argv } = command;
7333
+ if (argv[0].split("/").pop() !== "git") return [];
7334
+ let dir = command.dir;
7335
+ let index = 1;
7336
+ for (; argv[index]?.startsWith("-"); index++) {
7337
+ if (argv[index] === "-C" && argv[index + 1]) dir = resolveShellPath(dir, argv[index + 1]);
7338
+ if (/^--(?:git-dir|work-tree)\b/.test(argv[index])) dir = null;
7339
+ if (["-C", "-c", "--git-dir", "--work-tree", "--namespace"].includes(argv[index])) index++;
7340
+ }
7341
+ return argv[index] ? [{ dir, subcommand: argv[index], args: argv.slice(index + 1), command }] : [];
7342
+ });
7343
+ }
7344
+ function parseCommitArgs(args) {
7345
+ const messages = [];
7346
+ const trailers = [];
7347
+ let file;
7348
+ let reuse = false;
7349
+ let amend = false;
7350
+ for (let index = 0; index < args.length && args[index] !== "--"; index++) {
7351
+ const arg = args[index];
7352
+ const long = /^--([\w-]+)(?:=([\s\S]*))?$/.exec(arg);
7353
+ if (long) {
7354
+ const [, name, inline] = long;
7355
+ if (name === "amend") amend = true;
7356
+ if (!COMMIT_VALUE_OPTIONS.has(name)) continue;
7357
+ const value = inline ?? args[++index] ?? "";
7358
+ if (name === "message") messages.push(value);
7359
+ else if (name === "file") file = value;
7360
+ else if (name === "trailer") trailers.push(value);
7361
+ else if (["reuse-message", "reedit-message", "fixup", "squash"].includes(name)) reuse = true;
7362
+ continue;
7363
+ }
7364
+ if (!/^-[^-]/.test(arg)) continue;
7365
+ for (let position = 1; position < arg.length && !"Su".includes(arg[position]); position++) {
7366
+ const flag = arg[position];
7367
+ if (!"mFCct".includes(flag)) continue;
7368
+ const value = arg.slice(position + 1) || (args[++index] ?? "");
7369
+ if (flag === "m") messages.push(value);
7370
+ else if (flag === "F") file = value;
7371
+ else if (flag !== "t") reuse = true;
7372
+ break;
7373
+ }
7374
+ }
7375
+ return { messages, trailers, file, reuse, amend };
7376
+ }
7377
+ function parsePushArgs(args) {
7378
+ const positionals = [];
7379
+ const options = [];
7380
+ let all = false;
7381
+ let tags = false;
7382
+ let repo = false;
7383
+ for (let index = 0; index < args.length; index++) {
7384
+ const arg = args[index];
7385
+ const long = /^--([\w-]+)(?:=([\s\S]*))?$/.exec(arg);
7386
+ if (arg === "--") {
7387
+ positionals.push(...args.slice(index + 1));
7388
+ break;
7389
+ } else if (long) {
7390
+ const [, name, inline] = long;
7391
+ all ||= ["all", "mirror", "branches"].includes(name);
7392
+ tags ||= name === "tags";
7393
+ repo ||= name === "repo";
7394
+ if (["repo", "push-option", "receive-pack", "exec"].includes(name)) {
7395
+ const value = inline ?? args[++index] ?? "";
7396
+ if (name === "push-option") options.push(value);
7397
+ }
7398
+ } else if (/^-[^-]/.test(arg)) {
7399
+ const option = arg.indexOf("o");
7400
+ if (option > 0) options.push(arg.slice(option + 1) || (args[++index] ?? ""));
7401
+ } else {
7402
+ positionals.push(arg);
7403
+ }
7404
+ }
7405
+ return { refspecs: repo ? positionals : positionals.slice(1), options, all, tags };
7406
+ }
7407
+ function findCheckoutTarget(args) {
7408
+ if (args.includes("--")) return void 0;
7409
+ const create = args.findIndex((arg) => /^(?:-[bBcC]|--orphan)$/.test(arg));
7410
+ if (create >= 0) return { branch: args[create + 1] ?? null, certain: true };
7411
+ if (args.some((arg) => arg === "-" || arg === "--detach" || arg === "-d")) return { branch: null, certain: true };
7412
+ const positional = args.find((arg) => !arg.startsWith("-"));
7413
+ return positional === void 0 ? void 0 : { branch: positional, certain: false };
7414
+ }
7415
+
7416
+ // ../shared/src/routes/command-protection.ts
7417
+ var commandProtectionRepoStateSchema = z10.object({
7418
+ branch: z10.string().nullable(),
7419
+ defaultBranch: z10.string().nullable(),
7420
+ pushBranch: z10.string().nullable(),
7421
+ pushConfig: z10.string().nullable(),
7422
+ headMessage: z10.string().nullable(),
7423
+ mergeInProgress: z10.boolean().optional()
7424
+ });
7425
+ var commandProtectionEvaluateRequestSchema = z10.object({
7426
+ provider: z10.enum(["claude", "codex", "cursor", "opencode", "pi"]),
7427
+ source: z10.enum(["claude_pre_tool_use", "codex_approval_request", "cursor_pre_tool_use", "opencode_pre_tool_use", "pi_tool_call"]),
7428
+ toolName: z10.string(),
7429
+ toolInput: z10.unknown(),
7430
+ command: z10.string().nullish(),
7431
+ cwd: z10.string().nullish(),
7432
+ toolUseId: z10.string().nullish(),
7433
+ // Read by the engine before the command runs, keyed by absolute path, so the
7434
+ // policy can see branches and commit messages the command text only references.
7435
+ gitContext: z10.object({
7436
+ repos: z10.record(z10.string(), commandProtectionRepoStateSchema),
7437
+ messageFiles: z10.record(z10.string(), z10.string())
7438
+ }).optional()
7439
+ });
7059
7440
  var COMMAND_PROTECTION_COMMAND_KEYS = ["command", "cmd", "script", "query", "endpoint", "path", "url", "mutation"];
7060
7441
  function stringifyCommandProtectionInput(value) {
7061
7442
  if (typeof value === "string") return value;
@@ -7086,41 +7467,152 @@ function extractCommandProtectionCommandText(request, options = {}) {
7086
7467
  if (typeof input === "string") return input;
7087
7468
  return options.stringifyFallback ? stringifyCommandProtectionInput(input) : null;
7088
7469
  }
7089
- function findPrMergeSignals(request) {
7090
- const command = normalizeCommandProtectionText(extractCommandProtectionCommandText(request, { stringifyFallback: true }) ?? "");
7091
- const input = normalizeCommandProtectionText(stringifyCommandProtectionInput(request.toolInput));
7092
- const combined = `${request.toolName.toLowerCase()} ${command} ${input}`;
7093
- const checks = [
7094
- ["gh-pr-merge", /\bgh\s+pr\s+merge\b/],
7095
- ["gh-api-pulls-merge", /\bgh\s+api\b[\s\S]*\/pulls\/(?:\d+|[^/\s]+)\/merge\b/],
7096
- ["github-rest-pulls-merge", /api\.github\.com\/repos\/[^/\s]+\/[^/\s]+\/pulls\/(?:\d+|[^/\s]+)\/merge\b/],
7097
- ["gitlab-rest-mr-merge", /\/projects\/[^/\s]+\/merge_requests\/(?:\d+|[^/\s]+)\/merge\b/],
7098
- ["gitlab-rest-mr-merge-query", /\/projects\/[^/\s]+\/merge_requests\/(?:\d+|[^/\s]+)\b[\s\S]*\bmerge_when_pipeline_succeeds\b/],
7099
- ["github-rest-ref-update", /\b(?:gh\s+api|curl|wget|python3?)\b[\s\S]*(?:\/repos\/|repos\/)[^/\s]+\/[^/\s]+\/git\/refs\/heads\/(?:main|master|trunk|develop)\b[\s\S]*\b(?:patch|put|sha|oid|force)\b/],
7100
- ["github-graphql-merge-pr", /\bmergepullrequest\b/],
7101
- ["github-graphql-enable-auto-merge", /\benablepullrequestautomerge\b/],
7102
- ["github-graphql-update-ref", /\bupdateref\b/],
7103
- ["git-merge-default-branch", /\bgit\s+(?:checkout|switch)\s+(?:main|master|trunk|develop)\b[\s\S]*\bgit\s+merge\b/],
7104
- ["git-merge-standalone", /\bgit\s+merge\s+(?:origin\/)?(main|master|trunk|develop)\b/],
7105
- ["git-push-main", /\bgit\s+push\b[\s\S]*\b(origin\s+)?(main|master|trunk|develop)\b/],
7106
- ["git-push-refspec-default-branch", /\bgit\s+push\b[\s\S]*\S+:(?:refs\/heads\/)?(main|master|trunk|develop)\b/],
7107
- ["git-cherry-pick-default-branch", /\bgit\s+(?:checkout|switch)\s+(?:main|master|trunk|develop)\b[\s\S]*\bgit\s+cherry-pick\b[\s\S]*\bgit\s+push\b/],
7108
- ["git-push-all", /\bgit\s+push\s+(-[^\s]+\s+)*(--all|--mirror)\b/],
7109
- ["git-push-bare", /\bgit\s+push\s*(?:["{}\[\]]|$)/],
7110
- ["hub-merge", /\bhub\s+merge\b/],
7111
- ["obfuscated-gh-pr-merge", /printf\s+['"]\\x67\\x68['"][\s\S]*\bpr\b[\s\S]*printf\s+['"]m\\x65rge['"]/],
7112
- ["mcp-merge-tool", /\bmcp__[^\s"]*merge[^\s"]*\b/],
7113
- ["tool-merge-name", /\b(pr|pull[_-]?request|mr|merge[_-]?request).{0,40}\bmerge\b|\bmerge.{0,40}(pr|pull[_-]?request|mr|merge[_-]?request)\b/],
7114
- ["merge-word", /(?:^|[^a-z0-9])merge(?:$|[^a-z0-9])/]
7115
- ];
7116
- return checks.flatMap(([name, pattern]) => pattern.test(combined) ? [name] : []);
7117
- }
7118
- function findGitCommitCommands(command) {
7119
- return [...command.matchAll(/\bgit(?:\s+-[^\s;&|]+(?:\s+(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^\s;&|]+))?)*\s+commit\b(?:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\\\r?\n|[^;&|\r\n])*)/g)].map((match) => match[0]);
7470
+ var PROTECTED_BRANCH = /^(?:main|master|trunk|develop)$/;
7471
+ var AUTO_MERGE_PUSH_OPTION = /merge_when_pipeline_succeeds|auto_merge/i;
7472
+ var CONFIGURED_AUTO_MERGE_PUSH_OPTION = /^push\.pushoption[ =].*(?:merge_when_pipeline_succeeds|auto_merge)/im;
7473
+ var MERGE_SIGNAL_CHECKS = [
7474
+ ["gh-pr-merge", /\bgh\s+pr\s+merge\b/],
7475
+ ["glab-mr-merge", /\bglab\s+mr\s+merge\b/],
7476
+ ["gh-api-pulls-merge", /\bgh\s+api\b[\s\S]*\/pulls\/(?:\d+|[^/\s]+)\/merge\b/],
7477
+ ["github-rest-pulls-merge", /api\.github\.com\/repos\/[^/\s]+\/[^/\s]+\/pulls\/(?:\d+|[^/\s]+)\/merge\b/],
7478
+ ["gitlab-rest-mr-merge", /\/projects\/[^/\s]+\/merge_requests\/(?:\d+|[^/\s]+)\/merge\b/],
7479
+ ["gitlab-rest-mr-merge-query", /\/projects\/[^/\s]+\/merge_requests\/(?:\d+|[^/\s]+)\b[\s\S]*\bmerge_when_pipeline_succeeds\b/],
7480
+ ["github-rest-ref-update", /\b(?:gh\s+api|curl|wget|python3?)\b[\s\S]*(?:\/repos\/|repos\/)[^/\s]+\/[^/\s]+\/git\/refs\/heads\/(?:main|master|trunk|develop)\b[\s\S]*\b(?:patch|put|sha|oid|force)\b/],
7481
+ ["github-graphql-merge-pr", /\bmergepullrequest\b/],
7482
+ ["github-graphql-enable-auto-merge", /\benablepullrequestautomerge\b/],
7483
+ ["github-graphql-update-ref", /\bupdateref\b/],
7484
+ ["hub-merge", /\bhub\s+merge\b/],
7485
+ ["obfuscated-gh-pr-merge", /printf\s+['"]?\\x67\\x68['"]?[\s\S]*\bpr\b[\s\S]*printf\s+['"]?m\\x65rge['"]?/],
7486
+ ["mcp-merge-tool", /\bmcp__[^\s"]*merge[^\s"]*\b/]
7487
+ ];
7488
+ var BROAD_MERGE_SIGNAL_CHECKS = [
7489
+ ["git-push-default-branch-text", /\bgit\s+push\b[^;&|\n]*?\s(?:\S+:)?(?:refs\/heads\/)?(?:main|master|trunk|develop)\b/],
7490
+ ["tool-merge-name", /\b(pr|pull[_-]?request|mr|merge[_-]?request).{0,40}\bmerge\b|\bmerge.{0,40}(pr|pull[_-]?request|mr|merge[_-]?request)\b/],
7491
+ ["merge-word", /(?:^|[^a-z0-9])merge(?:$|[^a-z0-9])/]
7492
+ ];
7493
+ function shellScript(input) {
7494
+ if (typeof input === "string") return input;
7495
+ if (!isRecord(input)) return null;
7496
+ for (const key of ["command", "cmd", "script"]) {
7497
+ const value = input[key];
7498
+ if (typeof value === "string") return value;
7499
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value.map(shellQuotePosix).join(" ");
7500
+ }
7501
+ return isRecord(input.args) ? shellScript(input.args) : null;
7502
+ }
7503
+ function workingDirectory({ toolInput, cwd }) {
7504
+ const input = isRecord(toolInput) ? toolInput : {};
7505
+ const dir = [input.workdir, input.cwd].find((value) => typeof value === "string" && value.trim() !== "");
7506
+ return dir ? resolveShellPath(cwd || null, dir) : cwd || null;
7507
+ }
7508
+ function parseCommandProtectionRequest(request) {
7509
+ const script = shellScript(request.toolInput);
7510
+ const dir = workingDirectory(request);
7511
+ const commands = script === null ? [] : parseShellScript(script, dir);
7512
+ return { request, script, workingDirectory: dir, commands, invocations: findGitInvocations(commands), truncated: commands.some(({ truncated }) => truncated) };
7513
+ }
7514
+ var isProtectedBranch = (branch, repo) => branch === repo?.defaultBranch || PROTECTED_BRANCH.test(branch);
7515
+ function trackCheckedOutBranches(commands, invocations, context) {
7516
+ const switches = /* @__PURE__ */ new Map();
7517
+ return invocations.map(({ dir, subcommand, args, command }) => {
7518
+ const repo = dir === null ? void 0 : context?.repos[dir];
7519
+ const index = commands.indexOf(command);
7520
+ const last = switches.get(dir);
7521
+ const mayStayOnBefore = last !== void 0 && !commands.slice(last.index + 1, index + 1).every(({ afterAnd }) => afterAnd);
7522
+ const branch = last === void 0 ? repo?.branch ?? null : mayStayOnBefore && (last.before === null || isProtectedBranch(last.before, repo)) ? null : last.branch;
7523
+ const target = subcommand === "checkout" || subcommand === "switch" ? findCheckoutTarget(args) : void 0;
7524
+ if (target) {
7525
+ const trusted = target.certain || isProtectedBranch(target.branch ?? "", repo) || branch !== null && !isProtectedBranch(branch, repo);
7526
+ switches.set(dir, { branch: trusted ? target.branch : null, before: branch, index });
7527
+ }
7528
+ return { branch, switched: last !== void 0 };
7529
+ });
7120
7530
  }
7121
- function findGitCommitSignals(request) {
7122
- const command = extractCommandProtectionCommandText(request, { stringifyFallback: true }) ?? "";
7123
- return findGitCommitCommands(command).length > 0 ? ["git-commit"] : [];
7531
+ function refspecDestination(refspec, current) {
7532
+ const spec = refspec.replace(/^\+/, "");
7533
+ const destination = spec.slice(spec.indexOf(":") + 1);
7534
+ if (destination === "" || destination.includes("*")) return "*";
7535
+ if (destination.includes(SHELL_OPAQUE)) return null;
7536
+ if (destination === "HEAD" || destination === "@") return current;
7537
+ return destination.startsWith("refs/tags/") ? void 0 : destination.replace(/^refs\/heads\//, "");
7538
+ }
7539
+ function findPushSignals({ commands, invocations, truncated }, context) {
7540
+ const branches = trackCheckedOutBranches(commands, invocations, context);
7541
+ const signals = invocations.flatMap(({ dir, subcommand, args, command }, index) => {
7542
+ if (subcommand === "config") {
7543
+ return args.some((arg) => /^push\.pushoption$/i.test(arg)) && args.some((arg) => AUTO_MERGE_PUSH_OPTION.test(arg)) ? ["git-push-auto-merge"] : [];
7544
+ }
7545
+ if (subcommand !== "push") return [];
7546
+ const repo = dir === null ? void 0 : context?.repos[dir];
7547
+ const { branch, switched } = branches[index];
7548
+ const { refspecs, options, all, tags } = parsePushArgs(args);
7549
+ const pushSignals = [];
7550
+ if (all) pushSignals.push("git-push-all");
7551
+ if (options.some((option) => AUTO_MERGE_PUSH_OPTION.test(option)) || CONFIGURED_AUTO_MERGE_PUSH_OPTION.test([repo?.pushConfig ?? "", ...command.argv].join("\n"))) {
7552
+ pushSignals.push("git-push-auto-merge");
7553
+ }
7554
+ const bareDestination = /^remote\..+\.push |^push\.default matching$/m.test(repo?.pushConfig ?? "") ? null : switched ? branch : repo?.pushBranch ?? branch;
7555
+ const destinations = refspecs.length > 0 ? refspecs.map((refspec) => refspecDestination(refspec, branch)) : all || tags ? [] : [bareDestination];
7556
+ for (const destination of destinations) {
7557
+ if (destination === "*") pushSignals.push("git-push-all");
7558
+ else if (destination === null) pushSignals.push("git-push-unknown-destination");
7559
+ else if (destination !== void 0 && isProtectedBranch(destination, repo)) pushSignals.push("git-push-default-branch");
7560
+ }
7561
+ return pushSignals;
7562
+ });
7563
+ return truncated ? [...signals, "git-push-unknown-destination"] : signals;
7564
+ }
7565
+ function isPrMergeCommand(argv) {
7566
+ const name = argv[0].split("/").pop();
7567
+ if (name !== "gh" && name !== "glab") return false;
7568
+ const args = argv.slice(1);
7569
+ if (args.includes("--help") || args.includes("-h")) return false;
7570
+ const words = args.filter((arg, index) => !arg.startsWith("-") && !/^(?:-R|--repo)$/.test(args[index - 1] ?? ""));
7571
+ if (words[0] === (name === "gh" ? "pr" : "mr") && words[1] === "merge") return true;
7572
+ const method = /(?:^|\s)(?:-X\s*|--method[\s=])(\w+)/i.exec(args.join(" "))?.[1];
7573
+ return words[0] === "api" && method?.toUpperCase() === "PUT" && words.some((word) => /\/(?:pulls|merge_requests)\/[^/]+\/merge$/.test(word));
7574
+ }
7575
+ var matchingChecks = (checks, text2) => checks.flatMap(([name, pattern]) => pattern.test(text2) ? [name] : []);
7576
+ function executedText(commands, keepWord = () => true) {
7577
+ return commands.filter(({ argv, wrapper, truncated }) => (!wrapper || truncated) && argv[0].split("/").pop() !== "git").map(({ argv, stdin }) => normalizeCommandProtectionText([...argv.filter(keepWord), stdin ?? ""].join(" ").replaceAll(SHELL_OPAQUE, " "))).join("\n");
7578
+ }
7579
+ function findShellMergeSignals(parsed, context) {
7580
+ const actions = parsed.commands.filter(({ argv }) => !["cd", "pushd"].includes(argv[0].split("/").pop() ?? ""));
7581
+ return [.../* @__PURE__ */ new Set([
7582
+ ...matchingChecks(MERGE_SIGNAL_CHECKS, executedText(parsed.commands)),
7583
+ ...matchingChecks(BROAD_MERGE_SIGNAL_CHECKS, executedText(actions, (word) => !word.includes("/"))),
7584
+ ...parsed.commands.some(({ argv }) => isPrMergeCommand(argv)) ? ["pr-merge-command"] : [],
7585
+ ...findPushSignals(parsed, context)
7586
+ ])];
7587
+ }
7588
+ function findToolMergeSignals({ toolName, toolInput }) {
7589
+ if (/^(?:read|write|edit|multi_?edit|patch|apply_?patch|glob|grep|ls|list|notebook_?edit)$/i.test(toolName)) return [];
7590
+ const checks = [...MERGE_SIGNAL_CHECKS, ...BROAD_MERGE_SIGNAL_CHECKS];
7591
+ return [.../* @__PURE__ */ new Set([...matchingChecks(checks, toolName.toLowerCase()), ...matchingChecks(checks, normalizeCommandProtectionText(stringifyCommandProtectionInput(toolInput)))])].sort((a, b) => checks.findIndex(([name]) => name === a) - checks.findIndex(([name]) => name === b));
7592
+ }
7593
+ var DEFINITE_MERGE_REASONS = {
7594
+ "git-push-default-branch": "The command pushes to the default branch.",
7595
+ "git-push-auto-merge": "The command enables auto-merge through a git push option.",
7596
+ "pr-merge-command": "The command merges a pull request or merge request."
7597
+ };
7598
+ function findPrMergeSignals(parsed, context) {
7599
+ const signals = parsed.script === null ? findToolMergeSignals(parsed.request) : findShellMergeSignals(parsed, context);
7600
+ return { signals, definiteReasons: signals.flatMap((signal) => DEFINITE_MERGE_REASONS[signal] ?? []) };
7601
+ }
7602
+ function findGitCommitSignals({ invocations, truncated }) {
7603
+ return truncated || invocations.some(({ subcommand }) => subcommand === "commit") ? ["git-commit"] : [];
7604
+ }
7605
+ function findCommandProtectionGitLookups({ invocations }) {
7606
+ const writes = invocations.filter(({ subcommand }) => subcommand === "commit" || subcommand === "push");
7607
+ const messageFiles = writes.flatMap(({ subcommand, args, dir, command }) => {
7608
+ const { file } = subcommand === "commit" ? parseCommitArgs(args) : { file: void 0 };
7609
+ const path = file === "-" ? command.stdinFile : file === void 0 ? null : resolveShellPath(dir, file);
7610
+ return path ? [path] : [];
7611
+ });
7612
+ return {
7613
+ repoDirs: [...new Set(writes.flatMap(({ dir }) => dir === null ? [] : [dir]))],
7614
+ messageFiles: [...new Set(messageFiles)]
7615
+ };
7124
7616
  }
7125
7617
  function shouldRefreshPullRequests(toolName, toolInput) {
7126
7618
  const name = toolName.toLowerCase();
@@ -7139,38 +7631,38 @@ function shouldRefreshPullRequests(toolName, toolInput) {
7139
7631
  }
7140
7632
 
7141
7633
  // ../shared/src/routes/linear.ts
7142
- import { z as z10 } from "zod";
7143
- var linearSessionMetadataSchema = z10.object({
7144
- via_mothership: z10.boolean().optional(),
7145
- issue_id: z10.string(),
7146
- issue_identifier: z10.string(),
7147
- issue_title: z10.string(),
7148
- issue_description: z10.string(),
7149
- issue_url: z10.string(),
7150
- comment_id: z10.string(),
7151
- comment_body: z10.string(),
7152
- triggered_by_id: z10.string().optional(),
7153
- triggered_by_name: z10.string().optional(),
7154
- triggered_by_email: z10.string().optional(),
7155
- linear_workspace_id: z10.string().optional(),
7156
- creator_id: z10.string().optional(),
7157
- creator_name: z10.string().optional(),
7158
- creator_email: z10.string().optional(),
7159
- assignee_id: z10.string().optional(),
7160
- assignee_name: z10.string().optional(),
7161
- assignee_email: z10.string().optional(),
7162
- issue_state: z10.string().optional(),
7163
- parent_issue: z10.object({
7164
- id: z10.string(),
7165
- identifier: z10.string(),
7166
- title: z10.string(),
7167
- description: z10.string().nullable()
7634
+ import { z as z11 } from "zod";
7635
+ var linearSessionMetadataSchema = z11.object({
7636
+ via_mothership: z11.boolean().optional(),
7637
+ issue_id: z11.string(),
7638
+ issue_identifier: z11.string(),
7639
+ issue_title: z11.string(),
7640
+ issue_description: z11.string(),
7641
+ issue_url: z11.string(),
7642
+ comment_id: z11.string(),
7643
+ comment_body: z11.string(),
7644
+ triggered_by_id: z11.string().optional(),
7645
+ triggered_by_name: z11.string().optional(),
7646
+ triggered_by_email: z11.string().optional(),
7647
+ linear_workspace_id: z11.string().optional(),
7648
+ creator_id: z11.string().optional(),
7649
+ creator_name: z11.string().optional(),
7650
+ creator_email: z11.string().optional(),
7651
+ assignee_id: z11.string().optional(),
7652
+ assignee_name: z11.string().optional(),
7653
+ assignee_email: z11.string().optional(),
7654
+ issue_state: z11.string().optional(),
7655
+ parent_issue: z11.object({
7656
+ id: z11.string(),
7657
+ identifier: z11.string(),
7658
+ title: z11.string(),
7659
+ description: z11.string().nullable()
7168
7660
  }).optional(),
7169
- workspace: z10.object({
7170
- id: z10.string(),
7171
- coding_agent: z10.custom((value) => typeof value === "string" && isValidAgentProvider(value)),
7172
- task_description: z10.string(),
7173
- created_at: z10.string()
7661
+ workspace: z11.object({
7662
+ id: z11.string(),
7663
+ coding_agent: z11.custom((value) => typeof value === "string" && isValidAgentProvider(value)),
7664
+ task_description: z11.string(),
7665
+ created_at: z11.string()
7174
7666
  }).optional()
7175
7667
  });
7176
7668
 
@@ -7505,46 +7997,46 @@ var DEFAULT_WORKSPACE_FILTERS = {
7505
7997
  var ONE_DAY_MS = 24 * 60 * 60 * 1e3;
7506
7998
 
7507
7999
  // ../shared/src/routes/workspace-events.ts
7508
- import { z as z11 } from "zod";
7509
- var workspaceChangedEventSchema = z11.discriminatedUnion("type", [
7510
- z11.object({
7511
- type: z11.literal("workspace.changed"),
7512
- workspaceId: z11.string(),
7513
- completion: z11.object({
7514
- workspaceName: z11.string(),
7515
- completedAt: z11.string(),
7516
- processing: z11.boolean().optional()
8000
+ import { z as z12 } from "zod";
8001
+ var workspaceChangedEventSchema = z12.discriminatedUnion("type", [
8002
+ z12.object({
8003
+ type: z12.literal("workspace.changed"),
8004
+ workspaceId: z12.string(),
8005
+ completion: z12.object({
8006
+ workspaceName: z12.string(),
8007
+ completedAt: z12.string(),
8008
+ processing: z12.boolean().optional()
7517
8009
  }).optional(),
7518
- ts: z11.string()
8010
+ ts: z12.string()
7519
8011
  }),
7520
- z11.object({
7521
- type: z11.literal("workspace.chat.changed"),
7522
- workspaceId: z11.string(),
7523
- chatId: z11.string(),
7524
- ts: z11.string()
8012
+ z12.object({
8013
+ type: z12.literal("workspace.chat.changed"),
8014
+ workspaceId: z12.string(),
8015
+ chatId: z12.string(),
8016
+ ts: z12.string()
7525
8017
  }),
7526
- z11.object({ type: z11.literal("presence.changed"), ts: z11.string() }),
7527
- z11.object({
7528
- type: z11.literal("mobile-testing.changed"),
7529
- workspaceId: z11.string(),
7530
- ts: z11.string()
8018
+ z12.object({ type: z12.literal("presence.changed"), ts: z12.string() }),
8019
+ z12.object({
8020
+ type: z12.literal("mobile-testing.changed"),
8021
+ workspaceId: z12.string(),
8022
+ ts: z12.string()
7531
8023
  })
7532
8024
  ]);
7533
8025
 
7534
8026
  // ../shared/src/routes/presence.ts
7535
- import { z as z12 } from "zod";
7536
- var presenceStatusSchema = z12.enum(["online", "typing"]);
7537
- var presenceLocationSchema = z12.object({
7538
- environmentId: z12.string().optional(),
7539
- workspaceId: z12.string().optional()
8027
+ import { z as z13 } from "zod";
8028
+ var presenceStatusSchema = z13.enum(["online", "typing"]);
8029
+ var presenceLocationSchema = z13.object({
8030
+ environmentId: z13.string().optional(),
8031
+ workspaceId: z13.string().optional()
7540
8032
  });
7541
- var presenceEntrySchema = z12.object({
7542
- userId: z12.string(),
8033
+ var presenceEntrySchema = z13.object({
8034
+ userId: z13.string(),
7543
8035
  status: presenceStatusSchema,
7544
8036
  location: presenceLocationSchema,
7545
- ts: z12.string()
8037
+ ts: z13.string()
7546
8038
  });
7547
- var updatePresenceRequestSchema = z12.object({
8039
+ var updatePresenceRequestSchema = z13.object({
7548
8040
  status: presenceStatusSchema,
7549
8041
  location: presenceLocationSchema.optional()
7550
8042
  });
@@ -7634,14 +8126,15 @@ function formatChatForkHandoffMessage(handoff) {
7634
8126
  const sourceName = getProviderDisplayName(handoff.source.provider, "long");
7635
8127
  const reason = describeChatForkReason(handoff.reason, handoff.source.provider);
7636
8128
  const why = handoff.trigger === "auto" ? `until ${reason ?? "it stopped"}, so Replicas moved the conversation to you automatically` : "until the user forked it to you";
8129
+ const side = handoff.trigger === "side";
7637
8130
  const body = [
7638
- handoff.subagent ? "# Delegated task context" : `# Continuing a ${sourceName} chat`,
8131
+ side ? "# Side chat" : handoff.subagent ? "# Delegated task context" : `# Continuing a ${sourceName} chat`,
7639
8132
  "",
7640
- handoff.subagent ? `You are a subagent of the chat "${handoff.source.title}" in this same workspace. The inherited transcript is background for your assigned task below. Follow that task and report your result to the parent; do not take over the parent's entire request. Workspace files and git state are shared and authoritative.` : `You are picking up the chat "${handoff.source.title}" in this same workspace. It was running on ${sourceName} ${why}. Everything the previous agent changed is already on disk: the workspace files and git state are authoritative.`,
8133
+ side ? `You are a side chat the user opened next to the main chat "${handoff.source.title}" (${sourceName}) in this same workspace, to talk about it without interrupting it. The main chat may still be working, and nothing you say reaches it or its agent. Answer from its transcript and the workspace. The recent turns below are a snapshot from when you were opened and the main chat has likely moved on, so re-read the transcript file before answering anything about what it is doing or has done. Its agent works in the same files, so don't edit files, change git state, or start or stop processes unless the user explicitly asks you to.` : handoff.subagent ? `You are a subagent of the chat "${handoff.source.title}" in this same workspace. The inherited transcript is background for your assigned task below. Follow that task and report your result to the parent; do not take over the parent's entire request. Workspace files and git state are shared and authoritative.` : `You are picking up the chat "${handoff.source.title}" in this same workspace. It was running on ${sourceName} ${why}. Everything the previous agent changed is already on disk: the workspace files and git state are authoritative.`,
7641
8134
  "",
7642
8135
  "## Transcript",
7643
8136
  "",
7644
- `- Sanitized transcript: \`${handoff.transcriptPath}\` (read or grep it for anything not in the excerpt below)`,
8137
+ side ? `- Main chat transcript: \`${handoff.transcriptPath}\` (Replicas refreshes it with the main chat's latest turns before each of your turns; re-read it whenever you need the main chat's current state)` : `- Sanitized transcript: \`${handoff.transcriptPath}\` (read or grep it for anything not in the excerpt below)`,
7645
8138
  ...handoff.rawHistoryPath ? [`- Raw event log: \`${handoff.rawHistoryPath}\``] : [],
7646
8139
  ...handoff.sourceTruncated ? [`- The chat was too large to sanitize in full; the sanitized file holds only its most recent part.${handoff.rawHistoryPath ? " Grep the raw event log for anything older." : ""}`] : [],
7647
8140
  "",
@@ -7650,7 +8143,7 @@ function formatChatForkHandoffMessage(handoff) {
7650
8143
  ...handoff.excerptTruncated ? [CHAT_FORK_EXCERPT_OMITTED_NOTICE, ""] : [],
7651
8144
  handoff.excerpt.trim() || "_The source chat had no messages yet._"
7652
8145
  ].join("\n");
7653
- const instruction = handoff.message?.trim() || (handoff.resumeRequest ? `The previous agent was interrupted before it finished this request from the user. Continue it now:
8146
+ const instruction = handoff.message?.trim() || (side ? "Say in one sentence that you are ready for questions about the main chat." : handoff.resumeRequest ? `The previous agent was interrupted before it finished this request from the user. Continue it now:
7654
8147
 
7655
8148
  ${handoff.resumeRequest.trim().replace(/^/gm, "> ")}` : "Review the recent turns and the current workspace state, then continue where the previous agent left off. If nothing is pending, confirm in a sentence or two what you know and wait for the next request.");
7656
8149
  return `${OPEN_MARKER}${JSON.stringify(meta)}${OPEN_MARKER_END}
@@ -7659,6 +8152,18 @@ ${CLOSE_MARKER}
7659
8152
 
7660
8153
  ${instruction}`;
7661
8154
  }
8155
+ function formatSideChatUpdateMessage(source, turns, message) {
8156
+ const meta = { sourceProvider: source.provider, sourceTitle: source.title, trigger: "side" };
8157
+ return `${OPEN_MARKER}${JSON.stringify(meta)}${OPEN_MARKER_END}
8158
+ # Main chat update
8159
+
8160
+ The main chat "${source.title}" has new turns since your last reply:
8161
+
8162
+ ${turns}
8163
+ ${CLOSE_MARKER}
8164
+
8165
+ ${message}`;
8166
+ }
7662
8167
 
7663
8168
  // ../shared/src/onboarding-emails.ts
7664
8169
  var EMAIL_KEYS = [
@@ -7875,7 +8380,7 @@ function isSkillRegistryManifest(value) {
7875
8380
  }
7876
8381
 
7877
8382
  // ../shared/src/routes/environment-setups.ts
7878
- import { z as z13 } from "zod";
8383
+ import { z as z14 } from "zod";
7879
8384
  var ENVIRONMENT_SETUP_STEPS = [
7880
8385
  { key: "understand", label: "Understand the codebase" },
7881
8386
  { key: "install", label: "Install dependencies and run the app" },
@@ -7909,27 +8414,27 @@ var ENVIRONMENT_SETUP_LIMITS = {
7909
8414
  };
7910
8415
  var ENVIRONMENT_SETUP_VARIABLE_WAIT = { defaultMs: 5 * 6e4, maxMs: 15 * 6e4, pollMs: 5e3 };
7911
8416
  var VARIABLE_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
7912
- var text = (max) => max === void 0 ? z13.string().trim() : z13.string().trim().max(max);
8417
+ var text = (max) => max === void 0 ? z14.string().trim() : z14.string().trim().max(max);
7913
8418
  var requiredText = (max) => text(max).min(1, "must not be empty");
7914
8419
  var optionalText = (max) => text(max).nullish().transform((value) => value || null);
7915
8420
  var clearableText = (max) => text(max).nullish().transform((value) => value === void 0 ? void 0 : value || null);
7916
- var list = (item, max) => max === void 0 ? z13.array(item) : z13.array(item).max(max);
8421
+ var list = (item, max) => max === void 0 ? z14.array(item) : z14.array(item).max(max);
7917
8422
  var ENVIRONMENT_SETUP_AUTHORED_TRIGGER_TYPES = ["cron", "github", "gitlab"];
7918
8423
  function isEnvironmentSetupAuthoredTriggerType(type) {
7919
8424
  return ENVIRONMENT_SETUP_AUTHORED_TRIGGER_TYPES.some((authored) => authored === type);
7920
8425
  }
7921
- var repositoryTriggerConfigSchema = z13.object({
7922
- event: z13.string(),
7923
- repository_ids: z13.array(z13.string().regex(UUID_RE, "must be a repository id")).optional(),
7924
- group_pr_events: z13.boolean().optional(),
7925
- excluded_actors: z13.array(z13.string()).optional()
8426
+ var repositoryTriggerConfigSchema = z14.object({
8427
+ event: z14.string(),
8428
+ repository_ids: z14.array(z14.string().regex(UUID_RE, "must be a repository id")).optional(),
8429
+ group_pr_events: z14.boolean().optional(),
8430
+ excluded_actors: z14.array(z14.string()).optional()
7926
8431
  });
7927
- var proposalTriggerSchema = z13.discriminatedUnion("type", [
7928
- z13.object({ type: z13.literal("cron"), config: z13.object({ schedule: z13.string(), timezone: z13.string().optional() }) }),
7929
- z13.object({ type: z13.literal("github"), config: repositoryTriggerConfigSchema }),
7930
- z13.object({ type: z13.literal("gitlab"), config: repositoryTriggerConfigSchema })
8432
+ var proposalTriggerSchema = z14.discriminatedUnion("type", [
8433
+ z14.object({ type: z14.literal("cron"), config: z14.object({ schedule: z14.string(), timezone: z14.string().optional() }) }),
8434
+ z14.object({ type: z14.literal("github"), config: repositoryTriggerConfigSchema }),
8435
+ z14.object({ type: z14.literal("gitlab"), config: repositoryTriggerConfigSchema })
7931
8436
  ]);
7932
- var existingTriggerSchema = z13.custom(
8437
+ var existingTriggerSchema = z14.custom(
7933
8438
  (value) => isRecord(value) && typeof value.type === "string" && isRecord(value.config),
7934
8439
  "must be an automation trigger"
7935
8440
  );
@@ -7937,17 +8442,17 @@ var carriedTriggerSchema = existingTriggerSchema.refine(
7937
8442
  (trigger) => !isEnvironmentSetupAuthoredTriggerType(trigger.type)
7938
8443
  );
7939
8444
  function automationSchema(limits) {
7940
- const authored = z13.object({
8445
+ const authored = z14.object({
7941
8446
  name: text(limits.nameChars),
7942
8447
  description: text(limits.descriptionChars),
7943
8448
  prompt: text(limits.automationPromptChars),
7944
8449
  triggers: list(proposalTriggerSchema, limits.automationTriggers)
7945
8450
  });
7946
- const updated = authored.extend({ triggers: list(z13.union([proposalTriggerSchema, carriedTriggerSchema]), limits.automationTriggers) });
7947
- return z13.object({
8451
+ const updated = authored.extend({ triggers: list(z14.union([proposalTriggerSchema, carriedTriggerSchema]), limits.automationTriggers) });
8452
+ return z14.object({
7948
8453
  key: requiredText(limits.automationKeyChars),
7949
- action: z13.enum(ENVIRONMENT_SETUP_AUTOMATION_ACTIONS).default("create"),
7950
- automation_id: z13.string().regex(UUID_RE, "must be an automation id").nullable().default(null),
8454
+ action: z14.enum(ENVIRONMENT_SETUP_AUTOMATION_ACTIONS).default("create"),
8455
+ automation_id: z14.string().regex(UUID_RE, "must be an automation id").nullable().default(null),
7951
8456
  name: text().default(""),
7952
8457
  description: optionalText().transform((value) => value ?? ""),
7953
8458
  prompt: text().default(""),
@@ -7970,7 +8475,7 @@ function automationSchema(limits) {
7970
8475
  const content = (automation.action === "update" ? updated : authored).safeParse(automation);
7971
8476
  if (content.success) return { ...automation, ...content.data };
7972
8477
  for (const issue of content.error.issues) ctx.addIssue({ ...issue, code: "custom" });
7973
- return z13.NEVER;
8478
+ return z14.NEVER;
7974
8479
  });
7975
8480
  }
7976
8481
  function automationListSchema(limits) {
@@ -7988,7 +8493,7 @@ function automationListSchema(limits) {
7988
8493
  });
7989
8494
  }
7990
8495
  function environmentSchema(limits) {
7991
- return z13.object({
8496
+ return z14.object({
7992
8497
  name: optionalText(limits.nameChars).transform((value) => value ?? void 0),
7993
8498
  description: clearableText(limits.descriptionChars),
7994
8499
  system_prompt: clearableText(limits.systemPromptChars),
@@ -7997,26 +8502,26 @@ function environmentSchema(limits) {
7997
8502
  });
7998
8503
  }
7999
8504
  function variableSchema(limits, requiredDefault) {
8000
- return z13.object({
8001
- key: z13.string().regex(VARIABLE_KEY_RE, "must be a valid environment variable name").max(limits.variableKeyChars ?? Number.POSITIVE_INFINITY),
8505
+ return z14.object({
8506
+ key: z14.string().regex(VARIABLE_KEY_RE, "must be a valid environment variable name").max(limits.variableKeyChars ?? Number.POSITIVE_INFINITY),
8002
8507
  description: optionalText(limits.variableDescriptionChars).transform((value) => value ?? ""),
8003
- required: z13.boolean().default(requiredDefault)
8508
+ required: z14.boolean().default(requiredDefault)
8004
8509
  });
8005
8510
  }
8006
8511
  function proposalSchema(limits) {
8007
- return z13.object({
8512
+ return z14.object({
8008
8513
  summary: requiredText(limits.summaryChars),
8009
8514
  stack: list(text(), limits.stackItems).default([]).transform((items) => items.filter(Boolean)),
8010
8515
  environment: environmentSchema(limits),
8011
8516
  variables: list(variableSchema(limits, false), limits.variables).default([]),
8012
8517
  automations: automationListSchema(limits),
8013
- verification: list(z13.object({
8518
+ verification: list(z14.object({
8014
8519
  label: requiredText(limits.nameChars),
8015
- status: z13.enum(ENVIRONMENT_SETUP_VERIFICATION_STATUSES),
8520
+ status: z14.enum(ENVIRONMENT_SETUP_VERIFICATION_STATUSES),
8016
8521
  detail: optionalText(limits.verificationDetailChars).transform((value) => value ?? void 0)
8017
8522
  }), limits.verificationItems).default([]),
8018
- media: list(z13.object({
8019
- media_id: z13.string().regex(UUID_RE, "must be a media id"),
8523
+ media: list(z14.object({
8524
+ media_id: z14.string().regex(UUID_RE, "must be a media id"),
8020
8525
  title: requiredText(limits.nameChars)
8021
8526
  }), limits.mediaItems).default([])
8022
8527
  });
@@ -8024,35 +8529,35 @@ function proposalSchema(limits) {
8024
8529
  var environmentSetupProposalSchema = proposalSchema({});
8025
8530
  var environmentSetupProposalSubmissionSchema = proposalSchema(ENVIRONMENT_SETUP_LIMITS);
8026
8531
  var environmentSetupVariableRequestSchema = variableSchema({}, false).extend({
8027
- status: z13.enum(["pending", "provided", "skipped"]),
8028
- requested_at: z13.string(),
8029
- resolved_at: z13.string().nullable().default(null)
8532
+ status: z14.enum(["pending", "provided", "skipped"]),
8533
+ requested_at: z14.string(),
8534
+ resolved_at: z14.string().nullable().default(null)
8030
8535
  });
8031
- var environmentSetupRunStateSchema = z13.object({
8032
- status: z13.enum(ENVIRONMENT_SETUP_RUN_STATUSES),
8033
- steps: z13.partialRecord(z13.enum(ENVIRONMENT_SETUP_STEPS.map((step) => step.key)), z13.enum(ENVIRONMENT_SETUP_STEP_STATUSES)).default({}),
8536
+ var environmentSetupRunStateSchema = z14.object({
8537
+ status: z14.enum(ENVIRONMENT_SETUP_RUN_STATUSES),
8538
+ steps: z14.partialRecord(z14.enum(ENVIRONMENT_SETUP_STEPS.map((step) => step.key)), z14.enum(ENVIRONMENT_SETUP_STEP_STATUSES)).default({}),
8034
8539
  proposal: environmentSetupProposalSchema.nullable().default(null),
8035
- applied: z13.object({
8036
- applied_at: z13.string(),
8037
- automation_ids: z13.array(z13.string())
8540
+ applied: z14.object({
8541
+ applied_at: z14.string(),
8542
+ automation_ids: z14.array(z14.string())
8038
8543
  }).nullable().default(null),
8039
- variable_requests: z13.array(environmentSetupVariableRequestSchema).default([])
8544
+ variable_requests: z14.array(environmentSetupVariableRequestSchema).default([])
8040
8545
  });
8041
- var applyEnvironmentSetupRequestSchema = z13.object({
8546
+ var applyEnvironmentSetupRequestSchema = z14.object({
8042
8547
  environment: environmentSchema(ENVIRONMENT_SETUP_LIMITS).extend({ name: requiredText(ENVIRONMENT_SETUP_LIMITS.nameChars) }),
8043
- variables: list(z13.object({ key: z13.string().regex(VARIABLE_KEY_RE), value: z13.string() }), ENVIRONMENT_SETUP_LIMITS.variables).default([]).refine((variables) => new Set(variables.map((variable) => variable.key)).size === variables.length, "must have unique keys").transform((variables) => variables.filter((variable) => variable.value.length > 0)),
8548
+ variables: list(z14.object({ key: z14.string().regex(VARIABLE_KEY_RE), value: z14.string() }), ENVIRONMENT_SETUP_LIMITS.variables).default([]).refine((variables) => new Set(variables.map((variable) => variable.key)).size === variables.length, "must have unique keys").transform((variables) => variables.filter((variable) => variable.value.length > 0)),
8044
8549
  automations: automationListSchema(ENVIRONMENT_SETUP_LIMITS)
8045
8550
  });
8046
- var requestEnvironmentSetupVariablesSchema = z13.object({
8551
+ var requestEnvironmentSetupVariablesSchema = z14.object({
8047
8552
  variables: list(variableSchema(ENVIRONMENT_SETUP_LIMITS, true), ENVIRONMENT_SETUP_LIMITS.variables).min(1, "must not be empty")
8048
8553
  }).superRefine(({ variables }, ctx) => {
8049
8554
  if (new Set(variables.map((variable) => variable.key)).size !== variables.length) {
8050
8555
  ctx.addIssue({ code: "custom", path: ["variables"], message: "must have unique keys" });
8051
8556
  }
8052
8557
  });
8053
- var respondEnvironmentSetupVariablesSchema = z13.object({
8054
- values: z13.record(z13.string().regex(VARIABLE_KEY_RE), z13.string()).default({}),
8055
- skipped: z13.array(z13.string().regex(VARIABLE_KEY_RE)).default([])
8558
+ var respondEnvironmentSetupVariablesSchema = z14.object({
8559
+ values: z14.record(z14.string().regex(VARIABLE_KEY_RE), z14.string()).default({}),
8560
+ skipped: z14.array(z14.string().regex(VARIABLE_KEY_RE)).default([])
8056
8561
  });
8057
8562
 
8058
8563
  export {
@@ -8275,13 +8780,17 @@ export {
8275
8780
  claudeAuthEnvFromResponse,
8276
8781
  CLAUDE_AUTH_ENV_KEYS_BY_METHOD,
8277
8782
  extractCommandProtectionCommandText,
8783
+ parseCommandProtectionRequest,
8278
8784
  findPrMergeSignals,
8279
8785
  findGitCommitSignals,
8786
+ findCommandProtectionGitLookups,
8280
8787
  shouldRefreshPullRequests,
8281
8788
  MAX_REPO_FILE_CONTENT_BYTES,
8282
8789
  searchRepoFileIndex,
8283
8790
  isExcludedRepoFilePath,
8791
+ CHAT_FORK_EXCERPT_OMITTED_NOTICE,
8284
8792
  formatChatForkHandoffMessage,
8793
+ formatSideChatUpdateMessage,
8285
8794
  readJsonlPage,
8286
8795
  parseChatTranscriptArtifact,
8287
8796
  readSseStream,