pi-mipmux 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Warren Winter
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,119 @@
1
- # Temporary Holding Version
1
+ # pi-mipmux
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ pi-mipmux is a [Pi](https://pi.dev) extension for mipmux. Its `/mipmux` command opens a panel where you choose the folders that the agent's context packets come from, and set build preferences such as the budget and the discovery model. The extension applies these choices to the agent's `context_builder` and `context_prepare` calls before Pi sends them to mipmux.
4
+
5
+ ## Install
6
+
7
+ pi-mipmux needs mipmux connected to Pi as an MCP server named `mipmux`, and the `mipmux` command on your PATH; the [mipmux quickstart](https://github.com/w-winter/mipmux#quickstart) covers building and configuring it. With Pi's built-in MCP support:
8
+
9
+ ```sh
10
+ pi mcp add mipmux -- mipmux mcp
11
+ pi install npm:pi-mipmux
12
+ ```
13
+
14
+ ## Use the panel
15
+
16
+ Run `/mipmux`. The panel lists every setting with the value a build would use now. Highlight a row and press a key:
17
+
18
+ | Key | Action |
19
+ |---|---|
20
+ | ↑ ↓ | Move between rows |
21
+ | Enter | Edit the highlighted value, or open its list |
22
+ | `p` | Pin or unpin the value; a pinned value replaces the value the agent sends |
23
+ | Delete or Backspace | Clear the value, or remove the highlighted item in a list |
24
+ | Ctrl+S | Save every change |
25
+ | Esc or Ctrl+C | Go back one screen; on the main screen, close the panel |
26
+
27
+ Nothing changes until you press Ctrl+S. The footer shows `(unsaved)` while changes are waiting, and closing the panel discards them. Saved changes apply from the agent's next mipmux call, with no restart or reconnect.
28
+
29
+ `/mipmux <name>` selects a saved workspace without opening the panel and completes saved names. In RPC mode, `/mipmux` sends the current settings to the client as a notification instead of opening the panel. Print mode (`pi -p`) and JSON mode have no UI, so `/mipmux` shows nothing there.
30
+
31
+ ## Choose a workspace
32
+
33
+ Every build and prepare call names a workspace: the source folders mipmux indexes (its roots) and the output folder where mipmux saves packets. The panel saves workspaces under names so you can select one per session.
34
+
35
+ To create a workspace, press Enter on **Roots** and choose a folder. The workspace is named after that folder, or `name (1)` if the name is taken, and its output folder is `prompt-exports` inside it. Saving creates the output folder if it does not exist. Press Enter on **Roots** again to add or remove folders; a workspace keeps at least one. The other rows change the output folder and edit the ignore rules. **Rename workspace** changes the name; you never have to.
36
+
37
+ Enter on **Selected workspace** opens the list of saved workspaces. Select one for this session, delete one with Delete, start a new one from a folder, save the workspace the agent last declared in this session, or choose none.
38
+
39
+ While a workspace is selected, the agent receives its exact declaration in the system prompt, and the extension blocks a build or prepare call that names any other workspace, repeating the declaration in the error. With nothing selected, the agent chooses its own workspace and only your preferences apply. The extension never selects a workspace for you from Pi's current directory or from what the agent sends.
40
+
41
+ If the selected workspace is renamed or deleted, for example from another session, or `mipmux.json` cannot be read, the extension blocks build and prepare calls until you select a workspace again, and the footer adds `(missing)` or `(file error)` after the name.
42
+
43
+ ## Type paths
44
+
45
+ Root, output folder and ignore rule rows open a path field with completion. Type a path as in a shell: `~` is your home folder, and a relative path starts at Pi's current directory, or at the root for an ignore rule. Root and output fields open with a suggested folder; Ctrl+U clears it.
46
+
47
+ Below the field, the first row is the path you typed, when it names something you can choose. The rows after it are the entries of the folder you are typing in that match the name typed so far, best match first. Matching ignores case, so `~/proj` finds `~/Projects`. Hidden entries appear once the name you type starts with a dot.
48
+
49
+ | Key | Action |
50
+ |---|---|
51
+ | Tab | Complete the typed name to the highlighted entry, as the disk spells it |
52
+ | Shift+Tab | Go up one folder |
53
+ | ↑ ↓ | Highlight another row |
54
+ | Enter | Choose the highlighted row |
55
+
56
+ While a name is partly typed, the best match is highlighted, so typing a few letters and pressing Enter chooses it.
57
+
58
+ ## Leave paths out or bring them back
59
+
60
+ **Ignore rules** edits the `.mipmux_ignore` file at each root of the selected workspace. The file uses gitignore syntax, and mipmux reads it in every folder, so you can also edit it by hand or add one in a subfolder. A plain line leaves paths out. A line starting with `!` brings back a path that another ignore file hides, such as `.repo_ignore`, `.cursorignore`, mipmux's built-in patterns or Git's exclude files. Nothing brings back a path that `.gitignore` hides. As in Git, an ignore file in a deeper folder takes precedence over one in a folder above it, so to bring back a path that a subfolder's ignore file hides, add the `!` line to a `.mipmux_ignore` in that subfolder.
61
+
62
+ In the rule field, type a path inside the root, relative to it, or a pattern such as `*.log`, and put `!` in front to bring the path back. Tab completes the path after the `!`. A chosen path becomes a rule anchored to the root, such as `/node_modules/` or `!docs/investigations/`. Delete removes a highlighted rule. Ctrl+S writes the files you changed, keeping their comments, and refuses to overwrite a file that someone edited while the panel was open.
63
+
64
+ The rules belong to the folder, not to the saved workspace: every workspace and every client that uses the folder applies them, and RepoPrompt CE does not read them. Commit the file to share the rules, or add `.mipmux_ignore` to your global gitignore to keep it out of Git.
65
+
66
+ ## Set preferences
67
+
68
+ | Setting | Applies to | Saved with |
69
+ |---|---|---|
70
+ | Budget, in mipmux's estimated units, such as `210000` or `210k` | builds; preparations only when pinned | the session |
71
+ | Enhancement mode: `augment`, `fullRewrite` or `preserve` | builds | the session |
72
+ | Clarification questions from discovery, with an optional timeout | builds in sessions with a UI | the session |
73
+ | Discovery model, from the models mipmux allows | builds | the session or the selected workspace |
74
+ | Thinking level for the discovery model | builds | the session or the selected workspace |
75
+
76
+ A value you set fills in a setting the agent leaves out. A pinned value replaces the agent's value too. From highest precedence to lowest, a build uses a pinned session value, a pinned workspace value, the agent's value, a session value, a workspace value, and finally the server default.
77
+
78
+ Session choices are recorded in the session itself: resuming or forking a session restores them, and a new session starts with nothing selected. They do not change mipmux's configuration file or other sessions. Changing a preference changes the request, so repeating an earlier build start under the same output name fails with `outputNameConflict`; the extension adds a note saying so, and a new output name solves it.
79
+
80
+ ## Server defaults
81
+
82
+ The **Server defaults (all clients)** section edits mipmux's configuration file, whose path the panel names: the budget and enhancement mode of builds that name none, the discovery model and thinking level, and the allowed models. These apply to every client that uses mipmux, not only Pi. A running mipmux rereads them before each build, so a save takes effect at the next build without a reconnect. If `mipmux config` fails, the section is missing and the panel's header says why; if the file sets up no discovery, only the budget and enhancement mode rows appear.
83
+
84
+ The discovery model and **Allowed models** lists show the models mipmux has credentials for, from `mipmux models`; type to filter them. In **Allowed models**, Enter allows or disallows the highlighted model, and a model that is allowed but has no credentials is marked `no credentials`. Session and workspace model rows offer the discovery model and the allowed models, and mipmux refuses any other.
85
+
86
+ A save changes only the values you changed and keeps the file's other settings, their order and its indentation. It replaces the file only after `mipmux config` accepts the result, and refuses to overwrite a file that someone edited while the panel was open. Other settings in the file, such as the cache path or discovery credentials, apply when mipmux starts again; reconnect it from `/mcp` after editing them by hand.
87
+
88
+ ## Waiting for a build
89
+
90
+ A build can take minutes, and Pi delivers a steering message only after the tool call in progress returns. The extension adds a `mipmux_wait` tool, which waits for a job as `context_job` does with `op: "wait"`, takes the same `jobId` and `durationMs`, and returns mipmux's reply. When you send a steering message during the wait, the wait ends at once with a result telling the agent that the job is still running, so the agent reads your message straight away and waits again afterwards. The job itself never stops, and the interrupted wait leaves no row in Pi's terminal interface; your message appears in its place.
91
+
92
+ The extension blocks `context_job` waits, including those in codemode scripts, with a message that tells the agent to use `mipmux_wait`; status, answers, cancellation and disposal still go through `context_job`. A steering message counts when you send it from Pi's terminal or an RPC client, or when the [pi-queue-steer](https://github.com/tmustier/pi-queue-steer) extension accepts it into its queue. Codemode scripts cannot call `mipmux_wait`, so the agent waits with a direct call.
93
+
94
+ ## Footer
95
+
96
+ While the extension is loaded, Pi's footer shows `mipmux:` and the selected workspace, or `mipmux: no workspace`. The panel's last row, **Show in footer** under **Display**, turns this item on or off for all your sessions. The session where you save applies it at once; other open sessions apply it before their next prompt.
97
+
98
+ ## Storage
99
+
100
+ Saved workspaces and the footer setting are stored in `mipmux.json` in Pi's agent directory (`~/.pi/agent`, or `$PI_CODING_AGENT_DIR`) and shared by all your sessions. The footer setting is its `showInFooter` field; a file without it shows the footer item. A session keeps only the name it selected, so an edit reaches every session on its next call. Saving applies only the workspaces you added, changed or deleted, so changes another session saved while the panel was open remain. Two saved workspaces with the same root folders and output folder, in any order and under any names, are duplicates: saving keeps the earlier one, with its name, discovery model and thinking level, and the panel says which it removed.
101
+
102
+ ## Limits
103
+
104
+ - The extension sees calls that pass through Pi's tool pipeline, including calls from codemode scripts, under the tool names that Pi's built-in MCP support gives a server named `mipmux`: `mcp__mipmux__context_builder` and `mcp__mipmux__context_prepare`. Calls another extension makes outside Pi's tool pipeline bypass it.
105
+ - The panel reads and edits the configuration file that `mipmux config` reports when run from your PATH, and names it at the top. By default that is `~/.config/mipmux/config.json`, or `$XDG_CONFIG_HOME/mipmux/config.json`. If Pi starts mipmux with `--config` or a different `XDG_CONFIG_HOME`, the server uses another file, and the panel's server defaults and model lists do not describe that server.
106
+ - Without a UI, the clarification preference is not applied.
107
+
108
+ ## Development
109
+
110
+ ```sh
111
+ npm test
112
+ npm run typecheck
113
+ ```
114
+
115
+ Both run from this directory and use the TypeScript, TypeBox and Pi packages installed in the mipmux checkout. Two tests run Pi in RPC mode with a scripted model and a stand-in mipmux server.
116
+
117
+ The oh-my-pi extension in [`integrations/omp`](https://github.com/w-winter/mipmux/tree/main/integrations/omp#readme) copies every module in `src` except `extension.ts`, `routes.ts` and `wait.ts`, so after changing one, run that package's checks too.
118
+
119
+ To run the extension from a checkout instead of npm, install it by path: `pi install /absolute/path/to/mipmux/integrations/pi`.
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "pi-mipmux",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Pi extension that selects a saved mipmux workspace and applies build preferences to mipmux calls",
5
+ "license": "Apache-2.0",
6
+ "repository": { "type": "git", "url": "git+https://github.com/w-winter/mipmux.git", "directory": "integrations/pi" },
7
+ "homepage": "https://github.com/w-winter/mipmux/tree/main/integrations/pi#readme",
8
+ "bugs": "https://github.com/w-winter/mipmux/issues",
9
+ "type": "module",
10
+ "keywords": ["pi-package"],
11
+ "files": ["src"],
12
+ "pi": { "extensions": ["./src/extension.ts"] },
13
+ "peerDependencies": {
14
+ "@earendil-works/pi-coding-agent": "*",
15
+ "@earendil-works/pi-tui": "*",
16
+ "typebox": "*"
17
+ },
18
+ "scripts": {
19
+ "test": "node --experimental-strip-types --test test/*.test.ts",
20
+ "typecheck": "tsc -p tsconfig.json"
21
+ }
22
+ }
package/src/config.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import Type, { type Static } from 'typebox';
4
+ import { Compile } from 'typebox/compile';
5
+ import { EnhancementMode, ModelReference, ThinkingLevel } from './state.ts';
6
+
7
+ /** The global defaults `mipmux config` prints: what a build uses for every setting no request or preference names. */
8
+ const MipmuxConfig = Type.Object({ kind: Type.Literal('config'), path: Type.String(), contextBudgetUnits: Type.Integer({ minimum: 1 }),
9
+ defaultEnhancementMode: EnhancementMode, tools: Type.Enum(['core', 'full']),
10
+ discovery: Type.Union([Type.Null(), Type.Object({ model: ModelReference, thinking: ThinkingLevel, allowedModels: Type.Array(ModelReference) },
11
+ { additionalProperties: false })]) }, { additionalProperties: false });
12
+ export type MipmuxConfig = Static<typeof MipmuxConfig>;
13
+ /** The mipmux commands the extension runs: `config` reports the file at `path`, or the default file, and fails when mipmux rejects it. */
14
+ export interface MipmuxCommands {
15
+ config(path?: string): Promise<MipmuxConfig>;
16
+ models(path: string): Promise<string[]>;
17
+ }
18
+ const configValidator = Compile(MipmuxConfig);
19
+
20
+ /**
21
+ * Runs `mipmux config` from PATH, as an MCP client configured with `mipmux mcp` starts the server, so the defaults shown
22
+ * are the ones a newly started server reads. Fails with mipmux's error code, or with the reason the command could not run.
23
+ */
24
+ export async function readMipmuxConfig(path?: string): Promise<MipmuxConfig> {
25
+ const value: unknown = JSON.parse(await mipmux(['config', ...(path === undefined ? [] : ['--config', path])]));
26
+ if (!configValidator.Check(value)) throw new Error('mipmux config printed an unexpected result; update mipmux or the mipmux extension');
27
+ return value;
28
+ }
29
+
30
+ /** Runs mipmux from PATH and returns its output; fails with mipmux's error report, or with the reason the command could not run. */
31
+ async function mipmux(args: readonly string[]): Promise<string> {
32
+ try { return (await promisify(execFile)('mipmux', [...args])).stdout; }
33
+ catch (error) {
34
+ // mipmux reports its failures as JSON on stdout; a command that never ran reports through the error message.
35
+ const stdout = error instanceof Error && 'stdout' in error ? String(error.stdout).trim() : '';
36
+ throw new Error(`mipmux ${args[0]} failed: ${stdout || (error instanceof Error ? error.message : 'unknown error')}`, { cause: error });
37
+ }
38
+ }
39
+
40
+ const ModelList = Compile(Type.Object({ kind: Type.Literal('models'), models: Type.Array(ModelReference) }, { additionalProperties: false }));
41
+
42
+ /** The discovery models mipmux can use with its configured credentials, from `mipmux models`. */
43
+ export async function readMipmuxModels(path: string): Promise<string[]> {
44
+ const value: unknown = JSON.parse(await mipmux(['models', '--config', path]));
45
+ if (!ModelList.Check(value)) throw new Error('mipmux models printed an unexpected result; update mipmux or the mipmux extension');
46
+ return value.models;
47
+ }
package/src/draft.ts ADDED
@@ -0,0 +1,101 @@
1
+ import { basename } from 'node:path';
2
+ import type { ServerDefaults } from './server-config.ts';
3
+ import type { Store } from './store.ts';
4
+ import { type Preferences, type SavedWorkspace, type SessionState, type Workspace } from './state.ts';
5
+
6
+ /*
7
+ * The panel's unsaved changes. The panel edits a draft and writes it only on ctrl+s; closing discards it. A save applies
8
+ * only the saved workspaces the panel added, changed or deleted, so changes another session saved meanwhile survive, and
9
+ * writes only the `.mipmux_ignore` files the panel changed.
10
+ */
11
+ /** A saved workspace in the draft; `origin` is its name in the file when the panel read it, or null for a new one. */
12
+ export interface DraftEntry { readonly origin: string | null; readonly workspace: SavedWorkspace }
13
+ /** The complete new lines of one root's `.mipmux_ignore`. */
14
+ export interface IgnoreEdit { readonly root: string; readonly lines: readonly string[] }
15
+ export interface Draft {
16
+ readonly entries: readonly DraftEntry[];
17
+ readonly selected: string | null;
18
+ readonly preferences: Preferences;
19
+ readonly ignoreEdits: readonly IgnoreEdit[];
20
+ /** mipmux's request defaults, or null when `mipmux config` could not report them. */
21
+ readonly server: ServerDefaults | null;
22
+ /** Whether every session shows the footer item. */
23
+ readonly showInFooter: boolean;
24
+ }
25
+ const rootNamePattern = /^[A-Za-z][A-Za-z0-9_-]*$/;
26
+
27
+ export function openDraft(store: Store, state: SessionState, server: ServerDefaults | null): Draft {
28
+ return { entries: store.workspaces.map(workspace => ({ origin: workspace.name, workspace })), selected: state.selected,
29
+ preferences: state.preferences, ignoreEdits: [], server, showInFooter: store.showInFooter };
30
+ }
31
+
32
+ export function selectedWorkspace(draft: Draft): SavedWorkspace | null {
33
+ return draft.entries.find(entry => entry.workspace.name === draft.selected)?.workspace ?? null;
34
+ }
35
+
36
+ /** `base`, or `base (1)`, `base (2)` and so on, whichever is free first, as RepoPrompt CE names workspaces. */
37
+ export function uniqueName(base: string, taken: readonly string[]): string {
38
+ let name = base;
39
+ for (let counter = 1; taken.includes(name); counter++) name = `${base} (${counter})`;
40
+ return name;
41
+ }
42
+
43
+ /** A root name from the folder's name, in the form mipmux accepts, distinct from the workspace's other roots. */
44
+ function rootName(path: string, roots: Workspace['roots']): string {
45
+ const cleaned = basename(path).replace(/[^A-Za-z0-9_-]/g, '-');
46
+ const base = rootNamePattern.test(cleaned) ? cleaned : `root-${cleaned}`;
47
+ let name = base;
48
+ for (let counter = 2; roots.some(root => root.name === name); counter++) name = `${base}-${counter}`;
49
+ return name;
50
+ }
51
+
52
+ /** Adds the roots and output folder of `workspace`, such as one the agent declared, under a name taken from its first root, and selects it. */
53
+ export function addWorkspace(draft: Draft, workspace: Pick<Workspace, 'roots' | 'outputRoot'>): Draft {
54
+ const first = workspace.roots[0]?.absolutePath ?? 'workspace';
55
+ const name = uniqueName(basename(first), draft.entries.map(entry => entry.workspace.name));
56
+ const added: SavedWorkspace = { name, roots: workspace.roots, outputRoot: workspace.outputRoot };
57
+ return { ...draft, entries: [...draft.entries, { origin: null, workspace: added }], selected: name };
58
+ }
59
+
60
+ /** A new saved workspace with one root, `<root>/prompt-exports` as its output folder, named after the root and selected. */
61
+ export function createFromFolder(draft: Draft, folder: string): Draft {
62
+ return addWorkspace(draft, { roots: [{ name: rootName(folder, []), absolutePath: folder }], outputRoot: `${folder}/prompt-exports` });
63
+ }
64
+
65
+ /** Replaces the selected saved workspace with `change(workspace)`. */
66
+ export function editSelected(draft: Draft, change: (workspace: SavedWorkspace) => SavedWorkspace): Draft {
67
+ return { ...draft, entries: draft.entries.map(entry => entry.workspace.name === draft.selected ? { ...entry, workspace: change(entry.workspace) } : entry) };
68
+ }
69
+
70
+ export function addRoot(workspace: SavedWorkspace, folder: string): SavedWorkspace {
71
+ return { ...workspace, roots: [...workspace.roots, { name: rootName(folder, workspace.roots), absolutePath: folder }] };
72
+ }
73
+
74
+ export function removeRoot(workspace: SavedWorkspace, name: string): SavedWorkspace {
75
+ return { ...workspace, roots: workspace.roots.filter(root => root.name !== name) };
76
+ }
77
+
78
+ /** Renames the selected saved workspace; fails with a reason when the name is empty or taken. */
79
+ export function renameSelected(draft: Draft, name: string): Draft | { readonly problem: string } {
80
+ if (!name) return { problem: 'A name needs at least one character.' };
81
+ if (name !== draft.selected && draft.entries.some(entry => entry.workspace.name === name)) return { problem: `"${name}" is already saved.` };
82
+ return { ...editSelected(draft, workspace => ({ ...workspace, name })), selected: name };
83
+ }
84
+
85
+ export function deleteWorkspace(draft: Draft, name: string): Draft {
86
+ return { ...draft, entries: draft.entries.filter(entry => entry.workspace.name !== name), selected: draft.selected === name ? null : draft.selected };
87
+ }
88
+
89
+ /**
90
+ * The draft's additions, edits and deletions applied to the saved workspaces as the file holds them now: an edit keeps its
91
+ * entry's place, and a new workspace, or one another session deleted meanwhile, is added at the end.
92
+ */
93
+ export function applyDraft(stored: readonly SavedWorkspace[], draft: Draft, snapshot: readonly SavedWorkspace[]): SavedWorkspace[] {
94
+ const unchanged = (entry: DraftEntry) => snapshot.some(saved => saved.name === entry.origin && JSON.stringify(saved) === JSON.stringify(entry.workspace));
95
+ const changed = draft.entries.filter(entry => !unchanged(entry));
96
+ const deleted = snapshot.filter(saved => !draft.entries.some(entry => entry.origin === saved.name)).map(saved => saved.name);
97
+ const kept = stored.filter(saved => !deleted.includes(saved.name))
98
+ .map(saved => changed.find(entry => entry.origin === saved.name)?.workspace ?? saved);
99
+ const added = changed.filter(entry => entry.origin === null || !stored.some(saved => saved.name === entry.origin));
100
+ return [...kept, ...added.map(entry => entry.workspace)];
101
+ }
@@ -0,0 +1,31 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import { getAgentDir, type ExtensionAPI } from '@earendil-works/pi-coding-agent';
4
+ import { readMipmuxConfig, readMipmuxModels } from './config.ts';
5
+ import { createMipmux, entryType, workspaceSection } from './register.ts';
6
+ import { registerSteerableWait } from './wait.ts';
7
+
8
+ /** Registers the /mipmux command and the handlers that apply this session's mipmux choices to the agent's calls. */
9
+ export default function mipmux(pi: ExtensionAPI): void {
10
+ const extension = createMipmux({ storePath: join(getAgentDir(), 'mipmux.json'), home: homedir(), mipmux: { config: readMipmuxConfig, models: readMipmuxModels },
11
+ appendEntry: state => { pi.appendEntry(entryType, state); } });
12
+ pi.on('session_start', (_event, ctx) => extension.restore(ctx));
13
+ pi.on('session_tree', (_event, ctx) => extension.restore(ctx));
14
+ pi.on('before_agent_start', async (event, ctx) => {
15
+ const workspace = await extension.beforeAgentStart(ctx);
16
+ if (workspace !== null) event.systemPromptOptions.sections[workspaceSection] = workspace;
17
+ });
18
+ // Pi runs a call with the arguments as handlers left them, so the edits made in place need no result.
19
+ pi.on('tool_call', async (event, ctx) => {
20
+ const decision = await extension.toolCall(event, ctx);
21
+ return decision.kind === 'blocked' ? { block: true, reason: decision.reason } : undefined;
22
+ });
23
+ pi.on('tool_result', event => {
24
+ const content = extension.toolResult(event);
25
+ if (content === undefined) return undefined;
26
+ return event.structuredContent === undefined ? { content } : { content, structuredContent: event.structuredContent };
27
+ });
28
+ registerSteerableWait(pi);
29
+ pi.registerCommand('mipmux', { description: 'Select a saved mipmux workspace and set build preferences',
30
+ getArgumentCompletions: prefix => extension.completions(prefix), handler: (args, ctx) => extension.command(args, ctx) });
31
+ }
@@ -0,0 +1,82 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import { readFile, rename, writeFile } from 'node:fs/promises';
4
+ import { isAbsolute, join, relative } from 'node:path';
5
+ import { expand, resolveExisting, type PathBase, type PathEntry } from './paths.ts';
6
+
7
+ /*
8
+ * A root's `.mipmux_ignore`, in gitignore syntax. mipmux reads one in every folder; the panel edits the one at each root.
9
+ * Its rules belong to the folder, so they apply to every workspace and client that uses it.
10
+ */
11
+ export const ignoreFileName = '.mipmux_ignore';
12
+ const globCharacters = /[*?[\]]/;
13
+ /** The lines of a root's `.mipmux_ignore` as the panel read them, or why it could not read them. */
14
+ export type IgnoreFile = { readonly kind: 'read'; readonly lines: readonly string[] } | { readonly kind: 'unreadable'; readonly problem: string };
15
+ /** A line the picker would add, or why it refuses the typed text. */
16
+ export type RuleChoice = { readonly kind: 'rule'; readonly line: string } | { readonly kind: 'refused'; readonly reason: string };
17
+
18
+ export const ignoreFilePath = (root: string) => join(root, ignoreFileName);
19
+ /** A line that is a rule rather than a blank line or a comment. */
20
+ export const isRule = (line: string) => line.trim() !== '' && !line.startsWith('#');
21
+
22
+ function lines(text: string): string[] {
23
+ const split = text.split('\n');
24
+ return split.at(-1) === '' ? split.slice(0, -1) : split;
25
+ }
26
+
27
+ /** Reads a root's file; a missing file has no lines. */
28
+ export function readIgnoreFile(root: string): IgnoreFile {
29
+ try { return { kind: 'read', lines: lines(readFileSync(ignoreFilePath(root), 'utf8')) }; }
30
+ catch (error) {
31
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return { kind: 'read', lines: [] };
32
+ return { kind: 'unreadable', problem: error instanceof Error ? error.message : String(error) };
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Replaces a root's file with `next`. Fails, writing nothing, when the file no longer holds `read`, so a hand edit made
38
+ * while the panel was open is never overwritten.
39
+ */
40
+ export async function writeIgnoreFile(root: string, read: readonly string[], next: readonly string[]): Promise<void> {
41
+ const path = ignoreFilePath(root);
42
+ const current = await readFile(path, 'utf8').then(lines, (error: Error & { code?: string }) => {
43
+ if (error.code === 'ENOENT') return [];
44
+ throw error;
45
+ });
46
+ if (JSON.stringify(current) !== JSON.stringify(read)) throw new Error(`${path} changed while the panel was open; close the panel and open it again.`);
47
+ const temporary = join(root, `.mipmux_ignore.${randomUUID()}`);
48
+ await writeFile(temporary, next.map(line => `${line}\n`).join(''));
49
+ await rename(temporary, path);
50
+ }
51
+
52
+ /** The rule for a path inside `root`: relative to it, anchored to it, and ending in `/` for a folder. */
53
+ function pathRule(root: string, path: string, folder: boolean): string | null {
54
+ const under = relative(root, path);
55
+ if (!under || under.startsWith('..') || isAbsolute(under)) return null;
56
+ return (under.includes('/') ? under : `/${under}`) + (folder ? '/' : '');
57
+ }
58
+
59
+ /** The rule for a completion the user chose; `negated` brings the path back instead of leaving it out. */
60
+ export function entryRule(root: string, entry: PathEntry, negated: boolean): string {
61
+ const found = resolveExisting(entry.path);
62
+ return (negated ? '!' : '') + (pathRule(root, found.path, found.kind === 'folder') ?? entry.name);
63
+ }
64
+
65
+ /**
66
+ * The rule for typed text. A leading `!` brings paths back. A path that exists inside the root becomes a rule anchored to
67
+ * the root; `~` or an absolute path must lie inside it. Anything else, such as `*.log` or a path that does not exist yet,
68
+ * is kept as a gitignore pattern as typed.
69
+ */
70
+ export function typedRule(text: string, base: PathBase): RuleChoice {
71
+ if (text.startsWith('#')) return { kind: 'refused', reason: 'A line starting with # is a comment, not a rule.' };
72
+ const negated = text.startsWith('!'), body = negated ? text.slice(1) : text, marker = negated ? '!' : '';
73
+ if (!body) return { kind: 'refused', reason: 'Type a path or a pattern.' };
74
+ if (globCharacters.test(body)) return { kind: 'rule', line: marker + body };
75
+ const found = resolveExisting(expand(body, base));
76
+ const rule = found.kind === 'missing' ? null : pathRule(base.base, found.path, found.kind === 'folder');
77
+ if (rule) return { kind: 'rule', line: marker + rule };
78
+ if (body.startsWith('~') || (isAbsolute(body) && found.kind !== 'missing')) {
79
+ return { kind: 'refused', reason: `That path is outside ${base.base}.` };
80
+ }
81
+ return { kind: 'rule', line: marker + body };
82
+ }