@pstdio/sdk 0.7.0 → 0.9.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.
Files changed (74) hide show
  1. package/README.md +27 -188
  2. package/dist/api/extensions.d.ts +1 -1
  3. package/dist/api/index.d.ts +2 -2
  4. package/dist/api/settings.d.ts +1 -0
  5. package/dist/api/statuses.d.ts +1 -0
  6. package/dist/api/tags.d.ts +1 -0
  7. package/dist/api/tickets.d.ts +3 -0
  8. package/dist/api/workspaces.d.ts +10 -1
  9. package/dist/client/client.d.ts +7 -2
  10. package/dist/client/index.d.ts +5 -3
  11. package/dist/client/index.js +285 -31
  12. package/dist/client/projects.d.ts +0 -11
  13. package/dist/client/request.d.ts +9 -0
  14. package/dist/client/sessions.d.ts +25 -3
  15. package/dist/client/settings.d.ts +7 -0
  16. package/dist/client/sse.d.ts +15 -0
  17. package/dist/client/statuses.d.ts +2 -0
  18. package/dist/client/sync.d.ts +35 -0
  19. package/dist/client/tags.d.ts +2 -0
  20. package/dist/client/tickets.d.ts +6 -1
  21. package/dist/client/workspaces.d.ts +2 -0
  22. package/dist/extensions/define-command.d.ts +1 -1
  23. package/dist/extensions/define-extension.d.ts +50 -7
  24. package/dist/extensions/index.d.ts +3 -2
  25. package/dist/extensions/index.js +151 -11
  26. package/dist/extensions/kernel-slots.d.ts +131 -10
  27. package/dist/extensions/params.d.ts +19 -12
  28. package/dist/extensions/refs.d.ts +3 -3
  29. package/dist/extensions/slots.d.ts +1 -9
  30. package/dist/extensions/types/commands.d.ts +8 -0
  31. package/dist/extensions/types/context.d.ts +225 -18
  32. package/dist/extensions/types/contributions.d.ts +183 -10
  33. package/dist/extensions/types/extension.d.ts +16 -10
  34. package/dist/extensions/types/params.d.ts +43 -29
  35. package/dist/extensions/types/slots.d.ts +1 -1
  36. package/dist/extensions/types/webview-capabilities.d.ts +12 -2
  37. package/dist/extensions/workbench-targets.d.ts +134 -0
  38. package/dist/hooks/attempt.d.ts +2 -0
  39. package/dist/hooks/entities.d.ts +2 -0
  40. package/dist/hooks/ticket.d.ts +3 -0
  41. package/dist/resources/index.d.ts +3 -0
  42. package/dist/resources/index.js +26 -0
  43. package/dist/resources/known-agents.d.ts +12 -0
  44. package/dist/resources/settings.d.ts +1 -0
  45. package/dist/resources/status.d.ts +1 -0
  46. package/dist/resources/tag.d.ts +1 -0
  47. package/dist/resources/ticket.d.ts +1 -0
  48. package/dist/resources/workspace.d.ts +4 -1
  49. package/package.json +2 -6
  50. package/dist/api/actions.d.ts +0 -13
  51. package/dist/client/actions.d.ts +0 -8
  52. package/dist/plugins/define-plugin.d.ts +0 -2
  53. package/dist/plugins/helpers/context.d.ts +0 -24
  54. package/dist/plugins/helpers/create-attempt.d.ts +0 -5
  55. package/dist/plugins/helpers/create-session.d.ts +0 -21
  56. package/dist/plugins/helpers/create-workspace.d.ts +0 -5
  57. package/dist/plugins/helpers/find-ticket-by-ref.d.ts +0 -6
  58. package/dist/plugins/helpers/find-workspace-by-ref.d.ts +0 -5
  59. package/dist/plugins/helpers/followup-session.d.ts +0 -29
  60. package/dist/plugins/helpers/get-attempts-for-ticket.d.ts +0 -17
  61. package/dist/plugins/helpers/index.d.ts +0 -16
  62. package/dist/plugins/helpers/remove-all-worktrees-for-ticket.d.ts +0 -2
  63. package/dist/plugins/helpers/run-command.d.ts +0 -10
  64. package/dist/plugins/helpers/save-ticket.d.ts +0 -14
  65. package/dist/plugins/helpers/set-ticket-status.d.ts +0 -7
  66. package/dist/plugins/helpers/set-workspace-attempt-status.d.ts +0 -7
  67. package/dist/plugins/helpers/ticket-pull.d.ts +0 -18
  68. package/dist/plugins/helpers/update-ticket-when-all-attempts-match.d.ts +0 -7
  69. package/dist/plugins/helpers/workspaces-for-ticket.d.ts +0 -17
  70. package/dist/plugins/helpers/worktree-bootstrap.d.ts +0 -8
  71. package/dist/plugins/hooks.d.ts +0 -42
  72. package/dist/plugins/index.d.ts +0 -5
  73. package/dist/plugins/index.js +0 -739
  74. package/dist/plugins/types.d.ts +0 -112
