@pushary/agent-hooks 1.9.158 → 1.9.161

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 (146) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +1 -0
  3. package/dist/{api-MRFKFDVV.js → api-WHTSBK74.js} +15 -13
  4. package/dist/bin/pushary-audit.js +7 -7
  5. package/dist/bin/pushary-bell-hook.js +31 -31
  6. package/dist/bin/pushary-bell.js +16 -16
  7. package/dist/bin/pushary-calls.d.ts +1 -0
  8. package/dist/bin/pushary-calls.js +287 -0
  9. package/dist/bin/pushary-claude.js +37 -37
  10. package/dist/bin/pushary-clean.js +47 -45
  11. package/dist/bin/pushary-codex-bridge.js +27 -27
  12. package/dist/bin/pushary-codex-hook.js +46 -44
  13. package/dist/bin/pushary-codex-session.js +8 -8
  14. package/dist/bin/pushary-codex.js +19 -19
  15. package/dist/bin/pushary-connect.js +41 -40
  16. package/dist/bin/pushary-cowork.js +6 -6
  17. package/dist/bin/pushary-daemon.js +52 -51
  18. package/dist/bin/pushary-disconnect.js +39 -37
  19. package/dist/bin/pushary-display-hook.js +20 -1
  20. package/dist/bin/pushary-doctor.js +61 -59
  21. package/dist/bin/pushary-elicitation-hook.js +32 -32
  22. package/dist/bin/pushary-gemini-bridge.js +19 -19
  23. package/dist/bin/pushary-gemini-hook.js +36 -36
  24. package/dist/bin/pushary-hook.js +39 -38
  25. package/dist/bin/pushary-login.js +28 -28
  26. package/dist/bin/pushary-logout.js +34 -33
  27. package/dist/bin/pushary-mcp.js +15 -15
  28. package/dist/bin/pushary-mode.js +21 -21
  29. package/dist/bin/pushary-notification-hook.js +30 -30
  30. package/dist/bin/pushary-opencode-hook.js +399 -45
  31. package/dist/bin/pushary-permission-denied-hook.js +39 -38
  32. package/dist/bin/pushary-permission-hook.js +39 -38
  33. package/dist/bin/pushary-post-hook.js +31 -31
  34. package/dist/bin/pushary-prompt-hook.js +30 -30
  35. package/dist/bin/pushary-session-end-hook.js +30 -30
  36. package/dist/bin/pushary-session-start-hook.js +41 -40
  37. package/dist/bin/pushary-setup.js +73 -72
  38. package/dist/bin/pushary-stats.js +6 -6
  39. package/dist/bin/pushary-status.js +40 -39
  40. package/dist/bin/pushary-stop-hook.js +30 -30
  41. package/dist/bin/pushary-stopfailure-hook.js +30 -30
  42. package/dist/bin/pushary-suggestions.js +21 -21
  43. package/dist/bin/pushary-transcript-register.js +21 -21
  44. package/dist/bin/pushary-transcripts.js +32 -32
  45. package/dist/bin/pushary-upgrade.js +50 -49
  46. package/dist/bin/pushary-wait.js +23 -23
  47. package/dist/bin/pushary.js +10 -9
  48. package/dist/{chunk-IKC33YKC.js → chunk-26GVUJMR.js} +5 -2
  49. package/dist/{chunk-Q7WCDUFV.js → chunk-2ABUBECK.js} +6 -6
  50. package/dist/{chunk-V36P4KS4.js → chunk-2PY5DJTC.js} +1 -1
  51. package/dist/{chunk-J7HSUQK2.js → chunk-3F6HE5AK.js} +3 -3
  52. package/dist/{chunk-AZZNHW3R.js → chunk-4ZNZS6FM.js} +8 -5
  53. package/dist/{chunk-HA2SRYYP.js → chunk-55AHQF63.js} +92 -0
  54. package/dist/{chunk-UPI3JDHZ.js → chunk-5S66DHJS.js} +3 -3
  55. package/dist/{chunk-4I2SHNEU.js → chunk-5UBV26GO.js} +3 -3
  56. package/dist/{chunk-ALQWZCUT.js → chunk-6NWESDKK.js} +4 -4
  57. package/dist/{chunk-DHI3X5WK.js → chunk-6OSE2IRG.js} +2 -2
  58. package/dist/{chunk-NW63PGKF.js → chunk-7AQTKVA6.js} +12 -7
  59. package/dist/{chunk-FTTSQAF4.js → chunk-7IHVTLHK.js} +1 -1
  60. package/dist/{chunk-GTYVNVBZ.js → chunk-7VXHWU7A.js} +4 -4
  61. package/dist/{chunk-B3BOAYRO.js → chunk-7WLKE7QN.js} +3 -3
  62. package/dist/{chunk-QVVBU2JU.js → chunk-ANYLSZN3.js} +24 -9
  63. package/dist/{chunk-6GGK3T24.js → chunk-AT5ZLKMQ.js} +5 -5
  64. package/dist/{chunk-CCKY3JDB.js → chunk-ATI5XO3E.js} +4 -4
  65. package/dist/{chunk-CAMFNSJS.js → chunk-AVGYUZVK.js} +6 -6
  66. package/dist/{chunk-FGVBFDNV.js → chunk-AVRRD6AY.js} +1 -1
  67. package/dist/{chunk-ORQ7THNZ.js → chunk-BGU56XCS.js} +1 -1
  68. package/dist/{chunk-K3OCYJPK.js → chunk-BTYHDCAP.js} +3 -3
  69. package/dist/{chunk-YPFOTFEG.js → chunk-DHUWAUVL.js} +1 -1
  70. package/dist/{chunk-IOKJJ2SY.js → chunk-DHX5JZSH.js} +4 -4
  71. package/dist/{chunk-XNJ2HOEL.js → chunk-DLZ6RK2P.js} +3 -3
  72. package/dist/{chunk-TSR3FPGL.js → chunk-DWMQZM52.js} +1 -1
  73. package/dist/{chunk-N3CFEMLS.js → chunk-E7K6YCWY.js} +6 -6
  74. package/dist/{chunk-3QU4WXAH.js → chunk-EGEZKJHX.js} +5 -5
  75. package/dist/{chunk-3UNZ7HRN.js → chunk-F5NJUDGA.js} +20 -18
  76. package/dist/{chunk-UDLWNOXX.js → chunk-FZCEPG6J.js} +2 -2
  77. package/dist/{chunk-N5SSADNW.js → chunk-G44FOBHN.js} +4 -4
  78. package/dist/{chunk-TKBCLK4B.js → chunk-GJA3KQ3T.js} +5 -5
  79. package/dist/{chunk-CSZWWPNS.js → chunk-GNHXDRO6.js} +1 -1
  80. package/dist/{chunk-AMIUB22C.js → chunk-HHNC6FWO.js} +1 -1
  81. package/dist/{chunk-PND5IGC7.js → chunk-HKCJZGAJ.js} +6 -6
  82. package/dist/{chunk-IIK3CZXJ.js → chunk-HKI4RMZF.js} +8 -7
  83. package/dist/{chunk-PBPQRJ2T.js → chunk-I5HXAELM.js} +5 -5
  84. package/dist/{chunk-T3PZQNIK.js → chunk-IGSSDODQ.js} +2 -2
  85. package/dist/{chunk-CS4Z44F5.js → chunk-IHYKSPWH.js} +85 -8
  86. package/dist/chunk-J36DDPJV.js +18 -0
  87. package/dist/{chunk-ANQBLZAE.js → chunk-KDHLOPSO.js} +1 -1
  88. package/dist/{chunk-4B5K6YIP.js → chunk-KKDKPWGM.js} +1 -1
  89. package/dist/{chunk-XHCX6DOY.js → chunk-L2ADRR62.js} +5 -5
  90. package/dist/{chunk-RRVFN432.js → chunk-LRTRIDOC.js} +1 -1
  91. package/dist/{chunk-MTITL2IG.js → chunk-LVGRSC44.js} +5 -5
  92. package/dist/{chunk-C6PAIHLP.js → chunk-MGOBIHXH.js} +10 -10
  93. package/dist/{chunk-EHRWEXRN.js → chunk-MPYQW4IV.js} +2 -2
  94. package/dist/{chunk-QP3TCKRZ.js → chunk-N4OKAE65.js} +15 -15
  95. package/dist/{chunk-SZMDRBNK.js → chunk-ONMAG5BF.js} +2 -2
  96. package/dist/{chunk-TMWXWBFP.js → chunk-OOODAKCC.js} +6 -6
  97. package/dist/chunk-OQAIMSHQ.js +885 -0
  98. package/dist/{chunk-TZJR5ESF.js → chunk-OSCZ4MNE.js} +7 -7
  99. package/dist/{chunk-X254TRBU.js → chunk-OXZ75E2Y.js} +4 -4
  100. package/dist/{chunk-OCWXE4PR.js → chunk-OZK75SFS.js} +11 -9
  101. package/dist/{chunk-RL5JLDRE.js → chunk-PXLWR4TG.js} +2 -2
  102. package/dist/{chunk-4WL2MINE.js → chunk-QLEFFGCN.js} +1 -1
  103. package/dist/{chunk-4NHQAMSK.js → chunk-R7NAG65X.js} +4 -4
  104. package/dist/{chunk-UVWKMFLQ.js → chunk-R7RN3Z2T.js} +2 -2
  105. package/dist/{chunk-AOP55JR2.js → chunk-RZBCXPOV.js} +14 -3
  106. package/dist/{chunk-SNQOEDZ2.js → chunk-S6ARXVVZ.js} +1 -1
  107. package/dist/{chunk-TYBVQ33X.js → chunk-TYB2QGJD.js} +6 -6
  108. package/dist/{chunk-XSIZKQ2C.js → chunk-U36COV3Z.js} +11 -11
  109. package/dist/{chunk-PI3BOI3A.js → chunk-U3FVVMB3.js} +1 -1
  110. package/dist/{chunk-AGYD6XNI.js → chunk-UH7GJHOO.js} +3 -3
  111. package/dist/chunk-UJT32RSQ.js +242 -0
  112. package/dist/{chunk-WIIMW5YO.js → chunk-UQTQ6HPO.js} +2 -0
  113. package/dist/{chunk-JKRQL2BL.js → chunk-UZTGEACF.js} +5 -5
  114. package/dist/{chunk-MHYX5Q3F.js → chunk-VIS3EVRH.js} +1 -1
  115. package/dist/{chunk-4SN4FHFZ.js → chunk-VYNC7EYV.js} +2 -2
  116. package/dist/{chunk-EGBI4GRS.js → chunk-W6FCSBTM.js} +2 -2
  117. package/dist/{chunk-IVOELLUK.js → chunk-WAFJGQSE.js} +39 -8
  118. package/dist/{chunk-LVZBLKAU.js → chunk-WCXVPYSD.js} +1 -1
  119. package/dist/{chunk-K3I2NMEF.js → chunk-WNIDBPT2.js} +8 -8
  120. package/dist/{chunk-CIAJ55EQ.js → chunk-WTWBHE2Y.js} +42 -34
  121. package/dist/{chunk-GHHVXARK.js → chunk-XWCLKWKP.js} +1 -1
  122. package/dist/{chunk-ZYDE6QRW.js → chunk-Y23YO46U.js} +3 -3
  123. package/dist/{chunk-2L52USKM.js → chunk-Y553AEQU.js} +3 -3
  124. package/dist/{chunk-H6CL3T2S.js → chunk-Y6ILCLKE.js} +1 -1
  125. package/dist/{chunk-APCJZFTJ.js → chunk-YD45WNVQ.js} +1 -1
  126. package/dist/{chunk-MLPPQ556.js → chunk-YEB7YWW7.js} +13 -13
  127. package/dist/{chunk-TPLTB256.js → chunk-YGHHDDIM.js} +4 -4
  128. package/dist/{chunk-N2LWKWNY.js → chunk-Z5DOTAFI.js} +3 -3
  129. package/dist/{chunk-2MPT7YQK.js → chunk-ZIKSHD5M.js} +5 -3
  130. package/dist/{codex-app-cards-switch-CXXDGH7R.js → codex-app-cards-switch-DPCGWQSX.js} +14 -14
  131. package/dist/{codex-card-routing-WP4IHJFN.js → codex-card-routing-NFIEH66Q.js} +2 -2
  132. package/dist/{codex-desktop-launch-EN7ACHC6.js → codex-desktop-launch-MARNBY23.js} +1 -1
  133. package/dist/{codex-session-launch-7BV4VTJW.js → codex-session-launch-LSNU7CUV.js} +23 -23
  134. package/dist/{config-SZMMBOJV.js → config-5D34OAYM.js} +4 -4
  135. package/dist/{global-upgrade-I5J6BDHA.js → global-upgrade-5XBO6FYU.js} +11 -11
  136. package/dist/{identity-GLJNTNHW.js → identity-6QEFK7PW.js} +5 -5
  137. package/dist/{live-capabilities-AYO7FOHS.js → live-capabilities-6KOGY6KM.js} +5 -5
  138. package/dist/{paths-NRBEF3T2.js → paths-7M6V62NO.js} +4 -4
  139. package/dist/reapply-ZECM5JRX.js +69 -0
  140. package/dist/src/index.js +39 -38
  141. package/dist/{upgrade-lock-H6SU7MJR.js → upgrade-lock-DI4JY2CU.js} +5 -5
  142. package/dist/usage-X4BIHYR5.js +11 -0
  143. package/package.json +2 -1
  144. package/dist/chunk-GLDSXDRV.js +0 -593
  145. package/dist/reapply-J2QUV7J2.js +0 -68
  146. package/dist/usage-MY3DIFBG.js +0 -11
