@pushary/agent-hooks 1.9.43 → 1.9.45

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 (105) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +1 -0
  3. package/dist/bin/pushary-bell-hook.js +26 -26
  4. package/dist/bin/pushary-bell.js +11 -11
  5. package/dist/bin/pushary-claude.js +33 -33
  6. package/dist/bin/pushary-clean.js +38 -38
  7. package/dist/bin/pushary-codex-bridge.js +22 -680
  8. package/dist/bin/pushary-codex-hook.js +32 -32
  9. package/dist/bin/pushary-codex-session.d.ts +1 -0
  10. package/dist/bin/pushary-codex-session.js +649 -0
  11. package/dist/bin/pushary-codex.js +12 -12
  12. package/dist/bin/pushary-connect.js +27 -27
  13. package/dist/bin/pushary-cowork.js +6 -6
  14. package/dist/bin/pushary-daemon.js +55 -55
  15. package/dist/bin/pushary-disconnect.js +26 -26
  16. package/dist/bin/pushary-doctor.js +84 -82
  17. package/dist/bin/pushary-elicitation-hook.js +26 -26
  18. package/dist/bin/pushary-gemini-bridge.js +15 -15
  19. package/dist/bin/pushary-gemini-hook.js +29 -29
  20. package/dist/bin/pushary-hook.js +32 -32
  21. package/dist/bin/pushary-login.js +16 -16
  22. package/dist/bin/pushary-logout.js +27 -27
  23. package/dist/bin/pushary-mcp.js +9 -9
  24. package/dist/bin/pushary-mode.js +14 -14
  25. package/dist/bin/pushary-notification-hook.js +25 -25
  26. package/dist/bin/pushary-opencode-hook.js +28 -28
  27. package/dist/bin/pushary-permission-denied-hook.js +30 -30
  28. package/dist/bin/pushary-permission-hook.js +29 -29
  29. package/dist/bin/pushary-post-hook.js +25 -25
  30. package/dist/bin/pushary-prompt-hook.js +25 -25
  31. package/dist/bin/pushary-session-end-hook.js +25 -25
  32. package/dist/bin/pushary-session-start-hook.js +30 -30
  33. package/dist/bin/pushary-setup.js +164 -112
  34. package/dist/bin/pushary-stats.js +5 -5
  35. package/dist/bin/pushary-status.js +34 -34
  36. package/dist/bin/pushary-stop-hook.js +25 -25
  37. package/dist/bin/pushary-stopfailure-hook.js +25 -25
  38. package/dist/bin/pushary-suggestions.js +14 -14
  39. package/dist/bin/pushary-transcript-register.js +18 -18
  40. package/dist/bin/pushary-transcripts.js +7 -7
  41. package/dist/bin/pushary-upgrade.js +41 -41
  42. package/dist/bin/pushary-wait.js +14 -14
  43. package/dist/bin/pushary.js +7 -6
  44. package/dist/{chunk-HC4DQXAT.js → chunk-2DORVRDB.js} +2 -2
  45. package/dist/{chunk-C6QBNBL4.js → chunk-2FUHSKXH.js} +7 -7
  46. package/dist/{chunk-45W43U2Q.js → chunk-2SXXH6JY.js} +5 -5
  47. package/dist/{chunk-JE6GG3OV.js → chunk-335ZDJ7R.js} +1 -1
  48. package/dist/{chunk-S4QT3YFG.js → chunk-3PM62C2R.js} +15 -15
  49. package/dist/{chunk-Y3N3SYBX.js → chunk-46F4BRUQ.js} +1 -1
  50. package/dist/{chunk-W3BO56VE.js → chunk-4A6VUVXV.js} +1 -1
  51. package/dist/{chunk-LDCRV6HG.js → chunk-57M4ERJK.js} +2 -1
  52. package/dist/{chunk-IMD5FN6Y.js → chunk-5DCZL3BC.js} +3 -3
  53. package/dist/chunk-6JPDAUFP.js +866 -0
  54. package/dist/{chunk-H6V5S52A.js → chunk-6TYKZ4DN.js} +3 -3
  55. package/dist/{chunk-VQL62ECJ.js → chunk-7SGYCU5C.js} +1 -1
  56. package/dist/{chunk-SATOTPXW.js → chunk-7URSJMAB.js} +1 -1
  57. package/dist/{chunk-PIZ65U3D.js → chunk-ASK2MSD2.js} +5 -5
  58. package/dist/{chunk-SCYAXV7U.js → chunk-AUOSFZJ3.js} +7 -7
  59. package/dist/{chunk-LOUZNXTJ.js → chunk-BT57FUMT.js} +2 -2
  60. package/dist/{chunk-4T2TGP4T.js → chunk-CDERSTBO.js} +94 -7
  61. package/dist/{chunk-LAAOHBLO.js → chunk-CFMCV6Z7.js} +2 -2
  62. package/dist/{chunk-ENGASUEL.js → chunk-DSGB5JLG.js} +4 -4
  63. package/dist/{chunk-ZJXEQV3A.js → chunk-ECFEYB6Z.js} +1 -1
  64. package/dist/{chunk-CIERFMQT.js → chunk-EH5ZDG6V.js} +4 -4
  65. package/dist/{chunk-IDVKJICN.js → chunk-EKGQEDQ4.js} +3 -11
  66. package/dist/{chunk-GTOBOC6M.js → chunk-EWC4P4ZL.js} +1 -1
  67. package/dist/{chunk-F7SZ2RCK.js → chunk-FOUK4CBO.js} +4 -4
  68. package/dist/{chunk-LE2YVPAT.js → chunk-GQ5KCVGK.js} +11 -11
  69. package/dist/{chunk-YRE6GUFZ.js → chunk-GZSSAY6N.js} +75 -161
  70. package/dist/{chunk-LWW7SBK3.js → chunk-H4ODQD3Y.js} +2 -2
  71. package/dist/{chunk-O7ADPLBF.js → chunk-HHX6IRSH.js} +1 -1
  72. package/dist/{chunk-H64CU2VB.js → chunk-IFT3GU7Y.js} +2 -2
  73. package/dist/{chunk-FPJHS6PA.js → chunk-IKYI63RF.js} +6 -6
  74. package/dist/{chunk-S3OWTQ6Z.js → chunk-IOVJVGIT.js} +12 -5
  75. package/dist/{chunk-RXXKFM22.js → chunk-K7EGWMDU.js} +370 -138
  76. package/dist/{chunk-AVT7GPOF.js → chunk-KS7NA5CK.js} +10 -10
  77. package/dist/{chunk-A64UCGX3.js → chunk-N2K3BSCA.js} +5 -5
  78. package/dist/{chunk-ZORCUL3Z.js → chunk-NJN5NRHZ.js} +4 -4
  79. package/dist/{chunk-Q7CUTGT4.js → chunk-OHFC3GJY.js} +1 -1
  80. package/dist/{chunk-JW4S4O4W.js → chunk-P2F3JUFX.js} +4 -4
  81. package/dist/{chunk-C54VJJ37.js → chunk-PWUIPQ2I.js} +3 -3
  82. package/dist/{chunk-F5ALKPNS.js → chunk-QQXP3CQA.js} +1 -1
  83. package/dist/{chunk-EA5NWDK7.js → chunk-R7ZQHAVL.js} +29 -0
  84. package/dist/{chunk-V5SUKRRI.js → chunk-RBJWPUI6.js} +4 -4
  85. package/dist/{chunk-J6MVBWF2.js → chunk-RFQWB5ZV.js} +1 -1
  86. package/dist/{chunk-NKBAEGT7.js → chunk-S6EGJBI5.js} +1 -1
  87. package/dist/{chunk-53KLSE2F.js → chunk-SFQSOBLM.js} +3 -3
  88. package/dist/{chunk-MSUMSXTI.js → chunk-SIN7NJD7.js} +1 -1
  89. package/dist/{chunk-55FB6OSG.js → chunk-U45OINYS.js} +1 -1
  90. package/dist/{chunk-TH74SUVV.js → chunk-U6Z56IQS.js} +2 -2
  91. package/dist/{chunk-JJWG7CBT.js → chunk-VO6XI6AX.js} +3 -3
  92. package/dist/{chunk-VIVLJK3T.js → chunk-WDIX4XZH.js} +2 -2
  93. package/dist/{chunk-Y4VZYKSW.js → chunk-WM76AN4X.js} +11 -11
  94. package/dist/{chunk-NV2LARV4.js → chunk-WPPKXVV3.js} +2 -2
  95. package/dist/{chunk-VGPEXMYM.js → chunk-XFHISCJM.js} +42 -7
  96. package/dist/{chunk-C3RVRTHS.js → chunk-YK7FGPYS.js} +3 -3
  97. package/dist/{chunk-JB4JCGRW.js → chunk-YWIFK2UB.js} +2 -2
  98. package/dist/{chunk-O4SYJVAF.js → chunk-YXGWG5PO.js} +5 -5
  99. package/dist/{chunk-XLHFWG2E.js → chunk-ZSY6BWUD.js} +2 -2
  100. package/dist/{global-upgrade-FFWOHOJ4.js → global-upgrade-U6NWZA5W.js} +6 -6
  101. package/dist/{paths-Y2WPCM5Y.js → paths-IQTB3ZZI.js} +2 -2
  102. package/dist/{reapply-N3MV3CKD.js → reapply-LILGWJO3.js} +21 -21
  103. package/dist/src/index.js +19 -19
  104. package/dist/{upgrade-lock-ZXXNRH2P.js → upgrade-lock-2BVFIDU4.js} +3 -3
  105. package/package.json +5 -2
