omni-notify-mcp 1.3.409 → 1.3.413

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.
@@ -748,7 +748,11 @@ async function home() {
748
748
  if (res.status === 401) { signIn("You are signed out. Sign in again."); return; }
749
749
  if (!res.ok) throw new Error("The gateway answered " + res.status + ": " + await res.text());
750
750
  var opened = await res.json();
751
- if (mine === view) location.replace(opened.page);
751
+ if (mine === view) {
752
+ var back = sessionStorage.getItem("bullseye-return-to");
753
+ sessionStorage.removeItem("bullseye-return-to");
754
+ location.replace(back !== null && back.charAt(0) === "/" && back.charAt(1) !== "/" && back.charAt(1) !== "\\" ? back : opened.page);
755
+ }
752
756
  } catch (err) { if (!(err instanceof Error)) throw err; if (mine === view) said.replaceWith(el("div", "err", err.message)); }
753
757
  }
754
758
  `;
@@ -160,7 +160,7 @@ function show(name,heading){
160
160
  return view;
161
161
  }
162
162
 
163
- function down(what,method,path){if(method==="GET"&&path==="/v1/conversations")window.bullseyeConnection.reconnecting(what,8000);else if(method==="GET"&&path==="/v1/panel")window.bullseyeConnection.reconnecting(what,5000);else if(method==="GET"&&path.indexOf("/v1/terminals/")===0)window.bullseyeConnection.reconnecting(what,1000);else window.bullseyeConnection.disconnected(what,"this request did not go through — repeat it");}function scoped(h){if(scope!==null)h["x-bullseye-project"]=scope;return h}async function api(method,path,body,signal){var response;try{response=await fetch(path,{method:method,headers:scoped({authorization:"Bearer "+token,"content-type":"application/json"}),body:body===undefined?undefined:JSON.stringify(body),signal:signal});}catch(e){if(e.name!=="AbortError")down("the connection to the Notify service",method,path);throw e;}if(response.status>=502)down("the connection to the Notify service (HTTP "+response.status+")",method,path);else if(!socketDown)window.bullseyeConnection.live();var data=await response.json();if(!response.ok){if(response.status===401)signIn("Sign in again to reach your CLI.");var error=Error(data.error||"Request failed");error.status=response.status;throw error;}return data;}
163
+ function down(what,method,path){if(method==="GET"&&path==="/v1/conversations")window.bullseyeConnection.reconnecting(what,8000);else if(method==="GET"&&path==="/v1/panel")window.bullseyeConnection.reconnecting(what,5000);else if(method==="GET"&&path.indexOf("/v1/terminals/")===0)window.bullseyeConnection.reconnecting(what,1000);}function scoped(h){if(scope!==null)h["x-bullseye-project"]=scope;return h}async function api(method,path,body,signal){var response;try{response=await fetch(path,{method:method,headers:scoped({authorization:"Bearer "+token,"content-type":"application/json"}),body:body===undefined?undefined:JSON.stringify(body),signal:signal});}catch(e){if(e.name!=="AbortError")down("the connection to the Notify service",method,path);throw e;}if(response.status>=502)down("the connection to the Notify service (HTTP "+response.status+")",method,path);else if(!socketDown)window.bullseyeConnection.live();var data=await response.json();if(!response.ok){if(response.status===401)signIn("Sign in again to reach your CLI.");var error=Error(data.error||"Request failed");error.status=response.status;throw error;}return data;}
164
164
  function fail(error){note.textContent=error.message;}
165
165
  function ordered(id,act,body){if(!socket||socket.readyState!==WebSocket.OPEN)return;socket.send(JSON.stringify(Object.assign({kind:act},body)));}
166
166
  /** The last folder of a path, so a row names its project without printing the whole path. */
@@ -371,23 +371,41 @@ async function cliAttach(id,origin){
371
371
  else b.onclick=function(){sendKey(key.seq[term.modes.applicationCursorKeysMode?1:0]);term.focus();};
372
372
  keybar.append(b);
373
373
  });
374
- term.onData(function(data){if(ctrlHeld&&data.length===1){disarm();data=ctrlByte(data);}ordered(id,"input",{data:data});});term.onBinary(function(data){ordered(id,"input",{data:btoa(data),binary:true});});
374
+ var pending=[];function typed(body){if(socket&&socket.readyState===WebSocket.OPEN)ordered(id,"input",body);else pending.push(body);}
375
+ term.onData(function(data){if(ctrlHeld&&data.length===1){disarm();data=ctrlByte(data);}typed({data:data});});term.onBinary(function(data){typed({data:btoa(data),binary:true});});
375
376
  refit=function(){if(mine!==view||!socket||socket.readyState!==WebSocket.OPEN)return;fitAddon.fit();ordered(id,"resize",{cols:term.cols,rows:term.rows});};
376
377
  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();};
377
378
  reattach.onclick=function(){cliAttach(id,origin);};
378
379
  back.onclick=goBack;
379
380
  close.onclick=async function(){close.disabled=true;try{await api("DELETE","/v1/terminals/"+id);swap("list");}catch(error){close.disabled=false;fail(error);}};
380
381
  observer.observe(host);
382
+ var WHAT="the terminal connection to the CLI",reattached=false;
381
383
  function connect(){
382
384
  if(mine!==view)return;
383
- term.options.disableStdin=true;
384
385
  var ws=new WebSocket((location.protocol==="https:"?"wss://":"ws://")+location.host+"/v1/terminals/"+id+"/ws",["bn-terminal","bn-bearer."+token]);socket=ws;
385
386
  var frames=Promise.resolve(),opened=false;
386
- ws.onopen=function(){if(mine!==view){ws.close();return;}opened=true;socketDown=false;window.bullseyeConnection.live();term.options.disableStdin=false;fitAddon.fit();ordered(id,"resize",{cols:term.cols,rows:term.rows});term.focus();};
387
+ ws.onopen=function(){if(mine!==view){ws.close();return;}opened=true;socketDown=false;window.bullseyeConnection.opened(function(){return socket===ws&&ws.readyState===WebSocket.OPEN;},window.bullseyeConnection.live);term.options.disableStdin=false;fitAddon.fit();ordered(id,"resize",{cols:term.cols,rows:term.rows});while(pending.length)ordered(id,"input",pending.shift());term.focus();};
387
388
  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);};
388
- ws.onclose=function(event){if(mine!==view)return;term.options.disableStdin=true;if(event.code===1000){socketDown=false;window.bullseyeConnection.live();note.textContent="CLI ended.";return;}if(event.code===1008){socketDown=true;window.bullseyeConnection.disconnected("the terminal connection to the CLI",event.reason+" — press Reattach or sign in again");note.textContent="Disconnected: "+event.reason+". Press Reattach or sign in again.";return;}socketDown=true;window.bullseyeConnection.reconnecting("the terminal connection to the CLI",1000);note.textContent="Disconnected. Reattaching to the same CLI…";if(opened){reconnect=setTimeout(connect,1000);return;}api("GET","/v1/terminals/"+id).then(function(){if(mine===view)reconnect=setTimeout(connect,1000);},function(error){if(mine!==view)return;if(error.status!==404){reconnect=setTimeout(connect,1000);return;}window.bullseyeConnection.disconnected("the terminal connection to the CLI","this CLI no longer exists — press Back to pick another");note.textContent="This CLI no longer exists. Press Back to pick another.";});};
389
- ws.onerror=function(){socketDown=true;window.bullseyeConnection.reconnecting("the terminal connection to the CLI",1000);note.textContent="Terminal connection failed. Reconnecting…";};
389
+ ws.onclose=function(event){if(mine!==view)return;var ending=event.code===1000||(event.code===1008&&event.reason==="Sign in again");if(ending){term.options.disableStdin=true;pending.length=0;}if(event.code===1000){socketDown=false;window.bullseyeConnection.live();note.textContent="CLI ended.";return;}if(event.code===1008&&event.reason==="Sign in again"){socketDown=false;window.bullseyeConnection.live();signIn("Your sign-in expired. Sign in again to return to this CLI.");return;}socketDown=true;var wait=opened?window.bullseyeConnection.closed(reattached):window.bullseyeConnection.failed();reattached=true;window.bullseyeConnection.reconnecting(WHAT,wait);note.textContent="Disconnected. Reattaching to the same CLI…";reconnect=setTimeout(findCli,wait);};
390
+ ws.onerror=function(){socketDown=true;note.textContent="Terminal connection failed. Reconnecting…";};
390
391
  }
392
+ // GATE: a reattach's read of its CLI that has not answered in this long is abandoned and asked again with backoff, so a dead link never leaves the page waiting on it
393
+ var FIND_MS=8000;
394
+ // GATE: opening the CLI again that has not answered in this long is abandoned and asked again with backoff; it covers a CLI's own start
395
+ var START_MS=30000;
396
+ function findCli(){
397
+ if(mine!==view)return;
398
+ api("GET","/v1/terminals/"+id,undefined,AbortSignal.timeout(FIND_MS)).then(connect,function(error){
399
+ if(mine!==view)return;
400
+ if(error.status!==404)return later();
401
+ api("POST","/v1/terminals",{conversation:id,cols:term.cols,rows:term.rows},AbortSignal.timeout(START_MS)).then(function(started){if(mine!==view)return;if(started.id!==id){swap("term",started.id);return;}connect();},function(failure){
402
+ if(mine!==view)return;
403
+ if(failure.status!==404)return later();
404
+ swap("term",id);
405
+ });
406
+ });
407
+ }
408
+ function later(){var wait=window.bullseyeConnection.failed();window.bullseyeConnection.reconnecting(WHAT,wait);reconnect=setTimeout(findCli,wait);}
391
409
  connect();
392
410
  }
393
411
  ${CONVERSATIONS_VIEWS}
@@ -3115,7 +3115,7 @@ function forceEntry(e, now, by, eventAt = now) {
3115
3115
  e.forcedBy = by;
3116
3116
  if (by === HIS_PRESS)
3117
3117
  e.startPressedAt = Math.max(e.startPressedAt ?? 0, eventAt);
3118
- e.why = `${by} ⚡ Force start starts it on the next pass, past a ⏸ Stop`;
3118
+ e.why = `${by} ⚡ Force start starts it on the next pass, past a ⏸ Stop and this workspace's lane limit`;
3119
3119
  step(e, now, "placed", e.why);