@@ -0,0 +1,885 @@
1
+ import {
2
+ DECISION_STOP_REASON,
3
+ HOOK_BUDGETS,
4
+ KILL_REASON,
5
+ OPENCODE_APPROVAL_EVENT
6
+ } from "./chunk-55AHQF63.js";
7
+
8
+ // src/opencode-plugin.ts
9
+ var OPENCODE_PLUGIN_MARKER = "pushary-opencode-plugin w1";
10
+ var OPENCODE_PLUGIN_PLACEHOLDER = "__PUSHARY_COMMAND__";
11
+ var OPENCODE_APPROVAL_EVENTS_PLACEHOLDER = "__PUSHARY_APPROVAL_EVENTS__";
12
+ var OPENCODE_PLUGIN_FILE = "pushary.js";
13
+ var OPENCODE_PLUGIN_DIR = "plugins";
14
+ var OPENCODE_PLUGIN_SIBLING = "package.json";
15
+ var OPENCODE_PLUGIN_SIBLING_CONTENTS = `${JSON.stringify({ type: "module" }, null, 2)}
16
+ `;
17
+ var OPENCODE_ASKED_EVENTS = ["permission.asked", "permission.updated"];
18
+ var OPENCODE_REPLIED_EVENT = "permission.replied";
19
+ var OPENCODE_IDLE_EVENT = "session.idle";
20
+ var OPENCODE_FAILED_EVENT = "session.execution.failed";
21
+ var OPENCODE_SESSION_CREATED_EVENT = "session.created";
22
+ var OPENCODE_V2_FORWARDED_ACTIONS = ["shell", "read", "edit", "webfetch", "websearch", "skill", "subagent"];
23
+ var OPENCODE_STEP_ENDING_REASONS = [KILL_REASON, DECISION_STOP_REASON];
24
+ var OPENCODE_RESUBSCRIBE_DELAYS_MS = [1e3, 2e3, 5e3, 1e4];
25
+ var OPENCODE_SESSION_PARENT_TIMEOUT_MS = 2e3;
26
+ var OPENCODE_SUBAGENT_IDLE_EVENT = "session.subagent.idle";
27
+ var OPENCODE_QUESTION_EVENT = "form.created";
28
+ var OPENCODE_V1_QUESTION_EVENT = "question.asked";
29
+ var OPENCODE_QUESTION_SETTLED_EVENTS = ["form.replied", "form.cancelled", "question.replied", "question.rejected"];
30
+ var OPENCODE_INTERRUPTED_EVENT = "session.execution.interrupted";
31
+ var OPENCODE_GLOBAL_FORM_OWNER = "global";
32
+ var OPENCODE_QUESTION_ANSWERED = "answered";
33
+ var OPENCODE_QUESTION_CANCELLED = "cancelled";
34
+ var OPENCODE_QUESTION_FORM_KIND = "question";
35
+ var OPENCODE_QUESTION_UNDELIVERED_EVENT = "form.reply.failed";
36
+ var OPENCODE_QUESTION_RECHECK_MS = 3 * 6e4;
37
+ var OPENCODE_QUESTION_UNREACHABLE_EVENT = "form.unreachable";
38
+ var OPENCODE_SERVICE_REVERIFY_MS = 2e3;
39
+ var OPENCODE_SETTLED_ELSEWHERE_STATUSES = [404, 409];
40
+ var OPENCODE_CLI_BRIDGES_QUESTIONS = true;
41
+ var OPENCODE_SERVICE_REQUEST_TIMEOUT_MS = 5e3;
42
+ var approvalTimeoutMs = () => (HOOK_BUDGETS.opencode.budgetSeconds - HOOK_BUDGETS.opencode.guardSeconds) * 1e3;
43
+ var openCodePluginSource = (bridgesQuestions) => `// Pushary for OpenCode. Generated by @pushary/agent-hooks \u2014 do not edit.
44
+ // ${OPENCODE_PLUGIN_MARKER}
45
+ //
46
+ // OpenCode finds a plugin by globbing {plugin,plugins}/*.{ts,js} under its config
47
+ // directory and importing it, so this file is the whole install.
48
+ //
49
+ // It decides nothing. Each hook builds the payload OpenCode handed it, writes it
50
+ // to the Pushary hook command on stdin, and reads a verdict back. The policy
51
+ // engine, the phone, the wait and the settlement all live behind that command.
52
+ //
53
+ // Approvals ride the event stream rather than the "permission.ask" hook, which is
54
+ // declared in @opencode-ai/plugin and called by nothing. Permission.ask publishes
55
+ // "permission.asked" and blocks on a Deferred that only a reply resolves, so this
56
+ // answers that reply on the person's behalf when Pushary has a verdict.
57
+ //
58
+ // Failure is silence. A missing command, a crash, a timeout, unreadable bytes and
59
+ // an unparseable reply all leave OpenCode's own prompt exactly as it was. The
60
+ // worst this file may do to somebody is nothing at all.
61
+
62
+ import { spawn } from "node:child_process"
63
+ import { readdir, readFile } from "node:fs/promises"
64
+ import { homedir } from "node:os"
65
+ import { isAbsolute, join, relative, resolve, sep } from "node:path"
66
+
67
+ const COMMAND = ${OPENCODE_PLUGIN_PLACEHOLDER}
68
+ const APPROVAL_EVENTS = ${OPENCODE_APPROVAL_EVENTS_PLACEHOLDER}
69
+ const APPROVAL_TIMEOUT_MS = ${approvalTimeoutMs()}
70
+ const BRIDGES_QUESTIONS = ${JSON.stringify(bridgesQuestions)}
71
+ const QUESTION_EVENT = ${JSON.stringify(OPENCODE_QUESTION_EVENT)}
72
+ const V1_QUESTION_EVENT = ${JSON.stringify(OPENCODE_V1_QUESTION_EVENT)}
73
+ const QUESTION_SETTLED_EVENTS = ${JSON.stringify(OPENCODE_QUESTION_SETTLED_EVENTS)}
74
+ const INTERRUPTED_EVENT = ${JSON.stringify(OPENCODE_INTERRUPTED_EVENT)}
75
+ const GLOBAL_FORM_OWNER = ${JSON.stringify(OPENCODE_GLOBAL_FORM_OWNER)}
76
+ const QUESTION_ANSWERED = ${JSON.stringify(OPENCODE_QUESTION_ANSWERED)}
77
+ const QUESTION_CANCELLED = ${JSON.stringify(OPENCODE_QUESTION_CANCELLED)}
78
+ const SERVICE_REQUEST_TIMEOUT_MS = ${OPENCODE_SERVICE_REQUEST_TIMEOUT_MS}
79
+ const SERVICE_REGISTRATION = /^service.*\\.json$/
80
+ const SERVICE_USER = "opencode"
81
+ const SERVICE_PROTOCOL = "http:"
82
+ const SERVICE_INFO_PATH = "/api/info"
83
+ const LOOPBACK_HOSTS = ["127.0.0.1", "[::1]"]
84
+ const LOOPBACK_LITERAL = { "0.0.0.0": "127.0.0.1", "localhost": "127.0.0.1", "[::]": "[::1]" }
85
+ const NOT_FOUND = 404
86
+ const FORM_PENDING = "pending"
87
+ const QUESTION_FORM_KIND = ${JSON.stringify(OPENCODE_QUESTION_FORM_KIND)}
88
+ const QUESTION_UNDELIVERED_EVENT = ${JSON.stringify(OPENCODE_QUESTION_UNDELIVERED_EVENT)}
89
+ const QUESTION_RECHECK_MS = ${OPENCODE_QUESTION_RECHECK_MS}
90
+ const QUESTION_UNREACHABLE_EVENT = ${JSON.stringify(OPENCODE_QUESTION_UNREACHABLE_EVENT)}
91
+ const SERVICE_REVERIFY_MS = ${OPENCODE_SERVICE_REVERIFY_MS}
92
+ const SETTLED_ELSEWHERE_STATUSES = ${JSON.stringify(OPENCODE_SETTLED_ELSEWHERE_STATUSES)}
93
+ const REPLY_DELIVERED = "delivered"
94
+ const REPLY_SETTLED_ELSEWHERE = "settled_elsewhere"
95
+ const REPLY_REFUSED = "refused"
96
+ const STATE_DIRECTORY = "opencode"
97
+ const TELEMETRY_TIMEOUT_MS = 10000
98
+ const MAX_REPLY_BYTES = 65536
99
+ const FORWARDED_ACTIONS = ${JSON.stringify(OPENCODE_V2_FORWARDED_ACTIONS)}
100
+ const STEP_ENDING_REASONS = ${JSON.stringify(OPENCODE_STEP_ENDING_REASONS)}
101
+ const RESUBSCRIBE_DELAYS_MS = ${JSON.stringify(OPENCODE_RESUBSCRIBE_DELAYS_MS)}
102
+ const SESSION_PARENT_TIMEOUT_MS = ${OPENCODE_SESSION_PARENT_TIMEOUT_MS}
103
+ const SUBAGENT_IDLE_EVENT = ${JSON.stringify(OPENCODE_SUBAGENT_IDLE_EVENT)}
104
+ const HOME_PREFIX = "~"
105
+ const PARENT_SEGMENT = ".."
106
+ // One entry per call in flight. Bounded because a long session must not grow them
107
+ // without limit, and evicted oldest-first because whatever is still waiting on an
108
+ // answer is the newest thing in here, never the oldest.
109
+ const MAX_TRACKED = 256
110
+
111
+ const text = (value) => (typeof value === "string" && value.length > 0 ? value : undefined)
112
+
113
+ const remember = (map, key, value) => {
114
+ if (!key || value === undefined) return
115
+ if (map.size >= MAX_TRACKED) map.delete(map.keys().next().value)
116
+ map.set(key, value)
117
+ }
118
+
119
+ const run = (payload, timeoutMs, onSpawn) =>
120
+ new Promise((resolve) => {
121
+ let settled = false
122
+ let timer
123
+ const finish = (value) => {
124
+ if (settled) return
125
+ settled = true
126
+ clearTimeout(timer)
127
+ resolve(value)
128
+ }
129
+
130
+ let child
131
+ try {
132
+ child = spawn(COMMAND[0], COMMAND.slice(1), { stdio: ["pipe", "pipe", "ignore"] })
133
+ } catch {
134
+ return finish(null)
135
+ }
136
+ if (onSpawn) onSpawn(child)
137
+
138
+ if (timeoutMs !== undefined) {
139
+ timer = setTimeout(() => {
140
+ try {
141
+ child.kill("SIGKILL")
142
+ } catch {}
143
+ finish(null)
144
+ }, timeoutMs)
145
+ if (typeof timer.unref === "function") timer.unref()
146
+ }
147
+
148
+ let out = ""
149
+ child.stdout.on("data", (chunk) => {
150
+ if (out.length < MAX_REPLY_BYTES) out += chunk
151
+ })
152
+ child.on("error", () => finish(null))
153
+ child.on("close", () => {
154
+ const body = out.trim()
155
+ if (!body) return finish(null)
156
+ try {
157
+ finish(JSON.parse(body))
158
+ } catch {
159
+ finish(null)
160
+ }
161
+ })
162
+
163
+ try {
164
+ child.stdin.on("error", () => {})
165
+ child.stdin.end(JSON.stringify(payload))
166
+ } catch {
167
+ finish(null)
168
+ }
169
+ })
170
+
171
+ // Telemetry is fire and forget: the agent has already acted and is only being
172
+ // observed, so nothing here may hold up the next turn.
173
+ const tell = (payload) => {
174
+ void run(payload, TELEMETRY_TIMEOUT_MS)
175
+ }
176
+
177
+ // What OpenCode gates on, and what it hands over with it. Verified against its own
178
+ // tools: bash asks with { command }, write and edit both ask under "edit" with
179
+ // { filepath, diff }, webfetch with { url }, and a shell command reaching outside
180
+ // the worktree asks a second time under "external_directory".
181
+ const inputFrom = (permission, metadata, resources) => {
182
+ const meta = metadata && typeof metadata === "object" ? metadata : {}
183
+ if (permission === "read" && resources?.length === 1) return { file_path: resources[0] }
184
+ if (permission === "websearch" && resources?.length === 1) return { query: resources[0] }
185
+ if (permission === "skill" && resources?.length === 1) return { skill: resources[0] }
186
+ if (permission === "subagent" && resources?.length === 1) {
187
+ const description = text(meta.description)
188
+ return { subagent_type: resources[0], ...(description ? { description } : {}) }
189
+ }
190
+ const command = text(meta.command)
191
+ if (command) return { command }
192
+ const preview = Array.isArray(meta.files) && meta.files.length === 1 ? meta.files[0] : undefined
193
+ const filepath = text(preview?.file) ?? text(meta.filepath) ?? text(meta.file_path) ?? text(meta.path)
194
+ // The diff rides along, because it is what the person is actually approving.
195
+ // OpenCode computes it before raising the permission and hands it over; without
196
+ // it the phone shows a filename and nothing to judge.
197
+ const diff = text(preview?.patch) ?? text(meta.diff)
198
+ if (filepath) return { file_path: filepath, ...(diff ? { diff } : {}) }
199
+ const url = text(meta.url)
200
+ if (url) return { url }
201
+ return { permission, ...(resources?.length ? { resources } : {}) }
202
+ }
203
+
204
+ // Two spellings of one request: the runtime publishes PermissionV1.Request
205
+ // ({ permission, patterns }), the generated SDK types say Permission ({ type,
206
+ // pattern }). Whichever arrives, the id and the session are what we need.
207
+ const askedFrom = (properties) => {
208
+ if (!properties || typeof properties !== "object") return null
209
+ const id = text(properties.id)
210
+ const sessionID = text(properties.sessionID)
211
+ if (!id || !sessionID) return null
212
+ return {
213
+ id,
214
+ sessionID,
215
+ permission: text(properties.action) ?? text(properties.permission) ?? text(properties.type) ?? "unknown",
216
+ metadata: properties.metadata,
217
+ resources: Array.isArray(properties.resources) ? properties.resources.filter((item) => typeof item === "string") : undefined,
218
+ title: text(properties.title) ?? text(properties.message),
219
+ callID: text(properties.source && properties.source.id) ?? text(properties.callID) ?? text(properties.tool && properties.tool.callID),
220
+ }
221
+ }
222
+
223
+ const repliedID = (properties) => {
224
+ if (!properties || typeof properties !== "object") return undefined
225
+ return text(properties.requestID) ?? text(properties.permissionID) ?? text(properties.id)
226
+ }
227
+
228
+ const feedbackFor = (reason) => {
229
+ const message = text(reason)
230
+ return message && !STEP_ENDING_REASONS.includes(message) ? message : undefined
231
+ }
232
+
233
+ const failureReasonOf = (error) => {
234
+ if (typeof error === "string") return text(error)
235
+ if (!error || typeof error !== "object") return undefined
236
+ return text(error.message) ?? text(error.type)
237
+ }
238
+
239
+ const isWorkdirInside = (root, workdir) => {
240
+ if (workdir.startsWith(HOME_PREFIX)) return false
241
+ const path = relative(root, resolve(root, workdir))
242
+ return path === "" || (path !== PARENT_SEGMENT && !path.startsWith(PARENT_SEGMENT + sep) && !isAbsolute(path))
243
+ }
244
+
245
+ const formOf = (properties) => {
246
+ const form = properties && properties.form
247
+ if (!form || typeof form !== "object") return null
248
+ const id = text(form.id)
249
+ const sessionID = text(form.sessionID)
250
+ const kind = form.metadata && typeof form.metadata === "object" ? form.metadata.kind : undefined
251
+ if (!id || !sessionID || sessionID === GLOBAL_FORM_OWNER || kind !== QUESTION_FORM_KIND || !Array.isArray(form.fields)) return null
252
+ return { id, sessionID, title: text(form.title), fields: form.fields }
253
+ }
254
+
255
+ const v1OptionOf = (option) => {
256
+ const label = option && typeof option === "object" ? text(option.label) : undefined
257
+ return { value: label, label, description: option && text(option.description) }
258
+ }
259
+
260
+ const v1FieldOf = (question, index) => {
261
+ const asked = question && typeof question === "object" ? question : {}
262
+ return {
263
+ key: "q" + index,
264
+ title: text(asked.header),
265
+ description: text(asked.question),
266
+ type: asked.multiple === true ? "multiselect" : "string",
267
+ options: Array.isArray(asked.options) ? asked.options.map(v1OptionOf) : [],
268
+ custom: asked.custom !== false,
269
+ }
270
+ }
271
+
272
+ const v1FormOf = (properties) => {
273
+ if (!properties || typeof properties !== "object") return null
274
+ const id = text(properties.id)
275
+ const sessionID = text(properties.sessionID)
276
+ if (!id || !sessionID || !Array.isArray(properties.questions)) return null
277
+ return { id, sessionID, fields: properties.questions.map(v1FieldOf) }
278
+ }
279
+
280
+ const settledQuestionID = (properties) =>
281
+ properties && typeof properties === "object" ? text(properties.requestID) ?? text(properties.id) : undefined
282
+
283
+ const v1AnswerOf = (value) => {
284
+ if (value === undefined) return []
285
+ return Array.isArray(value) ? value : [String(value)]
286
+ }
287
+
288
+ const v1Answers = (form, answer) => form.fields.map((field) => v1AnswerOf(answer[field.key]))
289
+
290
+ const loopbackServiceUrl = (raw) => {
291
+ let url
292
+ try {
293
+ url = new URL(raw)
294
+ } catch {
295
+ return undefined
296
+ }
297
+ if (url.protocol !== SERVICE_PROTOCOL) return undefined
298
+ if (Object.hasOwn(LOOPBACK_LITERAL, url.hostname)) url.hostname = LOOPBACK_LITERAL[url.hostname]
299
+ return LOOPBACK_HOSTS.includes(url.hostname) ? url.origin : undefined
300
+ }
301
+
302
+ const serviceRequest = async (service, method, path, body) => {
303
+ const headers = {}
304
+ if (body) headers["content-type"] = "application/json"
305
+ if (service.password) headers.authorization = "Basic " + Buffer.from(SERVICE_USER + ":" + service.password).toString("base64")
306
+ try {
307
+ return await fetch(new URL(path, service.url), {
308
+ method,
309
+ headers,
310
+ body: body ? JSON.stringify(body) : undefined,
311
+ redirect: "error",
312
+ signal: AbortSignal.timeout(SERVICE_REQUEST_TIMEOUT_MS),
313
+ })
314
+ } catch {
315
+ return null
316
+ }
317
+ }
318
+
319
+ const serviceAnswersAsThisProcess = async (service) => {
320
+ const response = await serviceRequest(service, "GET", SERVICE_INFO_PATH)
321
+ if (!response || !response.ok) return false
322
+ try {
323
+ const info = await response.json()
324
+ return Boolean(info) && info.pid === process.pid
325
+ } catch {
326
+ return false
327
+ }
328
+ }
329
+
330
+ const registeredServiceOf = async (directory, name) => {
331
+ try {
332
+ const info = JSON.parse(await readFile(join(directory, name), "utf8"))
333
+ const url = info && info.pid === process.pid ? loopbackServiceUrl(text(info.url)) : undefined
334
+ return url ? { url, password: text(info.password) } : null
335
+ } catch {
336
+ return null
337
+ }
338
+ }
339
+
340
+ const ownService = async () => {
341
+ const directory = join(process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"), STATE_DIRECTORY)
342
+ let names
343
+ try {
344
+ names = await readdir(directory)
345
+ } catch {
346
+ return null
347
+ }
348
+ for (const name of names.filter((entry) => SERVICE_REGISTRATION.test(entry))) {
349
+ const service = await registeredServiceOf(directory, name)
350
+ if (service && (await serviceAnswersAsThisProcess(service))) return service
351
+ }
352
+ return null
353
+ }
354
+
355
+ const succeeded = (response) => Boolean(response) && response.ok
356
+
357
+ const replyOutcomeOf = (status) => {
358
+ if (status !== undefined && status >= 200 && status < 300) return REPLY_DELIVERED
359
+ return SETTLED_ELSEWHERE_STATUSES.includes(status) ? REPLY_SETTLED_ELSEWHERE : REPLY_REFUSED
360
+ }
361
+
362
+ const waitFor = (ms) => new Promise((resume) => {
363
+ const timer = setTimeout(resume, ms)
364
+ if (typeof timer.unref === "function") timer.unref()
365
+ })
366
+
367
+ const formPath = (form) => "/api/session/" + encodeURIComponent(form.sessionID) + "/form/" + encodeURIComponent(form.id)
368
+
369
+ const formIsPending = async (service, form) => {
370
+ const response = await serviceRequest(service, "GET", formPath(form))
371
+ if (!response) return true
372
+ if (response.status === NOT_FOUND) return false
373
+ if (!response.ok) return true
374
+ try {
375
+ const body = await response.json()
376
+ const state = body && body.data && body.data.state
377
+ return !state || state.status === FORM_PENDING
378
+ } catch {
379
+ return true
380
+ }
381
+ }
382
+
383
+ const formChannel = (service) => ({
384
+ reply: async (form, answer) => {
385
+ const response = await serviceRequest(service, "POST", formPath(form) + "/reply", { answer })
386
+ return replyOutcomeOf(response ? response.status : undefined)
387
+ },
388
+ cancel: async (form, message) => {
389
+ const query = message ? "?message=" + encodeURIComponent(message) : ""
390
+ if (succeeded(await serviceRequest(service, "DELETE", formPath(form) + query))) return true
391
+ return succeeded(await serviceRequest(service, "POST", formPath(form) + "/cancel"))
392
+ },
393
+ isPending: (form) => formIsPending(service, form),
394
+ })
395
+
396
+ const v2QuestionChannel = async () => {
397
+ const service = await ownService()
398
+ return service ? formChannel(service) : null
399
+ }
400
+
401
+ const v1QuestionChannel = (client) => {
402
+ const raw = client && client._client && typeof client._client.post === "function" && typeof client._client.get === "function"
403
+ ? client._client
404
+ : null
405
+ if (!raw) return undefined
406
+ const post = async (url, requestID, body) => {
407
+ const result = await raw.post({
408
+ url,
409
+ path: { requestID },
410
+ ...(body ? { body, headers: { "Content-Type": "application/json" } } : {}),
411
+ })
412
+ if (!result || !result.error) return REPLY_DELIVERED
413
+ return replyOutcomeOf(result.response ? result.response.status : undefined)
414
+ }
415
+ const isPending = async (form) => {
416
+ const result = await raw.get({ url: "/question" })
417
+ if (!result || result.error || !Array.isArray(result.data)) return true
418
+ return result.data.some((request) => request && request.id === form.id)
419
+ }
420
+ const channel = {
421
+ reply: (form, answer) => post("/question/{requestID}/reply", form.id, { answers: v1Answers(form, answer) }),
422
+ cancel: (form) => post("/question/{requestID}/reject", form.id),
423
+ isPending,
424
+ }
425
+ return async () => channel
426
+ }
427
+
428
+ const PusharyPlugin = async ({ client, directory, worktree, replyPermission, sessionParent, questionChannel }) => {
429
+ const cwd = directory || worktree || process.cwd()
430
+ // OpenCode raises a permission under a coarse key \u2014 "edit" covers both write and
431
+ // edit \u2014 and names the actual tool only on tool.execute.before. Keeping the
432
+ // pairing is what lets a rule written for Write mean Write here too.
433
+ const tools = new Map()
434
+ // Every gate still waiting. Held so a person answering in the terminal can end
435
+ // ours: whoever answers first wins, and the loser stops asking.
436
+ const waiting = new Map()
437
+ const subagentSessions = new Map()
438
+ const questions = new Map()
439
+ const openQuestionChannel = questionChannel ?? v1QuestionChannel(client)
440
+
441
+ const base = (sessionID) => ({ session_id: sessionID ?? "", cwd })
442
+
443
+ const noteSession = (sessionID, parentID) =>
444
+ remember(subagentSessions, text(sessionID), Promise.resolve(text(parentID)))
445
+
446
+ const parentWithin = (sessionID) => new Promise((resolve, reject) => {
447
+ const timer = setTimeout(() => reject(new Error("session lookup timed out")), SESSION_PARENT_TIMEOUT_MS)
448
+ if (typeof timer.unref === "function") timer.unref()
449
+ Promise.resolve()
450
+ .then(() => sessionParent(sessionID))
451
+ .then(resolve, reject)
452
+ .finally(() => clearTimeout(timer))
453
+ })
454
+
455
+ const parentOf = (sessionID) => {
456
+ if (!sessionID) return Promise.resolve(undefined)
457
+ const known = subagentSessions.get(sessionID)
458
+ if (known) return known
459
+ if (!sessionParent) return Promise.resolve(undefined)
460
+ const lookup = parentWithin(sessionID)
461
+ .then((parentID) => text(parentID))
462
+ .catch(() => {
463
+ if (subagentSessions.get(sessionID) === lookup) subagentSessions.delete(sessionID)
464
+ return undefined
465
+ })
466
+ remember(subagentSessions, sessionID, lookup)
467
+ return lookup
468
+ }
469
+
470
+ const tellUnlessSubagent = (sessionID, payload) => {
471
+ void parentOf(sessionID).then((parentID) => {
472
+ if (!parentID) tell(payload)
473
+ })
474
+ }
475
+
476
+ const tellTurnEnded = (sessionID, payload) => {
477
+ void parentOf(sessionID).then((parentID) => {
478
+ tell(parentID
479
+ ? { ...base(parentID), hook_event_name: SUBAGENT_IDLE_EVENT, agent_id: sessionID }
480
+ : payload)
481
+ })
482
+ }
483
+
484
+ // Replying is the whole approval. Two shapes, because the client handed to a
485
+ // plugin is generated: v1 exposes postSessionIdPermissionsPermissionId against
486
+ // /session/{id}/permissions/{permissionID}, v2 exposes permission.reply against
487
+ // /permission/{requestID}/reply. Both routes are live in the server today.
488
+ const respond = async (asked, allow, message) => {
489
+ const decision = allow ? "once" : "reject"
490
+ const feedback = !allow && message ? { message } : {}
491
+ if (replyPermission) {
492
+ try {
493
+ await replyPermission({ sessionID: asked.sessionID, requestID: asked.id, decision, ...feedback })
494
+ } catch {}
495
+ return
496
+ }
497
+ const legacy = client && typeof client.postSessionIdPermissionsPermissionId === "function"
498
+ ? () => client.postSessionIdPermissionsPermissionId({
499
+ path: { id: asked.sessionID, permissionID: asked.id },
500
+ body: { response: decision },
501
+ })
502
+ : null
503
+ const current = client && client.permission && typeof client.permission.reply === "function"
504
+ ? () => client.permission.reply({
505
+ // Current v2 uses flat parameters; older generated clients read path/body.
506
+ requestID: asked.id, reply: decision, ...feedback,
507
+ path: { requestID: asked.id },
508
+ body: { reply: decision, ...feedback },
509
+ }, { throwOnError: true })
510
+ : null
511
+
512
+ for (const attempt of [legacy, current]) {
513
+ if (!attempt) continue
514
+ try {
515
+ const result = await attempt()
516
+ if (result && result.error) continue
517
+ return
518
+ } catch {
519
+ // The person answered first, or this client does not serve that route.
520
+ // Either way the next shape is the only thing left to try.
521
+ }
522
+ }
523
+ }
524
+
525
+ const gate = async (asked) => {
526
+ if (asked.permission === "external_directory") return
527
+ if (replyPermission && !FORWARDED_ACTIONS.includes(asked.permission)) return
528
+ if (Array.isArray(asked.metadata?.files) && asked.metadata.files.length > 1) return
529
+ if (["read", "edit"].includes(asked.permission) && asked.resources?.length > 1) return
530
+ const tool = tools.get(asked.callID)
531
+ const workdir = ["shell", "bash"].includes(tool?.name) ? text(tool.input?.workdir) : undefined
532
+ if (workdir && !isWorkdirInside(cwd, workdir)) return
533
+ const reply = await run({
534
+ ...base(asked.sessionID),
535
+ cwd: workdir ? resolve(cwd, workdir) : cwd,
536
+ project_dir: cwd,
537
+ hook_event_name: "${OPENCODE_APPROVAL_EVENT}",
538
+ tool_name: tool?.name ?? asked.permission,
539
+ tool_input: inputFrom(asked.permission, { ...tool?.input, ...asked.metadata }, asked.resources),
540
+ permission_id: asked.id,
541
+ permission_type: asked.permission,
542
+ title: asked.title,
543
+ }, APPROVAL_TIMEOUT_MS, (child) => remember(waiting, asked.id, child))
544
+
545
+ // Gone means the terminal already answered while we were asking. Replying now
546
+ // would be answering a question nobody is holding open any more.
547
+ if (!waiting.has(asked.id)) return
548
+
549
+ const status = reply && typeof reply === "object" ? reply.status : undefined
550
+ if (status === "allow" || status === "deny") await respond(asked, status === "allow", feedbackFor(reply.reason))
551
+ waiting.delete(asked.id)
552
+ }
553
+
554
+ const withdraw = (id) => {
555
+ const child = id && waiting.get(id)
556
+ if (!child) return
557
+ waiting.delete(id)
558
+ // SIGTERM rather than SIGKILL: the hook cancels its outstanding question on
559
+ // the way out, so the phone stops showing a decision the terminal has taken.
560
+ try {
561
+ child.kill("SIGTERM")
562
+ } catch {}
563
+ }
564
+
565
+ const questionChannelFor = async () => {
566
+ if (!openQuestionChannel) return null
567
+ try {
568
+ return await openQuestionChannel()
569
+ } catch {
570
+ return null
571
+ }
572
+ }
573
+
574
+ const formPayload = (form) => ({
575
+ ...base(form.sessionID),
576
+ form_id: form.id,
577
+ form: { title: form.title, fields: form.fields },
578
+ })
579
+
580
+ const settleQuestion = async (channel, form, reply) => {
581
+ const outcome = reply && typeof reply === "object" ? reply : {}
582
+ if (outcome.status === QUESTION_ANSWERED && outcome.answer && typeof outcome.answer === "object") {
583
+ if ((await channel.reply(form, outcome.answer)) === REPLY_REFUSED) tell({ ...formPayload(form), hook_event_name: QUESTION_UNDELIVERED_EVENT })
584
+ return
585
+ }
586
+ if (outcome.status === QUESTION_CANCELLED) await channel.cancel(form, feedbackFor(outcome.reason))
587
+ }
588
+
589
+ let recheck
590
+ const stopRechecking = () => {
591
+ clearInterval(recheck)
592
+ recheck = undefined
593
+ }
594
+
595
+ const recheckQuestions = async () => {
596
+ for (const [id, pending] of Array.from(questions)) {
597
+ if (!pending.channel || !pending.child) continue
598
+ let open = true
599
+ try {
600
+ open = await pending.channel.isPending(pending.form)
601
+ } catch {}
602
+ if (!open && questions.get(id) === pending) withdrawQuestion(id)
603
+ }
604
+ if (questions.size === 0) stopRechecking()
605
+ }
606
+
607
+ const keepRechecking = () => {
608
+ if (recheck) return
609
+ recheck = setInterval(() => void recheckQuestions(), QUESTION_RECHECK_MS)
610
+ if (typeof recheck.unref === "function") recheck.unref()
611
+ }
612
+
613
+ const trackQuestion = (id, pending) => {
614
+ if (questions.size >= MAX_TRACKED) withdrawQuestion(questions.keys().next().value)
615
+ questions.set(id, pending)
616
+ }
617
+
618
+ const forgetQuestion = (id, pending) => {
619
+ if (questions.get(id) === pending) questions.delete(id)
620
+ if (questions.size === 0) stopRechecking()
621
+ }
622
+
623
+ const unreachableTold = new Map()
624
+
625
+ const tellUnreachable = (form) => {
626
+ if (unreachableTold.has(form.id)) return
627
+ remember(unreachableTold, form.id, true)
628
+ tell({ ...formPayload(form), hook_event_name: QUESTION_UNREACHABLE_EVENT })
629
+ }
630
+
631
+ const verifiedChannel = async (form, pending) => {
632
+ const channel = await questionChannelFor()
633
+ if (channel || !openQuestionChannel || questions.get(form.id) !== pending) return channel
634
+ await waitFor(SERVICE_REVERIFY_MS)
635
+ return questions.get(form.id) === pending ? questionChannelFor() : null
636
+ }
637
+
638
+ const bridgeQuestion = async (form) => {
639
+ const pending = { child: undefined, channel: undefined, form, sessionID: form.sessionID }
640
+ trackQuestion(form.id, pending)
641
+ const channel = await verifiedChannel(form, pending)
642
+ if (!channel || questions.get(form.id) !== pending) {
643
+ if (!channel && openQuestionChannel && questions.get(form.id) === pending) tellUnreachable(form)
644
+ forgetQuestion(form.id, pending)
645
+ return
646
+ }
647
+ pending.channel = channel
648
+ keepRechecking()
649
+ const reply = await run({ ...formPayload(form), hook_event_name: QUESTION_EVENT }, undefined, (child) => {
650
+ pending.child = child
651
+ })
652
+ if (questions.get(form.id) !== pending) return
653
+ try {
654
+ await settleQuestion(channel, form, reply)
655
+ } catch {}
656
+ forgetQuestion(form.id, pending)
657
+ }
658
+
659
+ const withdrawQuestion = (id) => {
660
+ const pending = id ? questions.get(id) : undefined
661
+ if (!pending) return
662
+ forgetQuestion(id, pending)
663
+ if (!pending.child) return
664
+ try {
665
+ pending.child.kill("SIGTERM")
666
+ } catch {}
667
+ }
668
+
669
+ const withdrawSessionQuestions = (sessionID) => {
670
+ for (const [id, pending] of Array.from(questions)) {
671
+ if (pending.sessionID === sessionID) withdrawQuestion(id)
672
+ }
673
+ }
674
+
675
+ return {
676
+ "tool.execute.before": async (input) => {
677
+ remember(tools, input && input.callID, { name: input?.tool, input: input?.args })
678
+ },
679
+
680
+ "tool.execute.after": async (input, output) => {
681
+ const call = input && input.callID
682
+ if (call) tools.delete(call)
683
+ tell({
684
+ ...base(input && input.sessionID),
685
+ hook_event_name: "tool.execute.after",
686
+ tool_name: text(input && input.tool) ?? "unknown",
687
+ tool_input: input && input.args && typeof input.args === "object" ? input.args : {},
688
+ tool_result: output?.error ? { error: output.error } : { title: text(output && output.title), output: text(output && output.output) },
689
+ })
690
+ },
691
+
692
+ "chat.message": async (input, output) => {
693
+ const parts = output && Array.isArray(output.parts) ? output.parts : []
694
+ const prompt = parts
695
+ .filter((part) => part && part.type === "text" && typeof part.text === "string")
696
+ .map((part) => part.text)
697
+ .join("\\n")
698
+ .trim()
699
+ if (!prompt) return
700
+ tellUnlessSubagent(input && input.sessionID, { ...base(input && input.sessionID), hook_event_name: "chat.message", prompt })
701
+ },
702
+
703
+ event: async ({ event }) => {
704
+ // Never allowed to throw: the host calls this hook without awaiting it, so a
705
+ // rejection here is an unhandled rejection in somebody's editor.
706
+ try {
707
+ const type = event && event.type
708
+ const properties = event && event.properties
709
+ if (APPROVAL_EVENTS.includes(type)) {
710
+ const asked = askedFrom(properties)
711
+ if (asked && !waiting.has(asked.id)) void gate(asked)
712
+ return
713
+ }
714
+ if (type === ${JSON.stringify(OPENCODE_REPLIED_EVENT)}) {
715
+ withdraw(repliedID(properties))
716
+ return
717
+ }
718
+ if (type === QUESTION_EVENT || type === V1_QUESTION_EVENT) {
719
+ const form = type === QUESTION_EVENT ? formOf(properties) : v1FormOf(properties)
720
+ if (form && BRIDGES_QUESTIONS && APPROVAL_EVENTS.length > 0 && !questions.has(form.id)) void bridgeQuestion(form)
721
+ return
722
+ }
723
+ if (QUESTION_SETTLED_EVENTS.includes(type)) {
724
+ withdrawQuestion(settledQuestionID(properties))
725
+ return
726
+ }
727
+ if (type === INTERRUPTED_EVENT) {
728
+ withdrawSessionQuestions(text(properties && properties.sessionID))
729
+ return
730
+ }
731
+ if (type === ${JSON.stringify(OPENCODE_SESSION_CREATED_EVENT)}) {
732
+ noteSession(properties && properties.sessionID, properties && properties.parentID)
733
+ return
734
+ }
735
+ // session.idle is the turn boundary \u2014 OpenCode's equivalent of Claude's
736
+ // Stop, not of its SessionEnd. Nothing else on the stream is relayed: the
737
+ // receipts already arrive through the hooks above, and reporting the same
738
+ // moment twice would double every row on the account.
739
+ if (type === ${JSON.stringify(OPENCODE_IDLE_EVENT)}) {
740
+ withdrawSessionQuestions(text(properties && properties.sessionID))
741
+ tellTurnEnded(text(properties && properties.sessionID), {
742
+ ...base(properties && properties.sessionID),
743
+ hook_event_name: ${JSON.stringify(OPENCODE_IDLE_EVENT)},
744
+ })
745
+ return
746
+ }
747
+ if (type === ${JSON.stringify(OPENCODE_FAILED_EVENT)}) {
748
+ withdrawSessionQuestions(text(properties && properties.sessionID))
749
+ tellTurnEnded(text(properties && properties.sessionID), {
750
+ ...base(properties && properties.sessionID),
751
+ hook_event_name: ${JSON.stringify(OPENCODE_FAILED_EVENT)},
752
+ error: failureReasonOf(properties && properties.error),
753
+ })
754
+ }
755
+ } catch {}
756
+ },
757
+
758
+ reconcile: recheckQuestions,
759
+
760
+ dispose: async () => {
761
+ for (const id of Array.from(waiting.keys())) withdraw(id)
762
+ for (const id of Array.from(questions.keys())) withdrawQuestion(id)
763
+ stopRechecking()
764
+ tools.clear()
765
+ },
766
+ }
767
+ }
768
+
769
+ export default {
770
+ id: "pushary",
771
+ server: PusharyPlugin,
772
+ async setup(ctx) {
773
+ const hooks = await PusharyPlugin({
774
+ directory: ctx.location.directory,
775
+ replyPermission: (request) => ctx.permission.reply(request),
776
+ sessionParent: typeof ctx.session.get === "function"
777
+ ? (sessionID) => Promise.resolve(ctx.session.get({ sessionID })).then((info) => info && info.parentID)
778
+ : undefined,
779
+ questionChannel: v2QuestionChannel,
780
+ })
781
+ await ctx.tool.hook("execute.before", (event) => hooks["tool.execute.before"]({
782
+ callID: event.id, tool: event.tool, sessionID: event.sessionID, args: event.input,
783
+ }))
784
+ await ctx.tool.hook("execute.after", (event) => hooks["tool.execute.after"]({
785
+ callID: event.id, tool: event.tool, sessionID: event.sessionID, args: event.input,
786
+ }, { output: event.status === "completed" && Array.isArray(event.result.content)
787
+ ? event.result.content.filter((part) => part.type === "text").map((part) => part.text).join("\\n")
788
+ : undefined, error: event.status === "error" ? event.error.message : undefined }))
789
+ await ctx.session.hook("prompt", (event) => hooks["chat.message"]({ sessionID: event.sessionID }, {
790
+ parts: [{ type: "text", text: event.prompt.text }],
791
+ }))
792
+ const controller = new AbortController()
793
+ const pause = (ms) => new Promise((resume) => {
794
+ if (controller.signal.aborted) return resume()
795
+ const done = () => {
796
+ clearTimeout(timer)
797
+ controller.signal.removeEventListener("abort", done)
798
+ resume()
799
+ }
800
+ const timer = setTimeout(done, ms)
801
+ if (typeof timer.unref === "function") timer.unref()
802
+ controller.signal.addEventListener("abort", done, { once: true })
803
+ })
804
+ const resubscribeDelay = (failures) => RESUBSCRIBE_DELAYS_MS[Math.min(failures, RESUBSCRIBE_DELAYS_MS.length - 1)]
805
+ const consume = async () => {
806
+ let failures = 0
807
+ let warned = false
808
+ while (!controller.signal.aborted) {
809
+ try {
810
+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
811
+ if (controller.signal.aborted) break
812
+ failures = 0
813
+ if (event.location && (event.location.directory !== ctx.location.directory || event.location.workspaceID !== ctx.location.workspaceID)) continue
814
+ const type = event.type === "session.execution.succeeded" ? "session.idle" : event.type
815
+ await hooks.event({ event: { type, properties: event.data } })
816
+ }
817
+ break
818
+ } catch {
819
+ if (controller.signal.aborted) break
820
+ if (!warned) console.error("Pushary event subscription stopped; native prompts remain available.")
821
+ warned = true
822
+ }
823
+ await pause(resubscribeDelay(failures))
824
+ failures += 1
825
+ await hooks.reconcile()
826
+ }
827
+ await hooks.dispose()
828
+ }
829
+ const events = consume()
830
+ return async () => {
831
+ controller.abort()
832
+ await hooks.dispose()
833
+ await events
834
+ }
835
+ },
836
+ }
837
+ `;
838
+ var openCodePluginModule = (bridgesQuestions = OPENCODE_CLI_BRIDGES_QUESTIONS) => ({
839
+ marker: OPENCODE_PLUGIN_MARKER,
840
+ source: openCodePluginSource(bridgesQuestions),
841
+ placeholder: OPENCODE_PLUGIN_PLACEHOLDER,
842
+ approvalEvents: {
843
+ placeholder: OPENCODE_APPROVAL_EVENTS_PLACEHOLDER,
844
+ events: OPENCODE_ASKED_EVENTS
845
+ },
846
+ sibling: {
847
+ path: OPENCODE_PLUGIN_SIBLING,
848
+ contents: OPENCODE_PLUGIN_SIBLING_CONTENTS
849
+ }
850
+ });
851
+ var renderOpenCodePlugin = (module, argv, holdsApprovals = true) => module.source.replace(module.placeholder, JSON.stringify(argv)).replace(module.approvalEvents.placeholder, JSON.stringify(holdsApprovals ? module.approvalEvents.events : []));
852
+ var COMMAND_LINE = /^const COMMAND = (.*)$/m;
853
+ var isArgv = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
854
+ var openCodePluginArgv = (contents) => {
855
+ if (!isOpenCodePluginOurs(contents)) return null;
856
+ const line = contents.match(COMMAND_LINE)?.[1];
857
+ if (line === void 0) return null;
858
+ try {
859
+ const parsed = JSON.parse(line);
860
+ return isArgv(parsed) ? parsed : null;
861
+ } catch {
862
+ return null;
863
+ }
864
+ };
865
+ var isOpenCodePluginOurs = (contents) => contents.includes(OPENCODE_PLUGIN_MARKER);
866
+
867
+ export {
868
+ OPENCODE_PLUGIN_PLACEHOLDER,
869
+ OPENCODE_PLUGIN_FILE,
870
+ OPENCODE_PLUGIN_DIR,
871
+ OPENCODE_PLUGIN_SIBLING,
872
+ OPENCODE_PLUGIN_SIBLING_CONTENTS,
873
+ OPENCODE_IDLE_EVENT,
874
+ OPENCODE_FAILED_EVENT,
875
+ OPENCODE_SUBAGENT_IDLE_EVENT,
876
+ OPENCODE_QUESTION_EVENT,
877
+ OPENCODE_QUESTION_ANSWERED,
878
+ OPENCODE_QUESTION_CANCELLED,
879
+ OPENCODE_QUESTION_UNDELIVERED_EVENT,
880
+ OPENCODE_QUESTION_UNREACHABLE_EVENT,
881
+ openCodePluginModule,
882
+ renderOpenCodePlugin,
883
+ openCodePluginArgv,
884
+ isOpenCodePluginOurs
885
+ };