@cotal-ai/connector-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,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.
@@ -0,0 +1,89 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { CotalEndpoint, type ControlReply, type Presence, type PresenceStatus, type CotalMessage } from "@cotal-ai/core";
3
+ import type { AgentConfig } from "./config.js";
4
+ /** A message that has arrived for us, normalized for the agent to read. */
5
+ export interface InboxItem {
6
+ id: string;
7
+ ts: number;
8
+ fromId: string;
9
+ fromName: string;
10
+ fromRole?: string;
11
+ kind: "channel" | "dm" | "anycast";
12
+ /** Set when kind === "channel". */
13
+ channel?: string;
14
+ /** Set when kind === "anycast" (the role addressed). */
15
+ service?: string;
16
+ /** Lowercased names called out on a channel message (priority hint). */
17
+ mentions?: string[];
18
+ /** True iff this message mentions us by name — computed once, here. Drives high-priority wake. */
19
+ mentionsMe: boolean;
20
+ text: string;
21
+ replyTo?: string;
22
+ contextId?: string;
23
+ }
24
+ /**
25
+ * A thin, mesh-native agent: a {@link CotalEndpoint} plus a buffered inbox and
26
+ * name-based peer resolution. This is the shared core behind the MCP server
27
+ * (and, later, the lifecycle hooks) — it owns the NATS connection and presence.
28
+ *
29
+ * Connecting is resilient: {@link start} kicks off a background retry loop so the
30
+ * MCP server is responsive immediately even if the mesh isn't up yet.
31
+ *
32
+ * Emits `"incoming"` (InboxItem) after each message is buffered, so a push layer
33
+ * (the channel) can deliver it immediately; `"wake"` (no payload) to ask that layer to
34
+ * wake the session now (the Stop→idle flush of held messages); `"error"` (Error) for
35
+ * endpoint faults.
36
+ */
37
+ export declare class MeshAgent extends EventEmitter {
38
+ readonly ep: CotalEndpoint;
39
+ readonly config: AgentConfig;
40
+ private inbox;
41
+ private _connected;
42
+ private _status;
43
+ private stopping;
44
+ constructor(config: AgentConfig);
45
+ get id(): string;
46
+ get connected(): boolean;
47
+ /** Begin connecting (with background retry). Returns immediately. */
48
+ start(retryMs?: number): void;
49
+ private connectLoop;
50
+ stop(): Promise<void>;
51
+ private ingest;
52
+ /** Return pending messages and ack them — call only when they're actually surfaced to the model. */
53
+ drainInbox(limit?: number): InboxItem[];
54
+ /** Return pending messages without acking them (they stay on the stream). */
55
+ peekInbox(): InboxItem[];
56
+ inboxCount(): number;
57
+ /** Ask any push layer (the channel) to wake the session now — used by the Stop→idle flush
58
+ * to deliver a batch of held ambient messages. Emits `"wake"`; a no-op if nothing listens.
59
+ * Never acks or drains: {@link drainInbox} stays the sole ack site. */
60
+ requestWake(): void;
61
+ send(text: string, channel?: string, mentions?: string[]): Promise<CotalMessage>;
62
+ /** Throw if any name isn't a peer we've observed. Validates against the FULL roster
63
+ * (incl. self — your own name is a valid participant; resolvePeer's self-filter would
64
+ * wrongly reject it), case-insensitively. Send is all-or-nothing: one unknown @name aborts
65
+ * the whole broadcast (fail-loud on typos). Caveat: only catches peers THIS client has seen
66
+ * — an offline peer lingers in the roster, but one never observed (or not yet filled in
67
+ * after connect) throws. See docs/architecture.md. */
68
+ private assertKnownMentions;
69
+ anycast(role: string, text: string): Promise<CotalMessage>;
70
+ /** Resolve a peer by instance id (exact) or display name (case-insensitive, prefer present). */
71
+ resolvePeer(target: string): Presence | undefined;
72
+ dm(target: string, text: string): Promise<{
73
+ msg: CotalMessage;
74
+ peer: Presence;
75
+ }>;
76
+ /** Ask the manager to spawn a new teammate into this space (its `start` op).
77
+ * How it lands — a detached PTY, a tmux window, a cmux tab — is the manager's
78
+ * runtime; from here it just joins the mesh as a lateral peer. */
79
+ spawn(name: string, role?: string): Promise<ControlReply>;
80
+ /** The full roster, including ourselves. */
81
+ roster(): Presence[];
82
+ /** Our last self-reported presence status. */
83
+ get status(): PresenceStatus;
84
+ setStatus(status: PresenceStatus, activity?: string): Promise<void>;
85
+ private who;
86
+ private assertConnected;
87
+ private log;
88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;IAQvB,OAAO,CAAC,GAAG;CAGZ"}
package/dist/agent.js ADDED
@@ -0,0 +1,215 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { normalizeMentions, CotalEndpoint, } from "@cotal-ai/core";
3
+ const MAX_INBOX = 200;
4
+ function sleep(ms) {
5
+ return new Promise((r) => setTimeout(r, ms));
6
+ }
7
+ /**
8
+ * A thin, mesh-native agent: a {@link CotalEndpoint} plus a buffered inbox and
9
+ * name-based peer resolution. This is the shared core behind the MCP server
10
+ * (and, later, the lifecycle hooks) — it owns the NATS connection and presence.
11
+ *
12
+ * Connecting is resilient: {@link start} kicks off a background retry loop so the
13
+ * MCP server is responsive immediately even if the mesh isn't up yet.
14
+ *
15
+ * Emits `"incoming"` (InboxItem) after each message is buffered, so a push layer
16
+ * (the channel) can deliver it immediately; `"wake"` (no payload) to ask that layer to
17
+ * wake the session now (the Stop→idle flush of held messages); `"error"` (Error) for
18
+ * endpoint faults.
19
+ */
20
+ export class MeshAgent extends EventEmitter {
21
+ ep;
22
+ config;
23
+ inbox = [];
24
+ _connected = false;
25
+ _status = "idle";
26
+ stopping = false;
27
+ constructor(config) {
28
+ super();
29
+ this.config = config;
30
+ this.ep = new CotalEndpoint({
31
+ space: config.space,
32
+ servers: config.servers,
33
+ token: config.token,
34
+ user: config.user,
35
+ pass: config.pass,
36
+ creds: config.creds,
37
+ tls: config.tls,
38
+ channels: config.channels,
39
+ card: {
40
+ id: config.id,
41
+ name: config.name,
42
+ role: config.role,
43
+ kind: config.kind,
44
+ description: config.description,
45
+ tags: config.tags,
46
+ },
47
+ });
48
+ this.ep.on("message", (m, d) => this.ingest(m, d));
49
+ this.ep.on("error", (e) => this.log(`endpoint error: ${e.message}`));
50
+ }
51
+ get id() {
52
+ return this.ep.card.id;
53
+ }
54
+ get connected() {
55
+ return this._connected;
56
+ }
57
+ /** Begin connecting (with background retry). Returns immediately. */
58
+ start(retryMs = 3000) {
59
+ void this.connectLoop(retryMs);
60
+ }
61
+ async connectLoop(retryMs) {
62
+ while (!this.stopping && !this._connected) {
63
+ try {
64
+ await this.ep.start();
65
+ this._connected = true;
66
+ this.log(`connected to ${this.config.servers} as ${this.who()} in space "${this.config.space}" on #${this.config.channels.join(", #")}`);
67
+ }
68
+ catch (e) {
69
+ this.log(`mesh unreachable (${e.message}); retrying in ${retryMs}ms`);
70
+ await sleep(retryMs);
71
+ }
72
+ }
73
+ }
74
+ async stop() {
75
+ this.stopping = true;
76
+ if (this._connected)
77
+ await this.ep.stop();
78
+ }
79
+ // ---- inbox ---------------------------------------------------------------
80
+ ingest(m, delivery) {
81
+ // Redelivery (we held it unacked past ack_wait): keep one entry, take the freshest ack handle.
82
+ const existing = this.inbox.find((p) => p.item.id === m.id);
83
+ if (existing) {
84
+ existing.ack = delivery.ack;
85
+ return;
86
+ }
87
+ const text = m.parts
88
+ .map((p) => (p.kind === "text" ? p.text : JSON.stringify(p.data)))
89
+ .join(" ");
90
+ const kind = m.to ? "dm" : m.toService ? "anycast" : "channel";
91
+ const item = {
92
+ id: m.id,
93
+ ts: m.ts,
94
+ fromId: m.from.id,
95
+ fromName: m.from.name,
96
+ fromRole: m.from.role,
97
+ kind,
98
+ channel: m.channel,
99
+ service: m.toService,
100
+ mentions: m.mentions,
101
+ mentionsMe: m.mentions?.includes(this.config.name.toLowerCase()) ?? false,
102
+ text,
103
+ replyTo: m.replyTo,
104
+ contextId: m.contextId,
105
+ };
106
+ this.inbox.push({ item, ack: delivery.ack });
107
+ if (this.inbox.length > MAX_INBOX) {
108
+ // Pathological backlog: ack the overflow so it stops redelivering.
109
+ for (const p of this.inbox.splice(0, this.inbox.length - MAX_INBOX))
110
+ p.ack();
111
+ }
112
+ this.emit("incoming", item);
113
+ }
114
+ /** Return pending messages and ack them — call only when they're actually surfaced to the model. */
115
+ drainInbox(limit) {
116
+ const n = limit && limit > 0 ? Math.min(limit, this.inbox.length) : this.inbox.length;
117
+ const taken = this.inbox.splice(0, n);
118
+ for (const p of taken)
119
+ p.ack();
120
+ return taken.map((p) => p.item);
121
+ }
122
+ /** Return pending messages without acking them (they stay on the stream). */
123
+ peekInbox() {
124
+ return this.inbox.map((p) => p.item);
125
+ }
126
+ inboxCount() {
127
+ return this.inbox.length;
128
+ }
129
+ /** Ask any push layer (the channel) to wake the session now — used by the Stop→idle flush
130
+ * to deliver a batch of held ambient messages. Emits `"wake"`; a no-op if nothing listens.
131
+ * Never acks or drains: {@link drainInbox} stays the sole ack site. */
132
+ requestWake() {
133
+ this.emit("wake");
134
+ }
135
+ // ---- sending -------------------------------------------------------------
136
+ async send(text, channel, mentions) {
137
+ this.assertConnected();
138
+ const clean = normalizeMentions(mentions);
139
+ if (clean)
140
+ this.assertKnownMentions(clean);
141
+ return this.ep.multicast(text, { channel, mentions: clean });
142
+ }
143
+ /** Throw if any name isn't a peer we've observed. Validates against the FULL roster
144
+ * (incl. self — your own name is a valid participant; resolvePeer's self-filter would
145
+ * wrongly reject it), case-insensitively. Send is all-or-nothing: one unknown @name aborts
146
+ * the whole broadcast (fail-loud on typos). Caveat: only catches peers THIS client has seen
147
+ * — an offline peer lingers in the roster, but one never observed (or not yet filled in
148
+ * after connect) throws. See docs/architecture.md. */
149
+ assertKnownMentions(mentions) {
150
+ const names = new Set(this.ep.getRoster().map((p) => p.card.name.toLowerCase()));
151
+ const unknown = mentions.filter((m) => !names.has(m));
152
+ if (unknown.length)
153
+ throw new Error(`unknown mention${unknown.length > 1 ? "s" : ""}: ${unknown.map((u) => `@${u}`).join(", ")} — no such peer observed in space "${this.config.space}"`);
154
+ }
155
+ async anycast(role, text) {
156
+ this.assertConnected();
157
+ return this.ep.anycast(role, text);
158
+ }
159
+ /** Resolve a peer by instance id (exact) or display name (case-insensitive, prefer present). */
160
+ resolvePeer(target) {
161
+ const roster = this.ep.getRoster().filter((p) => p.card.id !== this.id);
162
+ const byId = roster.find((p) => p.card.id === target);
163
+ if (byId)
164
+ return byId;
165
+ const t = target.toLowerCase();
166
+ const present = roster.filter((p) => p.status !== "offline");
167
+ return (present.find((p) => p.card.name.toLowerCase() === t) ??
168
+ roster.find((p) => p.card.name.toLowerCase() === t));
169
+ }
170
+ async dm(target, text) {
171
+ this.assertConnected();
172
+ const peer = this.resolvePeer(target);
173
+ if (!peer)
174
+ throw new Error(`no peer "${target}" in space "${this.config.space}"`);
175
+ const msg = await this.ep.unicast(peer.card.id, text);
176
+ return { msg, peer };
177
+ }
178
+ // ---- supervision ---------------------------------------------------------
179
+ /** Ask the manager to spawn a new teammate into this space (its `start` op).
180
+ * How it lands — a detached PTY, a tmux window, a cmux tab — is the manager's
181
+ * runtime; from here it just joins the mesh as a lateral peer. */
182
+ async spawn(name, role) {
183
+ this.assertConnected();
184
+ return this.ep.requestControl("manager", { op: "start", args: { name, role } });
185
+ }
186
+ // ---- presence ------------------------------------------------------------
187
+ /** The full roster, including ourselves. */
188
+ roster() {
189
+ return this.ep.getRoster();
190
+ }
191
+ /** Our last self-reported presence status. */
192
+ get status() {
193
+ return this._status;
194
+ }
195
+ async setStatus(status, activity) {
196
+ this.assertConnected();
197
+ this._status = status;
198
+ if (activity !== undefined)
199
+ await this.ep.setActivity(activity);
200
+ await this.ep.setStatus(status);
201
+ }
202
+ // ---- internals -----------------------------------------------------------
203
+ who() {
204
+ return this.config.role ? `${this.config.name}/${this.config.role}` : this.config.name;
205
+ }
206
+ assertConnected() {
207
+ if (!this._connected) {
208
+ throw new Error(`not connected to the mesh at ${this.config.servers} — is it running? (pnpm cotal up)`);
209
+ }
210
+ }
211
+ log(msg) {
212
+ process.stderr.write(`[cotal-connector] ${msg}\n`);
213
+ }
214
+ }
215
+ //# sourceMappingURL=agent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,iBAAiB,EACjB,aAAa,GAMd,MAAM,gBAAgB,CAAC;AA+BxB,MAAM,SAAS,GAAG,GAAG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C;IACzF,CAAC;IAEO,eAAe;QACrB,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CACb,gCAAgC,IAAI,CAAC,MAAM,CAAC,OAAO,mCAAmC,CACvF,CAAC;QACJ,CAAC;IACH,CAAC;IAEO,GAAG,CAAC,GAAW;QACrB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,qBAAqB,GAAG,IAAI,CAAC,CAAC;IACrD,CAAC;CACF"}
@@ -0,0 +1,48 @@
1
+ import { type EndpointKind } from "@cotal-ai/core";
2
+ /**
3
+ * How a connector instance presents itself on the mesh. Everything is read from
4
+ * the environment so the *launcher* (the manager spawning an agent, or a human
5
+ * running `cotal join` / their own terminal) decides identity once and both the
6
+ * MCP server and the lifecycle hooks inherit it.
7
+ */
8
+ export interface AgentConfig {
9
+ space: string;
10
+ /** Stable agent id (nkey public key) from the launcher; falls back to a random
11
+ * uuid in the endpoint when absent (unmanaged sessions). */
12
+ id?: string;
13
+ /** Minted creds file content (auth mode); the endpoint authenticates with it. */
14
+ creds?: string;
15
+ name: string;
16
+ role?: string;
17
+ description?: string;
18
+ tags?: string[];
19
+ servers: string;
20
+ /** Channels this agent subscribes to (read). May include wildcard subtrees (`team.>`). */
21
+ channels: string[];
22
+ /** Channels this agent may post to (write). Falls back to `channels` when unset, matching
23
+ * the agent-file convention and the minted publish ACL. */
24
+ publish: string[];
25
+ kind: EndpointKind;
26
+ token?: string;
27
+ user?: string;
28
+ pass?: string;
29
+ tls: boolean;
30
+ }
31
+ /** True iff the env carries a Cotal identity — i.e. this is a launcher-spawned
32
+ * session, not an operator's plain `claude`. `COTAL_LINK` / `COTAL_AGENT_FILE`
33
+ * count: setting either is itself the explicit opt-in. The connector stays
34
+ * inert otherwise. */
35
+ export declare function hasIdentity(env?: NodeJS.ProcessEnv): boolean;
36
+ /** Build an {@link AgentConfig} from `COTAL_*` environment variables. Two refs
37
+ * fill many fields at once: `COTAL_LINK` (cotal://token@host/space) supplies the
38
+ * *where* (server, auth, space); `COTAL_AGENT_FILE` (.cotal/agents/<name>.md)
39
+ * supplies the *who* (name, role, kind, channels, description, tags).
40
+ * Individual `COTAL_*` vars override both. Identity is NOT silently defaulted
41
+ * unless a link is present — guard with {@link hasIdentity} first. */
42
+ export declare function configFromEnv(env?: NodeJS.ProcessEnv): AgentConfig;
43
+ /** One sentence telling the agent its channel lanes — what it reads and where it may post —
44
+ * so it knows its scope up front instead of discovering it from inbound tags and send errors.
45
+ * Folded into each connector's MCP `instructions`. Publish outside the lane is rejected by the
46
+ * broker (auth mode), so state it plainly. */
47
+ export declare function laneLine(config: AgentConfig): string;
48
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAEA,OAAO,EAA+D,KAAK,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEhH;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd;iEAC6D;IAC7D,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,iFAAiF;IACjF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,0FAA0F;IAC1F,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB;gEAC4D;IAC5D,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,YAAY,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,OAAO,CAAC;CACd;AAUD;;;uBAGuB;AACvB,wBAAgB,WAAW,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,OAAO,CAEzE;AAED;;;;;uEAKuE;AACvE,wBAAgB,aAAa,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,WAAW,CA6B/E;AAED;;;+CAG+C;AAC/C,wBAAgB,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAQpD"}
package/dist/config.js ADDED
@@ -0,0 +1,68 @@
1
+ import { userInfo } from "node:os";
2
+ import { readFileSync } from "node:fs";
3
+ import { DEFAULT_SERVER, loadAgentFile, parseJoinLink } from "@cotal-ai/core";
4
+ function splitList(v) {
5
+ if (!v)
6
+ return [];
7
+ return v
8
+ .split(",")
9
+ .map((s) => s.trim())
10
+ .filter(Boolean);
11
+ }
12
+ /** True iff the env carries a Cotal identity — i.e. this is a launcher-spawned
13
+ * session, not an operator's plain `claude`. `COTAL_LINK` / `COTAL_AGENT_FILE`
14
+ * count: setting either is itself the explicit opt-in. The connector stays
15
+ * inert otherwise. */
16
+ export function hasIdentity(env = process.env) {
17
+ return Boolean(env.COTAL_NAME?.trim() || env.COTAL_LINK?.trim() || env.COTAL_AGENT_FILE?.trim());
18
+ }
19
+ /** Build an {@link AgentConfig} from `COTAL_*` environment variables. Two refs
20
+ * fill many fields at once: `COTAL_LINK` (cotal://token@host/space) supplies the
21
+ * *where* (server, auth, space); `COTAL_AGENT_FILE` (.cotal/agents/<name>.md)
22
+ * supplies the *who* (name, role, kind, channels, description, tags).
23
+ * Individual `COTAL_*` vars override both. Identity is NOT silently defaulted
24
+ * unless a link is present — guard with {@link hasIdentity} first. */
25
+ export function configFromEnv(env = process.env) {
26
+ const link = env.COTAL_LINK?.trim() ? parseJoinLink(env.COTAL_LINK.trim()) : undefined;
27
+ const def = env.COTAL_AGENT_FILE?.trim()
28
+ ? loadAgentFile(env.COTAL_AGENT_FILE.trim())
29
+ : undefined;
30
+ const name = env.COTAL_NAME?.trim() || def?.name || (link ? userInfo().username : undefined);
31
+ if (!name)
32
+ throw new Error("COTAL_NAME, COTAL_AGENT_FILE or COTAL_LINK is required — a Cotal session needs an explicit identity from its launcher");
33
+ const channels = splitList(env.COTAL_CHANNELS);
34
+ const resolvedChannels = channels.length ? channels : (def?.channels ?? link?.channels ?? ["general"]);
35
+ const publish = splitList(env.COTAL_PUBLISH);
36
+ const credsPath = env.COTAL_CREDS?.trim();
37
+ return {
38
+ space: env.COTAL_SPACE?.trim() || link?.space || "demo",
39
+ id: env.COTAL_ID?.trim() || undefined,
40
+ creds: credsPath ? readFileSync(credsPath, "utf8") : undefined,
41
+ name,
42
+ role: env.COTAL_ROLE?.trim() || def?.role || undefined,
43
+ description: def?.description,
44
+ tags: def?.tags,
45
+ servers: env.COTAL_SERVERS?.trim() || link?.servers || DEFAULT_SERVER,
46
+ channels: resolvedChannels,
47
+ publish: publish.length ? publish : (def?.publish ?? resolvedChannels),
48
+ kind: env.COTAL_KIND?.trim() || def?.kind || "agent",
49
+ token: env.COTAL_TOKEN?.trim() || link?.token,
50
+ user: link?.user,
51
+ pass: link?.pass,
52
+ tls: env.COTAL_TLS?.trim() === "1" || link?.tls || false,
53
+ };
54
+ }
55
+ /** One sentence telling the agent its channel lanes — what it reads and where it may post —
56
+ * so it knows its scope up front instead of discovering it from inbound tags and send errors.
57
+ * Folded into each connector's MCP `instructions`. Publish outside the lane is rejected by the
58
+ * broker (auth mode), so state it plainly. */
59
+ export function laneLine(config) {
60
+ const fmt = (cs) => cs.map((c) => `#${c}`).join(", ");
61
+ const subs = config.channels;
62
+ const pubs = config.publish.length ? config.publish : config.channels;
63
+ const same = subs.length === pubs.length && subs.every((c) => pubs.includes(c));
64
+ return same
65
+ ? `You read and may post to ${fmt(subs)}. `
66
+ : `You read ${fmt(subs)}; you may post only to ${fmt(pubs)} (posts to other channels are rejected). `;
67
+ }
68
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,O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E,IAAI,IAAI,OAAO;QACtE,KAAK,EAAE,GAAG,CAAC,WAAW,EAAE,IAAI,EAAE,IAAI,IAAI,EAAE,KAAK;QAC7C,IAAI,EAAE,IAAI,EAAE,IAAI;QAChB,IAAI,EAAE,IAAI,EAAE,IAAI;QAChB,GAAG,EAAE,GAAG,CAAC,SAAS,EAAE,IAAI,EAAE,KAAK,GAAG,IAAI,IAAI,EAAE,GAAG,IAAI,KAAK;KACzD,CAAC;AACJ,CAAC;AAED;;;+CAG+C;AAC/C,MAAM,UAAU,QAAQ,CAAC,MAAmB;IAC1C,MAAM,GAAG,GAAG,CAAC,EAAY,EAAE,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAChE,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC;IAC7B,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC;IACtE,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;IAChF,OAAO,IAAI;QACT,CAAC,CAAC,4BAA4B,GAAG,CAAC,IAAI,CAAC,IAAI;QAC3C,CAAC,CAAC,YAAY,GAAG,CAAC,IAAI,CAAC,0BAA0B,GAAG,CAAC,IAAI,CAAC,2CAA2C,CAAC;AAC1G,CAAC"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The connector's local control plane: a unix-socket server the lifecycle hooks
3
+ * talk to. Hooks are dumb relays — they forward the raw runtime event JSON (which
4
+ * carries `hook_event_name`) and print whatever we reply. All the logic lives here,
5
+ * in-process, because this is where the live mesh endpoint is.
6
+ *
7
+ * The socket plumbing is platform-agnostic; each connector passes a {@link HookHandle}
8
+ * that maps its runtime's events to presence changes + (for inject-capable events)
9
+ * queued peer messages, in that runtime's own hook-output shape.
10
+ */
11
+ import { type Server } from "node:net";
12
+ import type { MeshAgent, InboxItem } from "./agent.js";
13
+ /** One lifecycle event, as the agent runtime delivers it on stdin. */
14
+ export interface HookEvent {
15
+ hook_event_name?: string;
16
+ [k: string]: unknown;
17
+ }
18
+ /** Maps one hook event to the JSON reply the runtime applies. */
19
+ export type HookHandle = (agent: MeshAgent, ev: HookEvent) => Promise<Record<string, unknown>>;
20
+ /** The context block injected into a turn when peer messages are waiting (else undefined). */
21
+ export declare function formatInjection(items: InboxItem[]): string | undefined;
22
+ /** Start the control socket. One newline-delimited JSON request → one reply per connection. */
23
+ export declare function startControlServer(agent: MeshAgent, socketPath: string, handle: HookHandle): Server;
24
+ //# sourceMappingURL=control.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"control.d.ts","sourceRoot":"","sources":["../src/control.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAgB,KAAK,MAAM,EAAE,MAAM,UAAU,CAAC;AAErD,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvD,sEAAsE;AACtE,MAAM,WAAW,SAAS;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;CACtB;AAED,iEAAiE;AACjE,MAAM,MAAM,UAAU,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,EAAE,SAAS,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAY/F,8FAA8F;AAC9F,wBAAgB,eAAe,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,MAAM,GAAG,SAAS,CAKtE;AAED,+FAA+F;AAC/F,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,SAAS,EAChB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,UAAU,GACjB,MAAM,CAuCR"}
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The connector's local control plane: a unix-socket server the lifecycle hooks
3
+ * talk to. Hooks are dumb relays — they forward the raw runtime event JSON (which
4
+ * carries `hook_event_name`) and print whatever we reply. All the logic lives here,
5
+ * in-process, because this is where the live mesh endpoint is.
6
+ *
7
+ * The socket plumbing is platform-agnostic; each connector passes a {@link HookHandle}
8
+ * that maps its runtime's events to presence changes + (for inject-capable events)
9
+ * queued peer messages, in that runtime's own hook-output shape.
10
+ */
11
+ import { createServer } from "node:net";
12
+ import { existsSync, unlinkSync } from "node:fs";
13
+ function who(i) {
14
+ return i.fromRole ? `${i.fromName}/${i.fromRole}` : i.fromName;
15
+ }
16
+ function fmtItem(i) {
17
+ if (i.kind === "dm")
18
+ return `• DM from ${who(i)}: ${i.text}`;
19
+ if (i.kind === "anycast")
20
+ return `• @${i.service} (from ${who(i)}): ${i.text}`;
21
+ return `• #${i.channel} ${who(i)}: ${i.text}`;
22
+ }
23
+ /** The context block injected into a turn when peer messages are waiting (else undefined). */
24
+ export function formatInjection(items) {
25
+ if (!items.length)
26
+ return undefined;
27
+ const head = `📨 Cotal — ${items.length} new message${items.length === 1 ? "" : "s"} from peers:`;
28
+ const tail = `(Reply with cotal_send / cotal_dm, or cotal_roster to see who's here.)`;
29
+ return `${head}\n${items.map(fmtItem).join("\n")}\n${tail}`;
30
+ }
31
+ /** Start the control socket. One newline-delimited JSON request → one reply per connection. */
32
+ export function startControlServer(agent, socketPath, handle) {
33
+ if (existsSync(socketPath)) {
34
+ try {
35
+ unlinkSync(socketPath); // clear a stale socket from a dead predecessor
36
+ }
37
+ catch {
38
+ /* ignore */
39
+ }
40
+ }
41
+ const server = createServer((sock) => {
42
+ let buf = "";
43
+ sock.setEncoding("utf8");
44
+ sock.on("data", async (d) => {
45
+ buf += d;
46
+ const nl = buf.indexOf("\n");
47
+ if (nl < 0)
48
+ return; // wait for the full line
49
+ let ev = {};
50
+ try {
51
+ ev = JSON.parse(buf.slice(0, nl) || "{}");
52
+ }
53
+ catch {
54
+ /* malformed — treat as empty */
55
+ }
56
+ const reply = await handle(agent, ev);
57
+ try {
58
+ sock.end(JSON.stringify(reply) + "\n");
59
+ }
60
+ catch {
61
+ /* client gone */
62
+ }
63
+ });
64
+ sock.on("error", () => {
65
+ /* ignore client errors */
66
+ });
67
+ });
68
+ server.on("error", (e) => process.stderr.write(`[cotal-connector] control server error: ${e.message}\n`));
69
+ server.listen(socketPath, () => process.stderr.write(`[cotal-connector] control socket: ${socketPath}\n`));
70
+ return server;
71
+ }
72
+ //# sourceMappingURL=control.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"control.js","sourceRoot":"","sources":["../src/control.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,YAAY,EAAe,MAAM,UAAU,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAYjD,SAAS,GAAG,CAAC,CAAY;IACvB,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;AACjE,CAAC;AAED,SAAS,OAAO,CAAC,CAAY;IAC3B,IAAI,CAAC,CAAC,IAAI,KAAK,IAAI;QAAE,OAAO,aAAa,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC;IAC7D,IAAI,CAAC,CAAC,IAAI,KAAK,SAAS;QAAE,OAAO,MAAM,CAAC,CAAC,OAAO,UAAU,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/E,OAAO,MAAM,CAAC,CAAC,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC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E,CAAC,IAAI,IAAI,CAAc,CAAC;YACzD,CAAC;YAAC,MAAM,CAAC;gBACP,gCAAgC;YAClC,CAAC;YACD,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACtC,IAAI,CAAC;gBACH,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;YACzC,CAAC;YAAC,MAAM,CAAC;gBACP,iBAAiB;YACnB,CAAC;QACH,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;YACpB,0BAA0B;QAC5B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IACH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,CACvB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,2CAA4C,CAAW,CAAC,OAAO,IAAI,CAAC,CAC1F,CAAC;IACF,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,GAAG,EAAE,CAC7B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,qCAAqC,UAAU,IAAI,CAAC,CAC1E,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,7 @@
1
+ export * from "./config.js";
2
+ export * from "./agent.js";
3
+ export * from "./runtime.js";
4
+ export * from "./tools.js";
5
+ export * from "./control.js";
6
+ export * from "./relay.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./config.js";
2
+ export * from "./agent.js";
3
+ export * from "./runtime.js";
4
+ export * from "./tools.js";
5
+ export * from "./control.js";
6
+ export * from "./relay.js";
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** Relay one hook event from stdin to the connector's control socket and print the reply. */
2
+ export declare function runHookRelay(): Promise<void>;
3
+ //# sourceMappingURL=relay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relay.d.ts","sourceRoot":"","sources":["../src/relay.ts"],"names":[],"mappings":"AAmCA,6FAA6F;AAC7F,wBAAsB,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAsClD"}
package/dist/relay.js ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Cotal lifecycle hook relay — stateless.
3
+ *
4
+ * The agent runtime runs a hook on a lifecycle event and pipes the event JSON (which
5
+ * includes `hook_event_name`) on stdin. We forward it to this session's connector over
6
+ * its local control socket and print the reply for the runtime to apply. It must NEVER
7
+ * block the session: any error → exit 0, no output. Both the Claude Code and Codex hook
8
+ * entry points are one-liners over {@link runHookRelay}.
9
+ */
10
+ import { connect } from "node:net";
11
+ import { configFromEnv, hasIdentity } from "./config.js";
12
+ import { controlSocketPath } from "./runtime.js";
13
+ const TIMEOUT_MS = 2000;
14
+ function readStdin() {
15
+ return new Promise((resolve) => {
16
+ if (process.stdin.isTTY)
17
+ return resolve("");
18
+ let d = "";
19
+ process.stdin.setEncoding("utf8");
20
+ process.stdin.on("data", (c) => (d += c));
21
+ process.stdin.on("end", () => resolve(d));
22
+ process.stdin.on("error", () => resolve(d));
23
+ });
24
+ }
25
+ function done(out) {
26
+ const t = out.trim();
27
+ if (!t)
28
+ return process.exit(0); // fail open — never blocks the session
29
+ // Flush before exiting: stdout to a pipe is async, so exit()ing right after write() can
30
+ // truncate a large reply. Exit from the write callback; a 1s backstop guarantees we still leave.
31
+ process.stdout.write(t + "\n", () => process.exit(0));
32
+ setTimeout(() => process.exit(0), 1000);
33
+ }
34
+ /** Relay one hook event from stdin to the connector's control socket and print the reply. */
35
+ export async function runHookRelay() {
36
+ if (!hasIdentity())
37
+ return done(""); // plain session, not a managed one — no-op
38
+ const raw = (await readStdin()).trim() || "{}";
39
+ const cfg = configFromEnv();
40
+ const sock = connect(controlSocketPath(cfg.space, cfg.name));
41
+ let reply = "";
42
+ let settled = false;
43
+ const finish = (out) => {
44
+ if (settled)
45
+ return;
46
+ settled = true;
47
+ try {
48
+ sock.destroy();
49
+ }
50
+ catch {
51
+ /* ignore */
52
+ }
53
+ done(out);
54
+ };
55
+ const timer = setTimeout(() => finish(""), TIMEOUT_MS);
56
+ sock.setEncoding("utf8");
57
+ sock.on("connect", () => sock.write(raw + "\n"));
58
+ sock.on("data", (d) => {
59
+ reply += d;
60
+ const nl = reply.indexOf("\n");
61
+ if (nl >= 0) {
62
+ clearTimeout(timer);
63
+ finish(reply.slice(0, nl));
64
+ }
65
+ });
66
+ sock.on("error", () => {
67
+ clearTimeout(timer);
68
+ finish(""); // connector not running — no-op
69
+ });
70
+ sock.on("end", () => {
71
+ clearTimeout(timer);
72
+ finish(reply);
73
+ });
74
+ }
75
+ //# sourceMappingURL=relay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relay.js","sourceRoot":"","sources":["../src/relay.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEjD,MAAM,UAAU,G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AE,CAAC,OAAO,EAAE,GAAG,EAAE;QACpB,YAAY,CAAC,KAAK,CAAC,CAAC;QACpB,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,gCAAgC;IAC9C,CAAC,CAAC,CAAC;IACH,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;QAClB,YAAY,CAAC,KAAK,CAAC,CAAC;QACpB,MAAM,CAAC,KAAK,CAAC,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Deterministic path to a connector's local control socket. Both the long-lived
3
+ * MCP server (which listens) and its short-lived hooks (which connect) compute
4
+ * this from the SAME identity, so they always agree without a discovery step.
5
+ */
6
+ export declare function controlSocketPath(space: string, name: string): string;
7
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAUA;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAErE"}
@@ -0,0 +1,16 @@
1
+ import { tmpdir } from "node:os";
2
+ import { join } from "node:path";
3
+ const ILLEGAL = /[^A-Za-z0-9_-]/g;
4
+ function tok(s) {
5
+ const t = s.trim().replace(ILLEGAL, "_");
6
+ return t.length ? t.slice(0, 40) : "_";
7
+ }
8
+ /**
9
+ * Deterministic path to a connector's local control socket. Both the long-lived
10
+ * MCP server (which listens) and its short-lived hooks (which connect) compute
11
+ * this from the SAME identity, so they always agree without a discovery step.
12
+ */
13
+ export function controlSocketPath(space, name) {
14
+ return join(tmpdir(), `cotal-${tok(space)}-${tok(name)}.sock`);
15
+ }
16
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,MAAM,OAAO,GAAG,iBAAiB,CAAC;AAElC,SAAS,GAAG,CAAC,CAAS;IACpB,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IACzC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AACzC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAa,EAAE,IAAY;IAC3D,OAAO,IAAI,CAAC,MAAM,EAAE,EAAE,SAAS,GAAG,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACjE,CAAC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The Cotal MCP tool surface — platform-agnostic.
3
+ *
4
+ * Lets a session read its inbox, broadcast, DM a peer, address a role, and report
5
+ * status on the mesh. Both the Claude Code and Codex connectors build their own
6
+ * McpServer (with platform-specific capabilities) and call {@link registerCotalTools}
7
+ * to add this shared surface.
8
+ */
9
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
+ import type { MeshAgent, InboxItem } from "./agent.js";
11
+ import type { AgentConfig } from "./config.js";
12
+ /** "name/role" (or just "name") for a message's sender. */
13
+ export declare function fmtFrom(i: InboxItem): string;
14
+ /** Routing context for a `<channel …>` tag. Keys must be [A-Za-z0-9_] (others are dropped). */
15
+ export declare function channelMeta(i: InboxItem): Record<string, string>;
16
+ /** Register the six Cotal tools (roster, inbox, send, dm, anycast, status) on a server. */
17
+ export declare function registerCotalTools(server: McpServer, agent: MeshAgent, config: AgentConfig): void;
18
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAGzE,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAM/C,2DAA2D;AAC3D,wBAAgB,OAAO,CAAC,CAAC,EAAE,SAAS,GAAG,MAAM,CAE5C;AAWD,+FAA+F;AAC/F,wBAAgB,WAAW,CAAC,CAAC,EAAE,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQhE;AAED,2FAA2F;AAC3F,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,GAAG,IAAI,CAoKjG"}
package/dist/tools.js ADDED
@@ -0,0 +1,161 @@
1
+ import { z } from "zod";
2
+ import { isConcreteChannel } from "@cotal-ai/core";
3
+ function statusGlyph(s) {
4
+ return s === "working" ? "●" : s === "waiting" ? "◐" : s === "idle" ? "○" : "·";
5
+ }
6
+ /** "name/role" (or just "name") for a message's sender. */
7
+ export function fmtFrom(i) {
8
+ return i.fromRole ? `${i.fromName}/${i.fromRole}` : i.fromName;
9
+ }
10
+ function fmtItem(i) {
11
+ if (i.kind === "dm")
12
+ return `[DM from ${fmtFrom(i)}] ${i.text}`;
13
+ if (i.kind === "anycast")
14
+ return `[@${i.service} from ${fmtFrom(i)}] ${i.text}`;
15
+ return `[#${i.channel}${i.mentionsMe ? " @you" : ""} ${fmtFrom(i)}] ${i.text}`;
16
+ }
17
+ const text = (t) => ({ content: [{ type: "text", text: t }] });
18
+ const fail = (t) => ({ ...text(t), isError: true });
19
+ /** Routing context for a `<channel …>` tag. Keys must be [A-Za-z0-9_] (others are dropped). */
20
+ export function channelMeta(i) {
21
+ const m = { kind: i.kind, from: i.fromName, from_id: i.fromId };
22
+ if (i.fromRole)
23
+ m.role = i.fromRole;
24
+ if (i.channel)
25
+ m.channel = i.channel;
26
+ if (i.service)
27
+ m.to_role = i.service; // anycast: the role that was addressed
28
+ if (i.mentions?.length)
29
+ m.mentions = i.mentions.join(","); // names called out on this channel msg
30
+ if (i.mentionsMe)
31
+ m.mentioned = "true"; // we were addressed by name → high priority
32
+ return m;
33
+ }
34
+ /** Register the six Cotal tools (roster, inbox, send, dm, anycast, status) on a server. */
35
+ export function registerCotalTools(server, agent, config) {
36
+ server.registerTool("cotal_roster", {
37
+ title: "Cotal: who's present",
38
+ description: "List the agents currently present in your Cotal space, with their role, status, and current activity.",
39
+ }, async () => {
40
+ if (!agent.connected)
41
+ return text(`Not connected to the mesh yet (${config.servers}).`);
42
+ const roster = agent.roster();
43
+ if (!roster.length)
44
+ return text(`No one is present in "${config.space}" yet.`);
45
+ const lines = roster.map((p) => {
46
+ const who = p.card.role ? `${p.card.name}/${p.card.role}` : p.card.name;
47
+ const me = p.card.id === agent.id ? " (you)" : "";
48
+ return `${statusGlyph(p.status)} ${who} — ${p.status}${p.activity ? `: ${p.activity}` : ""}${me}`;
49
+ });
50
+ return text(`Present in "${config.space}" (${roster.length}):\n${lines.join("\n")}`);
51
+ });
52
+ server.registerTool("cotal_inbox", {
53
+ title: "Cotal: read incoming messages",
54
+ description: "Read messages other agents have sent you since you last checked — channel broadcasts, direct messages, and role requests. Clears them unless peek is true.",
55
+ inputSchema: {
56
+ peek: z.boolean().optional().describe("If true, show messages without clearing them."),
57
+ },
58
+ }, async ({ peek }) => {
59
+ const items = peek ? agent.peekInbox() : agent.drainInbox();
60
+ if (!items.length)
61
+ return text("Inbox empty — no new messages.");
62
+ const head = `${items.length} message${items.length === 1 ? "" : "s"}${peek ? " (peek — not cleared)" : ""}:`;
63
+ return text(`${head}\n${items.map(fmtItem).join("\n")}`);
64
+ });
65
+ server.registerTool("cotal_send", {
66
+ title: "Cotal: broadcast to a channel",
67
+ description: "Broadcast a message to everyone on a channel in your space.",
68
+ inputSchema: {
69
+ text: z.string().describe("The message to broadcast."),
70
+ channel: z
71
+ .string()
72
+ .optional()
73
+ .describe(`Channel to send on (default: ${config.channels.find(isConcreteChannel) ?? "general"}). Concrete only — not a wildcard like team.>; reply on the channel you received a message on.`),
74
+ mentions: z
75
+ .array(z.string())
76
+ .optional()
77
+ .describe("Names of peers to call out (e.g. ['bob']). Everyone on the channel still receives the message, but a mentioned peer gets high-priority delivery (eg @bob) — woken now if idle, instead of waiting for its next idle moment. Use sparingly: a mention WAKES that peer, so only call someone out when you need THAT specific peer to act now — never in an acknowledgement, thanks, or sign-off, or mentions ping-pong between peers and wake the channel in a loop."),
78
+ },
79
+ }, async ({ text: msg, channel, mentions }) => {
80
+ try {
81
+ const m = await agent.send(msg, channel, mentions);
82
+ return text(`Sent to #${m.channel}${m.mentions?.length ? ` (mentioned @${m.mentions.join(", @")})` : ""}.`);
83
+ }
84
+ catch (e) {
85
+ return fail(`Couldn't send: ${e.message}`);
86
+ }
87
+ });
88
+ server.registerTool("cotal_dm", {
89
+ title: "Cotal: direct-message a peer",
90
+ description: "Send a private message to one specific peer, by name (or instance id).",
91
+ inputSchema: {
92
+ to: z.string().describe("The peer's name (or instance id)."),
93
+ text: z.string().describe("The message."),
94
+ },
95
+ }, async ({ to, text: msg }) => {
96
+ try {
97
+ const { peer } = await agent.dm(to, msg);
98
+ return text(`DM sent to ${peer.card.name}.`);
99
+ }
100
+ catch (e) {
101
+ return fail(`Couldn't DM: ${e.message}`);
102
+ }
103
+ });
104
+ server.registerTool("cotal_anycast", {
105
+ title: "Cotal: ask any agent of a role",
106
+ description: "Send a request to ANY one available agent of a given role (load-balanced). Use when you need 'a reviewer' rather than a specific person.",
107
+ inputSchema: {
108
+ role: z.string().describe("The role to address (e.g. reviewer)."),
109
+ text: z.string().describe("The request."),
110
+ },
111
+ }, async ({ role, text: msg }) => {
112
+ try {
113
+ await agent.anycast(role, msg);
114
+ return text(`Sent to one @${role}.`);
115
+ }
116
+ catch (e) {
117
+ return fail(`Couldn't send: ${e.message}`);
118
+ }
119
+ });
120
+ server.registerTool("cotal_status", {
121
+ title: "Cotal: set your status",
122
+ description: "Set your presence status and activity so peers can see what you are doing.",
123
+ inputSchema: {
124
+ status: z
125
+ .enum(["idle", "working", "waiting"])
126
+ .describe("idle = free; working = busy on a task; waiting = blocked on input, approval, or a peer."),
127
+ activity: z.string().optional().describe("Short note on what you're doing right now."),
128
+ },
129
+ }, async ({ status, activity }) => {
130
+ try {
131
+ await agent.setStatus(status, activity);
132
+ return text(`You are now ${status}${activity ? `: ${activity}` : ""}.`);
133
+ }
134
+ catch (e) {
135
+ return fail(`Couldn't set status: ${e.message}`);
136
+ }
137
+ });
138
+ server.registerTool("cotal_spawn", {
139
+ title: "Cotal: spawn a new teammate",
140
+ description: "Ask the manager to start a new peer endpoint in your space. It joins the mesh as a lateral peer (and, when the manager runs the cmux runtime, appears in its own tab). Use when the team needs another agent.",
141
+ inputSchema: {
142
+ name: z.string().describe("Unique name for the new peer."),
143
+ role: z
144
+ .string()
145
+ .optional()
146
+ .describe("Optional role for the new peer (e.g. worker, reviewer)."),
147
+ },
148
+ }, async ({ name, role }) => {
149
+ try {
150
+ const reply = await agent.spawn(name, role);
151
+ if (!reply.ok)
152
+ return fail(`Couldn't spawn ${name}: ${reply.error ?? "manager refused"}`);
153
+ const mode = reply.data?.mode;
154
+ return text(`Spawning ${role ? `${name}/${role}` : name}${mode ? ` (${mode})` : ""} — it will appear in the roster shortly.`);
155
+ }
156
+ catch (e) {
157
+ return fail(`Couldn't spawn ${name}: no manager reachable (${e.message}). Is the manager running?`);
158
+ }
159
+ });
160
+ }
161
+ //# sourceMappingURL=tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.js","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAuB,MAAM,gBAAgB,CAAC;AAIxE,SA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M,EAAE;iBACR,QAAQ,EAAE;iBACV,QAAQ,CAAC,yDAAyD,CAAC;SACvE;KACF,EACD,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE;QACvB,IAAI,CAAC;YACH,MAAM,KAAK,GAAG,MAAM,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAC5C,IAAI,CAAC,KAAK,CAAC,EAAE;gBAAE,OAAO,IAAI,CAAC,kBAAkB,IAAI,KAAK,KAAK,CAAC,KAAK,IAAI,iBAAiB,EAAE,CAAC,CAAC;YAC1F,MAAM,IAAI,GAAI,KAAK,CAAC,IAAsC,EAAE,IAAI,CAAC;YACjE,OAAO,IAAI,CACT,YAAY,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,0CAA0C,CACjH,CAAC;QACJ,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,IAAI,CACT,kBAAkB,IAAI,2BAA4B,CAAW,CAAC,OAAO,4BAA4B,CAClG,CAAC;QACJ,CAAC;IACH,CAAC,CACF,CAAC;AACJ,CAAC"}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@cotal-ai/connector-core",
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "dependencies": {
15
+ "@modelcontextprotocol/sdk": "^1.29.0",
16
+ "zod": "^4.4.3"
17
+ },
18
+ "peerDependencies": {
19
+ "@cotal-ai/core": "0.1.0"
20
+ },
21
+ "devDependencies": {
22
+ "@cotal-ai/core": "0.1.0"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "typecheck": "tsc -p tsconfig.json --noEmit",
32
+ "build": "tsc -p tsconfig.json"
33
+ }
34
+ }