@@ -1,703 +1,45 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- LiveTranscriptRelay,
4
- liveSessionSleep,
5
- postLiveSession,
6
- postLiveSessionUntilAccepted,
7
- startLiveSessionHeartbeat
8
- } from "../chunk-IDVKJICN.js";
3
+ transcriptsEnabled
4
+ } from "../chunk-7SGYCU5C.js";
5
+ import "../chunk-YK7FGPYS.js";
6
+ import {
7
+ runCodexBridge
8
+ } from "../chunk-6JPDAUFP.js";
9
+ import "../chunk-EKGQEDQ4.js";
9
10
  import {
10
11
  resolveProviderBinary
11
- } from "../chunk-NV2LARV4.js";
12
+ } from "../chunk-WPPKXVV3.js";
12
13
  import "../chunk-RIVNNBEK.js";
13
14
  import {
14
- SESSION_IDLE_TIMEOUT_MS,
15
- describeIdleWindow,
16
- idleDeadlinePassed,
17
- startProcessOwnership,
18
15
  withSpawnProcessOwnership
19
- } from "../chunk-LWW7SBK3.js";
20
- import "../chunk-MSUMSXTI.js";
21
- import "../chunk-J6MVBWF2.js";
22
- import {
23
- transcriptsEnabled
24
- } from "../chunk-VQL62ECJ.js";
25
- import {
26
- spawnClaude
27
- } from "../chunk-XHKBHWLX.js";
16
+ } from "../chunk-H4ODQD3Y.js";
17
+ import "../chunk-SIN7NJD7.js";
18
+ import "../chunk-RFQWB5ZV.js";
19
+ import "../chunk-XHKBHWLX.js";
28
20
  import "../chunk-6ICPEJY5.js";
29
- import "../chunk-C3RVRTHS.js";
30
- import {
31
- isAskUserResponse,
32
- isDecisionStopped,
33
- isWaitForAnswerResponse,
34
- withdrawQuestion,
35
- writeDegraded
36
- } from "../chunk-4T2TGP4T.js";
21
+ import "../chunk-CFMCV6Z7.js";
22
+ import "../chunk-CDERSTBO.js";
37
23
  import "../chunk-POFBE6ZY.js";
