@catronomix/opencode-letmework 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 opencode-letmework authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,195 @@
1
- # Temporary Holding Version
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.
1
+ # opencode-letmework
2
+
3
+ An OpenCode plugin that makes work folders boring: when an action only touches a
4
+ project's **sibling work folder** (`../<project>-wt`, plus a few folders you
5
+ list), the permission prompt answers itself after a short delay instead of
6
+ blocking the agent.
7
+
8
+ The delay is the point. The prompt is published normally, stays visible for
9
+ `waitseconds`, and is only auto-approved if nobody answered it by then — so a
10
+ user who is watching can still reject the action.
11
+
12
+ > **This is a limited YOLO mode.** It answers permission prompts without you
13
+ > looking, and by default it *saves* those answers so the same folder stops
14
+ > prompting. It is only as safe as the folders you allow: the defaults are
15
+ > deliberately narrow (git repositories, sibling work folder only), but adding
16
+ > `C:\` or `/` to `extra-folders` is effectively turning permissions off.
17
+ > Nobody reviews an auto-approved edit. Read the config comments before you
18
+ > widen anything.
19
+
20
+ ## Installing does nothing until you configure it
21
+
22
+ The plugin ships **no active config on purpose**. Without a config file it stays
23
+ completely inert — every prompt waits for you as usual — and the first time it
24
+ sees a permission prompt it drops a one-time note into the session saying so,
25
+ with the exact command to turn it on:
26
+
27
+ ```
28
+ letmework is installed but idle - nothing is being auto-approved.
29
+ reason: C:\Users\you\.config\opencode\letmework.yaml not found
30
+ config: C:\Users\you\.config\opencode\letmework.yaml (not found)
31
+
32
+ To turn it on, copy the example config and edit it:
33
+ Copy-Item "C:\...\opencode-letmework\config.example.yaml" "C:\Users\you\.config\opencode\letmework.yaml"
34
+ ...
35
+ ```
36
+
37
+ The example lives at the **package root**, never inside `dist/`, so the hint
38
+ stays correct for a built install.
39
+
40
+ Once a config is loaded and the plugin actually answers a prompt, it shows a
41
+ similar one-time note in that session: what it approved, which rule allowed it,
42
+ where the config lives, and how to make it quieter. That note is the onboarding
43
+ — no dialogs, no wizards, no first-run state machine.
44
+
45
+ Config is looked up in this order, first hit wins:
46
+
47
+ 1. the `config` plugin option (see below),
48
+ 2. `config.yaml` inside the plugin's own folder (a clone or dev checkout),
49
+ 3. `config.yaml` in the package root, when the plugin runs from a built `dist`
50
+ folder,
51
+ 4. `~/.config/opencode/letmework.yaml` (`$XDG_CONFIG_HOME` respected) — the
52
+ right place for an npm install, which never ships a config.
53
+
54
+ ## What it checks
55
+
56
+ A permission request is auto-approved only when **all** checks pass:
57
+
58
+ 1. **The session folder is a git repository.** Detected by walking up from the
59
+ session directory for a `.git` entry (file or folder, so worktrees count).
60
+ 2. **Every target lives in an allowed folder:**
61
+ - the sibling work folder `../<session folder><suffix>` and anything below it
62
+ (`c:\GITHUB\myProject` → `c:\GITHUB\myProject-wt`), or
63
+ - anything below a folder in `extra-folders`, or
64
+ - anything **strictly below** a folder in `create-and-use` — those folders may
65
+ not be touched directly, but the agent may create subfolders and work there.
66
+ 3. **The action is eligible.** Only actions listed in `actions` qualify, so
67
+ command text (`shell`) never matches a path rule.
68
+ 4. **Resources are path-shaped.** Globs are judged on their literal prefix
69
+ (`C:\temp\**\*.ts` is fine, `C:\GITHUB\proj-*\x` is not), and a resource that
70
+ climbs out with `..` is never approved.
71
+
72
+ Anything else — no git repo, a different sibling, the project folder itself, an
73
+ unlisted action — behaves exactly as before: the prompt waits for you.
74
+
75
+ ## Config
76
+
77
+ `config.yaml` next to the plugin, or the user-level path above (see
78
+ `config.example.yaml`, which is heavily commented):
79
+
80
+ ```yaml
81
+ waitseconds: 5
82
+ suffix: -wt
83
+
84
+ extra-folders: []
85
+ # - /tmp
86
+
87
+ create-and-use: []
88
+ # - /tmp/opencode
89
+
90
+ actions:
91
+ - read
92
+ - edit
93
+ - write
94
+ - external_directory
95
+
96
+ decision: always
97
+ notice: once
98
+ ```
99
+
100
+ - `waitseconds` — grace period before auto-approval (0 approves immediately,
101
+ capped at 600).
102
+ - `suffix` — appended to the session folder's name to build the work folder.
103
+ - `extra-folders` — folders and everything below them; absolute or relative to
104
+ the session folder. Empty by default.
105
+ - `create-and-use` — folders whose subfolders are allowed while the folder itself
106
+ is not. Empty by default.
107
+ - `actions` — permission actions eligible for auto-approval. Defaults to `read`,
108
+ `edit`, `write`, `external_directory`. Narrow it (e.g. `read` only) to stay in
109
+ the loop for edits.
110
+ - `decision` — how the auto-approval is recorded: `always` (default) saves the
111
+ approval so the same target stops prompting, `once` answers only that single
112
+ request and the next one prompts again (with the same grace period).
113
+ - `notice` — the in-session onboarding note: `once` (default), `always`, or
114
+ `off`.
115
+
116
+ Point the plugin at another config file with a plugin option:
117
+
118
+ ```jsonc
119
+ {
120
+ "plugins": [{ "package": "./plugins/opencode-letmework", "options": { "config": "C:/path/config.yaml" } }]
121
+ }
122
+ ```
123
+
124
+ ## Install
125
+
126
+ Add the package to your global config (`~/.config/opencode/opencode.jsonc`):
127
+
128
+ ```jsonc
129
+ {
130
+ "plugins": ["@catronomix/opencode-letmework@0.2.0"]
131
+ }
132
+ ```
133
+
134
+ or let the CLI write it:
135
+
136
+ ```powershell
137
+ opencode plugin add @catronomix/opencode-letmework@0.2.0
138
+ ```
139
+
140
+ It installs **inactive**. Start a session with an agent that asks for permission,
141
+ and the notice from the previous section prints the exact copy command for your
142
+ machine — the packaged `config.example.yaml` sits inside the plugin install
143
+ directory, which differs between an npm install and a clone, so the notice
144
+ resolves it for you. The result is:
145
+
146
+ ```
147
+ ~/.config/opencode/letmework.yaml (%USERPROFILE%\.config\opencode\letmework.yaml)
148
+ ```
149
+
150
+ Edit that file and the change applies on the next prompt — no restart.
151
+
152
+ From a clone instead:
153
+
154
+ ```powershell
155
+ git clone <this repo> C:\GITHUB\opencode-letmework
156
+ New-Item -ItemType SymbolicLink -Path "$env:USERPROFILE\.config\opencode\plugins\opencode-letmework" -Target C:\GITHUB\opencode-letmework
157
+ Copy-Item C:\GITHUB\opencode-letmework\config.example.yaml C:\GITHUB\opencode-letmework\config.yaml
158
+ ```
159
+
160
+ Plugins in `~/.config/opencode/plugins/` load automatically. For a single
161
+ project, symlink into `<project>\.opencode\plugins\` instead.
162
+
163
+ ## How to turn it off
164
+
165
+ - Delete or rename the config file — the plugin goes idle immediately (config is
166
+ re-read on change) and says why on the next prompt.
167
+ - Or remove the plugin entry from your OpenCode config.
168
+ - Already-saved approvals are recorded by OpenCode, not by this plugin. Check
169
+ `opencode`'s permission settings if an old folder still does not prompt.
170
+
171
+ ## Notes
172
+
173
+ - Each request is answered with `always` by default, so the work folder stops
174
+ prompting after the first approval; a rejection by the user is respected
175
+ because the reply is skipped once the request is no longer pending.
176
+ - The plugin logs each decision to the server log (`letmework: ...`), so
177
+ `~/.local/share/opencode/log/opencode.log` shows why something was or was not
178
+ auto-approved. That log is also where the idle/config messages go.
179
+ - Path comparisons are case-insensitive on Windows and case-sensitive elsewhere.
180
+
181
+ ## Development
182
+
183
+ Contributor steps only. What you install from npm, or add with
184
+ `opencode plugin add`, is the prebuilt `dist/` bundle: no build step, no
185
+ lifecycle scripts, no dev toolchain.
186
+
187
+ ```powershell
188
+ git clone https://github.com/catronomix/opencode-letmework
189
+ cd opencode-letmework
190
+ npm install
191
+ npm install-scripts approve esbuild # tsup needs esbuild's platform binary
192
+ npm test # node --test logic.test.ts plugin.test.ts
193
+ npm run typecheck
194
+ npm run build # writes dist/, which is what the plugin loads
195
+ ```
@@ -0,0 +1,50 @@
1
+ # opencode-letmework - config
2
+ #
3
+ # READ THIS FIRST
4
+ # ---------------
5
+ # This plugin is a limited YOLO mode: it answers OpenCode permission prompts
6
+ # for you, without you looking, once the grace period runs out. It is only as
7
+ # safe as the folders you list below. The stock settings allow just the
8
+ # project's sibling work folder inside a git repository, so a plain copy of
9
+ # this file is the cautious default - widen it deliberately, one line at a time.
10
+ #
11
+ # If this file is missing, the plugin does nothing at all.
12
+ #
13
+ # Paths may be absolute, or relative to the session's working directory.
14
+ # This file is re-read whenever it changes; no restart needed.
15
+
16
+ # Seconds to wait before auto-approving. The permission prompt stays visible
17
+ # during that window, so a user who is present can still reject it.
18
+ waitseconds: 5
19
+
20
+ # Appended to the current folder's name to build the sibling work folder that
21
+ # needs no permission: ../<folder><suffix>
22
+ suffix: -wt
23
+
24
+ # Folders (and everything below them) that never need a permission prompt,
25
+ # as long as the session folder is a git repository. Leave empty for the
26
+ # cautious default and uncomment to widen.
27
+ extra-folders: []
28
+ # - /tmp
29
+
30
+ # Folders the agent may not touch directly, but may create and use subfolders
31
+ # inside. Leave empty unless you need a scratch area.
32
+ create-and-use: []
33
+ # - /tmp/opencode
34
+
35
+ # Permission actions that may be auto-approved. Anything else always prompts.
36
+ # Only path-shaped resources are auto-approved, so command text never matches.
37
+ # Narrow this (e.g. just `read`) if you want to stay in the loop for edits.
38
+ actions:
39
+ - read
40
+ - edit
41
+ - write
42
+ - external_directory
43
+
44
+ # How the auto-approval is recorded. `always` saves it, so the same target stops
45
+ # prompting; `once` answers a single request and the next one prompts again.
46
+ decision: always
47
+
48
+ # The one-time in-session notice that explains what was auto-approved and where
49
+ # this config lives: `once` (default), `always`, or `off`.
50
+ notice: once
@@ -0,0 +1,19 @@
1
+ import { Plugin } from '@opencode/plugin';
2
+
3
+ /** Cap on approvals in flight, so a burst of prompts cannot pile up. */
4
+ declare const MAX_PENDING = 8;
5
+ /**
6
+ * Where a config may live, most specific first: the plugin option, the plugin's
7
+ * own folder (a clone or a dev checkout), the package root when the plugin runs
8
+ * from a built `dist` folder, and the user config dir (an npm install, which
9
+ * never ships a config).
10
+ */
11
+ declare function configCandidates(option: unknown, pluginDir?: string): string[];
12
+ /**
13
+ * The example config ships at the package root, which sits one level up when the
14
+ * plugin runs from a built `dist` folder.
15
+ */
16
+ declare function exampleCandidate(pluginDir?: string): string;
17
+ declare const _default: Plugin.Plugin;
18
+
19
+ export { MAX_PENDING, configCandidates, _default as default, exampleCandidate };
package/dist/index.js ADDED
@@ -0,0 +1,475 @@
1
+ // index.ts
2
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
3
+ import { homedir } from "os";
4
+ import { basename as basename2, dirname as dirname2, join as join2 } from "path";
5
+ import { fileURLToPath } from "url";
6
+ import { Plugin } from "@opencode/plugin";
7
+
8
+ // logic.ts
9
+ import { existsSync, realpathSync } from "fs";
10
+ import { basename, dirname, isAbsolute, join, resolve } from "path";
11
+ var DEFAULT_ACTIONS = ["read", "edit", "write", "external_directory"];
12
+ var DEFAULT_CONFIG = {
13
+ waitseconds: 5,
14
+ suffix: "-wt",
15
+ extraFolders: [],
16
+ createAndUse: [],
17
+ actions: [...DEFAULT_ACTIONS],
18
+ decision: "always",
19
+ notice: "once"
20
+ };
21
+ function stripComment(line) {
22
+ let quote;
23
+ for (let index = 0; index < line.length; index += 1) {
24
+ const char = line[index];
25
+ if (quote) {
26
+ if (char === quote) quote = void 0;
27
+ continue;
28
+ }
29
+ if (char === '"' || char === "'") {
30
+ quote = char;
31
+ continue;
32
+ }
33
+ if (char === "#" && (index === 0 || /\s/.test(line[index - 1]))) return line.slice(0, index);
34
+ }
35
+ return line;
36
+ }
37
+ function unquote(value) {
38
+ const trimmed = value.trim();
39
+ if (trimmed.length >= 2) {
40
+ const first = trimmed[0];
41
+ const last = trimmed.at(-1);
42
+ if ((first === '"' || first === "'") && first === last) return trimmed.slice(1, -1);
43
+ }
44
+ return trimmed;
45
+ }
46
+ function inlineList(value) {
47
+ if (!value.startsWith("[") || !value.endsWith("]")) return void 0;
48
+ const inner = value.slice(1, -1).trim();
49
+ if (!inner) return [];
50
+ return inner.split(",").map((item) => unquote(item));
51
+ }
52
+ function parseYaml(text) {
53
+ const out = {};
54
+ let current;
55
+ for (const raw of text.split(/\r?\n/)) {
56
+ const line = stripComment(raw);
57
+ const trimmed = line.trim();
58
+ if (!trimmed) continue;
59
+ if (trimmed === "-" || trimmed.startsWith("- ")) {
60
+ if (!current) continue;
61
+ const item = unquote(trimmed.slice(1));
62
+ const previous = out[current];
63
+ if (Array.isArray(previous)) previous.push(item);
64
+ else out[current] = [item];
65
+ continue;
66
+ }
67
+ const match = /^([\w.-]+)\s*:\s*(.*)$/.exec(trimmed);
68
+ if (!match) continue;
69
+ const key = match[1];
70
+ const rest = match[2].trim();
71
+ current = key;
72
+ if (!rest) {
73
+ out[key] = [];
74
+ continue;
75
+ }
76
+ const list = inlineList(rest);
77
+ out[key] = list ?? unquote(rest);
78
+ }
79
+ return out;
80
+ }
81
+ function strings(value) {
82
+ if (Array.isArray(value)) return value.map((item) => item.trim()).filter((item) => item.length > 0);
83
+ if (typeof value === "string" && value.trim()) return [value.trim()];
84
+ return [];
85
+ }
86
+ function parseConfig(text) {
87
+ const raw = parseYaml(text);
88
+ const waitValue = raw["waitseconds"];
89
+ const waitText = (Array.isArray(waitValue) ? waitValue[0] ?? "" : waitValue ?? "").trim();
90
+ const wait = waitText === "" ? Number.NaN : Number(waitText);
91
+ const waitseconds = Number.isFinite(wait) && wait >= 0 ? Math.min(wait, 600) : DEFAULT_CONFIG.waitseconds;
92
+ const suffixValue = raw["suffix"];
93
+ const rawSuffix = (Array.isArray(suffixValue) ? suffixValue[0] ?? "" : suffixValue ?? "").trim();
94
+ const suffix = rawSuffix === "" ? DEFAULT_CONFIG.suffix : rawSuffix;
95
+ const actions = strings(raw["actions"]).map((action) => action.toLowerCase());
96
+ const decisionValue = raw["decision"];
97
+ const rawDecision = (Array.isArray(decisionValue) ? decisionValue[0] ?? "" : decisionValue ?? "").trim().toLowerCase();
98
+ const decision = rawDecision === "once" ? "once" : "always";
99
+ const noticeValue = raw["notice"];
100
+ const rawNotice = (Array.isArray(noticeValue) ? noticeValue[0] ?? "" : noticeValue ?? "").trim().toLowerCase();
101
+ const notice = rawNotice === "off" || rawNotice === "never" ? "off" : rawNotice === "always" ? "always" : "once";
102
+ return {
103
+ waitseconds,
104
+ suffix,
105
+ extraFolders: strings(raw["extra-folders"]),
106
+ createAndUse: strings(raw["create-and-use"]),
107
+ actions: actions.length > 0 ? actions : [...DEFAULT_ACTIONS],
108
+ decision,
109
+ notice
110
+ };
111
+ }
112
+ var WINDOWS = process.platform === "win32";
113
+ var GLOB_CHAR = /[*?[{]/;
114
+ function normalizePath(input) {
115
+ let path = resolve(input).replaceAll("\\", "/").replace(/\/+$/, "");
116
+ if (/^[a-z]:$/i.test(path)) path = `${path}/`;
117
+ if (!path) path = "/";
118
+ return WINDOWS ? path.toLowerCase() : path;
119
+ }
120
+ function isInside(child, parent, includeSelf) {
121
+ const target = normalizePath(child);
122
+ const root = normalizePath(parent);
123
+ if (target === root) return includeSelf;
124
+ if (root.endsWith("/")) return target.startsWith(root);
125
+ return target.startsWith(`${root}/`);
126
+ }
127
+ function staticPrefix(resource) {
128
+ const match = GLOB_CHAR.exec(resource);
129
+ return match ? resource.slice(0, match.index) : resource;
130
+ }
131
+ function escapes(resource) {
132
+ return /(^|[\\/])\.\.([\\/]|$)/.test(resource);
133
+ }
134
+ function realPath(input) {
135
+ const target = resolve(input);
136
+ const tail = [];
137
+ let current = target;
138
+ for (; ; ) {
139
+ try {
140
+ const real = realpathSync.native(current);
141
+ return tail.length === 0 ? real : join(real, ...tail.reverse());
142
+ } catch {
143
+ const parent = dirname(current);
144
+ if (parent === current) return target;
145
+ tail.push(basename(current));
146
+ current = parent;
147
+ }
148
+ }
149
+ }
150
+ function allowedRoots(cwd, config) {
151
+ const roots = [];
152
+ if (config.suffix.length > 0) {
153
+ const sibling = join(dirname(resolve(cwd)), `${basename(resolve(cwd))}${config.suffix}`);
154
+ roots.push({ path: sibling, includeSelf: true, label: `work folder ${sibling}` });
155
+ }
156
+ for (const folder of config.extraFolders) {
157
+ roots.push({ path: resolve(cwd, folder), includeSelf: true, label: `extra folder ${folder}` });
158
+ }
159
+ for (const folder of config.createAndUse) {
160
+ roots.push({ path: resolve(cwd, folder), includeSelf: false, label: `create-and-use folder ${folder}` });
161
+ }
162
+ return roots;
163
+ }
164
+ function isGitRepository(cwd, exists = existsSync) {
165
+ let directory = resolve(cwd);
166
+ for (; ; ) {
167
+ if (exists(join(directory, ".git"))) return true;
168
+ const parent = dirname(directory);
169
+ if (parent === directory) return false;
170
+ directory = parent;
171
+ }
172
+ }
173
+ function evaluate(input) {
174
+ const { cwd, isGitRepo, config, request } = input;
175
+ const action = request.action.toLowerCase();
176
+ if (!config.actions.includes(action)) {
177
+ return { allow: false, reason: `action "${request.action}" is not in actions` };
178
+ }
179
+ if (request.resources.length === 0) {
180
+ return { allow: false, reason: "no resources" };
181
+ }
182
+ if (!isGitRepo) {
183
+ return { allow: false, reason: `${cwd} is not a git repository` };
184
+ }
185
+ const roots = allowedRoots(cwd, config);
186
+ if (roots.length === 0) {
187
+ return { allow: false, reason: "no folders are allowlisted" };
188
+ }
189
+ const outside = [];
190
+ for (const resource of request.resources) {
191
+ if (escapes(resource)) {
192
+ outside.push(resource);
193
+ continue;
194
+ }
195
+ const prefix = staticPrefix(resource);
196
+ const target = isAbsolute(prefix) ? prefix : join(cwd, prefix);
197
+ const root = roots.find((candidate) => isInside(target, candidate.path, candidate.includeSelf));
198
+ if (!root) {
199
+ outside.push(resource);
200
+ continue;
201
+ }
202
+ if (!isInside(realPath(target), realPath(root.path), root.includeSelf)) outside.push(resource);
203
+ }
204
+ if (outside.length > 0) {
205
+ return { allow: false, reason: `outside the allowed folders: ${outside.join(", ")}` };
206
+ }
207
+ return { allow: true, reason: "all targets are inside the allowed folders" };
208
+ }
209
+ var INDENT = " ";
210
+ var CONTROL = /[\u0000-\u001f\u007f-\u009f]/g;
211
+ var TARGET_LIMIT = 200;
212
+ function oneLine(value, limit = TARGET_LIMIT) {
213
+ const flat = value.replace(CONTROL, " ").replace(/\s+/g, " ").trim();
214
+ return flat.length > limit ? `${flat.slice(0, limit)}...` : flat;
215
+ }
216
+ function activeNotice(input) {
217
+ const { action, resources, reason, config, configPath } = input;
218
+ const targets = resources.map((resource) => `\`${oneLine(resource)}\``).join(", ");
219
+ const label = targets ? `${oneLine(action, 40)} ${targets}` : oneLine(action, 40);
220
+ const lines = [
221
+ `letmework answered a permission prompt for you: ${label}`,
222
+ `${INDENT}rule: ${oneLine(reason)}`,
223
+ `${INDENT}grace: ${config.waitseconds}s - the prompt is left up that long first`,
224
+ `${INDENT}record: ${config.decision === "always" ? "saved, so this target stops prompting" : "this one request only"}`,
225
+ "",
226
+ "This is a limited YOLO mode. It only answers prompts whose every target is",
227
+ "inside an allowed folder and whose action is listed below; everything else",
228
+ `still waits for you. Actions: ${config.actions.join(", ")}.`,
229
+ "",
230
+ `Config: ${oneLine(configPath)}`,
231
+ `${INDENT}extra-folders: folders (and everything below) that may be touched`,
232
+ `${INDENT}create-and-use: folders whose subfolders may be created and used`,
233
+ `${INDENT}actions: narrow it (e.g. only "read") to be asked more often`,
234
+ `${INDENT}decision: once answer each request without saving it`,
235
+ `${INDENT}notice: off stop showing this notice`
236
+ ];
237
+ return lines.join("\n");
238
+ }
239
+ function inactiveNotice(input) {
240
+ const { configPath, examplePath, platform, reason } = input;
241
+ const copy = platform === "win32" ? `Copy-Item "${examplePath}" "${configPath}"` : `cp "${examplePath}" "${configPath}"`;
242
+ return [
243
+ "letmework is installed but idle - nothing is being auto-approved.",
244
+ `${INDENT}reason: ${reason}`,
245
+ `${INDENT}config: ${configPath} (not found)`,
246
+ "",
247
+ "To turn it on, copy the example config and edit it:",
248
+ `${INDENT}${copy}`,
249
+ "",
250
+ "The stock config only allows the project's sibling work folder",
251
+ "(`../<project>-wt`) in git repositories, and leaves every other prompt",
252
+ "alone. Read the comments in the file before adding folders."
253
+ ].join("\n");
254
+ }
255
+
256
+ // index.ts
257
+ var CONFIG_FILE = "config.yaml";
258
+ var USER_CONFIG_FILE = "letmework.yaml";
259
+ var EXAMPLE_FILE = "config.example.yaml";
260
+ var SEEN_LIMIT = 256;
261
+ var MAX_PENDING = 8;
262
+ var NOTICE_KEY = "letmework.notice";
263
+ function pluginDirectory() {
264
+ const meta = import.meta.dirname;
265
+ return meta ?? fileURLToPath(new URL(".", import.meta.url));
266
+ }
267
+ function configHome() {
268
+ const xdg = process.env["XDG_CONFIG_HOME"];
269
+ return xdg && xdg.length > 0 ? xdg : join2(homedir(), ".config");
270
+ }
271
+ function configCandidates(option, pluginDir = pluginDirectory()) {
272
+ if (typeof option === "string" && option.length > 0) {
273
+ return [option.startsWith("~") ? join2(homedir(), option.slice(1)) : option];
274
+ }
275
+ const local = [join2(pluginDir, CONFIG_FILE)];
276
+ if (basename2(pluginDir) === "dist") local.push(join2(dirname2(pluginDir), CONFIG_FILE));
277
+ return [...local, join2(configHome(), "opencode", USER_CONFIG_FILE)];
278
+ }
279
+ function exampleCandidate(pluginDir = pluginDirectory()) {
280
+ const root = basename2(pluginDir) === "dist" ? dirname2(pluginDir) : pluginDir;
281
+ return join2(root, EXAMPLE_FILE);
282
+ }
283
+ function sleep(ms, signal) {
284
+ if (ms <= 0) return Promise.resolve();
285
+ return new Promise((done) => {
286
+ const finish = () => {
287
+ clearTimeout(timer);
288
+ signal?.removeEventListener("abort", finish);
289
+ done();
290
+ };
291
+ const timer = setTimeout(finish, ms);
292
+ if (signal?.aborted) return finish();
293
+ signal?.addEventListener("abort", finish, { once: true });
294
+ });
295
+ }
296
+ function configLoader(paths) {
297
+ let mtime = Number.NaN;
298
+ let loaded = { state: "missing", path: paths[0] ?? CONFIG_FILE, config: DEFAULT_CONFIG };
299
+ return () => {
300
+ const path = paths.find((candidate) => existsSync2(candidate)) ?? paths[0] ?? CONFIG_FILE;
301
+ let next = Number.NaN;
302
+ try {
303
+ next = statSync(path).mtimeMs;
304
+ } catch {
305
+ next = Number.NaN;
306
+ }
307
+ if (path === loaded.path && next === mtime) return loaded;
308
+ mtime = next;
309
+ if (!Number.isFinite(next)) {
310
+ if (loaded.state !== "missing") console.error(`letmework: ${path} disappeared, staying idle`);
311
+ loaded = { state: "missing", path, config: DEFAULT_CONFIG };
312
+ return loaded;
313
+ }
314
+ try {
315
+ const config = parseConfig(readFileSync(path, "utf8"));
316
+ loaded = { state: "active", path, config };
317
+ console.error(
318
+ `letmework: loaded ${path} (wait ${config.waitseconds}s, suffix "${config.suffix}", ${config.extraFolders.length} extra folder(s), ${config.createAndUse.length} create-and-use folder(s), notice ${config.notice})`
319
+ );
320
+ } catch (error) {
321
+ console.error(`letmework: cannot read ${path}, staying idle`, error);
322
+ loaded = { state: "invalid", path, config: DEFAULT_CONFIG };
323
+ }
324
+ return loaded;
325
+ };
326
+ }
327
+ function pendingList(value) {
328
+ if (Array.isArray(value)) return value;
329
+ const data = value?.data;
330
+ return Array.isArray(data) ? data : [];
331
+ }
332
+ function validRequest(value) {
333
+ const request = value;
334
+ if (!request) return void 0;
335
+ if (typeof request.id !== "string" || !request.id) return void 0;
336
+ if (typeof request.sessionID !== "string") return void 0;
337
+ if (typeof request.action !== "string") return void 0;
338
+ if (!Array.isArray(request.resources)) return void 0;
339
+ if (!request.resources.every((resource) => typeof resource === "string")) return void 0;
340
+ return request;
341
+ }
342
+ var index_default = Plugin.define({
343
+ id: "letmework",
344
+ async setup(ctx) {
345
+ const cwd = ctx.location.directory;
346
+ const paths = configCandidates(ctx.options?.config);
347
+ const load = configLoader(paths);
348
+ const examplePath = exampleCandidate();
349
+ const start = load();
350
+ if (start.state !== "active") {
351
+ console.error(
352
+ `letmework: idle, no usable config (${start.state}: ${start.path}). Copy "${examplePath}" to "${start.path}" to enable it.`
353
+ );
354
+ }
355
+ const controller = new AbortController();
356
+ const seen = /* @__PURE__ */ new Set();
357
+ const noticeShown = /* @__PURE__ */ new Set();
358
+ let pending = 0;
359
+ const notice = async (key, sessionID, text) => {
360
+ if (noticeShown.has(key)) return;
361
+ noticeShown.add(key);
362
+ try {
363
+ const seenBefore = await ctx.storage.get(NOTICE_KEY);
364
+ if (seenBefore === key) return;
365
+ await ctx.session.synthetic({ sessionID, text, description: "letmework" });
366
+ await ctx.storage.set(NOTICE_KEY, key);
367
+ } catch (error) {
368
+ console.error("letmework: could not show the onboarding notice", error);
369
+ }
370
+ };
371
+ const approve = async (request) => {
372
+ const label = `${request.action} ${request.resources.join(", ")}`;
373
+ const loaded = load();
374
+ if (loaded.state !== "active") {
375
+ const config = loaded.config;
376
+ if (config.notice !== "off") {
377
+ void notice(
378
+ "inactive",
379
+ request.sessionID,
380
+ inactiveNotice({
381
+ configPath: loaded.path,
382
+ examplePath,
383
+ platform: process.platform,
384
+ reason: loaded.state === "invalid" ? `${loaded.path} could not be read` : `${loaded.path} not found`
385
+ })
386
+ );
387
+ }
388
+ console.error(`letmework: idle (${loaded.state}), leaving ${label} to the user`);
389
+ return;
390
+ }
391
+ const decision = evaluate({
392
+ cwd,
393
+ isGitRepo: isGitRepository(cwd),
394
+ config: loaded.config,
395
+ request
396
+ });
397
+ if (!decision.allow) {
398
+ console.error(`letmework: asking for ${label} (${decision.reason})`);
399
+ return;
400
+ }
401
+ const current = loaded.config;
402
+ const wait = current.waitseconds;
403
+ console.error(
404
+ `letmework: auto-approving ${label} in ${wait}s (${decision.reason}, ${current.decision})`
405
+ );
406
+ await sleep(wait * 1e3, controller.signal);
407
+ if (controller.signal.aborted) return;
408
+ try {
409
+ const raw = await ctx.permission.list({ sessionID: request.sessionID });
410
+ const list = pendingList(raw);
411
+ const stillPending = list.some((item) => item.id === request.id);
412
+ if (!stillPending) {
413
+ console.error(`letmework: kept the user's answer for ${label}`);
414
+ return;
415
+ }
416
+ await ctx.permission.reply({
417
+ sessionID: request.sessionID,
418
+ requestID: request.id,
419
+ decision: current.decision
420
+ });
421
+ } catch (error) {
422
+ console.error(`letmework: could not auto-approve ${label}`, error);
423
+ return;
424
+ }
425
+ if (current.notice !== "off") {
426
+ void notice(
427
+ "active",
428
+ request.sessionID,
429
+ activeNotice({
430
+ action: request.action,
431
+ resources: request.resources,
432
+ reason: decision.reason,
433
+ config: current,
434
+ configPath: loaded.path
435
+ })
436
+ );
437
+ }
438
+ };
439
+ void (async () => {
440
+ try {
441
+ for await (const event of ctx.event.subscribe({
442
+ types: ["permission.asked"],
443
+ signal: controller.signal
444
+ })) {
445
+ const data = event.data;
446
+ const request = validRequest(data);
447
+ if (!request) {
448
+ console.error("letmework: ignoring a malformed permission request");
449
+ continue;
450
+ }
451
+ if (seen.has(request.id)) continue;
452
+ seen.add(request.id);
453
+ if (seen.size > SEEN_LIMIT) seen.delete(seen.values().next().value);
454
+ if (pending >= MAX_PENDING) {
455
+ console.error(`letmework: ${MAX_PENDING} approvals already in flight, leaving ${request.id} to the user`);
456
+ continue;
457
+ }
458
+ pending += 1;
459
+ void approve(request).catch((error) => console.error(`letmework: could not handle ${request.id}`, error)).finally(() => {
460
+ pending -= 1;
461
+ });
462
+ }
463
+ } catch (error) {
464
+ if (!controller.signal.aborted) console.error("letmework: permission stream stopped", error);
465
+ }
466
+ })();
467
+ return () => controller.abort();
468
+ }
469
+ });
470
+ export {
471
+ MAX_PENDING,
472
+ configCandidates,
473
+ index_default as default,
474
+ exampleCandidate
475
+ };
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
- {
2
- "name": "@catronomix/opencode-letmework",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@catronomix/opencode-letmework",
3
+ "version": "0.2.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "OpenCode plugin that auto-approves permission prompts for the project's sibling work folder after a short, interruptible delay.",
8
+ "type": "module",
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/catronomix/opencode-letmework.git"
13
+ },
14
+ "keywords": [
15
+ "opencode",
16
+ "opencode-plugin",
17
+ "permissions",
18
+ "worktree"
19
+ ],
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "config.example.yaml",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "scripts": {
33
+ "build": "tsup",
34
+ "prepack": "npm run build",
35
+ "test": "node --test logic.test.ts plugin.test.ts",
36
+ "typecheck": "tsc --noEmit"
37
+ },
38
+ "engines": {
39
+ "node": ">=20"
40
+ },
41
+ "peerDependencies": {
42
+ "@opencode/plugin": ">=2.3 <3"
43
+ },
44
+ "devDependencies": {
45
+ "@opencode/plugin": "2.3.2",
46
+ "@types/node": "^22.10.2",
47
+ "tsup": "^9.0.0",
48
+ "typescript": "^5.7.2"
49
+ }
50
+ }