@orboto/mcp 0.198.0 → 0.200.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/README.md CHANGED
@@ -6,7 +6,25 @@ Model Context Protocol server for [orboto](https://orboto.io) - a self-hosted ti
6
6
 
7
7
  ## Quickstart
8
8
 
9
- There are two ways to authenticate the stdio proxy:
9
+ The shortest path is the [orboto CLI](https://www.npmjs.com/package/orboto):
10
+
11
+ ```bash
12
+ npm i -g orboto
13
+ orboto login
14
+ orboto mcp install # writes the "orboto" server entry into ./.mcp.json
15
+ orboto mcp install --scope user # or into the Claude Code user config
16
+ ```
17
+
18
+ The entry it writes runs `orboto mcp serve`, which installs and starts
19
+ `@orboto/mcp` at **the version of the instance it connects to**, so the tool
20
+ schemas always match that API. The proxy versions are cached under
21
+ `~/.orboto/mcp/<version>/`, the entry carries no credential, and
22
+ `orboto mcp status` prints the instance version, the cached proxies and the
23
+ entry of the current directory. In Claude Code, `orboto claude` then starts a
24
+ session with the wake channel loaded.
25
+
26
+ Everything below configures the proxy by hand, for clients the CLI does not
27
+ write. There are two ways to authenticate the stdio proxy:
10
28
 
11
29
  - **OAuth login (recommended for people).** Omit `ORBOTO_API_KEY`. On first use the proxy opens your browser to the orboto login (which is your SSO login when SSO is configured), you approve once, and it keeps a short-lived, self-refreshing session cached on disk. Nothing to paste, nothing long-lived.
12
30
  - **API key (service accounts / CI).** Set `ORBOTO_API_KEY` to an `orb_…` key from **Profile → API keys → Generate**. Best for headless machines with no browser.
@@ -104,6 +122,8 @@ Omit `ORBOTO_API_KEY` to use OAuth login instead. `codex mcp add` writes the sam
104
122
  | `ORBOTO_MCP_TOOLSET` | no | `minimal`, `curated` (default) or `full`. Curated is the measured high-frequency set (31 tools, ~7.8k tokens of schemas at connect) - the whole REST API stays reachable via `orboto_api_search` + `orboto_api_call`. `full` registers every named tool (175, ~39.5k tokens). `minimal` is the daily loop only (12 tools, ~2.8k tokens including the instructions block) for local models with an 8k/16k context window. HTTP clients can pick per connection instead: `?toolset=minimal` on the `/mcp` URL or an `x-orboto-toolset: minimal` header. |
105
123
  | `ORBOTO_MCP_PORT` | no | Listen port when transport is `http`. Default `3100`. |
106
124
  | `ORBOTO_MCP_CLIENT` | no | User-agent suffix that lands in the API audit log. Useful for filtering audit rows by client. |
125
+ | `ORBOTO_MCP_CHANNEL` | no | `1` (default) makes the stdio proxy a Claude Code channel: it follows the session's inbox stream and pushes each message as a `notifications/claude/channel` event that wakes the session (`claude --dangerously-load-development-channels server:orboto`, ORB-2140). `0` disables it. |
126
+ | `ORBOTO_MCP_CHANNEL_DIGEST_MINUTES` | no | Digest window for `info` / `complete` inbox mail on the channel. Default `15`; `0` delivers every message at once. Requests, errors, questions and mail older than five minutes always go out immediately. |
107
127
 
108
128
  ## Version compatibility
109
129
 
@@ -0,0 +1,47 @@
1
+ /**
2
+ * ORB-2149 - what a wake of this session costs. `orboto claude-statusline`
3
+ * writes one file per Claude Code session; the proxy reports the freshest one
4
+ * for its own directory. Two sessions in one directory, or none, report
5
+ * nothing - the ledger then says "unknown", never an estimate.
6
+ */
7
+ import { readdirSync, readFileSync } from 'node:fs';
8
+ import { homedir } from 'node:os';
9
+ import path from 'node:path';
10
+ export const CLAUDE_CONTEXT_MAX_AGE_MS = 10 * 60_000;
11
+ export function claudeContextDir() {
12
+ return path.join(homedir(), '.orboto', 'claude-context');
13
+ }
14
+ /** The one fresh report for `dir`; ambiguity and absence both mean "unknown". */
15
+ export function readClaudeContext(dir, now = Date.now(), root = claudeContextDir()) {
16
+ let names;
17
+ try {
18
+ names = readdirSync(root).filter((n) => n.endsWith('.json'));
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ const fresh = [];
24
+ for (const name of names) {
25
+ let parsed;
26
+ try {
27
+ parsed = JSON.parse(readFileSync(path.join(root, name), 'utf8'));
28
+ }
29
+ catch {
30
+ continue;
31
+ }
32
+ if (parsed.cwd !== dir)
33
+ continue;
34
+ const updated = typeof parsed.updatedAt === 'string' ? Date.parse(parsed.updatedAt) : NaN;
35
+ if (!Number.isFinite(updated) || now - updated > CLAUDE_CONTEXT_MAX_AGE_MS)
36
+ continue;
37
+ if (typeof parsed.contextTokens !== 'number' || !Number.isFinite(parsed.contextTokens))
38
+ continue;
39
+ fresh.push({
40
+ contextTokens: Math.max(0, Math.round(parsed.contextTokens)),
41
+ ...(typeof parsed.contextWindowSize === 'number' && Number.isFinite(parsed.contextWindowSize)
42
+ ? { contextWindowSize: Math.max(0, Math.round(parsed.contextWindowSize)) }
43
+ : {}),
44
+ });
45
+ }
46
+ return fresh.length === 1 ? fresh[0] : null;
47
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * ORB-2149 - the proxy reports a context size only when exactly one fresh
3
+ * report belongs to its directory.
4
+ */
5
+ import { describe, expect, it, beforeEach, afterEach } from 'vitest';
6
+ import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
7
+ import { tmpdir } from 'node:os';
8
+ import path from 'node:path';
9
+ import { readClaudeContext } from './claude-context.js';
10
+ let root;
11
+ beforeEach(() => {
12
+ root = mkdtempSync(path.join(tmpdir(), 'orboto-ctx-'));
13
+ mkdirSync(root, { recursive: true });
14
+ });
15
+ afterEach(() => { rmSync(root, { recursive: true, force: true }); });
16
+ function write(name, body) {
17
+ writeFileSync(path.join(root, name), JSON.stringify(body));
18
+ }
19
+ describe('ORB-2149 - claude statusline context reports', () => {
20
+ it('reports the one fresh file for this directory', () => {
21
+ write('a.json', { cwd: '/work/repo', contextTokens: 120_000, contextWindowSize: 200_000, updatedAt: new Date().toISOString() });
22
+ write('b.json', { cwd: '/elsewhere', contextTokens: 5, updatedAt: new Date().toISOString() });
23
+ expect(readClaudeContext('/work/repo', Date.now(), root)).toEqual({ contextTokens: 120_000, contextWindowSize: 200_000 });
24
+ });
25
+ it('reports nothing for a stale report, an unknown directory, a broken file or two sessions in one directory', () => {
26
+ write('stale.json', { cwd: '/work/repo', contextTokens: 1, updatedAt: new Date(Date.now() - 20 * 60_000).toISOString() });
27
+ expect(readClaudeContext('/work/repo', Date.now(), root)).toBeNull();
28
+ expect(readClaudeContext('/nothing/here', Date.now(), root)).toBeNull();
29
+ write('broken.json', { cwd: '/work/two' });
30
+ expect(readClaudeContext('/work/two', Date.now(), root)).toBeNull();
31
+ write('one.json', { cwd: '/work/two', contextTokens: 10, updatedAt: new Date().toISOString() });
32
+ write('two.json', { cwd: '/work/two', contextTokens: 20, updatedAt: new Date().toISOString() });
33
+ expect(readClaudeContext('/work/two', Date.now(), root)).toBeNull();
34
+ });
35
+ it('reports nothing when the directory does not exist', () => {
36
+ expect(readClaudeContext('/work/repo', Date.now(), path.join(root, 'missing'))).toBeNull();
37
+ });
38
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * ORB-2157 - the one source of the script an agent follows when a person
3
+ * asks it to set orboto up. `orboto_help { topic: "connect" }` returns it,
4
+ * docs/connect-your-agent.md, docs/claude-code.md and skills/orboto/SKILL.md
5
+ * carry the same sentences, and connect-script.test.ts holds them together.
6
+ */
7
+ export const CONNECT_SCRIPT_HEADING = 'If you are an AI agent helping a person set this up';
8
+ export const CONNECT_SCRIPT_STEPS = [
9
+ 'Work one step per message: say in one sentence what the step does and why, run it, show the result, and only then move on.',
10
+ 'Run every step you can run yourself - `orboto connect --yes` checks Node and Claude Code, writes the `orboto` server entry for this directory and prints the exact start command with the standing arguments.',
11
+ 'Hand the person only the steps that need a human: the browser login, quitting and restarting the session with that command, confirming the servers from `.mcp.json` and the local-development prompt, and, on a Team or Enterprise plan, the one Owner switch that allows channels.',
12
+ 'Give every command the person runs verbatim in its own code block, never paraphrased and never merged into prose.',
13
+ 'Verify before you continue: `orboto whoami` for the identity, `orboto mcp status` for the entry of this directory, `orboto connect --verify` for the channel.',
14
+ 'Never paste a reference page into the chat - link it and keep the message to the step you are on.',
15
+ 'Never ask for an API key, a password or a token in the chat; `orboto login` writes the credential itself.',
16
+ 'When a check fails, name the cause from the troubleshooting table, fix it, and repeat the check before the next step.',
17
+ 'Finish with `orboto connect --verify` and one real first task, so the person sees their own tickets rather than a success message.',
18
+ ];
19
+ /** The help topic's body: the heading, the numbered steps, the pages to link. */
20
+ export function connectScriptText() {
21
+ const steps = CONNECT_SCRIPT_STEPS.map((step, index) => `${index + 1}. ${step}`);
22
+ return [
23
+ CONNECT_SCRIPT_HEADING,
24
+ '',
25
+ ...steps,
26
+ '',
27
+ 'The pages to link instead of pasting: docs/connect-your-agent.md (the first hour, in plain words),',
28
+ 'docs/claude-code.md (start commands, standing arguments, troubleshooting table), docs/mcp-setup.md (any other client).',
29
+ ].join('\n');
30
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * ORB-2157 - the setup script has one source. The help topic, the two docs
3
+ * pages and the skill are checked against it, so a sentence cannot be
4
+ * improved in one place and stay old in the other three.
5
+ */
6
+ import { describe, expect, it } from 'vitest';
7
+ import { readFileSync } from 'node:fs';
8
+ import { CONNECT_SCRIPT_HEADING, CONNECT_SCRIPT_STEPS, connectScriptText } from './connect-script.js';
9
+ import { makeHelpHandler } from './tools/help.js';
10
+ const read = (relative) => readFileSync(new URL(`../../../${relative}`, import.meta.url), 'utf8');
11
+ const CARRIERS = ['docs/connect-your-agent.md', 'docs/claude-code.md', 'skills/orboto/SKILL.md'];
12
+ describe('the connect script', () => {
13
+ it('reads as a numbered script with the pages it links', () => {
14
+ const text = connectScriptText();
15
+ expect(text).toContain(CONNECT_SCRIPT_HEADING);
16
+ CONNECT_SCRIPT_STEPS.forEach((step, index) => expect(text).toContain(`${index + 1}. ${step}`));
17
+ expect(text).toContain('docs/connect-your-agent.md');
18
+ });
19
+ it.each(CARRIERS)('%s carries every step verbatim', (file) => {
20
+ const page = read(file);
21
+ for (const step of CONNECT_SCRIPT_STEPS)
22
+ expect(page).toContain(step);
23
+ });
24
+ it('orboto_help returns it for the topic "connect"', async () => {
25
+ const result = await makeHelpHandler()({ topic: 'connect' });
26
+ const text = (result.content?.[0]).text;
27
+ for (const step of CONNECT_SCRIPT_STEPS)
28
+ expect(text).toContain(step);
29
+ expect(result.structuredContent).toMatchObject({ tool: 'topic:connect' });
30
+ });
31
+ it('names the known topics when the topic is unknown, and asks for one when nothing is passed', async () => {
32
+ const handler = makeHelpHandler();
33
+ const unknown = (await handler({ topic: 'nope' })).content?.[0];
34
+ expect(unknown.text).toContain('connect');
35
+ const empty = (await handler({})).content?.[0];
36
+ expect(empty.text).toContain('connect');
37
+ });
38
+ it('still answers a tool name', async () => {
39
+ const result = await makeHelpHandler()({ tool: 'orboto_definitely_not_a_tool' });
40
+ expect((result.content?.[0]).text).toContain('No guidance registered');
41
+ });
42
+ });
@@ -0,0 +1,288 @@
1
+ export const CHANNEL_METHOD = 'notifications/claude/channel';
2
+ export const CHANNEL_CAPABILITY = 'claude/channel';
3
+ export const DEFAULT_DIGEST_MINUTES = 15;
4
+ const IMMEDIATE_AFTER_MS = 5 * 60_000;
5
+ const CONTENT_CAP = 2000;
6
+ const SEEN_WINDOW = 1000;
7
+ const MIN_BACKOFF_MS = 2_000;
8
+ const MAX_BACKOFF_MS = 60_000;
9
+ const HEARTBEAT_GRACE_MS = 90_000;
10
+ const ASK = /\?|\bplease\b|\bbitte\b|\bneed\b|\bshare\b/i;
11
+ /** The instructions paragraph Claude Code delivers on connect when the channel is active. */
12
+ export const CHANNEL_INSTRUCTIONS = 'Inbox channel: messages for THIS session arrive as <channel source="orboto" id="..." kind="..." ...> events - '
13
+ + 'peer requests, ticket-ready notices, replies, digests of info/complete mail. Treat each like an inbox message under the rules: '
14
+ + 'a ticket-ready or a request inside your scope is the operator\'s instruction, act on it; read the full message with orboto_messages when the event is cut; '
15
+ + 'reply with orboto_agent_notify (toSessionRef = the sender\'s instance short id in the from attribute) and acknowledge with orboto_messages { ackIds } once handled. '
16
+ + 'Never answer the channel itself and never ack what you did not handle - dismiss it instead with orboto_messages { dismiss: { ids, reason } }: '
17
+ + 'not_mine for another session\'s mail (the sender is told, and the message never reaches this session again), obsolete or duplicate with a note when the request is already done. '
18
+ + 'A session that declared no scope is woken by mail addressed to it and by broadcasts only, and gets one notice event saying so on connect: '
19
+ + 'declare the scope with orboto_session_start { scope: { role, projectKeys } } to be woken by the account\'s project mail again - '
20
+ + 'the rest of the account\'s inbox stays readable with orboto_messages the whole time.';
21
+ const START_FLAG = '--dangerously-load-development-channels server:orboto';
22
+ /** ORB-2148 - the commands an agent hands its operator verbatim; docs/claude-code.md carries the same lines. */
23
+ export const CHANNEL_START_COMMANDS = {
24
+ fresh: 'orboto claude',
25
+ continueLatest: 'orboto claude --continue',
26
+ resumeById: 'orboto claude --resume <session id>',
27
+ };
28
+ /** The raw Claude Code form, for a machine without the orboto CLI. */
29
+ export const CHANNEL_START_COMMANDS_WITHOUT_CLI = {
30
+ fresh: `claude ${START_FLAG}`,
31
+ continueLatest: `claude ${START_FLAG} --continue`,
32
+ resumeById: `claude ${START_FLAG} --resume <session id>`,
33
+ };
34
+ /** The `orboto_session_start` block of a stdio proxy whose channel is on. */
35
+ export function channelStartLines() {
36
+ return [
37
+ '## Wake channel',
38
+ 'This proxy pushes inbox messages into the session as <channel source="orboto"> events, but only when Claude Code was started with the development-channels flag. '
39
+ + 'Run in this repository (`orboto` is this server\'s key in .mcp.json), and confirm the "local development" prompt Claude Code shows on every such start:',
40
+ `- new session: \`${CHANNEL_START_COMMANDS.fresh}\``,
41
+ `- continue the most recent conversation here: \`${CHANNEL_START_COMMANDS.continueLatest}\``,
42
+ `- resume a specific conversation: \`${CHANNEL_START_COMMANDS.resumeById}\` (without an id Claude Code opens a picker)`,
43
+ 'The entry `orboto claude` needs comes from `orboto mcp install`; without the orboto CLI the same starts read '
44
+ + `\`${CHANNEL_START_COMMANDS_WITHOUT_CLI.fresh}\`, \`${CHANNEL_START_COMMANDS_WITHOUT_CLI.continueLatest}\` and \`${CHANNEL_START_COMMANDS_WITHOUT_CLI.resumeById}\`.`,
45
+ 'A probe that produces no channel event means this session was not started that way: give the operator these commands verbatim, do not paraphrase them.',
46
+ ];
47
+ }
48
+ function firstLine(payload) {
49
+ if (!payload)
50
+ return '';
51
+ for (const key of ['message', 'body', 'text']) {
52
+ const v = payload[key];
53
+ if (typeof v === 'string' && v.trim())
54
+ return v.trim();
55
+ }
56
+ return '';
57
+ }
58
+ function waitedMinutes(createdAt, now) {
59
+ const t = Date.parse(createdAt.replace(' ', 'T').replace(/\+00$/, '+00:00'));
60
+ if (Number.isNaN(t))
61
+ return 0;
62
+ return Math.max(0, Math.floor((now - t) / 60_000));
63
+ }
64
+ /** A message goes out at once when it asks for something or already waited; the rest is digest material. */
65
+ export function isImmediate(m, now, digestMinutes) {
66
+ if (digestMinutes <= 0)
67
+ return true;
68
+ if (m.kind === 'request' || m.kind === 'error')
69
+ return true;
70
+ if (waitedMinutes(m.createdAt, now) * 60_000 >= IMMEDIATE_AFTER_MS)
71
+ return true;
72
+ return ASK.test(`${m.subject} ${firstLine(m.payload)}`);
73
+ }
74
+ export function renderEvent(m, now) {
75
+ const from = m.from?.label ?? m.fromUserId ?? 'unknown';
76
+ const to = m.to?.label ?? 'you';
77
+ const text = firstLine(m.payload);
78
+ const body = text.length > CONTENT_CAP ? `${text.slice(0, CONTENT_CAP)} [... cut, read the rest with orboto_messages]` : text;
79
+ const lines = [
80
+ `[${m.kind}] ${m.subject}`,
81
+ `from ${from} to ${to}${m.projectKey ? ` | project ${m.projectKey}` : ''} | id ${m.id}${m.threadId ? ` | thread ${m.threadId}` : ''}`,
82
+ ];
83
+ if (body)
84
+ lines.push(body);
85
+ const waited = waitedMinutes(m.createdAt, now);
86
+ return {
87
+ content: lines.join('\n'),
88
+ meta: {
89
+ id: m.id, kind: m.kind, project: m.projectKey ?? '',
90
+ from: from, from_session: (m.from?.sessionId ?? '').slice(0, 8), to_session: (m.to?.sessionId ?? '').slice(0, 8),
91
+ waited_min: String(waited),
92
+ },
93
+ };
94
+ }
95
+ export function renderDigest(batch, now) {
96
+ const lines = [`Inbox digest: ${batch.length} info/complete message(s) since the last event. Ack the ones you handled with orboto_messages { ackIds }.`];
97
+ for (const m of batch) {
98
+ const text = firstLine(m.payload);
99
+ lines.push(`- [${m.kind}] ${m.subject} | from ${m.from?.label ?? m.fromUserId ?? 'unknown'}${m.projectKey ? ` | ${m.projectKey}` : ''} | id ${m.id}${text ? ` | ${text.slice(0, 160)}` : ''}`);
100
+ }
101
+ return { content: lines.join('\n'), meta: { kind: 'digest', count: String(batch.length), waited_min: String(waitedMinutes(batch[0].createdAt, now)) } };
102
+ }
103
+ export class InboxChannel {
104
+ opts;
105
+ log;
106
+ now;
107
+ digestMinutes;
108
+ abort = new AbortController();
109
+ closed = false;
110
+ retryTimer = null;
111
+ digestTimer = null;
112
+ backoff = MIN_BACKOFF_MS;
113
+ since;
114
+ lastId = null;
115
+ seen = new Set();
116
+ seenOrder = [];
117
+ batch = [];
118
+ /** Counters an operator can read from the log; tests read them directly. */
119
+ stats = { delivered: 0, digested: 0, duplicates: 0, reconnects: 0, notices: 0 };
120
+ constructor(opts) {
121
+ this.opts = opts;
122
+ this.log = opts.log ?? ((msg) => { try {
123
+ process.stderr.write(`[orboto-mcp-channel] ${msg}\n`);
124
+ }
125
+ catch { /* ignore */ } });
126
+ this.now = opts.now ?? (() => Date.now());
127
+ this.digestMinutes = opts.digestMinutes ?? DEFAULT_DIGEST_MINUTES;
128
+ this.since = opts.since ?? new Date(this.now()).toISOString();
129
+ }
130
+ start() {
131
+ void this.loop();
132
+ }
133
+ close() {
134
+ this.closed = true;
135
+ if (this.retryTimer) {
136
+ clearTimeout(this.retryTimer);
137
+ this.retryTimer = null;
138
+ }
139
+ if (this.digestTimer) {
140
+ clearTimeout(this.digestTimer);
141
+ this.digestTimer = null;
142
+ }
143
+ try {
144
+ this.abort.abort();
145
+ }
146
+ catch { /* ignore */ }
147
+ }
148
+ /** Feed one message as the stream would; exported for tests and for the digest policy. */
149
+ async deliver(m) {
150
+ if (!m?.id)
151
+ return;
152
+ if (this.seen.has(m.id)) {
153
+ this.stats.duplicates += 1;
154
+ return;
155
+ }
156
+ this.remember(m.id);
157
+ this.lastId = m.id;
158
+ if (isImmediate(m, this.now(), this.digestMinutes)) {
159
+ await this.emit(renderEvent(m, this.now()));
160
+ this.stats.delivered += 1;
161
+ return;
162
+ }
163
+ this.batch.push(m);
164
+ this.stats.digested += 1;
165
+ if (!this.digestTimer) {
166
+ this.digestTimer = setTimeout(() => { this.digestTimer = null; void this.flushDigest(); }, this.digestMinutes * 60_000);
167
+ }
168
+ }
169
+ /** ORB-2151 - a server notice (the scope hint) is emitted as-is and never becomes the replay anchor. */
170
+ async deliverNotice(notice, content) {
171
+ if (!content)
172
+ return;
173
+ this.stats.notices += 1;
174
+ await this.emit({ content, meta: { kind: 'notice', notice } });
175
+ }
176
+ async flushDigest() {
177
+ if (this.batch.length === 0)
178
+ return;
179
+ const batch = this.batch.splice(0);
180
+ await this.emit(renderDigest(batch, this.now()));
181
+ }
182
+ remember(id) {
183
+ this.seen.add(id);
184
+ this.seenOrder.push(id);
185
+ if (this.seenOrder.length > SEEN_WINDOW) {
186
+ const gone = this.seenOrder.shift();
187
+ if (gone)
188
+ this.seen.delete(gone);
189
+ }
190
+ }
191
+ async emit(event) {
192
+ try {
193
+ await this.opts.mcp.server.notification({ method: CHANNEL_METHOD, params: { content: event.content, meta: event.meta } });
194
+ this.log(`channel event → ${event.meta.kind} ${event.meta.id ?? ''}`.trim());
195
+ }
196
+ catch (err) {
197
+ this.log(`channel notification failed: ${err.message}`);
198
+ }
199
+ }
200
+ async loop() {
201
+ while (!this.closed) {
202
+ try {
203
+ await this.consume();
204
+ this.backoff = MIN_BACKOFF_MS;
205
+ }
206
+ catch (err) {
207
+ if (this.closed)
208
+ return;
209
+ this.log(`inbox stream closed: ${err instanceof Error ? err.message : String(err)} - retrying in ${this.backoff}ms`);
210
+ }
211
+ if (this.closed)
212
+ return;
213
+ this.stats.reconnects += 1;
214
+ await new Promise((resolve) => { this.retryTimer = setTimeout(resolve, this.backoff); });
215
+ this.backoff = Math.min(this.backoff * 2, MAX_BACKOFF_MS);
216
+ }
217
+ }
218
+ async consume() {
219
+ const fetchFn = this.opts.fetchFn ?? fetch;
220
+ this.abort = new AbortController();
221
+ const since = this.lastId ?? this.since;
222
+ const url = `${this.opts.baseUrl.replace(/\/$/, '')}/v1/agent/messages/stream?since=${encodeURIComponent(since)}`;
223
+ const bearer = this.opts.tokenProvider ? await this.opts.tokenProvider.getAccessToken() : (this.opts.apiKey ?? '');
224
+ const res = await fetchFn(url, {
225
+ method: 'GET',
226
+ headers: { Authorization: `Bearer ${bearer}`, Accept: 'text/event-stream', 'x-orboto-agent-session': this.opts.instanceToken },
227
+ signal: this.abort.signal,
228
+ });
229
+ if (!res.ok || !res.body)
230
+ throw new Error(`inbox stream handshake failed (status=${res.status})`);
231
+ this.log(`inbox channel connected (since ${since})`);
232
+ const reader = res.body.getReader();
233
+ const decoder = new TextDecoder();
234
+ let buf = '';
235
+ let lastFrame = this.now();
236
+ const heartbeat = setInterval(() => {
237
+ if (this.now() - lastFrame > HEARTBEAT_GRACE_MS) {
238
+ try {
239
+ this.abort.abort();
240
+ }
241
+ catch { /* ignore */ }
242
+ }
243
+ }, 30_000);
244
+ try {
245
+ for (;;) {
246
+ const { done, value } = await reader.read();
247
+ if (done)
248
+ break;
249
+ lastFrame = this.now();
250
+ buf += decoder.decode(value, { stream: true });
251
+ let idx;
252
+ while ((idx = buf.indexOf('\n\n')) !== -1) {
253
+ const frame = buf.slice(0, idx);
254
+ buf = buf.slice(idx + 2);
255
+ const line = frame.split('\n').find((l) => l.startsWith('data: '));
256
+ if (!line)
257
+ continue;
258
+ let parsed;
259
+ try {
260
+ parsed = JSON.parse(line.slice(6));
261
+ }
262
+ catch {
263
+ continue;
264
+ }
265
+ if (parsed.notice) {
266
+ await this.deliverNotice(parsed.notice, parsed.content ?? '');
267
+ continue;
268
+ }
269
+ await this.deliver(parsed);
270
+ }
271
+ }
272
+ }
273
+ finally {
274
+ clearInterval(heartbeat);
275
+ try {
276
+ reader.releaseLock();
277
+ }
278
+ catch { /* ignore */ }
279
+ }
280
+ }
281
+ }
282
+ /** ORB-2140 - the digest window from the environment; NaN or negative fall back to the default. */
283
+ export function digestMinutesFromEnv(raw) {
284
+ if (raw === undefined || raw.trim() === '')
285
+ return DEFAULT_DIGEST_MINUTES;
286
+ const n = Number(raw);
287
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : DEFAULT_DIGEST_MINUTES;
288
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * ORB-2140 - the inbox channel: stream messages become channel notifications,
3
+ * digest policy, dedupe across reconnects, and the capability declaration.
4
+ */
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
6
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
7
+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
8
+ import { CHANNEL_CAPABILITY, CHANNEL_INSTRUCTIONS, CHANNEL_METHOD, InboxChannel, digestMinutesFromEnv, isImmediate, renderEvent } from './inbox-channel.js';
9
+ import { buildOrbotoMcpServer } from './server.js';
10
+ function mockMcp() {
11
+ const notification = vi.fn().mockResolvedValue(undefined);
12
+ return { mcp: { server: { notification } }, notification };
13
+ }
14
+ function sse(frames) {
15
+ const encoder = new TextEncoder();
16
+ const stream = new ReadableStream({
17
+ start(controller) {
18
+ for (const frame of frames)
19
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(frame)}\n\n`));
20
+ controller.close();
21
+ },
22
+ });
23
+ return new Response(stream, { status: 200, headers: { 'content-type': 'text/event-stream' } });
24
+ }
25
+ const NOW = Date.parse('2026-09-18T10:00:00Z');
26
+ const msg = (over = {}) => ({
27
+ id: 'm1', fromUserId: 'u-spec', kind: 'request', subject: 'ticket-ready:ORB-1', payload: { message: 'please take it' },
28
+ threadId: null, projectKey: 'ORB', createdAt: '2026-09-18 09:59:30+00',
29
+ from: { email: 'spec@orboto.io', sessionId: 'aaaaaaaa-0000-4000-8000-000000000000', role: 'spec', label: 'spec@orboto.io (spec, aaaaaaaa)' },
30
+ to: { email: 'claude@orboto.io', sessionId: 'bbbbbbbb-0000-4000-8000-000000000000', role: 'integrator', label: 'claude@orboto.io (integrator, bbbbbbbb)' },
31
+ ...over,
32
+ });
33
+ beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(NOW); });
34
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });
35
+ describe('renderEvent / isImmediate', () => {
36
+ it('names both parties, carries id, project and thread, and caps the body', () => {
37
+ const e = renderEvent(msg({ threadId: 't1', payload: { message: 'x'.repeat(2500) } }), NOW);
38
+ expect(e.content.split('\n')[0]).toBe('[request] ticket-ready:ORB-1');
39
+ expect(e.content.split('\n')[1]).toBe('from spec@orboto.io (spec, aaaaaaaa) to claude@orboto.io (integrator, bbbbbbbb) | project ORB | id m1 | thread t1');
40
+ expect(e.content).toContain('[... cut, read the rest with orboto_messages]');
41
+ expect(e.meta).toMatchObject({ id: 'm1', kind: 'request', project: 'ORB', from_session: 'aaaaaaaa', to_session: 'bbbbbbbb', waited_min: '0' });
42
+ });
43
+ it('request, error, a question and a message that waited over five minutes go out at once; plain info is digest material', () => {
44
+ expect(isImmediate(msg({ kind: 'info', payload: { message: 'pushed abc' } }), NOW, 15)).toBe(false);
45
+ expect(isImmediate(msg({ kind: 'request' }), NOW, 15)).toBe(true);
46
+ expect(isImmediate(msg({ kind: 'error', payload: null }), NOW, 15)).toBe(true);
47
+ expect(isImmediate(msg({ kind: 'info', payload: { message: 'can you check?' } }), NOW, 15)).toBe(true);
48
+ expect(isImmediate(msg({ kind: 'info', payload: { message: 'old' }, createdAt: '2026-09-18 09:50:00+00' }), NOW, 15)).toBe(true);
49
+ expect(isImmediate(msg({ kind: 'info', payload: { message: 'pushed abc' } }), NOW, 0)).toBe(true);
50
+ });
51
+ it('reads the digest window from the environment with a safe default', () => {
52
+ expect(digestMinutesFromEnv(undefined)).toBe(15);
53
+ expect(digestMinutesFromEnv('0')).toBe(0);
54
+ expect(digestMinutesFromEnv('7.9')).toBe(7);
55
+ expect(digestMinutesFromEnv('nope')).toBe(15);
56
+ expect(digestMinutesFromEnv('-3')).toBe(15);
57
+ });
58
+ });
59
+ describe('InboxChannel', () => {
60
+ it('turns each streamed message into one channel notification and batches info into a digest', async () => {
61
+ const { mcp, notification } = mockMcp();
62
+ const fetchFn = vi.fn().mockResolvedValueOnce(sse([
63
+ msg(),
64
+ msg({ id: 'm2', kind: 'info', subject: 'pushed 1', payload: { message: 'ok' }, createdAt: '2026-09-18 09:59:50+00' }),
65
+ msg({ id: 'm3', kind: 'complete', subject: 'done 2', payload: null, createdAt: '2026-09-18 09:59:55+00' }),
66
+ ])).mockImplementation(() => new Promise(() => { }));
67
+ const channel = new InboxChannel({ baseUrl: 'https://x.test', apiKey: 'orb_k', instanceToken: 'mcp-proc', mcp, fetchFn, log: () => { }, digestMinutes: 15 });
68
+ channel.start();
69
+ await vi.waitFor(() => expect(notification).toHaveBeenCalledTimes(1));
70
+ const first = notification.mock.calls[0][0];
71
+ expect(first.method).toBe(CHANNEL_METHOD);
72
+ expect(first.params.meta.id).toBe('m1');
73
+ expect(fetchFn.mock.calls[0][1].headers['x-orboto-agent-session']).toBe('mcp-proc');
74
+ expect(String(fetchFn.mock.calls[0][0])).toContain('/v1/agent/messages/stream?since=2026-09-18T10%3A00%3A00.000Z');
75
+ expect(channel.stats).toMatchObject({ delivered: 1, digested: 2 });
76
+ await vi.advanceTimersByTimeAsync(15 * 60_000);
77
+ expect(notification).toHaveBeenCalledTimes(2);
78
+ const digest = notification.mock.calls[1][0];
79
+ expect(digest.params.meta).toMatchObject({ kind: 'digest', count: '2' });
80
+ expect(digest.params.content).toContain('- [info] pushed 1');
81
+ expect(digest.params.content).toContain('- [complete] done 2');
82
+ channel.close();
83
+ });
84
+ it('reconnects from the last delivered id and never delivers a message twice', async () => {
85
+ const { mcp, notification } = mockMcp();
86
+ const fetchFn = vi.fn()
87
+ .mockResolvedValueOnce(sse([msg()]))
88
+ .mockResolvedValueOnce(sse([msg(), msg({ id: 'm9', subject: 'second' })]))
89
+ .mockImplementation(() => new Promise(() => { }));
90
+ const channel = new InboxChannel({ baseUrl: 'https://x.test', apiKey: 'orb_k', instanceToken: 'mcp-proc', mcp, fetchFn, log: () => { }, digestMinutes: 0 });
91
+ channel.start();
92
+ await vi.waitFor(() => expect(notification).toHaveBeenCalledTimes(1));
93
+ await vi.advanceTimersByTimeAsync(2_000);
94
+ await vi.waitFor(() => expect(notification).toHaveBeenCalledTimes(2));
95
+ expect(String(fetchFn.mock.calls[1][0])).toContain('since=m1');
96
+ expect(channel.stats).toMatchObject({ delivered: 2, duplicates: 1 });
97
+ expect(channel.stats.reconnects).toBeGreaterThanOrEqual(1);
98
+ channel.close();
99
+ });
100
+ it('ORB-2151 - a server notice becomes its own event and never becomes the replay anchor', async () => {
101
+ const { mcp, notification } = mockMcp();
102
+ const hint = { notice: 'declare_scope', sessionId: 'cccccccc-0000-4000-8000-000000000000', content: 'declare your scope: orboto_session_start { scope: { role, projectKeys } }' };
103
+ const fetchFn = vi.fn()
104
+ .mockResolvedValueOnce(sse([hint, msg()]))
105
+ .mockImplementation(() => new Promise(() => { }));
106
+ const channel = new InboxChannel({ baseUrl: 'https://x.test', apiKey: 'orb_k', instanceToken: 'mcp-proc', mcp, fetchFn, log: () => { }, digestMinutes: 0 });
107
+ channel.start();
108
+ await vi.waitFor(() => expect(notification).toHaveBeenCalledTimes(2));
109
+ const first = notification.mock.calls[0][0];
110
+ expect(first.params.meta).toEqual({ kind: 'notice', notice: 'declare_scope' });
111
+ expect(first.params.content).toContain('orboto_session_start');
112
+ expect(channel.stats).toMatchObject({ notices: 1, delivered: 1 });
113
+ await vi.advanceTimersByTimeAsync(2_000);
114
+ await vi.waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(2));
115
+ expect(String(fetchFn.mock.calls[1][0])).toContain('since=m1');
116
+ channel.close();
117
+ });
118
+ });
119
+ describe('server capability', () => {
120
+ async function connect(channel) {
121
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('offline test'));
122
+ const server = await buildOrbotoMcpServer({ baseUrl: 'https://x.test', apiKey: 'orb_k', channel });
123
+ const client = new Client({ name: 't', version: '0' });
124
+ const [a, b] = InMemoryTransport.createLinkedPair();
125
+ await Promise.all([server.connect(a), client.connect(b)]);
126
+ return { server, client };
127
+ }
128
+ it('declares claude/channel and the channel instructions only when asked (stdio)', async () => {
129
+ const on = await connect(true);
130
+ expect(on.client.getServerCapabilities()?.experimental).toHaveProperty(CHANNEL_CAPABILITY);
131
+ expect(on.client.getInstructions()).toContain(CHANNEL_INSTRUCTIONS.slice(0, 40));
132
+ await on.client.close();
133
+ await on.server.close();
134
+ const off = await connect(false);
135
+ expect(off.client.getServerCapabilities()?.experimental ?? {}).not.toHaveProperty(CHANNEL_CAPABILITY);
136
+ expect(off.client.getInstructions() ?? '').not.toContain('Inbox channel:');
137
+ await off.client.close();
138
+ await off.server.close();
139
+ });
140
+ });
package/dist/index.js CHANGED
@@ -53,10 +53,28 @@ async function main() {
53
53
  console.error(`[orboto-mcp] ${err.message}`);
54
54
  process.exit(1);
55
55
  }
56
- const server = await buildOrbotoMcpServer(clientConfig);
56
+ const channel = (process.env.ORBOTO_MCP_CHANNEL ?? '1') !== '0';
57
+ const server = await buildOrbotoMcpServer({ ...clientConfig, channel, instanceToken: (await import('./tools/shared.js')).mcpProcessInstance() });
57
58
  const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js');
58
59
  const stdio = new StdioServerTransport();
59
60
  await server.connect(stdio);
61
+ if (channel) {
62
+ const { InboxChannel, digestMinutesFromEnv } = await import('./inbox-channel.js');
63
+ const { mcpProcessInstance } = await import('./tools/shared.js');
64
+ const instanceToken = mcpProcessInstance();
65
+ const inbox = new InboxChannel({ ...clientConfig, instanceToken, mcp: server, digestMinutes: digestMinutesFromEnv(process.env.ORBOTO_MCP_CHANNEL_DIGEST_MINUTES) });
66
+ inbox.start();
67
+ const { readClaudeContext } = await import('./claude-context.js');
68
+ const beat = () => {
69
+ const context = readClaudeContext(process.cwd());
70
+ preflightClient.post('/v1/agent/heartbeat', { clientInfo: { channel: 'claude-code', ...(context ?? {}) } }, { instanceToken })
71
+ .catch((err) => { console.error(`[orboto-mcp] channel heartbeat failed: ${err.message}`); });
72
+ };
73
+ beat();
74
+ const beats = setInterval(beat, 60_000);
75
+ beats.unref?.();
76
+ stdio.onclose = () => { clearInterval(beats); inbox.close(); };
77
+ }
60
78
  return;
61
79
  }
62
80
  if (transport === 'http') {
@@ -31,11 +31,19 @@ afterEach(() => { vi.restoreAllMocks(); });
31
31
  * session scope schema, agent_notify the toSessionRef, and orboto_messages
32
32
  * renders sender and receiver identities in its output schema (measured
33
33
  * curated = 38,640, full = 168,029 chars, minimal = 3,140 tokens).
34
+ * ORB-2150 raised the curated ceiling to 39,700: `orboto_messages` gained
35
+ * the `dismiss` envelope and the per-message `dismissed` record, which is
36
+ * the surface that stops foreign mail from waking every session of a
37
+ * shared account (measured curated = 39,461 chars / 10,961 tokens).
38
+ * ORB-2149 raised the full ceiling to 171,200: `orboto_agent_wakes` puts
39
+ * the wake ledger and the delivery precision per session and per sender
40
+ * in the full toolset (measured full = 170,030 chars); the curated tier
41
+ * reaches it through the escape hatch and is unchanged.
34
42
  *
35
43
  * @see ORB-1805, ORB-1669, ORB-1910
36
44
  */
37
- const CURATED_MAX_CHARS = 39_000;
38
- const FULL_MAX_CHARS = 169_000;
45
+ const CURATED_MAX_CHARS = 39_700;
46
+ const FULL_MAX_CHARS = 171_200;
39
47
  /**
40
48
  * ORB-1805 - the estimator the ticket measured the failure with
41
49
  * (`n_keep: 13533 >= n_ctx: 8192` in LM Studio): characters / 3.6. It is
@@ -56,7 +64,7 @@ const MINIMAL_MAX_TOKENS = 3_200;
56
64
  * The curated tier is ratcheted on its TOOL SCHEMAS (the instructions
57
65
  * block has its own budget, enforced in instructions-budget.test.ts).
58
66
  */
59
- const CURATED_SCHEMA_MAX_TOKENS = 10_800;
67
+ const CURATED_SCHEMA_MAX_TOKENS = 11_000;
60
68
  async function measuredManifest(toolset) {
61
69
  const server = await buildOrbotoMcpServer({
62
70
  baseUrl: 'https://orboto.example.com',
@@ -22,6 +22,7 @@ export class OrbotoClient {
22
22
  baseHeaders;
23
23
  apiKey;
24
24
  tokenProvider;
25
+ instanceToken;
25
26
  constructor(config) {
26
27
  this.baseUrl = config.baseUrl.replace(/\/+$/, '');
27
28
  if (!config.apiKey && !config.tokenProvider) {
@@ -29,6 +30,7 @@ export class OrbotoClient {
29
30
  }
30
31
  this.apiKey = config.apiKey;
31
32
  this.tokenProvider = config.tokenProvider;
33
+ this.instanceToken = config.instanceToken;
32
34
  const ua = config.userAgentSuffix
33
35
  ? `orboto-mcp/${VERSION} (${config.userAgentSuffix})`
34
36
  : `orboto-mcp/${VERSION}`;
@@ -60,6 +62,7 @@ export class OrbotoClient {
60
62
  const doFetch = async (token) => {
61
63
  const headers = {
62
64
  ...this.baseHeaders,
65
+ ...(this.instanceToken ? { 'x-orboto-agent-session': this.instanceToken } : {}),
63
66
  ...(accept ? { Accept: accept } : {}),
64
67
  ...(init.headers ?? {}),
65
68
  Authorization: `Bearer ${token}`,
@@ -126,4 +126,19 @@ describe('preflightMcpSession', () => {
126
126
  const client = new OrbotoClient({ baseUrl: 'https://orboto.example.com', apiKey: 'orb_test' });
127
127
  await expect(preflightMcpSession(client)).rejects.toBeInstanceOf(OrbotoApiError);
128
128
  });
129
+ it('ORB-2151: a client built with an instance token names the session on every request; an explicit token wins', async () => {
130
+ const seen = [];
131
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
132
+ seen.push((init?.headers ?? {}));
133
+ return { ok: true, status: 200, statusText: 'OK', json: async () => ({}), text: async () => '' };
134
+ });
135
+ const client = new OrbotoClient({ baseUrl: 'https://orboto.example.com', apiKey: 'orb_test', instanceToken: 'mcp-proc' });
136
+ await client.get('/users/me');
137
+ await client.post('/projects/p/tickets', { title: 't' });
138
+ await client.post('/v1/agent/heartbeat', {}, { instanceToken: 'mcp-explicit' });
139
+ expect(seen.map((h) => h['x-orboto-agent-session'])).toEqual(['mcp-proc', 'mcp-proc', 'mcp-explicit']);
140
+ const plain = new OrbotoClient({ baseUrl: 'https://orboto.example.com', apiKey: 'orb_test' });
141
+ await plain.get('/users/me');
142
+ expect(seen[3]['x-orboto-agent-session']).toBeUndefined();
143
+ });
129
144
  });
package/dist/server.js CHANGED
@@ -15,6 +15,7 @@ import { draftCustomerReplyToolConfig, makeDraftCustomerReplyHandler } from './t
15
15
  import { embeddingStatusToolConfig, makeEmbeddingStatusHandler } from './tools/embedding-status.js';
16
16
  import { aiUsageToolConfig, makeAiUsageHandler } from './tools/ai-usage.js';
17
17
  import { sessionStartToolConfig, makeSessionStartHandler } from './tools/session-start.js';
18
+ import { CHANNEL_CAPABILITY, CHANNEL_INSTRUCTIONS } from './inbox-channel.js';
18
19
  import { loadRequiredRules } from './required-rules.js';
19
20
  import { responseExpandToolConfig, makeResponseExpandHandler } from './tools/response-expand.js';
20
21
  import { helpToolConfig, makeHelpHandler } from './tools/help.js';
@@ -25,6 +26,7 @@ import { agentHeartbeatToolConfig, makeAgentHeartbeatHandler, agentPresenceToolC
25
26
  import { agentBroadcastToolConfig, makeAgentBroadcastHandler, } from './tools/agent-coordination.js';
26
27
  import { agentMessageWorkToolConfig, makeAgentMessageWorkHandler } from './tools/agent-message-work.js';
27
28
  import { agentMessagesToolConfig, makeAgentMessagesHandler } from './tools/agent-messages.js';
29
+ import { agentWakesToolConfig, makeAgentWakesHandler } from './tools/agent-wakes.js';
28
30
  import { listProjectsToolConfig, makeListProjectsHandler } from './tools/list-projects.js';
29
31
  import { getProjectToolConfig, makeGetProjectHandler } from './tools/get-project.js';
30
32
  import { projectReadinessToolConfig, makeProjectReadinessHandler } from './tools/project-readiness.js';
@@ -155,18 +157,22 @@ export async function buildOrbotoMcpServer(opts) {
155
157
  catch {
156
158
  workingRules = 'Workspace rules are unavailable. Built-in hints are not a substitute. Call orboto_session_start with forceRules and retry after connectivity or authentication recovers.';
157
159
  }
160
+ const channelHint = opts.channel ? [CHANNEL_INSTRUCTIONS] : [];
158
161
  const server = new McpServer({ name: 'orboto', version: VERSION }, {
159
162
  capabilities: {
160
163
  resources: { subscribe: true, listChanged: true },
164
+ ...(opts.channel ? { experimental: { [CHANNEL_CAPABILITY]: {} } } : {}),
161
165
  },
162
166
  instructions: toolset === 'minimal'
163
167
  ? [
164
168
  staticMcpHints(toolset),
165
169
  'FIRST ACTION: call `orboto_session_start` - it returns the binding workspace rules plus your in-progress work. Re-run it after any context compaction. Non-negotiables: claim or create a ticket before touching code, one commit per ticket with the ticket key in the subject, push after each commit, never mark work done that is not done.',
170
+ ...channelHint,
166
171
  ].join('\n\n')
167
172
  : assembleInstructions([
168
173
  staticMcpHints(toolset),
169
174
  'FIRST ACTION this session: call the `orboto_session_start` tool - it returns the complete, authoritative binding rules you must follow (plus your in-progress work). Re-run it after any context compaction. If the rules below look cut off, `orboto_session_start` and the `orboto://rules` resource always have the full set. (Do NOT use `orboto_list_agent_instructions` to read the rules - that manages rule blocks for admins.) Core non-negotiables: ticket-first (claim or create a ticket before touching code), one commit per ticket with the ticket key in the subject line, push after each commit, and never mark work done that is not actually done.',
175
+ ...channelHint,
170
176
  ].join('\n\n'), workingRules),
171
177
  });
172
178
  const nudgeState = createNudgeState(requireSessionStart);
@@ -183,7 +189,7 @@ export async function buildOrbotoMcpServer(opts) {
183
189
  reg('orboto_draft_customer_reply', draftCustomerReplyToolConfig, makeDraftCustomerReplyHandler(client));
184
190
  reg('orboto_embedding_status', embeddingStatusToolConfig, makeEmbeddingStatusHandler(client));
185
191
  reg('orboto_ai_usage', aiUsageToolConfig, makeAiUsageHandler(client));
186
- reg('orboto_session_start', sessionStartToolConfig, makeSessionStartHandler(client));
192
+ reg('orboto_session_start', sessionStartToolConfig, makeSessionStartHandler(client, { channel: opts.channel }));
187
193
  reg('orboto_response_expand', responseExpandToolConfig, makeResponseExpandHandler());
188
194
  reg('orboto_help', helpToolConfig, makeHelpHandler());
189
195
  reg('orboto_api_search', apiSearchToolConfig, makeApiSearchHandler(client));
@@ -198,6 +204,7 @@ export async function buildOrbotoMcpServer(opts) {
198
204
  reg('orboto_agent_notify', agentNotifyToolConfig, makeAgentNotifyHandler(client));
199
205
  reg('orboto_message_work', agentMessageWorkToolConfig, makeAgentMessageWorkHandler(client));
200
206
  reg('orboto_messages', agentMessagesToolConfig, makeAgentMessagesHandler(client));
207
+ reg('orboto_agent_wakes', agentWakesToolConfig, makeAgentWakesHandler(client));
201
208
  reg('orboto_agent_broadcast', agentBroadcastToolConfig, makeAgentBroadcastHandler(client));
202
209
  reg('orboto_list_projects', listProjectsToolConfig, makeListProjectsHandler(client));
203
210
  reg('orboto_get_project', getProjectToolConfig, makeGetProjectHandler(client));
@@ -1,5 +1,10 @@
1
1
  /**
2
2
  * ORB-1805 - the schema diet must never cost a PARAMETER.
3
+ *
4
+ * ORB-2157 - one reviewed baseline edit: `orboto_help.tool` is no longer
5
+ * required, because the tool now also answers `topic` ("connect" returns the
6
+ * setup script). The parameter itself is untouched and still the only way to
7
+ * ask for a tool's guidance; a call with neither says which topics exist.
3
8
  */
4
9
  import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
5
10
  import { readFileSync } from 'node:fs';
@@ -13,7 +13,7 @@ import { mcpInstanceToken } from './shared.js';
13
13
  const PartySchema = z.object({ userId: z.string(), email: z.string(), sessionId: z.string().nullable(), role: z.string().nullable(), label: z.string() });
14
14
  export const agentMessagesToolConfig = {
15
15
  title: 'Agent inbox and message work',
16
- description: 'Your inbox as THIS session sees it: mail to this session, account mail inside your declared scope, broadcasts; sibling-session mail and own sends stay out, all:true shows the whole account (ORB-2136). messageWork carries durable work ownership - claim before executing. ackIds is a plain read receipt: no claim needed, finishes nothing. Reply via orboto_agent_notify with threadId (toSessionRef = from.sessionId reaches that instance).',
16
+ description: 'Your inbox as THIS session sees it: mail to this session, account mail inside your declared scope, broadcasts; sibling-session mail and own sends stay out, all:true shows the whole account (ORB-2136). messageWork carries durable work ownership - claim before executing. ackIds is a plain read receipt: no claim needed, finishes nothing. dismiss is the third answer: not_mine hides it here and tells the sender, obsolete/duplicate close it for the account (note or duplicateOf required). Never leave mail you read and judged. Reply via orboto_agent_notify with threadId (toSessionRef = from.sessionId reaches that instance).',
17
17
  inputSchema: z.object({
18
18
  messageWork: z.record(z.unknown()).optional()
19
19
  .describe('Work envelope {messageId, mutation, cursor, limit, openOnly}; schema: orboto_api_search.'),
@@ -22,6 +22,12 @@ export const agentMessagesToolConfig = {
22
22
  project: z.string().min(1).max(64).optional().describe('Project key/UUID; includes unscoped mail.'),
23
23
  includeOwnSends: z.boolean().default(false),
24
24
  ackIds: z.array(z.string().uuid()).max(200).optional().describe('Message ids to mark read.'),
25
+ dismiss: z.object({
26
+ ids: z.array(z.string().uuid()).min(1).max(200),
27
+ reason: z.enum(['not_mine', 'obsolete', 'duplicate']),
28
+ note: z.string().max(500).optional(),
29
+ duplicateOf: z.string().uuid().optional(),
30
+ }).optional().describe('Dismiss with a reason; obsolete/duplicate need note or duplicateOf.'),
25
31
  }).shape,
26
32
  outputSchema: z.object({
27
33
  work: z.record(z.unknown()).optional(),
@@ -38,8 +44,13 @@ export const agentMessagesToolConfig = {
38
44
  projectKey: z.string().nullable(),
39
45
  createdAt: z.string(),
40
46
  readAt: z.string().nullable(),
47
+ dismissed: z.object({
48
+ reason: z.string(), note: z.string().nullable(), duplicateOf: z.string().nullable(), createdAt: z.string(),
49
+ }).nullable(),
41
50
  })),
42
51
  acked: z.number().int(),
52
+ dismissed: z.number().int().optional(),
53
+ closed: z.number().int().optional(),
43
54
  }).shape,
44
55
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
45
56
  };
@@ -51,6 +62,18 @@ export function makeAgentMessagesHandler(client) {
51
62
  const result = await makeAgentMessageWorkHandler(client)(args.messageWork, extra);
52
63
  return { content: result.content, structuredContent: { messages: [], acked: 0, work: result.structuredContent } };
53
64
  }
65
+ let dismissedCount = 0;
66
+ let closedCount = 0;
67
+ let feedbackSent = 0;
68
+ if (args.dismiss) {
69
+ const res = await client.post('/v1/agent/messages/dismiss', {
70
+ ...args.dismiss,
71
+ instanceToken: mcpInstanceToken(undefined, extra),
72
+ });
73
+ dismissedCount = res.dismissed;
74
+ closedCount = res.closed;
75
+ feedbackSent = res.feedbackSent;
76
+ }
54
77
  let acked = 0;
55
78
  if (args.ackIds && args.ackIds.length > 0) {
56
79
  const res = await client.post('/v1/agent/messages/ack', { ids: args.ackIds, instanceToken: mcpInstanceToken(undefined, extra) });
@@ -73,6 +96,9 @@ export function makeAgentMessagesHandler(client) {
73
96
  if (messages.length > 0) {
74
97
  lines.push(`Acknowledge with ackIds once handled; reply via orboto_agent_notify with threadId (toSessionRef = the sender's instance short id reaches that session only).`);
75
98
  }
99
+ if (args.dismiss) {
100
+ lines.unshift(`Dismissed ${dismissedCount} message(s) as ${args.dismiss.reason}${closedCount > 0 ? `, ${closedCount} closed for the account` : ''}${feedbackSent > 0 ? `, ${feedbackSent} sender(s) told about the misroute` : ''}.`);
101
+ }
76
102
  if (sessionId)
77
103
  lines.push(`This session: ${sessionId.slice(0, 8)} (ref ${instanceToken}).`);
78
104
  return {
@@ -82,9 +108,11 @@ export function makeAgentMessagesHandler(client) {
82
108
  messages: messages.map((m) => ({
83
109
  id: m.id, fromUserId: m.fromUserId, from: m.from, to: m.to, kind: m.kind, subject: m.subject,
84
110
  payload: m.payload, threadId: m.threadId, projectKey: m.projectKey ?? null,
85
- createdAt: m.createdAt, readAt: m.readAt,
111
+ createdAt: m.createdAt, readAt: m.readAt, dismissed: m.dismissed ?? null,
86
112
  })),
87
113
  acked,
114
+ dismissed: dismissedCount,
115
+ closed: closedCount,
88
116
  },
89
117
  };
90
118
  };
@@ -5,7 +5,7 @@ const WorkSessionResourceClaimSchema = z.object({
5
5
  state: z.enum(['granted', 'waiting']).optional(), requestedAt: z.string().optional(),
6
6
  });
7
7
  export const AgentInventoryKindSchema = z.enum(['agent', 'human']);
8
- export const AgentConnectionTypeSchema = z.enum(['api_key', 'oauth', 'lane', 'external_token', 'live_events', 'web']);
8
+ export const AgentConnectionTypeSchema = z.enum(['api_key', 'oauth', 'lane', 'external_token', 'live_events', 'web', 'channel']);
9
9
  export const AgentInventoryConnectionSchema = z.object({ type: AgentConnectionTypeSchema, label: z.string() });
10
10
  export const AgentInventoryProjectSchema = z.object({ id: z.string().uuid(), key: z.string(), name: z.string() });
11
11
  export const AgentInventoryEntrySchema = z.object({
@@ -34,6 +34,12 @@ export const AgentInventoryEntrySchema = z.object({
34
34
  scope: AgentSessionScopeSchema.nullable(),
35
35
  /** ORB-2136 - unread inbox messages this session would list. */
36
36
  unreadMessages: z.number().int(),
37
+ /** ORB-2149 - the last 24 hours of wakes: how many, how precise, what the wrong ones cost. */
38
+ wakes: z.object({
39
+ count: z.number().int(),
40
+ precision: z.number().nullable(),
41
+ wrongWakeContextTokens: z.number().int(),
42
+ }),
37
43
  lastSeenAt: z.string(),
38
44
  createdAt: z.string(),
39
45
  });
@@ -0,0 +1,60 @@
1
+ /**
2
+ * ORB-2149 - the wake ledger: what woke this session, by which rule, what it
3
+ * did with it and what it cost.
4
+ */
5
+ import { z } from 'zod';
6
+ export const agentWakesToolConfig = {
7
+ title: 'Wake ledger',
8
+ description: 'Who woke this account\'s sessions, which visibility rule delivered the message (addressed | scope_project | scope_ticket | broadcast | unscoped_session | account_view), what the woken session did with it (handled | not_mine | obsolete | duplicate | expired | pending) and what the wake cost in context tokens. `stats: true` returns delivery precision per woken session and per sender over `hours` (operator read, needs admin:agents:read); without it the ledger rows of your own account, newest first. Use it to prove a misrouting sender instead of describing it in prose.',
9
+ inputSchema: z.object({
10
+ stats: z.boolean().default(false).describe('Precision per session and per sender instead of rows.'),
11
+ hours: z.number().int().min(1).max(720).optional().describe('Stats window, default 24.'),
12
+ sessionId: z.string().uuid().optional().describe('Narrow to one woken session.'),
13
+ project: z.string().min(1).max(64).optional().describe('Project key or UUID.'),
14
+ outcome: z.enum(['pending', 'handled', 'not_mine', 'obsolete', 'duplicate', 'expired']).optional(),
15
+ limit: z.number().int().min(1).max(200).optional().describe('Default: 50.'),
16
+ cursor: z.string().optional().describe('Opaque cursor from a previous response.'),
17
+ }).shape,
18
+ annotations: { readOnlyHint: true, idempotentHint: true },
19
+ };
20
+ function statsLine(e) {
21
+ const precision = e.precision === null ? 'unjudged' : `${Math.round(e.precision * 100)}%`;
22
+ const tokens = e.wrongWakeContextTokens > 0 ? `, wrong wakes cost ${e.wrongWakeContextTokens} tokens` : '';
23
+ return `- ${e.label}: ${e.wakes} wakes, precision ${precision}, median ${e.medianLatencyMs ?? '?'} ms, top rule ${e.topRule ?? '-'}${tokens}`;
24
+ }
25
+ export function makeAgentWakesHandler(client) {
26
+ return async (args) => {
27
+ const qs = new URLSearchParams();
28
+ if (args.sessionId)
29
+ qs.set('sessionId', args.sessionId);
30
+ if (args.stats) {
31
+ if (args.hours)
32
+ qs.set('hours', String(args.hours));
33
+ const res = await client.get(`/admin/agents/wake-stats${qs.toString() ? `?${qs.toString()}` : ''}`);
34
+ const text = [
35
+ `Last ${res.hours} h - woken sessions:`,
36
+ ...(res.sessions.length ? res.sessions.map(statsLine) : ['- (no wakes)']),
37
+ 'Senders:',
38
+ ...(res.senders.length ? res.senders.map(statsLine) : ['- (none)']),
39
+ ].join('\n');
40
+ return { content: [{ type: 'text', text }], structuredContent: res };
41
+ }
42
+ if (args.project)
43
+ qs.set('project', args.project);
44
+ if (args.outcome)
45
+ qs.set('outcome', args.outcome);
46
+ if (args.limit)
47
+ qs.set('limit', String(args.limit));
48
+ if (args.cursor)
49
+ qs.set('cursor', args.cursor);
50
+ const res = await client.get(`/v1/agent/wakes${qs.toString() ? `?${qs.toString()}` : ''}`);
51
+ const lines = res.rows.length === 0
52
+ ? '(no wakes recorded)'
53
+ : res.rows.map((r) => `- ${r.wokenAt} ${r.subject} - from ${r.senderLabel} via ${r.rule}/${r.transport} -> ${r.outcome}`
54
+ + `${r.latencyMs === null ? '' : ` (${r.latencyMs} ms`}${r.contextTokens === null ? r.latencyMs === null ? '' : ')' : `, ${r.contextTokens} ctx tokens)`}`).join('\n');
55
+ return {
56
+ content: [{ type: 'text', text: lines + (res.nextCursor ? `\n\n(next cursor: ${res.nextCursor})` : '') }],
57
+ structuredContent: res,
58
+ };
59
+ };
60
+ }
@@ -9,6 +9,7 @@
9
9
  * instead of surfacing as an opaque tool failure.
10
10
  */
11
11
  import { z } from 'zod';
12
+ import { mcpInstanceToken } from './shared.js';
12
13
  export const apiCallToolConfig = {
13
14
  title: 'Call any orboto REST endpoint',
14
15
  description: 'Execute one REST API request - the escape hatch for every endpoint without a named tool. '
@@ -28,7 +29,7 @@ export const apiCallToolConfig = {
28
29
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
29
30
  };
30
31
  export function makeApiCallHandler(client) {
31
- return async (input) => {
32
+ return async (input, extra) => {
32
33
  let body = input.body;
33
34
  if (typeof body === 'string') {
34
35
  try {
@@ -41,7 +42,7 @@ export function makeApiCallHandler(client) {
41
42
  path: input.path,
42
43
  ...(input.query ? { query: input.query } : {}),
43
44
  ...(body !== undefined ? { body } : {}),
44
- });
45
+ }, { instanceToken: mcpInstanceToken(undefined, extra) });
45
46
  const bodyText = envelope.encoding === 'json'
46
47
  ? JSON.stringify(envelope.body, null, 1)
47
48
  : String(envelope.body ?? '');
@@ -100,4 +100,15 @@ describe('orboto_api_call', () => {
100
100
  const res = await makeApiCallHandler(client)({ method: 'GET', path: '/export' });
101
101
  expect(res.content[0].text).toContain('truncated by the proxy cap');
102
102
  });
103
+ it('ORB-2144: the proxy request carries this MCP session as x-orboto-agent-session', async () => {
104
+ const seen = [];
105
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
106
+ seen.push((init?.headers ?? {}));
107
+ return { ok: true, status: 200, statusText: 'OK', json: async () => ({ status: 200, contentType: 'application/json', body: { sessionId: 's' }, encoding: 'json', truncated: false, matchedRoute: '/v1/agent/heartbeat' }), text: async () => '' };
108
+ });
109
+ await makeApiCallHandler(client)({ method: 'POST', path: '/v1/agent/heartbeat', body: { scope: { role: 'spec' } } }, { sessionId: 'abc123' });
110
+ expect(seen[0]['x-orboto-agent-session']).toBe('mcp-abc123');
111
+ await makeApiCallHandler(client)({ method: 'GET', path: '/v1/agent/messages' });
112
+ expect(seen[1]['x-orboto-agent-session']).toMatch(/^mcp-/);
113
+ });
103
114
  });
@@ -42,7 +42,7 @@ export async function resolveDocId(client, docIdOrKey) {
42
42
  }
43
43
  export const getDocToolConfig = {
44
44
  title: 'Get a doc by id or key',
45
- description: 'Return the doc content (Markdown) plus backlinks (other docs that reference this doc, or tickets/milestones the doc is linked from). Accepts either the doc UUID or its human-readable key (e.g. ORB-D12 / DOC-5).',
45
+ description: 'Return the doc content (Markdown) plus backlinks (other docs that reference this doc, or tickets/milestones the doc is linked from). Accepts either the doc UUID or its human-readable key (e.g. ORB-D12 / DOC-5). A UUID read also reports `embedding.state` - embedded | pending | stale | not_embeddable - so a caller waits for semantic search instead of guessing (ORB-2154).',
46
46
  inputSchema: z.object({
47
47
  docId: z.string().min(1).describe('Doc UUID or human-readable key (ORB-D12 / DOC-5). Discover via orboto_list_doc_spaces or orboto_search.'),
48
48
  }).shape,
@@ -56,7 +56,7 @@ export function makeGetDocHandler(client) {
56
56
  const backlinks = await client.get(`/docs/${doc.id}/backlinks`).catch(() => []);
57
57
  const lines = [
58
58
  `# ${doc.icon ? `${doc.icon} ` : ''}${doc.title}`,
59
- `${doc.docKey ? `Key: ${doc.docKey} · ` : ''}ID: ${doc.id} · Visibility: ${doc.visibility} · Updated: ${doc.updatedAt}`,
59
+ `${doc.docKey ? `Key: ${doc.docKey} · ` : ''}ID: ${doc.id} · Visibility: ${doc.visibility} · Updated: ${doc.updatedAt}${doc.embedding ? ` · Embedding: ${doc.embedding.state}` : ''}`,
60
60
  '',
61
61
  doc.content || '_(empty)_',
62
62
  ];
@@ -80,6 +80,7 @@ export function makeGetDocHandler(client) {
80
80
  parentDocId: doc.parentDocId,
81
81
  spaceId: doc.spaceId,
82
82
  slug: doc.slug,
83
+ embedding: doc.embedding ?? null,
83
84
  },
84
85
  backlinks: backlinks.map((b) => ({
85
86
  sourceDocId: b.sourceDocId,
@@ -9,11 +9,15 @@
9
9
  */
10
10
  import { z } from 'zod';
11
11
  import { getToolDoc, listToolDocNames } from '../tool-docs.js';
12
+ import { connectScriptText } from '../connect-script.js';
13
+ /** ORB-2157 - guidance that belongs to no single tool, addressed by topic. */
14
+ const TOPICS = { connect: connectScriptText };
12
15
  export const helpToolConfig = {
13
16
  title: 'Full guidance for one orboto tool',
14
- description: 'Return the complete guidance text (workflows, warnings, edge cases) for one orboto tool by name - manifest descriptions are one-line summaries, this is the rest. Call it before first use of an unfamiliar write tool.',
17
+ description: 'Return the complete guidance text (workflows, warnings, edge cases) for one orboto tool by name - manifest descriptions are one-line summaries, this is the rest. Call it before first use of an unfamiliar write tool. topic: "connect" returns the step-by-step script for setting a person up instead.',
15
18
  inputSchema: z.object({
16
- tool: z.string().min(1).max(128).describe('Tool name, e.g. orboto_create_ticket.'),
19
+ tool: z.string().min(1).max(128).optional().describe('Tool name, e.g. orboto_create_ticket.'),
20
+ topic: z.enum(['connect']).optional().describe('Guidance topic instead of a tool.'),
17
21
  }).shape,
18
22
  outputSchema: z.object({
19
23
  tool: z.string(),
@@ -23,7 +27,19 @@ export const helpToolConfig = {
23
27
  };
24
28
  export function makeHelpHandler() {
25
29
  return async (args) => {
26
- const name = args.tool.trim();
30
+ const topic = args.topic?.trim();
31
+ if (topic) {
32
+ const render = TOPICS[topic];
33
+ const text = render
34
+ ? render()
35
+ : `No guidance registered for topic "${topic}". Known topics: ${Object.keys(TOPICS).join(', ')}`;
36
+ return { content: [{ type: 'text', text }], structuredContent: { tool: `topic:${topic}`, guidance: render ? text : '' } };
37
+ }
38
+ const name = (args.tool ?? '').trim();
39
+ if (!name) {
40
+ const text = `Name a tool, or a topic: ${Object.keys(TOPICS).join(', ')}.`;
41
+ return { content: [{ type: 'text', text }], structuredContent: { tool: '', guidance: '' } };
42
+ }
27
43
  const doc = getToolDoc(name) ?? getToolDoc(`orboto_${name}`);
28
44
  if (!doc) {
29
45
  const known = listToolDocNames();
@@ -14,6 +14,7 @@ import { AgentSessionScopeSchema } from './agent-session-scope.js';
14
14
  import { PROTECT_TEXT_META, storePayload } from '../response-budget.js';
15
15
  import { loadRequiredRules } from '../required-rules.js';
16
16
  import { GIT_HEALTH_REASON_TEXT } from './git-health-reasons.js';
17
+ import { channelStartLines } from '../inbox-channel.js';
17
18
  export const sessionStartToolConfig = {
18
19
  title: 'Load the rules you must follow + re-orient',
19
20
  description: 'THE canonical way to LOAD the binding workspace rules you must follow as an agent. Run it as your FIRST action in a session and immediately AFTER any context compaction. Returns a one-line-per-rule INDEX of the binding working-rules plus their hash (or a compact "unchanged" ack on a repeat call within the same connection) - read the index, then call this tool again with `rulesOnly: true` to read the full text of the rules whenever you do not already hold that exact hash, and expand before acting on any rule whose title touches what you are about to do. Also returns your in-progress tickets - each flagged LANDED, IDLE when it has a linked commit but has not moved for days, i.e. finished work you never handed to review - your running timer, and a warning if a project\'s git connection looks unhealthy (commit ingestion may be stalled). Pass `ticketKey` to also get a one-shot bundle for that ticket: project primer, the full ticket with dependencies + checklists, that project\'s git health, and any other agent sessions currently on it - replacing several separate calls. (Do NOT use orboto_list_agent_instructions to read the rules - that tool MANAGES/edits rule blocks for admins; this one is what you read to know how to work.) Registers this session (a heartbeat on its instance row) and is otherwise read-only. '
@@ -128,7 +129,7 @@ async function buildTicketBundle(client, ticketKey) {
128
129
  },
129
130
  };
130
131
  }
131
- export function makeSessionStartHandler(client) {
132
+ export function makeSessionStartHandler(client, opts = {}) {
132
133
  let lastKnownRulesHash;
133
134
  return async (input = {}, extra) => {
134
135
  const instanceToken = mcpInstanceToken(undefined, extra);
@@ -256,6 +257,8 @@ export function makeSessionStartHandler(client) {
256
257
  ? [registration.scope.role ? `role ${registration.scope.role}` : null, registration.scope.projectKeys?.length ? `projects ${registration.scope.projectKeys.join(', ')}` : null, registration.scope.ticketKeys?.length ? `tickets ${registration.scope.ticketKeys.join(', ')}` : null].filter(Boolean).join('; ')
257
258
  : 'no scope declared - this session lists every account-addressed message; pass scope: { projectKeys, role } to narrow it';
258
259
  lines.push(`ref ${instanceToken}${registration ? `, instance ${registration.sessionId.slice(0, 8)}` : ''}. ${scopeText}. Peers reach exactly this session with orboto_agent_notify { toSessionRef: "${registration ? registration.sessionId.slice(0, 8) : instanceToken}" }.`);
260
+ if (opts.channel)
261
+ lines.push('', ...channelStartLines());
259
262
  if (pendingMessages.length > 0) {
260
263
  lines.push('', '## Agent messages - unread');
261
264
  for (const m of pendingMessages)
@@ -9,6 +9,8 @@
9
9
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
10
10
  import { OrbotoClient } from '../orboto-client.js';
11
11
  import { makeSessionStartHandler } from './session-start.js';
12
+ import { CHANNEL_START_COMMANDS, CHANNEL_START_COMMANDS_WITHOUT_CLI } from '../inbox-channel.js';
13
+ import { readFileSync } from 'node:fs';
12
14
  import { makeResponseExpandHandler } from './response-expand.js';
13
15
  import { applyResponseBudget, budgetFor, DEFAULT_BUDGET_CHARS } from '../response-budget.js';
14
16
  beforeEach(() => { vi.restoreAllMocks(); });
@@ -566,4 +568,35 @@ describe('ORB-2136 - session scope and ref', () => {
566
568
  expect(seen.find((c) => c.path === '/v1/agent/heartbeat')?.body).toEqual({});
567
569
  expect(res.content[0].text).toContain('no scope declared');
568
570
  });
571
+ it('ORB-2148: a stdio proxy with the channel on hands over the exact start commands; other servers stay silent', async () => {
572
+ const fixture = {
573
+ '/users/me/assigned-tickets': { items: [] },
574
+ '/users/me': { email: 'dev@x.io', fullName: 'Dev' },
575
+ '/agent-instructions': { instructions: 'rules here', rulesHash: 'fixture' },
576
+ '/time/timer': {},
577
+ };
578
+ stubByPath(fixture);
579
+ const on = (await makeSessionStartHandler(client, { channel: true })()).content[0].text;
580
+ expect(on).toContain('## Wake channel');
581
+ for (const cmd of Object.values(CHANNEL_START_COMMANDS))
582
+ expect(on).toContain(`\`${cmd}\``);
583
+ for (const cmd of Object.values(CHANNEL_START_COMMANDS_WITHOUT_CLI))
584
+ expect(on).toContain(`\`${cmd}\``);
585
+ expect(on).toContain('orboto claude --continue');
586
+ expect(on).toContain('orboto claude --resume <session id>');
587
+ expect(on).toContain('orboto mcp install');
588
+ expect(on).toContain('local development');
589
+ stubByPath(fixture);
590
+ const off = (await makeSessionStartHandler(client)()).content[0].text;
591
+ expect(off).not.toContain('## Wake channel');
592
+ expect(off).not.toContain('--dangerously-load-development-channels');
593
+ });
594
+ it('ORB-2148: docs/claude-code.md carries both command forms', () => {
595
+ const docs = readFileSync(new URL('../../../../docs/claude-code.md', import.meta.url), 'utf8');
596
+ for (const cmd of Object.values(CHANNEL_START_COMMANDS))
597
+ expect(docs).toContain(cmd);
598
+ for (const cmd of Object.values(CHANNEL_START_COMMANDS_WITHOUT_CLI))
599
+ expect(docs).toContain(cmd);
600
+ expect(docs).toContain('orboto mcp install');
601
+ });
569
602
  });
@@ -102,6 +102,10 @@ const MCP_PROCESS_INSTANCE = `mcp-${randomUUID()}`;
102
102
  export function mcpInstanceToken(explicit, extra) {
103
103
  return explicit ?? (extra?.sessionId ? `mcp-${extra.sessionId}` : MCP_PROCESS_INSTANCE);
104
104
  }
105
+ /** ORB-2140 - the stdio process's own instance token, the one the inbox channel follows the stream with. */
106
+ export function mcpProcessInstance() {
107
+ return MCP_PROCESS_INSTANCE;
108
+ }
105
109
  /** ORB-1753 - the caller's self-declared agent profile from the process
106
110
  * environment (stdio servers / runners). The api-key standing profile
107
111
  * (ORB-1751) already covers keys server-side; these env vars let a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orboto/mcp",
3
- "version": "0.198.0",
3
+ "version": "0.200.0",
4
4
  "description": "Model Context Protocol server for orboto - exposes tickets, projects, milestones, time, docs, primer-facts, alerts and absences as MCP tools for Claude Desktop / Cursor / Copilot Chat / any MCP-aware AI client.",
5
5
  "license": "MIT",
6
6
  "type": "module",