xtrm-tools 2.1.10 → 2.1.11
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.
- package/cli/dist/index.cjs +551 -473
- package/cli/dist/index.cjs.map +1 -1
- package/cli/package.json +1 -1
- package/config/pi/auth.json.template +14 -0
- package/config/pi/extensions/auto-session-name.ts +29 -0
- package/config/pi/extensions/auto-update.ts +71 -0
- package/config/pi/extensions/bg-process.ts +230 -0
- package/config/pi/extensions/compact-header.ts +69 -0
- package/config/pi/extensions/custom-footer.ts +95 -0
- package/config/pi/extensions/custom-provider-qwen-cli/index.ts +363 -0
- package/config/pi/extensions/custom-provider-qwen-cli/package.json +1 -0
- package/config/pi/extensions/git-checkpoint.ts +53 -0
- package/config/pi/extensions/git-guard.ts +45 -0
- package/config/pi/extensions/safe-guard.ts +46 -0
- package/config/pi/extensions/todo.ts +299 -0
- package/config/pi/install-schema.json +41 -0
- package/config/pi/models.json.template +76 -0
- package/config/pi/settings.json.template +15 -0
- package/package.json +1 -1
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Qwen CLI Provider Extension
|
|
3
|
+
*
|
|
4
|
+
* Provides access to Qwen models via OAuth authentication with chat.qwen.ai.
|
|
5
|
+
* Uses device code flow with PKCE for secure browser-based authentication.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* pi -e ./packages/coding-agent/examples/extensions/custom-provider-qwen-cli
|
|
9
|
+
* # Then /login qwen-cli, or set QWEN_CLI_API_KEY=...
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { OAuthCredentials, OAuthLoginCallbacks } from "@mariozechner/pi-ai";
|
|
13
|
+
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
14
|
+
|
|
15
|
+
// =============================================================================
|
|
16
|
+
// Constants
|
|
17
|
+
// =============================================================================
|
|
18
|
+
|
|
19
|
+
const QWEN_DEVICE_CODE_ENDPOINT = "https://chat.qwen.ai/api/v1/oauth2/device/code";
|
|
20
|
+
const QWEN_TOKEN_ENDPOINT = "https://chat.qwen.ai/api/v1/oauth2/token";
|
|
21
|
+
const QWEN_CLIENT_ID = "f0304373b74a44d2b584a3fb70ca9e56";
|
|
22
|
+
const QWEN_SCOPE = "openid profile email model.completion";
|
|
23
|
+
const QWEN_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
|
|
24
|
+
const QWEN_DEFAULT_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1";
|
|
25
|
+
const QWEN_POLL_INTERVAL_MS = 2000;
|
|
26
|
+
|
|
27
|
+
// =============================================================================
|
|
28
|
+
// PKCE Helpers
|
|
29
|
+
// =============================================================================
|
|
30
|
+
|
|
31
|
+
async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {
|
|
32
|
+
const array = new Uint8Array(32);
|
|
33
|
+
crypto.getRandomValues(array);
|
|
34
|
+
const verifier = btoa(String.fromCharCode(...array))
|
|
35
|
+
.replace(/\+/g, "-")
|
|
36
|
+
.replace(/\//g, "_")
|
|
37
|
+
.replace(/=+$/, "");
|
|
38
|
+
|
|
39
|
+
const encoder = new TextEncoder();
|
|
40
|
+
const data = encoder.encode(verifier);
|
|
41
|
+
const hash = await crypto.subtle.digest("SHA-256", data);
|
|
42
|
+
const challenge = btoa(String.fromCharCode(...new Uint8Array(hash)))
|
|
43
|
+
.replace(/\+/g, "-")
|
|
44
|
+
.replace(/\//g, "_")
|
|
45
|
+
.replace(/=+$/, "");
|
|
46
|
+
|
|
47
|
+
return { verifier, challenge };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// =============================================================================
|
|
51
|
+
// OAuth Implementation
|
|
52
|
+
// =============================================================================
|
|
53
|
+
|
|
54
|
+
interface DeviceCodeResponse {
|
|
55
|
+
device_code: string;
|
|
56
|
+
user_code: string;
|
|
57
|
+
verification_uri: string;
|
|
58
|
+
verification_uri_complete?: string;
|
|
59
|
+
expires_in: number;
|
|
60
|
+
interval?: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface TokenResponse {
|
|
64
|
+
access_token: string;
|
|
65
|
+
refresh_token?: string;
|
|
66
|
+
token_type: string;
|
|
67
|
+
expires_in: number;
|
|
68
|
+
resource_url?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
if (signal?.aborted) {
|
|
74
|
+
reject(new Error("Login cancelled"));
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const timeout = setTimeout(resolve, ms);
|
|
78
|
+
signal?.addEventListener(
|
|
79
|
+
"abort",
|
|
80
|
+
() => {
|
|
81
|
+
clearTimeout(timeout);
|
|
82
|
+
reject(new Error("Login cancelled"));
|
|
83
|
+
},
|
|
84
|
+
{ once: true },
|
|
85
|
+
);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function startDeviceFlow(): Promise<{ deviceCode: DeviceCodeResponse; verifier: string }> {
|
|
90
|
+
const { verifier, challenge } = await generatePKCE();
|
|
91
|
+
|
|
92
|
+
const body = new URLSearchParams({
|
|
93
|
+
client_id: QWEN_CLIENT_ID,
|
|
94
|
+
scope: QWEN_SCOPE,
|
|
95
|
+
code_challenge: challenge,
|
|
96
|
+
code_challenge_method: "S256",
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const headers: Record<string, string> = {
|
|
100
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
101
|
+
Accept: "application/json",
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const requestId = globalThis.crypto?.randomUUID?.();
|
|
105
|
+
if (requestId) headers["x-request-id"] = requestId;
|
|
106
|
+
|
|
107
|
+
const response = await fetch(QWEN_DEVICE_CODE_ENDPOINT, {
|
|
108
|
+
method: "POST",
|
|
109
|
+
headers,
|
|
110
|
+
body: body.toString(),
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
if (!response.ok) {
|
|
114
|
+
const text = await response.text();
|
|
115
|
+
throw new Error(`Device code request failed: ${response.status} ${text}`);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const data = (await response.json()) as DeviceCodeResponse;
|
|
119
|
+
if (!data.device_code || !data.user_code || !data.verification_uri) {
|
|
120
|
+
throw new Error("Invalid device code response: missing required fields");
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return { deviceCode: data, verifier };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function pollForToken(
|
|
127
|
+
deviceCode: string,
|
|
128
|
+
verifier: string,
|
|
129
|
+
intervalSeconds: number | undefined,
|
|
130
|
+
expiresIn: number,
|
|
131
|
+
signal?: AbortSignal,
|
|
132
|
+
): Promise<TokenResponse> {
|
|
133
|
+
const deadline = Date.now() + expiresIn * 1000;
|
|
134
|
+
const resolvedIntervalSeconds =
|
|
135
|
+
typeof intervalSeconds === "number" &&
|
|
136
|
+
Number.isFinite(intervalSeconds) &&
|
|
137
|
+
intervalSeconds > 0
|
|
138
|
+
? intervalSeconds
|
|
139
|
+
: QWEN_POLL_INTERVAL_MS / 1000;
|
|
140
|
+
let intervalMs = Math.max(1000, Math.floor(resolvedIntervalSeconds * 1000));
|
|
141
|
+
|
|
142
|
+
const handleTokenError = async (
|
|
143
|
+
error: string,
|
|
144
|
+
description?: string,
|
|
145
|
+
): Promise<boolean> => {
|
|
146
|
+
switch (error) {
|
|
147
|
+
case "authorization_pending":
|
|
148
|
+
await abortableSleep(intervalMs, signal);
|
|
149
|
+
return true;
|
|
150
|
+
case "slow_down":
|
|
151
|
+
intervalMs = Math.min(intervalMs + 5000, 10000);
|
|
152
|
+
await abortableSleep(intervalMs, signal);
|
|
153
|
+
return true;
|
|
154
|
+
case "expired_token":
|
|
155
|
+
throw new Error("Device code expired. Please restart authentication.");
|
|
156
|
+
case "access_denied":
|
|
157
|
+
throw new Error("Authorization denied by user.");
|
|
158
|
+
default:
|
|
159
|
+
throw new Error(`Token request failed: ${error} - ${description || ""}`);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
while (Date.now() < deadline) {
|
|
164
|
+
if (signal?.aborted) {
|
|
165
|
+
throw new Error("Login cancelled");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const body = new URLSearchParams({
|
|
169
|
+
grant_type: QWEN_GRANT_TYPE,
|
|
170
|
+
client_id: QWEN_CLIENT_ID,
|
|
171
|
+
device_code: deviceCode,
|
|
172
|
+
code_verifier: verifier,
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
const response = await fetch(QWEN_TOKEN_ENDPOINT, {
|
|
176
|
+
method: "POST",
|
|
177
|
+
headers: {
|
|
178
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
179
|
+
Accept: "application/json",
|
|
180
|
+
},
|
|
181
|
+
body: body.toString(),
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
const responseText = await response.text();
|
|
185
|
+
let data:
|
|
186
|
+
| (TokenResponse & { error?: string; error_description?: string })
|
|
187
|
+
| null = null;
|
|
188
|
+
|
|
189
|
+
if (responseText) {
|
|
190
|
+
try {
|
|
191
|
+
data = JSON.parse(responseText) as TokenResponse & {
|
|
192
|
+
error?: string;
|
|
193
|
+
error_description?: string;
|
|
194
|
+
};
|
|
195
|
+
} catch {
|
|
196
|
+
data = null;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const error = data?.error;
|
|
201
|
+
const errorDescription = data?.error_description;
|
|
202
|
+
|
|
203
|
+
if (!response.ok) {
|
|
204
|
+
if (error && (await handleTokenError(error, errorDescription))) {
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
throw new Error(
|
|
208
|
+
`Token request failed: ${response.status} ${response.statusText}. Response: ${responseText}`,
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (data?.access_token) {
|
|
213
|
+
return data;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (error && (await handleTokenError(error, errorDescription))) {
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
throw new Error("Token request failed: missing access token in response");
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
throw new Error("Authentication timed out. Please try again.");
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function loginQwen(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
|
|
227
|
+
const { deviceCode, verifier } = await startDeviceFlow();
|
|
228
|
+
|
|
229
|
+
// Show verification URL and user code to user
|
|
230
|
+
const authUrl =
|
|
231
|
+
deviceCode.verification_uri_complete || deviceCode.verification_uri;
|
|
232
|
+
const instructions = deviceCode.verification_uri_complete
|
|
233
|
+
? undefined // Code is already embedded in the URL
|
|
234
|
+
: `Enter code: ${deviceCode.user_code}`;
|
|
235
|
+
|
|
236
|
+
callbacks.onAuth({ url: authUrl, instructions });
|
|
237
|
+
|
|
238
|
+
// Poll for token
|
|
239
|
+
const tokenResponse = await pollForToken(
|
|
240
|
+
deviceCode.device_code,
|
|
241
|
+
verifier,
|
|
242
|
+
deviceCode.interval,
|
|
243
|
+
deviceCode.expires_in,
|
|
244
|
+
callbacks.signal,
|
|
245
|
+
);
|
|
246
|
+
|
|
247
|
+
// Calculate expiry with 5-minute buffer
|
|
248
|
+
const expiresAt = Date.now() + tokenResponse.expires_in * 1000 - 5 * 60 * 1000;
|
|
249
|
+
|
|
250
|
+
return {
|
|
251
|
+
refresh: tokenResponse.refresh_token || "",
|
|
252
|
+
access: tokenResponse.access_token,
|
|
253
|
+
expires: expiresAt,
|
|
254
|
+
// Store resource_url for API base URL if provided
|
|
255
|
+
enterpriseUrl: tokenResponse.resource_url,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function refreshQwenToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
|
|
260
|
+
const body = new URLSearchParams({
|
|
261
|
+
grant_type: "refresh_token",
|
|
262
|
+
refresh_token: credentials.refresh,
|
|
263
|
+
client_id: QWEN_CLIENT_ID,
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
const response = await fetch(QWEN_TOKEN_ENDPOINT, {
|
|
267
|
+
method: "POST",
|
|
268
|
+
headers: {
|
|
269
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
270
|
+
Accept: "application/json",
|
|
271
|
+
},
|
|
272
|
+
body: body.toString(),
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
if (!response.ok) {
|
|
276
|
+
const text = await response.text();
|
|
277
|
+
throw new Error(`Token refresh failed: ${response.status} ${text}`);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const data = (await response.json()) as TokenResponse;
|
|
281
|
+
if (!data.access_token) {
|
|
282
|
+
throw new Error("Token refresh failed: no access token in response");
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const expiresAt = Date.now() + data.expires_in * 1000 - 5 * 60 * 1000;
|
|
286
|
+
|
|
287
|
+
return {
|
|
288
|
+
refresh: data.refresh_token || credentials.refresh,
|
|
289
|
+
access: data.access_token,
|
|
290
|
+
expires: expiresAt,
|
|
291
|
+
enterpriseUrl: data.resource_url ?? credentials.enterpriseUrl,
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function getQwenBaseUrl(resourceUrl?: string): string {
|
|
296
|
+
if (!resourceUrl) {
|
|
297
|
+
return QWEN_DEFAULT_BASE_URL;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
let url = resourceUrl.startsWith("http") ? resourceUrl : `https://${resourceUrl}`;
|
|
301
|
+
if (!url.endsWith("/v1")) {
|
|
302
|
+
url = `${url}/v1`;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return url;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// =============================================================================
|
|
309
|
+
// Extension Entry Point
|
|
310
|
+
// =============================================================================
|
|
311
|
+
|
|
312
|
+
export default function (pi: ExtensionAPI) {
|
|
313
|
+
pi.registerProvider("qwen-cli", {
|
|
314
|
+
baseUrl: QWEN_DEFAULT_BASE_URL,
|
|
315
|
+
apiKey: "QWEN_CLI_API_KEY",
|
|
316
|
+
api: "openai-completions",
|
|
317
|
+
models: [
|
|
318
|
+
{
|
|
319
|
+
id: "qwen3-coder-plus",
|
|
320
|
+
name: "Qwen3 Coder Plus",
|
|
321
|
+
reasoning: false,
|
|
322
|
+
input: ["text"],
|
|
323
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
324
|
+
contextWindow: 1000000,
|
|
325
|
+
maxTokens: 65536,
|
|
326
|
+
},
|
|
327
|
+
{
|
|
328
|
+
id: "qwen3-coder-flash",
|
|
329
|
+
name: "Qwen3 Coder Flash",
|
|
330
|
+
reasoning: false,
|
|
331
|
+
input: ["text"],
|
|
332
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
333
|
+
contextWindow: 1000000,
|
|
334
|
+
maxTokens: 65536,
|
|
335
|
+
},
|
|
336
|
+
{
|
|
337
|
+
id: "vision-model",
|
|
338
|
+
name: "Qwen3 VL Plus",
|
|
339
|
+
reasoning: true,
|
|
340
|
+
input: ["text", "image"],
|
|
341
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
342
|
+
contextWindow: 262144,
|
|
343
|
+
maxTokens: 32768,
|
|
344
|
+
compat: {
|
|
345
|
+
supportsDeveloperRole: false,
|
|
346
|
+
thinkingFormat: "qwen",
|
|
347
|
+
},
|
|
348
|
+
},
|
|
349
|
+
],
|
|
350
|
+
oauth: {
|
|
351
|
+
name: "Qwen CLI",
|
|
352
|
+
login: loginQwen,
|
|
353
|
+
refreshToken: refreshQwenToken,
|
|
354
|
+
getApiKey: (cred) => cred.access,
|
|
355
|
+
modifyModels: (models, cred) => {
|
|
356
|
+
const baseUrl = getQwenBaseUrl(cred.enterpriseUrl as string | undefined);
|
|
357
|
+
return models.map((m) =>
|
|
358
|
+
m.provider === "qwen-cli" ? { ...m, baseUrl } : m,
|
|
359
|
+
);
|
|
360
|
+
},
|
|
361
|
+
},
|
|
362
|
+
});
|
|
363
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "name": "pi-extension-custom-provider-qwen-cli", "private": true, "version": "1.7.1", "type": "module", "scripts": { "clean": "echo 'nothing to clean'", "build": "echo 'nothing to build'", "check": "echo 'nothing to check'" }, "pi": { "extensions": [ "./index.ts" ] } }
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git Checkpoint Extension
|
|
3
|
+
*
|
|
4
|
+
* Creates git stash checkpoints at each turn so /fork can restore code state.
|
|
5
|
+
* When forking, offers to restore code to that point in history.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
9
|
+
|
|
10
|
+
export default function (pi: ExtensionAPI) {
|
|
11
|
+
const checkpoints = new Map<string, string>();
|
|
12
|
+
let currentEntryId: string | undefined;
|
|
13
|
+
|
|
14
|
+
// Track the current entry ID when user messages are saved
|
|
15
|
+
pi.on("tool_result", async (_event, ctx) => {
|
|
16
|
+
const leaf = ctx.sessionManager.getLeafEntry();
|
|
17
|
+
if (leaf) currentEntryId = leaf.id;
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
pi.on("turn_start", async () => {
|
|
21
|
+
// Create a git stash entry before LLM makes changes
|
|
22
|
+
const { stdout } = await pi.exec("git", ["stash", "create"]);
|
|
23
|
+
const ref = stdout.trim();
|
|
24
|
+
if (ref && currentEntryId) {
|
|
25
|
+
checkpoints.set(currentEntryId, ref);
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
pi.on("session_before_fork", async (event, ctx) => {
|
|
30
|
+
const ref = checkpoints.get(event.entryId);
|
|
31
|
+
if (!ref) return;
|
|
32
|
+
|
|
33
|
+
if (!ctx.hasUI) {
|
|
34
|
+
// In non-interactive mode, don't restore automatically
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const choice = await ctx.ui.select("Restore code state?", [
|
|
39
|
+
"Yes, restore code to that point",
|
|
40
|
+
"No, keep current code",
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
if (choice?.startsWith("Yes")) {
|
|
44
|
+
await pi.exec("git", ["stash", "apply", ref]);
|
|
45
|
+
ctx.ui.notify("Code restored to checkpoint", "info");
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
pi.on("agent_end", async () => {
|
|
50
|
+
// Clear checkpoints after agent completes
|
|
51
|
+
checkpoints.clear();
|
|
52
|
+
});
|
|
53
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* oh-pi Git Checkpoint Extension
|
|
3
|
+
*
|
|
4
|
+
* Auto-stash before each turn, notify on agent completion.
|
|
5
|
+
* Combines git-checkpoint + notify + dirty-repo-guard.
|
|
6
|
+
*/
|
|
7
|
+
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
8
|
+
|
|
9
|
+
function terminalNotify(title: string, body: string): void {
|
|
10
|
+
if (process.env.KITTY_WINDOW_ID) {
|
|
11
|
+
process.stdout.write(`\x1b]99;i=1:d=0;${title}\x1b\\`);
|
|
12
|
+
process.stdout.write(`\x1b]99;i=1:p=body;${body}\x1b\\`);
|
|
13
|
+
} else {
|
|
14
|
+
process.stdout.write(`\x1b]777;notify;${title};${body}\x07`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export default function (pi: ExtensionAPI) {
|
|
19
|
+
let turnCount = 0;
|
|
20
|
+
|
|
21
|
+
// Warn on dirty repo at session start
|
|
22
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
23
|
+
try {
|
|
24
|
+
const { stdout } = await pi.exec("git", ["status", "--porcelain"]);
|
|
25
|
+
if (stdout.trim() && ctx.hasUI) {
|
|
26
|
+
const lines = stdout.trim().split("\n").length;
|
|
27
|
+
ctx.ui.notify(`⚠️ Dirty repo: ${lines} uncommitted change(s)`, "warning");
|
|
28
|
+
}
|
|
29
|
+
} catch { /* not a git repo, ignore */ }
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// Stash checkpoint before each turn
|
|
33
|
+
pi.on("turn_start", async () => {
|
|
34
|
+
turnCount++;
|
|
35
|
+
try {
|
|
36
|
+
await pi.exec("git", ["stash", "create", "-m", `oh-pi-turn-${turnCount}`]);
|
|
37
|
+
} catch { /* not a git repo */ }
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// Notify when agent is done
|
|
41
|
+
pi.on("agent_end", async () => {
|
|
42
|
+
terminalNotify("oh-pi", `Done after ${turnCount} turn(s). Ready for input.`);
|
|
43
|
+
turnCount = 0;
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* oh-pi Safe Guard Extension
|
|
3
|
+
*
|
|
4
|
+
* Combines destructive command confirmation + protected paths in one extension.
|
|
5
|
+
*/
|
|
6
|
+
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
7
|
+
|
|
8
|
+
export const DANGEROUS_PATTERNS = [
|
|
9
|
+
/\brm\s+(-[a-zA-Z]*f[a-zA-Z]*\s+|.*-rf\b|.*--force\b)/,
|
|
10
|
+
/\bsudo\s+rm\b/,
|
|
11
|
+
/\b(DROP|TRUNCATE|DELETE\s+FROM)\b/i,
|
|
12
|
+
/\bchmod\s+777\b/,
|
|
13
|
+
/\bmkfs\b/,
|
|
14
|
+
/\bdd\s+if=/,
|
|
15
|
+
/>\s*\/dev\/sd[a-z]/,
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
export const PROTECTED_PATHS = [".env", ".git/", "node_modules/", ".pi/", "id_rsa", ".ssh/"];
|
|
19
|
+
|
|
20
|
+
export default function (pi: ExtensionAPI) {
|
|
21
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
22
|
+
// Check bash commands for dangerous patterns
|
|
23
|
+
if (event.toolName === "bash") {
|
|
24
|
+
const cmd = (event.input as { command?: string }).command ?? "";
|
|
25
|
+
const match = DANGEROUS_PATTERNS.find((p) => p.test(cmd));
|
|
26
|
+
if (match && ctx.hasUI) {
|
|
27
|
+
const ok = await ctx.ui.confirm("⚠️ Dangerous Command", `Execute: ${cmd}?`);
|
|
28
|
+
if (!ok) return { block: true, reason: "Blocked by user" };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Check write/edit for protected paths
|
|
33
|
+
if (event.toolName === "write" || event.toolName === "edit") {
|
|
34
|
+
const path = (event.input as { path?: string }).path ?? "";
|
|
35
|
+
const hit = PROTECTED_PATHS.find((p) => path.includes(p));
|
|
36
|
+
if (hit) {
|
|
37
|
+
if (ctx.hasUI) {
|
|
38
|
+
const ok = await ctx.ui.confirm("🛡️ Protected Path", `Allow write to ${path}?`);
|
|
39
|
+
if (!ok) return { block: true, reason: `Protected path: ${hit}` };
|
|
40
|
+
} else {
|
|
41
|
+
return { block: true, reason: `Protected path: ${hit}` };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
}
|