pushary 1.9.177 → 1.9.179

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.
Files changed (143) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/{api-MOK62OPO.js → api-YH7WN4FA.js} +21 -11
  3. package/dist/bin/pushary-audit.js +3 -3
  4. package/dist/bin/pushary-bell-hook.js +28 -28
  5. package/dist/bin/pushary-bell.js +12 -12
  6. package/dist/bin/pushary-calls.js +15 -15
  7. package/dist/bin/pushary-claude.js +27 -27
  8. package/dist/bin/pushary-clean.js +38 -38
  9. package/dist/bin/pushary-codex-bridge.js +23 -23
  10. package/dist/bin/pushary-codex-hook.js +108 -54
  11. package/dist/bin/pushary-codex-session.js +8 -8
  12. package/dist/bin/pushary-codex.js +16 -16
  13. package/dist/bin/pushary-connect.js +34 -34
  14. package/dist/bin/pushary-cowork.js +5 -5
  15. package/dist/bin/pushary-daemon.js +102 -78
  16. package/dist/bin/pushary-disconnect.js +29 -29
  17. package/dist/bin/pushary-display-hook.js +22 -1
  18. package/dist/bin/pushary-doctor.js +62 -48
  19. package/dist/bin/pushary-elicitation-hook.js +28 -28
  20. package/dist/bin/pushary-gemini-bridge.js +20 -33
  21. package/dist/bin/pushary-gemini-hook.js +32 -32
  22. package/dist/bin/pushary-hook.js +36 -36
  23. package/dist/bin/pushary-login.js +22 -22
  24. package/dist/bin/pushary-logout.js +29 -29
  25. package/dist/bin/pushary-mcp.js +12 -12
  26. package/dist/bin/pushary-mode.js +16 -16
  27. package/dist/bin/pushary-notification-hook.js +27 -27
  28. package/dist/bin/pushary-opencode-bridge.d.ts +1 -0
  29. package/dist/bin/pushary-opencode-bridge.js +576 -0
  30. package/dist/bin/pushary-opencode-hook.js +33 -33
  31. package/dist/bin/pushary-permission-denied-hook.js +36 -36
  32. package/dist/bin/pushary-permission-hook.js +36 -36
  33. package/dist/bin/pushary-post-hook.js +28 -28
  34. package/dist/bin/pushary-prompt-hook.js +27 -27
  35. package/dist/bin/pushary-session-end-hook.js +27 -27
  36. package/dist/bin/pushary-session-start-hook.js +38 -38
  37. package/dist/bin/pushary-sessions.js +14 -14
  38. package/dist/bin/pushary-setup.js +58 -58
  39. package/dist/bin/pushary-stats.js +5 -5
  40. package/dist/bin/pushary-status.js +35 -35
  41. package/dist/bin/pushary-stop-hook.js +27 -27
  42. package/dist/bin/pushary-stopfailure-hook.js +27 -27
  43. package/dist/bin/pushary-suggestions.js +16 -16
  44. package/dist/bin/pushary-transcript-register.js +17 -17
  45. package/dist/bin/pushary-transcripts.js +25 -25
  46. package/dist/bin/pushary-upgrade.js +45 -44
  47. package/dist/bin/pushary-wait.js +16 -16
  48. package/dist/bin/pushary.js +7 -7
  49. package/dist/{chunk-2SFXPVAE.js → chunk-2HMDWEER.js} +1 -1
  50. package/dist/{chunk-7ZDL4EOA.js → chunk-2JSTCD7L.js} +2 -2
  51. package/dist/{chunk-GOL7TCMO.js → chunk-32YARQJC.js} +5 -5
  52. package/dist/{chunk-2HREYLQL.js → chunk-3BZ7IGGW.js} +5 -5
  53. package/dist/{chunk-G2RTHSTU.js → chunk-3JXSIPLF.js} +1 -1
  54. package/dist/{chunk-N7GV4Y5B.js → chunk-3NTAU6DN.js} +2 -2
  55. package/dist/{chunk-BTOP6AHZ.js → chunk-65CSOPQW.js} +12 -25
  56. package/dist/{chunk-MNWUZ4JH.js → chunk-6BIC2SHE.js} +2 -2
  57. package/dist/{chunk-FLEDJCTE.js → chunk-6KF26UUL.js} +3 -3
  58. package/dist/{chunk-6FFXBHVF.js → chunk-6W7Q6VB6.js} +2 -2
  59. package/dist/{chunk-77PUYCLF.js → chunk-7VNTZY7V.js} +90 -21
  60. package/dist/{chunk-A4AG42X2.js → chunk-A7G6CFZU.js} +4 -4
  61. package/dist/{chunk-HCW3KFL3.js → chunk-AXPZZFBW.js} +2 -2
  62. package/dist/{chunk-AH6FRO37.js → chunk-AYMFOYOZ.js} +9 -9
  63. package/dist/{chunk-UC4DTMPM.js → chunk-AYP4GE3X.js} +24 -0
  64. package/dist/{chunk-SOWF5BU3.js → chunk-BKZZSXEQ.js} +4 -4
  65. package/dist/{chunk-2O6TO2YW.js → chunk-BNZYEIBB.js} +18 -18
  66. package/dist/{chunk-UYBCGHGQ.js → chunk-CTJRWP6Y.js} +3 -3
  67. package/dist/{chunk-3HGR5T4W.js → chunk-D7GUUTOT.js} +4 -4
  68. package/dist/{chunk-AIM5GLBI.js → chunk-E25IZ5S3.js} +4 -4
  69. package/dist/{chunk-5SNBTQOU.js → chunk-EEHTVBKI.js} +6 -6
  70. package/dist/{chunk-R2VQ4OKM.js → chunk-FHVGZ6AN.js} +1 -1
  71. package/dist/{chunk-MIHH354F.js → chunk-FWUF33U6.js} +2 -2
  72. package/dist/{chunk-XWG4PSQL.js → chunk-HGP2DDW3.js} +1 -1
  73. package/dist/{chunk-WVU5TTRU.js → chunk-HNQ2FIBA.js} +2 -2
  74. package/dist/{chunk-FUSZOEZK.js → chunk-HOVBZBAJ.js} +4 -4
  75. package/dist/{chunk-5OBLFHMG.js → chunk-I4XCADTT.js} +1 -1
  76. package/dist/{chunk-M7LXGZM6.js → chunk-I6AMLYXS.js} +4 -4
  77. package/dist/{chunk-NNWUE7PY.js → chunk-INUW2CXK.js} +6 -6
  78. package/dist/{chunk-2HK3KVEJ.js → chunk-IV4ZY2DS.js} +5 -5
  79. package/dist/{chunk-OU4FPSNZ.js → chunk-J5PTUQMF.js} +3 -3
  80. package/dist/{chunk-5YUBUJ6F.js → chunk-JDNQC5IG.js} +5 -5
  81. package/dist/{chunk-JH6IUXXS.js → chunk-JMPC7HL6.js} +6 -6
  82. package/dist/{chunk-JLOOLENK.js → chunk-JSSCR6M2.js} +2 -2
  83. package/dist/{chunk-KLPOTV4Q.js → chunk-KFLHGN4D.js} +3 -3
  84. package/dist/{chunk-KSRMVJ2V.js → chunk-KUB4OGLG.js} +5 -5
  85. package/dist/{chunk-3DFKZATL.js → chunk-M2P5KFP5.js} +3 -3
  86. package/dist/{chunk-AUVB3J6X.js → chunk-MIJ2P4FZ.js} +7 -7
  87. package/dist/{chunk-XJJ4KJF5.js → chunk-MKKRQBQF.js} +114 -15
  88. package/dist/{chunk-5F2GVH3H.js → chunk-MM5QO2ZY.js} +1 -1
  89. package/dist/{chunk-LAJ62ADY.js → chunk-MWKKUBHQ.js} +1 -1
  90. package/dist/{chunk-ZHVWYX5I.js → chunk-N24MKYZ2.js} +1 -1
  91. package/dist/{chunk-6HEYIMTE.js → chunk-N2L7E5NE.js} +5 -5
  92. package/dist/{chunk-IIIVVFHC.js → chunk-NEAJLLIG.js} +5 -5
  93. package/dist/{chunk-RQYNZJZ3.js → chunk-NX33EVEP.js} +1 -1
  94. package/dist/{chunk-GCAFTVYG.js → chunk-OD6JNTGZ.js} +2 -2
  95. package/dist/{chunk-QS4IPOAQ.js → chunk-OIFWZESQ.js} +14 -11
  96. package/dist/{chunk-4YBTCIIU.js → chunk-P3MYHWF5.js} +5 -5
  97. package/dist/{chunk-L3R3XAQC.js → chunk-PFH7XMHE.js} +1 -1
  98. package/dist/{chunk-HWBO3QVL.js → chunk-PJHYFHP4.js} +1 -1
  99. package/dist/{chunk-ZRMI7POM.js → chunk-POESL3CD.js} +1 -1
  100. package/dist/{chunk-2MMTYCCV.js → chunk-QMV7WS7D.js} +2 -2
  101. package/dist/{chunk-TIGCU3PF.js → chunk-QYGO5EKA.js} +2 -2
  102. package/dist/{chunk-3CWVK6BS.js → chunk-RM3F4V6A.js} +64 -15
  103. package/dist/{chunk-RSRWMXEM.js → chunk-RM3YENVK.js} +3 -3
  104. package/dist/{chunk-UOM2JOQZ.js → chunk-RVIYAQC7.js} +2 -2
  105. package/dist/{chunk-CUE6IPNE.js → chunk-S7X3PENP.js} +6 -6
  106. package/dist/{chunk-G2T7S5RU.js → chunk-SV6AMA7J.js} +10 -10
  107. package/dist/{chunk-DOCNSQOB.js → chunk-SYIAWMBA.js} +6 -6
  108. package/dist/{chunk-SV7PLR6Z.js → chunk-TVBND3VL.js} +2 -2
  109. package/dist/{chunk-CEMYK6BM.js → chunk-UJUXZCQS.js} +6 -6
  110. package/dist/{chunk-NWO4GVKC.js → chunk-VOWNWXVE.js} +38 -10
  111. package/dist/{chunk-4PRJDA3J.js → chunk-W27VNI6G.js} +1 -1
  112. package/dist/{chunk-IR5B5EQI.js → chunk-WDPIZXCZ.js} +3 -3
  113. package/dist/{chunk-KX2SWWSD.js → chunk-WII73NRE.js} +1 -1
  114. package/dist/{chunk-J3V4CBKZ.js → chunk-WIKPDEOR.js} +29 -8
  115. package/dist/{chunk-FDB2VMJM.js → chunk-WMHXZDUT.js} +2 -2
  116. package/dist/{chunk-NSR3ZTUJ.js → chunk-XJG7YRF7.js} +3 -3
  117. package/dist/{chunk-W7KAVPQP.js → chunk-XOVAERD7.js} +1 -1
  118. package/dist/{chunk-EXK47DWS.js → chunk-XQGU77H7.js} +4 -4
  119. package/dist/{chunk-DN5FNT3O.js → chunk-XWWD2KTY.js} +22 -1
  120. package/dist/{chunk-LGKFRWQL.js → chunk-Y5BRXPL6.js} +1 -1
  121. package/dist/{chunk-QBIALYLY.js → chunk-YRGDHBS5.js} +4 -4
  122. package/dist/{chunk-EHFUVDRM.js → chunk-YXLJTIGG.js} +4 -4
  123. package/dist/{chunk-MIRXACOR.js → chunk-Z2DAWG5U.js} +6 -1
  124. package/dist/{chunk-QES7CGHR.js → chunk-ZMJKA7CF.js} +5 -5
  125. package/dist/{chunk-VOPORKYP.js → chunk-ZMSQQVVY.js} +1 -1
  126. package/dist/{chunk-LEWVT2A2.js → chunk-ZNCRZNLJ.js} +1 -1
  127. package/dist/{chunk-JWMS3WIN.js → chunk-ZPHPNTGW.js} +1 -1
  128. package/dist/{chunk-L7MROSFJ.js → chunk-ZTNGM6NU.js} +3 -3
  129. package/dist/{codex-app-cards-switch-VUX7FUBE.js → codex-app-cards-switch-RDVTCDVO.js} +11 -11
  130. package/dist/{codex-card-routing-F6PBOHKA.js → codex-card-routing-XUYIRUB7.js} +2 -2
  131. package/dist/{codex-desktop-launch-DHE24VP2.js → codex-desktop-launch-EX3E3T3Q.js} +1 -1
  132. package/dist/{codex-session-launch-5QMO4UNL.js → codex-session-launch-TDEWJ3G6.js} +20 -20
  133. package/dist/{config-VEUG5WVO.js → config-XDZZTOHU.js} +3 -3
  134. package/dist/{global-upgrade-TE6N2LPD.js → global-upgrade-QVFP4F7D.js} +9 -9
  135. package/dist/{identity-RUUBB2GE.js → identity-Q5HWBCJY.js} +4 -4
  136. package/dist/{live-capabilities-CATPYBSX.js → live-capabilities-G5FB5VBL.js} +28 -4
  137. package/dist/{paths-LE4WLG45.js → paths-IVCUVJM6.js} +3 -3
  138. package/dist/{reapply-4BTKZGKT.js → reapply-MQTAPBPH.js} +31 -31
  139. package/dist/src/index.d.ts +2 -0
  140. package/dist/src/index.js +35 -35
  141. package/dist/{upgrade-lock-HU2F5X57.js → upgrade-lock-Y56NERM5.js} +4 -4
  142. package/dist/{usage-UMIDTEI3.js → usage-J7O2QQEQ.js} +3 -3
  143. package/package.json +2 -1