3120
3120
  }
3121
3121
  /** The provider refused to start a story's worker: its own words, which the entry carries and the queue starts again on its backoff. */
@@ -3178,6 +3178,49 @@ export function fenceStart(provider, what) {
3178
3178
  export const WAKE_BASE_MS = 60_000;
3179
3179
  // GATE: how many times the wait doubles — past it a parked worker is woken every WAKE_BASE_MS * 2^WAKE_DOUBLINGS (32 min)
3180
3180
  export const WAKE_DOUBLINGS = 5;
3181
+ // GATE: the free physical memory below which no story worker is started or woken — the story waits in line and starts on the first pass the box has this much free again
3182
+ export const START_MEMORY_FLOOR_BYTES = 1.5 * 2 ** 30;
3183
+ // GATE: the memory one started worker's process tree is taken to reach (the largest working tree measured), reserved out of the free reading for each worker started or woken within START_MEMORY_GROWTH_MS, whose growth that reading cannot see yet
3184
+ export const AGENT_TREE_BYTES = 830 * 2 ** 20;
3185
+ // GATE: how long a started worker's growth is reserved before the free reading is trusted to carry it
3186
+ export const START_MEMORY_GROWTH_MS = 2 * 60_000;
3187
+ /** 🔴 #4460 — the short word a story's row reads while the box's free memory holds its start; the numbers are its why, the row's tooltip. */
3188
+ export const MEMORY_WAIT_WORD = "⏳ waiting for memory";
3189
+ /** 🔴 #4460 — when this process started or woke a story worker, on every board it drives. */
3190
+ const recentStarts = [];
3191
+ const gib = (bytes) => (bytes / 2 ** 30).toFixed(1);
3192
+ /** 🔴 #4460 — why the box's memory holds a start or wake now — its free reading, less {@link AGENT_TREE_BYTES} for each worker started within {@link START_MEMORY_GROWTH_MS}, is below {@link START_MEMORY_FLOOR_BYTES} — or undefined when it is not. `trace` carries no figure that changes pass to pass. */
3193
+ function memoryHeldWhy(world, now) {
3194
+ // NULL-OK: field freeMemory is OPTIONAL and therefore it is ok to check for NULL
3195
+ if (world.freeMemory === undefined)
3196
+ return undefined;
3197
+ recentStarts.splice(0, recentStarts.length, ...recentStarts.filter((at) => at > now - START_MEMORY_GROWTH_MS));
3198
+ const growing = recentStarts.length;
3199
+ const free = world.freeMemory();
3200
+ if (free - growing * AGENT_TREE_BYTES >= START_MEMORY_FLOOR_BYTES)
3201
+ return undefined;
3202
+ const trace = `${MEMORY_WAIT_WORD}: the box's free memory is below the ${gib(START_MEMORY_FLOOR_BYTES)} GB floor, so no worker is started or woken until it frees`;
3203
+ const reserved = growing === 0 ? "" : `, less ${gib(growing * AGENT_TREE_BYTES)} GB still to grow in the ${growing} worker${growing === 1 ? "" : "s"} started in the last ${START_MEMORY_GROWTH_MS / 60_000} min`;
3204
+ return { trace, why: `${MEMORY_WAIT_WORD} — ${gib(free)} GB free${reserved}, below the ${gib(START_MEMORY_FLOOR_BYTES)} GB floor; it starts on the first pass the box has that much free again` };
3205
+ }
3206
+ /** 🔴 #4460 — the release the step of a start or wake carries when free memory was what last held it; a hold that another reason took over since carries none. */
3207
+ function memoryReleased(e, now) {
3208
+ const held = e.memoryHeld;
3209
+ // NULL-OK: field memoryHeld is OPTIONAL and therefore it is ok to check for NULL
3210
+ if (held === undefined)
3211
+ return "";
3212
+ delete e.memoryHeld;
3213
+ return held.why === e.why ? ` — free memory is back above the ${gib(START_MEMORY_FLOOR_BYTES)} GB floor after ${Math.round((now - held.since) / 60_000)}m held` : "";
3214
+ }
3215
+ /** 🔴 #4460 — holds `e` on the box's memory: {@link holdBack} puts its why on it and its trace once per hold, and `memoryHeld` keeps since when and that why; a hold that follows another reason is a new one. */
3216
+ function holdOnMemory(e, now, stage, why, trace, moved = false) {
3217
+ // NULL-OK: field memoryHeld is OPTIONAL and therefore it is ok to check for NULL
3218
+ const since = e.memoryHeld !== undefined && e.memoryHeld.why === e.why ? e.memoryHeld.since : undefined;
3219
+ // NULL-OK: field since is OPTIONAL and therefore it is ok to check for NULL
3220
+ holdBack(e, now, stage, why, moved || since === undefined, trace);
3221
+ // NULL-OK: field since is OPTIONAL and therefore it is ok to check for NULL
3222
+ e.memoryHeld = { since: since ?? now, why };
3223
+ }
3181
3224
  // GATE: how long a 🛑 Stop waits for its worker to reach a step boundary (end its turn) before its row says plainly that it has not — it is never killed by the wait, and keeps being asked
3182
3225
  export const STOP_STEP_BOUND_MS = 10 * 60_000;
3183
3226
  /** 🔴 #4216 — where a 🛑 Stop's ask for one session waits for that session's next tool call, which hands the agent the order (the PreToolUse hook reads this file). */
@@ -3978,6 +4021,18 @@ export async function driveStoryQueue(board, world, now) {
3978
4021
  // NULL-OK: field halted is OPTIONAL and therefore it is ok to check for NULL
3979
4022
  return e.forced === true ? manual : halted ?? manual;
3980
4023
  };
4024
+ // NULL-OK: field laneLimit is OPTIONAL and therefore it is ok to check for NULL
4025
+ const lanes = world.laneLimit?.();
4026
+ // NULL-OK: field lanes is OPTIONAL and therefore it is ok to check for NULL
4027
+ let running = lanes?.running ?? 0;
4028
+ /** 🔴 #4460 — a worker this pass started or woke, or whose start may have made one: it takes a lane, and its growth is reserved out of the free reading. */
4029
+ const workerMade = () => {
4030
+ recentStarts.push(now);
4031
+ running += 1;
4032
+ };
4033
+ /** 🔴 #4460 — why this workspace's lane limit holds the entry's start or wake now, or undefined: no limit is set, a lane is free, or his ⚡ Force start passes it. */
4034
+ // NULL-OK: field lanes is OPTIONAL and therefore it is ok to check for NULL
4035
+ const laneHeld = (e) => (lanes === undefined || e.forced === true || running < lanes.limit ? undefined : `⏳ ${running} lanes run, this workspace's limit is ${lanes.limit}`);
3981
4036
  for (const e of queueOrder(store)) {
3982
4037
  try {
3983
4038
  const sessionId = wakeable.get(e);
@@ -4016,9 +4071,25 @@ export async function driveStoryQueue(board, world, now) {
4016
4071
  save();
4017
4072
  continue;
4018
4073
  }
4074
+ const full = laneHeld(e);
4075
+ // NULL-OK: field full is OPTIONAL and therefore it is ok to check for NULL
4076
+ if (full !== undefined) {
4077
+ unwoken(`its worker ${parked.jobId} is parked, and ${full}`);
4078
+ continue;
4079
+ }
4080
+ const lowMemory = memoryHeldWhy(world, now);
4081
+ // NULL-OK: field lowMemory is OPTIONAL and therefore it is ok to check for NULL
4082
+ if (lowMemory !== undefined) {
4083
+ const moved = e.state !== "queued";
4084
+ e.state = "queued";
4085
+ holdOnMemory(e, now, "parked", `its worker ${parked.jobId} is parked, and ${lowMemory.why}`, `its worker is parked, and ${lowMemory.trace}`, moved);
4086
+ continue;
4087
+ }
4088
+ const released = memoryReleased(e, now);
4019
4089
  const wakes = (parked.wakes ?? 0) + 1;
4020
4090
  try {
4021
4091
  const woken = await world.wake(e, board, sessionId, wakeMessage(e.storyId), worker => { e.worker = worker; save(); });
4092
+ workerMade();
4022
4093
  e.landedAt = now;
4023
4094
  // NULL-OK: field cwd is OPTIONAL and therefore it is ok to check for NULL
4024
4095
  e.worker = { ...woken, wakes, ...(woken.provider === parked.provider && woken.jobId === parked.jobId ? keptSession(parked) : {}), ...(parked.cwd === undefined ? {} : { cwd: parked.cwd }) };
@@ -4030,7 +4101,7 @@ export async function driveStoryQueue(board, world, now) {
4030
4101
  }
4031
4102
  e.state = "running";
4032
4103
  e.why = `its ${woken.provider} worker ${woken.jobId} was woken in its own session (wake ${wakes})`;
4033
- step(e, now, "woken", e.why);
4104
+ step(e, now, "woken", e.why + released);
4034
4105
  }
4035
4106
  catch (err) {
4036
4107
  if (!(err instanceof WorkerNotStarted))
@@ -4043,6 +4114,7 @@ export async function driveStoryQueue(board, world, now) {
4043
4114
  continue;
4044
4115
  }
4045
4116
  if (err instanceof WorkerStartUnconfirmed) {
4117
+ workerMade();
4046
4118
  e.worker = { ...(e.worker ?? parked), startedAt: now, wakes };
4047
4119
  delete e.worker.parkedAt;
4048
4120
  noteStartUnconfirmed(e, e.worker, err.message, err.deadlineAt, Date.now());
@@ -4076,6 +4148,7 @@ export async function driveStoryQueue(board, world, now) {
4076
4148
  // NULL-OK: field after is OPTIONAL and therefore it is ok to check for NULL
4077
4149
  if (after !== undefined && after.alive && (after.parked === undefined || after.parked.live)) {
4078
4150
  // OWNER: ITER/LOOP — the wake's answer was lost (a timeout on a busy box) but a process now runs the worker's session, so the wake landed: the entry keeps that worker and no second one is started; the next entry is read.
4151
+ workerMade();
4079
4152
  e.worker = { provider: parked.provider, startedAt: now, jobId: parked.jobId, wakes, ...keptSession(parked) };
4080
4153
  e.landedAt = now;
4081
4154
  e.state = "running";
@@ -4086,6 +4159,7 @@ export async function driveStoryQueue(board, world, now) {
4086
4159
  }
4087
4160
  else if (!err.unsent) {
4088
4161
  // OWNER: ITER/LOOP — the wake's answer was lost and no process is known to run the session (none has recorded it, or its transcript could not be read), so the worker stays parked and is read again next pass; it is never ended on a missing answer, which would start a second worker beside a wake that landed late; the next entry is read.
4162
+ workerMade();
4089
4163
  e.worker = { ...parked, startedAt: now, parkedAt: now, wakes };
4090
4164
  e.state = "queued";
4091
4165
  delete e.forced;
@@ -4167,6 +4241,19 @@ export async function driveStoryQueue(board, world, now) {
4167
4241
  const forced = e.forced === true && (halted !== undefined || unscheduled !== undefined);
4168
4242
  // NULL-OK: field halted is OPTIONAL and therefore it is ok to check for NULL
4169
4243
  const forcedPast = halted !== undefined ? "the queue's ⏸ Stop" : "AUTO START being off";
4244
+ const full = laneHeld(e);
4245
+ // NULL-OK: field full is OPTIONAL and therefore it is ok to check for NULL
4246
+ if (full !== undefined) {
4247
+ holdBack(e, now, "held-back", full);
4248
+ continue;
4249
+ }
4250
+ const lowMemory = memoryHeldWhy(world, now);
4251
+ // NULL-OK: field lowMemory is OPTIONAL and therefore it is ok to check for NULL
4252
+ if (lowMemory !== undefined) {
4253
+ holdOnMemory(e, now, "held-back", lowMemory.why, lowMemory.trace);
4254
+ continue;
4255
+ }
4256
+ const released = memoryReleased(e, now);
4170
4257
  if (e.forced === true)
4171
4258
  delete e.accountRefusals;
4172
4259
  delete e.forced;
@@ -4175,13 +4262,14 @@ export async function driveStoryQueue(board, world, now) {
4175
4262
  e.attempts += 1;
4176
4263
  delete e.accountRefused;
4177
4264
  dropWorker(e);
4178
- step(e, now, "selected", `start ${e.attempts}${e.attempts > WORKER_ATTEMPTS ? ", past the attempts a story is given" : ` of ${WORKER_ATTEMPTS}`}${forced ? ` — ${forcer} ⚡ Force start, past ${forcedPast}` : ""}`);
4265
+ step(e, now, "selected", `start ${e.attempts}${e.attempts > WORKER_ATTEMPTS ? ", past the attempts a story is given" : ` of ${WORKER_ATTEMPTS}`}${forced ? ` — ${forcer} ⚡ Force start, past ${forcedPast}` : ""}${released}`);
4179
4266
  save();
4180
4267
  try {
4181
4268
  e.worker = await world.launch(e, board, (sent) => {
4182
4269
  e.worker = sent;
4183
4270
  save();
4184
4271
  });
4272
+ workerMade();
4185
4273
  e.provider = "auto";
4186
4274
  e.landedAt = now;
4187
4275
  if (noteCarried(e, { alive: true, why: "", carried: e.worker.carried }, now)) {
@@ -4195,6 +4283,7 @@ export async function driveStoryQueue(board, world, now) {
4195
4283
  if (!(err instanceof WorkerNotStarted))
4196
4284
  throw err;
4197
4285
  if (err instanceof WorkerStartUnconfirmed && e.worker !== undefined) {
4286
+ workerMade();
4198
4287
  noteStartUnconfirmed(e, e.worker, err.message, err.deadlineAt, Date.now());
4199
4288
  continue;
4200
4289
  }
@@ -4210,6 +4299,7 @@ export async function driveStoryQueue(board, world, now) {
4210
4299
  // NULL-OK: field found is OPTIONAL and therefore it is ok to check for NULL
4211
4300
  if (made.alive && made.found !== undefined) {
4212
4301
  // OWNER: ITER/LOOP — the start answered no job id, yet the provider made the story's job: that job is the entry's worker, so no second one is started.
4302
+ workerMade();
4213
4303
  e.worker = made.found;
4214
4304
  e.landedAt = now;
4215
4305
  e.why = `its ${made.found.provider} worker ${made.found.jobId} runs, though its start answered: ${err.message}`;
@@ -4297,7 +4387,7 @@ export async function pressStory(board, storyId, press, now, by, requestHandledB
4297
4387
  if (working)
4298
4388
  throw new StoryPressRefused(`#${storyId} already has a worker at work, so there is nothing to force`);
4299
4389
  forceEntry(e, now, by);
4300
- did = `#${storyId} starts on the next pass, past a ⏸ Stop`;
4390
+ did = `#${storyId} starts on the next pass, past a ⏸ Stop and this workspace's lane limit`;
4301
4391
  }
4302
4392
  else if (press === "stop" || press === "kill") {
4303
4393
  if (e.worker === undefined || !(working || parkedInLine(e) || e.worker.carried !== undefined || ownerAction !== undefined))
@@ -144,7 +144,7 @@ export function createClaudeDriver(runtime) {
144
144
  throw spec.failures.fail(`Claude Code has not been trusted in ${spec.project}, so its CLI would stop on "Do you trust this folder?" before reading any message — run claude in that folder once and answer "Yes, I trust this folder", then send the message again`);
145
145
  super(spec, claudeProvider, spec.started || transcriptWritten(spec.sessionId), runtime);
146
146
  const hook = [{ hooks: [{ type: "http", url: `http://127.0.0.1:${hookPort()}${CLAUDE_HOOK_PATH}${this.key}` }] }];
147
- const settings = JSON.stringify({ hooks: Object.fromEntries(HOOKED.map((name) => [name, hook])) });
147
+ const settings = JSON.stringify({ viewMode: "focus", hooks: Object.fromEntries(HOOKED.map((name) => [name, hook])) });
148
148
  sessions.set(this.key, (event) => this.hook(event));
149
149
  // #4157 — at the workspace root no project's CLAUDE.md sits in the CLI's own folder chain, so every listed project is added and its rules loaded: the root session then routes each prompt as the project's own rules say.
150
150
  const atRoot = runtime.store.isRootFolder(spec.project);
@@ -154,7 +154,7 @@ export function createClaudeDriver(runtime) {
154
154
  ...(spec.title === undefined ? [] : ["--name", spec.title]),
155
155
  ...(this.resumes ? ["--resume", spec.sessionId] : ["--session-id", spec.sessionId]),
156
156
  "--permission-mode", "bypassPermissions", "--disallowedTools", BN_REACHES_HIM_ON_THE_PAGE, "--settings", settings,
157
- ], atRoot ? { CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD: "1" } : undefined);
157
+ ], { CLAUDE_CODE_NO_FLICKER: "1", ...(atRoot ? { CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD: "1" } : {}) });
158
158
  let draw;
159
159
  this.drawn = new Promise((resolve) => { draw = resolve; });
160
160
  this.terminal.onOutput(() => draw());
@@ -987,7 +987,8 @@ class WebHost {
987
987
  }
988
988
  // NULL-OK: field remembered is OPTIONAL and therefore it is ok to check for NULL
989
989
  if (remembered !== undefined && new URL(remembered, "http://localhost").searchParams.get("scope") !== "all") {
990
- return send(response, 302, MIME[".txt"], `moved to ${remembered}`, { Location: remembered, "Cache-Control": "no-store" });
990
+ const moved = url.searchParams.has("bullseye-framed") ? `${remembered}${remembered.includes("?") ? "&" : "?"}bullseye-framed=1` : remembered;
991
+ return send(response, 302, MIME[".txt"], `moved to ${moved}`, { Location: moved, "Cache-Control": "no-store" });
991
992
  }
992
993
  return this.serveDocument(page, response);
993
994
  }
@@ -1351,6 +1352,7 @@ function closedPage(extension, page) {
1351
1352
  function connect() {
1352
1353
  var opened = false;
1353
1354
  var socket = new WebSocket((location.protocol === "https:" ? "wss:" : "ws:") + "//" + location.host + "/__bullseye/ws?page=${encodeURIComponent(page.name)}&peek=1");
1355
+ setTimeout(function () { if (socket.readyState === 0) socket.close(); }, 10000);
1354
1356
  socket.addEventListener("open", function () {
1355
1357
  opened = true;
1356
1358
  var mine = socket;
@@ -1361,12 +1363,11 @@ function closedPage(extension, page) {
1361
1363
  fetch("/__bullseye/health", { cache: "no-store" }).then(function (r) { return r.json(); }).then(function (health) { if (health.pages[${JSON.stringify(page.name)}].live) location.reload(); });
1362
1364
  });
1363
1365
  socket.addEventListener("message", function (event) { if (JSON.parse(String(event.data)).type === "reload") location.reload(); });
1364
- socket.addEventListener("close", function () { if (opened) { var w = window.bullseyeConnection.closed(reconnected); reconnected = true; window.bullseyeConnection.reconnecting(WHAT, w); setTimeout(awaitHost, w); } else if (reconnected) { var refused = window.bullseyeConnection.failed(); window.bullseyeConnection.reconnecting(WHAT, refused); setTimeout(awaitHost, refused); } else { window.bullseyeConnection.disconnected(WHAT, "the host did not accept the connection — reload this page to try again"); document.getElementById("said").textContent = "⚠️ This page could not reach its host, so it cannot load the page when it opens — reload it to try again"; } });
1366
+ socket.addEventListener("close", function () { if (opened) { var w = window.bullseyeConnection.closed(reconnected); reconnected = true; window.bullseyeConnection.reconnecting(WHAT, w); document.getElementById("said").textContent = "⏳ This page's host is not answering — this page reconnects the moment it does"; setTimeout(awaitHost, w); } else { var refused = window.bullseyeConnection.failed(); window.bullseyeConnection.reconnecting(WHAT, refused); document.getElementById("said").textContent = "⏳ This page's host did not accept its connection — this page tries again by itself"; setTimeout(awaitHost, refused); } });
1365
1367
  }
1366
1368
  function awaitHost() {
1367
1369
  window.bullseyeConnection.reconnecting(WHAT, 250);
1368
- document.getElementById("said").textContent = "⏳ This page's host is not answering — this page reconnects the moment it does";
1369
- fetch("/__bullseye/health", { cache: "no-store" }).then(function (r) { if (r.ok) { connect(); } else if (r.status === 401) location.assign("/"); else setTimeout(awaitHost, 250); }, function () { setTimeout(awaitHost, 250); });
1370
+ fetch("/__bullseye/health", { cache: "no-store", signal: AbortSignal.timeout(8000) }).then(function (r) { if (r.ok) { connect(); } else if (r.status === 401) window.bullseyeConnection.signInAgain(); else setTimeout(awaitHost, 250); }, function () { setTimeout(awaitHost, 250); });
1370
1371
  }
1371
1372
  connect();
1372
1373
  })();</script></body></html>`;
@@ -278,8 +278,8 @@ const CONNECTION_SOURCE = String.raw `(function () {
278
278
  return;
279
279
  }
280
280
  var COVER = "__bullseye-connection";
281
- var MARKS = { reconnecting: "🔄 RECONNECTING", disconnected: "🔴 DISCONNECTED", live: "✅ LIVE" };
282
- var COLOURS = { reconnecting: "#7a5200", disconnected: "#8a1f1f", live: "#1d5a2c" };
281
+ var MARKS = { reconnecting: "🔄 RECONNECTING", live: "✅ LIVE" };
282
+ var COLOURS = { reconnecting: "#7a5200", live: "#1d5a2c" };
283
283
  var current = null;
284
284
  var ticker = 0;
285
285
  var clearer = 0;
@@ -294,8 +294,6 @@ const CONNECTION_SOURCE = String.raw `(function () {
294
294
  var lines = ["What dropped: " + current.what, "Since: " + clock(current.since) + " (" + Math.round((now - current.since) / 1000) + " s ago)"];
295
295
  if (current.state === "reconnecting" && current.retryAt !== undefined) {
296
296
  lines.push("Next retry: " + (current.retryAt > now ? "in " + Math.ceil((current.retryAt - now) / 1000) + " s" : "now"));
297
- } else if (current.state === "disconnected") {
298
- lines.push("Next retry: none — " + (current.why || "reload this page to try again"));
299
297
  } else if (current.state === "live") {
300
298
  lines.push("Live again after " + Math.round((now - current.since) / 1000) + " s");
301
299
  }
@@ -401,8 +399,9 @@ const CONNECTION_SOURCE = String.raw `(function () {
401
399
  reconnecting: function (what, retryInMs) {
402
400
  show("reconnecting", what, { retryAt: Date.now() + retryInMs });
403
401
  },
404
- disconnected: function (what, why) {
405
- show("disconnected", what, { why: why });
402
+ signInAgain: function () {
403
+ window.sessionStorage.setItem("bullseye-return-to", window.location.pathname + window.location.search + window.location.hash);
404
+ window.location.assign("/");
406
405
  },
407
406
  live: function () {
408
407
  if (current === null || current.state === "live") {
@@ -456,7 +455,7 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
456
455
  var WHAT = "this page's live connection to its service";
457
456
  // GATE: one health read is abandoned after this times the square of the tries so far (capped at 8000), then asked again
458
457
  var ANSWER_MS = 700;
459
- // GATE: how long a reopened socket may stay connecting before it is given up and the host is asked again, times the give-ups in a row (capped at 30000)
458
+ // GATE: how long a socket may stay connecting, or its sign-in check go unanswered, before it is given up and asked again, times the give-ups in a row (capped at 30000)
460
459
  var CONNECT_MS = 5000;
461
460
  var healthTries = 0;
462
461
  var lastHeard = Date.now();
@@ -473,19 +472,25 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
473
472
  awaitHost();
474
473
  }
475
474
 
475
+ function askAgainLater() {
476
+ var wait = window.bullseyeConnection.failed();
477
+ window.bullseyeConnection.reconnecting(WHAT, wait);
478
+ window.setTimeout(awaitHost, wait);
479
+ }
480
+
476
481
  function unreached(err) {
477
482
  if (err.name === "AbortError") {
478
483
  awaitHost();
479
484
  } else if (err instanceof TypeError) {
480
485
  window.setTimeout(awaitHost, 250);
481
486
  } else {
482
- window.bullseyeConnection.disconnected(WHAT, "the host answered its health read with something that is not its own reply — reload this page to try again");
487
+ askAgainLater();
483
488
  }
484
489
  }
485
490
 
486
491
  function reconnectOrReload(health) {
487
492
  if (health.pages === undefined) {
488
- window.bullseyeConnection.disconnected(WHAT, "the host answered its health read with something that is not its own reply — reload this page to try again");
493
+ askAgainLater();
489
494
  return;
490
495
  }
491
496
  var served = health.pages[page];
@@ -516,7 +521,7 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
516
521
  window.clearTimeout(abandon);
517
522
  healthTries = 0;
518
523
  if (response.status === 401) {
519
- window.location.assign("/");
524
+ window.bullseyeConnection.signInAgain();
520
525
  } else {
521
526
  window.setTimeout(awaitHost, 250);
522
527
  }
@@ -530,18 +535,15 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
530
535
  var scheme = window.location.protocol === "https:" ? "wss:" : "ws:";
531
536
  var mine = new WebSocket(scheme + "//" + window.location.host + "/__bullseye/ws?page=" + encodeURIComponent(page) + "&at=" + encodeURIComponent(window.location.search) + "&drawn=" + encodeURIComponent(drawn) + (new URLSearchParams(window.location.search).get("bullseye-peek") === null ? "" : "&peek=1"));
532
537
  socket = mine;
533
- if (reconnects > 0) {
534
- window.setTimeout(function () {
535
- if (socket === mine && mine.readyState === 0) {
536
- window.bullseyeConnection.failed();
537
- socket = null;
538
- mine.close();
539
- awaitHost();
540
- }
541
- }, Math.min(CONNECT_MS * (window.bullseyeConnection.attempts() + 1), 30000));
542
- }
543
538
  var opened = false;
544
539
  var reopened = reconnects > 0;
540
+ window.setTimeout(function () {
541
+ if (socket === mine && mine.readyState === 0) {
542
+ socket = null;
543
+ mine.close();
544
+ notAccepted(reopened);
545
+ }
546
+ }, Math.min(CONNECT_MS * (window.bullseyeConnection.attempts() + 1), 30000));
545
547
  mine.addEventListener("open", function () {
546
548
  opened = true;
547
549
  lastHeard = Date.now();
@@ -555,11 +557,9 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
555
557
  while (queue.length > 0) {
556
558
  mine.send(queue.shift());
557
559
  }
558
- if (reconnects > 0) {
559
- window.bullseyeConnection.opened(function () {
560
- return socket === mine && mine.readyState === 1;
561
- }, window.bullseyeConnection.live);
562
- }
560
+ window.bullseyeConnection.opened(function () {
561
+ return socket === mine && mine.readyState === 1;
562
+ }, window.bullseyeConnection.live);
563
563
  });
564
564
  mine.binaryType = "blob";
565
565
  var unpacking = Promise.resolve();
@@ -615,19 +615,25 @@ const SHIM_SOURCE = CONNECTION_SOURCE + ";" + String.raw `(function () {
615
615
  window.setTimeout(awaitHost, wait);
616
616
  return;
617
617
  }
618
- if (reopened) {
619
- var refusedWait = window.bullseyeConnection.failed();
620
- window.bullseyeConnection.reconnecting(WHAT, refusedWait);
621
- window.setTimeout(awaitHost, refusedWait);
622
- return;
618
+ notAccepted(reopened);
619
+ });
620
+ }
621
+
622
+ function notAccepted(reopened) {
623
+ var wait = window.bullseyeConnection.failed();
624
+ window.bullseyeConnection.reconnecting(WHAT, wait);
625
+ window.setTimeout(reopened ? awaitHost : openUnlessSignedOut, wait);
626
+ }
627
+
628
+ function openUnlessSignedOut() {
629
+ window.fetch("/__bullseye/health", { cache: "no-store", signal: AbortSignal.timeout(Math.min(CONNECT_MS * (window.bullseyeConnection.attempts() + 1), 30000)) }).then(function (response) {
630
+ if (response.status === 401) {
631
+ window.bullseyeConnection.signInAgain();
632
+ } else {
633
+ open();
623
634
  }
624
- window.fetch("/__bullseye/health", { cache: "no-store" }).then(function (response) {
625
- if (response.ok) {
626
- window.bullseyeConnection.disconnected(WHAT, "the host did not accept the connection — reload this page to try again");
627
- } else {
628
- awaitHost();
629
- }
630
- }, awaitHost);
635
+ }, function () {
636
+ notAccepted(false);
631
637
  });
632
638
  }
633
639
 
@@ -155,6 +155,9 @@ class SettingsMoved extends Error {
155
155
  /** Another process held a settings file's write lock for the whole wait, and its pid is alive: nothing was written, the writer tries again. */
156
156
  class SettingsLocked extends Error {
157
157
  }
158
+ /** A folder that is not on the workspace list, or left it after the list was read: it has no settings to read or write. */
159
+ class WorkspaceNotListed extends TypeError {
160
+ }
158
161
  /** The settings file of `tool` for a LISTED workspace — a folder off the list, a worktree included, is refused by name. */
159
162
  function settingsFile(root, tool) {
160
163
  if (typeof tool !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(tool))
@@ -164,7 +167,7 @@ function settingsFile(root, tool) {
164
167
  return home;
165
168
  const listed = workspacesHere().find((w) => sameRoot(w.root, root));
166
169
  if (listed === undefined)
167
- throw new TypeError(`${root} is not a workspace on this machine's list (${workspacesFile()}) — settings are kept only for a listed workspace`);
170
+ throw new WorkspaceNotListed(`${root} is not a workspace on this machine's list (${workspacesFile()}) — settings are kept only for a listed workspace`);
168
171
  return store().settingsFileOf(listed, tool);
169
172
  }
170
173
  const digest = (bytes) => crypto.createHash("sha256").update(bytes).digest("hex");
@@ -249,21 +252,24 @@ function savedAutoStart(root) {
249
252
  }
250
253
  if (!listed)
251
254
  throw new AutoStartUnread(`${root} is not a listed workspace — cannot save AUTO START here, so it runs for no board in this folder; add the folder on Bullseye Control`);
252
- let saved;
255
+ let read;
253
256
  try {
254
- saved = readSettings(root, "bb").settings.autoStart;
257
+ read = readSettings(root, "bb");
255
258
  }
256
259
  catch (err) {
257
260
  if (err instanceof SettingsUndefined)
258
261
  return undefined;
262
+ if (err instanceof WorkspaceNotListed)
263
+ throw new AutoStartUnread(`${root} left the workspace list while its AUTO START was read, so it runs for no board in this folder until the folder is listed again`);
259
264
  if (err instanceof SyntaxError)
260
265
  throw new AutoStartUnread(`AUTO START cannot be read — ${err.message}`);
261
266
  throw err;
262
267
  }
268
+ const saved = read.settings.autoStart;
263
269
  // NULL-OK: field autoStart is OPTIONAL and therefore it is ok to check for NULL
264
270
  if (saved === undefined || typeof saved === "boolean")
265
271
  return saved;
266
- throw new AutoStartUnread(`${settingsFile(root, "bb")} holds settings.autoStart ${JSON.stringify(saved)}, which is not true or false — fix the file`);
272
+ throw new AutoStartUnread(`${read.file} holds settings.autoStart ${JSON.stringify(saved)}, which is not true or false — fix the file`);
267
273
  }
268
274
  /** "" while the board at `root` would start work on its own — AUTO START saved on, or never saved — else why it would not. */
269
275
  function autoStartOff(root) {
@@ -682,4 +688,4 @@ function savedSettings(tool) {
682
688
  throw err;
683
689
  }
684
690
  }
685
- module.exports = { vscRoot, workspacesFile, publishWorkspaces, WorkspacesUndefined, listedWorkspaces, workspacesHere, listBase, saveWorkspaces, sameRoot, SettingsUndefined, SettingsMoved, SettingsLocked, settingsFile, readSettings, savedSettings, AutoStartUnread, savedAutoStart, autoStartOff, toolHome, settingsBase, writeSettings, setSettings, publishSettings, alive };
691
+ module.exports = { vscRoot, workspacesFile, publishWorkspaces, WorkspacesUndefined, listedWorkspaces, workspacesHere, listBase, saveWorkspaces, sameRoot, SettingsUndefined, SettingsMoved, SettingsLocked, WorkspaceNotListed, settingsFile, readSettings, savedSettings, AutoStartUnread, savedAutoStart, autoStartOff, toolHome, settingsBase, writeSettings, setSettings, publishSettings, alive };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.409",
3
+ "version": "1.3.413",
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))