khala-cli 0.3.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 +201 -0
- package/README.md +33 -0
- package/dist/chunk-4C2TBZVA.mjs +245 -0
- package/dist/chunk-525XNG6V.mjs +110 -0
- package/dist/chunk-6FNXMYOM.mjs +8 -0
- package/dist/chunk-6GOETMWV.mjs +91 -0
- package/dist/chunk-CTXFYQIX.mjs +352 -0
- package/dist/chunk-FGIU3YO2.mjs +214 -0
- package/dist/chunk-GO5DD2TR.mjs +442 -0
- package/dist/chunk-H2JCKPFR.mjs +149 -0
- package/dist/chunk-HMGN52QY.mjs +11 -0
- package/dist/chunk-HWKLLI7F.mjs +1652 -0
- package/dist/chunk-MGXWUWWP.mjs +1294 -0
- package/dist/chunk-PQO6675G.mjs +135 -0
- package/dist/chunk-S6XASSNU.mjs +120 -0
- package/dist/chunk-UYTGV6TW.mjs +280 -0
- package/dist/chunk-Y3TDVOGT.mjs +11 -0
- package/dist/chunk-ZRUF3P53.mjs +557 -0
- package/dist/khala.mjs +89 -0
- package/dist/web/assets/Bungee-Regular-BC4W3tCU.woff2 +0 -0
- package/dist/web/assets/JetBrainsMono-Variable-CZ7Klmjc.woff2 +0 -0
- package/dist/web/assets/SpaceGrotesk-Variable-BWuzNAiS.woff2 +0 -0
- package/dist/web/assets/aiur-logo-Dx5KVuwr.png +0 -0
- package/dist/web/assets/local-DuGvSGji.css +1 -0
- package/dist/web/assets/local-hWRGqoWt.js +9 -0
- package/dist/web/index.html +14 -0
- package/package.json +35 -0
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 [yyyy] [name of copyright owner]
|
|
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,33 @@
|
|
|
1
|
+
# khala-cli
|
|
2
|
+
|
|
3
|
+
The `khala` command connects your existing Claude Code or Codex session to a
|
|
4
|
+
[Khala](https://khala.aiur.team) channel: an MCP server (`khala_join`, `khala_status`,
|
|
5
|
+
`khala_read`, `khala_send`, `khala_event`), delivery hooks that bring channel messages into
|
|
6
|
+
the session, and local channels on this computer. Requires Node 22 or newer.
|
|
7
|
+
|
|
8
|
+
## Claude Code
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
claude plugin marketplace add aiur-team/khala
|
|
12
|
+
claude plugin install khala@khala
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Restart Claude Code (or exit and `claude --resume <session id>`). The plugin runs this
|
|
16
|
+
package at a pinned version; you do not install it yourself.
|
|
17
|
+
|
|
18
|
+
## Codex
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npx -y khala-cli install codex
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
This installs the CLI under `~/.local/share/khala/npm`, adds `[mcp_servers.khala]` to
|
|
25
|
+
`~/.codex/config.toml` and three delivery hooks to `~/.codex/hooks.json`. Restart or resume
|
|
26
|
+
Codex and trust the three Khala hooks under **Hooks need review**. Undo with
|
|
27
|
+
`npx -y khala-cli install codex --uninstall`.
|
|
28
|
+
|
|
29
|
+
## Then
|
|
30
|
+
|
|
31
|
+
Tell your agent "Join this Khala channel: <link>" and open the confirmation link it returns.
|
|
32
|
+
|
|
33
|
+
Source, docs and issues: <https://github.com/aiur-team/khala/tree/main/packages/agent>.
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { createRequire as __khalaCreateRequire } from 'node:module'; const require = __khalaCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
CHANNEL_EVENT_TYPE,
|
|
4
|
+
LISTENING_MODE_COMMAND_TYPE,
|
|
5
|
+
LISTENING_MODE_MEMBER_KEY
|
|
6
|
+
} from "./chunk-GO5DD2TR.mjs";
|
|
7
|
+
import "./chunk-6FNXMYOM.mjs";
|
|
8
|
+
|
|
9
|
+
// src/matrix/session.ts
|
|
10
|
+
import { createClient, ClientEvent, RoomEvent, MatrixEventEvent, SyncState, Direction, Method, EventType } from "matrix-js-sdk";
|
|
11
|
+
function message(event) {
|
|
12
|
+
const type = event.getType();
|
|
13
|
+
const eventId = event.getId();
|
|
14
|
+
const roomId = event.getRoomId();
|
|
15
|
+
const sender = event.getSender();
|
|
16
|
+
if (event.isDecryptionFailure() || !eventId || !roomId || !sender || type !== "m.room.message" && type !== "com.khala.event.v1") return;
|
|
17
|
+
const content = event.getContent();
|
|
18
|
+
return { eventId, roomId, sender, ts: event.getTs(), type, body: typeof content.body === "string" ? content.body : "", content };
|
|
19
|
+
}
|
|
20
|
+
async function createAgentMatrixSession(creds, opts) {
|
|
21
|
+
const started = Date.now();
|
|
22
|
+
const log = (line) => opts?.log?.(line);
|
|
23
|
+
const client = createClient({ baseUrl: creds.homeserver, userId: creds.userId, accessToken: creds.accessToken, deviceId: creds.deviceId });
|
|
24
|
+
const handlers = /* @__PURE__ */ new Set();
|
|
25
|
+
const modeHandlers = /* @__PURE__ */ new Set();
|
|
26
|
+
const inviters = /* @__PURE__ */ new Map();
|
|
27
|
+
const emitted = /* @__PURE__ */ new Set();
|
|
28
|
+
const liveEvents = /* @__PURE__ */ new Set();
|
|
29
|
+
const joinTimes = /* @__PURE__ */ new Map();
|
|
30
|
+
const cancellations = /* @__PURE__ */ new Set();
|
|
31
|
+
let joinedRoom;
|
|
32
|
+
let stopped = false;
|
|
33
|
+
const deliver = (event) => {
|
|
34
|
+
if (stopped || !liveEvents.has(event)) return;
|
|
35
|
+
const command = event.getType() === LISTENING_MODE_COMMAND_TYPE && !event.isDecryptionFailure() && event.getId() && event.getRoomId() && event.getSender() ? { eventId: event.getId(), roomId: event.getRoomId(), sender: event.getSender(), ts: event.getTs(), content: event.getContent() } : void 0;
|
|
36
|
+
const m = command ?? message(event);
|
|
37
|
+
if (!m) {
|
|
38
|
+
if (event.getType() !== "m.room.encrypted" && !event.isDecryptionFailure()) liveEvents.delete(event);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const cutoff = joinTimes.get(m.roomId);
|
|
42
|
+
if (cutoff === void 0) return;
|
|
43
|
+
if (m.sender === creds.userId || m.ts < cutoff || client.getRoom(m.roomId)?.getMyMembership() !== "join") {
|
|
44
|
+
liveEvents.delete(event);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
liveEvents.delete(event);
|
|
48
|
+
if (emitted.has(m.eventId)) return;
|
|
49
|
+
emitted.add(m.eventId);
|
|
50
|
+
if (command) {
|
|
51
|
+
for (const handler of modeHandlers) {
|
|
52
|
+
try {
|
|
53
|
+
handler(command);
|
|
54
|
+
} catch {
|
|
55
|
+
log("mode_handler_error");
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
} else {
|
|
59
|
+
const entry = message(event);
|
|
60
|
+
for (const handler of handlers) {
|
|
61
|
+
try {
|
|
62
|
+
handler(entry);
|
|
63
|
+
} catch {
|
|
64
|
+
log("message_handler_error");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const timeline = (event, _room, toStart, _removed, data) => {
|
|
70
|
+
if (stopped || toStart || data?.liveEvent === false) return;
|
|
71
|
+
liveEvents.add(event);
|
|
72
|
+
void client.decryptEventIfNeeded(event).then(() => deliver(event), () => log("live_decryption_failed"));
|
|
73
|
+
};
|
|
74
|
+
const decrypted = (event) => deliver(event);
|
|
75
|
+
const syncLog = (state) => log(`sync_state=${state}`);
|
|
76
|
+
const wait = (subscribe, ready, timeoutMs, error) => {
|
|
77
|
+
if (stopped) return Promise.reject(new Error("session_stopped"));
|
|
78
|
+
if (ready()) return Promise.resolve();
|
|
79
|
+
return new Promise((resolve, reject) => {
|
|
80
|
+
let unsubscribe = () => {
|
|
81
|
+
};
|
|
82
|
+
const finish = (failure) => {
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
unsubscribe();
|
|
85
|
+
cancellations.delete(cancel);
|
|
86
|
+
if (failure) reject(new Error(failure));
|
|
87
|
+
else resolve();
|
|
88
|
+
};
|
|
89
|
+
const cancel = () => finish("session_stopped");
|
|
90
|
+
const check = () => {
|
|
91
|
+
if (ready()) finish();
|
|
92
|
+
};
|
|
93
|
+
const timer = setTimeout(() => finish(error), timeoutMs);
|
|
94
|
+
cancellations.add(cancel);
|
|
95
|
+
unsubscribe = subscribe(check);
|
|
96
|
+
check();
|
|
97
|
+
});
|
|
98
|
+
};
|
|
99
|
+
const stop = async () => {
|
|
100
|
+
if (stopped) return;
|
|
101
|
+
stopped = true;
|
|
102
|
+
client.stopClient();
|
|
103
|
+
client.removeListener(RoomEvent.Timeline, timeline);
|
|
104
|
+
client.removeListener(MatrixEventEvent.Decrypted, decrypted);
|
|
105
|
+
client.removeListener(ClientEvent.Sync, syncLog);
|
|
106
|
+
for (const cancel of [...cancellations]) cancel();
|
|
107
|
+
liveEvents.clear();
|
|
108
|
+
emitted.clear();
|
|
109
|
+
handlers.clear();
|
|
110
|
+
modeHandlers.clear();
|
|
111
|
+
};
|
|
112
|
+
try {
|
|
113
|
+
await client.initRustCrypto({ useIndexedDB: false });
|
|
114
|
+
const crypto = client.getCrypto();
|
|
115
|
+
if (!crypto) throw new Error("crypto_unavailable");
|
|
116
|
+
log(`crypto_version=${crypto.getVersion()}`);
|
|
117
|
+
let outcome;
|
|
118
|
+
if (await crypto.isCrossSigningReady()) outcome = "already_ready";
|
|
119
|
+
else if (await crypto.userHasCrossSigningKeys(creds.userId, true)) outcome = "unavailable_existing_identity";
|
|
120
|
+
else {
|
|
121
|
+
await crypto.bootstrapCrossSigning({ authUploadDeviceSigningKeys: async (f) => {
|
|
122
|
+
await f(null);
|
|
123
|
+
} });
|
|
124
|
+
if (!await crypto.isCrossSigningReady()) throw new Error("cross_signing_failed");
|
|
125
|
+
outcome = "bootstrapped";
|
|
126
|
+
}
|
|
127
|
+
log(`cross_signing=${outcome}`);
|
|
128
|
+
client.on(RoomEvent.Timeline, timeline);
|
|
129
|
+
client.on(MatrixEventEvent.Decrypted, decrypted);
|
|
130
|
+
client.on(ClientEvent.Sync, syncLog);
|
|
131
|
+
const prepared = wait((check) => {
|
|
132
|
+
client.on(ClientEvent.Sync, check);
|
|
133
|
+
return () => {
|
|
134
|
+
client.removeListener(ClientEvent.Sync, check);
|
|
135
|
+
};
|
|
136
|
+
}, () => client.getSyncState() === SyncState.Prepared || client.getSyncState() === SyncState.Syncing, 3e4, "sync_timeout");
|
|
137
|
+
await Promise.all([client.startClient({ initialSyncLimit: 30 }), prepared]);
|
|
138
|
+
log(`session_ready_ms=${Date.now() - started}`);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
await stop();
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
const membershipWait = (roomId, ready, timeoutMs, error) => wait((check) => {
|
|
144
|
+
const listener = (room) => {
|
|
145
|
+
if (room.roomId === roomId) check();
|
|
146
|
+
};
|
|
147
|
+
client.on(RoomEvent.MyMembership, listener);
|
|
148
|
+
client.on(ClientEvent.Room, listener);
|
|
149
|
+
return () => {
|
|
150
|
+
client.removeListener(RoomEvent.MyMembership, listener);
|
|
151
|
+
client.removeListener(ClientEvent.Room, listener);
|
|
152
|
+
};
|
|
153
|
+
}, ready, timeoutMs, error);
|
|
154
|
+
return {
|
|
155
|
+
userId: creds.userId,
|
|
156
|
+
inviter(roomId) {
|
|
157
|
+
return inviters.get(roomId);
|
|
158
|
+
},
|
|
159
|
+
onListeningModeCommand(handler) {
|
|
160
|
+
modeHandlers.add(handler);
|
|
161
|
+
return () => {
|
|
162
|
+
modeHandlers.delete(handler);
|
|
163
|
+
};
|
|
164
|
+
},
|
|
165
|
+
async publishListeningMode(roomId, mode, signal) {
|
|
166
|
+
const content = client.getRoom(roomId)?.currentState.getStateEvents("m.room.member", creds.userId)?.getContent();
|
|
167
|
+
if (!content) throw new Error("join_state_unavailable");
|
|
168
|
+
const next = { ...content, membership: "join", [LISTENING_MODE_MEMBER_KEY]: mode };
|
|
169
|
+
await client.sendStateEvent(roomId, EventType.RoomMember, next, creds.userId, { localTimeoutMs: 5e3, ...signal ? { abortSignal: signal } : {} });
|
|
170
|
+
},
|
|
171
|
+
onMessage(handler) {
|
|
172
|
+
handlers.add(handler);
|
|
173
|
+
return () => {
|
|
174
|
+
handlers.delete(handler);
|
|
175
|
+
};
|
|
176
|
+
},
|
|
177
|
+
waitForInvite(roomId, timeoutMs) {
|
|
178
|
+
return membershipWait(roomId, () => ["invite", "join"].includes(client.getRoom(roomId)?.getMyMembership() ?? ""), timeoutMs, "invite_timeout");
|
|
179
|
+
},
|
|
180
|
+
async join(roomId) {
|
|
181
|
+
if (stopped) throw new Error("session_stopped");
|
|
182
|
+
const membership = client.getRoom(roomId)?.getMyMembership();
|
|
183
|
+
if (membership !== "join") {
|
|
184
|
+
if (membership !== "invite") throw new Error("not_invited");
|
|
185
|
+
const inviter = client.getRoom(roomId)?.currentState.getStateEvents("m.room.member", creds.userId)?.getSender();
|
|
186
|
+
if (inviter) inviters.set(roomId, inviter);
|
|
187
|
+
await client.joinRoom(roomId);
|
|
188
|
+
}
|
|
189
|
+
await membershipWait(roomId, () => client.getRoom(roomId)?.getMyMembership() === "join", 3e4, "join_timeout");
|
|
190
|
+
const ownJoin = client.getRoom(roomId)?.currentState.getStateEvents("m.room.member", creds.userId);
|
|
191
|
+
if (!ownJoin || ownJoin.getContent().membership !== "join") throw new Error("join_state_unavailable");
|
|
192
|
+
joinTimes.set(roomId, ownJoin.getTs());
|
|
193
|
+
joinedRoom = roomId;
|
|
194
|
+
for (const event of liveEvents) {
|
|
195
|
+
if (event.getRoomId() === roomId) deliver(event);
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
async history(roomId, limit, before) {
|
|
199
|
+
let token = null;
|
|
200
|
+
if (before !== void 0) {
|
|
201
|
+
const context = await client.http.authedRequest(Method.Get, `/rooms/${encodeURIComponent(roomId)}/context/${encodeURIComponent(before)}`, { limit: "0" });
|
|
202
|
+
token = context.start;
|
|
203
|
+
}
|
|
204
|
+
const res = await client.createMessagesRequest(roomId, token, limit, Direction.Backward);
|
|
205
|
+
const messages = [];
|
|
206
|
+
let undecryptable = 0;
|
|
207
|
+
for (const raw of res.chunk) {
|
|
208
|
+
const event = client.getEventMapper()({ ...raw, room_id: roomId });
|
|
209
|
+
try {
|
|
210
|
+
await client.decryptEventIfNeeded(event);
|
|
211
|
+
} catch {
|
|
212
|
+
}
|
|
213
|
+
if (event.getType() === "m.room.encrypted" || event.isDecryptionFailure()) {
|
|
214
|
+
undecryptable++;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const m = message(event);
|
|
218
|
+
if (m && m.eventId !== before) messages.push(m);
|
|
219
|
+
}
|
|
220
|
+
log(`history_undecryptable=${undecryptable}`);
|
|
221
|
+
messages.reverse();
|
|
222
|
+
const oldest = messages[0];
|
|
223
|
+
return typeof res.end === "string" && oldest ? { messages, nextBefore: oldest.eventId } : { messages };
|
|
224
|
+
},
|
|
225
|
+
async send(roomId, text) {
|
|
226
|
+
const res = await client.sendTextMessage(roomId, text);
|
|
227
|
+
return { eventId: res.event_id };
|
|
228
|
+
},
|
|
229
|
+
async sendChannelEvent(roomId, content, txnId) {
|
|
230
|
+
const res = await client.sendEvent(roomId, CHANNEL_EVENT_TYPE, content, txnId);
|
|
231
|
+
return { eventId: res.event_id };
|
|
232
|
+
},
|
|
233
|
+
roomName(roomId) {
|
|
234
|
+
return client.getRoom(roomId)?.name ?? void 0;
|
|
235
|
+
},
|
|
236
|
+
displayName(userId) {
|
|
237
|
+
const value = joinedRoom && client.getRoom(joinedRoom)?.currentState.getStateEvents("m.room.member", userId)?.getContent().displayname;
|
|
238
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
239
|
+
},
|
|
240
|
+
stop
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
export {
|
|
244
|
+
createAgentMatrixSession
|
|
245
|
+
};
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { createRequire as __khalaCreateRequire } from 'node:module'; const require = __khalaCreateRequire(import.meta.url);
|
|
2
|
+
import "./chunk-6FNXMYOM.mjs";
|
|
3
|
+
|
|
4
|
+
// hooks/claude-wake.ts
|
|
5
|
+
import fs from "node:fs/promises";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import os from "node:os";
|
|
8
|
+
import { randomBytes } from "node:crypto";
|
|
9
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
10
|
+
var NOTICE = "Khala: new channel messages. They arrive in the next hook context.\n";
|
|
11
|
+
var DEADLINE_MS = 3e3 * 1e3;
|
|
12
|
+
var POLL_MS = 500;
|
|
13
|
+
async function readJson(file) {
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(await fs.readFile(file, "utf8"));
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (error instanceof SyntaxError || error.code === "ENOENT") return null;
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
async function unreadMessages(dir) {
|
|
22
|
+
const cursor = await readJson(path.join(dir, "cursor.json"));
|
|
23
|
+
const delivered = cursor && (cursor.lastDeliveredEventId === null || typeof cursor.lastDeliveredEventId === "string") && Number.isSafeInteger(cursor.deliveredCount) && typeof cursor.deliveredCount === "number" && cursor.deliveredCount >= 0 ? cursor.deliveredCount : 0;
|
|
24
|
+
let content;
|
|
25
|
+
try {
|
|
26
|
+
content = await fs.readFile(path.join(dir, "inbox.jsonl"), "utf8");
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if (error.code === "ENOENT") return 0;
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
let index = 0, messages = 0;
|
|
32
|
+
for (const line of content.split("\n").slice(0, -1)) {
|
|
33
|
+
let entry;
|
|
34
|
+
try {
|
|
35
|
+
entry = JSON.parse(line);
|
|
36
|
+
} catch {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (!entry || !["eventId", "roomId", "ts", "sender", "senderLabel", "body"].every((key) => typeof entry[key] === "string") || !["human", "agent", "unknown"].includes(entry.senderKind) || !["message", "event"].includes(entry.kind)) continue;
|
|
40
|
+
if (index++ >= delivered && entry.kind === "message") messages++;
|
|
41
|
+
}
|
|
42
|
+
return messages;
|
|
43
|
+
}
|
|
44
|
+
function testDuration(value, fallback) {
|
|
45
|
+
const number = Number(value);
|
|
46
|
+
return Number.isSafeInteger(number) && number > 0 ? number : fallback;
|
|
47
|
+
}
|
|
48
|
+
function parentAlive(parent) {
|
|
49
|
+
if (process.ppid !== parent) return false;
|
|
50
|
+
try {
|
|
51
|
+
process.kill(parent, 0);
|
|
52
|
+
return true;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (error.code === "EPERM") return true;
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function watch(stdin, _argv, io = { stderr: process.stderr, env: process.env, now: () => /* @__PURE__ */ new Date() }) {
|
|
59
|
+
let temporary;
|
|
60
|
+
try {
|
|
61
|
+
const parent = process.ppid;
|
|
62
|
+
const input = JSON.parse(stdin);
|
|
63
|
+
if (input?.hook_event_name !== "Stop" || typeof input.session_id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(input.session_id)) return 0;
|
|
64
|
+
const root = io.env.XDG_STATE_HOME && path.isAbsolute(io.env.XDG_STATE_HOME) ? io.env.XDG_STATE_HOME : path.join(io.env.HOME ?? os.homedir(), ".local/state");
|
|
65
|
+
const dir = path.join(root, "khala", "claude", input.session_id);
|
|
66
|
+
if (!(await fs.stat(dir)).isDirectory()) return 0;
|
|
67
|
+
const nonce = randomBytes(6).toString("hex");
|
|
68
|
+
const owner = path.join(dir, "watcher.json");
|
|
69
|
+
temporary = path.join(dir, `.watcher-${nonce}.tmp`);
|
|
70
|
+
const started = io.now();
|
|
71
|
+
await fs.writeFile(temporary, JSON.stringify({ nonce, armedAt: started.toISOString() }) + "\n", { mode: 384, flag: "wx" });
|
|
72
|
+
await fs.rename(temporary, owner);
|
|
73
|
+
temporary = void 0;
|
|
74
|
+
const deadline = started.getTime() + testDuration(io.env.KHALA_WAKE_TEST_DEADLINE_MS, DEADLINE_MS);
|
|
75
|
+
const poll = testDuration(io.env.KHALA_WAKE_TEST_POLL_MS, POLL_MS);
|
|
76
|
+
const owns = async () => (await readJson(owner))?.nonce === nonce;
|
|
77
|
+
const idle = async () => {
|
|
78
|
+
const activity = await readJson(path.join(dir, "activity.json"));
|
|
79
|
+
return activity?.state === "idle" && typeof activity.updatedAt === "string" && Number.isFinite(Date.parse(activity.updatedAt));
|
|
80
|
+
};
|
|
81
|
+
const listening = async () => (await readJson(path.join(dir, "mode.json")))?.mode !== "async";
|
|
82
|
+
while (io.now().getTime() < deadline) {
|
|
83
|
+
if (!await owns() || !parentAlive(parent)) return 0;
|
|
84
|
+
if (await listening() && await idle() && await unreadMessages(dir) > 0) {
|
|
85
|
+
if (await unreadMessages(dir) > 0 && await listening() && await idle() && await owns() && parentAlive(parent) && io.now().getTime() < deadline) {
|
|
86
|
+
io.stderr.write(NOTICE);
|
|
87
|
+
return 2;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
await sleep(Math.min(poll, Math.max(0, deadline - io.now().getTime())));
|
|
91
|
+
}
|
|
92
|
+
} catch {
|
|
93
|
+
} finally {
|
|
94
|
+
if (temporary) {
|
|
95
|
+
try {
|
|
96
|
+
await fs.unlink(temporary);
|
|
97
|
+
} catch {
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return 0;
|
|
102
|
+
}
|
|
103
|
+
async function run(stdin, argv) {
|
|
104
|
+
return watch(stdin, argv);
|
|
105
|
+
}
|
|
106
|
+
export {
|
|
107
|
+
run as default,
|
|
108
|
+
unreadMessages,
|
|
109
|
+
watch
|
|
110
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createRequire as __khalaCreateRequire } from 'node:module'; const require = __khalaCreateRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// <define:__KHALA_BUNDLE__>
|
|
4
|
+
var define_KHALA_BUNDLE_default = { name: "khala-cli", version: "0.3.0" };
|
|
5
|
+
|
|
6
|
+
export {
|
|
7
|
+
define_KHALA_BUNDLE_default
|
|
8
|
+
};
|