@pushary/agent-hooks 1.9.145 → 1.9.147

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 (167) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +5 -4
  3. package/data/SKILL.md +3 -3
  4. package/data/cursor-plugin/scripts/redaction.mjs +2 -1
  5. package/data/cursor-plugin/skills/pushary/SKILL.md +2 -2
  6. package/data/openclaw-plugin/LICENSE +21 -0
  7. package/data/openclaw-plugin/README.md +113 -0
  8. package/data/openclaw-plugin/dist/api-key-shape.js +5 -0
  9. package/data/openclaw-plugin/dist/approval-hook.js +88 -0
  10. package/data/openclaw-plugin/dist/approval-question.js +66 -0
  11. package/data/openclaw-plugin/dist/connection.js +101 -0
  12. package/data/openclaw-plugin/dist/decision-reply.js +6 -0
  13. package/data/openclaw-plugin/dist/gate-result.js +58 -0
  14. package/data/openclaw-plugin/dist/gate.js +173 -0
  15. package/data/openclaw-plugin/dist/hook-budget.js +19 -0
  16. package/data/openclaw-plugin/dist/host-api.js +1 -0
  17. package/data/openclaw-plugin/dist/host-version.js +25 -0
  18. package/data/openclaw-plugin/dist/index.js +32 -0
  19. package/data/openclaw-plugin/dist/openclaw-paths.js +43 -0
  20. package/data/openclaw-plugin/dist/openclaw-write-guard.js +93 -0
  21. package/data/openclaw-plugin/dist/protected-writes.js +217 -0
  22. package/data/openclaw-plugin/dist/pushary-client.js +103 -0
  23. package/data/openclaw-plugin/dist/pushary-hosts.js +3 -0
  24. package/data/openclaw-plugin/dist/redaction.js +53 -0
  25. package/data/openclaw-plugin/dist/replies.js +65 -0
  26. package/data/openclaw-plugin/dist/settings.js +103 -0
  27. package/data/openclaw-plugin/openclaw.plugin.json +32 -0
  28. package/data/openclaw-plugin/package.json +70 -0
  29. package/data/vscode-plugin/scripts/redaction.mjs +2 -1
  30. package/data/vscode-plugin/skills/pushary/SKILL.md +2 -2
  31. package/dist/{api-KWJQMO6G.js → api-2KDVLXHT.js} +11 -11
  32. package/dist/bin/pushary-audit.js +3 -3
  33. package/dist/bin/pushary-bell-hook.js +28 -28
  34. package/dist/bin/pushary-bell.js +11 -11
  35. package/dist/bin/pushary-claude.js +27 -27
  36. package/dist/bin/pushary-clean.js +76 -39
  37. package/dist/bin/pushary-codex-bridge.js +23 -23
  38. package/dist/bin/pushary-codex-hook.js +35 -35
  39. package/dist/bin/pushary-codex-session.js +8 -8
  40. package/dist/bin/pushary-codex.js +16 -16
  41. package/dist/bin/pushary-connect.js +78 -36
  42. package/dist/bin/pushary-cowork.js +5 -5
  43. package/dist/bin/pushary-daemon.js +44 -43
  44. package/dist/bin/pushary-disconnect.js +28 -28
  45. package/dist/bin/pushary-display-hook.js +96 -44
  46. package/dist/bin/pushary-doctor.js +124 -55
  47. package/dist/bin/pushary-elicitation-hook.js +28 -28
  48. package/dist/bin/pushary-gemini-bridge.js +17 -17
  49. package/dist/bin/pushary-gemini-hook.js +32 -32
  50. package/dist/bin/pushary-hook.js +35 -35
  51. package/dist/bin/pushary-login.js +22 -22
  52. package/dist/bin/pushary-logout.js +33 -31
  53. package/dist/bin/pushary-mcp.js +12 -12
  54. package/dist/bin/pushary-mode.js +16 -16
  55. package/dist/bin/pushary-notification-hook.js +27 -27
  56. package/dist/bin/pushary-opencode-hook.js +31 -31
  57. package/dist/bin/pushary-permission-denied-hook.js +35 -35
  58. package/dist/bin/pushary-permission-hook.js +35 -35
  59. package/dist/bin/pushary-post-hook.js +28 -28
  60. package/dist/bin/pushary-prompt-hook.js +27 -27
  61. package/dist/bin/pushary-session-end-hook.js +27 -27
  62. package/dist/bin/pushary-session-start-hook.js +37 -36
  63. package/dist/bin/pushary-setup.js +140 -87
  64. package/dist/bin/pushary-stats.js +5 -5
  65. package/dist/bin/pushary-status.js +38 -36
  66. package/dist/bin/pushary-stop-hook.js +27 -27
  67. package/dist/bin/pushary-stopfailure-hook.js +27 -27
  68. package/dist/bin/pushary-suggestions.js +16 -16
  69. package/dist/bin/pushary-transcript-register.js +17 -17
  70. package/dist/bin/pushary-transcripts.js +25 -25
  71. package/dist/bin/pushary-upgrade.js +42 -41
  72. package/dist/bin/pushary-wait.js +16 -16
  73. package/dist/bin/pushary.js +7 -7
  74. package/dist/{chunk-4KDRT3OA.js → chunk-2EETRVCZ.js} +1 -1
  75. package/dist/{chunk-LJRPWUST.js → chunk-2G54YLN3.js} +3 -3
  76. package/dist/{chunk-R34RWVN2.js → chunk-2I6A34GJ.js} +14 -5
  77. package/dist/{chunk-WPBWJMBZ.js → chunk-2QY2BD4T.js} +5 -5
  78. package/dist/{chunk-RO6EVL5C.js → chunk-2RAIG6NF.js} +2 -2
  79. package/dist/{chunk-LD4R2P6N.js → chunk-2YNAQ5TX.js} +1 -1
  80. package/dist/{chunk-TRV3ETGY.js → chunk-37ZBJB2Q.js} +5 -5
  81. package/dist/{chunk-BWREST4F.js → chunk-3NMX4725.js} +1 -1
  82. package/dist/{chunk-YRJZF5RG.js → chunk-3TTXOU6G.js} +3 -3
  83. package/dist/{chunk-FCSPMSDC.js → chunk-4P3ML7HP.js} +200 -59
  84. package/dist/{chunk-IRPIMQ7U.js → chunk-526XSNMS.js} +3 -3
  85. package/dist/{chunk-4L5WPDTB.js → chunk-57GVGSOQ.js} +1 -1
  86. package/dist/{chunk-ZORBUQFG.js → chunk-5II3USXS.js} +2 -2
  87. package/dist/{chunk-USFZJAB4.js → chunk-5K65H6OO.js} +1 -1
  88. package/dist/{chunk-5TWW7ZUL.js → chunk-6C5QRJIH.js} +5 -5
  89. package/dist/{chunk-KFALRZIN.js → chunk-6EPTMB7L.js} +4 -4
  90. package/dist/{chunk-LQXUWXQP.js → chunk-6JBX55K4.js} +31 -8
  91. package/dist/{chunk-B4JQIH5M.js → chunk-6YVGY2ZX.js} +7 -7
  92. package/dist/{chunk-7LTP2GHO.js → chunk-72S6PF2I.js} +2 -2
  93. package/dist/{chunk-WMBWKPKJ.js → chunk-7P32YU2M.js} +10 -74
  94. package/dist/{chunk-TJXJGMSP.js → chunk-7TVSWGAV.js} +8 -6
  95. package/dist/{chunk-L4OGTRVW.js → chunk-7WDEJTNX.js} +4 -4
  96. package/dist/{chunk-KGFB2LEB.js → chunk-7XIJD7NL.js} +3 -3
  97. package/dist/{chunk-S3A4PCRR.js → chunk-A5MSVNFS.js} +10 -10
  98. package/dist/{chunk-OONMKLUF.js → chunk-ANLR5G2W.js} +4 -4
  99. package/dist/{chunk-HOQH5CLZ.js → chunk-BEDAQAEN.js} +1 -1
  100. package/dist/{chunk-JKWUF776.js → chunk-BHGSNYG5.js} +3 -3
  101. package/dist/{chunk-VTJ4WZOC.js → chunk-BU2J4P7P.js} +3 -3
  102. package/dist/{chunk-6UK4K5RS.js → chunk-BYVLAPCF.js} +1 -1
  103. package/dist/{chunk-KS3PNTRT.js → chunk-CSNG5NQR.js} +1 -1
  104. package/dist/{chunk-JZT2LPRM.js → chunk-D7ZWJYXB.js} +1 -1
  105. package/dist/{chunk-Y7INHH5G.js → chunk-ELRZO6A7.js} +3 -3
  106. package/dist/{chunk-6IWOMXUF.js → chunk-EV54ZQ5J.js} +4 -4
  107. package/dist/{chunk-33BYPZ52.js → chunk-FHBJJOMF.js} +1 -1
  108. package/dist/{chunk-YU5XE6VC.js → chunk-FKGWP4MF.js} +8 -7
  109. package/dist/{chunk-2ELNRGNX.js → chunk-FMAIUTVU.js} +3 -3
  110. package/dist/{chunk-EPWOARGR.js → chunk-FWCECQTY.js} +2 -2
  111. package/dist/{chunk-BYKRAYGD.js → chunk-GGCUXNZN.js} +1 -1
  112. package/dist/{chunk-WH4ODOCE.js → chunk-GIWI5IHB.js} +6 -6
  113. package/dist/{chunk-72LP4RPC.js → chunk-GJV5RVUU.js} +98 -47
  114. package/dist/chunk-GPAMD5JG.js +157 -0
  115. package/dist/{chunk-FNAH3YJC.js → chunk-I72UU75H.js} +16 -16
  116. package/dist/{chunk-ZSOCJHL7.js → chunk-ISM6XF3V.js} +309 -5
  117. package/dist/{chunk-Q6P7G4NY.js → chunk-ISOP4ENY.js} +17 -5
  118. package/dist/{chunk-6LZ7MXHD.js → chunk-JDIKCM2N.js} +5 -5
  119. package/dist/{chunk-52UXNCZG.js → chunk-KDJIDRJS.js} +3 -3
  120. package/dist/{chunk-LMU6NG2G.js → chunk-KFL7OWLI.js} +1 -1
  121. package/dist/{chunk-PXZTCR4M.js → chunk-KH27X5CW.js} +2 -2
  122. package/dist/{chunk-MOC2DN42.js → chunk-KXMIDDUN.js} +2 -2
  123. package/dist/{chunk-QKTF7WS6.js → chunk-L2M6D2N4.js} +4 -4
  124. package/dist/{chunk-CUR2DCZN.js → chunk-L6BTSIKF.js} +4 -4
  125. package/dist/{chunk-YZA3YBHX.js → chunk-LO52V6WG.js} +2 -2
  126. package/dist/{chunk-GK5X2ZTN.js → chunk-MI7GHNTO.js} +5 -5
  127. package/dist/{chunk-MKHVLDMN.js → chunk-MYJJNLT2.js} +2 -2
  128. package/dist/{chunk-WUT3PO33.js → chunk-NAGF5ZJ2.js} +8 -8
  129. package/dist/{chunk-ZBMVOMFG.js → chunk-NMUEUDTT.js} +1 -1
  130. package/dist/{chunk-MNU5N3CQ.js → chunk-OSYULPJO.js} +23 -12
  131. package/dist/{chunk-SQL5YXUH.js → chunk-OXDKZYBO.js} +1 -1
  132. package/dist/chunk-OYIN77HO.js +72 -0
  133. package/dist/{chunk-KKPT7ROP.js → chunk-P6W2V2AP.js} +2 -2
  134. package/dist/{chunk-G3VSMI7K.js → chunk-Q3JW44JV.js} +2 -2
  135. package/dist/{chunk-K2SKUBYY.js → chunk-Q6POCQOV.js} +12 -12
  136. package/dist/{chunk-IIN26HL7.js → chunk-Q767Y4LY.js} +1 -1
  137. package/dist/{chunk-GURIOZE7.js → chunk-QGKFDSEO.js} +8 -8
  138. package/dist/{chunk-YNCVSKUW.js → chunk-RZGR4G5G.js} +5 -5
  139. package/dist/{chunk-2LGDEPVL.js → chunk-RZJHCHEA.js} +6 -6
  140. package/dist/{chunk-ZJZNT2G5.js → chunk-T274HRSR.js} +4 -4
  141. package/dist/chunk-T2CR5REM.js +176 -0
  142. package/dist/{chunk-A2H256WR.js → chunk-T3TVMMXJ.js} +1 -1
  143. package/dist/{chunk-NTMKJRQ3.js → chunk-TZ7CBPCD.js} +2 -2
  144. package/dist/{chunk-S7HGPKCL.js → chunk-UGPNLU4O.js} +1 -1
  145. package/dist/{chunk-DZIZ3XFL.js → chunk-UR55VBLY.js} +2 -2
  146. package/dist/{chunk-PY6CM4NK.js → chunk-WLKW2TF7.js} +19 -12
  147. package/dist/{chunk-63WX5KZN.js → chunk-WNV3X2VU.js} +3 -3
  148. package/dist/{chunk-WOSO4YFQ.js → chunk-XQOBM3E6.js} +3 -3
  149. package/dist/{chunk-RWLNTZK5.js → chunk-YICO6HEW.js} +5 -5
  150. package/dist/{chunk-FO3MDD26.js → chunk-YM2T76UM.js} +27 -0
  151. package/dist/chunk-YOVJOHM5.js +36 -0
  152. package/dist/{chunk-IDLOJIIS.js → chunk-ZKAQWXGO.js} +1 -1
  153. package/dist/{codex-app-cards-switch-F7WQ7Y3I.js → codex-app-cards-switch-GN65VEKM.js} +11 -11
  154. package/dist/{codex-card-routing-EVL5L36G.js → codex-card-routing-JTS75442.js} +2 -2
  155. package/dist/{codex-desktop-launch-PL6Z2ELZ.js → codex-desktop-launch-AQ2HSOQJ.js} +1 -1
  156. package/dist/{codex-session-launch-7NQEAUDU.js → codex-session-launch-QYZZGVSQ.js} +20 -20
  157. package/dist/{config-KFFD4VWH.js → config-5ATI6KPI.js} +3 -3
  158. package/dist/{global-upgrade-L3CY6EFF.js → global-upgrade-K4HWVUMI.js} +9 -9
  159. package/dist/{identity-DPYYIMHL.js → identity-V2GZCPJV.js} +4 -4
  160. package/dist/{live-capabilities-QJEXK6GH.js → live-capabilities-PD62FO4K.js} +4 -4
  161. package/dist/{paths-PEF6C64P.js → paths-WPJEIHUE.js} +7 -3
  162. package/dist/{reapply-7APCQRRK.js → reapply-ZEWMGDXT.js} +30 -29
  163. package/dist/src/index.js +34 -34
  164. package/dist/{upgrade-lock-A7OKXMRW.js → upgrade-lock-7OR6V323.js} +4 -4
  165. package/dist/{usage-HSS33762.js → usage-GWZ3UGZG.js} +3 -3
  166. package/package.json +1 -1
  167. package/dist/chunk-D3UFDCTQ.js +0 -87
