pushary 1.9.179 → 1.9.180

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 (144) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/dist/{api-YH7WN4FA.js → api-UDDZRXXB.js} +11 -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 +42 -40
  9. package/dist/bin/pushary-codex-bridge.js +23 -23
  10. package/dist/bin/pushary-codex-hook.js +36 -36
  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 +35 -34
  14. package/dist/bin/pushary-cowork.js +5 -5
  15. package/dist/bin/pushary-daemon.js +46 -45
  16. package/dist/bin/pushary-disconnect.js +33 -31
  17. package/dist/bin/pushary-display-hook.js +36 -26
  18. package/dist/bin/pushary-doctor.js +47 -46
  19. package/dist/bin/pushary-elicitation-hook.js +28 -28
  20. package/dist/bin/pushary-gemini-bridge.js +18 -18
  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 +30 -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.js +19 -19
  29. package/dist/bin/pushary-opencode-hook.js +34 -33
  30. package/dist/bin/pushary-permission-denied-hook.js +36 -36
  31. package/dist/bin/pushary-permission-hook.js +36 -36
  32. package/dist/bin/pushary-post-hook.js +28 -28
  33. package/dist/bin/pushary-prompt-hook.js +27 -27
  34. package/dist/bin/pushary-session-end-hook.js +27 -27
  35. package/dist/bin/pushary-session-start-hook.js +39 -38
  36. package/dist/bin/pushary-sessions.js +14 -14
  37. package/dist/bin/pushary-setup.js +55 -54
  38. package/dist/bin/pushary-stats.js +5 -5
  39. package/dist/bin/pushary-status.js +36 -35
  40. package/dist/bin/pushary-stop-hook.js +27 -27
  41. package/dist/bin/pushary-stopfailure-hook.js +27 -27
  42. package/dist/bin/pushary-suggestions.js +16 -16
  43. package/dist/bin/pushary-transcript-register.js +17 -17
  44. package/dist/bin/pushary-transcripts.js +25 -25
  45. package/dist/bin/pushary-upgrade.js +44 -43
  46. package/dist/bin/pushary-wait.js +16 -16
  47. package/dist/bin/pushary.js +7 -7
  48. package/dist/{chunk-XQGU77H7.js → chunk-255TJOUT.js} +4 -4
  49. package/dist/{chunk-HNQ2FIBA.js → chunk-2C5DS3GU.js} +2 -2
  50. package/dist/{chunk-KFLHGN4D.js → chunk-2EWBZQHF.js} +3 -3
  51. package/dist/{chunk-A7G6CFZU.js → chunk-2RG454N6.js} +4 -4
  52. package/dist/{chunk-65CSOPQW.js → chunk-3GL34K67.js} +8 -8
  53. package/dist/{chunk-6KF26UUL.js → chunk-4XNQOTVR.js} +3 -3
  54. package/dist/{chunk-FHVGZ6AN.js → chunk-4XQN44EO.js} +1 -1
  55. package/dist/{chunk-POESL3CD.js → chunk-5JR6LPS2.js} +1 -1
  56. package/dist/{chunk-JMPC7HL6.js → chunk-5Q3KXXT3.js} +6 -6
  57. package/dist/{chunk-N2L7E5NE.js → chunk-67IYCZY2.js} +5 -5
  58. package/dist/{chunk-OIFWZESQ.js → chunk-76AS4CFU.js} +11 -11
  59. package/dist/{chunk-NEAJLLIG.js → chunk-A7MLOLAM.js} +5 -5
  60. package/dist/{chunk-HGP2DDW3.js → chunk-AFH5LR76.js} +1 -1
  61. package/dist/{chunk-MKKRQBQF.js → chunk-AG3BUNOK.js} +3 -3
  62. package/dist/{chunk-M2P5KFP5.js → chunk-B4K5OVOE.js} +3 -3
  63. package/dist/{chunk-PJHYFHP4.js → chunk-BRFHSICQ.js} +1 -1
  64. package/dist/{chunk-AXPZZFBW.js → chunk-CEHLYLLC.js} +2 -2
  65. package/dist/{chunk-MIJ2P4FZ.js → chunk-CGVQC5EF.js} +7 -7
  66. package/dist/{chunk-WMHXZDUT.js → chunk-CHG3NBBJ.js} +2 -2
  67. package/dist/{chunk-W27VNI6G.js → chunk-CVJ6H2VK.js} +1 -1
  68. package/dist/{chunk-AYP4GE3X.js → chunk-CXBOEYV6.js} +36 -34
  69. package/dist/{chunk-ZTNGM6NU.js → chunk-D5WXTN2C.js} +3 -3
  70. package/dist/{chunk-OD6JNTGZ.js → chunk-DULV2NZK.js} +2 -2
  71. package/dist/{chunk-FWUF33U6.js → chunk-E3TGXTDU.js} +2 -2
  72. package/dist/{chunk-YXLJTIGG.js → chunk-EOGOZ6XB.js} +4 -4
  73. package/dist/{chunk-I6AMLYXS.js → chunk-EVJ53Y2E.js} +4 -4
  74. package/dist/{chunk-IV4ZY2DS.js → chunk-FR6YVSPK.js} +5 -5
  75. package/dist/{chunk-J5PTUQMF.js → chunk-FSIIKAGP.js} +3 -3
  76. package/dist/{chunk-QYGO5EKA.js → chunk-HPSSY25E.js} +2 -2
  77. package/dist/{chunk-KUB4OGLG.js → chunk-IEWZ4O74.js} +5 -5
  78. package/dist/{chunk-QMV7WS7D.js → chunk-IMGGR66U.js} +2 -2
  79. package/dist/{chunk-3JXSIPLF.js → chunk-INTSTZH4.js} +1 -1
  80. package/dist/{chunk-JSSCR6M2.js → chunk-IQJL5HY5.js} +2 -2
  81. package/dist/{chunk-RVIYAQC7.js → chunk-ITLAO546.js} +2 -2
  82. package/dist/{chunk-JDNQC5IG.js → chunk-J45L73O6.js} +5 -5
  83. package/dist/{chunk-6W7Q6VB6.js → chunk-JBAFH5Q2.js} +2 -2
  84. package/dist/{chunk-RM3YENVK.js → chunk-JJNBX3SP.js} +3 -3
  85. package/dist/{chunk-CTJRWP6Y.js → chunk-JQCAB544.js} +3 -3
  86. package/dist/{chunk-HOVBZBAJ.js → chunk-K2H2XC52.js} +4 -4
  87. package/dist/{chunk-UJUXZCQS.js → chunk-K4IMFKPP.js} +6 -6
  88. package/dist/{chunk-XJG7YRF7.js → chunk-KFAYDRWP.js} +3 -3
  89. package/dist/{chunk-ZMJKA7CF.js → chunk-KIR4VFWX.js} +5 -5
  90. package/dist/{chunk-Z2DAWG5U.js → chunk-LRA423VV.js} +1 -1
  91. package/dist/chunk-LSR6SAV7.js +890 -0
  92. package/dist/{chunk-N24MKYZ2.js → chunk-M7KHET4S.js} +1 -1
  93. package/dist/{chunk-3BZ7IGGW.js → chunk-MQKEYMX4.js} +5 -5
  94. package/dist/{chunk-32YARQJC.js → chunk-N7EBHNYA.js} +5 -5
  95. package/dist/{chunk-NX33EVEP.js → chunk-NQXVL6LF.js} +1 -1
  96. package/dist/{chunk-ZPHPNTGW.js → chunk-O4IWURQP.js} +1 -1
  97. package/dist/{chunk-3NTAU6DN.js → chunk-O4IYGRNI.js} +2 -2
  98. package/dist/{chunk-BKZZSXEQ.js → chunk-OJWADO7D.js} +4 -4
  99. package/dist/{chunk-BNZYEIBB.js → chunk-OOA65NQG.js} +18 -18
  100. package/dist/{chunk-PFH7XMHE.js → chunk-OTY6O2LK.js} +1 -1
  101. package/dist/{chunk-2JSTCD7L.js → chunk-PEIQT6KC.js} +2 -2
  102. package/dist/{chunk-I4XCADTT.js → chunk-PTV6A5SZ.js} +1 -1
  103. package/dist/{chunk-MWKKUBHQ.js → chunk-Q7PIFWTG.js} +1 -1
  104. package/dist/{chunk-S7X3PENP.js → chunk-QZNC5XOW.js} +4 -4
  105. package/dist/{chunk-TVBND3VL.js → chunk-R2PK26FR.js} +2 -2
  106. package/dist/{chunk-XOVAERD7.js → chunk-R4TTSINC.js} +1 -1
  107. package/dist/{chunk-WDPIZXCZ.js → chunk-RE3TYSP7.js} +3 -3
  108. package/dist/{chunk-EEHTVBKI.js → chunk-RKYKCR22.js} +6 -6
  109. package/dist/{chunk-2HMDWEER.js → chunk-RNVHH6AN.js} +1 -1
  110. package/dist/{chunk-7VNTZY7V.js → chunk-RY4HYXOC.js} +12 -12
  111. package/dist/{chunk-VOWNWXVE.js → chunk-SNKG7NMV.js} +4 -4
  112. package/dist/{chunk-XWWD2KTY.js → chunk-ULYZX6VZ.js} +1 -1
  113. package/dist/{chunk-6BIC2SHE.js → chunk-UXPO3OEC.js} +2 -2
  114. package/dist/{chunk-SYIAWMBA.js → chunk-UZMMHZHU.js} +13 -11
  115. package/dist/{chunk-MM5QO2ZY.js → chunk-VD3Q2A5J.js} +1 -1
  116. package/dist/{chunk-RM3F4V6A.js → chunk-VKZPDU25.js} +6 -6
  117. package/dist/{chunk-P3MYHWF5.js → chunk-VOONPEA7.js} +5 -5
  118. package/dist/{chunk-Y5BRXPL6.js → chunk-VRPVNOHT.js} +1 -1
  119. package/dist/chunk-VT4JY2AI.js +77 -0
  120. package/dist/{chunk-D7GUUTOT.js → chunk-VTWMIYBM.js} +4 -4
  121. package/dist/{chunk-ZNCRZNLJ.js → chunk-VWZCVHJG.js} +1 -1
  122. package/dist/{chunk-AYMFOYOZ.js → chunk-XDZ3O7RV.js} +9 -9
  123. package/dist/{chunk-E25IZ5S3.js → chunk-XID6PO4T.js} +4 -4
  124. package/dist/{chunk-INUW2CXK.js → chunk-YH6QFABF.js} +6 -6
  125. package/dist/{chunk-YRGDHBS5.js → chunk-YQMNDBJD.js} +4 -4
  126. package/dist/{chunk-ZMSQQVVY.js → chunk-Z7DDOLAZ.js} +1 -1
  127. package/dist/{chunk-SV6AMA7J.js → chunk-ZFF4UNXN.js} +10 -10
  128. package/dist/{chunk-WII73NRE.js → chunk-ZL2RR6WP.js} +1 -1
  129. package/dist/{codex-app-cards-switch-RDVTCDVO.js → codex-app-cards-switch-NWDQLOTK.js} +11 -11
  130. package/dist/{codex-card-routing-XUYIRUB7.js → codex-card-routing-WS72OC7Y.js} +2 -2
  131. package/dist/{codex-desktop-launch-EX3E3T3Q.js → codex-desktop-launch-FH6RY46X.js} +1 -1
  132. package/dist/{codex-session-launch-TDEWJ3G6.js → codex-session-launch-SVUC7T26.js} +20 -20
  133. package/dist/{config-XDZZTOHU.js → config-4JVYJ27G.js} +3 -3
  134. package/dist/{global-upgrade-QVFP4F7D.js → global-upgrade-4FLQ53HE.js} +9 -9
  135. package/dist/{identity-Q5HWBCJY.js → identity-7H3PMMPS.js} +4 -4
  136. package/dist/{live-capabilities-G5FB5VBL.js → live-capabilities-YENLFDYL.js} +4 -4
  137. package/dist/{paths-IVCUVJM6.js → paths-PEFZYPII.js} +3 -3
  138. package/dist/reapply-DLMD74WK.js +70 -0
  139. package/dist/src/index.js +35 -35
  140. package/dist/{upgrade-lock-Y56NERM5.js → upgrade-lock-L5QYJEGO.js} +4 -4
  141. package/dist/{usage-J7O2QQEQ.js → usage-SKO6G5XJ.js} +3 -3
  142. package/package.json +2 -2
  143. package/dist/chunk-WIKPDEOR.js +0 -984
  144. package/dist/reapply-MQTAPBPH.js +0 -69