@@ -1,739 +0,0 @@
1
- // src/prompts/render-prompt.ts
2
- import Mustache from "mustache";
3
- var renderPrompt = (template, data) => Mustache.render(template, data);
4
- // src/plugins/define-plugin.ts
5
- var assertActionTriggers = (plugin) => {
6
- for (const action of plugin.actions ?? []) {
7
- if (typeof action.trigger !== "function") {
8
- throw new Error(`Action "${action.key}" is missing trigger(ctx)`);
9
- }
10
- }
11
- };
12
- var assertScheduleHandlers = (plugin) => {
13
- for (const schedule of plugin.schedules ?? []) {
14
- if (typeof schedule.handler !== "function") {
15
- throw new Error(`Schedule "${schedule.name}" is missing handler(ctx)`);
16
- }
17
- }
18
- };
19
- var definePlugin = (plugin) => {
20
- assertActionTriggers(plugin);
21
- assertScheduleHandlers(plugin);
22
- return plugin;
23
- };
24
- // src/plugins/helpers/context.ts
25
- var firstMatch = (values, ref, readName) => {
26
- if (ref) {
27
- const byIdMatch = values.find((value) => value.id === ref);
28
- if (byIdMatch)
29
- return byIdMatch;
30
- return values.find((value) => readName(value) === ref) ?? null;
31
- }
32
- return null;
33
- };
34
- var readTicketLike = (value) => {
35
- if (!value || typeof value !== "object")
36
- return null;
37
- const ticket = value;
38
- if (typeof ticket.id !== "string" || typeof ticket.shorthand !== "string") {
39
- return null;
40
- }
41
- return ticket;
42
- };
43
- var readWorkspaceLike = (value) => {
44
- if (!value || typeof value !== "object")
45
- return null;
46
- const workspace = value;
47
- if (typeof workspace.id !== "string" || typeof workspace.workspace_shorthand !== "string") {
48
- return null;
49
- }
50
- return workspace;
51
- };
52
- var matchesRef = (ref, id, name) => !ref || ref === id || ref === name;
53
- var readTicketFromContext = (ctx, ref) => {
54
- const actionTarget = "targetType" in ctx && ctx.targetType === "ticket" ? readTicketLike(ctx.target) : null;
55
- if (actionTarget && matchesRef(ref, actionTarget.id, actionTarget.shorthand)) {
56
- return actionTarget;
57
- }
58
- const hookTicket = readTicketLike(ctx.ticket);
59
- if (hookTicket && matchesRef(ref, hookTicket.id, hookTicket.shorthand)) {
60
- return hookTicket;
61
- }
62
- return null;
63
- };
64
- var readWorkspaceFromContext = (ctx, ref) => {
65
- const actionTarget = "targetType" in ctx && ctx.targetType === "workspace" ? readWorkspaceLike(ctx.target) : null;
66
- if (actionTarget && matchesRef(ref, actionTarget.id, actionTarget.workspace_shorthand)) {
67
- return actionTarget;
68
- }
69
- const hookWorkspace = readWorkspaceLike(ctx.workspace);
70
- if (hookWorkspace && matchesRef(ref, hookWorkspace.id, hookWorkspace.workspace_shorthand)) {
71
- return hookWorkspace;
72
- }
73
- return null;
74
- };
75
- var resolveSessionIdFromContext = (ctx) => {
76
- const actionTarget = "targetType" in ctx && ctx.targetType === "session" ? ctx.target.id : null;
77
- if (actionTarget)
78
- return actionTarget;
79
- const originalSessionId = ctx.originalSessionId;
80
- if (typeof originalSessionId === "string" && originalSessionId.length > 0) {
81
- return originalSessionId;
82
- }
83
- const sessionId = ctx.sessionId;
84
- if (typeof sessionId === "string" && sessionId.length > 0) {
85
- return sessionId;
86
- }
87
- return null;
88
- };
89
-
90
- // src/plugins/helpers/find-ticket-by-ref.ts
91
- var findTicketByRef = async (ctx, input) => {
92
- const contextualTicket = readTicketFromContext(ctx, input.ticketId);
93
- if (contextualTicket)
94
- return contextualTicket;
95
- const tickets = await ctx.client.tickets.list(ctx.projectId);
96
- return firstMatch(tickets, input.ticketId, (ticket) => ticket.shorthand);
97
- };
98
- var resolveTicketShorthand = async (ctx, input) => {
99
- if (!input.ticketId)
100
- return null;
101
- const ticket = await findTicketByRef(ctx, input);
102
- return ticket?.shorthand ?? null;
103
- };
104
-
105
- // src/plugins/helpers/create-attempt.ts
106
- var createAttempt = async (ctx, input) => {
107
- const ticketId = (await findTicketByRef(ctx, input))?.id;
108
- if (!ticketId)
109
- return null;
110
- const { ticketId: _ticketId, ...attemptInput } = input;
111
- return ctx.client.tickets.createAttempt(ticketId, {
112
- ...attemptInput,
113
- start_session: true
114
- });
115
- };
116
- // src/plugins/helpers/create-session.ts
117
- var createSession = async (ctx, input) => ctx.client.sessions.create({
118
- project_id: ctx.projectId,
119
- ...input
120
- });
121
- // src/plugins/helpers/create-workspace.ts
122
- var createWorkspace = async (ctx, input) => {
123
- const ticketId = (await findTicketByRef(ctx, input))?.id;
124
- if (!ticketId)
125
- return null;
126
- const { ticketId: _ticketId, ...attemptInput } = input;
127
- return ctx.client.tickets.createAttempt(ticketId, {
128
- ...attemptInput,
129
- start_session: false
130
- });
131
- };
132
- // src/plugins/helpers/find-workspace-by-ref.ts
133
- var findWorkspaceByRef = async (ctx, input) => {
134
- const contextualWorkspace = readWorkspaceFromContext(ctx, input.workspaceId);
135
- if (contextualWorkspace)
136
- return contextualWorkspace;
137
- const workspaces = await ctx.client.workspaces.list(ctx.projectId);
138
- return firstMatch(workspaces, input.workspaceId, (workspace) => workspace.workspace_shorthand);
139
- };
140
- // src/plugins/helpers/followup-session.ts
141
- var followupSession = async (ctx, input) => {
142
- const sessionId = input.sessionId ?? resolveSessionIdFromContext(ctx);
143
- if (!sessionId) {
144
- throw new Error("followupSession requires sessionId or hook/action session context");
145
- }
146
- const { sessionId: _sessionId, ...followupInput } = input;
147
- return ctx.client.sessions.followUp(sessionId, followupInput);
148
- };
149
- // src/plugins/helpers/workspaces-for-ticket.ts
150
- var workspacesForTicket = async (ctx, input) => {
151
- const ticketShorthand = await resolveTicketShorthand(ctx, input);
152
- if (!ticketShorthand)
153
- return [];
154
- const workspaces = await ctx.client.workspaces.list(ctx.projectId);
155
- return workspaces.filter((workspace) => workspace.ticket_shorthand === ticketShorthand);
156
- };
157
-
158
- // src/plugins/helpers/get-attempts-for-ticket.ts
159
- var getAttemptsForTicket = async (ctx, input) => {
160
- return workspacesForTicket(ctx, input);
161
- };
162
- // src/plugins/helpers/remove-all-worktrees-for-ticket.ts
163
- var removeAllWorktreesForTicket = async (ctx, input) => {
164
- const ticketShorthand = await resolveTicketShorthand(ctx, input);
165
- if (!ticketShorthand)
166
- return 0;
167
- const workspaces = await ctx.client.workspaces.list(ctx.projectId);
168
- const ticketWorkspaces = workspaces.filter((workspace) => workspace.ticket_shorthand === ticketShorthand && workspace.worktree_path);
169
- let removed = 0;
170
- for (const workspace of ticketWorkspaces) {
171
- try {
172
- const result = await ctx.client.workspaces.removeWorktree(workspace.id);
173
- if (result.removed) {
174
- removed++;
175
- }
176
- } catch {}
177
- }
178
- return removed;
179
- };
180
- // src/plugins/helpers/run-command.ts
181
- import { accessSync, constants } from "node:fs";
182
- import { delimiter, join } from "node:path";
183
- var resolveCommandPath = (command, env) => {
184
- if (command.includes("/") || command.includes("\\"))
185
- return command;
186
- for (const dir of env.PATH?.split(delimiter) ?? []) {
187
- const candidate = join(dir || ".", command);
188
- try {
189
- accessSync(candidate, constants.X_OK);
190
- return candidate;
191
- } catch {}
192
- }
193
- return command;
194
- };
195
- var runCommand = async (cwd, command, options = {}) => {
196
- const [cmd, ...args] = command;
197
- const stdio = options.quiet ? "ignore" : "pipe";
198
- const env = { ...process.env, ...options.env };
199
- const resolvedCmd = resolveCommandPath(cmd, env);
200
- let proc;
201
- try {
202
- proc = Bun.spawn([resolvedCmd, ...args], {
203
- cwd,
204
- env,
205
- stdin: "ignore",
206
- stdout: stdio,
207
- stderr: stdio
208
- });
209
- } catch (error) {
210
- return { exitCode: 1, stdout: "", stderr: error.message };
211
- }
212
- const readStream = (stream) => stream && typeof stream !== "number" ? new Response(stream).text() : Promise.resolve("");
213
- const [stdout, stderr] = await Promise.all([readStream(proc.stdout), readStream(proc.stderr)]);
214
- const exitCode = await proc.exited;
215
- return {
216
- exitCode,
217
- stdout: stdout.trim(),
218
- stderr: stderr.trim()
219
- };
220
- };
221
- // src/plugins/helpers/save-ticket.ts
222
- import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
223
- import { basename, isAbsolute, join as join2, relative, resolve } from "node:path";
224
- var TICKETS_DIR = join2(".pstdio", "tickets");
225
- var TICKET_FILES_DIR = "files";
226
- var TICKET_ARTIFACTS_DIR = "artifacts";
227
- var MAX_DISPLAY_TITLE_LENGTH = 50;
228
- var ACTIONABLE_FRONTMATTER_KEYS = ["blocked_reason", "parent_id", "status"];
229
- var resolveTicketDir = (rootPath, shorthand) => {
230
- const exactDir = join2(rootPath, TICKETS_DIR, shorthand);
231
- if (!existsSync(exactDir))
232
- return null;
233
- if (!statSync(exactDir).isDirectory()) {
234
- throw new Error(`Invalid ticket path for ${shorthand}: .pstdio/tickets/${shorthand} is not a directory.`);
235
- }
236
- return exactDir;
237
- };
238
- var readTicketFile = (rootPath, shorthand) => {
239
- const dir = resolveTicketDir(rootPath, shorthand);
240
- if (!dir)
241
- return null;
242
- const filePath = join2(dir, "ticket.md");
243
- if (!existsSync(filePath))
244
- return null;
245
- return readFileSync(filePath, "utf8");
246
- };
247
- var writeTicketFile = (rootPath, shorthand, content) => {
248
- const dir = resolveTicketDir(rootPath, shorthand) ?? join2(rootPath, TICKETS_DIR, shorthand);
249
- mkdirSync(dir, { recursive: true });
250
- writeFileSync(join2(dir, "ticket.md"), content);
251
- };
252
- var walkFiles = (baseDir, currentDir, files) => {
253
- const entries = readdirSync(currentDir, { withFileTypes: true });
254
- for (const entry of entries) {
255
- const fullPath = join2(currentDir, entry.name);
256
- if (entry.isDirectory()) {
257
- walkFiles(baseDir, fullPath, files);
258
- continue;
259
- }
260
- if (!entry.isFile())
261
- continue;
262
- files.push(relative(baseDir, fullPath).split("\\").join("/"));
263
- }
264
- };
265
- var listDirFiles = (rootPath, shorthand, subDir) => {
266
- const dir = resolveTicketDir(rootPath, shorthand);
267
- if (!dir)
268
- return [];
269
- const baseDir = join2(dir, subDir);
270
- if (!existsSync(baseDir))
271
- return [];
272
- const files = [];
273
- walkFiles(baseDir, baseDir, files);
274
- files.sort();
275
- return files;
276
- };
277
- var readSafe = (rootPath, shorthand, subDir, requestedPath) => {
278
- const ticketDir = resolveTicketDir(rootPath, shorthand);
279
- if (!ticketDir)
280
- throw new Error(`Ticket directory not found: ${shorthand}`);
281
- const baseDir = join2(ticketDir, subDir);
282
- const target = resolve(baseDir, requestedPath);
283
- const rel = relative(baseDir, target);
284
- if (isAbsolute(rel) || rel.startsWith("..")) {
285
- throw new Error(`Path resolves outside ticket ${subDir} directory: ${requestedPath}`);
286
- }
287
- return readFileSync(target);
288
- };
289
- var findFrontmatterClosingIndex = (content) => {
290
- if (!content.startsWith("---"))
291
- return -1;
292
- return content.indexOf("---", 3);
293
- };
294
- var stripFrontmatter = (content) => {
295
- const closing = findFrontmatterClosingIndex(content);
296
- if (closing === -1)
297
- return content;
298
- return content.slice(closing + 3);
299
- };
300
- var parseFrontmatter = (content) => {
301
- const closing = findFrontmatterClosingIndex(content);
302
- if (closing === -1)
303
- return {};
304
- const block = content.slice(3, closing).trim();
305
- const result = {};
306
- for (const line of block.split(`
307
- `)) {
308
- const colonIndex = line.indexOf(":");
309
- if (colonIndex === -1)
310
- continue;
311
- const key = line.slice(0, colonIndex).trim();
312
- const raw = line.slice(colonIndex + 1).trim().replace(/^["']|["']$/g, "");
313
- if (!raw)
314
- continue;
315
- if (ACTIONABLE_FRONTMATTER_KEYS.includes(key)) {
316
- result[key] = raw;
317
- }
318
- }
319
- return result;
320
- };
321
- var frontmatterLines = (content) => {
322
- const closing = findFrontmatterClosingIndex(content);
323
- if (closing === -1)
324
- return [];
325
- const block = content.slice(3, closing).trim();
326
- if (!block)
327
- return [];
328
- return block.split(`
329
- `);
330
- };
331
- var frontmatterKey = (line) => {
332
- const colon = line.indexOf(":");
333
- if (colon === -1)
334
- return null;
335
- return line.slice(0, colon).trim();
336
- };
337
- var applyFrontmatter = (frontmatter, content) => {
338
- const body = stripFrontmatter(content).replace(/^\n+/, "");
339
- if (!body)
340
- return frontmatter;
341
- return `${frontmatter}
342
-
343
- ${body}`;
344
- };
345
- var applyFrontmatterValues = (frontmatter, content) => {
346
- if (findFrontmatterClosingIndex(content) === -1)
347
- return applyFrontmatter(frontmatter, content);
348
- const overrides = new Map;
349
- const overrideOrder = [];
350
- for (const line of frontmatterLines(frontmatter)) {
351
- const key = frontmatterKey(line);
352
- if (!key)
353
- continue;
354
- overrides.set(key, line);
355
- overrideOrder.push(key);
356
- }
357
- const existing = frontmatterLines(content);
358
- const merged = existing.map((line) => {
359
- const key = frontmatterKey(line);
360
- if (!key || !overrides.has(key))
361
- return line;
362
- return overrides.get(key);
363
- });
364
- for (const key of overrideOrder) {
365
- if (existing.some((line2) => frontmatterKey(line2) === key))
366
- continue;
367
- const line = overrides.get(key);
368
- if (line)
369
- merged.push(line);
370
- }
371
- return applyFrontmatter(["---", ...merged, "---"].join(`
372
- `), content);
373
- };
374
- var markLocalTicketAsSaved = (content) => applyFrontmatterValues(["---", "draft: false", "---"].join(`
375
- `), content);
376
- var stripMarkdownFormatting = (text) => text.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\*\*([^*]*)\*\*/g, "$1").replace(/\*([^*]*)\*/g, "$1").replace(/`([^`]*)`/g, "$1");
377
- var slugify = (text, maxLength) => text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, maxLength).replace(/-+$/, "");
378
- var firstHeadingOrLine = (content) => {
379
- const lines = content.split(`
380
- `);
381
- for (const line of lines) {
382
- const trimmed = line.trim();
383
- if (trimmed.startsWith("# "))
384
- return trimmed.slice(2).trim();
385
- }
386
- for (const line of lines) {
387
- const trimmed = line.trim();
388
- if (trimmed.length > 0)
389
- return trimmed;
390
- }
391
- return null;
392
- };
393
- var extractDisplayTitle = (content) => {
394
- const raw = firstHeadingOrLine(stripFrontmatter(content)) ?? "untitled";
395
- return slugify(stripMarkdownFormatting(raw), MAX_DISPLAY_TITLE_LENGTH);
396
- };
397
- var resolveStatusId = async (ctx, statusName) => {
398
- const statuses = await ctx.client.statuses.list(ctx.projectId);
399
- const found = statuses.find((status) => status.name === statusName);
400
- if (!found)
401
- throw new Error(`Status not found: ${statusName}`);
402
- return found.id;
403
- };
404
- var resolveTagIds = async (ctx, tagNames) => {
405
- const tags = await ctx.client.tags.list(ctx.projectId);
406
- const options = tags.flatMap((tag) => tag.options);
407
- return tagNames.map((name) => {
408
- const found = options.find((option) => option.name === name);
409
- if (!found)
410
- throw new Error(`Tag option not found: ${name}`);
411
- return found.id;
412
- });
413
- };
414
- var saveTicket = async (ctx, input) => {
415
- const log = input.log ?? (() => {});
416
- const ticket = await findTicketByRef(ctx, { ticketId: input.ticketId });
417
- if (!ticket)
418
- throw new Error(`Ticket not found: ${input.ticketId ?? "<none>"}`);
419
- const shorthand = ticket.shorthand;
420
- const content = readTicketFile(input.rootPath, shorthand);
421
- if (content === null)
422
- throw new Error(`Local ticket not found: .pstdio/tickets/${shorthand}/ticket.md`);
423
- const frontmatter = parseFrontmatter(content);
424
- const statusName = input.status ?? frontmatter.status;
425
- const statusId = statusName ? await resolveStatusId(ctx, statusName) : undefined;
426
- const tagIds = input.tags?.length ? await resolveTagIds(ctx, input.tags) : undefined;
427
- const body = stripFrontmatter(content).replace(/^\n+/, "");
428
- const uploaded = await ctx.client.tickets.uploadFile(ticket.id, {
429
- file_name: "ticket.md",
430
- content_base64: Buffer.from(body).toString("base64"),
431
- mime_type: "text/markdown"
432
- });
433
- await ctx.client.tickets.update(ticket.id, {
434
- blocked_reason: frontmatter.blocked_reason,
435
- file_id: uploaded.id,
436
- display_title: extractDisplayTitle(body),
437
- draft: false,
438
- parent_id: frontmatter.parent_id,
439
- tag_ids: tagIds,
440
- status_id: statusId
441
- });
442
- let uploadedFileCount = 0;
443
- for (const fileName of listDirFiles(input.rootPath, shorthand, TICKET_FILES_DIR)) {
444
- const data = readSafe(input.rootPath, shorthand, TICKET_FILES_DIR, fileName);
445
- await ctx.client.tickets.uploadFile(ticket.id, {
446
- file_name: fileName,
447
- content_base64: data.toString("base64")
448
- });
449
- uploadedFileCount++;
450
- }
451
- for (const relativePath of listDirFiles(input.rootPath, shorthand, TICKET_ARTIFACTS_DIR)) {
452
- const data = readSafe(input.rootPath, shorthand, TICKET_ARTIFACTS_DIR, relativePath);
453
- await ctx.client.tickets.uploadFile(ticket.id, {
454
- file_name: basename(relativePath),
455
- relative_path: relativePath,
456
- content_base64: data.toString("base64")
457
- });
458
- uploadedFileCount++;
459
- }
460
- writeTicketFile(input.rootPath, shorthand, markLocalTicketAsSaved(content));
461
- log(`Saved ticket ${shorthand}`);
462
- if (uploadedFileCount > 0)
463
- log(`Uploaded ${uploadedFileCount} ticket files`);
464
- return { ticketShorthand: shorthand, uploadedFileCount };
465
- };
466
- // src/plugins/helpers/set-ticket-status.ts
467
- var setTicketStatus = async (ctx, input) => {
468
- const [ticket, statuses] = await Promise.all([
469
- findTicketByRef(ctx, { ticketId: input.ticket }),
470
- ctx.client.statuses.list(ctx.projectId)
471
- ]);
472
- if (!ticket)
473
- return false;
474
- const status = statuses.find((candidate) => candidate.name === input.status);
475
- if (!status)
476
- return false;
477
- await ctx.client.tickets.update(ticket.id, { status_id: status.id });
478
- return true;
479
- };
480
- // src/plugins/helpers/set-workspace-attempt-status.ts
481
- var setWorkspaceAttemptStatus = async (ctx, input) => {
482
- const workspace = await findWorkspaceByRef(ctx, input);
483
- const workspaceId = workspace?.id;
484
- if (!workspaceId)
485
- return false;
486
- await ctx.client.workspaces.updateAttemptStatus(workspaceId, {
487
- status: input.statusName,
488
- session_id: input.sessionId
489
- });
490
- return true;
491
- };
492
- // src/plugins/helpers/ticket-pull.ts
493
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
494
- import { dirname, isAbsolute as isAbsolute2, join as join3, relative as relative2, resolve as resolve2 } from "node:path";
495
- var TICKETS_DIR2 = join3(".pstdio", "tickets");
496
- var TICKET_FILES_DIR2 = "files";
497
- var escapeYamlScalar = (value) => value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
498
- var buildTicketFrontmatter = (fields) => {
499
- const lines = ["---"];
500
- const q = (value) => `"${escapeYamlScalar(value)}"`;
501
- lines.push(`ticket_id: ${q(fields.shorthand)}`);
502
- if (fields.user_prompt)
503
- lines.push(`user_prompt: ${q(fields.user_prompt)}`);
504
- lines.push(`created: ${q(fields.created_at)}`);
505
- if (fields.draft !== null)
506
- lines.push(`draft: ${fields.draft}`);
507
- if (fields.status_name)
508
- lines.push(`status: ${q(fields.status_name)}`);
509
- if (fields.parent_id)
510
- lines.push(`parent_id: ${q(fields.parent_id)}`);
511
- if (fields.depends_on)
512
- lines.push(`depends_on: ${q(fields.depends_on)}`);
513
- if (fields.parallelizable)
514
- lines.push(`parallelizable: ${q(fields.parallelizable)}`);
515
- if (fields.blocked_reason)
516
- lines.push(`blocked_reason: ${q(fields.blocked_reason)}`);
517
- if (fields.tag_names.length > 0)
518
- lines.push(`tags: [${fields.tag_names.map(q).join(", ")}]`);
519
- lines.push("---");
520
- return lines.join(`
521
- `);
522
- };
523
- var stripFrontmatter2 = (content) => {
524
- if (!content.startsWith("---"))
525
- return content;
526
- const closingIndex = content.indexOf("---", 3);
527
- if (closingIndex === -1)
528
- return content;
529
- return content.slice(closingIndex + 3);
530
- };
531
- var applyFrontmatter2 = (frontmatter, content) => {
532
- const body = stripFrontmatter2(content).replace(/^\n+/, "");
533
- if (!body)
534
- return frontmatter;
535
- return `${frontmatter}
536
-
537
- ${body}`;
538
- };
539
- var toRelativeFilePath = (baseDir, absolutePath) => relative2(baseDir, absolutePath).split("\\").join("/");
540
- var resolveTicketDir2 = (rootPath, shorthand) => {
541
- const exactDir = join3(rootPath, TICKETS_DIR2, shorthand);
542
- if (!existsSync2(exactDir))
543
- return null;
544
- if (!statSync2(exactDir).isDirectory()) {
545
- throw new Error(`Invalid ticket path for ${shorthand}: .pstdio/tickets/${shorthand} is not a directory.`);
546
- }
547
- return exactDir;
548
- };
549
- var writeTicketFile2 = (rootPath, shorthand, content, overwrite = true) => {
550
- const existingDir = resolveTicketDir2(rootPath, shorthand);
551
- const dir = existingDir ?? join3(rootPath, TICKETS_DIR2, shorthand);
552
- const filePath = join3(dir, "ticket.md");
553
- if (!overwrite && existsSync2(filePath)) {
554
- throw new Error(`Local file already exists: ${toRelativeFilePath(rootPath, filePath)}. Use force to overwrite.`);
555
- }
556
- mkdirSync2(dir, { recursive: true });
557
- writeFileSync2(filePath, content);
558
- return filePath;
559
- };
560
- var resolveTicketAttachmentPath = (rootPath, shorthand, fileName) => {
561
- const ticketDir = resolveTicketDir2(rootPath, shorthand);
562
- if (!ticketDir)
563
- throw new Error(`Ticket directory not found for ${shorthand}`);
564
- const filesDir = join3(ticketDir, TICKET_FILES_DIR2);
565
- const targetPath = resolve2(filesDir, fileName);
566
- const rel = relative2(filesDir, targetPath);
567
- if (isAbsolute2(rel) || rel.startsWith("..")) {
568
- throw new Error(`Ticket file path resolves outside ticket files directory: ${fileName}`);
569
- }
570
- return targetPath;
571
- };
572
- var writeTicketAttachment = (rootPath, shorthand, fileName, content, overwrite = false) => {
573
- const filePath = resolveTicketAttachmentPath(rootPath, shorthand, fileName);
574
- if (!overwrite && existsSync2(filePath)) {
575
- throw new Error(`Local file already exists: ${toRelativeFilePath(rootPath, filePath)}. Use force to overwrite.`);
576
- }
577
- mkdirSync2(dirname(filePath), { recursive: true });
578
- writeFileSync2(filePath, content);
579
- return filePath;
580
- };
581
- var isNotFoundError = (error) => typeof error === "object" && error !== null && ("status" in error) && error.status === 404;
582
- var isTicketShorthand = (value) => /^[A-Za-z]+-\d+$/.test(value);
583
- var resolveParentFrontmatterValue = async (ctx, parentId) => {
584
- if (!parentId)
585
- return null;
586
- if (isTicketShorthand(parentId))
587
- return parentId;
588
- try {
589
- const parentTicket = await ctx.client.tickets.get(parentId);
590
- return parentTicket.shorthand || parentId;
591
- } catch (error) {
592
- if (isNotFoundError(error))
593
- return parentId;
594
- throw error;
595
- }
596
- };
597
- var resolveTicketByShorthand = async (ctx, ticketShorthand) => {
598
- const published = await ctx.client.tickets.list(ctx.projectId, { shorthand: ticketShorthand });
599
- if (published.length > 0)
600
- return published[0];
601
- const drafts = await ctx.client.tickets.list(ctx.projectId, { shorthand: ticketShorthand, draft: true });
602
- return drafts[0];
603
- };
604
- var resolveTicketById = async (ctx, ticketId) => {
605
- try {
606
- const detail = await ctx.client.tickets.get(ticketId);
607
- const byShorthand = await resolveTicketByShorthand(ctx, detail.shorthand);
608
- if (byShorthand)
609
- return byShorthand;
610
- return {
611
- ...detail,
612
- status_name: null,
613
- tag_ids: [],
614
- tag_names: []
615
- };
616
- } catch (error) {
617
- if (isNotFoundError(error))
618
- return null;
619
- throw error;
620
- }
621
- };
622
- var resolveTicketByRef = async (ctx, ticketId) => {
623
- const byId = await resolveTicketById(ctx, ticketId);
624
- if (byId)
625
- return byId;
626
- return resolveTicketByShorthand(ctx, ticketId);
627
- };
628
- var pullSingleTicket = async (ctx, rootPath, ticketListItem, force, log) => {
629
- const ticket = await ctx.client.tickets.get(ticketListItem.id);
630
- const parentId = await resolveParentFrontmatterValue(ctx, ticket.parent_id);
631
- const frontmatter = buildTicketFrontmatter({
632
- shorthand: ticketListItem.shorthand,
633
- created_at: ticket.created_at,
634
- draft: ticket.draft,
635
- status_name: ticketListItem.status_name,
636
- parent_id: parentId,
637
- user_prompt: ticket.user_prompt ?? null,
638
- depends_on: ticket.depends_on,
639
- parallelizable: ticket.parallelizable,
640
- blocked_reason: ticket.blocked_reason,
641
- tag_names: ticketListItem.tag_names ?? []
642
- });
643
- const content = applyFrontmatter2(frontmatter, ticket.content ?? "");
644
- const filePath = writeTicketFile2(rootPath, ticketListItem.shorthand, content, force);
645
- const ticketDir = filePath.replace(/\/ticket\.md$/, "").replace(`${rootPath}/`, "");
646
- const files = await ctx.client.tickets.listFiles(ticket.id);
647
- const attachments = files.filter((file) => file.id !== ticket.file_id);
648
- for (const file of attachments) {
649
- const fileContent = await ctx.client.tickets.getFileContent(ticket.id, file.id);
650
- writeTicketAttachment(rootPath, ticketListItem.shorthand, file.file_name, fileContent, force);
651
- }
652
- log(`Pulled ticket ${ticketListItem.shorthand} to ${ticketDir}`);
653
- if (attachments.length > 0)
654
- log(`Downloaded ${attachments.length} ticket files`);
655
- return { shorthand: ticketListItem.shorthand, downloadedFileCount: attachments.length };
656
- };
657
- var pullTickets = async (ctx, input) => {
658
- const force = input.force ?? false;
659
- const log = input.log ?? (() => {});
660
- if (input.ticketId) {
661
- const ticket = await resolveTicketByRef(ctx, input.ticketId);
662
- if (!ticket)
663
- throw new Error(`Ticket not found: ${input.ticketId}`);
664
- const result = await pullSingleTicket(ctx, input.rootPath, ticket, force, log);
665
- return { pulledTicketShorthands: [result.shorthand], downloadedFileCount: result.downloadedFileCount };
666
- }
667
- const listedTickets = await ctx.client.tickets.list(ctx.projectId, { archived: false });
668
- const tickets = listedTickets.filter((ticket) => !ticket.archived);
669
- if (tickets.length === 0) {
670
- log("No tickets to pull.");
671
- return { pulledTicketShorthands: [], downloadedFileCount: 0 };
672
- }
673
- const pulledTicketShorthands = [];
674
- let downloadedFileCount = 0;
675
- for (const ticket of tickets) {
676
- const result = await pullSingleTicket(ctx, input.rootPath, ticket, force, log);
677
- pulledTicketShorthands.push(result.shorthand);
678
- downloadedFileCount += result.downloadedFileCount;
679
- }
680
- log(`Pulled ${tickets.length} tickets`);
681
- return { pulledTicketShorthands, downloadedFileCount };
682
- };
683
- // src/plugins/helpers/update-ticket-when-all-attempts-match.ts
684
- var updateTicketWhenAllAttemptsMatch = async (ctx, input) => {
685
- const ticket = await findTicketByRef(ctx, input);
686
- const ticketId = ticket?.id;
687
- if (!ticketId)
688
- return false;
689
- const result = await ctx.client.tickets.updateWhenAttemptStatus(ticketId, {
690
- all_attempts_status: input.allAttemptsStatus,
691
- set_status: input.setStatus
692
- });
693
- return result.updated;
694
- };
695
- // src/plugins/helpers/worktree-bootstrap.ts
696
- import { cpSync, existsSync as existsSync3, mkdirSync as mkdirSync3 } from "node:fs";
697
- import { join as join4 } from "node:path";
698
- var AGENT_DIRS = [".claude", ".opencode", ".agents"];
699
- var bootstrapWorktree = async (ctx, input) => {
700
- const { repoPath, worktreePath, ticketId } = input;
701
- const repoConfig = join4(repoPath, ".pstdio", "config.json");
702
- const worktreeConfigDir = join4(worktreePath, ".pstdio");
703
- const worktreeConfig = join4(worktreeConfigDir, "config.json");
704
- if (existsSync3(repoConfig)) {
705
- mkdirSync3(worktreeConfigDir, { recursive: true });
706
- cpSync(repoConfig, worktreeConfig);
707
- }
708
- for (const agentDir of AGENT_DIRS) {
709
- const fromDir = join4(repoPath, agentDir);
710
- const toDir = join4(worktreePath, agentDir);
711
- if (!existsSync3(fromDir))
712
- continue;
713
- mkdirSync3(toDir, { recursive: true });
714
- cpSync(fromDir, toDir, { recursive: true });
715
- }
716
- if (!ticketId)
717
- return;
718
- await pullTickets(ctx, { rootPath: worktreePath, ticketId });
719
- };
720
- export {
721
- workspacesForTicket,
722
- updateTicketWhenAllAttemptsMatch,
723
- setWorkspaceAttemptStatus,
724
- setTicketStatus,
725
- saveTicket,
726
- runCommand,
727
- renderPrompt,
728
- removeAllWorktreesForTicket,
729
- pullTickets,
730
- getAttemptsForTicket,
731
- followupSession,
732
- findWorkspaceByRef,
733
- findTicketByRef,
734
- definePlugin,
735
- createWorkspace,
736
- createSession,
737
- createAttempt,
738
- bootstrapWorktree
739
- };