@agentrq/agentrq-ws 0.7.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 Contextual, Inc.
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 ADDED
@@ -0,0 +1,167 @@
1
+ # @agentrq/agentrq-ws
2
+
3
+ The AgentRQ workspace client: everything an agent can do in a workspace, from a
4
+ shell, without spending an agent's tokens to do it.
5
+
6
+ ```bash
7
+ npx @agentrq/agentrq-ws@latest help
8
+ ```
9
+
10
+ It reads the `.mcp.json` in the current directory — the same file the agent
11
+ working there uses — so inside a workspace checkout there is nothing to
12
+ configure.
13
+
14
+ ```bash
15
+ cd ~/code/my-workspace
16
+ npx @agentrq/agentrq-ws@latest workspace
17
+ ```
18
+
19
+ ## Why it exists
20
+
21
+ An agent talks to its workspace over MCP, which is the right shape for an agent
22
+ and the wrong shape for a person: every call is a JSON envelope, and every
23
+ answer is tokens the agent pays for. The same eleven tools are underneath this
24
+ CLI, but a command is a line of shell and the answer is plain text.
25
+
26
+ It is also the difference between reading an attachment and *handling* one — see
27
+ below.
28
+
29
+ ## Install
30
+
31
+ Nothing to install: `npx @agentrq/agentrq-ws@latest <command>` fetches it on
32
+ demand, and it has no runtime dependencies. To keep it around:
33
+
34
+ ```bash
35
+ npm install -g @agentrq/agentrq-ws
36
+ agentrq-ws help
37
+ ```
38
+
39
+ Node 20.6 or newer.
40
+
41
+ ## Commands
42
+
43
+ | Command | What it does |
44
+ | --- | --- |
45
+ | `workspace` | Show the workspace title and mission |
46
+ | `task get <taskId>` | Fetch a task, with `--conversation` for its history |
47
+ | `task next` | Take the next not-started task — **this dequeues the queue** |
48
+ | `task create <title>` | Create a task |
49
+ | `task status <taskId> <status>` | Set a task's status |
50
+ | `reply <taskId> <text>` | Send a message to a task |
51
+ | `attachment get <id> --task <taskId>` | Download an attachment to a file |
52
+ | `memory load [name]` | Read a workspace memory (defaults to the index) |
53
+ | `memory save [name] --content …` | Replace a workspace memory |
54
+ | `memory delete [name]` | Delete a workspace memory |
55
+ | `event publish <name>` | Publish a named event |
56
+ | `ask <taskId> <message>` | Ask the human a question and wait |
57
+ | `tools` | List the tools this workspace server offers |
58
+ | `call <tool> --args '{…}'` | Call any tool directly |
59
+
60
+ Every command takes `--help`, and so does every family:
61
+
62
+ ```bash
63
+ agentrq-ws task --help # lists task get / next / create / status
64
+ agentrq-ws attachment get -h # the one command, its options and defaults
65
+ ```
66
+
67
+ `task next` is a separate verb rather than a bare `task get` on purpose: it
68
+ claims work, and a command that mutates the queue should say so in its name.
69
+
70
+ ## Attachments never become your problem
71
+
72
+ The underlying tools speak base64 in both directions. This CLI does not.
73
+
74
+ **Uploading** takes a path. The filename, media type and encoding are worked out
75
+ for you:
76
+
77
+ ```bash
78
+ agentrq-ws reply 0isnjTCkpW5 "Build is green — log attached" --attach ./run.log
79
+ agentrq-ws task create "Review the design" --body @brief.md --attach ./mock.png
80
+ ```
81
+
82
+ **Downloading** writes a file and prints where it went. With no `--out` it lands
83
+ in the OS temp directory:
84
+
85
+ ```bash
86
+ $ agentrq-ws attachment get 0isp9dJxr85 --task 0isnjTCkpW5
87
+ /tmp/agentrq-ws-help.txt
88
+ ```
89
+
90
+ `--out` takes a directory (keeping the attachment's own name) or a full path
91
+ (renaming it):
92
+
93
+ ```bash
94
+ agentrq-ws attachment get 0isp9dJxr85 --task 0isnjTCkpW5 --out ~/Downloads
95
+ agentrq-ws attachment get 0isp9dJxr85 --task 0isnjTCkpW5 --out ./report.pdf
96
+ ```
97
+
98
+ The `--task` is needed because the download tool returns bytes and no filename —
99
+ the task is where the name lives, so the CLI reads it first and your file
100
+ arrives called what a human called it.
101
+
102
+ ## Long text
103
+
104
+ Anywhere prose is expected — `--body`, `--content`, `--payload`, and a reply's
105
+ text — `@path` reads a file and `-` reads stdin:
106
+
107
+ ```bash
108
+ agentrq-ws task create "Post-mortem" --body @notes.md
109
+ git log --oneline -20 | agentrq-ws reply 0isnjTCkpW5 -
110
+ agentrq-ws memory save release-notes.md --content @CHANGELOG.md
111
+ ```
112
+
113
+ ## Asking the human something
114
+
115
+ ```bash
116
+ # a form
117
+ agentrq-ws ask 0isnjTCkpW5 "Which branch should I release from?" \
118
+ --field branch:string:"Branch name" --field sign:boolean:"Sign the tag?"
119
+
120
+ # or a link to go and do something
121
+ agentrq-ws ask 0isnjTCkpW5 "Approve the deploy, then confirm" --url https://example.com/approve
122
+ ```
123
+
124
+ Both block until the human answers or the timeout elapses (`--timeout`, one hour
125
+ by default and at most).
126
+
127
+ ## Output
128
+
129
+ Commands print the server's text. `--json` prints the raw result instead, for
130
+ piping into `jq`:
131
+
132
+ ```bash
133
+ agentrq-ws tools --json | jq -r '.[].name'
134
+ ```
135
+
136
+ Failures print one line and exit non-zero. A stack trace means a bug in the CLI,
137
+ not a mistake in the command.
138
+
139
+ ## Choosing a server
140
+
141
+ The nearest `.mcp.json` at or above the working directory is used. When it
142
+ defines several servers, name one:
143
+
144
+ ```bash
145
+ agentrq-ws workspace --server agentrq-workspace
146
+ agentrq-ws workspace --config ../other/.mcp.json
147
+ ```
148
+
149
+ | Variable | Effect |
150
+ | --- | --- |
151
+ | `AGENTRQ_WS_URL` | Use this server URL and ignore `.mcp.json` entirely |
152
+ | `AGENTRQ_WS_SERVER` | Which server in `.mcp.json` to use |
153
+
154
+ ## Development
155
+
156
+ ```bash
157
+ cd cli/agentrq-ws
158
+ npm test # 147 tests, no network
159
+ npm run test:coverage
160
+ ```
161
+
162
+ The tests drive the whole path — argv, config loading, the MCP handshake, SSE
163
+ framing, files on disk — with only the socket replaced.
164
+
165
+ ## License
166
+
167
+ Apache-2.0
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Contextual, Inc. https://agentrq.com
3
+ // This notice may not be modified or removed.
4
+
5
+ import { run } from '../src/cli.js'
6
+
7
+ // `agentrq-ws tools | head -1` closes the pipe while we are still writing to
8
+ // it, and an unhandled EPIPE turns an ordinary shell idiom into a stack trace
9
+ // and a failed exit. Piping into something that stops reading is the reader's
10
+ // decision, not an error here.
11
+ for (const stream of [process.stdout, process.stderr]) {
12
+ stream.on('error', (err) => {
13
+ if (err && err.code === 'EPIPE') process.exit(0)
14
+ throw err
15
+ })
16
+ }
17
+
18
+ process.exitCode = await run({ argv: process.argv.slice(2) })
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@agentrq/agentrq-ws",
3
+ "version": "0.7.0",
4
+ "description": "AgentRQ workspace client \u2014 drive an AgentRQ workspace from the command line, using the workspace's own .mcp.json",
5
+ "keywords": [
6
+ "agentrq",
7
+ "workspace",
8
+ "mcp",
9
+ "cli",
10
+ "tasks"
11
+ ],
12
+ "homepage": "https://github.com/agentrq/agentrq/tree/main/cli/agentrq-ws",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/agentrq/agentrq.git",
16
+ "directory": "cli/agentrq-ws"
17
+ },
18
+ "license": "Apache-2.0",
19
+ "type": "module",
20
+ "bin": {
21
+ "agentrq-ws": "bin/agentrq-ws.js"
22
+ },
23
+ "exports": {
24
+ ".": "./src/index.js",
25
+ "./package.json": "./package.json"
26
+ },
27
+ "files": [
28
+ "bin",
29
+ "src",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "engines": {
34
+ "node": ">=20.6.0"
35
+ },
36
+ "scripts": {
37
+ "test": "node --test test/*.test.js",
38
+ "test:coverage": "node --test --experimental-test-coverage --test-coverage-exclude=test/** test/*.test.js",
39
+ "test:ci": "node --test --experimental-test-coverage --test-coverage-exclude=test/** --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=95 test/*.test.js"
40
+ }
41
+ }
@@ -0,0 +1,152 @@
1
+ // Copyright 2026 Contextual, Inc. https://agentrq.com
2
+ // This notice may not be modified or removed.
3
+
4
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path'
7
+
8
+ import { UserError } from './errors.js'
9
+
10
+ /**
11
+ * Extension → media type. Deliberately a short table of what actually gets
12
+ * attached to a task rather than a dependency: anything unlisted travels as
13
+ * application/octet-stream, which is correct, just unspecific.
14
+ */
15
+ export const MIME_TYPES = {
16
+ '.bmp': 'image/bmp',
17
+ '.csv': 'text/csv',
18
+ '.gif': 'image/gif',
19
+ '.gz': 'application/gzip',
20
+ '.htm': 'text/html',
21
+ '.html': 'text/html',
22
+ '.ics': 'text/calendar',
23
+ '.jpeg': 'image/jpeg',
24
+ '.jpg': 'image/jpeg',
25
+ '.js': 'text/javascript',
26
+ '.json': 'application/json',
27
+ '.log': 'text/plain',
28
+ '.md': 'text/markdown',
29
+ '.mp3': 'audio/mpeg',
30
+ '.mp4': 'video/mp4',
31
+ '.pdf': 'application/pdf',
32
+ '.png': 'image/png',
33
+ '.svg': 'image/svg+xml',
34
+ '.tar': 'application/x-tar',
35
+ '.txt': 'text/plain',
36
+ '.wav': 'audio/wav',
37
+ '.webm': 'video/webm',
38
+ '.webp': 'image/webp',
39
+ '.xml': 'application/xml',
40
+ '.yaml': 'application/yaml',
41
+ '.yml': 'application/yaml',
42
+ '.zip': 'application/zip',
43
+ }
44
+
45
+ export function mimeTypeFor(filename) {
46
+ return MIME_TYPES[extname(String(filename)).toLowerCase()] || 'application/octet-stream'
47
+ }
48
+
49
+ /**
50
+ * Turn a path on disk into the attachment shape the workspace tools expect.
51
+ *
52
+ * This is the whole point of the `--attach` flag: the wire format wants
53
+ * `{id, filename, mimeType, data}` with base64 in `data`, and nobody should
54
+ * have to produce that by hand. The `id` is a placeholder — the backend mints
55
+ * the real one and blanks `data` as it stores the bytes — but the field is part
56
+ * of the schema, so it is sent.
57
+ */
58
+ export function readAttachment(filePath, { readFile = readFileSync, stat = statSync } = {}) {
59
+ const path = resolve(filePath)
60
+ let info
61
+ try {
62
+ info = stat(path)
63
+ } catch {
64
+ throw new UserError(`cannot attach ${filePath}: no such file`)
65
+ }
66
+ if (info.isDirectory()) {
67
+ throw new UserError(`cannot attach ${filePath}: it is a directory`)
68
+ }
69
+ let bytes
70
+ try {
71
+ bytes = readFile(path)
72
+ } catch (err) {
73
+ throw new UserError(`cannot read ${filePath}: ${err.message}`)
74
+ }
75
+ const filename = basename(path)
76
+ return {
77
+ id: `upload-${filename}`,
78
+ filename,
79
+ mimeType: mimeTypeFor(filename),
80
+ data: Buffer.from(bytes).toString('base64'),
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Index the attachments mentioned in a task's text, id → {filename, mimeType}.
86
+ *
87
+ * `downloadAttachment` answers with base64 and nothing else — no name, no type
88
+ * — so the only way to save a file under the name a human gave it is to read
89
+ * the task first. Task-level attachments arrive as `- id=… name=… type=…`
90
+ * lines and message-level ones inside the conversation JSON, so both shapes are
91
+ * scanned.
92
+ */
93
+ export function indexAttachments(taskText) {
94
+ const index = new Map()
95
+ const text = String(taskText || '')
96
+
97
+ const linePattern = /^\s*-\s*id=(\S+)\s+name=(.*?)\s+type=(\S+)\s*$/gm
98
+ for (const match of text.matchAll(linePattern)) {
99
+ index.set(match[1], { filename: match[2], mimeType: match[3] })
100
+ }
101
+
102
+ const jsonPattern = /"id"\s*:\s*"([^"]+)"\s*,\s*"filename"\s*:\s*"([^"]*)"\s*,\s*"mimeType"\s*:\s*"([^"]*)"/g
103
+ for (const match of text.matchAll(jsonPattern)) {
104
+ if (!index.has(match[1])) {
105
+ index.set(match[1], { filename: match[2], mimeType: match[3] })
106
+ }
107
+ }
108
+ return index
109
+ }
110
+
111
+ /**
112
+ * Work out where a downloaded attachment should land.
113
+ *
114
+ * With no `--out` it goes to the OS temp directory, which is what makes
115
+ * `attachment get` safe to run without thinking about the current directory.
116
+ * An `--out` naming an existing directory (or ending in a separator) keeps the
117
+ * attachment's own filename; anything else is taken as the full path to write,
118
+ * so `--out ./report.pdf` renames.
119
+ */
120
+ export function resolveOutputPath(filename, out, { cwd = process.cwd(), temp = tmpdir(), stat = statSync } = {}) {
121
+ const safeName = basename(String(filename || '')) || 'attachment'
122
+ if (!out) return join(temp, safeName)
123
+
124
+ const endsWithSeparator = /[\\/]$/.test(out)
125
+ const target = isAbsolute(out) ? out : resolve(cwd, out)
126
+ if (endsWithSeparator || isDirectory(target, stat)) {
127
+ return join(target, safeName)
128
+ }
129
+ return target
130
+ }
131
+
132
+ /** True only when the path exists *and* is a directory — an existing file at
133
+ * `--out` is a rename target to overwrite, not somewhere to nest inside. */
134
+ function isDirectory(path, stat) {
135
+ try {
136
+ return stat(path).isDirectory()
137
+ } catch {
138
+ return false
139
+ }
140
+ }
141
+
142
+ /** Write base64 content to `path`, creating the directory if it is missing. */
143
+ export function writeAttachment(path, base64, { write = writeFileSync, mkdir = mkdirSync } = {}) {
144
+ const buffer = Buffer.from(String(base64 || '').trim(), 'base64')
145
+ try {
146
+ mkdir(dirname(path), { recursive: true })
147
+ write(path, buffer)
148
+ } catch (err) {
149
+ throw new UserError(`cannot write ${path}: ${err.message}`)
150
+ }
151
+ return { path, bytes: buffer.length }
152
+ }