@@ -1,984 +0,0 @@
1
- import {
2
- DECISION_STOP_REASON,
3
- HOOK_BUDGETS,
4
- KILL_REASON,
5
- OPENCODE_APPROVAL_EVENT
6
- } from "./chunk-AYP4GE3X.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 OPENCODE_STATE_DIRECTORY = "opencode";
43
- var OPENCODE_SERVICE_REGISTRATION = /^service.*\.json$/;
44
- var OPENCODE_SERVICE_USER = "opencode";
45
- var OPENCODE_SERVICE_PROTOCOL = "http:";
46
- var OPENCODE_SERVICE_INFO_PATH = "/api/info";
47
- var OPENCODE_LOOPBACK_HOSTS = ["127.0.0.1", "[::1]"];
48
- var OPENCODE_LOOPBACK_ALIASES = {
49
- "0.0.0.0": "127.0.0.1",
50
- localhost: "127.0.0.1",
51
- "[::]": "[::1]"
52
- };
53
- var javaScriptArrayLiteral = (values) => `[${values.map((value) => JSON.stringify(value)).join(", ")}]`;
54
- var javaScriptObjectLiteral = (record) => `{ ${Object.entries(record).map(([key, value]) => `${JSON.stringify(key)}: ${JSON.stringify(value)}`).join(", ")} }`;
55
- var OPENCODE_WITHDRAW_ON_STDIN_END = "withdraw_on_stdin_end";
56
- var OPENCODE_CAPABILITIES_EVENT = "pushary.capabilities";
57
- var OPENCODE_HOOK_CAPABILITIES = { capabilities: [OPENCODE_WITHDRAW_ON_STDIN_END] };
58
- var OPENCODE_CAPABILITY_PROBE_TIMEOUT_MS = 5e3;
59
- var OPENCODE_QUESTION_WITHDRAW_TIMEOUT_MS = 5e3;
60
- var OPENCODE_QUESTION_ASK_IN_FLIGHT_GRACE_MS = 6e4;
61
- var OPENCODE_HOOK_EXIT_MARGIN_MS = 2e3;
62
- var OPENCODE_QUESTION_WITHDRAW_GRACE_MS = OPENCODE_QUESTION_ASK_IN_FLIGHT_GRACE_MS + OPENCODE_QUESTION_WITHDRAW_TIMEOUT_MS + 2 * OPENCODE_HOOK_EXIT_MARGIN_MS;
63
- var approvalTimeoutMs = () => (HOOK_BUDGETS.opencode.budgetSeconds - HOOK_BUDGETS.opencode.guardSeconds) * 1e3;
64
- var openCodePluginSource = (bridgesQuestions) => `// Pushary for OpenCode. Generated by @pushary/agent-hooks \u2014 do not edit.
65
- // ${OPENCODE_PLUGIN_MARKER}
66
- //
67
- // OpenCode finds a plugin by globbing {plugin,plugins}/*.{ts,js} under its config
68
- // directory and importing it, so this file is the whole install.
69
- //
70
- // It decides nothing. Each hook builds the payload OpenCode handed it, writes it
71
- // to the Pushary hook command on stdin, and reads a verdict back. The policy
72
- // engine, the phone, the wait and the settlement all live behind that command.
73
- //
74
- // Approvals ride the event stream rather than the "permission.ask" hook, which is
75
- // declared in @opencode-ai/plugin and called by nothing. Permission.ask publishes
76
- // "permission.asked" and blocks on a Deferred that only a reply resolves, so this
77
- // answers that reply on the person's behalf when Pushary has a verdict.
78
- //
79
- // Failure is silence. A missing command, a crash, a timeout, unreadable bytes and
80
- // an unparseable reply all leave OpenCode's own prompt exactly as it was. The
81
- // worst this file may do to somebody is nothing at all.
82
-
83
- import { spawn } from "node:child_process"
84
- import { readdir, readFile, stat } from "node:fs/promises"
85
- import { homedir } from "node:os"
86
- import { isAbsolute, join, relative, resolve, sep } from "node:path"
87
-
88
- const COMMAND = ${OPENCODE_PLUGIN_PLACEHOLDER}
89
- const APPROVAL_EVENTS = ${OPENCODE_APPROVAL_EVENTS_PLACEHOLDER}
90
- const APPROVAL_TIMEOUT_MS = ${approvalTimeoutMs()}
91
- const BRIDGES_QUESTIONS = ${JSON.stringify(bridgesQuestions)}
92
- const QUESTION_EVENT = ${JSON.stringify(OPENCODE_QUESTION_EVENT)}
93
- const V1_QUESTION_EVENT = ${JSON.stringify(OPENCODE_V1_QUESTION_EVENT)}
94
- const QUESTION_SETTLED_EVENTS = ${JSON.stringify(OPENCODE_QUESTION_SETTLED_EVENTS)}
95
- const INTERRUPTED_EVENT = ${JSON.stringify(OPENCODE_INTERRUPTED_EVENT)}
96
- const GLOBAL_FORM_OWNER = ${JSON.stringify(OPENCODE_GLOBAL_FORM_OWNER)}
97
- const QUESTION_ANSWERED = ${JSON.stringify(OPENCODE_QUESTION_ANSWERED)}
98
- const QUESTION_CANCELLED = ${JSON.stringify(OPENCODE_QUESTION_CANCELLED)}
99
- const SERVICE_REQUEST_TIMEOUT_MS = ${OPENCODE_SERVICE_REQUEST_TIMEOUT_MS}
100
- const WITHDRAW_ON_STDIN_END = ${JSON.stringify(OPENCODE_WITHDRAW_ON_STDIN_END)}
101
- const CAPABILITIES_EVENT = ${JSON.stringify(OPENCODE_CAPABILITIES_EVENT)}
102
- const CAPABILITY_PROBE_TIMEOUT_MS = ${OPENCODE_CAPABILITY_PROBE_TIMEOUT_MS}
103
- const QUESTION_WITHDRAW_GRACE_MS = ${OPENCODE_QUESTION_WITHDRAW_GRACE_MS}
104
- const SERVICE_REGISTRATION = ${OPENCODE_SERVICE_REGISTRATION}
105
- const SERVICE_USER = ${JSON.stringify(OPENCODE_SERVICE_USER)}
106
- const SERVICE_PROTOCOL = ${JSON.stringify(OPENCODE_SERVICE_PROTOCOL)}
107
- const SERVICE_INFO_PATH = ${JSON.stringify(OPENCODE_SERVICE_INFO_PATH)}
108
- const LOOPBACK_HOSTS = ${javaScriptArrayLiteral(OPENCODE_LOOPBACK_HOSTS)}
109
- const LOOPBACK_LITERAL = ${javaScriptObjectLiteral(OPENCODE_LOOPBACK_ALIASES)}
110
- const NOT_FOUND = 404
111
- const FORM_PENDING = "pending"
112
- const QUESTION_FORM_KIND = ${JSON.stringify(OPENCODE_QUESTION_FORM_KIND)}
113
- const QUESTION_UNDELIVERED_EVENT = ${JSON.stringify(OPENCODE_QUESTION_UNDELIVERED_EVENT)}
114
- const QUESTION_RECHECK_MS = ${OPENCODE_QUESTION_RECHECK_MS}
115
- const QUESTION_UNREACHABLE_EVENT = ${JSON.stringify(OPENCODE_QUESTION_UNREACHABLE_EVENT)}
116
- const SERVICE_REVERIFY_MS = ${OPENCODE_SERVICE_REVERIFY_MS}
117
- const SETTLED_ELSEWHERE_STATUSES = ${JSON.stringify(OPENCODE_SETTLED_ELSEWHERE_STATUSES)}
118
- const REPLY_DELIVERED = "delivered"
119
- const REPLY_SETTLED_ELSEWHERE = "settled_elsewhere"
120
- const REPLY_REFUSED = "refused"
121
- const STATE_DIRECTORY = ${JSON.stringify(OPENCODE_STATE_DIRECTORY)}
122
- const TELEMETRY_TIMEOUT_MS = 10000
123
- const MAX_REPLY_BYTES = 65536
124
- const FORWARDED_ACTIONS = ${JSON.stringify(OPENCODE_V2_FORWARDED_ACTIONS)}
125
- const STEP_ENDING_REASONS = ${JSON.stringify(OPENCODE_STEP_ENDING_REASONS)}
126
- const RESUBSCRIBE_DELAYS_MS = ${JSON.stringify(OPENCODE_RESUBSCRIBE_DELAYS_MS)}
127
- const SESSION_PARENT_TIMEOUT_MS = ${OPENCODE_SESSION_PARENT_TIMEOUT_MS}
128
- const SUBAGENT_IDLE_EVENT = ${JSON.stringify(OPENCODE_SUBAGENT_IDLE_EVENT)}
129
- const HOME_PREFIX = "~"
130
- const PARENT_SEGMENT = ".."
131
- // One entry per call in flight. Bounded because a long session must not grow them
132
- // without limit, and evicted oldest-first because whatever is still waiting on an
133
- // answer is the newest thing in here, never the oldest.
134
- const MAX_TRACKED = 256
135
-
136
- const text = (value) => (typeof value === "string" && value.length > 0 ? value : undefined)
137
-
138
- const remember = (map, key, value) => {
139
- if (!key || value === undefined) return
140
- if (map.size >= MAX_TRACKED) map.delete(map.keys().next().value)
141
- map.set(key, value)
142
- }
143
-
144
- const withdrawsOverStdin = (payload) => payload[WITHDRAW_ON_STDIN_END] === true
145
-
146
- const replyIn = (out) => {
147
- const body = out.trim()
148
- if (!body) return null
149
- try {
150
- return JSON.parse(body)
151
- } catch {
152
- return null
153
- }
154
- }
155
-
156
- const exitedCleanly = (code, signal) => code === 0 && !signal
157
-
158
- const runHook = (payload, timeoutMs, onSpawn) =>
159
- new Promise((resolve) => {
160
- let settled = false
161
- let timer
162
- const finish = (reply, cleanExit) => {
163
- if (settled) return
164
- settled = true
165
- clearTimeout(timer)
166
- resolve({ reply, cleanExit })
167
- }
168
-
169
- let child
170
- try {
171
- child = spawn(COMMAND[0], COMMAND.slice(1), { stdio: ["pipe", "pipe", "ignore"] })
172
- } catch {
173
- return finish(null, false)
174
- }
175
- if (onSpawn) onSpawn(child)
176
-
177
- if (timeoutMs !== undefined) {
178
- timer = setTimeout(() => {
179
- try {
180
- child.kill("SIGKILL")
181
- } catch {}
182
- finish(null, false)
183
- }, timeoutMs)
184
- if (typeof timer.unref === "function") timer.unref()
185
- }
186
-
187
- let out = ""
188
- child.stdout.on("data", (chunk) => {
189
- if (out.length < MAX_REPLY_BYTES) out += chunk
190
- })
191
- child.on("error", () => finish(null, false))
192
- child.on("close", (code, signal) => finish(replyIn(out), exitedCleanly(code, signal)))
193
-
194
- try {
195
- child.stdin.on("error", () => {})
196
- if (withdrawsOverStdin(payload)) child.stdin.write(JSON.stringify(payload) + "\\n")
197
- else child.stdin.end(JSON.stringify(payload))
198
- } catch {
199
- finish(null, false)
200
- }
201
- })
202
-
203
- const run = (payload, timeoutMs, onSpawn) => runHook(payload, timeoutMs, onSpawn).then((ended) => ended.reply)
204
-
205
- const commandSignature = async () => {
206
- const parts = []
207
- for (const entry of COMMAND.filter((part) => isAbsolute(part))) {
208
- try {
209
- const info = await stat(entry)
210
- parts.push([entry, info.ino, info.size, info.mtimeMs, info.ctimeMs].join(":"))
211
- } catch {}
212
- }
213
- return parts.join("|")
214
- }
215
-
216
- const reportsHeldStdin = (reply) =>
217
- Boolean(reply) && typeof reply === "object" && Array.isArray(reply.capabilities) && reply.capabilities.includes(WITHDRAW_ON_STDIN_END)
218
-
219
- const probeCapabilities = async () => {
220
- const ended = await runHook({ hook_event_name: CAPABILITIES_EVENT }, CAPABILITY_PROBE_TIMEOUT_MS)
221
- return { holds: ended.cleanExit && reportsHeldStdin(ended.reply), conclusive: ended.cleanExit }
222
- }
223
-
224
- let knownCapabilities
225
- let capabilityCheck
226
-
227
- const checkHookCapabilities = async () => {
228
- const signature = await commandSignature()
229
- if (signature && knownCapabilities && knownCapabilities.signature === signature) return knownCapabilities.holds
230
- const answer = await probeCapabilities()
231
- knownCapabilities = signature && answer.conclusive ? { signature, holds: answer.holds } : undefined
232
- return answer.holds
233
- }
234
-
235
- const hookWithdrawsOverStdin = () => {
236
- if (!capabilityCheck) capabilityCheck = checkHookCapabilities().finally(() => { capabilityCheck = undefined })
237
- return capabilityCheck
238
- }
239
-
240
- // Telemetry is fire and forget: the agent has already acted and is only being
241
- // observed, so nothing here may hold up the next turn.
242
- const tell = (payload) => {
243
- void run(payload, TELEMETRY_TIMEOUT_MS)
244
- }
245
-
246
- // What OpenCode gates on, and what it hands over with it. Verified against its own
247
- // tools: bash asks with { command }, write and edit both ask under "edit" with
248
- // { filepath, diff }, webfetch with { url }, and a shell command reaching outside
249
- // the worktree asks a second time under "external_directory".
250
- const inputFrom = (permission, metadata, resources) => {
251
- const meta = metadata && typeof metadata === "object" ? metadata : {}
252
- if (permission === "read" && resources?.length === 1) return { file_path: resources[0] }
253
- if (permission === "websearch" && resources?.length === 1) return { query: resources[0] }
254
- if (permission === "skill" && resources?.length === 1) return { skill: resources[0] }
255
- if (permission === "subagent" && resources?.length === 1) {
256
- const description = text(meta.description)
257
- return { subagent_type: resources[0], ...(description ? { description } : {}) }
258
- }
259
- const command = text(meta.command)
260
- if (command) return { command }
261
- const preview = Array.isArray(meta.files) && meta.files.length === 1 ? meta.files[0] : undefined
262
- const filepath = text(preview?.file) ?? text(meta.filepath) ?? text(meta.file_path) ?? text(meta.path)
263
- // The diff rides along, because it is what the person is actually approving.
264
- // OpenCode computes it before raising the permission and hands it over; without
265
- // it the phone shows a filename and nothing to judge.
266
- const diff = text(preview?.patch) ?? text(meta.diff)
267
- if (filepath) return { file_path: filepath, ...(diff ? { diff } : {}) }
268
- const url = text(meta.url)
269
- if (url) return { url }
270
- return { permission, ...(resources?.length ? { resources } : {}) }
271
- }
272
-
273
- // Two spellings of one request: the runtime publishes PermissionV1.Request
274
- // ({ permission, patterns }), the generated SDK types say Permission ({ type,
275
- // pattern }). Whichever arrives, the id and the session are what we need.
276
- const askedFrom = (properties) => {
277
- if (!properties || typeof properties !== "object") return null
278
- const id = text(properties.id)
279
- const sessionID = text(properties.sessionID)
280
- if (!id || !sessionID) return null
281
- return {
282
- id,
283
- sessionID,
284
- permission: text(properties.action) ?? text(properties.permission) ?? text(properties.type) ?? "unknown",
285
- metadata: properties.metadata,
286
- resources: Array.isArray(properties.resources) ? properties.resources.filter((item) => typeof item === "string") : undefined,
287
- title: text(properties.title) ?? text(properties.message),
288
- callID: text(properties.source && properties.source.id) ?? text(properties.callID) ?? text(properties.tool && properties.tool.callID),
289
- }
290
- }
291
-
292
- const repliedID = (properties) => {
293
- if (!properties || typeof properties !== "object") return undefined
294
- return text(properties.requestID) ?? text(properties.permissionID) ?? text(properties.id)
295
- }
296
-
297
- const feedbackFor = (reason) => {
298
- const message = text(reason)
299
- return message && !STEP_ENDING_REASONS.includes(message) ? message : undefined
300
- }
301
-
302
- const failureReasonOf = (error) => {
303
- if (typeof error === "string") return text(error)
304
- if (!error || typeof error !== "object") return undefined
305
- return text(error.message) ?? text(error.type)
306
- }
307
-
308
- const isWorkdirInside = (root, workdir) => {
309
- if (workdir.startsWith(HOME_PREFIX)) return false
310
- const path = relative(root, resolve(root, workdir))
311
- return path === "" || (path !== PARENT_SEGMENT && !path.startsWith(PARENT_SEGMENT + sep) && !isAbsolute(path))
312
- }
313
-
314
- const formOf = (properties) => {
315
- const form = properties && properties.form
316
- if (!form || typeof form !== "object") return null
317
- const id = text(form.id)
318
- const sessionID = text(form.sessionID)
319
- const kind = form.metadata && typeof form.metadata === "object" ? form.metadata.kind : undefined
320
- if (!id || !sessionID || sessionID === GLOBAL_FORM_OWNER || kind !== QUESTION_FORM_KIND || !Array.isArray(form.fields)) return null
321
- return { id, sessionID, title: text(form.title), fields: form.fields }
322
- }
323
-
324
- const v1OptionOf = (option) => {
325
- const label = option && typeof option === "object" ? text(option.label) : undefined
326
- return { value: label, label, description: option && text(option.description) }
327
- }
328
-
329
- const v1FieldOf = (question, index) => {
330
- const asked = question && typeof question === "object" ? question : {}
331
- return {
332
- key: "q" + index,
333
- title: text(asked.header),
334
- description: text(asked.question),
335
- type: asked.multiple === true ? "multiselect" : "string",
336
- options: Array.isArray(asked.options) ? asked.options.map(v1OptionOf) : [],
337
- custom: asked.custom !== false,
338
- }
339
- }
340
-
341
- const v1FormOf = (properties) => {
342
- if (!properties || typeof properties !== "object") return null
343
- const id = text(properties.id)
344
- const sessionID = text(properties.sessionID)
345
- if (!id || !sessionID || !Array.isArray(properties.questions)) return null
346
- return { id, sessionID, fields: properties.questions.map(v1FieldOf) }
347
- }
348
-
349
- const settledQuestionID = (properties) =>
350
- properties && typeof properties === "object" ? text(properties.requestID) ?? text(properties.id) : undefined
351
-
352
- const v1AnswerOf = (value) => {
353
- if (value === undefined) return []
354
- return Array.isArray(value) ? value : [String(value)]
355
- }
356
-
357
- const v1Answers = (form, answer) => form.fields.map((field) => v1AnswerOf(answer[field.key]))
358
-
359
- const loopbackServiceUrl = (raw) => {
360
- let url
361
- try {
362
- url = new URL(raw)
363
- } catch {
364
- return undefined
365
- }
366
- if (url.protocol !== SERVICE_PROTOCOL) return undefined
367
- if (Object.hasOwn(LOOPBACK_LITERAL, url.hostname)) url.hostname = LOOPBACK_LITERAL[url.hostname]
368
- return LOOPBACK_HOSTS.includes(url.hostname) ? url.origin : undefined
369
- }
370
-
371
- const serviceRequest = async (service, method, path, body) => {
372
- const headers = {}
373
- if (body) headers["content-type"] = "application/json"
374
- if (service.password) headers.authorization = "Basic " + Buffer.from(SERVICE_USER + ":" + service.password).toString("base64")
375
- try {
376
- return await fetch(new URL(path, service.url), {
377
- method,
378
- headers,
379
- body: body ? JSON.stringify(body) : undefined,
380
- redirect: "error",
381
- signal: AbortSignal.timeout(SERVICE_REQUEST_TIMEOUT_MS),
382
- })
383
- } catch {
384
- return null
385
- }
386
- }
387
-
388
- const serviceAnswersAsThisProcess = async (service) => {
389
- const response = await serviceRequest(service, "GET", SERVICE_INFO_PATH)
390
- if (!response || !response.ok) return false
391
- try {
392
- const info = await response.json()
393
- return Boolean(info) && info.pid === process.pid
394
- } catch {
395
- return false
396
- }
397
- }
398
-
399
- const registeredServiceOf = async (directory, name) => {
400
- try {
401
- const info = JSON.parse(await readFile(join(directory, name), "utf8"))
402
- const url = info && info.pid === process.pid ? loopbackServiceUrl(text(info.url)) : undefined
403
- return url ? { url, password: text(info.password) } : null
404
- } catch {
405
- return null
406
- }
407
- }
408
-
409
- const ownService = async () => {
410
- const directory = join(process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"), STATE_DIRECTORY)
411
- let names
412
- try {
413
- names = await readdir(directory)
414
- } catch {
415
- return null
416
- }
417
- for (const name of names.filter((entry) => SERVICE_REGISTRATION.test(entry))) {
418
- const service = await registeredServiceOf(directory, name)
419
- if (service && (await serviceAnswersAsThisProcess(service))) return service
420
- }
421
- return null
422
- }
423
-
424
- const succeeded = (response) => Boolean(response) && response.ok
425
-
426
- const replyOutcomeOf = (status) => {
427
- if (status !== undefined && status >= 200 && status < 300) return REPLY_DELIVERED
428
- return SETTLED_ELSEWHERE_STATUSES.includes(status) ? REPLY_SETTLED_ELSEWHERE : REPLY_REFUSED
429
- }
430
-
431
- const waitFor = (ms) => new Promise((resume) => {
432
- const timer = setTimeout(resume, ms)
433
- if (typeof timer.unref === "function") timer.unref()
434
- })
435
-
436
- const formPath = (form) => "/api/session/" + encodeURIComponent(form.sessionID) + "/form/" + encodeURIComponent(form.id)
437
-
438
- const formIsPending = async (service, form) => {
439
- const response = await serviceRequest(service, "GET", formPath(form))
440
- if (!response) return true
441
- if (response.status === NOT_FOUND) return false
442
- if (!response.ok) return true
443
- try {
444
- const body = await response.json()
445
- const state = body && body.data && body.data.state
446
- return !state || state.status === FORM_PENDING
447
- } catch {
448
- return true
449
- }
450
- }
451
-
452
- const formChannel = (service) => ({
453
- reply: async (form, answer) => {
454
- const response = await serviceRequest(service, "POST", formPath(form) + "/reply", { answer })
455
- return replyOutcomeOf(response ? response.status : undefined)
456
- },
457
- cancel: async (form, message) => {
458
- const query = message ? "?message=" + encodeURIComponent(message) : ""
459
- if (succeeded(await serviceRequest(service, "DELETE", formPath(form) + query))) return true
460
- return succeeded(await serviceRequest(service, "POST", formPath(form) + "/cancel"))
461
- },
462
- isPending: (form) => formIsPending(service, form),
463
- })
464
-
465
- const v2QuestionChannel = async () => {
466
- const service = await ownService()
467
- return service ? formChannel(service) : null
468
- }
469
-
470
- const v1QuestionChannel = (client) => {
471
- const raw = client && client._client && typeof client._client.post === "function" && typeof client._client.get === "function"
472
- ? client._client
473
- : null
474
- if (!raw) return undefined
475
- const post = async (url, requestID, body) => {
476
- const result = await raw.post({
477
- url,
478
- path: { requestID },
479
- ...(body ? { body, headers: { "Content-Type": "application/json" } } : {}),
480
- })
481
- if (!result || !result.error) return REPLY_DELIVERED
482
- return replyOutcomeOf(result.response ? result.response.status : undefined)
483
- }
484
- const isPending = async (form) => {
485
- const result = await raw.get({ url: "/question" })
486
- if (!result || result.error || !Array.isArray(result.data)) return true
487
- return result.data.some((request) => request && request.id === form.id)
488
- }
489
- const channel = {
490
- reply: (form, answer) => post("/question/{requestID}/reply", form.id, { answers: v1Answers(form, answer) }),
491
- cancel: (form) => post("/question/{requestID}/reject", form.id),
492
- isPending,
493
- }
494
- return async () => channel
495
- }
496
-
497
- const PusharyPlugin = async ({ client, directory, worktree, replyPermission, sessionParent, questionChannel }) => {
498
- const cwd = directory || worktree || process.cwd()
499
- // OpenCode raises a permission under a coarse key \u2014 "edit" covers both write and
500
- // edit \u2014 and names the actual tool only on tool.execute.before. Keeping the
501
- // pairing is what lets a rule written for Write mean Write here too.
502
- const tools = new Map()
503
- // Every gate still waiting. Held so a person answering in the terminal can end
504
- // ours: whoever answers first wins, and the loser stops asking.
505
- const waiting = new Map()
506
- const subagentSessions = new Map()
507
- const questions = new Map()
508
- const openQuestionChannel = questionChannel ?? v1QuestionChannel(client)
509
-
510
- const base = (sessionID) => ({ session_id: sessionID ?? "", cwd })
511
-
512
- const noteSession = (sessionID, parentID) =>
513
- remember(subagentSessions, text(sessionID), Promise.resolve(text(parentID)))
514
-
515
- const parentWithin = (sessionID) => new Promise((resolve, reject) => {
516
- const timer = setTimeout(() => reject(new Error("session lookup timed out")), SESSION_PARENT_TIMEOUT_MS)
517
- if (typeof timer.unref === "function") timer.unref()
518
- Promise.resolve()
519
- .then(() => sessionParent(sessionID))
520
- .then(resolve, reject)
521
- .finally(() => clearTimeout(timer))
522
- })
523
-
524
- const parentOf = (sessionID) => {
525
- if (!sessionID) return Promise.resolve(undefined)
526
- const known = subagentSessions.get(sessionID)
527
- if (known) return known
528
- if (!sessionParent) return Promise.resolve(undefined)
529
- const lookup = parentWithin(sessionID)
530
- .then((parentID) => text(parentID))
531
- .catch(() => {
532
- if (subagentSessions.get(sessionID) === lookup) subagentSessions.delete(sessionID)
533
- return undefined
534
- })
535
- remember(subagentSessions, sessionID, lookup)
536
- return lookup
537
- }
538
-
539
- const tellUnlessSubagent = (sessionID, payload) => {
540
- void parentOf(sessionID).then((parentID) => {
541
- if (!parentID) tell(payload)
542
- })
543
- }
544
-
545
- const tellTurnEnded = (sessionID, payload) => {
546
- void parentOf(sessionID).then((parentID) => {
547
- tell(parentID
548
- ? { ...base(parentID), hook_event_name: SUBAGENT_IDLE_EVENT, agent_id: sessionID }
549
- : payload)
550
- })
551
- }
552
-
553
- // Replying is the whole approval. Two shapes, because the client handed to a
554
- // plugin is generated: v1 exposes postSessionIdPermissionsPermissionId against
555
- // /session/{id}/permissions/{permissionID}, v2 exposes permission.reply against
556
- // /permission/{requestID}/reply. Both routes are live in the server today.
557
- const respond = async (asked, allow, message) => {
558
- const decision = allow ? "once" : "reject"
559
- const feedback = !allow && message ? { message } : {}
560
- if (replyPermission) {
561
- try {
562
- await replyPermission({ sessionID: asked.sessionID, requestID: asked.id, decision, ...feedback })
563
- } catch {}
564
- return
565
- }
566
- const legacy = client && typeof client.postSessionIdPermissionsPermissionId === "function"
567
- ? () => client.postSessionIdPermissionsPermissionId({
568
- path: { id: asked.sessionID, permissionID: asked.id },
569
- body: { response: decision },
570
- })
571
- : null
572
- const current = client && client.permission && typeof client.permission.reply === "function"
573
- ? () => client.permission.reply({
574
- // Current v2 uses flat parameters; older generated clients read path/body.
575
- requestID: asked.id, reply: decision, ...feedback,
576
- path: { requestID: asked.id },
577
- body: { reply: decision, ...feedback },
578
- }, { throwOnError: true })
579
- : null
580
-
581
- for (const attempt of [legacy, current]) {
582
- if (!attempt) continue
583
- try {
584
- const result = await attempt()
585
- if (result && result.error) continue
586
- return
587
- } catch {
588
- // The person answered first, or this client does not serve that route.
589
- // Either way the next shape is the only thing left to try.
590
- }
591
- }
592
- }
593
-
594
- const gate = async (asked) => {
595
- if (asked.permission === "external_directory") return
596
- if (replyPermission && !FORWARDED_ACTIONS.includes(asked.permission)) return
597
- if (Array.isArray(asked.metadata?.files) && asked.metadata.files.length > 1) return
598
- if (["read", "edit"].includes(asked.permission) && asked.resources?.length > 1) return
599
- const tool = tools.get(asked.callID)
600
- const workdir = ["shell", "bash"].includes(tool?.name) ? text(tool.input?.workdir) : undefined
601
- if (workdir && !isWorkdirInside(cwd, workdir)) return
602
- const reply = await run({
603
- ...base(asked.sessionID),
604
- cwd: workdir ? resolve(cwd, workdir) : cwd,
605
- project_dir: cwd,
606
- hook_event_name: "${OPENCODE_APPROVAL_EVENT}",
607
- tool_name: tool?.name ?? asked.permission,
608
- tool_input: inputFrom(asked.permission, { ...tool?.input, ...asked.metadata }, asked.resources),
609
- permission_id: asked.id,
610
- permission_type: asked.permission,
611
- title: asked.title,
612
- }, APPROVAL_TIMEOUT_MS, (child) => remember(waiting, asked.id, child))
613
-
614
- // Gone means the terminal already answered while we were asking. Replying now
615
- // would be answering a question nobody is holding open any more.
616
- if (!waiting.has(asked.id)) return
617
-
618
- const status = reply && typeof reply === "object" ? reply.status : undefined
619
- if (status === "allow" || status === "deny") await respond(asked, status === "allow", feedbackFor(reply.reason))
620
- waiting.delete(asked.id)
621
- }
622
-
623
- const withdraw = (id) => {
624
- const child = id && waiting.get(id)
625
- if (!child) return
626
- waiting.delete(id)
627
- // SIGTERM rather than SIGKILL: the hook cancels its outstanding question on
628
- // the way out, so the phone stops showing a decision the terminal has taken.
629
- try {
630
- child.kill("SIGTERM")
631
- } catch {}
632
- }
633
-
634
- const questionChannelFor = async () => {
635
- if (!openQuestionChannel) return null
636
- try {
637
- return await openQuestionChannel()
638
- } catch {
639
- return null
640
- }
641
- }
642
-
643
- const formPayload = (form) => ({
644
- ...base(form.sessionID),
645
- form_id: form.id,
646
- form: { title: form.title, fields: form.fields },
647
- })
648
-
649
- const settleQuestion = async (channel, form, reply) => {
650
- const outcome = reply && typeof reply === "object" ? reply : {}
651
- if (outcome.status === QUESTION_ANSWERED && outcome.answer && typeof outcome.answer === "object") {
652
- if ((await channel.reply(form, outcome.answer)) === REPLY_REFUSED) tell({ ...formPayload(form), hook_event_name: QUESTION_UNDELIVERED_EVENT })
653
- return
654
- }
655
- if (outcome.status === QUESTION_CANCELLED) await channel.cancel(form, feedbackFor(outcome.reason))
656
- }
657
-
658
- let recheck
659
- const stopRechecking = () => {
660
- clearInterval(recheck)
661
- recheck = undefined
662
- }
663
-
664
- const recheckQuestions = async () => {
665
- for (const [id, pending] of Array.from(questions)) {
666
- if (!pending.channel || !pending.child) continue
667
- let open = true
668
- try {
669
- open = await pending.channel.isPending(pending.form)
670
- } catch {}
671
- if (!open && questions.get(id) === pending) withdrawQuestion(id)
672
- }
673
- if (questions.size === 0) stopRechecking()
674
- }
675
-
676
- const keepRechecking = () => {
677
- if (recheck) return
678
- recheck = setInterval(() => void recheckQuestions(), QUESTION_RECHECK_MS)
679
- if (typeof recheck.unref === "function") recheck.unref()
680
- }
681
-
682
- const trackQuestion = (id, pending) => {
683
- if (questions.size >= MAX_TRACKED) withdrawQuestion(questions.keys().next().value)
684
- questions.set(id, pending)
685
- }
686
-
687
- const forgetQuestion = (id, pending) => {
688
- if (questions.get(id) === pending) questions.delete(id)
689
- if (questions.size === 0) stopRechecking()
690
- }
691
-
692
- const unreachableTold = new Map()
693
-
694
- const tellUnreachable = (form) => {
695
- if (unreachableTold.has(form.id)) return
696
- remember(unreachableTold, form.id, true)
697
- tell({ ...formPayload(form), hook_event_name: QUESTION_UNREACHABLE_EVENT })
698
- }
699
-
700
- const verifiedChannel = async (form, pending) => {
701
- const channel = await questionChannelFor()
702
- if (channel || !openQuestionChannel || questions.get(form.id) !== pending) return channel
703
- await waitFor(SERVICE_REVERIFY_MS)
704
- return questions.get(form.id) === pending ? questionChannelFor() : null
705
- }
706
-
707
- const bridgeQuestion = async (form) => {
708
- const pending = { child: undefined, channel: undefined, form, sessionID: form.sessionID }
709
- trackQuestion(form.id, pending)
710
- const channel = await verifiedChannel(form, pending)
711
- if (!channel || questions.get(form.id) !== pending) {
712
- if (!channel && openQuestionChannel && questions.get(form.id) === pending) tellUnreachable(form)
713
- forgetQuestion(form.id, pending)
714
- return
715
- }
716
- pending.channel = channel
717
- keepRechecking()
718
- pending.holdsStdin = await hookWithdrawsOverStdin()
719
- if (questions.get(form.id) !== pending) return
720
- const asked = { ...formPayload(form), hook_event_name: QUESTION_EVENT, ...(pending.holdsStdin ? { [WITHDRAW_ON_STDIN_END]: true } : {}) }
721
- const reply = await run(asked, undefined, (child) => {
722
- pending.child = child
723
- })
724
- if (questions.get(form.id) !== pending) return
725
- try {
726
- await settleQuestion(channel, form, reply)
727
- } catch {}
728
- forgetQuestion(form.id, pending)
729
- }
730
-
731
- const signalQuestionHook = (child) => {
732
- try {
733
- child.kill("SIGTERM")
734
- } catch {}
735
- }
736
-
737
- const endQuestionHook = (child) => {
738
- try {
739
- child.stdin.end()
740
- } catch {}
741
- const fallback = setTimeout(() => signalQuestionHook(child), QUESTION_WITHDRAW_GRACE_MS)
742
- if (typeof fallback.unref === "function") fallback.unref()
743
- child.once("close", () => clearTimeout(fallback))
744
- }
745
-
746
- const withdrawQuestion = (id) => {
747
- const pending = id ? questions.get(id) : undefined
748
- if (!pending) return
749
- forgetQuestion(id, pending)
750
- if (!pending.child) return
751
- if (pending.holdsStdin) endQuestionHook(pending.child)
752
- else signalQuestionHook(pending.child)
753
- }
754
-
755
- const withdrawSessionQuestions = (sessionID) => {
756
- for (const [id, pending] of Array.from(questions)) {
757
- if (pending.sessionID === sessionID) withdrawQuestion(id)
758
- }
759
- }
760
-
761
- return {
762
- "tool.execute.before": async (input) => {
763
- remember(tools, input && input.callID, { name: input?.tool, input: input?.args })
764
- },
765
-
766
- "tool.execute.after": async (input, output) => {
767
- const call = input && input.callID
768
- if (call) tools.delete(call)
769
- tell({
770
- ...base(input && input.sessionID),
771
- hook_event_name: "tool.execute.after",
772
- tool_name: text(input && input.tool) ?? "unknown",
773
- tool_input: input && input.args && typeof input.args === "object" ? input.args : {},
774
- tool_result: output?.error ? { error: output.error } : { title: text(output && output.title), output: text(output && output.output) },
775
- })
776
- },
777
-
778
- "chat.message": async (input, output) => {
779
- const parts = output && Array.isArray(output.parts) ? output.parts : []
780
- const prompt = parts
781
- .filter((part) => part && part.type === "text" && typeof part.text === "string")
782
- .map((part) => part.text)
783
- .join("\\n")
784
- .trim()
785
- if (!prompt) return
786
- tellUnlessSubagent(input && input.sessionID, { ...base(input && input.sessionID), hook_event_name: "chat.message", prompt })
787
- },
788
-
789
- event: async ({ event }) => {
790
- // Never allowed to throw: the host calls this hook without awaiting it, so a
791
- // rejection here is an unhandled rejection in somebody's editor.
792
- try {
793
- const type = event && event.type
794
- const properties = event && event.properties
795
- if (APPROVAL_EVENTS.includes(type)) {
796
- const asked = askedFrom(properties)
797
- if (asked && !waiting.has(asked.id)) void gate(asked)
798
- return
799
- }
800
- if (type === ${JSON.stringify(OPENCODE_REPLIED_EVENT)}) {
801
- withdraw(repliedID(properties))
802
- return
803
- }
804
- if (type === QUESTION_EVENT || type === V1_QUESTION_EVENT) {
805
- const form = type === QUESTION_EVENT ? formOf(properties) : v1FormOf(properties)
806
- if (form && BRIDGES_QUESTIONS && APPROVAL_EVENTS.length > 0 && !questions.has(form.id)) void bridgeQuestion(form)
807
- return
808
- }
809
- if (QUESTION_SETTLED_EVENTS.includes(type)) {
810
- withdrawQuestion(settledQuestionID(properties))
811
- return
812
- }
813
- if (type === INTERRUPTED_EVENT) {
814
- withdrawSessionQuestions(text(properties && properties.sessionID))
815
- return
816
- }
817
- if (type === ${JSON.stringify(OPENCODE_SESSION_CREATED_EVENT)}) {
818
- noteSession(properties && properties.sessionID, properties && properties.parentID)
819
- return
820
- }
821
- // session.idle is the turn boundary \u2014 OpenCode's equivalent of Claude's
822
- // Stop, not of its SessionEnd. Nothing else on the stream is relayed: the
823
- // receipts already arrive through the hooks above, and reporting the same
824
- // moment twice would double every row on the account.
825
- if (type === ${JSON.stringify(OPENCODE_IDLE_EVENT)}) {
826
- withdrawSessionQuestions(text(properties && properties.sessionID))
827
- tellTurnEnded(text(properties && properties.sessionID), {
828
- ...base(properties && properties.sessionID),
829
- hook_event_name: ${JSON.stringify(OPENCODE_IDLE_EVENT)},
830
- })
831
- return
832
- }
833
- if (type === ${JSON.stringify(OPENCODE_FAILED_EVENT)}) {
834
- withdrawSessionQuestions(text(properties && properties.sessionID))
835
- tellTurnEnded(text(properties && properties.sessionID), {
836
- ...base(properties && properties.sessionID),
837
- hook_event_name: ${JSON.stringify(OPENCODE_FAILED_EVENT)},
838
- error: failureReasonOf(properties && properties.error),
839
- })
840
- }
841
- } catch {}
842
- },
843
-
844
- reconcile: recheckQuestions,
845
-
846
- dispose: async () => {
847
- for (const id of Array.from(waiting.keys())) withdraw(id)
848
- for (const id of Array.from(questions.keys())) withdrawQuestion(id)
849
- stopRechecking()
850
- tools.clear()
851
- },
852
- }
853
- }
854
-
855
- export default {
856
- id: "pushary",
857
- server: PusharyPlugin,
858
- async setup(ctx) {
859
- const hooks = await PusharyPlugin({
860
- directory: ctx.location.directory,
861
- replyPermission: (request) => ctx.permission.reply(request),
862
- sessionParent: typeof ctx.session.get === "function"
863
- ? (sessionID) => Promise.resolve(ctx.session.get({ sessionID })).then((info) => info && info.parentID)
864
- : undefined,
865
- questionChannel: v2QuestionChannel,
866
- })
867
- await ctx.tool.hook("execute.before", (event) => hooks["tool.execute.before"]({
868
- callID: event.id, tool: event.tool, sessionID: event.sessionID, args: event.input,
869
- }))
870
- await ctx.tool.hook("execute.after", (event) => hooks["tool.execute.after"]({
871
- callID: event.id, tool: event.tool, sessionID: event.sessionID, args: event.input,
872
- }, { output: event.status === "completed" && Array.isArray(event.result.content)
873
- ? event.result.content.filter((part) => part.type === "text").map((part) => part.text).join("\\n")
874
- : undefined, error: event.status === "error" ? event.error.message : undefined }))
875
- await ctx.session.hook("prompt", (event) => hooks["chat.message"]({ sessionID: event.sessionID }, {
876
- parts: [{ type: "text", text: event.prompt.text }],
877
- }))
878
- const controller = new AbortController()
879
- const pause = (ms) => new Promise((resume) => {
880
- if (controller.signal.aborted) return resume()
881
- const done = () => {
882
- clearTimeout(timer)
883
- controller.signal.removeEventListener("abort", done)
884
- resume()
885
- }
886
- const timer = setTimeout(done, ms)
887
- if (typeof timer.unref === "function") timer.unref()
888
- controller.signal.addEventListener("abort", done, { once: true })
889
- })
890
- const resubscribeDelay = (failures) => RESUBSCRIBE_DELAYS_MS[Math.min(failures, RESUBSCRIBE_DELAYS_MS.length - 1)]
891
- const consume = async () => {
892
- let failures = 0
893
- let warned = false
894
- while (!controller.signal.aborted) {
895
- try {
896
- for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
897
- if (controller.signal.aborted) break
898
- failures = 0
899
- if (event.location && (event.location.directory !== ctx.location.directory || event.location.workspaceID !== ctx.location.workspaceID)) continue
900
- const type = event.type === "session.execution.succeeded" ? "session.idle" : event.type
901
- await hooks.event({ event: { type, properties: event.data } })
902
- }
903
- break
904
- } catch {
905
- if (controller.signal.aborted) break
906
- if (!warned) console.error("Pushary event subscription stopped; native prompts remain available.")
907
- warned = true
908
- }
909
- await pause(resubscribeDelay(failures))
910
- failures += 1
911
- await hooks.reconcile()
912
- }
913
- await hooks.dispose()
914
- }
915
- const events = consume()
916
- return async () => {
917
- controller.abort()
918
- await hooks.dispose()
919
- await events
920
- }
921
- },
922
- }
923
- `;
924
- var openCodePluginModule = (bridgesQuestions = OPENCODE_CLI_BRIDGES_QUESTIONS) => ({
925
- marker: OPENCODE_PLUGIN_MARKER,
926
- source: openCodePluginSource(bridgesQuestions),
927
- placeholder: OPENCODE_PLUGIN_PLACEHOLDER,
928
- approvalEvents: {
929
- placeholder: OPENCODE_APPROVAL_EVENTS_PLACEHOLDER,
930
- events: OPENCODE_ASKED_EVENTS
931
- },
932
- sibling: {
933
- path: OPENCODE_PLUGIN_SIBLING,
934
- contents: OPENCODE_PLUGIN_SIBLING_CONTENTS
935
- }
936
- });
937
- var renderOpenCodePlugin = (module, argv, holdsApprovals = true) => module.source.replace(module.placeholder, JSON.stringify(argv)).replace(module.approvalEvents.placeholder, JSON.stringify(holdsApprovals ? module.approvalEvents.events : []));
938
- var COMMAND_LINE = /^const COMMAND = (.*)$/m;
939
- var isArgv = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
940
- var openCodePluginArgv = (contents) => {
941
- if (!isOpenCodePluginOurs(contents)) return null;
942
- const line = contents.match(COMMAND_LINE)?.[1];
943
- if (line === void 0) return null;
944
- try {
945
- const parsed = JSON.parse(line);
946
- return isArgv(parsed) ? parsed : null;
947
- } catch {
948
- return null;
949
- }
950
- };
951
- var isOpenCodePluginOurs = (contents) => contents.includes(OPENCODE_PLUGIN_MARKER);
952
-
953
- export {
954
- OPENCODE_PLUGIN_PLACEHOLDER,
955
- OPENCODE_PLUGIN_FILE,
956
- OPENCODE_PLUGIN_DIR,
957
- OPENCODE_PLUGIN_SIBLING,
958
- OPENCODE_PLUGIN_SIBLING_CONTENTS,
959
- OPENCODE_IDLE_EVENT,
960
- OPENCODE_FAILED_EVENT,
961
- OPENCODE_SUBAGENT_IDLE_EVENT,
962
- OPENCODE_QUESTION_EVENT,
963
- OPENCODE_QUESTION_ANSWERED,
964
- OPENCODE_QUESTION_CANCELLED,
965
- OPENCODE_QUESTION_UNDELIVERED_EVENT,
966
- OPENCODE_QUESTION_UNREACHABLE_EVENT,
967
- OPENCODE_SERVICE_REQUEST_TIMEOUT_MS,
968
- OPENCODE_STATE_DIRECTORY,
969
- OPENCODE_SERVICE_REGISTRATION,
970
- OPENCODE_SERVICE_USER,
971
- OPENCODE_SERVICE_PROTOCOL,
972
- OPENCODE_SERVICE_INFO_PATH,
973
- OPENCODE_LOOPBACK_HOSTS,
974
- OPENCODE_LOOPBACK_ALIASES,
975
- OPENCODE_CAPABILITIES_EVENT,
976
- OPENCODE_HOOK_CAPABILITIES,
977
- OPENCODE_QUESTION_WITHDRAW_TIMEOUT_MS,
978
- OPENCODE_QUESTION_ASK_IN_FLIGHT_GRACE_MS,
979
- OPENCODE_HOOK_EXIT_MARGIN_MS,
980
- openCodePluginModule,
981
- renderOpenCodePlugin,
982
- openCodePluginArgv,
983
- isOpenCodePluginOurs
984
- };