@thoth-agents/pi-junie-bridge 0.1.0 → 0.1.1

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.1.1] - 2026-11-15
6
+
7
+ ### Fixed
8
+
9
+ - Windows Job teardown waits for the Junie leader's exit notification before
10
+ releasing the Job, avoiding working-directory locks (`EBUSY`) after shutdown.
11
+ A missing notification is bounded and reported rather than blocking teardown.
12
+
5
13
  ## [0.1.0] - 2026-11-15
6
14
 
7
15
  ### Added
package/dist/index.ts CHANGED
@@ -7412,8 +7412,23 @@ async function launchJunie(options = {}) {
7412
7412
  ...owned,
7413
7413
  jobBacked: true,
7414
7414
  terminate: () => termination ??= (async () => {
7415
- await owned.terminate(3e3);
7416
- await owned.release();
7415
+ let timer;
7416
+ try {
7417
+ await owned.terminate(3e3);
7418
+ const observed = await Promise.race([
7419
+ owned.exited.then(() => true),
7420
+ new Promise((resolve3) => {
7421
+ timer = setTimeout(() => resolve3(false), 3e3);
7422
+ })
7423
+ ]);
7424
+ if (!observed)
7425
+ (options.warn ?? console.warn)(
7426
+ "Junie Windows job exit notification timed out after 3000ms; the empty job will be released."
7427
+ );
7428
+ } finally {
7429
+ clearTimeout(timer);
7430
+ await owned.release();
7431
+ }
7417
7432
  })()
7418
7433
  };
