pi-matt-pocock 0.1.0 → 0.2.0

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.
@@ -0,0 +1,403 @@
1
+ import { spawn } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+
6
+ export interface PiMattPocockConfig {
7
+ useNativeDialog: boolean;
8
+ }
9
+
10
+ export function defaultConfigFile(): string {
11
+ return path.join(os.homedir(), ".pi", "agent", "pi-matt-pocock.json");
12
+ }
13
+
14
+ /**
15
+ * Load package configuration from ~/.pi/agent/pi-matt-pocock.json
16
+ * Defaults to useNativeDialog: false if the file is absent or invalid.
17
+ */
18
+ export function loadConfig(configPath?: string): PiMattPocockConfig {
19
+ const targetPath = configPath ?? process.env.PI_MATT_POCOCK_CONFIG_FILE ?? defaultConfigFile();
20
+ try {
21
+ if (!fs.existsSync(targetPath)) {
22
+ return { useNativeDialog: false };
23
+ }
24
+ const raw = fs.readFileSync(targetPath, "utf8");
25
+ const parsed = JSON.parse(raw);
26
+ return {
27
+ useNativeDialog: Boolean(parsed?.useNativeDialog),
28
+ };
29
+ } catch {
30
+ return { useNativeDialog: false };
31
+ }
32
+ }
33
+
34
+ export interface NativeDialogEnvironment {
35
+ platform?: string;
36
+ env?: NodeJS.ProcessEnv;
37
+ }
38
+
39
+ /**
40
+ * Check whether the current process is running in a local macOS GUI session
41
+ * where native system dialogs can safely be presented.
42
+ *
43
+ * Explicitly rejects:
44
+ * - Non-macOS platforms (Linux, Windows, etc.)
45
+ * - Remote SSH sessions (SSH_CONNECTION, SSH_CLIENT, SSH_TTY)
46
+ * - CI / automated headless environments (CI=true)
47
+ * - Explicit opt-out (PI_NO_NATIVE_DIALOG=1)
48
+ */
49
+ export function isNativeDialogSupported(options: NativeDialogEnvironment = {}): boolean {
50
+ const platform = options.platform ?? process.platform;
51
+ if (platform !== "darwin") return false;
52
+
53
+ const env = options.env ?? process.env;
54
+
55
+ if (Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.SSH_TTY)) {
56
+ return false;
57
+ }
58
+
59
+ if (env.CI && env.CI !== "false" && env.CI !== "0") {
60
+ return false;
61
+ }
62
+
63
+ if (env.PI_NO_NATIVE_DIALOG === "1" || env.PI_NO_NATIVE_DIALOG === "true") {
64
+ return false;
65
+ }
66
+
67
+ return true;
68
+ }
69
+
70
+ export interface MacosChooseFromListOptions {
71
+ title?: string;
72
+ prompt: string;
73
+ items: string[];
74
+ defaultItem?: string;
75
+ okButtonName?: string;
76
+ cancelButtonName?: string;
77
+ timeoutSeconds?: number;
78
+ }
79
+
80
+ export interface MacosChooseFromListResult {
81
+ action: "selected" | "cancelled" | "timed_out";
82
+ item?: string;
83
+ }
84
+
85
+ /**
86
+ * Present a native macOS list selection dialog using chooseFromList in JXA.
87
+ * Runs in the current process context without TCC permission prompts.
88
+ */
89
+ export async function macosChooseFromList(
90
+ options: MacosChooseFromListOptions,
91
+ envOptions: NativeDialogEnvironment = {},
92
+ ): Promise<MacosChooseFromListResult> {
93
+ if (!isNativeDialogSupported(envOptions)) {
94
+ throw new Error("Native macOS dialog is not supported in this environment (non-macOS or SSH session).");
95
+ }
96
+
97
+ const items = options.items;
98
+ if (items.length === 0) {
99
+ return { action: "cancelled" };
100
+ }
101
+
102
+ const defaultItem = options.defaultItem && items.includes(options.defaultItem)
103
+ ? options.defaultItem
104
+ : items[0];
105
+
106
+ const jxaScript = `
107
+ const app = Application.currentApplication();
108
+ app.includeStandardAdditions = true;
109
+ app.activate();
110
+ const res = app.chooseFromList(${JSON.stringify(items)}, {
111
+ withPrompt: ${JSON.stringify(options.prompt)},
112
+ ${options.title ? `withTitle: ${JSON.stringify(options.title)},` : ""}
113
+ ${options.okButtonName ? `okButtonName: ${JSON.stringify(options.okButtonName)},` : ""}
114
+ ${options.cancelButtonName ? `cancelButtonName: ${JSON.stringify(options.cancelButtonName)},` : ""}
115
+ defaultItems: [${JSON.stringify(defaultItem)}],
116
+ multipleSelectionsAllowed: false,
117
+ emptySelectionAllowed: false
118
+ });
119
+ JSON.stringify(res);
120
+ `;
121
+
122
+ return new Promise<MacosChooseFromListResult>((resolve) => {
123
+ const proc = spawn("osascript", ["-l", "JavaScript", "-e", jxaScript], {
124
+ stdio: ["ignore", "pipe", "pipe"],
125
+ });
126
+
127
+ let stdout = "";
128
+ let stderr = "";
129
+ let isTimedOut = false;
130
+ let timer: NodeJS.Timeout | undefined;
131
+ let killEscalation: NodeJS.Timeout | undefined;
132
+
133
+ if (options.timeoutSeconds !== undefined && options.timeoutSeconds > 0) {
134
+ timer = setTimeout(() => {
135
+ isTimedOut = true;
136
+ try {
137
+ proc.kill("SIGTERM");
138
+ } catch {
139
+ // ignore kill errors
140
+ }
141
+ killEscalation = setTimeout(() => {
142
+ try {
143
+ proc.kill("SIGKILL");
144
+ } catch {
145
+ // ignore kill errors
146
+ }
147
+ }, 500);
148
+ }, options.timeoutSeconds * 1000);
149
+ }
150
+
151
+ proc.stdout.on("data", (chunk: Buffer) => {
152
+ stdout += chunk.toString("utf8");
153
+ });
154
+ proc.stderr.on("data", (chunk: Buffer) => {
155
+ stderr += chunk.toString("utf8");
156
+ });
157
+
158
+ proc.on("error", () => {
159
+ if (timer) clearTimeout(timer);
160
+ if (killEscalation) clearTimeout(killEscalation);
161
+ resolve({ action: "cancelled" });
162
+ });
163
+
164
+ proc.on("close", (code) => {
165
+ if (timer) clearTimeout(timer);
166
+ if (killEscalation) clearTimeout(killEscalation);
167
+
168
+ if (isTimedOut) {
169
+ return resolve({ action: "timed_out" });
170
+ }
171
+
172
+ if (code === 0 && stdout.trim()) {
173
+ try {
174
+ const parsed = JSON.parse(stdout.trim());
175
+ if (Array.isArray(parsed) && parsed.length > 0 && typeof parsed[0] === "string") {
176
+ return resolve({ action: "selected", item: parsed[0] });
177
+ }
178
+ if (parsed === false) {
179
+ return resolve({ action: "cancelled" });
180
+ }
181
+ } catch {
182
+ // fallback
183
+ }
184
+ }
185
+
186
+ if (stderr.includes("-128") || stderr.includes("User canceled")) {
187
+ return resolve({ action: "cancelled" });
188
+ }
189
+
190
+ resolve({ action: "cancelled" });
191
+ });
192
+ });
193
+ }
194
+
195
+ export interface MacosInputDialogOptions {
196
+ title?: string;
197
+ prompt: string;
198
+ defaultAnswer?: string;
199
+ buttons?: string[];
200
+ defaultButton?: string;
201
+ cancelButton?: string;
202
+ timeoutSeconds?: number;
203
+ }
204
+
205
+ export interface MacosInputDialogResult {
206
+ action: "confirmed" | "cancelled" | "timed_out";
207
+ text?: string;
208
+ }
209
+
210
+ /**
211
+ * Present a native macOS text input dialog using displayDialog with defaultAnswer in JXA.
212
+ */
213
+ export async function macosInputDialog(
214
+ options: MacosInputDialogOptions,
215
+ envOptions: NativeDialogEnvironment = {},
216
+ ): Promise<MacosInputDialogResult> {
217
+ if (!isNativeDialogSupported(envOptions)) {
218
+ throw new Error("Native macOS dialog is not supported in this environment (non-macOS or SSH session).");
219
+ }
220
+
221
+ const buttons = options.buttons && options.buttons.length > 0 ? options.buttons : ["取消", "确定"];
222
+ if (buttons.length > 3) {
223
+ throw new Error(`macOS displayDialog supports at most 3 buttons, got ${buttons.length}`);
224
+ }
225
+
226
+ const defaultButton = options.defaultButton ?? buttons[buttons.length - 1];
227
+ const cancelButton = options.cancelButton ?? (buttons.includes("取消") ? "取消" : (buttons.includes("Cancel") ? "Cancel" : undefined));
228
+ const timeoutSeconds = options.timeoutSeconds && options.timeoutSeconds > 0 ? Math.floor(options.timeoutSeconds) : undefined;
229
+
230
+ const jxaScript = `
231
+ const app = Application.currentApplication();
232
+ app.includeStandardAdditions = true;
233
+ app.activate();
234
+ const opts = {
235
+ buttons: ${JSON.stringify(buttons)},
236
+ defaultButton: ${JSON.stringify(defaultButton)},
237
+ ${cancelButton ? `cancelButton: ${JSON.stringify(cancelButton)},` : ""}
238
+ ${options.title ? `withTitle: ${JSON.stringify(options.title)},` : ""}
239
+ defaultAnswer: ${JSON.stringify(options.defaultAnswer ?? "")},
240
+ ${timeoutSeconds !== undefined ? `givingUpAfter: ${timeoutSeconds},` : ""}
241
+ };
242
+ const res = app.displayDialog(${JSON.stringify(options.prompt)}, opts);
243
+ JSON.stringify(res);
244
+ `;
245
+
246
+ return new Promise<MacosInputDialogResult>((resolve) => {
247
+ const proc = spawn("osascript", ["-l", "JavaScript", "-e", jxaScript], {
248
+ stdio: ["ignore", "pipe", "pipe"],
249
+ });
250
+
251
+ let stdout = "";
252
+ let stderr = "";
253
+
254
+ proc.stdout.on("data", (chunk: Buffer) => {
255
+ stdout += chunk.toString("utf8");
256
+ });
257
+ proc.stderr.on("data", (chunk: Buffer) => {
258
+ stderr += chunk.toString("utf8");
259
+ });
260
+
261
+ proc.on("error", () => {
262
+ resolve({ action: "cancelled" });
263
+ });
264
+
265
+ proc.on("close", (code) => {
266
+ if (code === 0 && stdout.trim()) {
267
+ try {
268
+ const parsed = JSON.parse(stdout.trim()) as {
269
+ buttonReturned?: string;
270
+ textReturned?: string;
271
+ gaveUp?: boolean;
272
+ };
273
+ if (parsed.gaveUp) {
274
+ return resolve({
275
+ action: "timed_out",
276
+ text: parsed.textReturned,
277
+ });
278
+ }
279
+ const isCancel = cancelButton && parsed.buttonReturned === cancelButton;
280
+ return resolve({
281
+ action: isCancel ? "cancelled" : "confirmed",
282
+ text: parsed.textReturned,
283
+ });
284
+ } catch {
285
+ // fallback
286
+ }
287
+ }
288
+
289
+ if (stderr.includes("-128") || stderr.includes("User canceled")) {
290
+ return resolve({ action: "cancelled" });
291
+ }
292
+
293
+ resolve({ action: "cancelled" });
294
+ });
295
+ });
296
+ }
297
+
298
+ export interface MacosPromptOptions {
299
+ message: string;
300
+ defaultAnswer?: string;
301
+ buttons?: string[];
302
+ defaultButton?: string;
303
+ cancelButton?: string;
304
+ timeoutSeconds?: number;
305
+ }
306
+
307
+ export interface MacosPromptResult {
308
+ action: "confirmed" | "cancelled" | "timed_out";
309
+ button?: string;
310
+ text?: string;
311
+ gaveUp: boolean;
312
+ }
313
+
314
+ /**
315
+ * General prompt using displayDialog (backwards-compatible).
316
+ */
317
+ export async function macosPrompt(
318
+ options: MacosPromptOptions,
319
+ envOptions: NativeDialogEnvironment = {},
320
+ ): Promise<MacosPromptResult> {
321
+ if (!isNativeDialogSupported(envOptions)) {
322
+ throw new Error("Native macOS dialog is not supported in this environment (non-macOS or SSH session).");
323
+ }
324
+
325
+ const buttons = options.buttons && options.buttons.length > 0 ? options.buttons : ["Cancel", "OK"];
326
+ if (buttons.length > 3) {
327
+ throw new Error(`macOS displayDialog supports at most 3 buttons, got ${buttons.length}`);
328
+ }
329
+
330
+ const defaultButton = options.defaultButton ?? buttons[buttons.length - 1];
331
+ const cancelButton = options.cancelButton ?? (buttons.includes("Cancel") ? "Cancel" : undefined);
332
+ const timeoutSeconds = options.timeoutSeconds && options.timeoutSeconds > 0 ? Math.floor(options.timeoutSeconds) : undefined;
333
+
334
+ const jxaScript = `
335
+ const app = Application.currentApplication();
336
+ app.includeStandardAdditions = true;
337
+ app.activate();
338
+ const opts = {
339
+ buttons: ${JSON.stringify(buttons)},
340
+ defaultButton: ${JSON.stringify(defaultButton)},
341
+ ${cancelButton ? `cancelButton: ${JSON.stringify(cancelButton)},` : ""}
342
+ ${options.defaultAnswer !== undefined ? `defaultAnswer: ${JSON.stringify(options.defaultAnswer)},` : ""}
343
+ ${timeoutSeconds !== undefined ? `givingUpAfter: ${timeoutSeconds},` : ""}
344
+ };
345
+ const res = app.displayDialog(${JSON.stringify(options.message)}, opts);
346
+ JSON.stringify(res);
347
+ `;
348
+
349
+ return new Promise<MacosPromptResult>((resolve) => {
350
+ const proc = spawn("osascript", ["-l", "JavaScript", "-e", jxaScript], {
351
+ stdio: ["ignore", "pipe", "pipe"],
352
+ });
353
+
354
+ let stdout = "";
355
+ let stderr = "";
356
+
357
+ proc.stdout.on("data", (chunk: Buffer) => {
358
+ stdout += chunk.toString("utf8");
359
+ });
360
+ proc.stderr.on("data", (chunk: Buffer) => {
361
+ stderr += chunk.toString("utf8");
362
+ });
363
+
364
+ proc.on("error", () => {
365
+ resolve({ action: "cancelled", gaveUp: false });
366
+ });
367
+
368
+ proc.on("close", (code) => {
369
+ if (code === 0 && stdout.trim()) {
370
+ try {
371
+ const parsed = JSON.parse(stdout.trim()) as {
372
+ buttonReturned?: string;
373
+ textReturned?: string;
374
+ gaveUp?: boolean;
375
+ };
376
+ if (parsed.gaveUp) {
377
+ return resolve({
378
+ action: "timed_out",
379
+ button: parsed.buttonReturned || undefined,
380
+ text: parsed.textReturned,
381
+ gaveUp: true,
382
+ });
383
+ }
384
+ const isCancel = cancelButton && parsed.buttonReturned === cancelButton;
385
+ return resolve({
386
+ action: isCancel ? "cancelled" : "confirmed",
387
+ button: parsed.buttonReturned,
388
+ text: parsed.textReturned,
389
+ gaveUp: false,
390
+ });
391
+ } catch {
392
+ // JSON parsing failure fallback
393
+ }
394
+ }
395
+
396
+ if (stderr.includes("-128") || stderr.includes("User canceled")) {
397
+ return resolve({ action: "cancelled", gaveUp: false });
398
+ }
399
+
400
+ resolve({ action: "cancelled", gaveUp: false });
401
+ });
402
+ });
403
+ }
@@ -0,0 +1,127 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import {
4
+ findProcedure,
5
+ findProcedureByFile,
6
+ normalizeProcedureId,
7
+ type ProcedureDefinition,
8
+ } from "./catalog.ts";
9
+
10
+ export const MAX_PROCEDURE_BUNDLE_BYTES = 64 * 1024;
11
+
12
+ export interface ResolvedProcedureBundle {
13
+ root: string;
14
+ loaded: string[];
15
+ availableReferences: string[];
16
+ content: string;
17
+ byteLength: number;
18
+ }
19
+
20
+ const procedureDirectory = fileURLToPath(new URL("../procedures/", import.meta.url));
21
+
22
+ function requireDefinition(id: string): ProcedureDefinition {
23
+ const definition = findProcedure(id);
24
+ if (!definition) throw new Error(`Unknown Matt Pocock procedure: ${id}`);
25
+ return definition;
26
+ }
27
+
28
+ function loadContent(definition: ProcedureDefinition): string {
29
+ const body = readFileSync(`${procedureDirectory}${definition.file}`, "utf8").trim();
30
+ return body.replace(/\]\((\.\/)?([A-Za-z0-9.-]+)(#[^)]+)?\)/g, (match, _prefix, file, anchor = "") => {
31
+ const target = findProcedureByFile(file);
32
+ return target ? `](procedure:${target.id}${anchor})` : match;
33
+ });
34
+ }
35
+
36
+ function dependencyClosure(root: string): ProcedureDefinition[] {
37
+ const ordered: ProcedureDefinition[] = [];
38
+ const visiting = new Set<string>();
39
+ const visited = new Set<string>();
40
+
41
+ const visit = (id: string): void => {
42
+ const definition = requireDefinition(id);
43
+ if (visited.has(definition.id)) return;
44
+ if (visiting.has(definition.id)) {
45
+ throw new Error(`Cyclic Matt Pocock procedure dependency at ${definition.id}`);
46
+ }
47
+ visiting.add(definition.id);
48
+ ordered.push(definition);
49
+ for (const dependency of definition.requires ?? []) visit(dependency);
50
+ visiting.delete(definition.id);
51
+ visited.add(definition.id);
52
+ };
53
+
54
+ visit(root);
55
+ return ordered;
56
+ }
57
+
58
+ function renderSource(definition: ProcedureDefinition): string {
59
+ const body = loadContent(definition);
60
+ return `<procedure-source id="${definition.id}" source="procedure/${definition.id}">\n${body}\n</procedure-source>`;
61
+ }
62
+
63
+ function resolvedBundle(root: string, definitions: ProcedureDefinition[]): ResolvedProcedureBundle {
64
+ const unique = definitions.filter((definition, index) => (
65
+ definitions.findIndex((candidate) => candidate.id === definition.id) === index
66
+ ));
67
+ const content = unique.map(renderSource).join("\n\n");
68
+ const byteLength = Buffer.byteLength(content, "utf8");
69
+ if (byteLength > MAX_PROCEDURE_BUNDLE_BYTES) {
70
+ throw new Error(
71
+ `Matt Pocock procedure bundle ${root} is ${byteLength} bytes; maximum is ${MAX_PROCEDURE_BUNDLE_BYTES}`,
72
+ );
73
+ }
74
+ const loaded = unique.map((definition) => definition.id);
75
+ const availableReferences = [
76
+ ...new Set(unique.flatMap((definition) => definition.discloses ?? [])),
77
+ ].filter((reference) => !loaded.includes(reference));
78
+ return { root, loaded, availableReferences, content, byteLength };
79
+ }
80
+
81
+ export function resolveProcedureBundle(id: string): ResolvedProcedureBundle {
82
+ const definitions = dependencyClosure(id);
83
+ return resolvedBundle(definitions[0].id, definitions);
84
+ }
85
+
86
+ export function resolveWorkflowContext(
87
+ activeProcedure: string,
88
+ loadedReferences: string[],
89
+ ): ResolvedProcedureBundle {
90
+ const root = normalizeProcedureId(activeProcedure);
91
+ const definitions = [...dependencyClosure(root)];
92
+ const loaded = new Set(definitions.map((definition) => definition.id));
93
+ let available = new Set(definitions.flatMap((definition) => definition.discloses ?? []));
94
+
95
+ for (const requested of loadedReferences.map(normalizeProcedureId)) {
96
+ if (loaded.has(requested)) continue;
97
+ if (!available.has(requested)) {
98
+ throw new Error(
99
+ `Reference ${requested} is not disclosed by the restored workflow context. Available references: ${[...available].join(", ") || "none"}`,
100
+ );
101
+ }
102
+ for (const definition of dependencyClosure(requested)) {
103
+ if (!loaded.has(definition.id)) {
104
+ definitions.push(definition);
105
+ loaded.add(definition.id);
106
+ }
107
+ }
108
+ available = new Set(definitions.flatMap((definition) => definition.discloses ?? []));
109
+ }
110
+
111
+ return resolvedBundle(root, definitions);
112
+ }
113
+
114
+ export function resolveAccessibleReference(
115
+ activeProcedure: string,
116
+ loadedReferences: string[],
117
+ reference: string,
118
+ ): ResolvedProcedureBundle {
119
+ const context = resolveWorkflowContext(activeProcedure, loadedReferences);
120
+ const target = requireDefinition(reference);
121
+ if (!context.availableReferences.includes(target.id)) {
122
+ throw new Error(
123
+ `Reference ${target.id} is not disclosed by ${activeProcedure}. Available references: ${context.availableReferences.join(", ") || "none"}`,
124
+ );
125
+ }
126
+ return resolveProcedureBundle(target.id);
127
+ }