@usepipa/pipa 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 +202 -0
- package/README.md +70 -0
- package/bin/pipa.mjs +121 -0
- package/package.json +42 -0
- package/src/app.mjs +227 -0
- package/src/opencode.mjs +151 -0
- package/src/state.mjs +184 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Pipa
|
|
2
|
+
|
|
3
|
+
[](https://github.com/lunchpaillola/pipa/actions/workflows/ci.yml)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
Pipa connects Slack to the OpenCode already installed on your computer. It runs locally: no hosted relay, database, public endpoint, or sandbox is involved.
|
|
7
|
+
|
|
8
|
+
**Pipa is in early preview. Features may break unintentionally, and CLI commands, configuration, and Slack behavior may continue to change.**
|
|
9
|
+
|
|
10
|
+
## Requirements
|
|
11
|
+
|
|
12
|
+
- Node.js 22 or newer
|
|
13
|
+
- [OpenCode](https://opencode.ai) installed and authenticated
|
|
14
|
+
- A Slack workspace where you can create an app
|
|
15
|
+
|
|
16
|
+
Invite the Slack app only to channels whose members may use OpenCode in the configured working directory.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
1. Install Pipa:
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
npm install --global @usepipa/pipa
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
2. From the folder where you want Pipa to work, run:
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
pipa init
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`pipa init` guides you through creating and installing the Slack app and saving its local configuration.
|
|
33
|
+
|
|
34
|
+
3. Start Pipa:
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
pipa start
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Keep `pipa start` running, invite Pipa to a trusted public or private Slack channel, and mention it there. Pipa replies in a thread, and follow-up messages in that thread do not need another mention.
|
|
41
|
+
|
|
42
|
+
## Commands
|
|
43
|
+
|
|
44
|
+
```text
|
|
45
|
+
pipa init Configure Slack and the local working directory
|
|
46
|
+
pipa start Connect Slack Socket Mode to local OpenCode
|
|
47
|
+
pipa --version Print the installed version
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Pipa v0.1 is text-only. File handling, DMs, interactive questions, schedulers, and hosted fallback are not included.
|
|
51
|
+
|
|
52
|
+
## Development
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
npm ci
|
|
56
|
+
npm test
|
|
57
|
+
npm run test:pack
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
|
|
61
|
+
|
|
62
|
+
See the [repository overview](docs/repository-overview.md) for a file-by-file explanation of how Pipa works.
|
|
63
|
+
|
|
64
|
+
## Releases
|
|
65
|
+
|
|
66
|
+
Pipa follows [Semantic Versioning](https://semver.org/). Release notes are published on [GitHub Releases](https://github.com/lunchpaillola/pipa/releases).
|
|
67
|
+
|
|
68
|
+
## License
|
|
69
|
+
|
|
70
|
+
Licensed under the [Apache License 2.0](LICENSE).
|
package/bin/pipa.mjs
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import crossSpawn from "cross-spawn";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { Writable } from "node:stream";
|
|
7
|
+
import { stdin, stdout } from "node:process";
|
|
8
|
+
import { acquireInstanceLock, createManifest, createManifestUrl } from "../src/state.mjs";
|
|
9
|
+
import { initializePipa, startPipa } from "../src/app.mjs";
|
|
10
|
+
|
|
11
|
+
const packageJson = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
|
|
12
|
+
|
|
13
|
+
async function main(argv = process.argv.slice(2), io = { input: stdin, output: stdout }) {
|
|
14
|
+
const command = argv[0];
|
|
15
|
+
if (command === "--version" || command === "-v") {
|
|
16
|
+
io.output.write(`${packageJson.version}\n`);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (command === "init") return init(io);
|
|
20
|
+
if (command === "start") return start(io);
|
|
21
|
+
throw new Error("Usage: pipa init | pipa start | pipa --version");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function init(io) {
|
|
25
|
+
let muted = false;
|
|
26
|
+
const promptOutput = new Writable({
|
|
27
|
+
write(chunk, encoding, callback) {
|
|
28
|
+
if (!muted) io.output.write(chunk, encoding);
|
|
29
|
+
callback();
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
const prompt = createInterface({ input: io.input, output: promptOutput, terminal: Boolean(io.input.isTTY) });
|
|
33
|
+
try {
|
|
34
|
+
const botName = process.env.PIPA_BOT_NAME?.trim()
|
|
35
|
+
|| (await prompt.question("What should we call your bot? (leave empty to use Pipa; you can change this later): ")).trim()
|
|
36
|
+
|| "Pipa";
|
|
37
|
+
const hasSlackTokens = process.env.PIPA_SLACK_APP_TOKEN && process.env.PIPA_SLACK_BOT_TOKEN;
|
|
38
|
+
const workingDirectory = process.cwd();
|
|
39
|
+
if (!hasSlackTokens) {
|
|
40
|
+
io.output.write(`\nPipa will work in this folder:\n\n ${workingDirectory}\n\nPeople in Slack channels where you add ${botName} can ask it to read and change files in this folder.\n\n`);
|
|
41
|
+
if (!await confirm(prompt, io.output)) {
|
|
42
|
+
io.output.write("\nSetup cancelled. Change into the folder where you want Pipa to work, then run `pipa init` again.\n");
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (!hasSlackTokens) {
|
|
47
|
+
const manifestUrl = createManifestUrl(createManifest(botName));
|
|
48
|
+
io.output.write("\nOpening Slack with your app configuration...\n");
|
|
49
|
+
if (io.input.isTTY) await openUrl(manifestUrl).catch(() => undefined);
|
|
50
|
+
io.output.write(`\nIf Slack did not open, use this link:\n${manifestUrl}\n\n`);
|
|
51
|
+
io.output.write("In Slack:\n1. Choose your workspace, review the configuration, and create the app.\n2. Under Basic Information, generate an app-level token with connections:write.\n3. Under OAuth & Permissions, install the app and copy its Bot User OAuth Token.\n\n");
|
|
52
|
+
}
|
|
53
|
+
const askSecret = async (question, label) => {
|
|
54
|
+
io.output.write(question);
|
|
55
|
+
muted = true;
|
|
56
|
+
const value = await prompt.question("");
|
|
57
|
+
muted = false;
|
|
58
|
+
io.output.write(`\n✓ ${label} received.\n`);
|
|
59
|
+
return value;
|
|
60
|
+
};
|
|
61
|
+
const slackAppToken = process.env.PIPA_SLACK_APP_TOKEN || await askSecret("Slack app token (xapp-, input hidden): ", "App token");
|
|
62
|
+
const slackBotToken = process.env.PIPA_SLACK_BOT_TOKEN || await askSecret("Slack bot token (xoxb-, input hidden): ", "Bot token");
|
|
63
|
+
io.output.write("\nChecking OpenCode and Slack credentials...\n");
|
|
64
|
+
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken });
|
|
65
|
+
io.output.write(`✓ Credentials validated.\n\nSaved config to ${result.paths.config}. Run \`pipa start\`.\n`);
|
|
66
|
+
} finally {
|
|
67
|
+
prompt.close();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function confirm(prompt, output) {
|
|
72
|
+
while (true) {
|
|
73
|
+
const answer = (await prompt.question("Continue? [Y/n]: ")).trim().toLowerCase();
|
|
74
|
+
if (!answer || answer === "y" || answer === "yes") return true;
|
|
75
|
+
if (answer === "n" || answer === "no") return false;
|
|
76
|
+
output.write("Please answer y or n.\n");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function openUrl(url) {
|
|
81
|
+
let command = "xdg-open";
|
|
82
|
+
let args = [url];
|
|
83
|
+
if (process.platform === "darwin") command = "open";
|
|
84
|
+
if (process.platform === "win32") {
|
|
85
|
+
command = "rundll32";
|
|
86
|
+
args = ["url.dll,FileProtocolHandler", url];
|
|
87
|
+
}
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
const child = crossSpawn(command, args, { detached: true, stdio: "ignore" });
|
|
90
|
+
child.once("spawn", () => {
|
|
91
|
+
child.unref();
|
|
92
|
+
resolve();
|
|
93
|
+
});
|
|
94
|
+
child.once("error", reject);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function start(io) {
|
|
99
|
+
const releaseLock = await acquireInstanceLock();
|
|
100
|
+
try {
|
|
101
|
+
const app = await startPipa();
|
|
102
|
+
io.output.write("Pipa is connected through Slack Socket Mode.\n");
|
|
103
|
+
await new Promise((resolve, reject) => {
|
|
104
|
+
let stopping = false;
|
|
105
|
+
const shutdown = () => {
|
|
106
|
+
if (stopping) return;
|
|
107
|
+
stopping = true;
|
|
108
|
+
app.shutdown().then(resolve, reject);
|
|
109
|
+
};
|
|
110
|
+
process.once("SIGINT", shutdown);
|
|
111
|
+
process.once("SIGTERM", shutdown);
|
|
112
|
+
});
|
|
113
|
+
} finally {
|
|
114
|
+
await releaseLock();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
main().catch((error) => {
|
|
119
|
+
process.stderr.write(`Pipa failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
120
|
+
process.exitCode = 1;
|
|
121
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@usepipa/pipa",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Run Pipa locally through Slack and OpenCode",
|
|
5
|
+
"keywords": ["slack", "opencode", "ai-agent", "cli"],
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"pipa": "bin/pipa.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"src",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"test": "node --test",
|
|
18
|
+
"test:pack": "node scripts/pack-smoke.mjs"
|
|
19
|
+
},
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/lunchpaillola/pipa.git"
|
|
26
|
+
},
|
|
27
|
+
"homepage": "https://github.com/lunchpaillola/pipa#readme",
|
|
28
|
+
"bugs": {
|
|
29
|
+
"url": "https://github.com/lunchpaillola/pipa/issues"
|
|
30
|
+
},
|
|
31
|
+
"author": "Lunch Pail Labs",
|
|
32
|
+
"license": "Apache-2.0",
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@chat-adapter/slack": "4.38.1",
|
|
38
|
+
"@chat-adapter/state-memory": "4.38.1",
|
|
39
|
+
"chat": "4.38.1",
|
|
40
|
+
"cross-spawn": "7.0.6"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/app.mjs
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { Chat } from "chat";
|
|
2
|
+
import { createSlackAdapter } from "@chat-adapter/slack";
|
|
3
|
+
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
4
|
+
import { canonicalWorkingDirectory, createManifest, createSessionStore, loadConfig, pipaPaths, saveConfig } from "./state.mjs";
|
|
5
|
+
import { createOpenCodeExecutor, runOpenCodeVersion } from "./opencode.mjs";
|
|
6
|
+
|
|
7
|
+
export async function initializePipa(input, options = {}) {
|
|
8
|
+
const paths = options.paths ?? pipaPaths();
|
|
9
|
+
const manifest = createManifest(input.botName);
|
|
10
|
+
const config = {
|
|
11
|
+
botName: input.botName.trim(),
|
|
12
|
+
slackAppToken: requireToken(input.slackAppToken, "Slack app token", "xapp-"),
|
|
13
|
+
slackBotToken: requireToken(input.slackBotToken, "Slack bot token", "xoxb-"),
|
|
14
|
+
workingDirectory: await canonicalWorkingDirectory(input.workingDirectory),
|
|
15
|
+
};
|
|
16
|
+
const openCodeVersion = await (options.checkOpenCode ?? runOpenCodeVersion)();
|
|
17
|
+
if (!/^v?1(?:\.|$)/u.test(openCodeVersion)) throw new Error(`Pipa requires OpenCode v1; found ${openCodeVersion || "an unknown version"}.`);
|
|
18
|
+
await (options.checkSlackAppToken ?? checkSlackAppToken)(config.slackAppToken);
|
|
19
|
+
await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
20
|
+
|
|
21
|
+
await saveConfig(config, paths, manifest);
|
|
22
|
+
return { config, manifest, paths };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function startPipa(options = {}) {
|
|
26
|
+
const paths = options.paths ?? pipaPaths();
|
|
27
|
+
const config = options.config ?? await loadConfig(paths.config);
|
|
28
|
+
await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
29
|
+
const sessionStore = options.sessionStore ?? await createSessionStore(paths.sessions);
|
|
30
|
+
const executor = options.executor ?? createOpenCodeExecutor();
|
|
31
|
+
const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn });
|
|
32
|
+
const state = options.state ?? createMemoryState();
|
|
33
|
+
const chat = options.chat ?? new Chat({
|
|
34
|
+
adapters: {
|
|
35
|
+
slack: createSlackAdapter({
|
|
36
|
+
appToken: config.slackAppToken,
|
|
37
|
+
botToken: config.slackBotToken,
|
|
38
|
+
mode: "socket",
|
|
39
|
+
userName: config.botName,
|
|
40
|
+
webClientOptions: { timeout: 30_000, retryConfig: { retries: 0 } },
|
|
41
|
+
}),
|
|
42
|
+
},
|
|
43
|
+
concurrency: "concurrent",
|
|
44
|
+
state,
|
|
45
|
+
userName: config.botName,
|
|
46
|
+
});
|
|
47
|
+
let accepting = true;
|
|
48
|
+
|
|
49
|
+
const handle = async (thread, message, subscribe) => {
|
|
50
|
+
if (!accepting || shouldIgnore(thread, message)) return;
|
|
51
|
+
const prompt = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
|
|
52
|
+
if (!prompt) return;
|
|
53
|
+
if (subscribe) await thread.subscribe();
|
|
54
|
+
if (!accepting) return;
|
|
55
|
+
|
|
56
|
+
await react(thread, message, "eyes");
|
|
57
|
+
try {
|
|
58
|
+
const result = await runner.enqueue(thread.id, {
|
|
59
|
+
prompt,
|
|
60
|
+
workingDirectory: config.workingDirectory,
|
|
61
|
+
contextEnvironment: slackContext(thread, message),
|
|
62
|
+
deliver: (text) => postInChunks(thread, text),
|
|
63
|
+
deliverFailure: (error) => thread.post(`Pipa failed: ${safeError(error)}`),
|
|
64
|
+
});
|
|
65
|
+
await finishReaction(thread, message, result.error ? "warning" : "white_check_mark");
|
|
66
|
+
} catch (error) {
|
|
67
|
+
await finishReaction(thread, message, "warning");
|
|
68
|
+
process.stderr.write("Pipa could not complete or deliver a Slack turn.\n");
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
chat.onNewMention((thread, message) => handle(thread, message, true));
|
|
73
|
+
chat.onSubscribedMessage((thread, message) => handle(thread, message, false));
|
|
74
|
+
try {
|
|
75
|
+
await state.connect();
|
|
76
|
+
for (const conversationKey of sessionStore.keys()) {
|
|
77
|
+
await chat.thread(conversationKey).subscribe();
|
|
78
|
+
}
|
|
79
|
+
await withTimeout(chat.initialize(), options.startupTimeoutMs ?? 30_000, "Slack Socket Mode startup timed out.");
|
|
80
|
+
} catch (error) {
|
|
81
|
+
executor.stopAll();
|
|
82
|
+
await withTimeout(chat.shutdown(), options.shutdownTimeoutMs ?? 15_000, "Slack shutdown timed out.").catch(() => undefined);
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
async shutdown() {
|
|
88
|
+
accepting = false;
|
|
89
|
+
runner.close();
|
|
90
|
+
executor.stopAll();
|
|
91
|
+
await withTimeout((async () => {
|
|
92
|
+
await runner.drain();
|
|
93
|
+
await chat.shutdown();
|
|
94
|
+
})(), options.shutdownTimeoutMs ?? 15_000, "Pipa shutdown timed out.");
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function createConversationRunner({ sessionStore, runTurn }) {
|
|
100
|
+
const tails = new Map();
|
|
101
|
+
let closed = false;
|
|
102
|
+
|
|
103
|
+
function enqueue(conversationKey, input) {
|
|
104
|
+
if (closed) return Promise.reject(new Error("Pipa is shutting down."));
|
|
105
|
+
const previous = tails.get(conversationKey) ?? Promise.resolve();
|
|
106
|
+
const current = previous.catch(() => undefined).then(async () => {
|
|
107
|
+
if (closed) throw new Error("Pipa is shutting down.");
|
|
108
|
+
const { deliver, deliverFailure, ...turn } = input;
|
|
109
|
+
let result;
|
|
110
|
+
try {
|
|
111
|
+
result = await runTurn({ ...turn, sessionId: sessionStore.get(conversationKey) });
|
|
112
|
+
if (result.sessionId) await sessionStore.set(conversationKey, result.sessionId);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if (deliverFailure) {
|
|
115
|
+
await deliverFailure(error);
|
|
116
|
+
return { error };
|
|
117
|
+
}
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
if (deliver) await deliver(result.text);
|
|
121
|
+
return result;
|
|
122
|
+
});
|
|
123
|
+
const tail = current.then(() => undefined, () => undefined);
|
|
124
|
+
tails.set(conversationKey, tail);
|
|
125
|
+
tail.finally(() => {
|
|
126
|
+
if (tails.get(conversationKey) === tail) tails.delete(conversationKey);
|
|
127
|
+
});
|
|
128
|
+
return current;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
enqueue,
|
|
133
|
+
close() { closed = true; },
|
|
134
|
+
drain: () => Promise.all([...tails.values()]),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function checkSlackToken(token, fetchImpl = fetch) {
|
|
139
|
+
const botToken = requireToken(token, "Slack bot token", "xoxb-");
|
|
140
|
+
const response = await fetchImpl("https://slack.com/api/auth.test", {
|
|
141
|
+
method: "POST",
|
|
142
|
+
headers: { authorization: `Bearer ${botToken}` },
|
|
143
|
+
signal: AbortSignal.timeout(15_000),
|
|
144
|
+
});
|
|
145
|
+
const result = await response.json();
|
|
146
|
+
if (!response.ok || !result.ok) throw new Error("Slack rejected the bot token.");
|
|
147
|
+
return result;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function checkSlackAppToken(token, fetchImpl = fetch) {
|
|
151
|
+
const appToken = requireToken(token, "Slack app token", "xapp-");
|
|
152
|
+
const response = await fetchImpl("https://slack.com/api/apps.connections.open", {
|
|
153
|
+
method: "POST",
|
|
154
|
+
headers: {
|
|
155
|
+
authorization: `Bearer ${appToken}`,
|
|
156
|
+
"content-type": "application/json",
|
|
157
|
+
},
|
|
158
|
+
body: "{}",
|
|
159
|
+
signal: AbortSignal.timeout(15_000),
|
|
160
|
+
});
|
|
161
|
+
const result = await response.json();
|
|
162
|
+
if (!response.ok || !result.ok) throw new Error("Slack rejected the app token. Generate an app-level token with the connections:write scope.");
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function shouldIgnore(thread, message) {
|
|
167
|
+
return message.author?.isMe
|
|
168
|
+
|| message.author?.isBot
|
|
169
|
+
|| thread.channel?.isDM
|
|
170
|
+
|| thread.channel?.channelVisibility === "external"
|
|
171
|
+
|| Boolean(message.raw?.subtype)
|
|
172
|
+
|| !message.text?.trim();
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function stripMention(text = "") {
|
|
176
|
+
return text.replace(/(?:<@|@)[UW][A-Z0-9]+>?/u, "").trim();
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function requireToken(value, label, prefix) {
|
|
180
|
+
const token = String(value ?? "").trim();
|
|
181
|
+
if (!token.startsWith(prefix)) throw new Error(`${label} must start with ${prefix}`);
|
|
182
|
+
return token;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function safeError(error) {
|
|
186
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
187
|
+
return message.replace(/xox[baprs]-[^\s]+|xapp-[^\s]+/gu, "[redacted]");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function slackContext(thread, message) {
|
|
191
|
+
const [, channelId = "", threadTs = ""] = thread.id.split(":");
|
|
192
|
+
return {
|
|
193
|
+
PIPA_MESSAGE_CHANNEL: "slack",
|
|
194
|
+
PIPA_CURRENT_SLACK_CHANNEL_ID: channelId,
|
|
195
|
+
PIPA_CURRENT_SLACK_THREAD_TS: threadTs,
|
|
196
|
+
PIPA_REQUESTER_SLACK_USER_ID: message.author?.userId ?? message.author?.id ?? "",
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function postInChunks(thread, text) {
|
|
201
|
+
for (let index = 0; index < text.length; index += 3500) {
|
|
202
|
+
await thread.post(text.slice(index, index + 3500));
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function react(thread, message, emoji) {
|
|
207
|
+
if (!message.id) return;
|
|
208
|
+
await thread.adapter.addReaction(thread.id, message.id, emoji).catch(() => undefined);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function finishReaction(thread, message, emoji) {
|
|
212
|
+
if (!message.id) return;
|
|
213
|
+
await thread.adapter.removeReaction(thread.id, message.id, "eyes").catch(() => undefined);
|
|
214
|
+
await react(thread, message, emoji);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function withTimeout(promise, timeoutMs, message) {
|
|
218
|
+
let timer;
|
|
219
|
+
try {
|
|
220
|
+
return await Promise.race([
|
|
221
|
+
promise,
|
|
222
|
+
new Promise((_, reject) => timer = setTimeout(() => reject(new Error(message)), timeoutMs)),
|
|
223
|
+
]);
|
|
224
|
+
} finally {
|
|
225
|
+
clearTimeout(timer);
|
|
226
|
+
}
|
|
227
|
+
}
|
package/src/opencode.mjs
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import crossSpawn from "cross-spawn";
|
|
2
|
+
|
|
3
|
+
const SECRET_ENV_KEYS = new Set([
|
|
4
|
+
"PIPA_SLACK_APP_TOKEN",
|
|
5
|
+
"PIPA_SLACK_BOT_TOKEN",
|
|
6
|
+
"SLACK_APP_TOKEN",
|
|
7
|
+
"SLACK_BOT_TOKEN",
|
|
8
|
+
]);
|
|
9
|
+
|
|
10
|
+
export function cleanChildEnvironment(environment = process.env) {
|
|
11
|
+
return Object.fromEntries(Object.entries(environment).filter(([key]) => !SECRET_ENV_KEYS.has(key.toUpperCase())));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function buildRunArguments({ prompt, sessionId, workingDirectory }) {
|
|
15
|
+
const args = ["run", "--format", "json", "--dir", workingDirectory];
|
|
16
|
+
if (sessionId) args.push("--session", sessionId);
|
|
17
|
+
args.push("--", prompt);
|
|
18
|
+
return args;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function createOpenCodeExecutor(options = {}) {
|
|
22
|
+
const spawn = options.spawn ?? crossSpawn;
|
|
23
|
+
const platform = options.platform ?? process.platform;
|
|
24
|
+
const environment = options.environment ?? process.env;
|
|
25
|
+
const timeoutMs = options.timeoutMs ?? 2.5 * 60 * 60 * 1000;
|
|
26
|
+
const children = new Set();
|
|
27
|
+
|
|
28
|
+
async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {} }) {
|
|
29
|
+
if (!prompt?.trim()) throw new Error("A prompt is required.");
|
|
30
|
+
const child = spawn("opencode", buildRunArguments({ prompt, sessionId, workingDirectory }), {
|
|
31
|
+
cwd: workingDirectory,
|
|
32
|
+
env: { ...cleanChildEnvironment(environment), ...contextEnvironment },
|
|
33
|
+
shell: false,
|
|
34
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
35
|
+
});
|
|
36
|
+
children.add(child);
|
|
37
|
+
const exit = waitForExit(child);
|
|
38
|
+
void exit.finally(() => children.delete(child)).catch(() => undefined);
|
|
39
|
+
let timer;
|
|
40
|
+
|
|
41
|
+
try {
|
|
42
|
+
const operation = Promise.all([collect(child.stdout), collect(child.stderr), exit]);
|
|
43
|
+
const timeout = new Promise((_, reject) => {
|
|
44
|
+
timer = setTimeout(() => {
|
|
45
|
+
terminateChild(child, platform);
|
|
46
|
+
reject(new Error(`OpenCode timed out after ${timeoutMs}ms.`));
|
|
47
|
+
}, timeoutMs);
|
|
48
|
+
});
|
|
49
|
+
const [stdout, stderr, code] = await Promise.race([operation, timeout]);
|
|
50
|
+
const output = parseOpenCodeOutput(stdout);
|
|
51
|
+
if (output.error) throw new Error(output.error);
|
|
52
|
+
if (code !== 0) throw new Error(output.error || stderr.trim() || `OpenCode exited with code ${code}.`);
|
|
53
|
+
if (!output.text) throw new Error("OpenCode completed without assistant text.");
|
|
54
|
+
return { text: output.text, sessionId: output.sessionId ?? sessionId ?? null };
|
|
55
|
+
} catch (error) {
|
|
56
|
+
terminateChild(child, platform);
|
|
57
|
+
throw error;
|
|
58
|
+
} finally {
|
|
59
|
+
clearTimeout(timer);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return {
|
|
64
|
+
runTurn,
|
|
65
|
+
stopAll() {
|
|
66
|
+
for (const child of children) terminateChild(child, platform);
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function runOpenCodeVersion(options = {}) {
|
|
72
|
+
const spawn = options.spawn ?? crossSpawn;
|
|
73
|
+
const platform = options.platform ?? process.platform;
|
|
74
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
75
|
+
const child = spawn("opencode", ["--version"], {
|
|
76
|
+
env: cleanChildEnvironment(options.environment ?? process.env),
|
|
77
|
+
shell: false,
|
|
78
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
79
|
+
});
|
|
80
|
+
let timer;
|
|
81
|
+
try {
|
|
82
|
+
const operation = Promise.all([collect(child.stdout), collect(child.stderr), waitForExit(child)]);
|
|
83
|
+
const timeout = new Promise((_, reject) => {
|
|
84
|
+
timer = setTimeout(() => {
|
|
85
|
+
terminateChild(child, platform);
|
|
86
|
+
reject(new Error(`OpenCode version check timed out after ${timeoutMs}ms.`));
|
|
87
|
+
}, timeoutMs);
|
|
88
|
+
});
|
|
89
|
+
const [stdout, stderr, code] = await Promise.race([operation, timeout]);
|
|
90
|
+
if (code !== 0) throw new Error(stderr.trim() || "OpenCode version check failed.");
|
|
91
|
+
return stdout.trim();
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (error?.code === "ENOENT") {
|
|
94
|
+
throw new Error("OpenCode is unavailable. Install it and make sure `opencode --version` succeeds.");
|
|
95
|
+
}
|
|
96
|
+
throw error;
|
|
97
|
+
} finally {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function parseOpenCodeOutput(stdout) {
|
|
103
|
+
let text = "";
|
|
104
|
+
let sessionId = null;
|
|
105
|
+
let error = "";
|
|
106
|
+
|
|
107
|
+
for (const line of stdout.split("\n")) {
|
|
108
|
+
if (!line.trim().startsWith("{")) continue;
|
|
109
|
+
try {
|
|
110
|
+
const event = JSON.parse(line);
|
|
111
|
+
const candidate = event.part?.type === "text" ? event.part.text : event.type === "text" ? event.text : null;
|
|
112
|
+
if (typeof candidate === "string" && candidate.trim()) text = candidate.trim();
|
|
113
|
+
const eventSessionId = event.sessionID ?? event.sessionId ?? event.part?.sessionID;
|
|
114
|
+
if (typeof eventSessionId === "string" && eventSessionId) sessionId = eventSessionId;
|
|
115
|
+
const eventError = event.error?.data?.message ?? event.error?.message;
|
|
116
|
+
if (typeof eventError === "string" && eventError.trim()) error = eventError.trim();
|
|
117
|
+
} catch {
|
|
118
|
+
// OpenCode can emit non-JSON diagnostics between JSON events.
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return { text, sessionId, error };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function collect(stream, limit = 10 * 1024 * 1024) {
|
|
125
|
+
return new Promise((resolve, reject) => {
|
|
126
|
+
let output = "";
|
|
127
|
+
stream.on("data", (chunk) => {
|
|
128
|
+
output += chunk;
|
|
129
|
+
if (output.length > limit) stream.destroy(new Error("OpenCode output exceeded 10 MB."));
|
|
130
|
+
});
|
|
131
|
+
stream.once("error", reject);
|
|
132
|
+
stream.once("end", () => resolve(output));
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function waitForExit(child) {
|
|
137
|
+
return new Promise((resolve, reject) => {
|
|
138
|
+
child.once("error", reject);
|
|
139
|
+
child.once("close", (code) => resolve(code ?? 1));
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function terminateChild(child, platform) {
|
|
144
|
+
if (platform === "win32" && child.pid) {
|
|
145
|
+
crossSpawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore" });
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
child.kill();
|
|
149
|
+
const force = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
|
150
|
+
force.unref?.();
|
|
151
|
+
}
|
package/src/state.mjs
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access, chmod, link, mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
|
|
7
|
+
const MANIFEST = {
|
|
8
|
+
display_information: {
|
|
9
|
+
name: "Pippette",
|
|
10
|
+
description: "Pippette connects Slack to OpenCode running on your computer.",
|
|
11
|
+
background_color: "#1f2de6",
|
|
12
|
+
long_description: "Pippette connects Slack to the OpenCode installed on your computer. Send text requests from Slack and receive replies in threads for the local folder you choose. OpenCode runs locally, and your Slack credentials stay on your machine. Learn more at usepipa.com.",
|
|
13
|
+
},
|
|
14
|
+
features: {
|
|
15
|
+
bot_user: {
|
|
16
|
+
display_name: "Pippette",
|
|
17
|
+
always_online: true,
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
oauth_config: {
|
|
21
|
+
scopes: {
|
|
22
|
+
user: ["files:read", "files:write"],
|
|
23
|
+
bot: [
|
|
24
|
+
"files:read",
|
|
25
|
+
"app_mentions:read",
|
|
26
|
+
"channels:history",
|
|
27
|
+
"chat:write",
|
|
28
|
+
"groups:history",
|
|
29
|
+
"groups:read",
|
|
30
|
+
"reactions:write",
|
|
31
|
+
"users:read",
|
|
32
|
+
"files:write",
|
|
33
|
+
],
|
|
34
|
+
},
|
|
35
|
+
pkce_enabled: false,
|
|
36
|
+
},
|
|
37
|
+
settings: {
|
|
38
|
+
event_subscriptions: {
|
|
39
|
+
bot_events: ["app_mention", "message.channels", "message.groups"],
|
|
40
|
+
},
|
|
41
|
+
interactivity: { is_enabled: true },
|
|
42
|
+
org_deploy_enabled: false,
|
|
43
|
+
socket_mode_enabled: true,
|
|
44
|
+
token_rotation_enabled: false,
|
|
45
|
+
is_mcp_enabled: false,
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export function pipaPaths(home = process.env.PIPA_HOME || os.homedir()) {
|
|
50
|
+
const directory = path.join(home, ".pipa");
|
|
51
|
+
return {
|
|
52
|
+
directory,
|
|
53
|
+
config: path.join(directory, "config.json"),
|
|
54
|
+
manifest: path.join(directory, "slack-manifest.json"),
|
|
55
|
+
lock: path.join(directory, "pipa.lock"),
|
|
56
|
+
sessions: path.join(directory, "sessions.json"),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function acquireInstanceLock(file = pipaPaths().lock) {
|
|
61
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
62
|
+
const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
63
|
+
await writeFile(temporary, String(process.pid), { mode: 0o600 });
|
|
64
|
+
try {
|
|
65
|
+
await claimLock(temporary, file);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (error?.code !== "EEXIST") throw error;
|
|
68
|
+
const pid = Number.parseInt(await readFile(file, "utf8").catch(() => ""), 10);
|
|
69
|
+
if (pid && isRunning(pid)) throw new Error(`Pipa is already running (PID ${pid}).`);
|
|
70
|
+
await rm(file, { force: true });
|
|
71
|
+
await claimLock(temporary, file);
|
|
72
|
+
} finally {
|
|
73
|
+
await rm(temporary, { force: true });
|
|
74
|
+
}
|
|
75
|
+
return () => rm(file, { force: true });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function createManifest(botName) {
|
|
79
|
+
const name = validateBotName(botName);
|
|
80
|
+
const manifest = structuredClone(MANIFEST);
|
|
81
|
+
manifest.display_information.name = name;
|
|
82
|
+
manifest.display_information.description = manifest.display_information.description.replaceAll("Pippette", name);
|
|
83
|
+
manifest.display_information.long_description = manifest.display_information.long_description.replaceAll("Pippette", name);
|
|
84
|
+
manifest.features.bot_user.display_name = name;
|
|
85
|
+
return manifest;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function createManifestUrl(manifest) {
|
|
89
|
+
return `https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(manifest))}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function canonicalWorkingDirectory(directory) {
|
|
93
|
+
const resolved = await realpath(path.resolve(directory));
|
|
94
|
+
if (!(await stat(resolved)).isDirectory()) throw new Error("Working directory must be a directory.");
|
|
95
|
+
await access(resolved, constants.R_OK | constants.W_OK);
|
|
96
|
+
return resolved;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function loadConfig(file = pipaPaths().config) {
|
|
100
|
+
const config = await readJson(file, "Run `pipa init` first.");
|
|
101
|
+
for (const key of ["botName", "slackAppToken", "slackBotToken", "workingDirectory"]) {
|
|
102
|
+
if (typeof config[key] !== "string" || !config[key].trim()) {
|
|
103
|
+
throw new Error(`Invalid Pipa config: ${key} is missing.`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return config;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function saveConfig(config, paths = pipaPaths(), manifest = createManifest(config.botName)) {
|
|
110
|
+
await writePrivateJson(paths.manifest, manifest);
|
|
111
|
+
await writePrivateJson(paths.config, config);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function loadSessions(file = pipaPaths().sessions) {
|
|
115
|
+
try {
|
|
116
|
+
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
117
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
|
|
118
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
119
|
+
if (typeof value !== "string" || !value) throw new Error(`invalid session for ${key}`);
|
|
120
|
+
}
|
|
121
|
+
return parsed;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (error?.code === "ENOENT") return {};
|
|
124
|
+
throw new Error(`Could not read Pipa sessions: ${error.message}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function createSessionStore(file = pipaPaths().sessions, writeJson = writePrivateJson) {
|
|
129
|
+
const sessions = await loadSessions(file);
|
|
130
|
+
let writeTail = Promise.resolve();
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
keys: () => Object.keys(sessions),
|
|
134
|
+
get: (conversationKey) => sessions[conversationKey] ?? null,
|
|
135
|
+
async set(conversationKey, sessionId) {
|
|
136
|
+
sessions[conversationKey] = sessionId;
|
|
137
|
+
const write = writeTail.then(() => writeJson(file, sessions));
|
|
138
|
+
writeTail = write.catch(() => undefined);
|
|
139
|
+
await write;
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function readJson(file, missingMessage) {
|
|
145
|
+
try {
|
|
146
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (error?.code === "ENOENT") throw new Error(missingMessage);
|
|
149
|
+
throw new Error(`Could not read ${path.basename(file)}: ${error.message}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function writePrivateJson(file, value) {
|
|
154
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
155
|
+
const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
156
|
+
try {
|
|
157
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
158
|
+
if (process.platform !== "win32") await chmod(temporary, 0o600);
|
|
159
|
+
await rename(temporary, file);
|
|
160
|
+
} finally {
|
|
161
|
+
await rm(temporary, { force: true });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function validateBotName(value) {
|
|
166
|
+
const name = String(value ?? "").trim();
|
|
167
|
+
if (!name || name.length > 35 || /[\r\n]/u.test(name)) {
|
|
168
|
+
throw new Error("Bot name must be 1 to 35 characters on one line.");
|
|
169
|
+
}
|
|
170
|
+
return name;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function isRunning(pid) {
|
|
174
|
+
try {
|
|
175
|
+
process.kill(pid, 0);
|
|
176
|
+
return true;
|
|
177
|
+
} catch (error) {
|
|
178
|
+
return error?.code === "EPERM";
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function claimLock(source, destination) {
|
|
183
|
+
return link(source, destination);
|
|
184
|
+
}
|