@@ -0,0 +1,576 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ OPENCODE_LOOPBACK_ALIASES,
4
+ OPENCODE_LOOPBACK_HOSTS,
5
+ OPENCODE_SERVICE_INFO_PATH,
6
+ OPENCODE_SERVICE_PROTOCOL,
7
+ OPENCODE_SERVICE_REGISTRATION,
8
+ OPENCODE_SERVICE_REQUEST_TIMEOUT_MS,
9
+ OPENCODE_SERVICE_USER,
10
+ OPENCODE_STATE_DIRECTORY
11
+ } from "../chunk-WIKPDEOR.js";
12
+ import {
13
+ BRIDGE_FAILURE_MESSAGE_MAX,
14
+ LiveTranscriptRelay,
15
+ acknowledgeSpawnFailure,
16
+ liveSessionSleep,
17
+ postLiveSession,
18
+ postLiveSessionUntilAccepted,
19
+ startLiveSessionHeartbeat
20
+ } from "../chunk-XWWD2KTY.js";
21
+ import {
22
+ OPENCODE_DESKTOP_CLI,
23
+ isExecutableFile,
24
+ resolveProviderBinary
25
+ } from "../chunk-MKKRQBQF.js";
26
+ import "../chunk-2JSTCD7L.js";
27
+ import {
28
+ CommandReceipts,
29
+ controllerCommandSchema
30
+ } from "../chunk-HGP2DDW3.js";
31
+ import {
32
+ SESSION_IDLE_TIMEOUT_MS,
33
+ describeIdleWindow,
34
+ idleDeadlinePassed,
35
+ startProcessOwnership,
36
+ withSpawnProcessOwnership
37
+ } from "../chunk-6W7Q6VB6.js";
38
+ import "../chunk-TCE3J44Z.js";
39
+ import {
40
+ AGENT_IDENTITIES,
41
+ agentNameFor
42
+ } from "../chunk-Z2DAWG5U.js";
43
+ import "../chunk-M2P5KFP5.js";
44
+ import {
45
+ external_exports
46
+ } from "../chunk-55L4JSPA.js";
47
+ import {
48
+ transcriptsEnabled
49
+ } from "../chunk-3JXSIPLF.js";
50
+ import {
51
+ spawnClaude
52
+ } from "../chunk-VRNGMRJA.js";
53
+ import {
54
+ readCommandAck
55
+ } from "../chunk-XOVAERD7.js";
56
+ import "../chunk-PJHYFHP4.js";
57
+ import {
58
+ getMachineId
59
+ } from "../chunk-PFH7XMHE.js";
60
+ import "../chunk-ZTNGM6NU.js";
61
+ import "../chunk-HNQ2FIBA.js";
62
+ import "../chunk-3NTAU6DN.js";
63
+ import "../chunk-BKZZSXEQ.js";
64
+ import {
65
+ getApiKey,
66
+ getBaseUrl
67
+ } from "../chunk-ZPHPNTGW.js";
68
+ import "../chunk-PM2NRK6Y.js";
69
+ import "../chunk-MWKKUBHQ.js";
70
+ import "../chunk-UQTQ6HPO.js";
71
+ import {
72
+ isRecord
73
+ } from "../chunk-AYP4GE3X.js";
74
+ import "../chunk-MLKGABMK.js";
75
+
76
+ // bin/pushary-opencode-bridge.ts
77
+ import { existsSync } from "fs";
78
+ import { homedir } from "os";
79
+
80
+ // src/opencode-service.ts
81
+ import { spawn } from "child_process";
82
+ import { closeSync, constants, fstatSync, openSync, readdirSync, readFileSync } from "fs";
83
+ import { join } from "path";
84
+ var OPENCODE_SERVICE_FILE = "service.json";
85
+ var OPENCODE_SERVICE_FILE_VARIABLE = "PUSHARY_OPENCODE_SERVICE_FILE";
86
+ var OPENCODE_SERVICE_START_ARGS = ["service", "start"];
87
+ var OPENCODE_SESSION_ID = /^ses_[A-Za-z0-9_-]{1,120}$/;
88
+ var SERVICE_START_TIMEOUT_MS = 6e4;
89
+ var SERVICE_READY_ATTEMPTS = 20;
90
+ var SERVICE_READY_INTERVAL_MS = 500;
91
+ var MAX_REGISTRATION_BYTES = 4096;
92
+ var SHARED_PERMISSION_BITS = 63;
93
+ var SPAWN_SCOPED_VARIABLE_PREFIXES = ["PUSHARY_SPAWN_", "PUSHARY_BRIDGE_"];
94
+ var MISSING_FILE_CODES = /* @__PURE__ */ new Set(["ENOENT", "ENOTDIR"]);
95
+ var REGISTRATION_OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
96
+ var MESSAGE_PAGE_SIZE = 50;
97
+ var MAX_MESSAGE_PAGES = 8;
98
+ var registrationSchema = external_exports.object({
99
+ id: external_exports.string().optional(),
100
+ version: external_exports.string().optional(),
101
+ url: external_exports.string().min(1).max(512),
102
+ pid: external_exports.number().int().positive(),
103
+ password: external_exports.string().min(1).max(1024).optional()
104
+ });
105
+ var serverInfoSchema = external_exports.object({ version: external_exports.string(), pid: external_exports.number().int().nonnegative() });
106
+ var createdSessionSchema = external_exports.object({ data: external_exports.object({ id: external_exports.string().regex(OPENCODE_SESSION_ID) }) });
107
+ var activeSessionsSchema = external_exports.object({ data: external_exports.record(external_exports.string(), external_exports.unknown()) });
108
+ var interruptSchema = external_exports.object({ interrupted: external_exports.boolean() });
109
+ var messagePageSchema = external_exports.object({
110
+ data: external_exports.array(external_exports.object({ id: external_exports.string().min(1) }).passthrough()),
111
+ cursor: external_exports.object({ next: external_exports.string().min(1).nullish() }).passthrough().nullish()
112
+ });
113
+ var userMessageSchema = external_exports.object({ id: external_exports.string(), type: external_exports.literal("user"), text: external_exports.string() });
114
+ var assistantMessageSchema = external_exports.object({
115
+ id: external_exports.string(),
116
+ type: external_exports.literal("assistant"),
117
+ content: external_exports.array(external_exports.object({ type: external_exports.string(), text: external_exports.string().optional() }).passthrough())
118
+ });
119
+ var OpenCodeServiceConnection = class {
120
+ constructor(origin, pid, password) {
121
+ this.origin = origin;
122
+ this.pid = pid;
123
+ this.#authorization = password === void 0 ? null : `Basic ${Buffer.from(`${OPENCODE_SERVICE_USER}:${password}`).toString("base64")}`;
124
+ }
125
+ #authorization;
126
+ request(method, path, signal, body) {
127
+ const headers = {};
128
+ if (body) headers["content-type"] = "application/json";
129
+ if (this.#authorization) headers.authorization = this.#authorization;
130
+ return fetch(new URL(path, this.origin), {
131
+ method,
132
+ headers,
133
+ body: body ? JSON.stringify(body) : void 0,
134
+ redirect: "error",
135
+ signal: AbortSignal.any([signal, AbortSignal.timeout(OPENCODE_SERVICE_REQUEST_TIMEOUT_MS)])
136
+ });
137
+ }
138
+ };
139
+ var openCodeRegistrationDirectory = (environment, home2) => join(environment.XDG_STATE_HOME || join(home2, ".local", "state"), OPENCODE_STATE_DIRECTORY);
140
+ var orderedRegistrationNames = (names) => {
141
+ const registrations = names.filter((name) => OPENCODE_SERVICE_REGISTRATION.test(name));
142
+ return [
143
+ ...registrations.filter((name) => name === OPENCODE_SERVICE_FILE),
144
+ ...registrations.filter((name) => name !== OPENCODE_SERVICE_FILE).sort()
145
+ ];
146
+ };
147
+ var openCodeLoopbackOrigin = (raw) => {
148
+ let url;
149
+ try {
150
+ url = new URL(raw);
151
+ } catch {
152
+ return null;
153
+ }
154
+ if (url.protocol !== OPENCODE_SERVICE_PROTOCOL) return null;
155
+ if (Object.hasOwn(OPENCODE_LOOPBACK_ALIASES, url.hostname)) url.hostname = OPENCODE_LOOPBACK_ALIASES[url.hostname] ?? url.hostname;
156
+ return OPENCODE_LOOPBACK_HOSTS.some((host) => host === url.hostname) ? url.origin : null;
157
+ };
158
+ var registrationFileRefusal = (facts, owner) => {
159
+ if (!facts.isFile) return "is not a regular file";
160
+ if (facts.size > MAX_REGISTRATION_BYTES) return "is larger than a service registration";
161
+ if (owner === null) return null;
162
+ if (facts.uid !== owner) return "belongs to another user";
163
+ if ((facts.mode & SHARED_PERMISSION_BITS) !== 0) return "can be read by other users";
164
+ return null;
165
+ };
166
+ var refusedRegistration = (reason) => ({ kind: "refused", reason });
167
+ var parseOpenCodeRegistration = (text) => {
168
+ let value;
169
+ try {
170
+ value = JSON.parse(text);
171
+ } catch {
172
+ return refusedRegistration("is not valid JSON");
173
+ }
174
+ const parsed = registrationSchema.safeParse(value);
175
+ if (!parsed.success) return refusedRegistration("is not an OpenCode service registration");
176
+ const origin = openCodeLoopbackOrigin(parsed.data.url);
177
+ if (!origin) return refusedRegistration("names an address that is not this computer");
178
+ return {
179
+ kind: "registered",
180
+ service: new OpenCodeServiceConnection(origin, parsed.data.pid, parsed.data.password),
181
+ version: parsed.data.version
182
+ };
183
+ };
184
+ var isMissingFile = (error) => error instanceof Error && "code" in error && typeof error.code === "string" && MISSING_FILE_CODES.has(error.code);
185
+ var readOpenCodeRegistration = (file, owner) => {
186
+ let descriptor;
187
+ try {
188
+ descriptor = openSync(file, REGISTRATION_OPEN_FLAGS);
189
+ } catch (error) {
190
+ return isMissingFile(error) ? { kind: "absent" } : refusedRegistration("cannot be opened as a regular file");
191
+ }
192
+ try {
193
+ const stats = fstatSync(descriptor);
194
+ const refusal = registrationFileRefusal({ isFile: stats.isFile(), uid: stats.uid, mode: stats.mode, size: stats.size }, owner);
195
+ return refusal ? refusedRegistration(refusal) : parseOpenCodeRegistration(readFileSync(descriptor, "utf8"));
196
+ } catch {
197
+ return refusedRegistration("cannot be read");
198
+ } finally {
199
+ closeSync(descriptor);
200
+ }
201
+ };
202
+ var openCodeRegistrationFiles = (location) => {
203
+ if (location.serviceFile) return [location.serviceFile];
204
+ let names;
205
+ try {
206
+ names = readdirSync(location.directory);
207
+ } catch {
208
+ return [];
209
+ }
210
+ return orderedRegistrationNames(names).map((name) => join(location.directory, name));
211
+ };
212
+ var serviceAnswersAsRegistered = (registered, answered) => answered.pid === registered.pid && (registered.version === void 0 || answered.version === registered.version);
213
+ var readJson = async (response) => {
214
+ try {
215
+ return await response.json();
216
+ } catch {
217
+ return null;
218
+ }
219
+ };
220
+ var serviceAnswers = async (registered, signal) => {
221
+ try {
222
+ const response = await registered.service.request("GET", OPENCODE_SERVICE_INFO_PATH, signal);
223
+ if (!response.ok) return false;
224
+ const info = serverInfoSchema.safeParse(await readJson(response));
225
+ return info.success && serviceAnswersAsRegistered({ pid: registered.service.pid, version: registered.version }, info.data);
226
+ } catch {
227
+ return false;
228
+ }
229
+ };
230
+ var discoverOpenCodeService = async (location, signal) => {
231
+ let refusal = null;
232
+ for (const file of openCodeRegistrationFiles(location)) {
233
+ const read = readOpenCodeRegistration(file, location.owner);
234
+ if (read.kind === "absent") continue;
235
+ if (read.kind === "refused") {
236
+ refusal ??= { kind: "refused", file, reason: read.reason };
237
+ continue;
238
+ }
239
+ if (await serviceAnswers(read, signal)) return { kind: "live", service: read.service };
240
+ }
241
+ return refusal ?? { kind: "none" };
242
+ };
243
+ var openCodeServiceEnvironment = (environment) => Object.fromEntries(Object.entries(environment).filter(([name]) => !SPAWN_SCOPED_VARIABLE_PREFIXES.some((prefix) => name.startsWith(prefix))));
244
+ var openCodeServiceStarter = (launchBinary2, platform, isExecutable) => platform === "darwin" && isExecutable(OPENCODE_DESKTOP_CLI) ? OPENCODE_DESKTOP_CLI : launchBinary2;
245
+ var serviceStartProcess = (start) => {
246
+ const options = {
247
+ cwd: start.cwd,
248
+ env: openCodeServiceEnvironment(start.environment),
249
+ stdio: "ignore",
250
+ windowsHide: true
251
+ };
252
+ return process.platform === "win32" ? spawnClaude(start.command, OPENCODE_SERVICE_START_ARGS, options) : spawn(start.command, OPENCODE_SERVICE_START_ARGS, options);
253
+ };
254
+ var runServiceStart = (start, signal) => new Promise((resolve, reject) => {
255
+ const child = serviceStartProcess(start);
256
+ const stop2 = () => {
257
+ if (child.exitCode === null) child.kill();
258
+ };
259
+ const timer = setTimeout(stop2, SERVICE_START_TIMEOUT_MS);
260
+ signal.addEventListener("abort", stop2, { once: true });
261
+ const settle = (error) => {
262
+ clearTimeout(timer);
263
+ signal.removeEventListener("abort", stop2);
264
+ if (error) reject(error);
265
+ else resolve();
266
+ };
267
+ child.once("error", (error) => settle(error));
268
+ child.once("exit", (code) => settle(code === 0 ? null : new Error(`OpenCode could not start its background service (exit ${code ?? "signal"})`)));
269
+ });
270
+ var describeRefusal = (refusal) => `OpenCode's service registration ${refusal.file} ${refusal.reason}, so Pushary will not use it`;
271
+ var connectOpenCodeService = async (setup, signal) => {
272
+ const found = await discoverOpenCodeService(setup.location, signal);
273
+ if (found.kind === "live") return found.service;
274
+ if (found.kind === "refused") throw new Error(describeRefusal(found));
275
+ if (!setup.start) throw new Error("OpenCode is not running on this computer and no OpenCode program was found to start it");
276
+ await runServiceStart(setup.start, signal);
277
+ for (let attempt = 0; attempt < SERVICE_READY_ATTEMPTS && !signal.aborted; attempt++) {
278
+ const started = await discoverOpenCodeService(setup.location, signal);
279
+ if (started.kind === "live") return started.service;
280
+ if (started.kind === "refused") throw new Error(describeRefusal(started));
281
+ await liveSessionSleep(SERVICE_READY_INTERVAL_MS, signal);
282
+ }
283
+ throw new Error("OpenCode started its background service but it did not register in time");
284
+ };
285
+ var openCodeModelRef = (input) => {
286
+ const providerEnd = input.indexOf("/");
287
+ if (providerEnd <= 0) return null;
288
+ const providerID = input.slice(0, providerEnd);
289
+ const variantStart = input.indexOf("#", providerEnd + 1);
290
+ const id = input.slice(providerEnd + 1, variantStart === -1 ? void 0 : variantStart);
291
+ const variant = variantStart === -1 ? void 0 : input.slice(variantStart + 1);
292
+ if (!id || providerID.includes("#") || variant !== void 0 && (!variant || variant.includes("#"))) return null;
293
+ return variant === void 0 ? { providerID, id } : { providerID, id, variant };
294
+ };
295
+ var sessionPath = (sessionId, action) => `/api/session/${encodeURIComponent(sessionId)}${action ? `/${action}` : ""}`;
296
+ var createOpenCodeSession = async (service, request, signal) => {
297
+ const response = await service.request("POST", "/api/session", signal, {
298
+ location: { directory: request.directory },
299
+ ...request.model ? { model: request.model } : {}
300
+ });
301
+ if (!response.ok) throw new Error(`OpenCode refused to create a session (${response.status})`);
302
+ const created = createdSessionSchema.safeParse(await readJson(response));
303
+ if (!created.success) throw new Error("OpenCode created a session without a usable id");
304
+ return created.data.data.id;
305
+ };
306
+ var promptOpenCodeSession = async (service, sessionId, text, signal) => {
307
+ const response = await service.request("POST", sessionPath(sessionId, "prompt"), signal, { text });
308
+ return response.ok ? "admitted" : "refused";
309
+ };
310
+ var interruptOpenCodeSession = async (service, sessionId, signal) => {
311
+ const response = await service.request("POST", sessionPath(sessionId, "interrupt"), signal);
312
+ const interrupted = interruptSchema.safeParse(await readJson(response));
313
+ return response.ok && interrupted.success && interrupted.data.interrupted;
314
+ };
315
+ var openCodeSessionIsActive = async (service, sessionId, signal) => {
316
+ const response = await service.request("GET", "/api/session/active", signal);
317
+ if (!response.ok) throw new Error(`OpenCode did not list its active sessions (${response.status})`);
318
+ const active = activeSessionsSchema.safeParse(await readJson(response));
319
+ if (!active.success) throw new Error("OpenCode listed its active sessions in an unknown shape");
320
+ return Object.hasOwn(active.data.data, sessionId);
321
+ };
322
+ var openCodeSessionExists = async (service, sessionId, signal) => (await service.request("GET", sessionPath(sessionId), signal)).ok;
323
+ var assistantText = (content) => content.flatMap((part) => part.type === "text" && part.text ? [part.text] : []).join("");
324
+ var openCodeTranscriptMessage = (value) => {
325
+ const user = userMessageSchema.safeParse(value);
326
+ if (user.success) return user.data.text ? { id: user.data.id, role: "user", text: user.data.text } : null;
327
+ const assistant = assistantMessageSchema.safeParse(value);
328
+ if (!assistant.success) return null;
329
+ const text = assistantText(assistant.data.content);
330
+ return text ? { id: assistant.data.id, role: "assistant", text } : null;
331
+ };
332
+ var messagePageQuery = (cursor) => cursor ? `cursor=${encodeURIComponent(cursor)}&limit=${MESSAGE_PAGE_SIZE}` : `order=desc&limit=${MESSAGE_PAGE_SIZE}`;
333
+ var oldestFirst = (listed, newestFirst) => ({ listed, messages: [...newestFirst].reverse() });
334
+ var readOpenCodeMessagesSince = async (service, sessionId, isKnown, signal) => {
335
+ const listed = [];
336
+ const newestFirst = [];
337
+ let cursor = null;
338
+ for (let pagesRead = 0; pagesRead < MAX_MESSAGE_PAGES; pagesRead++) {
339
+ const response = await service.request("GET", `${sessionPath(sessionId, "message")}?${messagePageQuery(cursor)}`, signal);
340
+ if (!response.ok) throw new Error(`OpenCode did not list the session's messages (${response.status})`);
341
+ const page = messagePageSchema.safeParse(await readJson(response));
342
+ if (!page.success) throw new Error("OpenCode listed the session's messages in an unknown shape");
343
+ for (const item of page.data.data) {
344
+ if (isKnown(item.id)) return oldestFirst(listed, newestFirst);
345
+ listed.push(item.id);
346
+ const message = openCodeTranscriptMessage(item);
347
+ if (message) newestFirst.push(message);
348
+ }
349
+ cursor = page.data.cursor?.next ?? null;
350
+ if (!cursor) break;
351
+ }
352
+ return oldestFirst(listed, newestFirst);
353
+ };
354
+
355
+ // src/opencode-session-bridge.ts
356
+ import { realpathSync } from "fs";
357
+ var OPENCODE_MODEL_FORMAT_MESSAGE = "Write an OpenCode model as provider/model, for example anthropic/claude-sonnet-4-5";
358
+ var OPENCODE_SERVICE_LOST_MESSAGE = "OpenCode stopped answering, and no running OpenCode service has this session";
359
+ var OPENCODE_PROMPT_REFUSED_ACTION = "OpenCode did not accept the prompt";
360
+ var OPENCODE_IDENTITY = AGENT_IDENTITIES.opencode;
361
+ var CLOSING_TIMEOUT_MS = 3e3;
362
+ var MAX_REMEMBERED_MESSAGES = 2e3;
363
+ var DEFAULT_POLL_INTERVAL_MS = 2e3;
364
+ var SERVICE_RETURN_GRACE_MS = 3e4;
365
+ var openCodeTranscriptRecord = (message) => ({
366
+ type: message.role,
367
+ uuid: message.id,
368
+ message: { role: message.role, content: message.text }
369
+ });
370
+ var rememberMessage = (known, id) => {
371
+ if (known.has(id)) return;
372
+ if (known.size >= MAX_REMEMBERED_MESSAGES) {
373
+ const oldest = known.values().next().value;
374
+ if (oldest !== void 0) known.delete(oldest);
375
+ }
376
+ known.add(id);
377
+ };
378
+ var drainedCommand = (body) => isRecord(body) ? body.command : void 0;
379
+ var closingOptions = (options) => ({ ...options, signal: AbortSignal.timeout(CLOSING_TIMEOUT_MS) });
380
+ var failureMessage = (error) => error instanceof Error ? error.message : String(error);
381
+ var runOpenCodeBridge = async (options) => {
382
+ const now = options.now ?? Date.now;
383
+ const idleTimeoutMs = options.idleTimeoutMs ?? SESSION_IDLE_TIMEOUT_MS;
384
+ const known = /* @__PURE__ */ new Set();
385
+ let cwd = options.cwd;
386
+ let attached = null;
387
+ let ownership = null;
388
+ let relay = null;
389
+ let stopHeartbeat = () => {
390
+ };
391
+ let linked = false;
392
+ const reportBody = (event, action) => ({
393
+ event,
394
+ action,
395
+ agentType: OPENCODE_IDENTITY.type,
396
+ agentName: agentNameFor(OPENCODE_IDENTITY, cwd),
397
+ sessionId: attached?.sessionId ?? null,
398
+ spawnId: options.spawnId,
399
+ machineId: options.machineId,
400
+ pid: process.pid,
401
+ cwd
402
+ });
403
+ const report = (event, action, through = options) => postLiveSession(through, "/api/agent/event", reportBody(event, action));
404
+ const relayNewMessages = async (session, signal) => {
405
+ if (!relay) return;
406
+ const since = await readOpenCodeMessagesSince(session.service, session.sessionId, (id) => known.has(id), signal);
407
+ for (const id of since.listed) rememberMessage(known, id);
408
+ for (const message of since.messages) relay.add(openCodeTranscriptRecord(message));
409
+ };
410
+ let serviceUnreachableSince = null;
411
+ const reattached = async (session) => {
412
+ const found = await discoverOpenCodeService(options.service.location, options.signal).catch(() => null);
413
+ if (found?.kind !== "live") return false;
414
+ if (!await openCodeSessionExists(found.service, session.sessionId, options.signal).catch(() => false)) return false;
415
+ session.service = found.service;
416
+ return true;
417
+ };
418
+ const serviceStayedAway = () => {
419
+ serviceUnreachableSince ??= now();
420
+ return now() - serviceUnreachableSince >= (options.serviceReturnGraceMs ?? SERVICE_RETURN_GRACE_MS);
421
+ };
422
+ const runningOrReattached = async (session) => {
423
+ try {
424
+ const running = await openCodeSessionIsActive(session.service, session.sessionId, options.signal);
425
+ serviceUnreachableSince = null;
426
+ return running;
427
+ } catch {
428
+ if (options.signal.aborted) return null;
429
+ if (serviceStayedAway()) throw new Error(OPENCODE_SERVICE_LOST_MESSAGE);
430
+ await reattached(session);
431
+ return null;
432
+ }
433
+ };
434
+ const pollPause = () => liveSessionSleep(options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, options.signal);
435
+ try {
436
+ cwd = realpathSync(options.cwd);
437
+ const model = options.model ? openCodeModelRef(options.model) : null;
438
+ if (options.model && !model) throw new Error(OPENCODE_MODEL_FORMAT_MESSAGE);
439
+ const service = await connectOpenCodeService(options.service, options.signal);
440
+ const session = { sessionId: await createOpenCodeSession(service, { directory: cwd, model }, options.signal), service };
441
+ attached = session;
442
+ ownership = startProcessOwnership({ sessionId: session.sessionId, pid: process.pid, spawnId: options.spawnId }, { dir: options.ownershipDirectory });
443
+ await ownership.ready;
444
+ relay = options.transcripts === false ? null : options.transcriptSink?.(session.sessionId) ?? new LiveTranscriptRelay(options, session.sessionId);
445
+ await postLiveSessionUntilAccepted(options, "/api/agent/event", reportBody("session_start", "Session started"));
446
+ linked = true;
447
+ await options.onReady?.(session.sessionId);
448
+ stopHeartbeat = startLiveSessionHeartbeat(options, reportBody("heartbeat", "Session online"), void 0, () => ownership?.touch());
449
+ let active = false;
450
+ let turnPending = false;
451
+ let idleSince = now();
452
+ let idledOut = false;
453
+ const deliverPrompt = async (text) => {
454
+ const outcome2 = await promptOpenCodeSession(session.service, session.sessionId, text, options.signal);
455
+ idleSince = now();
456
+ if (outcome2 === "refused") return "failed";
457
+ turnPending = true;
458
+ return "delivered";
459
+ };
460
+ if (options.prompt) {
461
+ const delivery = await deliverPrompt(options.prompt).catch(() => "failed");
462
+ if (delivery === "failed") await report("turn_error", OPENCODE_PROMPT_REFUSED_ACTION).catch(() => null);
463
+ }
464
+ const receipts = new CommandReceipts({
465
+ submit: (command) => deliverPrompt(command.text),
466
+ log: (message) => process.stderr.write(`${message}
467
+ `)
468
+ });
469
+ const acknowledgeCommand = (commandId) => async (state, dispatchId) => readCommandAck(await postLiveSession(options, "/api/agent/command/ack", {
470
+ commandId,
471
+ sessionId: session.sessionId,
472
+ machineId: options.machineId,
473
+ state,
474
+ dispatchId
475
+ }));
476
+ while (!options.signal.aborted) {
477
+ if (!active && !turnPending && idleDeadlinePassed(idleSince, now(), idleTimeoutMs)) {
478
+ idledOut = true;
479
+ break;
480
+ }
481
+ const running = await runningOrReattached(session);
482
+ if (running === null) {
483
+ await pollPause();
484
+ continue;
485
+ }
486
+ if (running) idleSince = now();
487
+ if (!running && (active || turnPending)) await relayNewMessages(session, options.signal).catch(() => {
488
+ });
489
+ active = running;
490
+ turnPending = false;
491
+ try {
492
+ await receipts.flush();
493
+ const response = await postLiveSession(options, "/api/agent/command/drain", {
494
+ sessionId: session.sessionId,
495
+ machineId: options.machineId,
496
+ ackMode: true,
497
+ receiptVersion: 1
498
+ });
499
+ if (response.ok) {
500
+ const command = controllerCommandSchema.safeParse(drainedCommand(await response.json()));
501
+ if (command.success) {
502
+ idleSince = now();
503
+ await receipts.receive(command.data, acknowledgeCommand(command.data.id));
504
+ }
505
+ }
506
+ } catch {
507
+ }
508
+ await relay?.flush();
509
+ await pollPause();
510
+ }
511
+ if (options.signal.aborted) {
512
+ await interruptOpenCodeSession(session.service, session.sessionId, AbortSignal.timeout(CLOSING_TIMEOUT_MS)).catch(() => false);
513
+ }
514
+ await relayNewMessages(session, AbortSignal.timeout(CLOSING_TIMEOUT_MS)).catch(() => {
515
+ });
516
+ await relay?.flush();
517
+ await report(
518
+ "session_closed",
519
+ idledOut ? `Session ended after ${describeIdleWindow(idleTimeoutMs)} idle` : "Session stopped",
520
+ closingOptions(options)
521
+ ).catch(() => null);
522
+ return "stopped";
523
+ } catch (error) {
524
+ const message = failureMessage(error);
525
+ if (!linked && options.claimId) {
526
+ const through = options.signal.aborted ? closingOptions(options) : options;
527
+ await acknowledgeSpawnFailure(through, { spawnId: options.spawnId, claimId: options.claimId }, message);
528
+ }
529
+ if (options.signal.aborted) {
530
+ await report("session_closed", "Session stopped", closingOptions(options)).catch(() => null);
531
+ return "stopped";
532
+ }
533
+ await report("error", `Live bridge failed: ${message}`.slice(0, BRIDGE_FAILURE_MESSAGE_MAX)).catch(() => null);
534
+ return "failed";
535
+ } finally {
536
+ stopHeartbeat();
537
+ ownership?.stop();
538
+ }
539
+ };
540
+
541
+ // bin/pushary-opencode-bridge.ts
542
+ var spawnId = process.env.PUSHARY_SPAWN_ID?.trim();
543
+ var requestedCwd = process.env.PUSHARY_BRIDGE_CWD?.trim();
544
+ if (!spawnId || !requestedCwd || !existsSync(requestedCwd)) {
545
+ process.stderr.write("[pushary] OpenCode bridge received an invalid launch request\n");
546
+ process.exit(1);
547
+ }
548
+ var abort = new AbortController();
549
+ var signals = process.platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP"];
550
+ var stop = () => abort.abort();
551
+ for (const signal of signals) process.on(signal, stop);
552
+ var home = homedir();
553
+ var launchBinary = process.env.PUSHARY_OPENCODE_COMMAND?.trim() || resolveProviderBinary("opencode") || null;
554
+ var starter = openCodeServiceStarter(launchBinary, process.platform, isExecutableFile);
555
+ var outcome = await withSpawnProcessOwnership(spawnId, () => runOpenCodeBridge({
556
+ apiKey: getApiKey(),
557
+ baseUrl: getBaseUrl(),
558
+ machineId: getMachineId(),
559
+ spawnId,
560
+ claimId: process.env.PUSHARY_SPAWN_CLAIM_ID?.trim() || void 0,
561
+ cwd: requestedCwd,
562
+ prompt: process.env.PUSHARY_BRIDGE_PROMPT?.trim() || void 0,
563
+ model: process.env.PUSHARY_BRIDGE_MODEL?.trim() || void 0,
564
+ service: {
565
+ location: {
566
+ directory: openCodeRegistrationDirectory(process.env, home),
567
+ serviceFile: process.env[OPENCODE_SERVICE_FILE_VARIABLE]?.trim() || void 0,
568
+ owner: process.getuid?.() ?? null
569
+ },
570
+ start: starter ? { command: starter, environment: process.env, cwd: home } : null
571
+ },
572
+ signal: abort.signal,
573
+ transcripts: transcriptsEnabled()
574
+ }));
575
+ for (const signal of signals) process.off(signal, stop);
576
+ process.exit(outcome === "stopped" ? 0 : 1);