38
- import {
39
- callMcpTool,
40
- isRetryable
41
- } from "../chunk-53KLSE2F.js";
42
- import "../chunk-C54VJJ37.js";
43
- import "../chunk-H6V5S52A.js";
24
+ import "../chunk-SFQSOBLM.js";
25
+ import "../chunk-PWUIPQ2I.js";
26
+ import "../chunk-6TYKZ4DN.js";
44
27
  import {
45
28
  getMachineId
46
- } from "../chunk-W3BO56VE.js";
29
+ } from "../chunk-4A6VUVXV.js";
47
30
  import "../chunk-7QLSKOSU.js";
48
31
  import "../chunk-KZERVKTD.js";
49
- import "../chunk-LAAOHBLO.js";
50
- import "../chunk-S3OWTQ6Z.js";
32
+ import "../chunk-IOVJVGIT.js";
51
33
  import "../chunk-AQFEP65J.js";
52
34
  import {
53
35
  getApiKey,
54
36
  getBaseUrl
55
- } from "../chunk-GTOBOC6M.js";
56
- import "../chunk-LDCRV6HG.js";
57
- import {
58
- AGENT_QUESTION_DESCRIPTION_MAX,
59
- AGENT_QUESTION_HEADER_MAX,
60
- AGENT_QUESTION_OPTION_MAX,
61
- ASK_CONTEXT_MAX,
62
- ASK_QUESTION_MAX,
63
- PERSONAL_QUESTION_CAPABILITY,
64
- canonicalJsonText,
65
- elicitationContent,
66
- isQuestionOwner,
67
- parseAgentQuestionAnswers,
68
- parseCodexQuestions,
69
- planElicitationAsk,
70
- readElicitationFields
71
- } from "../chunk-RXXKFM22.js";
37
+ } from "../chunk-EWC4P4ZL.js";
38
+ import "../chunk-57M4ERJK.js";
39
+ import "../chunk-K7EGWMDU.js";
72
40
 
73
41
  // bin/pushary-codex-bridge.ts
74
42
  import { existsSync } from "fs";
