opencode-apex 0.2.3 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,664 @@
1
+ /**
2
+ * Contexto de procesos para el advisor — de quién es cada PID que se quiere matar.
3
+ *
4
+ * POR QUÉ EXISTE. El advisor solo veía el texto del comando. Ante `kill 705875`
5
+ * no tenía forma de saber si ese PID era el servidor de pruebas que el propio
6
+ * agente arrancó un minuto antes o el navegador del usuario, y con una regla del
7
+ * tipo «deniega matar procesos ajenos» la única respuesta prudente era denegar.
8
+ * Medido en las sesiones advisor: 7 de 7 `kill <PID>` denegados, mientras los
9
+ * `pkill -f "n8n start"` — donde el nombre sí se ve — pasaban.
10
+ *
11
+ * QUÉ SE AVERIGUA, por cada proceso objetivo, leyendo `/proc` (solo Linux):
12
+ * - dueño (uid → usuario) y si es el mismo usuario que corre opencode;
13
+ * - comando completo;
14
+ * - quién lo lanzó: el tool `shell` de opencode exporta `OPENCODE_SESSION_ID`
15
+ * a cada hijo, así que `/proc/<pid>/environ` dice qué sesión lo creó. Se lee
16
+ * también el de los ancestros, porque un `setsid nohup bash -c …` deja el
17
+ * proceso final colgando de init pero heredando el entorno;
18
+ * - si es CRÍTICO: el propio servidor opencode, uno de sus ancestros (la
19
+ * terminal que lo sostiene) o el PID 1. Matar cualquiera de ellos corta la
20
+ * sesión que está pidiendo el permiso.
21
+ *
22
+ * Lo que NO hace: decidir. Solo describe; la decisión sigue siendo del advisor.
23
+ * Y nunca lanza: un `/proc` ilegible (otro usuario, proceso ya muerto, macOS)
24
+ * acaba en «desconocido», no en un fallo del hook de permisos.
25
+ *
26
+ * Fichero sin Effect ni dependencias del host, como `guard.ts`, para probarlo con
27
+ * un `/proc` falso.
28
+ */
29
+
30
+ import { readFileSync, readdirSync } from "node:fs"
31
+ import { userInfo } from "node:os"
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Objetivos: qué procesos nombra un comando
35
+ // ---------------------------------------------------------------------------
36
+
37
+ /** Un objetivo extraído de un comando de shell. */
38
+ export type KillTarget =
39
+ | { readonly kind: "pid"; readonly pid: number }
40
+ /** PID negativo o `0`: un grupo de procesos entero (`kill -- -1234`, `kill 0`). */
41
+ | { readonly kind: "group"; readonly pgid: number }
42
+ /** `kill -1`: todos los procesos del usuario. */
43
+ | { readonly kind: "all" }
44
+ /** `pkill -f patrón`, `pkill nombre`, `killall nombre`, `kill $(pgrep …)`. */
45
+ | { readonly kind: "pattern"; readonly pattern: string; readonly full: boolean; readonly exact: boolean; readonly via: string }
46
+
47
+ /** Opciones de pkill/pgrep que llevan valor y por tanto consumen el siguiente token. */
48
+ const PGREP_VALUE_OPTS = new Set([
49
+ "-s", "--signal", "-u", "--euid", "-U", "--uid", "-g", "--pgroup", "-G", "--group",
50
+ "-P", "--parent", "-t", "--terminal", "--session", "--ns", "--nslist", "-d", "--delimiter",
51
+ "-F", "--pidfile", "--cgroup", "--env",
52
+ ])
53
+
54
+ /** Opciones de killall que llevan valor. */
55
+ const KILLALL_VALUE_OPTS = new Set(["-s", "--signal", "-u", "--user", "-o", "--older-than", "-y", "--younger-than", "-n", "--ns", "-Z", "--context"])
56
+
57
+ /**
58
+ * Trocea una línea de comando en palabras, respetando comillas simples y dobles.
59
+ * No pretende ser un parser de shell: basta para separar `pkill -f "n8n start"`
60
+ * en tres palabras y para no partir un `$(pgrep -f "x y")`.
61
+ */
62
+ export function tokenize(command: string): string[] {
63
+ const out: string[] = []
64
+ let current = ""
65
+ let quote: "'" | '"' | null = null
66
+ let depth = 0 // dentro de $( … )
67
+ let has = false
68
+ for (let i = 0; i < command.length; i++) {
69
+ const ch = command[i]!
70
+ if (quote) {
71
+ if (ch === quote) quote = null
72
+ else current += ch
73
+ continue
74
+ }
75
+ if (depth > 0) {
76
+ current += ch
77
+ if (ch === "(") depth++
78
+ else if (ch === ")") depth--
79
+ continue
80
+ }
81
+ if (ch === "`") {
82
+ // `…` es una sustitución como $( … ): se conserva entera, con las comillas.
83
+ const end = command.indexOf("`", i + 1)
84
+ const stop = end === -1 ? command.length : end + 1
85
+ current += command.slice(i, stop)
86
+ i = stop - 1
87
+ has = true
88
+ continue
89
+ }
90
+ if (ch === "$" && command[i + 1] === "(") {
91
+ current += "$("
92
+ i++
93
+ depth = 1
94
+ has = true
95
+ continue
96
+ }
97
+ if (ch === "'" || ch === '"') {
98
+ quote = ch
99
+ has = true
100
+ continue
101
+ }
102
+ if (ch === "\\" && i + 1 < command.length) {
103
+ current += command[++i]
104
+ has = true
105
+ continue
106
+ }
107
+ if (/\s/.test(ch)) {
108
+ if (has) out.push(current)
109
+ current = ""
110
+ has = false
111
+ continue
112
+ }
113
+ current += ch
114
+ has = true
115
+ }
116
+ if (has) out.push(current)
117
+ return out
118
+ }
119
+
120
+ /**
121
+ * Divide una línea en los comandos simples que la componen (`;`, `&&`, `||`, `|`, `&`).
122
+ * El host ya entrega cada comando por separado como recurso, pero un `bash -c "…"`
123
+ * o un `$(…)` llega entero, y ahí dentro también puede haber un kill.
124
+ */
125
+ function splitCommands(line: string): string[] {
126
+ const parts: string[] = []
127
+ let current = ""
128
+ let quote: "'" | '"' | null = null
129
+ let depth = 0
130
+ for (let i = 0; i < line.length; i++) {
131
+ const ch = line[i]!
132
+ if (quote) {
133
+ if (ch === quote) quote = null
134
+ current += ch
135
+ continue
136
+ }
137
+ if (ch === "'" || ch === '"') {
138
+ quote = ch
139
+ current += ch
140
+ continue
141
+ }
142
+ if (ch === "(") depth++
143
+ if (ch === ")") depth = Math.max(0, depth - 1)
144
+ if (depth === 0 && (ch === ";" || ch === "|" || ch === "&" || ch === "\n")) {
145
+ parts.push(current)
146
+ current = ""
147
+ continue
148
+ }
149
+ current += ch
150
+ }
151
+ parts.push(current)
152
+ return parts.map((p) => p.trim()).filter((p) => p.length > 0)
153
+ }
154
+
155
+ /** Quita prefijos que no cambian el comando real: `sudo`, `env A=b`, `nohup`, `timeout 5`, `VAR=x`. */
156
+ function stripPrefixes(words: string[]): string[] {
157
+ let i = 0
158
+ while (i < words.length) {
159
+ const w = words[i]!
160
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) {
161
+ i++
162
+ continue
163
+ }
164
+ if (w === "sudo" || w === "nohup" || w === "setsid" || w === "exec" || w === "command" || w === "builtin") {
165
+ i++
166
+ while (i < words.length && words[i]!.startsWith("-")) i++
167
+ continue
168
+ }
169
+ if (w === "env") {
170
+ i++
171
+ while (i < words.length && (words[i]!.startsWith("-") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]!))) i++
172
+ continue
173
+ }
174
+ if (w === "timeout") {
175
+ i++
176
+ while (i < words.length && words[i]!.startsWith("-")) i++
177
+ i++ // la duración
178
+ continue
179
+ }
180
+ break
181
+ }
182
+ return words.slice(i)
183
+ }
184
+
185
+ const basename = (word: string) => word.slice(word.lastIndexOf("/") + 1)
186
+
187
+ /** Interpreta las opciones de pkill/pgrep y devuelve el patrón. */
188
+ function parsePgrep(args: string[], via: string): KillTarget | null {
189
+ let full = false
190
+ let exact = false
191
+ let pattern: string | undefined
192
+ for (let i = 0; i < args.length; i++) {
193
+ const a = args[i]!
194
+ if (a === "--") {
195
+ pattern = args[i + 1]
196
+ break
197
+ }
198
+ if (PGREP_VALUE_OPTS.has(a)) {
199
+ i++
200
+ continue
201
+ }
202
+ if (a.startsWith("--")) {
203
+ if (a === "--full") full = true
204
+ else if (a === "--exact") exact = true
205
+ continue
206
+ }
207
+ if (a.startsWith("-") && a.length > 1) {
208
+ // `-9`, `-KILL`, `-SIGTERM` son señales; `-fx` son flags combinados.
209
+ if (/^-(\d+|[A-Z]+|SIG[A-Z]+)$/.test(a)) continue
210
+ if (a.includes("f")) full = true
211
+ if (a.includes("x")) exact = true
212
+ continue
213
+ }
214
+ pattern = a
215
+ break
216
+ }
217
+ if (pattern === undefined || pattern === "") return null
218
+ return { kind: "pattern", pattern, full, exact, via }
219
+ }
220
+
221
+ /** Interpreta `killall` y devuelve un objetivo por nombre. */
222
+ function parseKillall(args: string[]): KillTarget[] {
223
+ const out: KillTarget[] = []
224
+ let regex = false
225
+ for (let i = 0; i < args.length; i++) {
226
+ const a = args[i]!
227
+ if (KILLALL_VALUE_OPTS.has(a)) {
228
+ i++
229
+ continue
230
+ }
231
+ if (a === "-r" || a === "--regexp") {
232
+ regex = true
233
+ continue
234
+ }
235
+ if (a.startsWith("-")) continue
236
+ out.push({ kind: "pattern", pattern: a, full: false, exact: !regex, via: "killall" })
237
+ }
238
+ return out
239
+ }
240
+
241
+ /** Interpreta los argumentos de `kill`: PIDs, grupos, `-1` y sustituciones `$(pgrep …)`. */
242
+ function parseKill(args: string[]): KillTarget[] {
243
+ const out: KillTarget[] = []
244
+ let operands = false // tras `--` todo es operando, incluso `-1234`
245
+ for (let i = 0; i < args.length; i++) {
246
+ const a = args[i]!
247
+ if (!operands) {
248
+ if (a === "--") {
249
+ operands = true
250
+ continue
251
+ }
252
+ if (a === "-s" || a === "-n" || a === "--signal") {
253
+ i++
254
+ operands = true
255
+ continue
256
+ }
257
+ if (a === "-l" || a === "-L" || a === "--list" || a === "--table") return []
258
+ // Señal: `-9`, `-KILL`, `-SIGTERM`. Solo hay una y va primero: lo que viene
259
+ // detrás son objetivos, así que `kill -9 -1` es «todos» igual que `kill -- -1`.
260
+ // `kill -1 PID` sí lee `-1` como señal (SIGHUP), que es lo que hace bash.
261
+ if (/^-(\d+|[A-Za-z]+[A-Za-z0-9+-]*)$/.test(a)) {
262
+ operands = true
263
+ continue
264
+ }
265
+ }
266
+ const sub = /^\$\((.*)\)$/s.exec(a) ?? /^`(.*)`$/s.exec(a)
267
+ if (sub) {
268
+ for (const inner of splitCommands(sub[1]!)) {
269
+ const words = stripPrefixes(tokenize(inner))
270
+ const head = words[0] ? basename(words[0]) : ""
271
+ if (head === "pgrep" || head === "pidof") {
272
+ const t = head === "pgrep" ? parsePgrep(words.slice(1), "kill $(pgrep)") : pidofTarget(words.slice(1))
273
+ if (t) out.push(t)
274
+ }
275
+ }
276
+ continue
277
+ }
278
+ if (/^-?\d+$/.test(a)) {
279
+ const n = Number(a)
280
+ if (n === -1) out.push({ kind: "all" })
281
+ else if (n <= 0) out.push({ kind: "group", pgid: -n })
282
+ else out.push({ kind: "pid", pid: n })
283
+ }
284
+ // `%1` (jobs), `$PID` (variables): no se pueden resolver sin el shell; se ignoran.
285
+ }
286
+ return out
287
+ }
288
+
289
+ function pidofTarget(args: string[]): KillTarget | null {
290
+ const name = args.find((a) => !a.startsWith("-"))
291
+ return name ? { kind: "pattern", pattern: name, full: false, exact: true, via: "kill $(pidof)" } : null
292
+ }
293
+
294
+ /**
295
+ * Extrae los objetivos de kill de un recurso de `shell`.
296
+ * Devuelve [] si el comando no mata nada — que es lo normal, y lo que hace barato
297
+ * llamar a esto en cada permiso.
298
+ */
299
+ export function parseKillTargets(command: string): KillTarget[] {
300
+ // Filtro barato antes de trocear: la inmensa mayoría de comandos no matan nada.
301
+ if (!/\b(kill|pkill|killall)\b/.test(command)) return []
302
+ const out: KillTarget[] = []
303
+ for (const part of splitCommands(command)) {
304
+ const words = stripPrefixes(tokenize(part))
305
+ if (words.length === 0) continue
306
+ const head = basename(words[0]!)
307
+ if (head === "kill") out.push(...parseKill(words.slice(1)))
308
+ else if (head === "pkill") {
309
+ const t = parsePgrep(words.slice(1), "pkill")
310
+ if (t) out.push(t)
311
+ } else if (head === "killall") out.push(...parseKillall(words.slice(1)))
312
+ else if ((head === "bash" || head === "sh" || head === "zsh") && words[1] === "-c" && words[2]) {
313
+ out.push(...parseKillTargets(words[2]))
314
+ }
315
+ }
316
+ return out
317
+ }
318
+
319
+ // ---------------------------------------------------------------------------
320
+ // /proc: qué es cada proceso
321
+ // ---------------------------------------------------------------------------
322
+
323
+ /** Acceso al sistema de ficheros de procesos; inyectable para los tests. */
324
+ export interface ProcSource {
325
+ /** Contenido de `/proc/<pid>/<file>`, o null si no existe o no se puede leer. */
326
+ read(pid: number, file: "status" | "cmdline" | "environ" | "stat"): string | null
327
+ /** PIDs vivos. */
328
+ pids(): number[]
329
+ /** uid → nombre de usuario. */
330
+ userName(uid: number): string | undefined
331
+ }
332
+
333
+ export function systemProcSource(root = "/proc"): ProcSource {
334
+ let passwd: Map<number, string> | undefined
335
+ return {
336
+ read(pid, file) {
337
+ try {
338
+ return readFileSync(`${root}/${pid}/${file}`, "latin1")
339
+ } catch {
340
+ return null
341
+ }
342
+ },
343
+ pids() {
344
+ try {
345
+ return readdirSync(root)
346
+ .filter((name) => /^\d+$/.test(name))
347
+ .map(Number)
348
+ } catch {
349
+ return []
350
+ }
351
+ },
352
+ userName(uid) {
353
+ if (!passwd) {
354
+ passwd = new Map()
355
+ try {
356
+ for (const line of readFileSync("/etc/passwd", "utf8").split("\n")) {
357
+ const [name, , id] = line.split(":")
358
+ if (name && id && /^\d+$/.test(id)) passwd.set(Number(id), name)
359
+ }
360
+ } catch {
361
+ // sin /etc/passwd se muestra el uid
362
+ }
363
+ }
364
+ return passwd.get(uid)
365
+ },
366
+ }
367
+ }
368
+
369
+ export interface ProcInfo {
370
+ readonly pid: number
371
+ readonly ppid: number
372
+ readonly pgid: number
373
+ readonly uid: number
374
+ readonly user: string
375
+ readonly command: string
376
+ /** `OPENCODE_SESSION_ID` del proceso o de un ancestro; undefined si no se pudo leer. */
377
+ readonly launchedBy?: string
378
+ /** El entorno era legible (si no, `launchedBy` no dice nada). */
379
+ readonly environReadable: boolean
380
+ }
381
+
382
+ function parseStatus(text: string): { ppid: number; uid: number; name: string } | null {
383
+ const ppid = /^PPid:\s+(\d+)/m.exec(text)
384
+ const uid = /^Uid:\s+(\d+)/m.exec(text)
385
+ const name = /^Name:\s+(.*)$/m.exec(text)
386
+ if (!ppid || !uid) return null
387
+ return { ppid: Number(ppid[1]), uid: Number(uid[1]), name: name?.[1]?.trim() ?? "?" }
388
+ }
389
+
390
+ /** pgid sale de `/proc/<pid>/stat`, campo 5; el nombre va entre paréntesis y puede tener espacios. */
391
+ function parsePgid(stat: string | null): number {
392
+ if (!stat) return 0
393
+ const close = stat.lastIndexOf(")")
394
+ const fields = stat.slice(close + 2).split(" ")
395
+ return Number(fields[2] ?? 0)
396
+ }
397
+
398
+ function sessionFromEnviron(environ: string): string | undefined {
399
+ for (const entry of environ.split("\0")) {
400
+ if (entry.startsWith("OPENCODE_SESSION_ID=")) return entry.slice("OPENCODE_SESSION_ID=".length)
401
+ }
402
+ return undefined
403
+ }
404
+
405
+ export function readProc(src: ProcSource, pid: number): ProcInfo | null {
406
+ const status = src.read(pid, "status")
407
+ if (!status) return null
408
+ const parsed = parseStatus(status)
409
+ if (!parsed) return null
410
+ const cmdline = (src.read(pid, "cmdline") ?? "").split("\0").filter(Boolean).join(" ")
411
+ const environ = src.read(pid, "environ")
412
+
413
+ // Quién lo lanzó: su propio entorno y, si no lo trae, el de sus ancestros
414
+ // (cortando en el servidor opencode, que no lleva la variable pero sí es padre
415
+ // de todo lo que lanza). Hasta 8 niveles: shell → subshell → nohup → …
416
+ let launchedBy = environ ? sessionFromEnviron(environ) : undefined
417
+ let parent = parsed.ppid
418
+ for (let depth = 0; launchedBy === undefined && environ !== null && parent > 1 && depth < 8; depth++) {
419
+ const env = src.read(parent, "environ")
420
+ if (!env) break
421
+ launchedBy = sessionFromEnviron(env)
422
+ const st = src.read(parent, "status")
423
+ parent = st ? (parseStatus(st)?.ppid ?? 0) : 0
424
+ }
425
+
426
+ return {
427
+ pid,
428
+ ppid: parsed.ppid,
429
+ pgid: parsePgid(src.read(pid, "stat")),
430
+ uid: parsed.uid,
431
+ user: src.userName(parsed.uid) ?? String(parsed.uid),
432
+ command: cmdline || `[${parsed.name}]`,
433
+ launchedBy,
434
+ environReadable: environ !== null,
435
+ }
436
+ }
437
+
438
+ /** Ancestros de un PID (padre, abuelo, …), sin incluirlo. */
439
+ export function ancestors(src: ProcSource, pid: number): Set<number> {
440
+ const out = new Set<number>()
441
+ let current = pid
442
+ for (let depth = 0; depth < 64; depth++) {
443
+ const status = src.read(current, "status")
444
+ const ppid = status ? parseStatus(status)?.ppid : undefined
445
+ if (!ppid || out.has(ppid)) break
446
+ out.add(ppid)
447
+ current = ppid
448
+ }
449
+ return out
450
+ }
451
+
452
+ /**
453
+ * Coincidencia como la hace pgrep: el patrón es una regex extendida que se busca
454
+ * en el nombre del proceso (o en la línea completa con `-f`). Si la regex no
455
+ * compila se trata como texto literal.
456
+ */
457
+ function pgrepMatch(target: Extract<KillTarget, { kind: "pattern" }>, info: ProcInfo, name: string): boolean {
458
+ const subject = target.full ? info.command : name
459
+ let re: RegExp
460
+ try {
461
+ re = new RegExp(target.exact ? `^(?:${target.pattern})$` : target.pattern)
462
+ } catch {
463
+ return target.exact ? subject === target.pattern : subject.includes(target.pattern)
464
+ }
465
+ return re.test(subject)
466
+ }
467
+
468
+ // ---------------------------------------------------------------------------
469
+ // Descripción para el advisor
470
+ // ---------------------------------------------------------------------------
471
+
472
+ export interface DescribeOptions {
473
+ /** PID del servidor opencode (process.pid). */
474
+ readonly selfPid: number
475
+ /** Tope de procesos descritos por patrón o grupo. */
476
+ readonly maxMatches?: number
477
+ }
478
+
479
+ export interface DescribedProcess {
480
+ readonly info: ProcInfo
481
+ readonly critical?: string
482
+ }
483
+
484
+ export interface TargetDescription {
485
+ readonly target: KillTarget
486
+ readonly processes: readonly DescribedProcess[]
487
+ /** Coincidencias totales (puede superar a `processes.length` si se recortó). */
488
+ readonly total: number
489
+ readonly note?: string
490
+ }
491
+
492
+ function criticalReason(info: ProcInfo, selfPid: number, selfAncestors: Set<number>): string | undefined {
493
+ if (info.pid === 1) return "es init (PID 1)"
494
+ if (info.pid === selfPid) return "es el propio servidor de opencode"
495
+ if (selfAncestors.has(info.pid)) return "es un ancestro del servidor de opencode (la terminal o shell que lo sostiene)"
496
+ return undefined
497
+ }
498
+
499
+ export function describeTargets(
500
+ targets: readonly KillTarget[],
501
+ src: ProcSource,
502
+ opts: DescribeOptions,
503
+ ): TargetDescription[] {
504
+ const max = opts.maxMatches ?? 8
505
+ const selfAncestors = ancestors(src, opts.selfPid)
506
+ const describe = (info: ProcInfo): DescribedProcess => ({
507
+ info,
508
+ critical: criticalReason(info, opts.selfPid, selfAncestors),
509
+ })
510
+
511
+ // Lista de procesos, solo si algún objetivo la necesita (patrón o grupo).
512
+ let all: { info: ProcInfo; name: string }[] | undefined
513
+ const listAll = () => {
514
+ if (all) return all
515
+ all = []
516
+ for (const pid of src.pids()) {
517
+ const info = readProc(src, pid)
518
+ if (!info) continue
519
+ const status = src.read(pid, "status")
520
+ all.push({ info, name: (status && parseStatus(status)?.name) ?? "" })
521
+ }
522
+ return all
523
+ }
524
+
525
+ return targets.map((target): TargetDescription => {
526
+ switch (target.kind) {
527
+ case "pid": {
528
+ const info = readProc(src, target.pid)
529
+ if (!info) return { target, processes: [], total: 0, note: "no existe ningún proceso con ese PID (o ya terminó)" }
530
+ return { target, processes: [describe(info)], total: 1 }
531
+ }
532
+ case "all":
533
+ return {
534
+ target,
535
+ processes: [],
536
+ total: 0,
537
+ note: "kill -1 envía la señal a TODOS los procesos del usuario, incluido opencode y la sesión gráfica",
538
+ }
539
+ case "group": {
540
+ if (target.pgid === 0)
541
+ return { target, processes: [], total: 0, note: "kill 0 mata el grupo de procesos del propio shell que ejecuta el comando" }
542
+ const members = listAll().filter((p) => p.info.pgid === target.pgid).map((p) => describe(p.info))
543
+ return { target, processes: members.slice(0, max), total: members.length }
544
+ }
545
+ case "pattern": {
546
+ const matched = listAll()
547
+ .filter((p) => p.info.pid !== opts.selfPid && pgrepMatch(target, p.info, p.name))
548
+ // El shell que va a ejecutar el pkill lleva el patrón en su cmdline y
549
+ // coincidiría consigo mismo con -f; pkill real nunca se cuenta a sí mismo.
550
+ .filter((p) => !(target.full && /\b(pkill|pgrep|killall)\b/.test(p.info.command)))
551
+ .map((p) => describe(p.info))
552
+ // Lo crítico y lo no lanzado por un agente primero: es lo que cambia la decisión.
553
+ const rank = (d: DescribedProcess) => (d.critical ? 0 : d.info.launchedBy ? 2 : 1)
554
+ matched.sort((a, b) => rank(a) - rank(b))
555
+ return {
556
+ target,
557
+ processes: matched.slice(0, max),
558
+ total: matched.length,
559
+ note: matched.length === 0 ? "ningún proceso coincide ahora mismo (el comando no mataría nada)" : undefined,
560
+ }
561
+ }
562
+ }
563
+ })
564
+ }
565
+
566
+ /** Sesiones de opencode que lanzaron alguno de los procesos descritos. */
567
+ export function launchers(descriptions: readonly TargetDescription[]): string[] {
568
+ const out = new Set<string>()
569
+ for (const d of descriptions) for (const p of d.processes) if (p.info.launchedBy) out.add(p.info.launchedBy)
570
+ return [...out]
571
+ }
572
+
573
+ export type Ownership = "this-tree" | "other-agent-session" | "user" | "other-user" | "unknown"
574
+
575
+ export interface FormatOptions {
576
+ /** uid del servidor opencode. */
577
+ readonly selfUid: number
578
+ /** Sesiones del árbol que pide el permiso (la raíz y sus subagentes). */
579
+ readonly treeSessions: ReadonlySet<string>
580
+ }
581
+
582
+ export function classify(info: ProcInfo, opts: FormatOptions): Ownership {
583
+ if (info.uid !== opts.selfUid) return "other-user"
584
+ if (info.launchedBy && opts.treeSessions.has(info.launchedBy)) return "this-tree"
585
+ if (info.launchedBy) return "other-agent-session"
586
+ return info.environReadable ? "user" : "unknown"
587
+ }
588
+
589
+ const OWNERSHIP_LABEL: Record<Ownership, string> = {
590
+ "this-tree": "lanzado por un agente de ESTA conversación (o uno de sus subagentes)",
591
+ "other-agent-session": "lanzado por un agente de OTRA conversación de opencode",
592
+ user: "del usuario, no lanzado por opencode",
593
+ "other-user": "de OTRO usuario del sistema",
594
+ unknown: "origen desconocido (entorno ilegible)",
595
+ }
596
+
597
+ function targetLabel(target: KillTarget): string {
598
+ switch (target.kind) {
599
+ case "pid":
600
+ return `PID ${target.pid}`
601
+ case "group":
602
+ return target.pgid === 0 ? "grupo del propio shell (kill 0)" : `grupo de procesos ${target.pgid}`
603
+ case "all":
604
+ return "todos los procesos (kill -1)"
605
+ case "pattern":
606
+ return `${target.via} "${target.pattern}"${target.full ? " (línea completa, -f)" : ""}${target.exact ? " (exacto)" : ""}`
607
+ }
608
+ }
609
+
610
+ function truncate(text: string, max: number): string {
611
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text
612
+ }
613
+
614
+ /**
615
+ * Bloque de texto para el advisor. Vacío si no hay objetivos.
616
+ * Va en texto plano y corto: el advisor es un modelo barato y cada línea le cuesta latencia.
617
+ */
618
+ export function formatProcessContext(descriptions: readonly TargetDescription[], opts: FormatOptions): string {
619
+ if (descriptions.length === 0) return ""
620
+ const lines = ["Procesos afectados (leído de /proc por apex, no lo afirma el agente):"]
621
+ for (const d of descriptions) {
622
+ // Un `kill PID` encontrado no necesita cabecera: la línea del proceso ya dice el PID.
623
+ const headed = d.target.kind !== "pid" || d.processes.length === 0
624
+ if (headed) lines.push(`- ${targetLabel(d.target)}${d.note ? `: ${d.note}` : ""}`)
625
+ const [bullet, indent] = headed ? [" ", " "] : ["- ", " "]
626
+ for (const p of d.processes) {
627
+ const flag = p.critical ? ` · ⚠ CRÍTICO: ${p.critical}` : ""
628
+ lines.push(
629
+ `${bullet}PID ${p.info.pid} · ${p.info.user} · ${OWNERSHIP_LABEL[classify(p.info, opts)]}${flag}\n${indent}${truncate(p.info.command, 160)}`,
630
+ )
631
+ }
632
+ if (d.total > d.processes.length) lines.push(` … y ${d.total - d.processes.length} más`)
633
+ }
634
+ return lines.join("\n")
635
+ }
636
+
637
+ /**
638
+ * Punto de entrada: objetivos de kill de un permiso de `shell`, ya descritos.
639
+ * Devuelve null si el permiso no mata nada. Nunca lanza: un fallo leyendo /proc
640
+ * deja la petición al advisor como estaba antes de este módulo.
641
+ */
642
+ export function processTargetsFor(
643
+ action: string,
644
+ resources: readonly string[],
645
+ opts: Partial<DescribeOptions> = {},
646
+ src: ProcSource = systemProcSource(),
647
+ ): TargetDescription[] | null {
648
+ if (action !== "shell" && action !== "bash") return null
649
+ try {
650
+ const targets = resources.flatMap((r) => parseKillTargets(r))
651
+ if (targets.length === 0) return null
652
+ return describeTargets(targets, src, { ...opts, selfPid: opts.selfPid ?? process.pid })
653
+ } catch {
654
+ return null
655
+ }
656
+ }
657
+
658
+ export function currentUid(): number {
659
+ try {
660
+ return userInfo().uid
661
+ } catch {
662
+ return -1
663
+ }
664
+ }