omni-notify-mcp 1.3.398 → 1.3.400

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.
@@ -4,6 +4,8 @@ export { dimensions, validFiles } from "../shared/conversation/terminalTransport
4
4
  import { GatewayError, closeNativeTerminal, consoleSession, conversationInScope, createdOn, creatorOf, deleteConversation, nativeTerminal, nativeTerminals, openConversation, PROVIDER_NAMES, providerFor, requireOwnCli, requireConversationEnabled, scopedConversation, terminalArriving, viewerOfHeaders } from "./conversationOwner.js";
5
5
  import { AgentGateway } from "../agentGateway.js";
6
6
  import { bearer, bearerAdmitted, fromThisMachine, personId, sessionExpiresAt } from "./passkeyDoor.js";
7
+ // GATE: how often a terminal socket is pinged so an idle phone connection is not dropped by the tunnel; a peer silent for two periods is closed.
8
+ const TERMINAL_PING_MS = 25_000;
7
9
  export function terminalSockets(server, token) {
8
10
  const sockets = new WebSocketServer({ noServer: true, handleProtocols: () => "bn-terminal" });
9
11
  server.on("upgrade", (req, socket, head) => {
@@ -31,6 +33,14 @@ export function terminalSockets(server, token) {
31
33
  const given = bearer(req);
32
34
  const terminal = nativeTerminal(personId(), match[1]);
33
35
  sockets.handleUpgrade(req, socket, head, (ws) => {
36
+ // A phone idles the socket: a tunnel or carrier drops a connection that carries nothing, so the browser's automatic pong answers this ping and keeps it open; one that never answers is dead and is closed so the page reattaches.
37
+ let answered = true;
38
+ ws.on("pong", () => { answered = true; });
39
+ const keepalive = setInterval(() => { if (!answered) {
40
+ ws.terminate();
41
+ return;
42
+ } answered = false; ws.ping(); }, TERMINAL_PING_MS);
43
+ ws.on("close", () => clearInterval(keepalive));
34
44
  attachTerminalSocket(ws, terminal, {
35
45
  admitted: () => bearerAdmitted(req, token),
36
46
  requireEnabled: () => requireConversationEnabled(),
@@ -203,25 +203,32 @@ async function newAgentView(){
203
203
  // Neither select forces a pick (#4157): no workspace runs the agent at the workspace root, where the rules of every project route each prompt, and no CLI runs the one whose subscription has room.
204
204
  var cliPlaceholder=el("option","","CLI with room (subscription first)"),folderPlaceholder=el("option","","Workspace root (any project)");
205
205
  cliPlaceholder.value="";folderPlaceholder.value="";provider.append(cliPlaceholder);project.append(folderPlaceholder);
206
- setup.append(provider,project,model,open);main.append(setup);
207
- var folders=[],catalog=[];
206
+ var problem=el("div","err");problem.hidden=true;problem.setAttribute("role","alert");
207
+ setup.append(provider,project,model,open);main.append(setup,problem);
208
+ var folders=[],catalog=[],unread=null;
209
+ function refuse(text){problem.textContent="❌ "+text;problem.hidden=false;}
210
+ function cliName(){var chosen=catalog.filter(function(entry){return entry.name===provider.value;})[0];return chosen?(chosen.label||chosen.name):"the CLI whose subscription has room";}
208
211
  function sync(){
209
212
  var chosen=catalog.filter(function(entry){return entry.name===provider.value;})[0];
210
213
  model.hidden=!(chosen&&chosen.model);if(model.hidden)model.value="";
211
- open.disabled=catalog.length===0;
212
- note.textContent=catalog.length===0
214
+ open.disabled=unread===null&&catalog.length===0;
215
+ note.textContent=unread!==null
216
+ ?"The CLIs and workspaces could not be read. Press ▶ New Agent to read them again."
217
+ :catalog.length===0
213
218
  ?"This gateway lists no CLI to run."
214
- :"Starts a session with "+(chosen?(chosen.label||chosen.name):"the CLI whose subscription has room")+" "+(project.value===""?"at the workspace root, where each prompt is routed to its project":"in "+project.value)+". Its conversation then opens in the same view.";
219
+ :"Starts a session with "+cliName()+" "+(project.value===""?"at the workspace root, where each prompt is routed to its project":"in "+project.value)+". Its conversation then opens in the same view.";
215
220
  }
216
221
  try{var listed=await api("GET","/v1/projects");if(mine!==view)return;folders=listed.projects.filter(function(p){return p.board;});folders.forEach(function(p){var option=el("option","",p.name);option.value=p.name;project.append(option);});
217
222
  var sessions=await api("GET","/v1/terminals");if(mine!==view)return;
218
223
  catalog=sessions.providers||[];
219
224
  catalog.forEach(function(entry){var option=el("option","",entry.label||entry.name);option.value=entry.name;provider.append(option);});
220
- }catch(error){fail(error);}
225
+ }catch(error){if(mine!==view)return;unread=error.message;refuse("The CLIs and workspaces could not be read: "+error.message);}
221
226
  provider.onchange=sync;project.onchange=sync;sync();
222
227
  open.onclick=async function(){
223
- open.disabled=true;
224
- try{var s=await api("POST","/v1/terminals",{provider:provider.value||undefined,project:project.value||undefined,model:model.hidden?"":model.value,cols:100,rows:30});if(mine===view)swap("term",s.id);}catch(error){fail(error);open.disabled=false;}
228
+ if(unread!==null){swap("new");return;}
229
+ open.disabled=true;problem.hidden=true;note.textContent="Starting "+cliName()+"…";
230
+ try{var s=await api("POST","/v1/terminals",{provider:provider.value||undefined,project:project.value||undefined,model:model.hidden?"":model.value,cols:100,rows:30});if(mine===view)swap("term",s.id);}
231
+ catch(error){if(mine!==view)return;refuse("Not started: "+error.message);note.textContent="Not started — the reason is below.";open.disabled=false;}
225
232
  };
226
233
  }
227
234
 
@@ -308,7 +315,8 @@ async function cliAttach(id,origin){
308
315
  if(!files.length)return;
309
316
  event.preventDefault();event.stopImmediatePropagation();upload(files);term.focus();
310
317
  },true);
311
- term.onData(function(data){ordered(id,"input",{data:data});});term.onBinary(function(data){ordered(id,"input",{data:btoa(data),binary:true});});
318
+ var pending=[];function typed(body){if(socket&&socket.readyState===WebSocket.OPEN)ordered(id,"input",body);else pending.push(body);}
319
+ term.onData(function(data){typed({data:data});});term.onBinary(function(data){typed({data:btoa(data),binary:true});});
312
320
  refit=function(){if(mine!==view||!socket||socket.readyState!==WebSocket.OPEN)return;fitAddon.fit();ordered(id,"resize",{cols:term.cols,rows:term.rows});};
313
321
  if(observer)observer.disconnect();observer=new ResizeObserver(refit);host.addEventListener("pointerdown",refit);host.addEventListener("touchstart",refit,{passive:true});var wake=function(){if(!document.hidden)refit();},off=observer.disconnect.bind(observer);window.addEventListener("focus",wake);document.addEventListener("visibilitychange",wake);observer.disconnect=function(){window.removeEventListener("focus",wake);document.removeEventListener("visibilitychange",wake);off();};
314
322
  reattach.onclick=function(){cliAttach(id,origin);};
@@ -317,12 +325,11 @@ async function cliAttach(id,origin){
317
325
  observer.observe(host);
318
326
  function connect(){
319
327
  if(mine!==view)return;
320
- term.options.disableStdin=true;
321
328
  var ws=new WebSocket((location.protocol==="https:"?"wss://":"ws://")+location.host+"/v1/terminals/"+id+"/ws",["bn-terminal","bn-bearer."+token]);socket=ws;
322
329
  var frames=Promise.resolve();
323
- ws.onopen=function(){if(mine!==view){ws.close();return;}term.options.disableStdin=false;fitAddon.fit();ordered(id,"resize",{cols:term.cols,rows:term.rows});term.focus();};
330
+ ws.onopen=function(){if(mine!==view){ws.close();return;}fitAddon.fit();ordered(id,"resize",{cols:term.cols,rows:term.rows});while(pending.length)ordered(id,"input",pending.shift());term.focus();};
324
331
  ws.onmessage=function(event){frames=frames.then(async function(){if(mine!==view)return;var frame=JSON.parse(event.data);if(frame.files){fileNotice=frame.error||"Sent to CLI: "+frame.paths.join(" · ");note.textContent=fileNotice;return;}if(frame.error){note.textContent=frame.error;return;}var behind=frame.reset?term.buffer.active.baseY-term.buffer.active.viewportY:0;if(frame.reset)term.reset();await new Promise(function(done){term.write(frame.data,done);});if(mine!==view)return;if(behind>0)term.scrollLines(-behind);note.textContent=frame.provider+" · "+(phone?base(frame.project):frame.project)+(frame.ended?" · CLI ended":" · connected")+(frame.failure?" · "+frame.failure:"")+(fileNotice?" · "+fileNotice:"");}).catch(fail);};
325
- ws.onclose=function(event){if(mine!==view)return;term.options.disableStdin=true;if(event.code===1000){note.textContent="CLI ended.";return;}if(event.code===1008){note.textContent="Disconnected: "+event.reason+". Press Reattach or sign in again.";return;}note.textContent="Disconnected. Reattaching to the same CLI…";reconnect=setTimeout(connect,1000);};
332
+ ws.onclose=function(event){if(mine!==view)return;if(event.code===1000||event.code===1008){term.options.disableStdin=true;pending.length=0;}if(event.code===1000){note.textContent="CLI ended.";return;}if(event.code===1008){note.textContent="Disconnected: "+event.reason+". Press Reattach or sign in again.";return;}note.textContent="Disconnected. Reattaching to the same CLI…";reconnect=setTimeout(connect,1000);};
326
333
  ws.onerror=function(){note.textContent="Terminal connection failed. Reconnecting…";};
327
334
  }
328
335
  connect();
@@ -479,6 +479,7 @@ export class CodexControl {
479
479
  await this.post(threadId, message, beforeSend);
480
480
  }
481
481
  async archiveStory(threadId) {
482
+ await this.daemonUp();
482
483
  const [observed] = await this.observeThreads([{ threadId }]);
483
484
  const ended = observed.state === "terminal" && observed.parent.kind === "known" && observed.parent.threadId === null;
484
485
  if (!ended && !(await this.untouched(threadId)))
@@ -489,6 +490,7 @@ export class CodexControl {
489
490
  await this.request("thread/archive", { threadId });
490
491
  }
491
492
  async restoreStory(threadId) {
493
+ await this.daemonUp();
492
494
  await this.open();
493
495
  await this.request("thread/unarchive", { threadId });
494
496
  }
@@ -3210,7 +3212,7 @@ export const REARM_DOUBLINGS = 2;
3210
3212
  // GATE: how long a done story's archived Claude Code conversation is kept after its archive — past it the queue deletes every file of it, and a story that comes back later starts afresh
3211
3213
  export const ARCHIVE_KEPT_DAYS = 7;
3212
3214
  /** 🔴 #4418 — a provider's HTTP 402 refusal, in the words its CLI reports it: the account the worker billed has no money or quota left, which no re-send to that account changes. */
3213
- const ACCOUNT_REFUSAL = /API Error: 402\b|\b402 (?:Payment Required|Insufficient Balance|You need positive balance|You have exceeded your monthly quota)/i;
3215
+ const ACCOUNT_REFUSAL = /API Error: 402\b|\b402 (?:Payment Required|Insufficient Balance|You need positive balance|You have exceeded your monthly quota)|hit your (?:weekly|5-hour|five-hour|session|usage|monthly)? ?limit|Credit balance is too low|issue with the selected model|account (?:has been |is )?(?:suspended|disabled)/i;
3214
3216
  /** 🔴 #4123 — how long after the queue gave up on a story it is offered to the line again. */
3215
3217
  export const rearmDelayMs = (attempts) => REARM_BASE_MS * 2 ** Math.min(Math.max(attempts - WORKER_ATTEMPTS, 0), REARM_DOUBLINGS);
3216
3218
  /** The acks the passes' requests call for: one per request read, carrying its entry's state and place, rewritten only when one of them changed. */
@@ -3285,7 +3287,7 @@ function afterWorker(e, now, why, retried = true, refund = false) {
3285
3287
  step(e, now, "withdrawn", e.why);
3286
3288
  }
3287
3289
  else if (ACCOUNT_REFUSAL.test(why)) {
3288
- if (!retried)
3290
+ if (e.attempts > 0)
3289
3291
  e.attempts -= 1;
3290
3292
  e.state = "failed";
3291
3293
  delete e.nextTryAt;
@@ -3600,18 +3602,17 @@ export async function driveStoryQueue(board, world, now) {
3600
3602
  const gaveUp = e.trace.filter((t) => t.stage === "failed").pop();
3601
3603
  if (!e.eligible || gaveUp === undefined)
3602
3604
  continue;
3603
- if (now - gaveUp.at < rearmDelayMs(e.attempts))
3605
+ // NULL-OK: field accountRefused is OPTIONAL and therefore it is ok to check for NULL
3606
+ if (e.accountRefused === undefined && now - gaveUp.at < rearmDelayMs(e.attempts))
3604
3607
  continue;
3605
3608
  // NULL-OK: field accountRefused is OPTIONAL and therefore it is ok to check for NULL
3606
3609
  if (e.accountRefused !== undefined) {
3607
- if (now - e.accountRefused.at < rearmDelayMs(e.attempts))
3608
- continue;
3609
3610
  // NULL-OK: field noRoomForStart is OPTIONAL and therefore it is ok to check for NULL
3610
3611
  const noRoom = world.noRoomForStart === undefined ? "this FleetView cannot tell where its next start would land" : await world.noRoomForStart(e);
3611
3612
  // NULL-OK: field noRoom is OPTIONAL and therefore it is ok to check for NULL
3612
3613
  if (noRoom !== undefined) {
3613
3614
  e.accountRefused.at = now;
3614
- const waits = `${e.accountRefused.why} — it waits failed, read again every ${Math.round(rearmDelayMs(e.attempts) / 60_000)}m: ${noRoom}`;
3615
+ const waits = `${e.accountRefused.why} — it waits failed, read again every pass: ${noRoom}`;
3615
3616
  if (e.why !== waits) {
3616
3617
  e.why = waits;
3617
3618
  step(e, now, "held-back", waits);
@@ -3965,10 +3966,6 @@ export async function driveStoryQueue(board, world, now) {
3965
3966
  unwoken(`its worker ${parked.jobId} is parked, and ${wakeHeld}`);
3966
3967
  continue;
3967
3968
  }
3968
- if (lanes >= world.limit && e.forced !== true) {
3969
- unwoken(`its worker ${parked.jobId} is parked, and ${lanes} lanes run with this workspace's lane limit at ${world.limit}, so it is woken when one finishes`);
3970
- continue;
3971
- }
3972
3969
  const roomless = world.noRoomFor === undefined ? undefined : await world.noRoomFor(e);
3973
3970
  if (roomless !== undefined) {
3974
3971
  const moved = `its ${parked.provider} worker ${parked.jobId} is not woken: ${roomless}`;
@@ -4119,10 +4116,6 @@ export async function driveStoryQueue(board, world, now) {
4119
4116
  continue;
4120
4117
  }
4121
4118
  }
4122
- if (lanes >= world.limit && e.forced !== true) {
4123
- holdBack(e, now, "held-back", `${lanes} lanes run and this workspace's lane limit is ${world.limit}, so it starts when one finishes`);
4124
- continue;
4125
- }
4126
4119
  lanes += 1;
4127
4120
  world.seat(e);
4128
4121
  // NULL-OK: field forcedBy is OPTIONAL and therefore it is ok to check for NULL
@@ -824,6 +824,10 @@ class WebHost {
824
824
  ownOrigin(value) {
825
825
  return value === undefined || value === `http://127.0.0.1:${this.port}` || value === `http://localhost:${this.port}`;
826
826
  }
827
+ /** An Origin is this host's own, or the public address the gateway forwarded this very request from (`base`) — a browser through the gateway always sends the latter. */
828
+ admittedOrigin(origin, base) {
829
+ return this.ownOrigin(origin) || (base !== undefined && origin === base);
830
+ }
827
831
  answer(request, response) {
828
832
  this.answered(request, response, () => this.handle(request, response));
829
833
  }
@@ -878,7 +882,7 @@ class WebHost {
878
882
  return send(response, 403, MIME[".txt"], "open this page from its link on the Bullseye dashboard in VS Code — that link carries this window's key");
879
883
  }
880
884
  if (url.pathname === "/__bullseye/workspaces") {
881
- if (!this.ownOrigin(request.headers.origin)) {
885
+ if (!this.admittedOrigin(request.headers.origin, base)) {
882
886
  return send(response, 403, MIME[".txt"], "refused");
883
887
  }
884
888
  if (request.method === "POST") {
@@ -1169,37 +1173,43 @@ class WebHost {
1169
1173
  }
1170
1174
  upgrade(request, socket) {
1171
1175
  socket.on("error", () => socket.destroy());
1172
- if (!this.ownHost(request.headers.host) || !this.ownOrigin(request.headers.origin) || !this.admitted(request)) {
1176
+ if (!this.ownHost(request.headers.host)) {
1173
1177
  socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
1174
1178
  return;
1175
1179
  }
1176
- let url;
1180
+ let base;
1177
1181
  try {
1178
- url = new URL(request.url, `http://127.0.0.1:${this.port}`);
1182
+ base = publicBase(request);
1179
1183
  }
1180
1184
  catch (err) {
1181
- if (err.code !== "ERR_INVALID_URL")
1185
+ if (!(err instanceof TypeError))
1182
1186
  throw err;
1183
- // OWNER: a socket request's malformed address is this request's trigger root, and the process serving it may be a service every agent uses — that one socket is answered 400 and closed.
1187
+ // OWNER: this socket request's trigger root — a gateway name that is not a host name is answered 400, and no address is built on it.
1184
1188
  socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
1185
1189
  return;
1186
1190
  }
1187
- const page = this.pages.get(url.searchParams.get("page"));
1188
- const key = request.headers["sec-websocket-key"];
1189
- if (!this.ownHost(request.headers.host) || !this.ownOrigin(request.headers.origin) || !this.admitted(request) || url.pathname !== "/__bullseye/ws" || page === undefined || typeof key !== "string") {
1191
+ if (!this.admittedOrigin(request.headers.origin, base) || !this.admitted(request)) {
1190
1192
  socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
1191
1193
  return;
1192
1194
  }
1195
+ let url;
1193
1196
  try {
1194
- socket.base = publicBase(request);
1197
+ url = new URL(request.url, `http://127.0.0.1:${this.port}`);
1195
1198
  }
1196
1199
  catch (err) {
1197
- if (!(err instanceof TypeError))
1200
+ if (err.code !== "ERR_INVALID_URL")
1198
1201
  throw err;
1199
- // OWNER: this socket request's trigger root — a gateway name that is not a host name is answered 400, and no address is built on it.
1202
+ // OWNER: a socket request's malformed address is this request's trigger root, and the process serving it may be a service every agent uses — that one socket is answered 400 and closed.
1200
1203
  socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
1201
1204
  return;
1202
1205
  }
1206
+ const page = this.pages.get(url.searchParams.get("page"));
1207
+ const key = request.headers["sec-websocket-key"];
1208
+ if (url.pathname !== "/__bullseye/ws" || page === undefined || typeof key !== "string") {
1209
+ socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
1210
+ return;
1211
+ }
1212
+ socket.base = base;
1203
1213
  const accept = crypto.createHash("sha1").update(key + WS_GUID).digest("base64");
1204
1214
  socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
1205
1215
  socket.setNoDelay(true);
@@ -331,7 +331,9 @@ const SHIM_SOURCE = String.raw `(function () {
331
331
  }
332
332
  var scheme = window.location.protocol === "https:" ? "wss:" : "ws:";
333
333
  socket = new WebSocket(scheme + "//" + window.location.host + "/__bullseye/ws?page=" + encodeURIComponent(page) + "&at=" + encodeURIComponent(window.location.search) + (new URLSearchParams(window.location.search).get("bullseye-peek") === null ? "" : "&peek=1"));
334
+ var opened = false;
334
335
  socket.addEventListener("open", function () {
336
+ opened = true;
335
337
  if (typeof DecompressionStream === "function") {
336
338
  socket.send(JSON.stringify({ type: "packed" }));
337
339
  }
@@ -380,7 +382,17 @@ const SHIM_SOURCE = String.raw `(function () {
380
382
  }
381
383
  socket.addEventListener("close", function () {
382
384
  socket = null;
383
- window.setTimeout(awaitHost, 1000);
385
+ if (opened) {
386
+ window.setTimeout(awaitHost, 1000);
387
+ return;
388
+ }
389
+ window.fetch("/__bullseye/health", { cache: "no-store" }).then(function (response) {
390
+ if (response.ok) {
391
+ notice("__bullseye-host-refused", "⚠️ This page's host refused its connection, so the page cannot receive updates — reload it to try again");
392
+ } else {
393
+ awaitHost();
394
+ }
395
+ }, awaitHost);
384
396
  });
385
397
  }
386
398
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.398",
3
+ "version": "1.3.400",
4
4
  "description": "Reach your AI agents from anywhere — and let them reach you. One resident process on 127.0.0.1:7475 serves the whole tool surface to Claude Code, GitHub Copilot Chat and Codex: desktop, Telegram, Slack, ntfy, Discord, Teams and SMS are configured in one file, and agents notify you when long work finishes or a decision is needed, ask you a question and wait for your answer, and receive and reply to the messages you send them — with Do Not Disturb and idle detection deciding what actually gets through.",
5
5
  "main": "dist/daemon.js",
6
6
  "type": "module",
@@ -1,665 +0,0 @@
1
- // OWNER-BOUND JOB (#1968, #1983): the ONE source of the kill-on-close Job Object that ends a process tree
2
- // with its owner. Loaded by ownerGuard.ps1 through Add-Type and called as OwnerJob.Run(...) for FleetView's
3
- // own launches.
4
- //
5
- // #2925: it is NO LONGER compiled into ~/.bullseye/bin/ownerGuard.exe for `claudeCode.claudeProcessWrapper`.
6
- // That build ran the .NET Framework's csc.exe at every activation, which made a compiler a dependency of a
7
- // marketplace install; the wrapper is now POSIX-only (media/shared/claudeWrapper.sh, a shell script that needs
8
- // nothing but /bin/sh) and Windows installs none. Nothing in this file may be re-wired into that setting.
9
- // Language level is C# 5 (the csc.exe that ships with Windows).
10
- //
11
- // THE MECHANISM: the target is created SUSPENDED, assigned to a job carrying KILL_ON_JOB_CLOSE, and only then
12
- // resumed, so no child can be born outside the job. The guard waits on the owner and the target and, when
13
- // EITHER ends, terminates the job. BREAKAWAY_OK is set on purpose and SILENT_BREAKAWAY is not: a process that
14
- // asks for CREATE_BREAKAWAY_FROM_JOB may leave, but nothing leaves by accident - except under `contain`, which leaves
15
- // BREAKAWAY_OK off because the msys2 runtime asks to break away from every job that allows it (spawn.cc), so a
16
- // Git Bash tree would otherwise leave the job whole. A child that asks then stays (Microsoft, "Nested Jobs").
17
- //
18
- // usage (wrapper mode, owner = the parent process, which is the extension host): ownerGuard.exe <exe> [args...]
19
- // (explicit owner): ownerGuard.exe --owner <pid> <exe> [args...]
20
- using System;
21
- using System.Collections.Generic;
22
- using System.IO;
23
- using System.Runtime.InteropServices;
24
- using System.Text;
25
- using System.Text.RegularExpressions;
26
- using System.Threading;
27
-
28
- public static class OwnerJob
29
- {
30
- const uint KILL_ON_JOB_CLOSE = 0x2000;
31
- const uint BREAKAWAY_OK = 0x800;
32
- const int EXTENDED_LIMIT_INFORMATION = 9;
33
- const uint CREATE_SUSPENDED = 0x00000004;
34
- const int STARTF_USESTDHANDLES = 0x00000100;
35
- const uint SYNCHRONIZE = 0x00100000;
36
- const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
37
- const uint INFINITE = 0xFFFFFFFF;
38
-
39
- public const int EXIT_NO_TARGET = 90;
40
- public const int EXIT_NO_JOB = 91;
41
- public const int EXIT_NO_LIMIT = 92;
42
- public const int EXIT_NOT_CREATED = 93;
43
- public const int EXIT_NOT_ASSIGNED = 94;
44
- public const int EXIT_OWNER_GONE = 95;
45
- public const int EXIT_NOT_FOUND = 96;
46
- public const int EXIT_BATCH_LINE_BREAK = 97;
47
- public const int EXIT_NOT_RESUMED = 98;
48
- public const int EXIT_WAIT_FAILED = 99;
49
- public const int EXIT_NO_EXIT_CODE = 100;
50
- public const int EXIT_DEADLINE = 101;
51
- public const int EXIT_ALREADY_RUNNING = 102;
52
- public const int FRAME_OWNERS = -1;
53
- const uint WAIT_TIMEOUT = 0x102;
54
- const uint STILL_ACTIVE = 259;
55
- const int ERROR_INVALID_PARAMETER = 87;
56
-
57
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
58
- struct STARTUPINFO
59
- {
60
- public int cb;
61
- public string lpReserved;
62
- public string lpDesktop;
63
- public string lpTitle;
64
- public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
65
- public short wShowWindow, cbReserved2;
66
- public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
67
- }
68
-
69
- [StructLayout(LayoutKind.Sequential)]
70
- struct PROCESS_INFORMATION
71
- {
72
- public IntPtr hProcess, hThread;
73
- public int dwProcessId, dwThreadId;
74
- }
75
-
76
- [StructLayout(LayoutKind.Sequential)]
77
- struct IO_COUNTERS
78
- {
79
- public ulong a, b, c, d, e, f;
80
- }
81
-
82
- [StructLayout(LayoutKind.Sequential)]
83
- struct JOBOBJECT_BASIC_LIMIT_INFORMATION
84
- {
85
- public long PerProcessUserTimeLimit, PerJobUserTimeLimit;
86
- public uint LimitFlags;
87
- public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize;
88
- public uint ActiveProcessLimit;
89
- public UIntPtr Affinity;
90
- public uint PriorityClass, SchedulingClass;
91
- }
92
-
93
- [StructLayout(LayoutKind.Sequential)]
94
- struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
95
- {
96
- public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
97
- public IO_COUNTERS IoInfo;
98
- public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed;
99
- }
100
-
101
- [StructLayout(LayoutKind.Sequential)]
102
- struct PROCESS_BASIC_INFORMATION
103
- {
104
- public IntPtr ExitStatus, PebBaseAddress, AffinityMask, BasePriority, UniqueProcessId, InheritedFromUniqueProcessId;
105
- }
106
-
107
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
108
- static extern IntPtr CreateJobObject(IntPtr attributes, string name);
109
- [DllImport("kernel32.dll", SetLastError = true)]
110
- static extern bool SetInformationJobObject(IntPtr job, int infoClass, IntPtr info, uint length);
111
- [DllImport("kernel32.dll", SetLastError = true)]
112
- static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
113
- [DllImport("kernel32.dll", SetLastError = true)]
114
- static extern bool TerminateJobObject(IntPtr job, uint exitCode);
115
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
116
- static extern bool CreateProcess(string application, string commandLine, IntPtr processAttributes, IntPtr threadAttributes,
117
- bool inheritHandles, uint creationFlags, IntPtr environment, string currentDirectory, ref STARTUPINFO startupInfo,
118
- out PROCESS_INFORMATION processInformation);
119
- [DllImport("kernel32.dll", SetLastError = true)]
120
- static extern IntPtr GetStdHandle(int which);
121
- [DllImport("kernel32.dll", SetLastError = true)]
122
- static extern bool CloseHandle(IntPtr handle);
123
- [DllImport("kernel32.dll", SetLastError = true)]
124
- static extern uint WaitForMultipleObjects(uint count, IntPtr[] handles, bool waitAll, uint milliseconds);
125
- [DllImport("kernel32.dll", SetLastError = true)]
126
- static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
127
- [DllImport("kernel32.dll", SetLastError = true)]
128
- static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode);
129
- [DllImport("kernel32.dll", SetLastError = true)]
130
- static extern uint ResumeThread(IntPtr thread);
131
- [DllImport("kernel32.dll")]
132
- static extern IntPtr GetCurrentProcess();
133
- [DllImport("kernel32.dll")]
134
- static extern int GetCurrentProcessId();
135
- [DllImport("kernel32.dll", SetLastError = true)]
136
- static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
137
- [DllImport("ntdll.dll")]
138
- static extern int NtQueryInformationProcess(IntPtr process, int infoClass, ref PROCESS_BASIC_INFORMATION info, int length, out int returned);
139
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
140
- static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder name, ref int size);
141
-
142
- // One argument as CommandLineToArgvW reads it back: quoted only when it must be, a quote escaped by
143
- // backslashes per the Windows rules, so a path with spaces stays ONE argument.
144
- public static string QuoteArg(string arg)
145
- {
146
- if (arg.Length > 0 && arg.IndexOfAny(new char[] { ' ', '\t', '\n', '\v', '"' }) < 0)
147
- {
148
- return arg;
149
- }
150
- StringBuilder sb = new StringBuilder("\"");
151
- int slashes = 0;
152
- foreach (char ch in arg)
153
- {
154
- if (ch == '\\') { slashes++; continue; }
155
- if (ch == '"') { sb.Append('\\', 2 * slashes + 1); sb.Append('"'); }
156
- else { sb.Append('\\', slashes); sb.Append(ch); }
157
- slashes = 0;
158
- }
159
- sb.Append('\\', 2 * slashes);
160
- sb.Append('"');
161
- return sb.ToString();
162
- }
163
-
164
- // cmd.exe reads its command line by rules of its own: every character it treats as special, the quote and the
165
- // space included, is escaped with a caret so the whole argument is literal text to it.
166
- static string EscapeCmd(string text)
167
- {
168
- return Regex.Replace(text, "([()\\]\\[%!^\"`<>&|;, *?])", "^$1");
169
- }
170
-
171
- static int ParentOf(IntPtr process)
172
- {
173
- PROCESS_BASIC_INFORMATION info = new PROCESS_BASIC_INFORMATION();
174
- int returned;
175
- if (NtQueryInformationProcess(process, 0, ref info, Marshal.SizeOf(info), out returned) != 0)
176
- {
177
- return 0;
178
- }
179
- return (int)info.InheritedFromUniqueProcessId.ToInt64();
180
- }
181
-
182
- static int ParentPid()
183
- {
184
- return ParentOf(GetCurrentProcess());
185
- }
186
-
187
- static long StartOf(IntPtr process, int pid)
188
- {
189
- long start, ignored;
190
- if (!GetProcessTimes(process, out start, out ignored, out ignored, out ignored))
191
- {
192
- throw new InvalidOperationException("the start time of process " + pid + " could not be read (win32 " + Marshal.GetLastWin32Error() + ")");
193
- }
194
- return start;
195
- }
196
-
197
- // A pid names an ancestor only if that process STARTED BEFORE the younger one: a recycled pid belongs to a
198
- // younger process, and then the real ancestor is already dead.
199
- static IntPtr OpenGone(int pid, uint access)
200
- {
201
- IntPtr process = OpenProcess(access, false, pid);
202
- if (process == IntPtr.Zero)
203
- {
204
- int why = Marshal.GetLastWin32Error();
205
- if (why != ERROR_INVALID_PARAMETER)
206
- {
207
- throw new InvalidOperationException("process " + pid + " could not be opened (win32 " + why + ")");
208
- }
209
- }
210
- return process;
211
- }
212
-
213
- static IntPtr OpenOlderThan(int pid, IntPtr younger, int youngerPid)
214
- {
215
- IntPtr process = OpenGone(pid, SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION);
216
- if (process == IntPtr.Zero)
217
- {
218
- return process;
219
- }
220
- if (StartOf(process, pid) > StartOf(younger, youngerPid))
221
- {
222
- CloseHandle(process);
223
- return IntPtr.Zero;
224
- }
225
- return process;
226
- }
227
-
228
- static IntPtr OpenOwner(int ownerPid, bool mustPredateSelf)
229
- {
230
- return mustPredateSelf
231
- ? OpenOlderThan(ownerPid, GetCurrentProcess(), GetCurrentProcessId())
232
- : OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, ownerPid);
233
- }
234
-
235
- static string ImageOf(IntPtr process, int pid)
236
- {
237
- StringBuilder name = new StringBuilder(1024);
238
- int size = name.Capacity;
239
- if (!QueryFullProcessImageName(process, 0, name, ref size))
240
- {
241
- throw new InvalidOperationException("the image of process " + pid + " could not be read (win32 " + Marshal.GetLastWin32Error() + ")");
242
- }
243
- return name.ToString(0, size);
244
- }
245
-
246
- static List<IntPtr> ShellFrame()
247
- {
248
- List<IntPtr> frame = new List<IntPtr>();
249
- IntPtr child = GetCurrentProcess();
250
- int childPid = GetCurrentProcessId();
251
- while (true)
252
- {
253
- int parentPid = ParentOf(child);
254
- if (parentPid == 0)
255
- {
256
- throw new InvalidOperationException("the parent of process " + childPid + " could not be read");
257
- }
258
- IntPtr parent = OpenOlderThan(parentPid, child, childPid);
259
- if (parent == IntPtr.Zero)
260
- {
261
- return frame;
262
- }
263
- frame.Add(parent);
264
- string image = Path.GetFileName(ImageOf(parent, parentPid)).ToLowerInvariant();
265
- if (image != "bash.exe" && image != "sh.exe")
266
- {
267
- return frame;
268
- }
269
- child = parent;
270
- childPid = parentPid;
271
- }
272
- }
273
-
274
- static string ReadLock(string path)
275
- {
276
- try
277
- {
278
- using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)))
279
- {
280
- return reader.ReadToEnd().Trim();
281
- }
282
- }
283
- catch (FileNotFoundException)
284
- {
285
- return null;
286
- }
287
- }
288
-
289
- static bool StillHolds(int pid, long start)
290
- {
291
- IntPtr process = OpenGone(pid, PROCESS_QUERY_LIMITED_INFORMATION);
292
- if (process == IntPtr.Zero)
293
- {
294
- return false;
295
- }
296
- uint code;
297
- bool alive = StartOf(process, pid) == start && GetExitCodeProcess(process, out code) && code == STILL_ACTIVE;
298
- CloseHandle(process);
299
- return alive;
300
- }
301
-
302
- static bool ParseLock(string held, out int pid, out long start)
303
- {
304
- string[] parts = held.Split(' ');
305
- start = 0;
306
- pid = 0;
307
- return parts.Length == 2 && int.TryParse(parts[0], out pid) && long.TryParse(parts[1], out start);
308
- }
309
-
310
- static int TakeLock(string path, out string mine)
311
- {
312
- mine = GetCurrentProcessId() + " " + StartOf(GetCurrentProcess(), GetCurrentProcessId());
313
- for (int attempt = 0; attempt < 2; attempt++)
314
- {
315
- if (!File.Exists(path))
316
- {
317
- try
318
- {
319
- using (FileStream file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
320
- {
321
- byte[] bytes = Encoding.ASCII.GetBytes(mine);
322
- file.Write(bytes, 0, bytes.Length);
323
- }
324
- return 0;
325
- }
326
- catch (IOException)
327
- {
328
- if (!File.Exists(path))
329
- {
330
- throw;
331
- }
332
- }
333
- }
334
- string held = ReadLock(path);
335
- int pid;
336
- long start;
337
- if (held != null && !ParseLock(held, out pid, out start))
338
- {
339
- Thread.Sleep(1000);
340
- held = ReadLock(path);
341
- }
342
- if (held == null)
343
- {
344
- continue;
345
- }
346
- bool parsed = ParseLock(held, out pid, out start);
347
- if (parsed && StillHolds(pid, start))
348
- {
349
- Say("REFUSED - an earlier run (pid " + pid + ", started " + DateTime.FromFileTime(start).ToString("yyyy-MM-dd HH:mm:ss") + ") still holds " + path + " - this launch did not run");
350
- return EXIT_ALREADY_RUNNING;
351
- }
352
- try
353
- {
354
- File.Delete(path);
355
- }
356
- catch (IOException e)
357
- {
358
- Say("REFUSED - " + path + " named '" + held + "' and could not be replaced (" + e.Message + ") - this launch did not run");
359
- return EXIT_ALREADY_RUNNING;
360
- }
361
- Say("STALE LOCK - " + path + " named '" + held + "', which " + (parsed ? "no longer runs" : "is not a pid and start time") + " - taken over");
362
- }
363
- Say("REFUSED - " + path + " was taken by another launch while its stale holder was being replaced - this launch did not run");
364
- return EXIT_ALREADY_RUNNING;
365
- }
366
-
367
- static void ReleaseLock(string path, string mine)
368
- {
369
- if (ReadLock(path) == mine)
370
- {
371
- File.Delete(path);
372
- }
373
- }
374
-
375
- static void Say(string text)
376
- {
377
- Console.Error.WriteLine("ownerGuard: " + text);
378
- }
379
-
380
- // The target as the launch has always resolved it (Get-Command -CommandType Application): a name with a folder is
381
- // taken as given, a bare name is searched along PATH, and a name without a PATHEXT extension tries each one.
382
- static string Resolve(string exe)
383
- {
384
- List<string> extensions = new List<string>((Environment.GetEnvironmentVariable("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD")
385
- .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
386
- List<string> folders = new List<string>();
387
- if (exe.IndexOfAny(new char[] { '\\', '/', ':' }) >= 0)
388
- {
389
- folders.Add(null);
390
- }
391
- else
392
- {
393
- foreach (string dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
394
- {
395
- folders.Add(dir.Trim('"'));
396
- }
397
- }
398
- foreach (string folder in folders)
399
- {
400
- string stem = folder == null ? exe : Path.Combine(folder, exe);
401
- if (File.Exists(stem) && extensions.Exists(delegate(string e) { return stem.EndsWith(e, StringComparison.OrdinalIgnoreCase); }))
402
- {
403
- return Path.GetFullPath(stem);
404
- }
405
- foreach (string ext in extensions)
406
- {
407
- if (File.Exists(stem + ext))
408
- {
409
- return Path.GetFullPath(stem + ext);
410
- }
411
- }
412
- }
413
- return null;
414
- }
415
-
416
- // The command line the target is created with, or null (and a refusal said) when it cannot be carried.
417
- static string CommandLine(ref string exe, string[] args, out int refusal)
418
- {
419
- refusal = 0;
420
- string ext = Path.GetExtension(exe).ToLowerInvariant();
421
- StringBuilder line = new StringBuilder();
422
- if (ext == ".cmd" || ext == ".bat")
423
- {
424
- foreach (string arg in args)
425
- {
426
- if (arg.IndexOfAny(new char[] { '\r', '\n' }) >= 0)
427
- {
428
- Say("the target '" + exe + "' is a batch file and one of its arguments holds a line break, which cmd.exe cannot carry - nothing was started");
429
- refusal = EXIT_BATCH_LINE_BREAK;
430
- return null;
431
- }
432
- }
433
- StringBuilder inner = new StringBuilder(EscapeCmd(exe));
434
- foreach (string arg in args)
435
- {
436
- inner.Append(' ').Append(EscapeCmd(EscapeCmd(QuoteArg(arg))));
437
- }
438
- exe = Path.Combine(Environment.SystemDirectory, "cmd.exe");
439
- return QuoteArg(exe) + " /d /s /v:off /c \"" + inner + "\"";
440
- }
441
- line.Append(QuoteArg(exe));
442
- foreach (string arg in args)
443
- {
444
- line.Append(' ').Append(QuoteArg(arg));
445
- }
446
- return line.ToString();
447
- }
448
-
449
- public static int Run(int ownerPid, string exe, string[] args, string cwd)
450
- {
451
- return Run(ownerPid, exe, args, cwd, 0, false, null);
452
- }
453
-
454
- // Runs the target inside a kill-on-close job and answers the target's own exit code. ownerPid <= 0 means
455
- // "the parent process owns this launch", FRAME_OWNERS means "the shell frame owns it" (ShellFrame). cwd null or
456
- // empty starts the target where this process runs. deadlineSeconds > 0 ends the whole job at that age
457
- // (EXIT_DEADLINE). contain leaves BREAKAWAY_OK off, so no process inside can leave the job, Git Bash's
458
- // included. lockFile, when given, admits one launch at a time (TakeLock).
459
- public static int Run(int ownerPid, string exe, string[] args, string cwd, int deadlineSeconds, bool contain, string lockFile)
460
- {
461
- if (string.IsNullOrEmpty(exe) || exe.Trim().Length == 0)
462
- {
463
- Say("the target executable is empty - nothing was started");
464
- return EXIT_NO_TARGET;
465
- }
466
- if (string.IsNullOrEmpty(cwd))
467
- {
468
- cwd = null;
469
- }
470
- string resolved = Resolve(exe);
471
- if (resolved == null)
472
- {
473
- Say("the target '" + exe + "' is not an executable on PATH or on disk - nothing was started");
474
- return EXIT_NOT_FOUND;
475
- }
476
- exe = resolved;
477
- int refusal;
478
- string line = CommandLine(ref exe, args, out refusal);
479
- if (line == null)
480
- {
481
- return refusal;
482
- }
483
- string mine = null;
484
- if (!string.IsNullOrEmpty(lockFile))
485
- {
486
- int refused = TakeLock(lockFile, out mine);
487
- if (refused != 0)
488
- {
489
- return refused;
490
- }
491
- }
492
- try
493
- {
494
- return Launch(ownerPid, exe, line, cwd, deadlineSeconds, contain);
495
- }
496
- finally
497
- {
498
- if (mine != null)
499
- {
500
- ReleaseLock(lockFile, mine);
501
- }
502
- }
503
- }
504
-
505
- static int Launch(int ownerPid, string exe, string line, string cwd, int deadlineSeconds, bool contain)
506
- {
507
- bool frame = ownerPid == FRAME_OWNERS;
508
- bool viaParent = !frame && ownerPid <= 0;
509
- if (viaParent)
510
- {
511
- ownerPid = ParentPid();
512
- }
513
-
514
- IntPtr job = CreateJobObject(IntPtr.Zero, null);
515
- if (job == IntPtr.Zero)
516
- {
517
- Say("the job object could not be created (win32 " + Marshal.GetLastWin32Error() + ") - the target was NOT started unguarded");
518
- return EXIT_NO_JOB;
519
- }
520
- JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
521
- limits.BasicLimitInformation.LimitFlags = contain ? KILL_ON_JOB_CLOSE : KILL_ON_JOB_CLOSE | BREAKAWAY_OK;
522
- int size = Marshal.SizeOf(limits);
523
- IntPtr buffer = Marshal.AllocHGlobal(size);
524
- try
525
- {
526
- Marshal.StructureToPtr(limits, buffer, false);
527
- if (!SetInformationJobObject(job, EXTENDED_LIMIT_INFORMATION, buffer, (uint)size))
528
- {
529
- Say("the job could not be told to kill on close (win32 " + Marshal.GetLastWin32Error() + ") - the target was NOT started unguarded");
530
- CloseHandle(job);
531
- return EXIT_NO_LIMIT;
532
- }
533
- }
534
- finally
535
- {
536
- Marshal.FreeHGlobal(buffer);
537
- }
538
-
539
- STARTUPINFO startup = new STARTUPINFO();
540
- startup.cb = Marshal.SizeOf(startup);
541
- IntPtr stdin = GetStdHandle(-10), stdout = GetStdHandle(-11), stderr = GetStdHandle(-12);
542
- if (stdin != IntPtr.Zero && stdout != IntPtr.Zero && stderr != IntPtr.Zero)
543
- {
544
- startup.dwFlags = STARTF_USESTDHANDLES;
545
- startup.hStdInput = stdin;
546
- startup.hStdOutput = stdout;
547
- startup.hStdError = stderr;
548
- }
549
-
550
- PROCESS_INFORMATION process;
551
- if (!CreateProcess(exe, line, IntPtr.Zero, IntPtr.Zero, true, CREATE_SUSPENDED, IntPtr.Zero, cwd, ref startup, out process))
552
- {
553
- Say("the target could not be created (win32 " + Marshal.GetLastWin32Error() + ") - nothing was started");
554
- CloseHandle(job);
555
- return EXIT_NOT_CREATED;
556
- }
557
- if (!AssignProcessToJobObject(job, process.hProcess))
558
- {
559
- int error = Marshal.GetLastWin32Error();
560
- TerminateJobObject(job, EXIT_NOT_ASSIGNED);
561
- CloseHandle(process.hThread);
562
- CloseHandle(process.hProcess);
563
- CloseHandle(job);
564
- Say("the target could not be put under the job that ends it with its owner (win32 " + error + ") - it was stopped rather than left unguarded");
565
- return EXIT_NOT_ASSIGNED;
566
- }
567
-
568
- // The owner is opened AFTER the target sits in the job and BEFORE it runs, so a dead owner stops it unrun.
569
- List<IntPtr> owners = new List<IntPtr>();
570
- if (frame)
571
- {
572
- owners = ShellFrame();
573
- }
574
- else if (ownerPid > 0)
575
- {
576
- IntPtr owner = OpenOwner(ownerPid, viaParent);
577
- if (owner != IntPtr.Zero)
578
- {
579
- owners.Add(owner);
580
- }
581
- }
582
- if (owners.Count == 0)
583
- {
584
- int why = Marshal.GetLastWin32Error();
585
- TerminateJobObject(job, EXIT_OWNER_GONE);
586
- CloseHandle(process.hThread);
587
- CloseHandle(process.hProcess);
588
- CloseHandle(job);
589
- Say((frame ? "the shell frame above this guard" : "the owner process " + ownerPid) + " cannot be watched (win32 " + why + ") - the target was stopped before it ran");
590
- return EXIT_OWNER_GONE;
591
- }
592
-
593
- if (ResumeThread(process.hThread) == 0xFFFFFFFF)
594
- {
595
- int why = Marshal.GetLastWin32Error();
596
- TerminateJobObject(job, EXIT_NOT_RESUMED);
597
- Say("the target could not be resumed (win32 " + why + ") - it was stopped rather than left suspended");
598
- return EXIT_NOT_RESUMED;
599
- }
600
- CloseHandle(process.hThread);
601
-
602
- List<IntPtr> watched = new List<IntPtr>(owners);
603
- watched.Insert(0, process.hProcess);
604
- uint waited = WaitForMultipleObjects((uint)watched.Count, watched.ToArray(), false, deadlineSeconds > 0 ? (uint)deadlineSeconds * 1000 : INFINITE);
605
- int waitError = Marshal.GetLastWin32Error();
606
- foreach (IntPtr owner in owners)
607
- {
608
- CloseHandle(owner);
609
- }
610
- if (waited == 0xFFFFFFFF)
611
- {
612
- TerminateJobObject(job, EXIT_WAIT_FAILED);
613
- Say("the wait on the target and its owner failed (win32 " + waitError + ") - the target was stopped rather than left unwatched");
614
- return EXIT_WAIT_FAILED;
615
- }
616
- if (waited == WAIT_TIMEOUT)
617
- {
618
- TerminateJobObject(job, EXIT_DEADLINE);
619
- Say("DEADLINE - the target ran past its " + deadlineSeconds + " s; its whole job was ended");
620
- return EXIT_DEADLINE;
621
- }
622
- if (waited != 0)
623
- {
624
- TerminateJobObject(job, EXIT_OWNER_GONE);
625
- Say("OWNER GONE - a process this launch was bound to ended; the target's whole job was ended");
626
- return EXIT_OWNER_GONE;
627
- }
628
-
629
- uint code = 0;
630
- if (!GetExitCodeProcess(process.hProcess, out code))
631
- {
632
- int why = Marshal.GetLastWin32Error();
633
- TerminateJobObject(job, EXIT_NO_EXIT_CODE);
634
- Say("the target's exit code could not be read (win32 " + why + ") - the target was stopped");
635
- return EXIT_NO_EXIT_CODE;
636
- }
637
- TerminateJobObject(job, 1);
638
- CloseHandle(process.hProcess);
639
- CloseHandle(job);
640
- return (int)code;
641
- }
642
-
643
- public static int Main(string[] argv)
644
- {
645
- List<string> rest = new List<string>(argv);
646
- int ownerPid = 0;
647
- if (rest.Count >= 2 && rest[0] == "--owner")
648
- {
649
- if (!int.TryParse(rest[1], out ownerPid) || ownerPid <= 0)
650
- {
651
- Say("--owner needs a process id");
652
- return EXIT_NO_TARGET;
653
- }
654
- rest.RemoveRange(0, 2);
655
- }
656
- if (rest.Count == 0)
657
- {
658
- Say("usage: ownerGuard.exe [--owner <pid>] <exe> [args...]");
659
- return EXIT_NO_TARGET;
660
- }
661
- string exe = rest[0];
662
- rest.RemoveAt(0);
663
- return Run(ownerPid, exe, rest.ToArray(), null);
664
- }
665
- }
@@ -1,31 +0,0 @@
1
- # OWNER-BOUND LAUNCH (#1968): start one target so that it can never outlive its owner, and so that nothing it
2
- # started can outlive IT. This script is only the PowerShell door onto ownerGuard.cs, which holds the whole job.
3
- # #2925: the same source is no longer compiled into an ownerGuard.exe for `claudeCode.claudeProcessWrapper` — that
4
- # build ran csc.exe at every activation, and the .NET compiler is not a dependency a marketplace install may carry.
5
- # The target's own exit code is answered as this script's exit code.
6
- param(
7
- [Parameter(Mandatory = $true)][int]$OwnerPid,
8
- [Parameter(Mandatory = $true)][string]$ExeB64,
9
- [Parameter(Mandatory = $true)][string]$ArgsB64,
10
- [Parameter(Mandatory = $true)][AllowEmptyString()][string]$CwdB64,
11
- [switch]$ShellFrame,
12
- [int]$DeadlineSeconds = 0,
13
- [switch]$Contain,
14
- [string]$LockFile = ""
15
- )
16
-
17
- $ErrorActionPreference = "Stop"
18
-
19
- Add-Type -Path (Join-Path $PSScriptRoot "ownerGuard.cs")
20
-
21
- $exe = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($ExeB64))
22
- # ConvertFrom-Json hands back the WHOLE array as one object on Windows PowerShell, so iterate it with
23
- # foreach: a one-element array arrives as the element itself and a longer one as the array, both right.
24
- $argv = New-Object System.Collections.Generic.List[string]
25
- foreach ($item in ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($ArgsB64)) | ConvertFrom-Json)) {
26
- $argv.Add([string]$item)
27
- }
28
- $cwd = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($CwdB64))
29
-
30
- if ($ShellFrame) { $OwnerPid = [OwnerJob]::FRAME_OWNERS }
31
- exit ([OwnerJob]::Run($OwnerPid, $exe, $argv.ToArray(), $cwd, $DeadlineSeconds, $Contain.IsPresent, $LockFile))