75
-
76
- // src/codex-question-owner.ts
77
- import { createHash } from "crypto";
78
- var codexQuestionOwner = (params, requestId, runtime) => {
79
- if (params.threadId !== runtime.threadId || typeof params.isBlocking !== "boolean") return null;
80
- const owner = {
81
- capability: PERSONAL_QUESTION_CAPABILITY,
82
- machineId: runtime.machineId,
83
- generation: runtime.generation,
84
- threadId: params.threadId,
85
- turnId: params.turnId,
86
- itemId: params.itemId,
87
- requestId,
88
- method: "item/tool/requestUserInput",
89
- subjectHash: createHash("sha256").update(canonicalJsonText(params)).digest("hex")
90
- };
91
- return isQuestionOwner(owner) ? owner : null;
92
- };
93
- var closesOwnedQuestion = (owner, method, params) => {
94
- if (method === "serverRequest/resolved") return params.requestId === owner.requestId;
95
- if (params.threadId !== owner.threadId) return false;
96
- if (method === "thread/closed" || method === "thread/archived") return true;
97
- if (method === "turn/completed") {
98
- const turn = params.turn;
99
- return turn !== null && typeof turn === "object" && "id" in turn && turn.id === owner.turnId;
100
- }
101
- if (method === "item/completed" && params.turnId === owner.turnId) {
102
- const item = params.item;
103
- return item !== null && typeof item === "object" && "id" in item && item.id === owner.itemId;
104
- }
105
- return false;
106
- };
107
-
108
- // src/question-dispatch.ts
109
- var claimOwnedQuestion = async (options, dispatch) => {
110
- const response = await postLiveSession(options, "/api/agent/question/dispatch", {
111
- owner: dispatch.owner,
112
- correlationIds: dispatch.correlationIds,
113
- operation: "claim"
114
- });
115
- const body = await response.json();
116
- if (!response.ok || body === null || typeof body !== "object" || !("claimId" in body) || typeof body.claimId !== "string" || !body.claimId) throw new Error("Question delivery could not be claimed");
117
- dispatch.claimId = body.claimId;
118
- };
119
- var reportOwnedQuestion = async (options, dispatch, operation) => {
120
- if (dispatch.correlationIds.length === 0) return;
121
- try {
122
- const response = await postLiveSession({ ...options, signal: AbortSignal.timeout(3e3), requestTimeoutMs: 3e3 }, "/api/agent/question/dispatch", {
123
- owner: dispatch.owner,
124
- correlationIds: dispatch.correlationIds,
125
- claimId: dispatch.claimId,
126
- operation
127
- });
128
- if (!response.ok) throw new Error("Receipt refused");
129
- } catch {
130
- writeDegraded("questions", { reason: "question_receipt_unconfirmed", fallback: "no automatic replay", event: operation });
131
- }
132
- };
133
-
134
- // src/codex-bridge.ts
135
- import { randomUUID } from "crypto";
136
-
137
- // src/codex-elicitation.ts
138
- var planCodexElicitation = (params, threadId) => {
139
- if (!threadId || params.threadId !== threadId || params.mode !== "form" || params._meta != null || typeof params.serverName !== "string" || !params.serverName.trim() || typeof params.message !== "string" || !params.message.trim()) return null;
140
- const fields = readElicitationFields(params.requestedSchema);
141
- if (!fields || fields.length > 3) return null;
142
- const plan = [];
143
- for (const [index, field] of fields.entries()) {
144
- const question = `${params.serverName}: ${params.message} \u2014 ${field.label}`;
145
- const ask = planElicitationAsk(question, [field]);
146
- if (!ask || ask.kind === "questions" || question.length > 500) return null;
147
- let labels = [];
148
- if (ask.kind === "confirm") labels = ["Yes", "No"];
149
- if (ask.kind === "select") labels = ask.options;
150
- if (labels.length > 4 || labels.some((label) => label.length > 100)) return null;
151
- plan.push({ ask, question: { id: String(index), question, isOther: false, options: labels.map((label) => ({ label })) } });
152
- }
153
- return plan;
154
- };
155
- var codexElicitationContent = (plan, answers) => {
156
- let content = {};
157
- for (const { ask, question } of plan) {
158
- const values = answers[question.id]?.answers;
159
- if (!values || values.length !== 1) return null;
160
- const field = elicitationContent(ask, values[0]);
161
- if (!field) return null;
162
- content = { ...content, ...field };
163
- }
164
- return content;
165
- };
166
-
167
- // src/codex-bridge.ts
168
- import { spawn } from "child_process";
169
- import { basename } from "path";
170
- var MAX_RPC_LINE = 1024 * 1024;
171
- var STDERR_TAIL_LIMIT = 2e3;
172
- var FAILURE_MESSAGE_MAX = 240;
173
- var MAX_PENDING_RPC = 8;
174
- var QUESTION_UNAVAILABLE = "Question unavailable";
175
- var LOCAL_QUESTION_UNAVAILABLE = "Pushary handed this question to the current client, but this Codex bridge has no local question UI. Continue in an interactive Codex session, or choose a Pushary mode that permits remote questions.";
176
- var MAX_TRANSCRIPT_TEXT = 32 * 1024;
177
- var MAX_MESSAGE_BUFFERS = 16;
178
- var JsonRpcClient = class {
179
- constructor(command, cwd, timeoutMs, bridgeOptions) {
180
- this.bridgeOptions = bridgeOptions;
181
- this.threadId = bridgeOptions.resumeThreadId ?? null;
182
- const options = { cwd, env: { ...process.env, PUSHARY_CODEX_BRIDGE: "1" }, stdio: ["pipe", "pipe", "pipe"] };
183
- this.child = process.platform === "win32" ? spawnClaude(command.command, command.args ?? [], options) : spawn(command.command, command.args ?? [], options);
184
- this.child.stdout?.setEncoding("utf8");
185
- this.child.stdout?.on("data", (chunk) => this.read(String(chunk)));
186
- this.child.stderr?.setEncoding("utf8");
187
- this.child.stderr?.on("data", (chunk) => this.keepStderrTail(String(chunk)));
188
- this.child.once("error", (error) => this.fail(error));
189
- this.child.once("exit", (code, signal) => this.fail(new Error(this.exitMessage(code, signal))));
190
- this.timeoutMs = timeoutMs;
191
- }
192
- child;
193
- pending = /* @__PURE__ */ new Map();
194
- notifications = /* @__PURE__ */ new Set();
195
- generation = randomUUID();
196
- serverRequests = /* @__PURE__ */ new Map();
197
- threadId = null;
198
- nextId = 1;
199
- buffer = "";
200
- closed = false;
201
- stderrTail = "";
202
- failure = null;
203
- keepStderrTail(chunk) {
204
- this.stderrTail = (this.stderrTail + chunk).slice(-STDERR_TAIL_LIMIT);
205
- }
206
- exitMessage(code, signal) {
207
- const how = signal ? `signal ${signal}` : `code ${code ?? "unknown"}`;
208
- const tail = this.stderrTail.trim();
209
- return tail ? `Codex app-server exited (${how}): ${tail}` : `Codex app-server exited (${how})`;
210
- }
211
- timeoutMs;
212
- get isClosed() {
213
- return this.closed;
214
- }
215
- get closedReason() {
216
- return this.failure?.message ?? "Codex app-server exited";
217
- }
218
- onNotification(listener) {
219
- this.notifications.add(listener);
220
- return () => this.notifications.delete(listener);
221
- }
222
- bindThread(threadId) {
223
- this.threadId = threadId;
224
- }
225
- notify(method) {
226
- this.write({ method });
227
- }
228
- request(method, params) {
229
- if (this.closed) return Promise.reject(new Error("Codex app-server is closed"));
230
- if (this.pending.size >= MAX_PENDING_RPC) return Promise.reject(new Error("Codex app-server request limit reached"));
231
- const id = this.nextId++;
232
- return new Promise((resolve, reject) => {
233
- const timer = setTimeout(() => {
234
- this.pending.delete(id);
235
- reject(new Error(`${method} timed out`));
236
- }, this.timeoutMs);
237
- this.pending.set(id, { resolve, reject, timer });
238
- this.write({ id, method, params });
239
- });
240
- }
241
- async close() {
242
- if (this.closed) return;
243
- this.closed = true;
244
- for (const request of this.serverRequests.values()) {
245
- request.controller.abort();
246
- if (request.dispatch) void reportOwnedQuestion(this.bridgeOptions, request.dispatch, "unavailable");
247
- }
248
- this.serverRequests.clear();
249
- this.child.stdin?.end();
250
- if (this.child.exitCode != null) return;
251
- await Promise.race([
252
- new Promise((resolve) => this.child.once("exit", () => resolve())),
253
- new Promise((resolve) => setTimeout(resolve, 1e3))
254
- ]);
255
- if (this.child.exitCode == null) this.child.kill();
256
- this.rejectPending(new Error("Codex app-server closed"));
257
- }
258
- write(value) {
259
- this.child.stdin?.write(`${JSON.stringify(value)}
260
- `);
261
- }
262
- read(chunk) {
263
- this.buffer += chunk;
264
- if (this.buffer.length > MAX_RPC_LINE && !this.buffer.includes("\n")) {
265
- this.fail(new Error("Codex app-server sent an oversized message"));
266
- return;
267
- }
268
- let newline = this.buffer.indexOf("\n");
269
- while (newline >= 0) {
270
- const line = this.buffer.slice(0, newline);
271
- this.buffer = this.buffer.slice(newline + 1);
272
- if (line.length > MAX_RPC_LINE) {
273
- this.fail(new Error("Codex app-server sent an oversized message"));
274
- return;
275
- }
276
- this.handle(line);
277
- newline = this.buffer.indexOf("\n");
278
- }
279
- }
280
- handle(line) {
281
- let message;
282
- try {
283
- const parsed = JSON.parse(line);
284
- if (!isRpcMessage(parsed)) return;
285
- message = parsed;
286
- } catch {
287
- return;
288
- }
289
- if (message.id !== void 0 && (message.method === "item/tool/requestUserInput" || message.method === "mcpServer/elicitation/request")) {
290
- const id = message.id;
291
- const owner = message.method === "item/tool/requestUserInput" ? codexQuestionOwner(message.params ?? {}, id, { machineId: this.bridgeOptions.machineId, generation: this.generation, threadId: this.threadId }) : null;
292
- if (message.method === "item/tool/requestUserInput" && !owner) {
293
- this.write({ id, error: { code: -32e3, message: "Unsupported question ownership" } });
294
- return;
295
- }
296
- const existing = this.serverRequests.get(id);
297
- if (existing) {
298
- if (existing.dispatch && existing.dispatch.owner.subjectHash !== owner?.subjectHash) existing.controller.abort();
299
- return;
300
- }
301
- if (this.serverRequests.size >= MAX_PENDING_RPC) {
302
- this.write({ id, error: { code: -32e3, message: "Too many pending user questions" } });
303
- return;
304
- }
305
- const controller = new AbortController();
306
- const now = this.bridgeOptions.now ?? Date.now;
307
- const duration = message.params?.autoResolutionMs;
308
- if (duration != null && (typeof duration !== "number" || !Number.isFinite(duration) || duration < 0)) {
309
- this.write({ id, error: { code: -32e3, message: "Invalid question deadline" } });
310
- return;
311
- }
312
- const deadline = typeof duration === "number" ? now() + duration : null;
313
- const dispatch = owner ? { owner, correlationIds: [], deadline } : void 0;
314
- this.serverRequests.set(id, { controller, dispatch });
315
- const signal = AbortSignal.any([controller.signal, this.bridgeOptions.signal]);
316
- const answer = message.method === "mcpServer/elicitation/request" ? answerCodexElicitation(this.bridgeOptions, message.params ?? {}, this.threadId, signal) : answerCodexQuestions(this.bridgeOptions, message.params ?? {}, signal, "request_user_input", dispatch);
317
- void answer.then(
318
- async (result) => {
319
- if (signal.aborted || this.closed) return;
320
- if (dispatch) await claimOwnedQuestion(this.bridgeOptions, dispatch);
321
- if (signal.aborted || this.closed || this.serverRequests.get(id)?.controller !== controller) return;
322
- if (deadline !== null && now() >= deadline) throw new Error("Question expired");
323
- this.write({ id, result });
324
- if (dispatch) await reportOwnedQuestion(this.bridgeOptions, dispatch, "reply_queued");
325
- },
326
- (error) => {
327
- if (!signal.aborted && !this.closed) this.write({ id, error: { code: -32e3, message: error instanceof Error && error.message === LOCAL_QUESTION_UNAVAILABLE ? LOCAL_QUESTION_UNAVAILABLE : "No user answer was received through Pushary" } });
328
- }
329
- ).catch(() => {
330
- if (!signal.aborted && !this.closed) this.write({ id, error: { code: -32e3, message: "Question delivery is unconfirmed; no automatic retry" } });
331
- }).finally(async () => {
332
- if (dispatch && (signal.aborted || !dispatch.claimId)) await reportOwnedQuestion(this.bridgeOptions, dispatch, "unavailable");
333
- if (!dispatch?.claimId || signal.aborted) this.serverRequests.delete(id);
334
- });
335
- return;
336
- }
337
- if (message.id !== void 0 && message.method) {
338
- const result = message.method === "item/commandExecution/requestApproval" || message.method === "item/fileChange/requestApproval" ? { decision: "decline" } : message.method === "applyPatchApproval" || message.method === "execCommandApproval" ? { decision: { denied: { rejection: "No interactive Codex client is attached" } } } : null;
339
- this.write(result ? { id: message.id, result } : { id: message.id, error: { code: -32601, message: "Unsupported server request" } });
340
- return;
341
- }
342
- if (typeof message.id === "number") {
343
- const pending = this.pending.get(message.id);
344
- if (!pending) return;
345
- this.pending.delete(message.id);
346
- clearTimeout(pending.timer);
347
- if (message.error) pending.reject(new Error(message.error.message ?? "Codex app-server request failed"));
348
- else pending.resolve(message.result);
349
- return;
350
- }
351
- if (message.method) {
352
- for (const request of this.serverRequests.values()) {
353
- if (request.dispatch && closesOwnedQuestion(request.dispatch.owner, message.method, message.params ?? {})) {
354
- request.controller.abort();
355
- void reportOwnedQuestion(this.bridgeOptions, request.dispatch, request.dispatch.claimId ? "request_closed" : "unavailable");
356
- this.serverRequests.delete(request.dispatch.owner.requestId);
357
- } else if (!request.dispatch && message.method === "serverRequest/resolved") {
358
- const id = message.params?.requestId;
359
- if ((typeof id === "string" || typeof id === "number") && this.serverRequests.get(id) === request) request.controller.abort();
360
- }
361
- }
362
- }
363
- if (message.method) {
364
- for (const listener of this.notifications) listener(message);
365
- }
366
- }
367
- fail(error) {
368
- if (this.closed) return;
369
- this.closed = true;
370
- this.failure = error;
371
- for (const request of this.serverRequests.values()) {
372
- request.controller.abort();
373
- if (request.dispatch) void reportOwnedQuestion(this.bridgeOptions, request.dispatch, "unavailable");
374
- }
375
- this.serverRequests.clear();
376
- this.rejectPending(error);
377
- if (this.child.exitCode == null) this.child.kill();
378
- }
379
- rejectPending(error) {
380
- for (const pending of this.pending.values()) {
381
- clearTimeout(pending.timer);
382
- pending.reject(error);
383
- }
384
- this.pending.clear();
385
- }
386
- };
387
- var isJsonObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
388
- var object = (value) => isJsonObject(value) ? value : null;
389
- var isRpcMessage = (value) => isJsonObject(value) && (value.id === void 0 || typeof value.id === "string" || typeof value.id === "number" && Number.isFinite(value.id)) && (value.method === void 0 || typeof value.method === "string") && (value.params === void 0 || isJsonObject(value.params)) && (value.error === void 0 || isJsonObject(value.error) && (value.error.message === void 0 || typeof value.error.message === "string"));
390
- var string = (value) => typeof value === "string" && value.length > 0 ? value : null;
391
- var input = (text) => [{ type: "text", text, text_elements: [] }];
392
- var rpcThreadId = (result) => string(object(object(result)?.thread)?.id);
393
- var rpcTurnId = (result) => {
394
- const response = object(result);
395
- return string(object(response?.turn)?.id) ?? string(response?.turnId);
396
- };
397
- var readCodexBridgeQuestion = (raw) => {
398
- const question = object(raw);
399
- const id = string(question?.id);
400
- const prompt = string(question?.question);
401
- if (!question || !id || !prompt || prompt.length > ASK_QUESTION_MAX || question.isSecret != null && question.isSecret !== false || question.isOther != null && typeof question.isOther !== "boolean" || question.multiSelect != null && question.multiSelect !== false || question.header !== void 0 && typeof question.header !== "string") throw new Error("Unsupported question");
402
- const hasChoices = question.options != null && !(Array.isArray(question.options) && question.options.length === 0);
403
- const structured = hasChoices ? parseCodexQuestions("request_user_input", { questions: [{ ...question, multiSelect: false, allowOther: question.isOther === true }] })?.[0] : void 0;
404
- if (hasChoices && !structured) throw new Error("Unsupported question");
405
- const headerLimit = structured ? AGENT_QUESTION_HEADER_MAX : ASK_CONTEXT_MAX;
406
- if (typeof question.header === "string" && question.header.length > headerLimit || structured?.options.some((option) => option.label.length > AGENT_QUESTION_OPTION_MAX || (option.description?.length ?? 0) > AGENT_QUESTION_DESCRIPTION_MAX)) throw new Error("Unsupported question");
407
- return { question, id, prompt, structured };
408
- };
409
- var answerCodexQuestions = async (options, params, signal, toolName = "request_user_input", dispatch) => {
410
- if (!Array.isArray(params.questions) || !params.questions.length || params.questions.length > 3) throw new Error("Invalid questions");
411
- const questions = params.questions.map(readCodexBridgeQuestion);
412
- if (new Set(questions.map((question) => question.id)).size !== questions.length) throw new Error("Unsupported question");
413
- const answers = /* @__PURE__ */ Object.create(null);
414
- const now = options.now ?? Date.now;
415
- if (params.autoResolutionMs != null && (typeof params.autoResolutionMs !== "number" || !Number.isFinite(params.autoResolutionMs) || params.autoResolutionMs < 0)) throw new Error("Invalid question deadline");
416
- const deadline = dispatch ? dispatch.deadline : typeof params.autoResolutionMs === "number" ? now() + params.autoResolutionMs : null;
417
- for (const { question, id, prompt, structured } of questions) {
418
- if (signal.aborted || deadline !== null && now() >= deadline) throw new Error("Question expired");
419
- const labels = structured?.options.map((option) => option.label) ?? [];
420
- let correlationId = null;
421
- let settled = false;
422
- const call = async (name, args, timeoutMs, waitSignal = signal) => {
423
- const result = await callMcpTool(options.apiKey, name, args, { baseUrl: options.baseUrl, signal: waitSignal, timeoutMs, maxRetries: 1 });
424
- if (name === "wait_for_answer" && !isWaitForAnswerResponse(result)) throw new Error("Invalid wait_for_answer response");
425
- return result;
426
- };
427
- try {
428
- signal.throwIfAborted();
429
- if (deadline !== null && now() >= deadline) throw new Error("Question expired");
430
- let result = await call("ask_user", {
431
- ...dispatch ? { questionOwner: dispatch.owner } : {},
432
- requestId: randomUUID(),
433
- question: prompt,
434
- type: labels.length >= 2 ? "select" : "input",
435
- ...labels.length >= 2 ? { options: labels } : {},
436
- ...structured ? { questions: [structured] } : {},
437
- context: string(question?.header),
438
- agentName: `Codex - ${basename(options.cwd)}`,
439
- sessionId: params.threadId,
440
- machineId: options.machineId,
441
- toolName,
442
- wait: false,
443
- ...deadline === null ? {} : { waitEndsAt: new Date(deadline).toISOString() },
444
- localSurfaceAvailable: false
445
- }, deadline === null ? 1e4 : Math.min(1e4, deadline - now()));
446
- correlationId = string(object(result)?.correlationId);
447
- if (!isAskUserResponse(result)) throw new Error("Invalid ask_user response");
448
- if (correlationId && dispatch) dispatch.correlationIds.push(correlationId);
449
- while (!result.answered) {
450
- if (result.status === "terminal" || result.status === "notified" || result.suppressed || result.mode === "terminal_only" || result.mode === "notify_only") {
451
- if (correlationId) {
452
- const withdrawn = await withdrawQuestion(options.apiKey, correlationId, {
453
- cancelQuestion: (_key, id2, abort2) => call("cancel_question", { correlationId: id2 }, 3e3, abort2),
454
- waitForAnswer: (_key, id2, timeoutMs, abort2) => call("wait_for_answer", { correlationId: id2, timeoutMs }, 2e3, abort2)
455
- });
456
- result = { ...withdrawn };
457
- settled = withdrawn.answered || withdrawn.status === "withdrawn" || isDecisionStopped(withdrawn);
458
- if (withdrawn.answered) break;
459
- if (isDecisionStopped(withdrawn)) throw new Error(QUESTION_UNAVAILABLE);
460
- }
461
- throw new Error(LOCAL_QUESTION_UNAVAILABLE);
462
- }
463
- if (signal.aborted) throw new Error("Question cancelled");
464
- if (!correlationId || result.handoffAction === "stop" && result.status !== "unavailable" || result.noDevices || result.status && result.status !== "pending" && result.status !== "unavailable") throw new Error(QUESTION_UNAVAILABLE);
465
- const remaining = deadline === null ? 27e3 : deadline - now();
466
- if (remaining <= 0) throw new Error("Question expired");
467
- try {
468
- result = await call("wait_for_answer", { correlationId, timeoutMs: Math.min(25e3, remaining) }, Math.min(27e3, remaining));
469
- } catch (error) {
470
- if (signal.aborted || !isRetryable(error)) throw error;
471
- await liveSessionSleep(2e3, signal);
472
- continue;
473
- }
474
- if (!result.answered) await liveSessionSleep(result.status === "unavailable" ? 2e3 : 100, signal);
475
- }
476
- if (signal.aborted || deadline !== null && now() >= deadline) throw new Error("Question expired");
477
- settled = true;
478
- const rawValue = string(result.value);
479
- const value = rawValue && structured ? (parseAgentQuestionAnswers([structured], rawValue) ?? parseAgentQuestionAnswers([structured], JSON.stringify({ [prompt]: rawValue })))?.[prompt] : rawValue;
480
- if (!value || value === "defer" || labels.length && question?.isOther !== true && !labels.includes(value)) throw new Error("Invalid answer");
481
- answers[id] = { answers: [value] };
482
- } finally {
483
- if (correlationId && !settled) {
484
- await call("cancel_question", { correlationId }, 3e3, AbortSignal.timeout(3e3)).catch(() => {
485
- });
486
- }
487
- }
488
- }
489
- return { answers };
490
- };
491
- var answerCodexElicitation = async (options, params, threadId, signal) => {
492
- const plan = planCodexElicitation(params, threadId);
493
- if (!plan) {
494
- writeDegraded("questions", { reason: "unsupported_codex_elicitation", fallback: "no form answer submitted", event: "mcpServer/elicitation/request" });
495
- return { action: "cancel", content: null };
496
- }
497
- try {
498
- const result = await answerCodexQuestions(options, {
499
- threadId,
500
- questions: plan.map((field) => field.question)
501
- }, signal, "Elicitation");
502
- const content = codexElicitationContent(plan, result.answers);
503
- if (!content) throw new Error("Invalid elicitation answer");
504
- return { action: "accept", content };
505
- } catch {
506
- writeDegraded("questions", { reason: "codex_elicitation_unanswered", fallback: "no form answer submitted", event: "mcpServer/elicitation/request" });
507
- return { action: "cancel", content: null };
508
- }
509
- };
510
- var runCodexBridge = async (options) => {
511
- const timeoutMs = options.requestTimeoutMs ?? 1e4;
512
- const now = options.now ?? Date.now;
513
- const idleTimeoutMs = options.idleTimeoutMs ?? SESSION_IDLE_TIMEOUT_MS;
514
- const rpc = new JsonRpcClient(options.appServer, options.cwd, timeoutMs, options);
515
- let threadId = options.resumeThreadId ?? null;
516
- let activeTurnId = null;
517
- let lastCompletedTurnId = null;
518
- let idleSince = now();
519
- let idledOut = false;
520
- let relay = null;
521
- let linked = false;
522
- let stopHeartbeat = () => {
523
- };
524
- let ownership = null;
525
- const messages = /* @__PURE__ */ new Map();
526
- const idleDeadlineReached = () => activeTurnId === null && idleDeadlinePassed(idleSince, now(), idleTimeoutMs);
527
- const reportBody = (event, action) => ({
528
- event,
529
- action,
530
- agentType: "codex",
531
- agentName: `Codex - ${basename(options.cwd)}`,
532
- sessionId: threadId,
533
- codexThreadId: threadId,
534
- spawnId: options.spawnId,
535
- machineId: options.machineId,
536
- pid: process.pid,
537
- cwd: options.cwd
538
- });
539
- const report = (event, action) => postLiveSession(options, "/api/agent/event", reportBody(event, action));
540
- const removeNotification = rpc.onNotification((message) => {
541
- const params = message.params ?? {};
542
- if (message.method === "turn/started") activeTurnId = string(object(params.turn)?.id);
543
- if (message.method === "turn/completed") {
544
- lastCompletedTurnId = string(object(params.turn)?.id) ?? activeTurnId;
545
- activeTurnId = null;
546
- idleSince = now();
547
- void report("stop", "Turn completed").catch(() => {
548
- });
549
- }
550
- if (message.method === "item/agentMessage/delta") {
551
- const itemId = string(params.itemId);
552
- const delta = string(params.delta);
553
- if (!itemId || !delta) return;
554
- if (!messages.has(itemId) && messages.size === MAX_MESSAGE_BUFFERS) {
555
- const oldest = messages.keys().next().value;
556
- if (typeof oldest === "string") messages.delete(oldest);
557
- }
558
- messages.set(itemId, `${messages.get(itemId) ?? ""}${delta}`.slice(0, MAX_TRANSCRIPT_TEXT));
559
- }
560
- if (message.method === "item/completed") {
561
- const itemId = string(object(params.item)?.id);
562
- const text = itemId ? messages.get(itemId) : null;
563
- if (!itemId || !text) return;
564
- messages.delete(itemId);
565
- relay?.add({ type: "assistant", uuid: itemId, message: { role: "assistant", content: text } });
566
- }
567
- });
568
- try {
569
- await rpc.request("initialize", {
570
- clientInfo: { name: "pushary", title: "Pushary", version: "1" },
571
- capabilities: { experimentalApi: true, requestAttestation: false }
572
- });
573
- rpc.notify("initialized");
574
- const thread = options.resumeThreadId ? await rpc.request("thread/resume", { threadId: options.resumeThreadId, cwd: options.cwd, excludeTurns: true }) : await rpc.request("thread/start", { cwd: options.cwd, model: options.model ?? null });
575
- threadId = rpcThreadId(thread);
576
- if (threadId) rpc.bindThread(threadId);
577
- if (!threadId) throw new Error("Codex app-server did not return a thread id");
578
- ownership = startProcessOwnership({ sessionId: threadId, pid: process.pid, spawnId: options.spawnId });
579
- await ownership.ready;
580
- relay = options.transcripts === false ? null : new LiveTranscriptRelay(options, threadId);
581
- await postLiveSessionUntilAccepted(
582
- options,
583
- "/api/agent/event",
584
- reportBody("session_start", options.resumeThreadId ? "Session resumed" : "Session started")
585
- );
586
- linked = true;
587
- stopHeartbeat = startLiveSessionHeartbeat(
588
- options,
589
- reportBody("heartbeat", "Session online"),
590
- void 0,
591
- () => ownership?.touch()
592
- );
593
- const startTurn = async (text, commandId) => {
594
- relay?.add({ type: "user", uuid: commandId, message: { role: "user", content: text } });
595
- const result = activeTurnId ? await rpc.request("turn/steer", {
596
- threadId,
597
- expectedTurnId: activeTurnId,
598
- input: input(text),
599
- clientUserMessageId: commandId
600
- }) : await rpc.request("turn/start", {
601
- threadId,
602
- input: input(text),
603
- cwd: options.cwd,
604
- model: options.model ?? null,
605
- clientUserMessageId: commandId
606
- });
607
- const startedTurnId = rpcTurnId(result);
608
- if (startedTurnId && startedTurnId !== lastCompletedTurnId) activeTurnId = startedTurnId;
609
- };
610
- if (options.prompt) await startTurn(options.prompt, `spawn-${options.spawnId}`);
611
- let pendingAck = null;
612
- while (!options.signal.aborted && !rpc.isClosed) {
613
- if (idleDeadlineReached()) {
614
- idledOut = true;
615
- break;
616
- }
617
- try {
618
- if (pendingAck) {
619
- const acknowledged = await postLiveSession(options, "/api/agent/command/ack", pendingAck);
620
- if (acknowledged.ok) pendingAck = null;
621
- }
622
- if (pendingAck) {
623
- await liveSessionSleep(options.pollIntervalMs ?? 2e3, options.signal);
624
- continue;
625
- }
626
- const response = await postLiveSession(options, "/api/agent/command/drain", {
627
- sessionId: threadId,
628
- machineId: options.machineId,
629
- ackMode: true
630
- });
631
- if (response.ok) {
632
- const command = object((await response.json()).command);
633
- const commandId = string(command?.id);
634
- const text = string(command?.text);
635
- if (commandId && text) {
636
- idleSince = now();
637
- try {
638
- await startTurn(text, commandId);
639
- pendingAck = {
640
- commandId,
641
- sessionId: threadId,
642
- machineId: options.machineId,
643
- state: "delivered"
644
- };
645
- } catch {
646
- pendingAck = {
647
- commandId,
648
- sessionId: threadId,
649
- machineId: options.machineId,
650
- state: "failed",
651
- failureCode: "codex_rejected"
652
- };
653
- }
654
- }
655
- }
656
- } catch {
657
- }
658
- await relay?.flush();
659
- await liveSessionSleep(options.pollIntervalMs ?? 2e3, options.signal);
660
- }
661
- if (rpc.isClosed && !options.signal.aborted) throw new Error(rpc.closedReason);
662
- if (activeTurnId) {
663
- await rpc.request("turn/interrupt", { threadId, turnId: activeTurnId }).catch(() => null);
664
- }
665
- await relay?.flush();
666
- await report(
667
- "session_closed",
668
- idledOut ? `Session ended after ${describeIdleWindow(idleTimeoutMs)} idle` : "Session stopped"
669
- ).catch(() => null);
670
- return "stopped";
671
- } catch (error) {
672
- const message = error instanceof Error ? error.message : String(error);
673
- if (!linked && options.claimId) {
674
- for (let attempt = 0; attempt < 3; attempt++) {
675
- const acknowledged = await postLiveSession(options, "/api/agent/spawn/ack", {
676
- spawnId: options.spawnId,
677
- claimId: options.claimId,
678
- machineId: options.machineId,
679
- state: "failed",
680
- failure: {
681
- code: "bridge_failed",
682
- message: message.slice(0, FAILURE_MESSAGE_MAX),
683
- retryable: false
684
- }
685
- }).catch(() => null);
686
- if (acknowledged?.ok) break;
687
- await liveSessionSleep(200 * (attempt + 1), options.signal);
688
- }
689
- }
690
- await report("error", `Live bridge failed: ${message}`.slice(0, FAILURE_MESSAGE_MAX)).catch(() => null);
691
- return "failed";
692
- } finally {
693
- stopHeartbeat();
694
- ownership?.stop();
695
- removeNotification();
696
- await rpc.close();
697
- }
698
- };
699
-
700
- // bin/pushary-codex-bridge.ts
701
43
  var spawnId = process.env.PUSHARY_SPAWN_ID?.trim();
702
44
  var requestedCwd = process.env.PUSHARY_BRIDGE_CWD?.trim();
703
45
  if (!spawnId || !requestedCwd || !existsSync(requestedCwd)) {