@justjoshn/pi-pstack 0.15.36-pi.1 → 0.15.36-pi.12
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/CHANGELOG.md +94 -0
- package/README.md +29 -24
- package/agents/ci-watcher.md +28 -0
- package/agents/thermo-nuclear-code-quality-review.md +23 -0
- package/assets/logo.png +0 -0
- package/automations/benny/FOR_AGENTS.md +2 -1
- package/automations/benny/README.md +2 -2
- package/automations/benny/skills/setup-benny/SKILL.md +10 -9
- package/automations/benny/templates/reproduce-automation-prompt.md +1 -1
- package/automations/benny/templates/triage-automation-prompt.md +1 -1
- package/bin/pstack-routines-supervisor +9 -0
- package/docs/guide/01-setup.md +2 -2
- package/docs/guide/07-overnight.md +1 -1
- package/docs/guide/09-make-it-yours.md +1 -1
- package/docs/guide/10-recipes-and-pitfalls.md +1 -1
- package/docs/native-gaps.md +14 -8
- package/docs/parity-reverse-engineering.md +94 -0
- package/docs/parity-status.md +128 -0
- package/package.json +41 -6
- package/packaging/install-supervisor-unit.sh +164 -0
- package/packaging/launchd/com.pstack.routines-supervisor.plist.example +24 -0
- package/packaging/systemd/pstack-routines-supervisor.service.example +15 -0
- package/skills/architect/SKILL.md +1 -1
- package/skills/architect/references/runner-prompt.md +1 -1
- package/skills/arena/SKILL.md +4 -4
- package/skills/check-compiler-errors/SKILL.md +23 -0
- package/skills/create-skill/SKILL.md +515 -29
- package/skills/fix-ci/SKILL.md +29 -0
- package/skills/fix-merge-conflicts/SKILL.md +32 -0
- package/skills/get-pr-comments/SKILL.md +23 -0
- package/skills/how/SKILL.md +1 -1
- package/skills/ketchup/SKILL.md +2 -2
- package/skills/ketchup-video/SKILL.md +2 -2
- package/skills/loop-on-ci/SKILL.md +50 -0
- package/skills/make-bot-ui/SKILL.md +2 -2
- package/skills/make-pr-easy-to-review/SKILL.md +59 -0
- package/skills/new-branch-and-pr/SKILL.md +29 -0
- package/skills/no-inline-imports/SKILL.md +12 -0
- package/skills/poteto-help/SKILL.md +4 -4
- package/skills/poteto-mode/SKILL.md +2 -2
- package/skills/poteto-mode/playbooks/bug-fix.md +1 -1
- package/skills/poteto-mode/playbooks/feature.md +1 -1
- package/skills/poteto-mode/playbooks/hillclimb.md +1 -1
- package/skills/poteto-mode/playbooks/multi-phase-plan.md +2 -2
- package/skills/poteto-mode/playbooks/orchestrate.md +2 -2
- package/skills/poteto-mode/playbooks/perf-issue.md +1 -1
- package/skills/poteto-mode/playbooks/refactoring.md +1 -1
- package/skills/pr-review-canvas/SKILL.md +176 -0
- package/skills/pr-review-canvas/renderer.js +170 -0
- package/skills/pr-review-canvas/styles.css +96 -0
- package/skills/pr-review-canvas/template.html +18 -0
- package/skills/reflect/SKILL.md +2 -2
- package/skills/review-and-ship/SKILL.md +41 -0
- package/skills/run-smoke-tests/SKILL.md +42 -0
- package/skills/setup-pstack/SKILL.md +13 -13
- package/skills/statechart/scripts/test/cli.test.ts +1 -1
- package/skills/swarm/SKILL.md +2 -2
- package/skills/teach/SKILL.md +1 -1
- package/skills/thermo-nuclear-code-quality-review/SKILL.md +192 -0
- package/skills/typescript-exhaustive-switch/SKILL.md +10 -0
- package/skills/verify-this/SKILL.md +74 -0
- package/skills/weekly-review/SKILL.md +32 -0
- package/skills/what-did-i-get-done/SKILL.md +31 -0
- package/skills/why/SKILL.md +2 -2
- package/skills/workflow-from-chats/SKILL.md +50 -0
- package/src/ask.ts +24 -10
- package/src/child-env.ts +15 -2
- package/src/generate-image.ts +98 -0
- package/src/index.ts +28 -9
- package/src/loop.ts +74 -17
- package/src/mode.ts +89 -27
- package/src/paths.ts +18 -0
- package/src/pi-command.ts +12 -0
- package/src/plan.ts +285 -30
- package/src/rule.ts +4 -4
- package/src/sections.ts +27 -3
- package/src/subscriptions/durable-store.ts +531 -0
- package/src/subscriptions/durable-types.ts +69 -0
- package/src/subscriptions/ensure-supervisor.ts +67 -0
- package/src/subscriptions/index.ts +310 -282
- package/src/subscriptions/supervisor-main.ts +134 -0
- package/src/subscriptions/supervisor.ts +325 -0
- package/src/subscriptions/webhook.ts +82 -21
- package/src/task/agents.ts +39 -3
- package/src/task/card.ts +31 -0
- package/src/task/format.ts +17 -3
- package/src/task/models.ts +7 -0
- package/src/task/progress.ts +112 -0
- package/src/task/records.ts +7 -9
- package/src/task/registry.ts +9 -4
- package/src/task/runner.ts +116 -24
- package/src/task/stop.ts +3 -3
- package/src/task/tool.ts +158 -57
- package/src/task/worktree.ts +5 -3
- package/src/todo.ts +29 -4
- package/scripts/live-e2e.mjs +0 -257
- package/test/aliases.test.ts +0 -57
- package/test/ask.test.ts +0 -85
- package/test/autocomplete.test.ts +0 -39
- package/test/e2e/aliases.e2e.test.ts +0 -81
- package/test/e2e/ask.e2e.test.ts +0 -135
- package/test/e2e/harness.ts +0 -179
- package/test/e2e/host.e2e.test.ts +0 -193
- package/test/e2e/lifecycle.e2e.test.ts +0 -99
- package/test/e2e/mode.e2e.test.ts +0 -160
- package/test/e2e/package.e2e.test.ts +0 -67
- package/test/e2e/task.e2e.test.ts +0 -734
- package/test/e2e/todo.e2e.test.ts +0 -59
- package/test/fixtures/cursor-askquestion-calls.json +0 -806
- package/test/fixtures/fake-pi.mjs +0 -96
- package/test/fixtures/image-model.ts +0 -16
- package/test/fixtures/list-models.ts +0 -15
- package/test/fixtures/readonly-shell-exit.ts +0 -17
- package/test/fixtures/scripted-model.ts +0 -113
- package/test/loop.test.ts +0 -209
- package/test/mode.test.ts +0 -143
- package/test/plan.test.ts +0 -126
- package/test/readonly-shell-security.test.ts +0 -84
- package/test/readonly-shell.test.ts +0 -44
- package/test/records.test.ts +0 -143
- package/test/registry.test.ts +0 -18
- package/test/resources.test.ts +0 -162
- package/test/rule.test.ts +0 -92
- package/test/scripts.test.ts +0 -182
- package/test/sections.test.ts +0 -56
- package/test/subscriptions-cron.test.ts +0 -60
- package/test/subscriptions.test.ts +0 -598
- package/test/task-agents.test.ts +0 -49
- package/test/task-card.test.ts +0 -34
- package/test/task-fork.test.ts +0 -233
- package/test/task-format.test.ts +0 -65
- package/test/task-model.test.ts +0 -141
- package/test/task-runner.test.ts +0 -259
- package/test/task-schema.test.ts +0 -50
- package/test/task-status.test.ts +0 -155
- package/test/task-worktree.test.ts +0 -106
- package/test/todo.test.ts +0 -74
- package/test/visualize.test.ts +0 -152
- package/tsconfig.json +0 -5
- package/vitest.config.ts +0 -16
package/skills/teach/SKILL.md
CHANGED
|
@@ -14,7 +14,7 @@ Teach sits on top of `how` and `why`. Get your bearings on what the work is and
|
|
|
14
14
|
2. Let `how` and `why` do the work, don't redo it. Read the code yourself to get oriented, then run `how` for how it works and `why` for why. Run them in parallel and combine the results. Match the size to the question. Run both for a subsystem, maybe one is enough for a small change. Keep `why` narrow by default since its full sweep is slow. Put the narrowing in the ask itself (a scoped question, git plus a source or two) so `why` records the skipped categories per its own contract, and widen it only when the reasons are the point.
|
|
15
15
|
3. Start with a plain definition. Name the thing and say what it is in general terms, the way a senior engineer would say it out loud, with its common name if it has one. Then tie it to the case in front of you ("in X, we use this to ...") and build from there: how it works, the deeper reasons, the edge cases. For each part, explain the idea so it clicks: the problem it solves and how it actually works. Walk through what happens as the person does the thing (opens a long chat, scrolls up) when that is what makes it land. Listing functions and constants is reference, not teaching. Don't print framing labels ("the one idea to hold onto", "the thing to walk away with", "the key insight", "at its core", "TL;DR"). Give the smallest complete answer first, a sentence or two, not a dense paragraph, then stop. Add layers when they ask. Never a wall of text.
|
|
16
16
|
4. Keep it a conversation, not a lecture or a performance. Offer to go deeper or move on, and follow their lead. No quizzes. No pacing theater. Don't print "Pause", don't ask them to say it back, don't announce "the sentence to nail", and don't flag a part as important or hard ("here is the part worth slowing down on", "this is the tricky part", "here is where it gets interesting"). Just say it. When you would pause, stop and let them respond. Running one-shot with no live human, deliver it cleanly and put any offer to go deeper at the end.
|
|
17
|
-
5. Show, don't only tell, and build the picture up diagram by diagram. Open the diff, the code, or the debugger when that is the fastest way to land it. Draw when a picture lands faster than words. For anything with three or more moving parts, do not draw one diagram with all of them at once. Draw a short series instead, where each diagram redraws the last and adds a single part, so the reader watches the system assemble. A single all-at-once diagram, especially one saved for the end, is a reference, not teaching. Concretely, to teach a flow from A to B to C, draw it three times. First A to B. Then redraw and add C. Then redraw and add the return edge or the next piece. Match the medium to the idea, and use both kinds when both help. A mermaid diagram fits a flow or structure where the labels carry the meaning. When the idea is spatial, like layout, overlap, scroll position, or a before and after, reach for image
|
|
17
|
+
5. Show, don't only tell, and build the picture up diagram by diagram. Open the diff, the code, or the debugger when that is the fastest way to land it. Draw when a picture lands faster than words. For anything with three or more moving parts, do not draw one diagram with all of them at once. Draw a short series instead, where each diagram redraws the last and adds a single part, so the reader watches the system assemble. A single all-at-once diagram, especially one saved for the end, is a reference, not teaching. Concretely, to teach a flow from A to B to C, draw it three times. First A to B. Then redraw and add C. Then redraw and add the return edge or the next piece. Match the medium to the idea, and use both kinds when both help. A mermaid diagram fits a flow or structure where the labels carry the meaning. When the idea is spatial, like layout, overlap, scroll position, or a before and after, reach for the image-generation tool and draw it marker-on-whiteboard style with a few short labels, since image models garble long text. Generate that picture, don't settle for describing it in words. The build-up rule holds for generated images too. A single simple point needs no figure.
|
|
18
18
|
|
|
19
19
|
Write every response through the **unslop** skill, in plain spoken English, the way you'd explain it to a colleague. Be tight, not terse. Cut filler and hedging, keep the part that makes it click. State the concrete mechanism, not a metaphor, a framing, or a preview of what is coming. This is the target density: "Virtualization runs in two parts, one for rendering and one for loading from disk. When an item scrolls out past the buffer, both its DOM node and its in-memory data are evicted." Normal sentence case, not all-lowercase. No em dashes. Prefer periods over commas. Keep each sentence to one or two commas. If clauses pile up, split them into separate sentences. Give each concept one name and keep it. Avoid mirror sentences ("A without B, or B without A") and tidy closers ("the rest follows", "it all falls out"). The words in these steps are directions to you, not labels to print. Don't echo the structure as headers or stock phrases.
|
|
20
20
|
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: thermo-nuclear-code-quality-review
|
|
3
|
+
description: Run an extremely strict maintainability review for abstraction quality, giant files, and spaghetti-condition growth. Use for a thermo-nuclear code quality review, thermonuclear review, deep code quality audit, or especially harsh maintainability review.
|
|
4
|
+
disable-model-invocation: true
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Thermo-Nuclear Code Quality Review
|
|
8
|
+
|
|
9
|
+
Use this skill for an unusually strict review focused on implementation quality, maintainability, abstraction quality, and codebase health.
|
|
10
|
+
|
|
11
|
+
Above all, this skill should push the reviewer to be **ambitious** about code structure. Do not merely identify local cleanup opportunities. Actively search for "code judo" moves: restructurings that preserve behavior while making the implementation dramatically simpler, smaller, more direct, and more elegant.
|
|
12
|
+
|
|
13
|
+
## Core Prompt
|
|
14
|
+
|
|
15
|
+
Start from this baseline:
|
|
16
|
+
|
|
17
|
+
> Perform a deep code quality audit of the current branch's changes.
|
|
18
|
+
> Rethink how to structure / implement the changes to meaningfully improve code quality without impacting behavior.
|
|
19
|
+
> Work to improve abstractions, modularity, reduce Spaghetti code, improve succinctness and legibility.
|
|
20
|
+
> Be ambitious, if there is a clear path to improving the implementation that involves restructuring some of the codebase, go for it.
|
|
21
|
+
> Be extremely thorough and rigorous. Measure twice, cut once.
|
|
22
|
+
|
|
23
|
+
## Non-Negotiable Additional Standards
|
|
24
|
+
|
|
25
|
+
Apply the baseline prompt above, plus these explicit review rules:
|
|
26
|
+
|
|
27
|
+
0. **Be ambitious about structural simplification.**
|
|
28
|
+
- Do not stop at "this could be a bit cleaner."
|
|
29
|
+
- Look for opportunities to reframe the change so that whole branches, helpers, modes, conditionals, or layers disappear entirely.
|
|
30
|
+
- Prefer the solution that makes the code feel inevitable in hindsight.
|
|
31
|
+
- Assume there is often a "code judo" move available: a re-organization that uses the existing architecture more effectively and makes the change dramatically simpler and more elegant.
|
|
32
|
+
- If you see a path to delete complexity rather than rearrange it, push hard for that path.
|
|
33
|
+
|
|
34
|
+
1. **Do not let a PR push a file from under 1k lines to over 1k lines without a very strong reason.**
|
|
35
|
+
- Treat this as a strong code-quality smell by default.
|
|
36
|
+
- Prefer extracting helpers, subcomponents, modules, or local abstractions instead of letting a file sprawl past 1000 lines.
|
|
37
|
+
- If the diff crosses that threshold, explicitly ask whether the code should be decomposed first.
|
|
38
|
+
- Only waive this if there is a compelling structural reason and the resulting file is still clearly organized.
|
|
39
|
+
|
|
40
|
+
2. **Do not allow random spaghetti growth in existing code.**
|
|
41
|
+
- Be highly suspicious of new ad-hoc conditionals, scattered special cases, or one-off branches inserted into unrelated flows.
|
|
42
|
+
- If a change adds "weird if statements in random places", treat that as a design problem, not a stylistic nit.
|
|
43
|
+
- Prefer pushing the logic into a dedicated abstraction, helper, state machine, policy object, or separate module instead of tangling an existing path.
|
|
44
|
+
- Call out changes that make the surrounding code harder to reason about, even if they technically work.
|
|
45
|
+
|
|
46
|
+
3. **Bias toward cleaning the design, not just accepting working code.**
|
|
47
|
+
- If behavior can stay the same while the structure becomes meaningfully cleaner, push for the cleaner version.
|
|
48
|
+
- Do not rubber-stamp "it works" implementations that leave the codebase messier.
|
|
49
|
+
- Strongly prefer simplifications that remove moving pieces altogether over refactors that merely spread the same complexity around.
|
|
50
|
+
|
|
51
|
+
4. **Prefer direct, boring, maintainable code over hacky or magical code.**
|
|
52
|
+
- Treat brittle, ad-hoc, or "magic" behavior as a code-quality problem.
|
|
53
|
+
- Be skeptical of generic mechanisms that hide simple data-shape assumptions.
|
|
54
|
+
- Flag thin abstractions, identity wrappers, or pass-through helpers that add indirection without buying clarity.
|
|
55
|
+
|
|
56
|
+
5. **Push hard on type and boundary cleanliness when they affect maintainability.**
|
|
57
|
+
- Question unnecessary optionality, `unknown`, `any`, or cast-heavy code when a clearer type boundary could exist.
|
|
58
|
+
- Prefer explicit typed models or shared contracts over loosely-shaped ad-hoc objects.
|
|
59
|
+
- If a branch relies on silent fallback to paper over an unclear invariant, ask whether the boundary should be made explicit instead.
|
|
60
|
+
|
|
61
|
+
6. **Keep logic in the canonical layer and reuse existing helpers.**
|
|
62
|
+
- Call out feature logic leaking into shared paths or implementation details leaking through APIs.
|
|
63
|
+
- Prefer existing canonical utilities/helpers over bespoke one-offs.
|
|
64
|
+
- Push code toward the right package, service, or module instead of normalizing architectural drift.
|
|
65
|
+
|
|
66
|
+
7. **Treat unnecessary sequential orchestration and non-atomic updates as design smells when the cleaner structure is obvious.**
|
|
67
|
+
- If independent work is serialized for no good reason, ask whether the flow should run in parallel instead.
|
|
68
|
+
- If related updates can leave state half-applied, push for a more atomic structure.
|
|
69
|
+
- Do not over-index on micro-optimizations, but do flag avoidable orchestration complexity that makes the implementation more brittle.
|
|
70
|
+
|
|
71
|
+
## Primary Review Questions
|
|
72
|
+
|
|
73
|
+
For every meaningful change, ask:
|
|
74
|
+
|
|
75
|
+
- Is there a "code judo" move that would make this dramatically simpler?
|
|
76
|
+
- Can this change be reframed so fewer concepts, branches, or helper layers are needed?
|
|
77
|
+
- Does this improve or worsen the local architecture?
|
|
78
|
+
- Did the diff add branching complexity where a better abstraction should exist?
|
|
79
|
+
- Did a previously cohesive module become more coupled, more stateful, or harder to scan?
|
|
80
|
+
- Is this logic living in the right file and layer?
|
|
81
|
+
- Did this change enlarge a file or component past a healthy size boundary?
|
|
82
|
+
- Are there repeated conditionals that signal a missing model or missing helper?
|
|
83
|
+
- Is the implementation direct and legible, or does it rely on special cases and incidental control flow?
|
|
84
|
+
- Is this abstraction actually earning its keep, or is it just a wrapper?
|
|
85
|
+
- Did the diff introduce casts, optionality, or ad-hoc object shapes that obscure the real invariant?
|
|
86
|
+
- Is this logic living in the canonical layer, or did the diff leak details across a boundary?
|
|
87
|
+
- Is this orchestration more sequential or less atomic than it needs to be?
|
|
88
|
+
|
|
89
|
+
## What to Flag Aggressively
|
|
90
|
+
|
|
91
|
+
Escalate findings when you see:
|
|
92
|
+
|
|
93
|
+
- A complicated implementation where a cleaner reframing could delete whole categories of complexity.
|
|
94
|
+
- Refactors that move code around but fail to reduce the number of concepts a reader must hold in their head.
|
|
95
|
+
- A file crossing 1000 lines due to the PR, especially if the new code could be split out.
|
|
96
|
+
- New conditionals bolted onto unrelated code paths.
|
|
97
|
+
- One-off booleans, nullable modes, or flags that complicate existing control flow.
|
|
98
|
+
- Feature-specific logic leaking into general-purpose modules.
|
|
99
|
+
- Generic "magic" handling that hides simple structure and makes the code harder to reason about.
|
|
100
|
+
- Thin wrappers or identity abstractions that add indirection without simplifying anything.
|
|
101
|
+
- Unnecessary casts, `any`, `unknown`, or optional params that muddy the real contract.
|
|
102
|
+
- Copy-pasted logic instead of extracted helpers.
|
|
103
|
+
- Narrow edge-case handling implemented in the middle of an already busy function.
|
|
104
|
+
- Refactors that technically pass tests but make the code less modular or less readable.
|
|
105
|
+
- "Temporary" branching that is likely to become permanent debt.
|
|
106
|
+
- Bespoke helpers where the codebase already has a canonical utility for the job.
|
|
107
|
+
- Logic added in the wrong layer/package when it should live somewhere more central.
|
|
108
|
+
- Sequential async flow where obviously independent work could stay simpler and clearer with parallel execution.
|
|
109
|
+
- Partial-update logic that leaves state less atomic than necessary.
|
|
110
|
+
|
|
111
|
+
## Preferred Remedies
|
|
112
|
+
|
|
113
|
+
When you identify a code-quality problem, prefer suggestions like:
|
|
114
|
+
|
|
115
|
+
- Delete a whole layer of indirection rather than polishing it.
|
|
116
|
+
- Reframe the state model so conditionals disappear instead of getting centralized.
|
|
117
|
+
- Change the ownership boundary so the feature becomes a natural extension of an existing abstraction.
|
|
118
|
+
- Turn special-case logic into a simpler default flow with fewer exceptions.
|
|
119
|
+
- Extract a helper or pure function.
|
|
120
|
+
- Split a large file into smaller focused modules.
|
|
121
|
+
- Move feature-specific logic behind a dedicated abstraction.
|
|
122
|
+
- Replace condition chains with a typed model or explicit dispatcher.
|
|
123
|
+
- Separate orchestration from business logic.
|
|
124
|
+
- Collapse duplicate branches into a single clearer flow.
|
|
125
|
+
- Delete wrappers that do not meaningfully clarify the API.
|
|
126
|
+
- Reuse the existing canonical helper instead of introducing a near-duplicate.
|
|
127
|
+
- Make type boundaries more explicit so the control flow gets simpler.
|
|
128
|
+
- Move the logic to the package/module/layer that already owns the concept.
|
|
129
|
+
- Parallelize independent work when that also simplifies the orchestration.
|
|
130
|
+
- Restructure related updates into a more atomic flow when partial state would be harder to reason about.
|
|
131
|
+
|
|
132
|
+
Do not be satisfied with "maybe rename this" feedback when the real issue is structural.
|
|
133
|
+
Do not be satisfied with a merely cleaner version of the same messy idea if there is a plausible path to a much simpler idea.
|
|
134
|
+
|
|
135
|
+
## Review Tone
|
|
136
|
+
|
|
137
|
+
Be direct, serious, and demanding about quality.
|
|
138
|
+
Do not be rude, but do not soften major maintainability issues into mild suggestions.
|
|
139
|
+
If the code is making the codebase messier, say so clearly.
|
|
140
|
+
If the implementation missed an opportunity for a dramatic simplification, say that clearly too.
|
|
141
|
+
|
|
142
|
+
Good phrases:
|
|
143
|
+
|
|
144
|
+
- `this pushes the file past 1k lines. can we decompose this first?`
|
|
145
|
+
- `this adds another special-case branch into an already busy flow. can we move this behind its own abstraction?`
|
|
146
|
+
- `this works, but it makes the surrounding code more spaghetti. let's keep the behavior and restructure the implementation.`
|
|
147
|
+
- `this feels like feature logic leaking into a shared path. can we isolate it?`
|
|
148
|
+
- `this abstraction seems unnecessary. can we just keep the direct flow?`
|
|
149
|
+
- `why does this need a cast / optional here? can we make the boundary more explicit instead?`
|
|
150
|
+
- `this looks like a bespoke helper for something we already have elsewhere. can we reuse the canonical one?`
|
|
151
|
+
- `i think there's a code-judo move here that makes this much simpler. can we reframe this so these branches disappear?`
|
|
152
|
+
- `this refactor moves complexity around, but doesn't really delete it. is there a way to make the model itself simpler?`
|
|
153
|
+
|
|
154
|
+
## Output Expectations
|
|
155
|
+
|
|
156
|
+
Prioritize findings in this order:
|
|
157
|
+
|
|
158
|
+
1. Structural code-quality regressions
|
|
159
|
+
2. Missed opportunities for dramatic simplification / code-judo restructuring
|
|
160
|
+
3. Spaghetti / branching complexity increases
|
|
161
|
+
4. Boundary / abstraction / type-contract problems that make the code harder to reason about
|
|
162
|
+
5. File-size and decomposition concerns
|
|
163
|
+
6. Modularity and abstraction issues
|
|
164
|
+
7. Legibility and maintainability concerns
|
|
165
|
+
|
|
166
|
+
Do not flood the review with low-value nits if there are larger structural issues.
|
|
167
|
+
Prefer a smaller number of high-conviction comments over a long list of cosmetic notes.
|
|
168
|
+
|
|
169
|
+
## Approval Bar
|
|
170
|
+
|
|
171
|
+
Do not approve merely because behavior seems correct.
|
|
172
|
+
The bar for approval is:
|
|
173
|
+
|
|
174
|
+
- no clear structural regression
|
|
175
|
+
- no obvious missed opportunity to make the implementation dramatically simpler when such a path is visible
|
|
176
|
+
- no unjustified file-size explosion
|
|
177
|
+
- no obvious spaghetti-growth from special-case branching
|
|
178
|
+
- no obviously hacky or magical abstraction that makes the code harder to reason about
|
|
179
|
+
- no unnecessary wrapper/cast/optionality churn obscuring the real design
|
|
180
|
+
- no clear architecture-boundary leak or avoidable canonical-helper duplication
|
|
181
|
+
- no missed opportunity for an obvious decomposition that would materially improve maintainability
|
|
182
|
+
|
|
183
|
+
Treat these as presumptive blockers unless the author can justify them clearly:
|
|
184
|
+
|
|
185
|
+
- the PR preserves a lot of incidental complexity when there is a plausible code-judo move that would delete it
|
|
186
|
+
- the PR pushes a file from below 1000 lines to above 1000 lines
|
|
187
|
+
- the PR adds ad-hoc branching that makes an existing flow more tangled
|
|
188
|
+
- the PR solves a local problem by scattering feature checks across shared code
|
|
189
|
+
- the PR adds an unnecessary abstraction, wrapper, or cast-heavy contract that makes the design more indirect
|
|
190
|
+
- the PR duplicates an existing helper or puts logic in the wrong layer when there is a clear canonical home
|
|
191
|
+
|
|
192
|
+
If those conditions are not met, leave explicit, actionable feedback and push for a cleaner decomposition.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: typescript-exhaustive-switch
|
|
3
|
+
description: Use exhaustive switch handling for TypeScript unions and enums
|
|
4
|
+
disable-model-invocation: true
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Typescript Exhaustive Switch
|
|
8
|
+
|
|
9
|
+
typescript-exhaustive-switch: In switch statements over discriminated unions or enums, use a `never` check in the default case so newly added variants cause compile-time failures until handled.
|
|
10
|
+
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: verify-this
|
|
3
|
+
description: "Verify a claim with fresh local evidence: restate it falsifiably, capture baseline and treatment, compare artifacts, and return VERIFIED, NOT VERIFIED, or INCONCLUSIVE."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Verify This
|
|
7
|
+
|
|
8
|
+
Verification is not a recap. It proves or disproves a specific claim with repeatable evidence.
|
|
9
|
+
|
|
10
|
+
## When To Use
|
|
11
|
+
|
|
12
|
+
- The user asks "verify this", "prove it works", "did this fix it", or "show me the evidence".
|
|
13
|
+
- A bug fix needs a before/after repro.
|
|
14
|
+
- A UI, CLI, API, performance, or memory claim needs measurement.
|
|
15
|
+
- A test passes but the user-visible behavior still needs confirmation.
|
|
16
|
+
|
|
17
|
+
Do not use this for vague claims like "the code is cleaner". Ask for a measurable claim first.
|
|
18
|
+
|
|
19
|
+
## Workflow
|
|
20
|
+
|
|
21
|
+
1. Restate the claim in falsifiable form: condition, metric, and threshold.
|
|
22
|
+
2. Pick the smallest local surface that can disprove it.
|
|
23
|
+
3. Capture a baseline from the old state: merge base, parent commit, failing branch, or current broken repro.
|
|
24
|
+
4. Capture treatment from the changed state with the same command, data, warmup, and environment.
|
|
25
|
+
5. Compare raw artifacts: numbers, screenshots, terminal transcripts, HTTP responses, profiles, heap snapshots, or test output.
|
|
26
|
+
6. Return exactly one verdict: `VERIFIED`, `NOT VERIFIED`, or `INCONCLUSIVE`.
|
|
27
|
+
|
|
28
|
+
## Local Surfaces
|
|
29
|
+
|
|
30
|
+
- Code behavior: focused unit/integration tests or a minimal repro script.
|
|
31
|
+
- CLI/TUI behavior: `control-cli`, terminal transcript, or demo recording.
|
|
32
|
+
- UI behavior: `control-ui`, screenshots, accessibility snapshots, or browser traces.
|
|
33
|
+
- API behavior: local HTTP/RPC request and response diff.
|
|
34
|
+
- Performance: same-machine baseline/treatment timings or CPU profiles.
|
|
35
|
+
- Memory: heap snapshots before and after the suspected operation.
|
|
36
|
+
|
|
37
|
+
## Artifact Layout
|
|
38
|
+
|
|
39
|
+
When safe to write artifacts:
|
|
40
|
+
|
|
41
|
+
```text
|
|
42
|
+
/tmp/verify-this/<claim-slug>/
|
|
43
|
+
├── claim.md
|
|
44
|
+
├── timeline.md
|
|
45
|
+
├── baseline/
|
|
46
|
+
├── treatment/
|
|
47
|
+
├── diff/
|
|
48
|
+
└── verdict.md
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
If artifacts may contain sensitive code, prompts, screenshots, HTTP bodies, or heap data, keep only the minimal inline evidence unless the user agrees to disk storage.
|
|
52
|
+
|
|
53
|
+
## Verdict Rules
|
|
54
|
+
|
|
55
|
+
- `VERIFIED`: baseline and treatment differ in the predicted direction, by the claimed threshold, with no obvious confound.
|
|
56
|
+
- `NOT VERIFIED`: the behavior is unchanged, moves the wrong way, or misses the threshold.
|
|
57
|
+
- `INCONCLUSIVE`: no valid baseline, noisy signal, failed measurement, or an environment difference invalidates the comparison.
|
|
58
|
+
|
|
59
|
+
## Output
|
|
60
|
+
|
|
61
|
+
Use this shape:
|
|
62
|
+
|
|
63
|
+
```text
|
|
64
|
+
VERIFIED | NOT VERIFIED | INCONCLUSIVE
|
|
65
|
+
Claim: <falsifiable claim>
|
|
66
|
+
|
|
67
|
+
Evidence:
|
|
68
|
+
<metric/artifact>: baseline=<...>, treatment=<...>, delta=<...>, threshold=<...>
|
|
69
|
+
|
|
70
|
+
Reasoning:
|
|
71
|
+
<one tight paragraph naming the evidence and any confounds>
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Do not soften a negative result. A clear `NOT VERIFIED` is useful.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: weekly-review
|
|
3
|
+
description: Produce a weekly synthesis of authored commits with highlights by bugfix, tech debt, and net-new work
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Weekly review
|
|
7
|
+
|
|
8
|
+
## Trigger
|
|
9
|
+
|
|
10
|
+
Need a weekly recap of shipped work for status updates, retros, or planning.
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
1. Determine the current git user email from repo config.
|
|
15
|
+
2. Collect authored commits from the last 7-10 days on the primary branch context.
|
|
16
|
+
3. Exclude merge commits.
|
|
17
|
+
4. Group meaningful changes into 2-5 concise bullets.
|
|
18
|
+
5. Add a short classification paragraph covering:
|
|
19
|
+
- likely bug fixes
|
|
20
|
+
- likely tech debt work
|
|
21
|
+
- likely net-new functionality
|
|
22
|
+
|
|
23
|
+
## Guardrails
|
|
24
|
+
|
|
25
|
+
- Keep the recap short and executive-readable.
|
|
26
|
+
- Base claims only on commit history and diffs.
|
|
27
|
+
- If git email is missing, ask the user to set it before proceeding.
|
|
28
|
+
|
|
29
|
+
## Output
|
|
30
|
+
|
|
31
|
+
- 2-5 bullet weekly summary
|
|
32
|
+
- Brief classification paragraph (bugfix / tech debt / net-new)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: what-did-i-get-done
|
|
3
|
+
description: Summarize authored commits over a user-specified time period into a concise update
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# What did I get done
|
|
7
|
+
|
|
8
|
+
## Trigger
|
|
9
|
+
|
|
10
|
+
Need a short, high-signal summary of work completed in a specific time range (for example: yesterday, last 3 days, or last week).
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
1. Resolve the requested time window into concrete dates.
|
|
15
|
+
2. Read commits authored by the current git user email within that range.
|
|
16
|
+
3. Exclude merge commits and uncommitted changes.
|
|
17
|
+
4. Synthesize the most important shipped changes into a concise status update.
|
|
18
|
+
5. Include the actual date range used in the final summary.
|
|
19
|
+
|
|
20
|
+
## Guardrails
|
|
21
|
+
|
|
22
|
+
- Be extremely concise and information-dense.
|
|
23
|
+
- Prioritize substantial behavior or architecture changes.
|
|
24
|
+
- Omit cosmetic-only changes (formatting, imports, minor renames).
|
|
25
|
+
- Do not infer intent or motivation. Describe changes functionally.
|
|
26
|
+
|
|
27
|
+
## Output
|
|
28
|
+
|
|
29
|
+
- One short summary suitable for a status update
|
|
30
|
+
- Real date range
|
|
31
|
+
- Optional 2-5 bullets for major changes only
|
package/skills/why/SKILL.md
CHANGED
|
@@ -8,7 +8,7 @@ disable-model-invocation: true
|
|
|
8
8
|
|
|
9
9
|
Investigate the motivation and intent behind code. The companion `how` skill answers what the code does and how it works. `why` answers what forces led to its shape.
|
|
10
10
|
|
|
11
|
-
Each spawn below names a role line in the model rule
|
|
11
|
+
Each spawn below names a role line in the model rule at the path the system prompt names and a default. Set `model` to that line's value, or to the default if the rule or the line is missing. Leave `model` unset when the value is `auto` or `inherit-parent`. If the Task tool rejects a slug, use the default and say so. If it rejects the default, use the closest valid slug of the same family from its error message. Pick each subagent's reasoning level (the `:<level>` suffix), and fast or standard speed when the model has a `-fast` variant, for the job, per the Subagents section of the **poteto-mode** skill.
|
|
12
12
|
|
|
13
13
|
Every spawn is `generalPurpose` with `readonly: false` (or `readonly` unset). **Do not set `readonly: true`.** It strips MCP access, which disables the MCP-backed investigators and the synthesizer's citation spot-checks. Investigators still shouldn't write anything.
|
|
14
14
|
|
|
@@ -46,7 +46,7 @@ Map each available MCP to one evidence category:
|
|
|
46
46
|
|
|
47
47
|
Source control is always available through git and `gh`. For the other six, classify using the MCP name, server instructions, tool names, and resource descriptors. If an MCP could fit more than one category, choose the one matching its primary evidence. Record ambiguous cases in the coverage map.
|
|
48
48
|
|
|
49
|
-
Spawn one investigator per category that has a matching MCP, all in a single message so they run concurrently, each owning exactly one tool or MCP. Don't ask one agent to cover multiple MCPs. `model`: the `why investigators` line, default `grok-4.7
|
|
49
|
+
Spawn one investigator per category that has a matching MCP, all in a single message so they run concurrently, each owning exactly one tool or MCP. Don't ask one agent to cover multiple MCPs. `model`: the `why investigators` line, default `grok-4.7[effort=xhigh,fast=true]`.
|
|
50
50
|
|
|
51
51
|
Each investigator's prompt is `references/investigator-prompt.md` filled in, plus:
|
|
52
52
|
- the category playbook `references/sources/<source>.md` for the selected MCP, adapted from the examples in `references/source-playbook.md`
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: workflow-from-chats
|
|
3
|
+
description: Extract durable working preferences from recent Pi chats and convert them into skills, rules, or workflow docs. Use when asked to learn preferences, mine feedback, personalize workflows, or generate team/person-specific agent guidance.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Workflow From Chats
|
|
7
|
+
|
|
8
|
+
Infer durable working preferences from recent chats. Do not summarize chats; extract reusable workflow guidance.
|
|
9
|
+
|
|
10
|
+
## Scope
|
|
11
|
+
|
|
12
|
+
- Default to the last 7 days unless the user asks for a different window.
|
|
13
|
+
- Read parent transcripts and relevant subagent transcripts. Use subagent content as evidence, but cite only parent conversations.
|
|
14
|
+
- Do not expose local transcript paths, secrets, customer data, private chat content, or credentials.
|
|
15
|
+
|
|
16
|
+
## Workflow
|
|
17
|
+
|
|
18
|
+
1. State the target workflow or preference surface in one paragraph.
|
|
19
|
+
2. Build an internal transcript inventory: title/topic, parent conversation ID, approximate date, completion state, relevant subagents, and why it may contain preference evidence.
|
|
20
|
+
3. Scan for explicit preferences, corrections, and workflow markers such as "I prefer", "always", "never", "not what I asked", "stop", "review", "PR", "CI", "logs", and "skill".
|
|
21
|
+
4. Extract preference atoms: trigger, workflow step, decision rule, quality bar, stop condition, evidence, and confidence.
|
|
22
|
+
5. Rate confidence as strong, medium, weak, or contradicted.
|
|
23
|
+
6. Cluster by workflow shape rather than transcript: shipping, review, simplification, debugging, capture, communication, delegation, or validation.
|
|
24
|
+
7. Choose the artifact: new skill, skill edit, rule, workflow doc, or no artifact.
|
|
25
|
+
8. Draft only the reusable guidance. Filter anecdotes that will not help future tasks.
|
|
26
|
+
|
|
27
|
+
## Confidence
|
|
28
|
+
|
|
29
|
+
- Strong: explicit user preference, workflow-changing correction, repeated parent-chat pattern, or direct request to encode behavior.
|
|
30
|
+
- Medium: accepted workflow, repeated tool/model/validation preference, or subagent consensus that the parent used successfully.
|
|
31
|
+
- Weak: agent-chosen behavior with no user feedback, one ambiguous transcript, or a likely task-specific correction.
|
|
32
|
+
- Contradicted: evidence points in incompatible directions; ask the user before writing files.
|
|
33
|
+
|
|
34
|
+
## Artifact Choice
|
|
35
|
+
|
|
36
|
+
- Skill: recurring multi-step workflow with clear triggers.
|
|
37
|
+
- Rule: general behavior that should apply broadly.
|
|
38
|
+
- Workflow doc: useful context that is not reliably triggerable.
|
|
39
|
+
- No artifact: situational, stale, or low-confidence observation.
|
|
40
|
+
|
|
41
|
+
## Output
|
|
42
|
+
|
|
43
|
+
Return a concise synthesis first:
|
|
44
|
+
|
|
45
|
+
- Target workflow.
|
|
46
|
+
- Evidence corpus with parent conversation citations only.
|
|
47
|
+
- Preference profile.
|
|
48
|
+
- Adopt, consider, dismissed.
|
|
49
|
+
- Proposed artifacts.
|
|
50
|
+
- Open questions only if they block writing.
|
package/src/ask.ts
CHANGED
|
@@ -9,17 +9,22 @@ export const OTHER_ID = 'other';
|
|
|
9
9
|
const SKIPPED = 'skipped (no one can answer questions in this session; decide yourself and say what you chose)';
|
|
10
10
|
|
|
11
11
|
export const AskParams = Type.Object({
|
|
12
|
-
title: Type.Optional(Type.String({ description: '
|
|
12
|
+
title: Type.Optional(Type.String({ description: 'Optional title for the questions form' })),
|
|
13
13
|
questions: Type.Array(
|
|
14
14
|
Type.Object({
|
|
15
|
-
id: Type.String({ description: '
|
|
16
|
-
prompt: Type.String({ description: 'The question
|
|
17
|
-
options: Type.Array(
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
15
|
+
id: Type.String({ description: 'Unique identifier for this question' }),
|
|
16
|
+
prompt: Type.String({ description: 'The question text to display to the user, without the options.' }),
|
|
17
|
+
options: Type.Array(
|
|
18
|
+
Type.Object({
|
|
19
|
+
id: Type.String({ description: 'Unique identifier for this option' }),
|
|
20
|
+
label: Type.String({ description: 'Display text for this option' }),
|
|
21
|
+
description: Type.Optional(Type.String({ description: 'Detail shown after the label' })),
|
|
22
|
+
}),
|
|
23
|
+
{ minItems: 2, description: 'Array of answer options (minimum 2 required)' },
|
|
24
|
+
),
|
|
25
|
+
allow_multiple: Type.Optional(Type.Boolean({ description: 'If true, the user can select several options. Defaults to false.' })),
|
|
21
26
|
}),
|
|
22
|
-
{ description: 'Questions
|
|
27
|
+
{ minItems: 1, description: 'Questions to present to the user, one after another (minimum 1 required)' },
|
|
23
28
|
),
|
|
24
29
|
});
|
|
25
30
|
export type Question = Static<typeof AskParams>['questions'][number];
|
|
@@ -102,8 +107,17 @@ export function registerAskQuestion(pi: ExtensionAPI): void {
|
|
|
102
107
|
pi.registerTool({
|
|
103
108
|
name: 'AskQuestion',
|
|
104
109
|
label: 'Ask question',
|
|
105
|
-
description:
|
|
106
|
-
|
|
110
|
+
description: [
|
|
111
|
+
"Collect structured multiple-choice answers from the user. Use this tool only when you are blocked on a decision that is genuinely the user's to make: one you cannot resolve from the request, the code, or sensible defaults.",
|
|
112
|
+
'',
|
|
113
|
+
'Usage notes:',
|
|
114
|
+
'- Give each question at least 2 options.',
|
|
115
|
+
'- The user can always pick "Other" and type an answer, which comes back as other with the text.',
|
|
116
|
+
'- Set allow_multiple: true to let the user pick several options.',
|
|
117
|
+
'- If you recommend an option, put it first and end its label with "(Recommended)".',
|
|
118
|
+
'',
|
|
119
|
+
'Prefer this tool over listing options in your reply text as letters, numbers, or bullets.',
|
|
120
|
+
].join('\n'),
|
|
107
121
|
promptSnippet: 'Structured multiple-choice questions for the user',
|
|
108
122
|
parameters: AskParams,
|
|
109
123
|
exposure: 'model-only',
|
package/src/child-env.ts
CHANGED
|
@@ -6,6 +6,7 @@ export const PARENT_ENV = 'PI_PSTACK_PARENT_PID';
|
|
|
6
6
|
export const READONLY_ENV = 'PI_PSTACK_READONLY';
|
|
7
7
|
export const ROOT_STORE_ENV = 'PI_PSTACK_ROOT_STORE';
|
|
8
8
|
export const WORKSPACE_ENV = 'PI_PSTACK_WORKSPACE_STATE';
|
|
9
|
+
export const ROOT_WORKSPACE_ENV = 'PI_PSTACK_ROOT_WORKSPACE';
|
|
9
10
|
|
|
10
11
|
export interface ChildIdentity {
|
|
11
12
|
depth: number;
|
|
@@ -15,6 +16,8 @@ export interface ChildIdentity {
|
|
|
15
16
|
rootStore: string | undefined;
|
|
16
17
|
/** The main chat's workspace state folder, which every agent in the tree shares, an isolated worker included. */
|
|
17
18
|
workspaceState: string | undefined;
|
|
19
|
+
/** The main chat's working directory, which authorizes every record stored in its shared workspace. */
|
|
20
|
+
rootWorkspace: string | undefined;
|
|
18
21
|
}
|
|
19
22
|
|
|
20
23
|
function read(): ChildIdentity {
|
|
@@ -27,6 +30,7 @@ function read(): ChildIdentity {
|
|
|
27
30
|
readonly: process.env[READONLY_ENV] === '1',
|
|
28
31
|
rootStore: process.env[ROOT_STORE_ENV] || undefined,
|
|
29
32
|
workspaceState: process.env[WORKSPACE_ENV] || undefined,
|
|
33
|
+
rootWorkspace: process.env[ROOT_WORKSPACE_ENV] || undefined,
|
|
30
34
|
};
|
|
31
35
|
}
|
|
32
36
|
|
|
@@ -37,8 +41,17 @@ delete process.env[PARENT_ENV];
|
|
|
37
41
|
delete process.env[READONLY_ENV];
|
|
38
42
|
delete process.env[ROOT_STORE_ENV];
|
|
39
43
|
delete process.env[WORKSPACE_ENV];
|
|
44
|
+
delete process.env[ROOT_WORKSPACE_ENV];
|
|
40
45
|
|
|
41
46
|
/** Variables for a child of this process at `depth` (an agent keeps the depth it was created at). */
|
|
42
|
-
export function childVariables(agentType: string, depth: number, readonly: boolean, rootStore: string, workspaceState: string): Record<string, string> {
|
|
43
|
-
return {
|
|
47
|
+
export function childVariables(agentType: string, depth: number, readonly: boolean, rootStore: string, workspaceState: string, rootWorkspace: string): Record<string, string> {
|
|
48
|
+
return {
|
|
49
|
+
[DEPTH_ENV]: String(depth),
|
|
50
|
+
[AGENT_ENV]: agentType,
|
|
51
|
+
[PARENT_ENV]: String(process.pid),
|
|
52
|
+
[ROOT_STORE_ENV]: rootStore,
|
|
53
|
+
[WORKSPACE_ENV]: workspaceState,
|
|
54
|
+
[ROOT_WORKSPACE_ENV]: rootWorkspace,
|
|
55
|
+
...(readonly ? { [READONLY_ENV]: '1' } : {}),
|
|
56
|
+
};
|
|
44
57
|
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { basename, extname, isAbsolute, join, resolve } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { detectSupportedImageMimeTypeFromFile, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
5
|
+
import { Type } from 'typebox';
|
|
6
|
+
|
|
7
|
+
export const GENERATE_IMAGE = 'GenerateImage';
|
|
8
|
+
|
|
9
|
+
const ASPECT_RATIOS = ['1:1', '4:3', '3:4', '16:9', '9:16'] as const;
|
|
10
|
+
const EXTENSIONS: Record<string, string> = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'image/webp': '.webp' };
|
|
11
|
+
|
|
12
|
+
// Cursor's GenerateImage rules: explicit requests only, no data charts, a concrete description, and no Markdown echo.
|
|
13
|
+
const DESCRIPTION = [
|
|
14
|
+
'Generate an image file from a text description.',
|
|
15
|
+
'',
|
|
16
|
+
'Use this tool only when the user explicitly asks for an image; do not generate images just to be helpful. Do not use it for data-heavy visuals such as charts, plots, or tables; make those with code or the visualize tool.',
|
|
17
|
+
'',
|
|
18
|
+
'Describe the image concretely first: the subjects, layout, style, colors, any text, and constraints, in at least 6 words. A description of 3 words or fewer is rejected. Set aspect_ratio when the user asks for one, and pass reference images in reference_image_paths.',
|
|
19
|
+
'The result shows the generated image and names the saved file, so do not repeat the image as Markdown in your reply.',
|
|
20
|
+
].join('\n');
|
|
21
|
+
|
|
22
|
+
const Params = Type.Object({
|
|
23
|
+
description: Type.String({ description: 'A detailed description of the image, at least 6 words. Descriptions of 3 words or fewer are rejected.' }),
|
|
24
|
+
filename: Type.Optional(Type.String({ description: "Optional file name for the image, such as 'diagram.png', without a directory. Defaults to a timestamped name." })),
|
|
25
|
+
reference_image_paths: Type.Optional(Type.Array(Type.String(), { description: 'Optional paths of reference images to use as additional inputs.' })),
|
|
26
|
+
aspect_ratio: Type.Optional(Type.Enum(ASPECT_RATIOS, { type: 'string', description: 'Optional aspect ratio: "1:1", "4:3", "3:4", "16:9", or "9:16".' })),
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
type ImageBlock = { type: 'image'; data: string; mimeType: string };
|
|
30
|
+
|
|
31
|
+
async function referenceImage(path: string, cwd: string): Promise<ImageBlock> {
|
|
32
|
+
const absolute = isAbsolute(path) ? path : resolve(cwd, path);
|
|
33
|
+
const mimeType = await detectSupportedImageMimeTypeFromFile(absolute);
|
|
34
|
+
if (mimeType === null) throw new Error(`reference_image_paths: ${absolute} is not a PNG, JPEG, GIF, or WebP image.`);
|
|
35
|
+
return { type: 'image', data: readFileSync(absolute).toString('base64'), mimeType };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The saved file name: the requested name without any directory, with the extension the image data has. */
|
|
39
|
+
export function imageFileName(requested: string | undefined, mimeType: string, index: number, now: Date): string {
|
|
40
|
+
const extension = EXTENSIONS[mimeType] ?? '.png';
|
|
41
|
+
const base = requested === undefined || basename(requested).trim() === '' ? `image-${now.toISOString().replace(/[:.]/g, '-')}` : basename(requested, extname(requested));
|
|
42
|
+
return `${base}${index === 0 ? '' : `-${index + 1}`}${extension}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The first image model Pi can call with the configured credentials. */
|
|
46
|
+
async function imageModel(ctx: ExtensionContext) {
|
|
47
|
+
const [model] = await ctx.modelRegistry.getAvailableOfType('image');
|
|
48
|
+
return model;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Cursor's GenerateImage on Pi's image models, offered when one is available. Images save to the session's artifacts folder. */
|
|
52
|
+
export interface GenerateImageOptions {
|
|
53
|
+
artifactsDir: (ctx: ExtensionContext) => string;
|
|
54
|
+
/** False where the session may not write files: a readonly subagent, or plan mode. */
|
|
55
|
+
mayOffer: () => boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function registerGenerateImage(pi: ExtensionAPI, options: GenerateImageOptions): void {
|
|
59
|
+
pi.registerTool({
|
|
60
|
+
name: GENERATE_IMAGE,
|
|
61
|
+
label: 'Generate image',
|
|
62
|
+
description: DESCRIPTION,
|
|
63
|
+
promptSnippet: 'Generate an image file from a text description',
|
|
64
|
+
parameters: Params,
|
|
65
|
+
defaultActive: false,
|
|
66
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
67
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
68
|
+
if (params.description.trim().split(/\s+/).length <= 3) throw new Error('Describe the image in at least 6 words. Descriptions of 3 words or fewer are rejected.');
|
|
69
|
+
const model = await imageModel(ctx);
|
|
70
|
+
if (model === undefined) throw new Error('No image model is available. Configure one, such as an OpenRouter image model, to generate images.');
|
|
71
|
+
const references = await Promise.all((params.reference_image_paths ?? []).map((path) => referenceImage(path, ctx.cwd)));
|
|
72
|
+
const text = params.aspect_ratio === undefined ? params.description.trim() : `${params.description.trim()}\n\nAspect ratio: ${params.aspect_ratio}.`;
|
|
73
|
+
const result = await ctx.modelRegistry.generateImages(model, { input: [{ type: 'text', text }, ...references] }, signal === undefined ? undefined : { signal });
|
|
74
|
+
if (result.stopReason !== 'stop') throw new Error(`Image generation failed: ${result.errorMessage ?? result.stopReason}`);
|
|
75
|
+
const images = result.output.filter((block): block is ImageBlock => block.type === 'image');
|
|
76
|
+
if (images.length === 0) throw new Error('The image model returned no image.');
|
|
77
|
+
const dir = options.artifactsDir(ctx);
|
|
78
|
+
mkdirSync(dir, { recursive: true });
|
|
79
|
+
const now = new Date();
|
|
80
|
+
const paths = images.map((image, index) => {
|
|
81
|
+
const path = join(dir, imageFileName(params.filename, image.mimeType, index, now));
|
|
82
|
+
writeFileSync(path, Buffer.from(image.data, 'base64'));
|
|
83
|
+
return path;
|
|
84
|
+
});
|
|
85
|
+
return {
|
|
86
|
+
content: [{ type: 'text' as const, text: `Generated ${paths.length === 1 ? 'an image' : `${paths.length} images`} with ${model.provider}/${model.id}, saved to ${paths.join(', ')}.` }, ...images],
|
|
87
|
+
details: { paths, model: `${model.provider}/${model.id}` },
|
|
88
|
+
};
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
// The tool is on only while an image model is available, as Cursor offers GenerateImage only where it can run.
|
|
93
|
+
pi.on('session_start', async (_event, ctx) => {
|
|
94
|
+
if (!options.mayOffer() || (await imageModel(ctx)) === undefined) return;
|
|
95
|
+
const active = pi.getActiveTools();
|
|
96
|
+
if (!active.includes(GENERATE_IMAGE)) pi.setActiveTools([...active, GENERATE_IMAGE]);
|
|
97
|
+
});
|
|
98
|
+
}
|