@mosadd/mcp 3.0.0-alpha.1 → 3.0.0-alpha.10
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/README.md +127 -116
- package/dist/bin/login.js +4 -4
- package/dist/bin/mcp.js +29 -1
- package/dist/chunk-6EPYADVR.js +2095 -0
- package/dist/index.d.ts +46 -4
- package/dist/index.js +5 -3
- package/package.json +8 -5
- package/src/__tests__/golden-path.test.ts +137 -132
- package/src/__tests__/integration.test.ts +178 -175
- package/src/__tests__/mdm-e2ee.test.ts +178 -149
- package/src/__tests__/mtalk.test.ts +122 -0
- package/src/__tests__/server.test.ts +67 -67
- package/src/bin/login.ts +138 -127
- package/src/bin/mcp.ts +97 -55
- package/src/config.ts +66 -66
- package/src/crypto/mdm-session.ts +403 -378
- package/src/index.ts +19 -17
- package/src/observability/sentry.ts +79 -79
- package/src/providers/memory-voice.ts +79 -0
- package/src/providers/supabase-dm.ts +117 -117
- package/src/providers/supabase-voice.ts +91 -0
- package/src/providers/supabase.ts +120 -89
- package/src/server.ts +105 -103
- package/src/tools/capabilities.ts +68 -68
- package/src/tools/index.ts +53 -37
- package/src/tools/knowledge.ts +191 -0
- package/src/tools/mail.ts +371 -89
- package/src/tools/mcall.ts +216 -0
- package/src/tools/mdm-voice.ts +206 -0
- package/src/tools/mdm.ts +448 -379
- package/src/tools/mirc-edge.ts +190 -0
- package/src/tools/mirc-members.ts +177 -177
- package/src/tools/mirc-messages.ts +156 -0
- package/src/tools/mirc.ts +170 -170
- package/src/tools/mroom-messages.ts +142 -142
- package/src/tools/mroom.ts +221 -189
- package/src/tools/mtalk.ts +121 -0
- package/src/tools/murl.ts +141 -0
- package/src/types.ts +85 -79
- package/src/voice/floor.ts +132 -0
- package/dist/chunk-6IA4QVAJ.js +0 -1191
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mURL — IRC-for-URLs: real-time chat attached to any web DOMAIN, AGENT-NATIVE.
|
|
3
|
+
*
|
|
4
|
+
* Same mosadd-edge Cloudflare Worker / Durable Object backend as mIRC edge, but the
|
|
5
|
+
* channel id is the DOMAIN SLUG (domain lowercased, "." → "-"). A domain channel is
|
|
6
|
+
* auto-created on first activity (status "open"); a domain owner can later verify/claim it.
|
|
7
|
+
*
|
|
8
|
+
* THE WEDGE: every prior "chat on a web page" (Google Sidewiki, Genius, Hypothes.is,
|
|
9
|
+
* HERE.fm) died on the empty-room cold-start because they were HUMAN-ONLY — you arrive,
|
|
10
|
+
* nobody's there, you leave. mURL is agent-native: an AI agent researching a domain can
|
|
11
|
+
* READ the channel (human + agent context — "is this a scam?", "promo code here") and
|
|
12
|
+
* WRITE findings back, so the room is never empty. First per-domain chat where agents are
|
|
13
|
+
* first-class citizens.
|
|
14
|
+
*
|
|
15
|
+
* Auth: MOSADD_API_KEY (hub key) for read/post; presence is public.
|
|
16
|
+
*/
|
|
17
|
+
import { z } from "zod";
|
|
18
|
+
import type { MosaddTool, MosaddToolContext } from "../types.js";
|
|
19
|
+
|
|
20
|
+
const DEFAULT_EDGE_URL = "https://mosadd-edge.mr-brics-33.workers.dev";
|
|
21
|
+
function edgeUrl(): string {
|
|
22
|
+
return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL;
|
|
23
|
+
}
|
|
24
|
+
function hubKey(): string {
|
|
25
|
+
const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
|
|
26
|
+
if (!key) throw new Error("MOSADD_API_KEY required for mURL tools (see `mosadd login` / hub-keys).");
|
|
27
|
+
return key;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** A domain OR full URL → { domain, slug }. slug = host lowercased, "." → "-". */
|
|
31
|
+
function domainToSlug(input: string): { domain: string; slug: string } {
|
|
32
|
+
let host = String(input).trim().toLowerCase();
|
|
33
|
+
host = host.replace(/^[a-z]+:\/\//, "").replace(/[/?#].*$/, "").replace(/:\d+$/, "");
|
|
34
|
+
if (host.startsWith("www.")) host = host.slice(4);
|
|
35
|
+
if (!host || !/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(host)) {
|
|
36
|
+
throw new Error(`Invalid domain: "${input}" — pass a domain like "example.com" or a URL.`);
|
|
37
|
+
}
|
|
38
|
+
return { domain: host, slug: host.replace(/\./g, "-") };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const DomainArg = z
|
|
42
|
+
.string()
|
|
43
|
+
.min(3)
|
|
44
|
+
.max(255)
|
|
45
|
+
.describe("A domain (e.g. 'example.com') or a full URL — the channel is keyed to the domain.");
|
|
46
|
+
|
|
47
|
+
// ── read ──────────────────────────────────────────────────────────────────────
|
|
48
|
+
const mURL_read_channel_input = z.object({
|
|
49
|
+
domain: DomainArg,
|
|
50
|
+
limit: z.number().int().min(1).max(100).optional().describe("Recent messages to return (max 100). Default 50."),
|
|
51
|
+
});
|
|
52
|
+
async function mURL_read_channel(
|
|
53
|
+
input: z.infer<typeof mURL_read_channel_input>,
|
|
54
|
+
ctx: MosaddToolContext,
|
|
55
|
+
): Promise<{ domain: string; messages: Array<{ id: string; from: string | null; text: string; timestamp: number }> }> {
|
|
56
|
+
const { domain, slug } = domainToSlug(input.domain);
|
|
57
|
+
const limit = input.limit ?? 50;
|
|
58
|
+
ctx.log("debug", "mURL_read_channel", { domain });
|
|
59
|
+
const r = await fetch(`${edgeUrl()}/c/${slug}/history?limit=${limit}`, {
|
|
60
|
+
headers: { Authorization: `Bearer ${hubKey()}` },
|
|
61
|
+
});
|
|
62
|
+
if (!r.ok) {
|
|
63
|
+
const e = await r.text().catch(() => "");
|
|
64
|
+
throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
|
|
65
|
+
}
|
|
66
|
+
const data = (await r.json()) as { messages?: Array<{ id: string; ts: number; from?: string | null; text: string }> };
|
|
67
|
+
return {
|
|
68
|
+
domain,
|
|
69
|
+
messages: (data.messages ?? []).map((m) => ({ id: m.id, from: m.from ?? null, text: m.text, timestamp: m.ts })),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ── post ──────────────────────────────────────────────────────────────────────
|
|
74
|
+
const mURL_post_input = z.object({
|
|
75
|
+
domain: DomainArg,
|
|
76
|
+
text: z.string().min(1).max(2000).describe("Message body (max 2000 chars, up to 3 lines — Worker-enforced)."),
|
|
77
|
+
from: z.string().max(120).optional().describe("Sender hint shown to others (defaults to the hub-key owner / your agent name)."),
|
|
78
|
+
});
|
|
79
|
+
async function mURL_post(
|
|
80
|
+
input: z.infer<typeof mURL_post_input>,
|
|
81
|
+
ctx: MosaddToolContext,
|
|
82
|
+
): Promise<{ domain: string; message_id: string; posted_at: number }> {
|
|
83
|
+
const { domain, slug } = domainToSlug(input.domain);
|
|
84
|
+
ctx.log("debug", "mURL_post", { domain });
|
|
85
|
+
const r = await fetch(`${edgeUrl()}/c/${slug}/send`, {
|
|
86
|
+
method: "POST",
|
|
87
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${hubKey()}` },
|
|
88
|
+
body: JSON.stringify({ text: input.text, from: input.from }),
|
|
89
|
+
});
|
|
90
|
+
if (!r.ok) {
|
|
91
|
+
const e = await r.text().catch(() => "");
|
|
92
|
+
throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
|
|
93
|
+
}
|
|
94
|
+
const data = (await r.json()) as { id?: string; ts?: number };
|
|
95
|
+
if (!data?.id) throw new Error("mosadd-edge: send returned no id");
|
|
96
|
+
return { domain, message_id: data.id, posted_at: data.ts ?? Date.now() };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ── presence ────────────────────────────────────────────────────────────────────
|
|
100
|
+
const mURL_presence_input = z.object({ domain: DomainArg });
|
|
101
|
+
async function mURL_presence(
|
|
102
|
+
input: z.infer<typeof mURL_presence_input>,
|
|
103
|
+
ctx: MosaddToolContext,
|
|
104
|
+
): Promise<{ domain: string; count: number; roster: string[]; status: string }> {
|
|
105
|
+
const { domain, slug } = domainToSlug(input.domain);
|
|
106
|
+
ctx.log("debug", "mURL_presence", { domain });
|
|
107
|
+
const r = await fetch(`${edgeUrl()}/c/${slug}/presence`);
|
|
108
|
+
if (!r.ok) {
|
|
109
|
+
const e = await r.text().catch(() => "");
|
|
110
|
+
throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
|
|
111
|
+
}
|
|
112
|
+
const data = (await r.json()) as { count?: number; roster?: string[]; status?: string };
|
|
113
|
+
return { domain, count: data.count ?? 0, roster: data.roster ?? [], status: data.status ?? "open" };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export const murlTools: MosaddTool[] = [
|
|
117
|
+
{
|
|
118
|
+
name: "mURL_read_channel",
|
|
119
|
+
requires: "network",
|
|
120
|
+
description:
|
|
121
|
+
"Read the live chat channel for a web DOMAIN (mURL — 'IRC for URLs'). Returns the most recent messages humans and agents have posted about that domain. Use it to get real-time, crowd-sourced context before acting on a site — e.g. scam warnings, promo codes, outage reports, 'is this legit?'. The channel auto-exists for any domain. Auth: MOSADD_API_KEY (hub key).",
|
|
122
|
+
inputSchema: mURL_read_channel_input,
|
|
123
|
+
handler: mURL_read_channel as MosaddTool["handler"],
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
name: "mURL_post",
|
|
127
|
+
requires: "network",
|
|
128
|
+
description:
|
|
129
|
+
"Post a message into a web DOMAIN's mURL chat channel — leave context for the humans and agents who visit that site next (a finding, warning, tip, or coordination note). Sub-100ms global fan-out to everyone currently on the channel. Auth: MOSADD_API_KEY (hub key).",
|
|
130
|
+
inputSchema: mURL_post_input,
|
|
131
|
+
handler: mURL_post as MosaddTool["handler"],
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
name: "mURL_presence",
|
|
135
|
+
requires: "network",
|
|
136
|
+
description:
|
|
137
|
+
"Who is on a domain's mURL channel right now: live participant count + roster nicknames + channel status (open/claimed/blocked). Public (no key needed). Use it to gauge whether a domain has an active audience before posting.",
|
|
138
|
+
inputSchema: mURL_presence_input,
|
|
139
|
+
handler: mURL_presence as MosaddTool["handler"],
|
|
140
|
+
},
|
|
141
|
+
];
|
package/src/types.ts
CHANGED
|
@@ -1,79 +1,85 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Internal types for the mosadd MCP server.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import type { z } from "zod";
|
|
6
|
-
import type { DmProvider } from "@mosadd/providers";
|
|
7
|
-
import type { MdmKeyStore } from "./crypto/mdm-session.js";
|
|
8
|
-
|
|
9
|
-
export type Mode = "cloud" | "local" | "self-host";
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Transport backends per channel. The server fills any missing entry with its
|
|
13
|
-
* default network adapter; a host (e.g. cymru-os) injects alternatives —
|
|
14
|
-
* notably a radio DmProvider — via `MosaddServerOptions.providers`. This is
|
|
15
|
-
* the DI seam that keeps mosadd-os transport-agnostic.
|
|
16
|
-
*
|
|
17
|
-
* `keys` is LOCAL crypto custody (identity + prekeys + ratchet sessions) for
|
|
18
|
-
* mDM E2EE — distinct from transport. Defaults to an in-process keystore; a
|
|
19
|
-
* host may inject a file/keychain-backed one.
|
|
20
|
-
*/
|
|
21
|
-
export interface ProviderRegistry {
|
|
22
|
-
dm: DmProvider;
|
|
23
|
-
keys: MdmKeyStore;
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
providers
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Internal types for the mosadd MCP server.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { z } from "zod";
|
|
6
|
+
import type { DmProvider, VoiceProvider } from "@mosadd/providers";
|
|
7
|
+
import type { MdmKeyStore } from "./crypto/mdm-session.js";
|
|
8
|
+
|
|
9
|
+
export type Mode = "cloud" | "local" | "self-host";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Transport backends per channel. The server fills any missing entry with its
|
|
13
|
+
* default network adapter; a host (e.g. cymru-os) injects alternatives —
|
|
14
|
+
* notably a radio DmProvider — via `MosaddServerOptions.providers`. This is
|
|
15
|
+
* the DI seam that keeps mosadd-os transport-agnostic.
|
|
16
|
+
*
|
|
17
|
+
* `keys` is LOCAL crypto custody (identity + prekeys + ratchet sessions) for
|
|
18
|
+
* mDM E2EE — distinct from transport. Defaults to an in-process keystore; a
|
|
19
|
+
* host may inject a file/keychain-backed one.
|
|
20
|
+
*/
|
|
21
|
+
export interface ProviderRegistry {
|
|
22
|
+
dm: DmProvider;
|
|
23
|
+
keys: MdmKeyStore;
|
|
24
|
+
/**
|
|
25
|
+
* mTALK push-to-talk transport. Defaults to the network provider (LiveKit
|
|
26
|
+
* media + authoritative floor state). A radio host injects a provider that
|
|
27
|
+
* maps the floor onto a physical RF channel.
|
|
28
|
+
*/
|
|
29
|
+
voice: VoiceProvider;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface MosaddServerOptions {
|
|
33
|
+
/** API key for hosted mode. Required if mode === "cloud". */
|
|
34
|
+
apiKey?: string;
|
|
35
|
+
/** Override the default hub URL (https://mcp.mosadd.com). */
|
|
36
|
+
hubUrl?: string;
|
|
37
|
+
/** Operating mode. Defaults to "cloud" if apiKey is present, else "local". */
|
|
38
|
+
mode?: Mode;
|
|
39
|
+
/** Log level. */
|
|
40
|
+
logLevel?: "debug" | "info" | "warn" | "error";
|
|
41
|
+
/**
|
|
42
|
+
* Host-injected channel providers. Any omitted channel uses the default
|
|
43
|
+
* network adapter. A carrier-aware host supplies e.g. a radio DmProvider here.
|
|
44
|
+
*/
|
|
45
|
+
providers?: Partial<ProviderRegistry>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface MosaddToolContext {
|
|
49
|
+
options: Required<Pick<MosaddServerOptions, "mode" | "hubUrl">> & MosaddServerOptions;
|
|
50
|
+
/** Resolved channel providers (defaults merged with host-injected ones). */
|
|
51
|
+
providers: ProviderRegistry;
|
|
52
|
+
/** Per-request logger. */
|
|
53
|
+
log: (level: "debug" | "info" | "warn" | "error", msg: string, extra?: unknown) => void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Transport capability a tool requires to function. This is the ONE contract
|
|
58
|
+
* string shared with consuming hosts. e.g. cymru-os gates tools by carrier
|
|
59
|
+
* availability via this flag (cymru-os RFC 0002 D-Bus "Capability-flag bridge").
|
|
60
|
+
* The enum is FINAL and normalized with the cymru-os host; changing these
|
|
61
|
+
* values must be coordinated (Linear label `requires:cymru-input`).
|
|
62
|
+
*
|
|
63
|
+
* - "any" works over any transport, incl. off-grid radio (small,
|
|
64
|
+
* packet-friendly payloads). e.g. text DM.
|
|
65
|
+
* - "radio" radio-specific path (e.g. Codec2 audio frames). Off-grid OK.
|
|
66
|
+
* - "network" needs IP connectivity (server-hosted channels, email, public
|
|
67
|
+
* join links, bridges). NOT available off-grid.
|
|
68
|
+
*/
|
|
69
|
+
export type CapabilityRequirement = "any" | "radio" | "network";
|
|
70
|
+
|
|
71
|
+
export interface MosaddTool<TInput = unknown, TOutput = unknown> {
|
|
72
|
+
/** Tool name. MUST follow the m{MODULE}_{operation} convention. */
|
|
73
|
+
name: string;
|
|
74
|
+
/** Short human-readable description. Shown to the model. */
|
|
75
|
+
description: string;
|
|
76
|
+
/**
|
|
77
|
+
* Transport this tool requires. Consuming hosts read this to gate tools by
|
|
78
|
+
* available carriers. Every tool MUST declare it explicitly.
|
|
79
|
+
*/
|
|
80
|
+
requires: CapabilityRequirement;
|
|
81
|
+
/** Zod schema for input. */
|
|
82
|
+
inputSchema: z.ZodType<TInput>;
|
|
83
|
+
/** Tool handler. */
|
|
84
|
+
handler: (input: TInput, ctx: MosaddToolContext) => Promise<TOutput>;
|
|
85
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mTALK floor control — the half-duplex push-to-talk state machine.
|
|
3
|
+
*
|
|
4
|
+
* This is the kill-feature logic: a walkie-talkie discipline over a real-time
|
|
5
|
+
* room. At most ONE participant transmits at a time (holds "the floor"); others
|
|
6
|
+
* who press PTT are queued FIFO and promoted when the holder releases. An
|
|
7
|
+
* anti-hog timeout auto-releases a holder who never lets go, so one participant
|
|
8
|
+
* can't lock everyone else out.
|
|
9
|
+
*
|
|
10
|
+
* It is a PURE, deterministic reducer over plain data — no I/O, no clock of its
|
|
11
|
+
* own (the caller passes `now`). That makes it:
|
|
12
|
+
* - the reference implementation the authoritative server (mtalk-floor edge
|
|
13
|
+
* function) runs per room, and
|
|
14
|
+
* - trivially unit-testable, and
|
|
15
|
+
* - reusable by an in-memory provider for local/off-grid and for tests.
|
|
16
|
+
*
|
|
17
|
+
* A radio host does NOT use this — there the floor is the physical RF channel
|
|
18
|
+
* (carrier sense + the hardware PTT button). This models the NETWORK floor.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { FloorSnapshot } from "@mosadd/providers";
|
|
22
|
+
|
|
23
|
+
/** Serializable floor state for one room. `since` is epoch ms (number) here; the snapshot exposes ISO. */
|
|
24
|
+
export interface FloorState {
|
|
25
|
+
roomId: string;
|
|
26
|
+
holder: string | null;
|
|
27
|
+
/** Epoch ms when the holder acquired the floor; null when idle. */
|
|
28
|
+
sinceMs: number | null;
|
|
29
|
+
queue: string[];
|
|
30
|
+
/**
|
|
31
|
+
* Max ms a holder may keep the floor before auto-release (anti-hog). 0/undefined
|
|
32
|
+
* disables the timeout. Default applied by `createFloorState`.
|
|
33
|
+
*/
|
|
34
|
+
maxHoldMs: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Default anti-hog ceiling: 30s of continuous transmission, like a real PTT radio. */
|
|
38
|
+
export const DEFAULT_MAX_HOLD_MS = 30_000;
|
|
39
|
+
|
|
40
|
+
export function createFloorState(roomId: string, maxHoldMs: number = DEFAULT_MAX_HOLD_MS): FloorState {
|
|
41
|
+
return { roomId, holder: null, sinceMs: null, queue: [], maxHoldMs };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function toSnapshot(state: FloorState): FloorSnapshot {
|
|
45
|
+
return {
|
|
46
|
+
roomId: state.roomId,
|
|
47
|
+
holder: state.holder,
|
|
48
|
+
since: state.sinceMs === null ? null : new Date(state.sinceMs).toISOString(),
|
|
49
|
+
queue: [...state.queue],
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Auto-release the holder if they've exceeded the anti-hog ceiling, promoting
|
|
55
|
+
* the next queued participant. Idempotent; call before any decision so a stale
|
|
56
|
+
* holder never blocks a fresh request. Mutates and returns `state`.
|
|
57
|
+
*/
|
|
58
|
+
export function expireStale(state: FloorState, now: number): FloorState {
|
|
59
|
+
if (
|
|
60
|
+
state.holder !== null &&
|
|
61
|
+
state.maxHoldMs > 0 &&
|
|
62
|
+
state.sinceMs !== null &&
|
|
63
|
+
now - state.sinceMs >= state.maxHoldMs
|
|
64
|
+
) {
|
|
65
|
+
promoteNext(state, now);
|
|
66
|
+
}
|
|
67
|
+
return state;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Internal: clear the holder and promote the head of the queue (if any). */
|
|
71
|
+
function promoteNext(state: FloorState, now: number): void {
|
|
72
|
+
const next = state.queue.shift();
|
|
73
|
+
if (next !== undefined) {
|
|
74
|
+
state.holder = next;
|
|
75
|
+
state.sinceMs = now;
|
|
76
|
+
} else {
|
|
77
|
+
state.holder = null;
|
|
78
|
+
state.sinceMs = null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface RequestOutcome {
|
|
83
|
+
granted: boolean;
|
|
84
|
+
/** 1-based queue position when not granted; 0 when granted. */
|
|
85
|
+
position: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Press PTT. Grants the floor if idle (or refreshes if the caller already holds
|
|
90
|
+
* it); otherwise enqueues FIFO and reports the caller's position. Mutates state.
|
|
91
|
+
*/
|
|
92
|
+
export function requestFloor(state: FloorState, participant: string, now: number): RequestOutcome {
|
|
93
|
+
expireStale(state, now);
|
|
94
|
+
|
|
95
|
+
if (state.holder === null) {
|
|
96
|
+
state.holder = participant;
|
|
97
|
+
state.sinceMs = now;
|
|
98
|
+
// Acquiring clears any prior queued entry for this participant.
|
|
99
|
+
state.queue = state.queue.filter((p) => p !== participant);
|
|
100
|
+
return { granted: true, position: 0 };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (state.holder === participant) {
|
|
104
|
+
// Holding PTT down — refresh the hold so a long legitimate transmission
|
|
105
|
+
// isn't cut by the anti-hog timer mid-sentence.
|
|
106
|
+
state.sinceMs = now;
|
|
107
|
+
return { granted: true, position: 0 };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Someone else holds the floor → queue (idempotent: no duplicate entries).
|
|
111
|
+
const existing = state.queue.indexOf(participant);
|
|
112
|
+
if (existing !== -1) return { granted: false, position: existing + 1 };
|
|
113
|
+
state.queue.push(participant);
|
|
114
|
+
return { granted: false, position: state.queue.length };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Release PTT. If the caller holds the floor, it's freed and the next queued
|
|
119
|
+
* participant is promoted. If the caller is only queued, their request is
|
|
120
|
+
* cancelled. No-op otherwise. Mutates state.
|
|
121
|
+
*/
|
|
122
|
+
export function releaseFloor(state: FloorState, participant: string, now: number): FloorState {
|
|
123
|
+
expireStale(state, now);
|
|
124
|
+
|
|
125
|
+
if (state.holder === participant) {
|
|
126
|
+
promoteNext(state, now);
|
|
127
|
+
return state;
|
|
128
|
+
}
|
|
129
|
+
// Not holding — cancel a pending queued request if present.
|
|
130
|
+
state.queue = state.queue.filter((p) => p !== participant);
|
|
131
|
+
return state;
|
|
132
|
+
}
|