@@ -0,0 +1,173 @@
1
+ import { CANCEL_REQUEST_TIMEOUT_MS, POLL_RESPONSE_GRACE_MS, } from './pushary-client.js';
2
+ import { askReplyOf, isExplicitApproval, questionStateOf, withdrawalOf } from './replies.js';
3
+ export const ASK_ATTEMPTS = 3;
4
+ export const ASK_RETRY_PAUSE_MS = 1_000;
5
+ export const POLL_RETRY_PAUSES_MS = [2_000, 4_000, 8_000, 15_000];
6
+ export const UNANSWERED_POLL_PAUSE_MS = 2_000;
7
+ export const LATE_ANSWER_POLL_MS = 1_000;
8
+ export const WITHDRAW_ATTEMPTS = 3;
9
+ export const WITHDRAW_RETRY_PAUSE_MS = 500;
10
+ const RETRYABLE_FAILURES = new Set(['network', 'timed_out', 'server_error']);
11
+ const LATE_ANSWER_REQUEST_MS = LATE_ANSWER_POLL_MS + POLL_RESPONSE_GRACE_MS;
12
+ const decisionFor = (answer) => isExplicitApproval(answer) ? { kind: 'approved' } : { kind: 'denied' };
13
+ const askArgumentsFor = (request, waitEndsAt) => ({
14
+ question: request.question.question,
15
+ type: 'confirm',
16
+ wait: false,
17
+ context: request.question.context,
18
+ agentName: request.agentName,
19
+ toolName: request.question.toolName,
20
+ action: request.question.action,
21
+ actionBody: request.question.actionBody,
22
+ waitEndsAt,
23
+ localSurfaceAvailable: false,
24
+ requestId: request.requestId,
25
+ ...(request.question.toolTarget === undefined ? {} : { toolTarget: request.question.toolTarget }),
26
+ ...(request.sessionId === undefined ? {} : { sessionId: request.sessionId }),
27
+ ...(request.machineId === undefined ? {} : { machineId: request.machineId }),
28
+ });
29
+ const isRetryable = (failure) => RETRYABLE_FAILURES.has(failure);
30
+ const pollFailureOf = (polled, state) => {
31
+ if (polled.kind === 'failed')
32
+ return polled.failure;
33
+ return state?.kind === 'unreadable' ? 'unreadable_reply' : null;
34
+ };
35
+ const retryPauseMs = (consecutiveFailures) => POLL_RETRY_PAUSES_MS[Math.min(consecutiveFailures, POLL_RETRY_PAUSES_MS.length) - 1] ?? POLL_RETRY_PAUSES_MS[0];
36
+ const pauseAfterPoll = (consecutiveFailures) => consecutiveFailures > 0 ? retryPauseMs(consecutiveFailures) : UNANSWERED_POLL_PAUSE_MS;
37
+ const isAbortFailure = (result) => result.kind === 'failed' && result.failure === 'aborted';
38
+ const isSettled = (state) => state !== null && state.kind !== 'pending' && state.kind !== 'unreadable';
39
+ const withdrawalOfResult = (result) => (result.kind === 'reply' ? withdrawalOf(result.value) : 'unreachable');
40
+ const WITHDRAW_RETRY_NEEDS_MS = WITHDRAW_RETRY_PAUSE_MS + CANCEL_REQUEST_TIMEOUT_MS;
41
+ const mayRetryWithdrawal = (result, attempt, remainingMs) => result.kind === 'failed' && isRetryable(result.failure) && attempt < WITHDRAW_ATTEMPTS && remainingMs >= WITHDRAW_RETRY_NEEDS_MS;
42
+ export const runApprovalGate = async (request, dependencies) => {
43
+ const { questions, clock } = dependencies;
44
+ const startedAt = clock.monotonicMs();
45
+ const deadline = startedAt + request.holdMs;
46
+ const hookDeadline = deadline + request.withdrawReserveMs;
47
+ const aborted = () => request.signal?.aborted === true;
48
+ const remainingMs = (until) => until - clock.monotonicMs();
49
+ const heldMs = () => Math.max(0, clock.monotonicMs() - startedAt);
50
+ const cancelWithRetry = async (correlationId, endsAt) => {
51
+ for (let attempt = 1;; attempt += 1) {
52
+ const result = await questions.cancel(correlationId);
53
+ const withdrawal = withdrawalOfResult(result);
54
+ if (withdrawal !== 'unreachable' || !mayRetryWithdrawal(result, attempt, remainingMs(endsAt)))
55
+ return withdrawal;
56
+ await clock.sleep(WITHDRAW_RETRY_PAUSE_MS, undefined);
57
+ }
58
+ };
59
+ const lateAnswerOf = async (correlationId, endsAt) => {
60
+ if (remainingMs(endsAt) < LATE_ANSWER_REQUEST_MS)
61
+ return { kind: 'gone' };
62
+ const late = await questions.waitForAnswer(correlationId, LATE_ANSWER_POLL_MS, undefined);
63
+ const state = late.kind === 'reply' ? questionStateOf(late.value) : null;
64
+ if (state?.kind === 'stopped')
65
+ return { kind: 'stop' };
66
+ return state?.kind === 'answered' ? { kind: 'answered', value: state.value } : { kind: 'gone' };
67
+ };
68
+ const withdraw = async (correlationId) => {
69
+ const endsAt = Math.min(hookDeadline, clock.monotonicMs() + request.withdrawReserveMs);
70
+ const withdrawal = await cancelWithRetry(correlationId, endsAt);
71
+ if (withdrawal === 'not_pending')
72
+ return lateAnswerOf(correlationId, endsAt);
73
+ return { kind: withdrawal };
74
+ };
75
+ const cancelledAfterWithdrawing = async (correlationId) => {
76
+ await withdraw(correlationId);
77
+ return { kind: 'cancelled' };
78
+ };
79
+ const unavailableAfterWithdrawing = async (correlationId, failure) => {
80
+ await withdraw(correlationId);
81
+ return { kind: 'unavailable', failure };
82
+ };
83
+ const handBack = async (correlationId, reason) => {
84
+ const withdrawn = await withdraw(correlationId);
85
+ if (withdrawn.kind === 'answered')
86
+ return decisionFor(withdrawn.value);
87
+ if (withdrawn.kind === 'stop')
88
+ return { kind: 'stopped' };
89
+ if (withdrawn.kind === 'unreachable')
90
+ return { kind: 'unavailable', failure: 'network' };
91
+ return reason === 'no_devices' ? { kind: 'undeliverable' } : { kind: 'handed_back' };
92
+ };
93
+ const createQuestion = async () => {
94
+ const args = askArgumentsFor(request, new Date(clock.wallMs() + request.holdMs).toISOString());
95
+ let last = { kind: 'failed', failure: 'network' };
96
+ for (let attempt = 0; attempt < ASK_ATTEMPTS && remainingMs(deadline) > 0; attempt += 1) {
97
+ if (attempt > 0) {
98
+ if (aborted())
99
+ return last;
100
+ await clock.sleep(Math.min(ASK_RETRY_PAUSE_MS, remainingMs(deadline)), request.signal);
101
+ }
102
+ last = await questions.ask(args);
103
+ if (last.kind === 'reply' || !isRetryable(last.failure))
104
+ return last;
105
+ }
106
+ return last;
107
+ };
108
+ const settleAfterHold = async (correlationId, handBackAt, lastFailure) => {
109
+ const handBackDue = handBackAt !== null && handBackAt < deadline && clock.monotonicMs() >= handBackAt;
110
+ const withdrawn = await withdraw(correlationId);
111
+ if (withdrawn.kind === 'answered')
112
+ return decisionFor(withdrawn.value);
113
+ if (withdrawn.kind === 'stop')
114
+ return { kind: 'stopped' };
115
+ if (withdrawn.kind === 'unreachable')
116
+ return { kind: 'unavailable', failure: lastFailure ?? 'network' };
117
+ if (handBackDue)
118
+ return { kind: 'handed_back' };
119
+ if (lastFailure !== null)
120
+ return { kind: 'unavailable', failure: lastFailure };
121
+ return { kind: 'unanswered', heldMs: heldMs() };
122
+ };
123
+ const settleState = async (correlationId, state) => {
124
+ if (state.kind === 'answered')
125
+ return decisionFor(state.value);
126
+ if (state.kind === 'stopped')
127
+ return { kind: 'stopped' };
128
+ if (state.kind === 'ended')
129
+ return { kind: 'unanswered', heldMs: heldMs() };
130
+ return handBack(correlationId, state.reason);
131
+ };
132
+ const waitForDecision = async (correlationId, handBackAfterMs) => {
133
+ const handBackAt = handBackAfterMs === null ? null : startedAt + handBackAfterMs;
134
+ const until = handBackAt === null ? deadline : Math.min(deadline, handBackAt);
135
+ let lastFailure = null;
136
+ let consecutiveFailures = 0;
137
+ while (remainingMs(until) > 0) {
138
+ if (aborted())
139
+ return cancelledAfterWithdrawing(correlationId);
140
+ const polled = await questions.waitForAnswer(correlationId, remainingMs(until), request.signal);
141
+ if (aborted() || isAbortFailure(polled))
142
+ return cancelledAfterWithdrawing(correlationId);
143
+ const state = polled.kind === 'reply' ? questionStateOf(polled.value) : null;
144
+ if (isSettled(state))
145
+ return settleState(correlationId, state);
146
+ lastFailure = pollFailureOf(polled, state);
147
+ if (lastFailure !== null && !isRetryable(lastFailure))
148
+ return unavailableAfterWithdrawing(correlationId, lastFailure);
149
+ consecutiveFailures = lastFailure === null ? 0 : consecutiveFailures + 1;
150
+ await clock.sleep(Math.min(pauseAfterPoll(consecutiveFailures), Math.max(0, remainingMs(until))), request.signal);
151
+ }
152
+ if (aborted())
153
+ return cancelledAfterWithdrawing(correlationId);
154
+ return settleAfterHold(correlationId, handBackAt, lastFailure);
155
+ };
156
+ if (aborted())
157
+ return { kind: 'cancelled' };
158
+ const created = await createQuestion();
159
+ const reply = created.kind === 'reply' ? askReplyOf(created.value) : null;
160
+ if (aborted())
161
+ return reply?.kind === 'question' ? cancelledAfterWithdrawing(reply.correlationId) : { kind: 'cancelled' };
162
+ if (created.kind === 'failed')
163
+ return { kind: 'unavailable', failure: created.failure };
164
+ if (reply === null || reply.kind === 'unreadable')
165
+ return { kind: 'unavailable', failure: 'unreadable_reply' };
166
+ if (reply.kind === 'stopped')
167
+ return { kind: 'stopped' };
168
+ if (reply.state.kind === 'pending')
169
+ return waitForDecision(reply.correlationId, reply.handBackAfterMs);
170
+ if (reply.state.kind === 'unreadable')
171
+ return unavailableAfterWithdrawing(reply.correlationId, 'unreadable_reply');
172
+ return settleState(reply.correlationId, reply.state);
173
+ };
@@ -0,0 +1,19 @@
1
+ import { BEFORE_TOOL_CALL_HOOK } from './host-api.js';
2
+ export const REQUESTED_HOOK_TIMEOUT_MS = 300_000;
3
+ export const WITHDRAW_RESERVE_MS = 10_000;
4
+ export const OPERATOR_HOOK_TIMEOUT_MAX_MS = 600_000;
5
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
6
+ const fieldOf = (value, key) => (isRecord(value) ? value[key] : undefined);
7
+ const operatorMilliseconds = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 && value <= OPERATOR_HOOK_TIMEOUT_MAX_MS ? value : null;
8
+ const hookPolicyOf = (hostConfig, pluginId) => fieldOf(fieldOf(fieldOf(fieldOf(hostConfig, 'plugins'), 'entries'), pluginId), 'hooks');
9
+ export const hookBudgetFrom = (hostConfig, pluginId) => {
10
+ const policy = hookPolicyOf(hostConfig, pluginId);
11
+ const perHook = operatorMilliseconds(fieldOf(fieldOf(policy, 'timeouts'), BEFORE_TOOL_CALL_HOOK));
12
+ if (perHook !== null)
13
+ return { timeoutMs: perHook, source: 'operator_hook_timeout' };
14
+ const perPlugin = operatorMilliseconds(fieldOf(policy, 'timeoutMs'));
15
+ if (perPlugin !== null)
16
+ return { timeoutMs: perPlugin, source: 'operator_plugin_timeout' };
17
+ return { timeoutMs: REQUESTED_HOOK_TIMEOUT_MS, source: 'plugin' };
18
+ };
19
+ export const holdMsWithin = (hookTimeoutMs) => Math.max(hookTimeoutMs - WITHDRAW_RESERVE_MS, Math.floor(hookTimeoutMs / 2));
@@ -0,0 +1 @@
1
+ export const BEFORE_TOOL_CALL_HOOK = 'before_tool_call';
@@ -0,0 +1,25 @@
1
+ export const MIN_HOST_VERSION = '2026.11.3';
2
+ const RELEASE_VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?$/;
3
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ const releaseVersionOf = (text) => {
5
+ const match = RELEASE_VERSION_PATTERN.exec(text.trim());
6
+ if (match === null)
7
+ return null;
8
+ const [, major, minor, patch, prerelease] = match;
9
+ return { parts: [Number(major), Number(minor), Number(patch)], prerelease: prerelease !== undefined };
10
+ };
11
+ const isAtLeast = (version, floor) => {
12
+ const differing = version.parts.findIndex((part, index) => part !== floor.parts[index]);
13
+ if (differing === -1)
14
+ return !version.prerelease || floor.prerelease;
15
+ return (version.parts[differing] ?? 0) > (floor.parts[differing] ?? 0);
16
+ };
17
+ const FLOOR = releaseVersionOf(MIN_HOST_VERSION);
18
+ export const hostSupportFrom = (runtime) => {
19
+ const version = isRecord(runtime) && typeof runtime.version === 'string' ? runtime.version : null;
20
+ const parsed = version === null ? null : releaseVersionOf(version);
21
+ if (version === null || parsed === null || FLOOR === null)
22
+ return { kind: 'unknown' };
23
+ return isAtLeast(parsed, FLOOR) ? { kind: 'supported', version } : { kind: 'too_old', version };
24
+ };
25
+ export const handsBackToTheHost = (support) => support.kind === 'supported';
@@ -0,0 +1,32 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ import { registerApprovalGate } from './approval-hook.js';
4
+ import { processConnectionSources, readPusharyConnection } from './connection.js';
5
+ import { createPusharyQuestions } from './pushary-client.js';
6
+ import { PLUGIN_DESCRIPTION, PLUGIN_ID, PLUGIN_NAME } from './settings.js';
7
+ const sleepUnlessAborted = async (ms, signal) => {
8
+ try {
9
+ await delay(ms, undefined, signal === undefined ? undefined : { signal });
10
+ }
11
+ catch {
12
+ return;
13
+ }
14
+ };
15
+ export const systemClock = {
16
+ monotonicMs: () => performance.now(),
17
+ wallMs: () => Date.now(),
18
+ sleep: sleepUnlessAborted,
19
+ };
20
+ export const processGateEnvironment = () => ({
21
+ readConnection: () => readPusharyConnection(processConnectionSources()),
22
+ questionsFor: connection => createPusharyQuestions(connection),
23
+ clock: systemClock,
24
+ newRequestId: randomUUID,
25
+ });
26
+ const pusharyPlugin = {
27
+ id: PLUGIN_ID,
28
+ name: PLUGIN_NAME,
29
+ description: PLUGIN_DESCRIPTION,
30
+ register: api => registerApprovalGate(api, processGateEnvironment()),
31
+ };
32
+ export default pusharyPlugin;
@@ -0,0 +1,43 @@
1
+ // Generated by scripts/generate-editor-redaction.mjs.
2
+ import { join, resolve } from 'node:path';
3
+ export const OPENCLAW_ENVIRONMENT_KEYS = ['OPENCLAW_HOME', 'OPENCLAW_STATE_DIR', 'OPENCLAW_CONFIG_PATH', 'OPENCLAW_PROFILE'];
4
+ const STATE_DIRECTORY_NAME = '.openclaw';
5
+ const PUSHARY_DIRECTORY_NAME = '.pushary';
6
+ export const OWNED_PLUGIN_FOLDER_NAME = 'openclaw-plugin';
7
+ const CONFIG_FILE_NAME = 'openclaw.json';
8
+ const ENVIRONMENT_FILE_NAME = '.env';
9
+ const UNSET_SPELLINGS = new Set(['undefined', 'null']);
10
+ const HOME_PREFIX = /^~(?=$|[\\/])/;
11
+ const setValue = (value) => {
12
+ const trimmed = value?.trim();
13
+ return trimmed && !UNSET_SPELLINGS.has(trimmed) ? trimmed : undefined;
14
+ };
15
+ const expandedFrom = (path, home) => resolve(path.replace(HOME_PREFIX, () => home));
16
+ const homeOf = (environment, osHome) => {
17
+ const configured = setValue(environment.OPENCLAW_HOME);
18
+ if (configured === undefined)
19
+ return resolve(osHome);
20
+ return HOME_PREFIX.test(configured) ? expandedFrom(configured, osHome) : resolve(configured);
21
+ };
22
+ const pathSetting = (value, home) => {
23
+ const configured = value?.trim();
24
+ if (!configured)
25
+ return undefined;
26
+ return HOME_PREFIX.test(configured) ? expandedFrom(configured, home) : resolve(configured);
27
+ };
28
+ export const openClawPathsFrom = (environment, osHome) => {
29
+ const home = homeOf(environment, osHome);
30
+ const stateDirectory = pathSetting(environment.OPENCLAW_STATE_DIR, home) ?? join(home, STATE_DIRECTORY_NAME);
31
+ return {
32
+ home,
33
+ stateDirectory,
34
+ configFile: pathSetting(environment.OPENCLAW_CONFIG_PATH, home) ?? join(stateDirectory, CONFIG_FILE_NAME),
35
+ environmentFile: join(stateDirectory, ENVIRONMENT_FILE_NAME),
36
+ };
37
+ };
38
+ export const openClawDirectoriesToLookIn = (paths) => [...new Set([paths.stateDirectory, paths.configFile, join(paths.home, STATE_DIRECTORY_NAME)])];
39
+ export const openClawEnvironmentOf = (environment) => Object.fromEntries(OPENCLAW_ENVIRONMENT_KEYS.flatMap(key => {
40
+ const value = environment[key];
41
+ return value === undefined ? [] : [[key, value]];
42
+ }));
43
+ export const ownedPluginFolderIn = (osHome) => join(osHome, PUSHARY_DIRECTORY_NAME, OWNED_PLUGIN_FOLDER_NAME);
@@ -0,0 +1,93 @@
1
+ import { homedir } from 'node:os';
2
+ import { basename, dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { openClawEnvironmentOf, openClawPathsFrom, ownedPluginFolderIn } from './openclaw-paths.js';
5
+ import { nodeRealpath, spawnsOutsideTheWorkspace, writesIntoOpenClaw } from './protected-writes.js';
6
+ import { DEFAULT_OPENCLAW_AGENT_ID } from './settings.js';
7
+ const CASE_INSENSITIVE_PLATFORMS = new Set(['darwin', 'win32']);
8
+ const EXTENSIONS_DIRECTORY_NAME = 'extensions';
9
+ const PLUGIN_ROOT_DEPTH = 2;
10
+ const USER_CONFIG_DIRECTORY = '.config';
11
+ const GATEWAY_ENV_FALLBACK_DIRECTORY = 'openclaw';
12
+ const LAUNCHD_LABEL_PREFIX = 'ai.openclaw';
13
+ const SYSTEMD_UNIT_PREFIX = 'openclaw';
14
+ const USER_LAUNCH_AGENTS = ['Library', 'LaunchAgents'];
15
+ const USER_SYSTEMD_UNITS = ['systemd', 'user'];
16
+ const SYSTEM_SERVICE_FILES = [
17
+ { directory: '/Library/LaunchDaemons', namePrefix: LAUNCHD_LABEL_PREFIX },
18
+ { directory: '/etc/systemd/system', namePrefix: SYSTEMD_UNIT_PREFIX },
19
+ ];
20
+ const GATEWAY_WORKING_ENV_FILE = '.env';
21
+ const LAUNCHD_LABEL_VARIABLE = 'OPENCLAW_LAUNCHD_LABEL';
22
+ const SYSTEMD_UNIT_VARIABLE = 'OPENCLAW_SYSTEMD_UNIT';
23
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
24
+ const hostFunction = (namespace, name) => {
25
+ if (!isRecord(namespace))
26
+ return null;
27
+ const candidate = namespace[name];
28
+ return typeof candidate === 'function' ? (...args) => Reflect.apply(candidate, namespace, args) : null;
29
+ };
30
+ const hostPath = (resolver, ...args) => {
31
+ if (resolver === null)
32
+ return null;
33
+ try {
34
+ const value = resolver(...args);
35
+ return typeof value === 'string' && value.trim().length > 0 ? value : null;
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ };
41
+ const runtimeNamespace = (api, name) => (isRecord(api.runtime) ? api.runtime[name] : undefined);
42
+ export const stateDirectoryHoldingPlugin = (pluginFile) => {
43
+ let pluginRoot = pluginFile;
44
+ for (let level = 0; level < PLUGIN_ROOT_DEPTH; level += 1)
45
+ pluginRoot = dirname(pluginRoot);
46
+ const extensions = dirname(pluginRoot);
47
+ return basename(extensions) === EXTENSIONS_DIRECTORY_NAME ? dirname(extensions) : null;
48
+ };
49
+ const presentOnly = (paths) => [...new Set(paths.flatMap(path => (path === null ? [] : [path])))];
50
+ export const openClawStateLocationsFor = (api, environment, osHome, pluginFile, gatewayWorkingDirectory) => {
51
+ const active = openClawPathsFrom(openClawEnvironmentOf(environment), osHome);
52
+ const persistent = openClawPathsFrom(openClawEnvironmentOf({ OPENCLAW_HOME: environment.OPENCLAW_HOME }), osHome);
53
+ const hostState = hostPath(hostFunction(runtimeNamespace(api, 'state'), 'resolveStateDir'), environment);
54
+ const homes = presentOnly([osHome, active.home]);
55
+ return {
56
+ stateDirectories: presentOnly([active.stateDirectory, persistent.stateDirectory, hostState, stateDirectoryHoldingPlugin(pluginFile)]),
57
+ configFiles: presentOnly([active.configFile, persistent.configFile, join(gatewayWorkingDirectory, GATEWAY_WORKING_ENV_FILE)]),
58
+ protectedTrees: presentOnly([
59
+ dirname(ownedPluginFolderIn(osHome)),
60
+ ...homes.map(home => join(home, USER_CONFIG_DIRECTORY, GATEWAY_ENV_FALLBACK_DIRECTORY)),
61
+ ]),
62
+ serviceFiles: serviceFilesFor(homes, environment),
63
+ };
64
+ };
65
+ const overriddenServiceNames = (environment) => presentOnly([environment[LAUNCHD_LABEL_VARIABLE]?.trim() || null, environment[SYSTEMD_UNIT_VARIABLE]?.trim() || null]);
66
+ const serviceFilesFor = (homes, environment) => {
67
+ const directories = [
68
+ ...homes.map(home => join(home, ...USER_LAUNCH_AGENTS)),
69
+ ...homes.map(home => join(home, USER_CONFIG_DIRECTORY, ...USER_SYSTEMD_UNITS)),
70
+ ...SYSTEM_SERVICE_FILES.map(service => service.directory),
71
+ ];
72
+ return [
73
+ ...homes.flatMap(home => [
74
+ { directory: join(home, ...USER_LAUNCH_AGENTS), namePrefix: LAUNCHD_LABEL_PREFIX },
75
+ { directory: join(home, USER_CONFIG_DIRECTORY, ...USER_SYSTEMD_UNITS), namePrefix: SYSTEMD_UNIT_PREFIX },
76
+ ]),
77
+ ...SYSTEM_SERVICE_FILES,
78
+ ...overriddenServiceNames(environment).flatMap(name => directories.map(directory => ({ directory, namePrefix: name }))),
79
+ ];
80
+ };
81
+ const workspaceFrom = (api) => (agentId) => hostPath(hostFunction(runtimeNamespace(api, 'agent'), 'resolveAgentWorkspaceDir'), api.config, agentId ?? DEFAULT_OPENCLAW_AGENT_ID);
82
+ export const openClawWriteGuardFor = (api) => {
83
+ const osHome = homedir();
84
+ const locations = openClawStateLocationsFor(api, process.env, osHome, fileURLToPath(import.meta.url), process.cwd());
85
+ const system = {
86
+ osHome,
87
+ realpath: nodeRealpath,
88
+ caseInsensitive: CASE_INSENSITIVE_PLATFORMS.has(process.platform),
89
+ workspaceFor: workspaceFrom(api),
90
+ otherWorkingDirectories: [process.cwd()],
91
+ };
92
+ return call => writesIntoOpenClaw(locations, system, call) || spawnsOutsideTheWorkspace(locations, system, call);
93
+ };
@@ -0,0 +1,217 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ export const WRITE_TOOL = 'write';
5
+ export const EDIT_TOOL = 'edit';
6
+ export const APPLY_PATCH_TOOL = 'apply_patch';
7
+ export const FILE_WRITING_TOOLS = [WRITE_TOOL, EDIT_TOOL, APPLY_PATCH_TOOL];
8
+ const PATH_PARAMETER = 'path';
9
+ const PATCH_PARAMETER = 'input';
10
+ const PATCH_TARGET_MARKERS = ['*** Add File: ', '*** Delete File: ', '*** Update File: ', '*** Move to: '];
11
+ const PATCH_MARKER_PREFIX = '***';
12
+ const FILE_URL_PREFIX = 'file://';
13
+ const FILE_REFERENCE_PREFIX = '@';
14
+ const HOME_PREFIX = '~';
15
+ const MISSING_PATH_CODES = new Set(['ENOENT', 'ENOTDIR']);
16
+ const WORKSPACE_HOOKS_DIRECTORY = 'hooks';
17
+ const RISKY_RELATIVE_STARTS = ['.pushary', '.config'];
18
+ const errorCodeOf = (error) => typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string' ? error.code : null;
19
+ const canonicalPathOf = (path, system) => {
20
+ const missing = [];
21
+ let current = normalize(path);
22
+ for (;;) {
23
+ try {
24
+ const real = system.realpath(current);
25
+ return missing.length === 0 ? real : join(real, ...missing.reverse());
26
+ }
27
+ catch (error) {
28
+ const code = errorCodeOf(error);
29
+ const parent = dirname(current);
30
+ if (code === null || !MISSING_PATH_CODES.has(code) || parent === current)
31
+ return null;
32
+ missing.push(basename(current));
33
+ current = parent;
34
+ }
35
+ }
36
+ };
37
+ const comparable = (path, system) => {
38
+ const composed = path.normalize('NFC');
39
+ return system.caseInsensitive ? composed.toLowerCase() : composed;
40
+ };
41
+ const spellingsOfLocation = (path, system) => {
42
+ const canonical = canonicalPathOf(path, system);
43
+ const resolved = comparable(resolve(path), system);
44
+ return canonical === null ? [resolved] : [...new Set([comparable(canonical, system), resolved])];
45
+ };
46
+ const spellingsOfAll = (paths, system) => [...new Set(paths.flatMap(path => spellingsOfLocation(path, system)))];
47
+ const isSameOrInside = (path, directory) => path === directory || path.startsWith(directory.endsWith(sep) ? directory : `${directory}${sep}`);
48
+ const isStrictlyInside = (path, directory) => path !== directory && isSameOrInside(path, directory);
49
+ const firstComponentUnder = (path, directory) => {
50
+ if (!isStrictlyInside(path, directory))
51
+ return null;
52
+ return relative(directory, path).split(sep)[0] ?? null;
53
+ };
54
+ const comparablePathsFor = (locations, system, agentId) => {
55
+ const stateDirectories = spellingsOfAll(locations.stateDirectories, system);
56
+ const workspace = system.workspaceFor(agentId);
57
+ const workspaceCanonical = workspace === null ? null : canonicalPathOf(workspace, system);
58
+ return {
59
+ stateDirectories,
60
+ configFiles: spellingsOfAll(locations.configFiles, system),
61
+ protectedTrees: spellingsOfAll(locations.protectedTrees, system),
62
+ serviceFiles: locations.serviceFiles.flatMap(location => spellingsOfLocation(location.directory, system).map(directory => ({ directory, namePrefix: comparable(location.namePrefix, system) }))),
63
+ workspace: workspaceCanonical === null ? null : comparable(workspaceCanonical, system),
64
+ riskyRelativeStarts: new Set([
65
+ ...locations.stateDirectories.map(state => comparable(basename(state), system)),
66
+ ...locations.configFiles.map(file => comparable(basename(file), system)),
67
+ ...RISKY_RELATIVE_STARTS.map(start => comparable(start, system)),
68
+ ]),
69
+ };
70
+ };
71
+ const isServiceFile = (path, services) => services.some(service => firstComponentUnder(path, service.directory)?.startsWith(service.namePrefix) === true);
72
+ const isInWorkspaceHooks = (path, workspace) => workspace !== null && firstComponentUnder(path, workspace) === WORKSPACE_HOOKS_DIRECTORY;
73
+ const isInWorkspaceUnderState = (path, paths) => {
74
+ const { workspace } = paths;
75
+ if (workspace === null || !isSameOrInside(path, workspace))
76
+ return false;
77
+ return paths.stateDirectories.some(state => isStrictlyInside(workspace, state));
78
+ };
79
+ const isProtectedLocation = (path, paths) => {
80
+ if (paths.configFiles.includes(path))
81
+ return true;
82
+ if (paths.protectedTrees.some(tree => isSameOrInside(path, tree)))
83
+ return true;
84
+ if (isServiceFile(path, paths.serviceFiles))
85
+ return true;
86
+ if (isInWorkspaceHooks(path, paths.workspace))
87
+ return true;
88
+ if (!paths.stateDirectories.some(state => isSameOrInside(path, state)))
89
+ return false;
90
+ return !isInWorkspaceUnderState(path, paths);
91
+ };
92
+ const verdictForAbsolute = (path, paths, system) => {
93
+ const canonical = canonicalPathOf(path, system);
94
+ if (canonical === null)
95
+ return 'uncertain';
96
+ return isProtectedLocation(comparable(canonical, system), paths) ? 'protected' : 'clear';
97
+ };
98
+ const firstComponentOf = (relativePath) => normalize(relativePath).split(/[\\/]/).find(part => part.length > 0) ?? '';
99
+ const expandedHome = (path, osHome) => path === HOME_PREFIX || path.startsWith(`${HOME_PREFIX}/`) || (process.platform === 'win32' && path.startsWith(`${HOME_PREFIX}\\`))
100
+ ? join(osHome, path.slice(HOME_PREFIX.length))
101
+ : path;
102
+ const spellingsOf = (raw) => {
103
+ if (!raw.startsWith(FILE_REFERENCE_PREFIX))
104
+ return [raw];
105
+ const referenced = raw.slice(FILE_REFERENCE_PREFIX.length);
106
+ return [referenced.startsWith(FILE_REFERENCE_PREFIX) ? `./${referenced}` : referenced, `./${raw}`];
107
+ };
108
+ const absoluteOrRelative = (spelling, osHome) => {
109
+ if (!spelling.startsWith(FILE_URL_PREFIX))
110
+ return expandedHome(spelling, osHome);
111
+ try {
112
+ return fileURLToPath(spelling);
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ };
118
+ const worstOf = (verdicts) => {
119
+ if (verdicts.includes('protected'))
120
+ return 'protected';
121
+ if (verdicts.length === 0 || verdicts.includes('uncertain'))
122
+ return 'uncertain';
123
+ return 'clear';
124
+ };
125
+ const PARENT_SEGMENT = '..';
126
+ const leadingClimbsOf = (relativePath) => {
127
+ const parts = normalize(relativePath).split(/[\\/]/);
128
+ const firstOther = parts.findIndex(part => part !== PARENT_SEGMENT);
129
+ return firstOther === -1 ? parts.length : firstOther;
130
+ };
131
+ const ancestorsUpTo = (directory, levels) => {
132
+ const ancestors = [directory];
133
+ for (let level = 0; level < levels; level += 1)
134
+ ancestors.push(dirname(ancestors[ancestors.length - 1] ?? directory));
135
+ return ancestors;
136
+ };
137
+ const landingPlacesOf = (relativePath, workspace, others) => {
138
+ const climbs = leadingClimbsOf(relativePath);
139
+ const rest = normalize(relativePath).split(/[\\/]/).slice(climbs).join(sep);
140
+ const fromInsideTheWorkspace = ancestorsUpTo(workspace, climbs).map(base => join(base, rest));
141
+ return [...fromInsideTheWorkspace, resolve(workspace, relativePath), ...others.map(directory => resolve(directory, relativePath))];
142
+ };
143
+ const verdictForSpelling = (spelling, paths, system) => {
144
+ const path = absoluteOrRelative(spelling, system.osHome);
145
+ if (path === null || path.trim().length === 0)
146
+ return 'uncertain';
147
+ if (isAbsolute(path))
148
+ return verdictForAbsolute(path, paths, system);
149
+ if (paths.riskyRelativeStarts.has(comparable(firstComponentOf(path), system)))
150
+ return 'protected';
151
+ if (paths.workspace === null)
152
+ return 'uncertain';
153
+ return worstOf(landingPlacesOf(path, paths.workspace, system.otherWorkingDirectories).map(place => verdictForAbsolute(place, paths, system)));
154
+ };
155
+ const verdictForRawPath = (raw, paths, system) => {
156
+ if (typeof raw !== 'string' || raw.trim().length === 0)
157
+ return 'uncertain';
158
+ return worstOf(spellingsOf(raw.trim()).map(spelling => verdictForSpelling(spelling, paths, system)));
159
+ };
160
+ const patchTargetOf = (line) => {
161
+ const header = line.trimStart();
162
+ if (!header.startsWith(PATCH_MARKER_PREFIX))
163
+ return null;
164
+ const trimmed = header.trimEnd();
165
+ const marker = PATCH_TARGET_MARKERS.find(candidate => trimmed.startsWith(candidate));
166
+ return marker === undefined ? null : trimmed.slice(marker.length);
167
+ };
168
+ export const patchTargetsOf = (patch) => typeof patch === 'string' ? patch.split(/\r?\n/).flatMap(line => {
169
+ const target = patchTargetOf(line);
170
+ return target === null ? [] : [target];
171
+ }) : [];
172
+ const hostResolvedPathsOf = (event) => Array.isArray(event.derivedPaths) ? event.derivedPaths : [];
173
+ const rawTargetsOf = (toolId, event) => {
174
+ if (toolId === APPLY_PATCH_TOOL) {
175
+ const targets = [...patchTargetsOf(event.params[PATCH_PARAMETER]), ...hostResolvedPathsOf(event)];
176
+ return targets.length === 0 ? null : targets;
177
+ }
178
+ return [event.params[PATH_PARAMETER]];
179
+ };
180
+ export const writesIntoOpenClaw = (locations, system, call) => {
181
+ if (!FILE_WRITING_TOOLS.includes(call.toolId))
182
+ return false;
183
+ const targets = rawTargetsOf(call.toolId, call.event);
184
+ if (targets === null)
185
+ return true;
186
+ const paths = comparablePathsFor(locations, system, call.agentId);
187
+ return targets.some(target => verdictForRawPath(target, paths, system) !== 'clear');
188
+ };
189
+ export const SESSIONS_SPAWN_TOOL = 'sessions_spawn';
190
+ export const SPAWN_FOLDER_PARAMETER = 'cwd';
191
+ const SPAWN_SOURCES_IT_CANNOT_SEE = ['projectId', 'projectGitUrl', 'worktree'];
192
+ const namesAFolderItCannotSee = (params) => SPAWN_SOURCES_IT_CANNOT_SEE.some(name => params[name] !== undefined && params[name] !== false);
193
+ const spawnFolderVerdict = (raw, paths, system) => {
194
+ if (typeof raw !== 'string' || raw.trim().length === 0 || paths.workspace === null)
195
+ return 'uncertain';
196
+ const expanded = absoluteOrRelative(raw.trim(), system.osHome);
197
+ if (expanded === null)
198
+ return 'uncertain';
199
+ const canonical = canonicalPathOf(resolve(paths.workspace, expanded), system);
200
+ if (canonical === null)
201
+ return 'uncertain';
202
+ const folder = comparable(canonical, system);
203
+ if (!isSameOrInside(folder, paths.workspace))
204
+ return 'protected';
205
+ return isInWorkspaceHooks(folder, paths.workspace) ? 'protected' : 'clear';
206
+ };
207
+ export const spawnsOutsideTheWorkspace = (locations, system, call) => {
208
+ if (call.toolId !== SESSIONS_SPAWN_TOOL)
209
+ return false;
210
+ const { params } = call.event;
211
+ if (namesAFolderItCannotSee(params))
212
+ return true;
213
+ if (params[SPAWN_FOLDER_PARAMETER] === undefined)
214
+ return false;
215
+ return spawnFolderVerdict(params[SPAWN_FOLDER_PARAMETER], comparablePathsFor(locations, system, call.agentId), system) !== 'clear';
216
+ };
217
+ export const nodeRealpath = (path) => realpathSync(path);