7419
7434
  } else {
package/dist/launcher.cs CHANGED
@@ -1,180 +1,180 @@
1
- // Windows Job Object containment. Compiled once per persistent PowerShell helper.
2
- using System;
3
- using System.Collections.Generic;
4
- using System.ComponentModel;
5
- using System.Runtime.InteropServices;
6
- using System.Text;
7
- using System.Threading;
8
-
9
- public static class ThothJobLauncher
10
- {
11
- const uint INFINITE = 0xffffffff;
12
- static readonly Dictionary<string, Container> Jobs = new Dictionary<string, Container>();
13
- static IntPtr parent;
14
- sealed class Container { public IntPtr Job, Process; public uint Pid; public IntPtr[] Pipes; }
15
- [StructLayout(LayoutKind.Sequential)] struct Security { public int Length; public IntPtr Descriptor; public int Inherit; }
16
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct Startup {
17
- public int cb; public string Reserved, Desktop, Title;
18
- public uint X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
19
- public ushort ShowWindow, Reserved2; public IntPtr ReservedPtr, StdInput, StdOutput, StdError;
20
- }
21
- [StructLayout(LayoutKind.Sequential)] struct StartupEx { public Startup Startup; public IntPtr Attributes; }
22
- [StructLayout(LayoutKind.Sequential)] struct ProcessInfo { public IntPtr Process, Thread; public uint ProcessId, ThreadId; }
23
- [StructLayout(LayoutKind.Sequential)] struct BasicLimits {
24
- public long ProcessTime, JobTime; public uint Flags;
25
- public UIntPtr MinWorkingSet, MaxWorkingSet; public uint ActiveProcessLimit;
26
- public UIntPtr Affinity; public uint PriorityClass, SchedulingClass;
27
- }
28
- [StructLayout(LayoutKind.Sequential)] struct IoCounters { public ulong ReadCount, WriteCount, OtherCount, ReadBytes, WriteBytes, OtherBytes; }
29
- [StructLayout(LayoutKind.Sequential)] struct ExtendedLimits {
30
- public BasicLimits Basic; public IoCounters Io;
31
- public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
32
- }
33
- [StructLayout(LayoutKind.Sequential)] struct Accounting {
34
- public long UserTime, KernelTime, PeriodUserTime, PeriodKernelTime;
35
- public uint PageFaults, TotalProcesses, ActiveProcesses, TerminatedProcesses;
36
- }
37
- [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateJobObjectW(IntPtr attributes, string name);
38
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetInformationJobObject(IntPtr job, int kind, ref ExtendedLimits info, uint size);
39
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool QueryInformationJobObject(IntPtr job, int kind, out Accounting info, uint size, IntPtr returned);
40
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateJobObject(IntPtr job, uint code);
41
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool CloseHandle(IntPtr handle);
42
- [DllImport("kernel32.dll", SetLastError=true)] static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
43
- [DllImport("kernel32.dll", SetLastError=true)] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
44
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
45
- [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern bool CreateProcessW(string application, StringBuilder command, IntPtr processAttributes, IntPtr threadAttributes, bool inherit, uint flags, IntPtr environment, string cwd, ref StartupEx startup, out ProcessInfo info);
46
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool InitializeProcThreadAttributeList(IntPtr attributes, int count, uint flags, ref IntPtr size);
47
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool UpdateProcThreadAttribute(IntPtr attributes, uint flags, IntPtr attribute, IntPtr value, IntPtr size, IntPtr previous, IntPtr returned);
48
- [DllImport("kernel32.dll")] static extern void DeleteProcThreadAttributeList(IntPtr attributes);
49
-
50
- [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern bool ConvertStringSecurityDescriptorToSecurityDescriptorW(string text, uint revision, out IntPtr descriptor, out uint size);
51
- [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr memory);
52
- [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateNamedPipeW(string name, uint mode, uint pipeMode, uint instances, uint outputSize, uint inputSize, uint timeout, ref Security security);
53
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool ConnectNamedPipe(IntPtr pipe, IntPtr overlapped);
54
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetNamedPipeHandleState(IntPtr pipe, ref uint mode, IntPtr maximum, IntPtr timeout);
55
- static readonly object OutputLock = new object();
56
- public static void Emit(string json) { lock (OutputLock) { Console.WriteLine(json); Console.Out.Flush(); } }
57
- static void Check(bool ok, string operation) { if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error(), operation); }
58
- static IntPtr Handle(IntPtr handle, string operation) { if (handle == IntPtr.Zero || handle == new IntPtr(-1)) throw new Win32Exception(Marshal.GetLastWin32Error(), operation); return handle; }
59
- public static void WatchParent(int pid) {
60
- parent = Handle(OpenProcess(0x100000, false, pid), "OpenProcess(parent)");
61
- var watcher = new Thread(() => { WaitForSingleObject(parent, INFINITE); Environment.Exit(0); });
62
- watcher.IsBackground = true; watcher.Start();
63
- }
64
- public static string[] Prepare(string key) {
65
- if (key.Length != 32 || System.Text.RegularExpressions.Regex.IsMatch(key, "[^a-f0-9]")) throw new ArgumentException("Invalid key");
66
- if (Jobs.ContainsKey(key)) throw new ArgumentException("Duplicate key");
67
- var container = new Container { Pipes = new IntPtr[3] };
68
- IntPtr descriptor = IntPtr.Zero;
69
- try {
70
- container.Job = Handle(CreateJobObjectW(IntPtr.Zero, null), "CreateJobObjectW");
71
- var limits = new ExtendedLimits(); limits.Basic.Flags = 0x2000;
72
- Check(SetInformationJobObject(container.Job, 9, ref limits, (uint)Marshal.SizeOf(typeof(ExtendedLimits))), "SetInformationJobObject");
73
- string sid = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
74
- uint size;
75
- // Protected DACL, one ACE, no Everyone/anonymous/admin grants.
76
- Check(ConvertStringSecurityDescriptorToSecurityDescriptorW("D:P(A;;GA;;;" + sid + ")", 1, out descriptor, out size), "Pipe DACL");
77
- var security = new Security { Length = Marshal.SizeOf(typeof(Security)), Descriptor = descriptor, Inherit = 1 };
78
- string[] names = new string[3];
79
- string[] suffixes = { "stdin", "stdout", "stderr" };
80
- for (int i = 0; i < 3; i++) {
81
- names[i] = "\\\\.\\pipe\\thoth-job-" + key + "-" + suffixes[i];
82
- // Node net.Socket opens duplex handles. Unused directions stay idle.
83
- // FIRST_PIPE_INSTANCE; NOWAIT only for bounded connect, then WAIT.
84
- container.Pipes[i] = Handle(CreateNamedPipeW(names[i], 0x80000u | 3u, 0x9, 1, 65536, 65536, 10000, ref security), "CreateNamedPipeW");
85
- }
86
- Jobs.Add(key, container); return names;
87
- } catch { Dispose(container); throw; }
88
- finally { if (descriptor != IntPtr.Zero) LocalFree(descriptor); }
89
- }
90
- static Container Find(string key) { Container c; if (!Jobs.TryGetValue(key, out c)) throw new ArgumentException("Unknown job key"); return c; }
91
- public static uint Start(string key, string executable, string command, string cwd, string[] env) {
92
- var c = Find(key);
93
- IntPtr attributes = IntPtr.Zero, handles = IntPtr.Zero, jobValue = IntPtr.Zero, environment = IntPtr.Zero;
94
- bool initialized = false; ProcessInfo pi = new ProcessInfo();
95
- try {
96
- if (c.Process != IntPtr.Zero) throw new InvalidOperationException("Already started");
97
- var deadline = System.Diagnostics.Stopwatch.StartNew();
98
- foreach (IntPtr pipe in c.Pipes) {
99
- while (!ConnectNamedPipe(pipe, IntPtr.Zero)) {
100
- int error = Marshal.GetLastWin32Error();
101
- if (error == 535) break; // client connected before ConnectNamedPipe
102
- if (error != 536) throw new Win32Exception(error, "ConnectNamedPipe error=" + error);
103
- if (deadline.ElapsedMilliseconds >= 10000) throw new TimeoutException("Pipe connect timeout");
104
- Thread.Sleep(10);
105
- }
106
- uint mode = 0;
107
- Check(SetNamedPipeHandleState(pipe, ref mode, IntPtr.Zero, IntPtr.Zero), "SetNamedPipeHandleState(WAIT)");
108
- }
109
- IntPtr size = IntPtr.Zero;
110
- InitializeProcThreadAttributeList(IntPtr.Zero, 2, 0, ref size);
111
- attributes = Marshal.AllocHGlobal(size);
112
- Check(InitializeProcThreadAttributeList(attributes, 2, 0, ref size), "InitializeProcThreadAttributeList"); initialized = true;
113
- handles = Marshal.AllocHGlobal(IntPtr.Size * 3);
114
- for (int i = 0; i < 3; i++) Marshal.WriteIntPtr(handles, IntPtr.Size * i, c.Pipes[i]);
115
- Check(UpdateProcThreadAttribute(attributes, 0, new IntPtr(0x20002), handles, new IntPtr(IntPtr.Size * 3), IntPtr.Zero, IntPtr.Zero), "HANDLE_LIST");
116
- jobValue = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(jobValue, c.Job);
117
- Check(UpdateProcThreadAttribute(attributes, 0, new IntPtr(0x2000D), jobValue, new IntPtr(IntPtr.Size), IntPtr.Zero, IntPtr.Zero), "JOB_LIST");
118
- var startup = new StartupEx { Attributes = attributes };
119
- startup.Startup.cb = Marshal.SizeOf(typeof(StartupEx)); startup.Startup.Flags = 0x100;
120
- startup.Startup.StdInput = c.Pipes[0]; startup.Startup.StdOutput = c.Pipes[1]; startup.Startup.StdError = c.Pipes[2];
121
- Array.Sort(env, StringComparer.OrdinalIgnoreCase);
122
- environment = Marshal.StringToHGlobalUni(String.Join("\0", env) + "\0\0");
123
- if (!CreateProcessW(executable, new StringBuilder(command), IntPtr.Zero, IntPtr.Zero, true, 0x08080400, environment, cwd, ref startup, out pi)) {
124
- int error = Marshal.GetLastWin32Error();
125
- var failure = new Win32Exception(error, "CreateProcessW");
126
- // Only ordinary target resolution errors permit non-containment errors.
127
- failure.Data["kind"] = (error == 2 || error == 3 || error == 193 || error == 267) ? "target" : "unavailable";
128
- throw failure;
129
- }
130
- // Separate wait handle: release cannot invalidate a wait in progress.
131
- IntPtr waitHandle = Handle(OpenProcess(0x100000 | 0x1000, false, (int)pi.ProcessId), "OpenProcess(exit wait)");
132
- var waiter = new Thread(() => {
133
- try {
134
- WaitForSingleObject(waitHandle, INFINITE); uint code;
135
- if (GetExitCodeProcess(waitHandle, out code)) Emit("{\"event\":\"exit\",\"key\":\"" + key + "\",\"code\":" + code + "}");
136
- } finally { CloseHandle(waitHandle); }
137
- });
138
- waiter.IsBackground = true; waiter.Start();
139
- c.Process = pi.Process; c.Pid = pi.ProcessId; pi.Process = IntPtr.Zero;
140
- return c.Pid;
141
- } catch {
142
- // JOB_LIST guarantees any created target was born in this job.
143
- if (pi.Process != IntPtr.Zero) { TerminateJobObject(c.Job, 1); WaitForSingleObject(pi.Process, 5000); }
144
- throw;
145
- } finally {
146
- if (pi.Thread != IntPtr.Zero) CloseHandle(pi.Thread);
147
- if (pi.Process != IntPtr.Zero) CloseHandle(pi.Process);
148
- foreach (IntPtr pipe in c.Pipes) if (pipe != IntPtr.Zero) CloseHandle(pipe);
149
- c.Pipes = new IntPtr[0];
150
- if (initialized) DeleteProcThreadAttributeList(attributes);
151
- if (attributes != IntPtr.Zero) Marshal.FreeHGlobal(attributes);
152
- if (handles != IntPtr.Zero) Marshal.FreeHGlobal(handles);
153
- if (jobValue != IntPtr.Zero) Marshal.FreeHGlobal(jobValue);
154
- if (environment != IntPtr.Zero) Marshal.FreeHGlobal(environment);
155
- }
156
- }
157
- static uint Active(Container c) {
158
- Accounting info;
159
- Check(QueryInformationJobObject(c.Job, 1, out info, (uint)Marshal.SizeOf(typeof(Accounting)), IntPtr.Zero), "QueryInformationJobObject");
160
- return info.ActiveProcesses;
161
- }
162
- public static void Terminate(string key, int timeoutMs) {
163
- var c = Find(key);
164
- Check(TerminateJobObject(c.Job, 1), "TerminateJobObject");
165
- var elapsed = System.Diagnostics.Stopwatch.StartNew();
166
- while (Active(c) != 0) { if (elapsed.ElapsedMilliseconds >= Math.Max(0, Math.Min(60000, timeoutMs))) throw new TimeoutException("Job did not become empty"); Thread.Sleep(10); }
167
- }
168
- public static void Release(string key) {
169
- var c = Find(key);
170
- if (Active(c) != 0) throw new InvalidOperationException("Cannot release a nonempty job");
171
- Jobs.Remove(key); Dispose(c);
172
- }
173
- static void Dispose(Container c) {
174
- if (c.Job != IntPtr.Zero) CloseHandle(c.Job);
175
- if (c.Process != IntPtr.Zero) CloseHandle(c.Process);
176
- if (c.Pipes != null) foreach (IntPtr pipe in c.Pipes) if (pipe != IntPtr.Zero) CloseHandle(pipe);
177
- }
178
- public static void Close() { foreach (var c in Jobs.Values) Dispose(c); Jobs.Clear(); }
179
- }
180
-
1
+ // Windows Job Object containment. Compiled once per persistent PowerShell helper.
2
+ using System;
3
+ using System.Collections.Generic;
4
+ using System.ComponentModel;
5
+ using System.Runtime.InteropServices;
6
+ using System.Text;
7
+ using System.Threading;
8
+
9
+ public static class ThothJobLauncher
10
+ {
11
+ const uint INFINITE = 0xffffffff;
12
+ static readonly Dictionary<string, Container> Jobs = new Dictionary<string, Container>();
13
+ static IntPtr parent;
14
+ sealed class Container { public IntPtr Job, Process; public uint Pid; public IntPtr[] Pipes; }
15
+ [StructLayout(LayoutKind.Sequential)] struct Security { public int Length; public IntPtr Descriptor; public int Inherit; }
16
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct Startup {
17
+ public int cb; public string Reserved, Desktop, Title;
18
+ public uint X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
19
+ public ushort ShowWindow, Reserved2; public IntPtr ReservedPtr, StdInput, StdOutput, StdError;
20
+ }
21
+ [StructLayout(LayoutKind.Sequential)] struct StartupEx { public Startup Startup; public IntPtr Attributes; }
22
+ [StructLayout(LayoutKind.Sequential)] struct ProcessInfo { public IntPtr Process, Thread; public uint ProcessId, ThreadId; }
23
+ [StructLayout(LayoutKind.Sequential)] struct BasicLimits {
24
+ public long ProcessTime, JobTime; public uint Flags;
25
+ public UIntPtr MinWorkingSet, MaxWorkingSet; public uint ActiveProcessLimit;
26
+ public UIntPtr Affinity; public uint PriorityClass, SchedulingClass;
27
+ }
28
+ [StructLayout(LayoutKind.Sequential)] struct IoCounters { public ulong ReadCount, WriteCount, OtherCount, ReadBytes, WriteBytes, OtherBytes; }
29
+ [StructLayout(LayoutKind.Sequential)] struct ExtendedLimits {
30
+ public BasicLimits Basic; public IoCounters Io;
31
+ public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
32
+ }
33
+ [StructLayout(LayoutKind.Sequential)] struct Accounting {
34
+ public long UserTime, KernelTime, PeriodUserTime, PeriodKernelTime;
35
+ public uint PageFaults, TotalProcesses, ActiveProcesses, TerminatedProcesses;
36
+ }
37
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateJobObjectW(IntPtr attributes, string name);
38
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetInformationJobObject(IntPtr job, int kind, ref ExtendedLimits info, uint size);
39
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool QueryInformationJobObject(IntPtr job, int kind, out Accounting info, uint size, IntPtr returned);
40
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateJobObject(IntPtr job, uint code);
41
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool CloseHandle(IntPtr handle);
42
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
43
+ [DllImport("kernel32.dll", SetLastError=true)] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
44
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
45
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern bool CreateProcessW(string application, StringBuilder command, IntPtr processAttributes, IntPtr threadAttributes, bool inherit, uint flags, IntPtr environment, string cwd, ref StartupEx startup, out ProcessInfo info);
46
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool InitializeProcThreadAttributeList(IntPtr attributes, int count, uint flags, ref IntPtr size);
47
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool UpdateProcThreadAttribute(IntPtr attributes, uint flags, IntPtr attribute, IntPtr value, IntPtr size, IntPtr previous, IntPtr returned);
48
+ [DllImport("kernel32.dll")] static extern void DeleteProcThreadAttributeList(IntPtr attributes);
49
+
50
+ [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern bool ConvertStringSecurityDescriptorToSecurityDescriptorW(string text, uint revision, out IntPtr descriptor, out uint size);
51
+ [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr memory);
52
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateNamedPipeW(string name, uint mode, uint pipeMode, uint instances, uint outputSize, uint inputSize, uint timeout, ref Security security);
53
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool ConnectNamedPipe(IntPtr pipe, IntPtr overlapped);
54
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetNamedPipeHandleState(IntPtr pipe, ref uint mode, IntPtr maximum, IntPtr timeout);
55
+ static readonly object OutputLock = new object();
56
+ public static void Emit(string json) { lock (OutputLock) { Console.WriteLine(json); Console.Out.Flush(); } }
57
+ static void Check(bool ok, string operation) { if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error(), operation); }
58
+ static IntPtr Handle(IntPtr handle, string operation) { if (handle == IntPtr.Zero || handle == new IntPtr(-1)) throw new Win32Exception(Marshal.GetLastWin32Error(), operation); return handle; }
59
+ public static void WatchParent(int pid) {
60
+ parent = Handle(OpenProcess(0x100000, false, pid), "OpenProcess(parent)");
61
+ var watcher = new Thread(() => { WaitForSingleObject(parent, INFINITE); Environment.Exit(0); });
62
+ watcher.IsBackground = true; watcher.Start();
63
+ }
64
+ public static string[] Prepare(string key) {
65
+ if (key.Length != 32 || System.Text.RegularExpressions.Regex.IsMatch(key, "[^a-f0-9]")) throw new ArgumentException("Invalid key");
66
+ if (Jobs.ContainsKey(key)) throw new ArgumentException("Duplicate key");
67
+ var container = new Container { Pipes = new IntPtr[3] };
68
+ IntPtr descriptor = IntPtr.Zero;
69
+ try {
70
+ container.Job = Handle(CreateJobObjectW(IntPtr.Zero, null), "CreateJobObjectW");
71
+ var limits = new ExtendedLimits(); limits.Basic.Flags = 0x2000;
72
+ Check(SetInformationJobObject(container.Job, 9, ref limits, (uint)Marshal.SizeOf(typeof(ExtendedLimits))), "SetInformationJobObject");
73
+ string sid = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
74
+ uint size;
75
+ // Protected DACL, one ACE, no Everyone/anonymous/admin grants.
76
+ Check(ConvertStringSecurityDescriptorToSecurityDescriptorW("D:P(A;;GA;;;" + sid + ")", 1, out descriptor, out size), "Pipe DACL");
77
+ var security = new Security { Length = Marshal.SizeOf(typeof(Security)), Descriptor = descriptor, Inherit = 1 };
78
+ string[] names = new string[3];
79
+ string[] suffixes = { "stdin", "stdout", "stderr" };
80
+ for (int i = 0; i < 3; i++) {
81
+ names[i] = "\\\\.\\pipe\\thoth-job-" + key + "-" + suffixes[i];
82
+ // Node net.Socket opens duplex handles. Unused directions stay idle.
83
+ // FIRST_PIPE_INSTANCE; NOWAIT only for bounded connect, then WAIT.
84
+ container.Pipes[i] = Handle(CreateNamedPipeW(names[i], 0x80000u | 3u, 0x9, 1, 65536, 65536, 10000, ref security), "CreateNamedPipeW");
85
+ }
86
+ Jobs.Add(key, container); return names;
87
+ } catch { Dispose(container); throw; }
88
+ finally { if (descriptor != IntPtr.Zero) LocalFree(descriptor); }
89
+ }
90
+ static Container Find(string key) { Container c; if (!Jobs.TryGetValue(key, out c)) throw new ArgumentException("Unknown job key"); return c; }
91
+ public static uint Start(string key, string executable, string command, string cwd, string[] env) {
92
+ var c = Find(key);
93
+ IntPtr attributes = IntPtr.Zero, handles = IntPtr.Zero, jobValue = IntPtr.Zero, environment = IntPtr.Zero;
94
+ bool initialized = false; ProcessInfo pi = new ProcessInfo();
95
+ try {
96
+ if (c.Process != IntPtr.Zero) throw new InvalidOperationException("Already started");
97
+ var deadline = System.Diagnostics.Stopwatch.StartNew();
98
+ foreach (IntPtr pipe in c.Pipes) {
99
+ while (!ConnectNamedPipe(pipe, IntPtr.Zero)) {
100
+ int error = Marshal.GetLastWin32Error();
101
+ if (error == 535) break; // client connected before ConnectNamedPipe
102
+ if (error != 536) throw new Win32Exception(error, "ConnectNamedPipe error=" + error);
103
+ if (deadline.ElapsedMilliseconds >= 10000) throw new TimeoutException("Pipe connect timeout");
104
+ Thread.Sleep(10);
105
+ }
106
+ uint mode = 0;
107
+ Check(SetNamedPipeHandleState(pipe, ref mode, IntPtr.Zero, IntPtr.Zero), "SetNamedPipeHandleState(WAIT)");
108
+ }
109
+ IntPtr size = IntPtr.Zero;
110
+ InitializeProcThreadAttributeList(IntPtr.Zero, 2, 0, ref size);
111
+ attributes = Marshal.AllocHGlobal(size);
112
+ Check(InitializeProcThreadAttributeList(attributes, 2, 0, ref size), "InitializeProcThreadAttributeList"); initialized = true;
113
+ handles = Marshal.AllocHGlobal(IntPtr.Size * 3);
114
+ for (int i = 0; i < 3; i++) Marshal.WriteIntPtr(handles, IntPtr.Size * i, c.Pipes[i]);
115
+ Check(UpdateProcThreadAttribute(attributes, 0, new IntPtr(0x20002), handles, new IntPtr(IntPtr.Size * 3), IntPtr.Zero, IntPtr.Zero), "HANDLE_LIST");
116
+ jobValue = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(jobValue, c.Job);
117
+ Check(UpdateProcThreadAttribute(attributes, 0, new IntPtr(0x2000D), jobValue, new IntPtr(IntPtr.Size), IntPtr.Zero, IntPtr.Zero), "JOB_LIST");
118
+ var startup = new StartupEx { Attributes = attributes };
119
+ startup.Startup.cb = Marshal.SizeOf(typeof(StartupEx)); startup.Startup.Flags = 0x100;
120
+ startup.Startup.StdInput = c.Pipes[0]; startup.Startup.StdOutput = c.Pipes[1]; startup.Startup.StdError = c.Pipes[2];
121
+ Array.Sort(env, StringComparer.OrdinalIgnoreCase);
122
+ environment = Marshal.StringToHGlobalUni(String.Join("\0", env) + "\0\0");
123
+ if (!CreateProcessW(executable, new StringBuilder(command), IntPtr.Zero, IntPtr.Zero, true, 0x08080400, environment, cwd, ref startup, out pi)) {
124
+ int error = Marshal.GetLastWin32Error();
125
+ var failure = new Win32Exception(error, "CreateProcessW");
126
+ // Only ordinary target resolution errors permit non-containment errors.
127
+ failure.Data["kind"] = (error == 2 || error == 3 || error == 193 || error == 267) ? "target" : "unavailable";
128
+ throw failure;
129
+ }
130
+ // Separate wait handle: release cannot invalidate a wait in progress.
131
+ IntPtr waitHandle = Handle(OpenProcess(0x100000 | 0x1000, false, (int)pi.ProcessId), "OpenProcess(exit wait)");
132
+ var waiter = new Thread(() => {
133
+ try {
134
+ WaitForSingleObject(waitHandle, INFINITE); uint code;
135
+ if (GetExitCodeProcess(waitHandle, out code)) Emit("{\"event\":\"exit\",\"key\":\"" + key + "\",\"code\":" + code + "}");
136
+ } finally { CloseHandle(waitHandle); }
137
+ });
138
+ waiter.IsBackground = true; waiter.Start();
139
+ c.Process = pi.Process; c.Pid = pi.ProcessId; pi.Process = IntPtr.Zero;
140
+ return c.Pid;
141
+ } catch {
142
+ // JOB_LIST guarantees any created target was born in this job.
143
+ if (pi.Process != IntPtr.Zero) { TerminateJobObject(c.Job, 1); WaitForSingleObject(pi.Process, 5000); }
144
+ throw;
145
+ } finally {
146
+ if (pi.Thread != IntPtr.Zero) CloseHandle(pi.Thread);
147
+ if (pi.Process != IntPtr.Zero) CloseHandle(pi.Process);
148
+ foreach (IntPtr pipe in c.Pipes) if (pipe != IntPtr.Zero) CloseHandle(pipe);
149
+ c.Pipes = new IntPtr[0];
150
+ if (initialized) DeleteProcThreadAttributeList(attributes);
151
+ if (attributes != IntPtr.Zero) Marshal.FreeHGlobal(attributes);
152
+ if (handles != IntPtr.Zero) Marshal.FreeHGlobal(handles);
153
+ if (jobValue != IntPtr.Zero) Marshal.FreeHGlobal(jobValue);
154
+ if (environment != IntPtr.Zero) Marshal.FreeHGlobal(environment);
155
+ }
156
+ }
157
+ static uint Active(Container c) {
158
+ Accounting info;
159
+ Check(QueryInformationJobObject(c.Job, 1, out info, (uint)Marshal.SizeOf(typeof(Accounting)), IntPtr.Zero), "QueryInformationJobObject");
160
+ return info.ActiveProcesses;
161
+ }
162
+ public static void Terminate(string key, int timeoutMs) {
163
+ var c = Find(key);
164
+ Check(TerminateJobObject(c.Job, 1), "TerminateJobObject");
165
+ var elapsed = System.Diagnostics.Stopwatch.StartNew();
166
+ while (Active(c) != 0) { if (elapsed.ElapsedMilliseconds >= Math.Max(0, Math.Min(60000, timeoutMs))) throw new TimeoutException("Job did not become empty"); Thread.Sleep(10); }
167
+ }
168
+ public static void Release(string key) {
169
+ var c = Find(key);
170
+ if (Active(c) != 0) throw new InvalidOperationException("Cannot release a nonempty job");
171
+ Jobs.Remove(key); Dispose(c);
172
+ }
173
+ static void Dispose(Container c) {
174
+ if (c.Job != IntPtr.Zero) CloseHandle(c.Job);
175
+ if (c.Process != IntPtr.Zero) CloseHandle(c.Process);
176
+ if (c.Pipes != null) foreach (IntPtr pipe in c.Pipes) if (pipe != IntPtr.Zero) CloseHandle(pipe);
177
+ }
178
+ public static void Close() { foreach (var c in Jobs.Values) Dispose(c); Jobs.Clear(); }
179
+ }
180
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thoth-agents/pi-junie-bridge",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Junie ACP provider for Pi",
5
5
  "keywords": [
6
6
  "pi-package",