@orboto/mcp 0.181.0 → 0.182.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.
@@ -18,14 +18,9 @@
18
18
  import { z } from 'zod';
19
19
  import { OrbotoApiError } from '../orboto-client.js';
20
20
  import { mcpInstanceToken, resolveTicketByKey } from './shared.js';
21
- const ResourceClaimShape = {
22
- kind: z.enum(['path', 'named']),
23
- value: z.string().min(1).max(500),
24
- mode: z.enum(['read', 'write']),
25
- };
26
- /** Shared 409-body reader: the endpoint's body carries EITHER `holder`
27
- * (a lease conflict) OR `claimConflicts` (a resource-claim conflict) -
28
- * never both, since the lease is checked before claims are applied. */
21
+ import { validateRulesReceipt } from '../required-rules.js';
22
+ export { makeWorkNextHandler, workNextToolConfig } from './work-next.js';
23
+ import { GIT_HEALTH_REASON_TEXT, ResourceClaimShape, } from './work-sessions-shared.js';
29
24
  function parseClaimConflicts(err) {
30
25
  try {
31
26
  return JSON.parse(err.body).claimConflicts;
@@ -55,12 +50,6 @@ function describe(s) {
55
50
  // Mirrors apps/mcp/src/tools/session-start.ts's local shapes - kept
56
51
  // duplicated rather than imported, same choice that file already made for
57
52
  // its own bundle types (no shared MCP-side schema layer for these).
58
- const GIT_HEALTH_REASON_TEXT = {
59
- connection_inactive: 'connection is deactivated',
60
- app_installation_suspended: 'GitHub App installation is suspended',
61
- oauth_token_expired: 'OAuth token expired with no refresh path',
62
- history_backfill_error: 'last history backfill failed',
63
- };
64
53
  export const workStartToolConfig = {
65
54
  title: 'Start a work session and load the full context bundle',
66
55
  description: 'ORB-1611 - the one-call ticket pickup. Acquires the (ticket, role) work lease with the exact same guarantees as orboto_work_session_start (exactly ONE active session per ticket+role workspace-wide, a conflict names the holder, resourceClaims apply atomically with the lease), AND in the SAME response returns the rules-hash ack (same semantics as orboto_session_start), the project primer, the ticket enriched with its description/status/priority, its checklists, its dependencies, that project\'s git connection health, and any other live sessions already on the ticket. This replaces the 8-15 separate calls (orboto_session_start, orboto_get_project_primer, orboto_get_ticket, orboto_get_checklists, orboto_list_ticket_dependencies, ...) a normal ticket pickup used to cost. Prefer this over orboto_work_session_start for picking up a ticket; use the plain tool only when you deliberately do not want the bundle (e.g. a mid-task lease renewal where you already have fresh context). A conflict never leaves a partial session behind - same rollback-on-conflict guarantee as orboto_work_session_start.',
@@ -81,7 +70,8 @@ export const workStartToolConfig = {
81
70
  onConflict: z.enum(['reject', 'queue']).optional()
82
71
  .describe('Only matters when `resourceClaims` is set. Default `reject`.'),
83
72
  }).shape,
84
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
73
+ // takeover=true cancels another holder; hints describe the worst allowed call.
74
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
85
75
  };
86
76
  export function makeWorkStartHandler(client) {
87
77
  // Per-connection rules-hash cache, mirrored from session-start.ts's
@@ -109,8 +99,7 @@ export function makeWorkStartHandler(client) {
109
99
  agentSessionToken: token,
110
100
  ...(lastKnownRulesHash ? { knownRulesHash: lastKnownRulesHash } : {}),
111
101
  });
112
- if (res.rulesHash)
113
- lastKnownRulesHash = res.rulesHash;
102
+ validateRulesReceipt(res, lastKnownRulesHash, 'rules');
114
103
  const lines = [
115
104
  res.reused
116
105
  ? `Renewed your existing ${res.session.role} session on ${args.ticketKey}.`
@@ -127,7 +116,7 @@ export function makeWorkStartHandler(client) {
127
116
  }
128
117
  lines.push('', '## Working rules');
129
118
  if (res.rulesUnchanged) {
130
- lines.push(`Unchanged since your last work-start on this connection (hash ${res.rulesHash}) - keep following what you already loaded.`);
119
+ lines.push(`Unchanged since your last work-start on this connection (hash ${res.rulesHash}). If these rules are not currently in your context, call orboto_session_start with rulesOnly: true before proceeding.`);
131
120
  }
132
121
  else {
133
122
  lines.push(res.rules?.trim() || '(no workspace rules configured)');
@@ -169,6 +158,7 @@ export function makeWorkStartHandler(client) {
169
158
  lines.push(res.siblingSessions.length === 0
170
159
  ? '(none)'
171
160
  : res.siblingSessions.map((s) => ` - [${s.role}] ${s.userFullName ?? s.userEmail ?? 'unknown'} - lease until ${s.leaseUntil}`).join('\n'));
161
+ lastKnownRulesHash = res.rulesHash;
172
162
  return {
173
163
  content: [{ type: 'text', text: lines.join('\n') }],
174
164
  structuredContent: {
@@ -249,7 +239,8 @@ export const workSessionStartToolConfig = {
249
239
  onConflict: z.enum(['reject', 'queue']).optional()
250
240
  .describe('Only matters when `resourceClaims` is set. Default `reject`: a conflicting write claim fails the WHOLE call with the conflicting holder(s) named - if this call would have created a brand-new session, that session is rolled back rather than left holding the lease without its claims. `queue`: the conflicting claim is accepted as `state: "waiting"` instead of failing; it is promoted automatically once the conflict clears (release, finish, or the next orboto_work_sessions read).'),
251
241
  }).shape,
252
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
242
+ // The optional takeover can displace someone else's active session.
243
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
253
244
  };
254
245
  export function makeWorkSessionStartHandler(client) {
255
246
  return async (args, extra) => {
@@ -423,179 +414,6 @@ export function makeWorkFinishHandler(client) {
423
414
  };
424
415
  };
425
416
  }
426
- /** ORB-1799 - rendered identically on every exit (reserved, empty, paused):
427
- * an agent that just pulled fresh work is exactly the one about to forget
428
- * the ticket it already finished. Empty array renders nothing. */
429
- function landedIdleLines(rows) {
430
- if (!rows || rows.length === 0)
431
- return [];
432
- return [
433
- '',
434
- '## Landed, idle - finished-looking work of yours awaiting the status move',
435
- ...rows.map((r) => `- ${r.ticketKey ?? r.ticketId} "${r.title}" - ${r.commitCount} commit(s) linked, no activity for ${r.idleWorkingDays} working day(s) (since ${r.lastActivityAt}).`),
436
- 'Verify each is actually finished, then move it into the review lane (orboto_work_finish with targetCategory "in_review", or orboto_move_ticket) - do NOT re-implement it.',
437
- ];
438
- }
439
- export const workNextToolConfig = {
440
- title: 'Pull and reserve the next ready ticket (worker-pool dispatch)',
441
- description: 'ORB-1613 - the pull side of low-management dispatch, sibling of orboto_work_start on the "I already know which ticket" side. Picks the highest-priority ticket in a project that is READY FOR THE REQUESTED ROLE (default role implementation pulls TODO tickets; `role: "review"` pulls tickets in the in_review status category instead, and NEVER offers a ticket the caller itself implemented - the review lane primitive, ORB-1777), unblocked (every dependency closed), not already leased under the requested role, and not blocked by a conflicting resourceClaim - then reserves it with the EXACT same guarantees as orboto_work_start (atomic lease acquire + the full context bundle: rules ack, primer, ticket, checklists, dependencies, git health, siblings) in the same response. Priority then ticket number, deterministic - never a coin flip on ties. Two workers calling this concurrently never receive the SAME ticket: the underlying reservation is the identical partial-unique-index INSERT orboto_work_start uses, just walked across an ordered candidate list - a collision just advances to the next candidate. Epics are never returned (they are containers, not directly implementable). When nothing is ready, the response is a STRUCTURED result (`reserved: null`) with a `reason` (`none-matching` = no todo tickets at all; `all-blocked` = candidates exist but all have open dependencies; `all-leased` = ready candidates exist but are all currently leased or claim-conflicted; `autonomy_paused` = ORB-1774, this agent identity or the whole workspace has autonomous pulls paused by an operator - idle and wait for an operator/notify wakeup instead of retrying) and, ONLY when derivable from an actual active lease, a `retryAfterSeconds` backoff hint (`earliestFreeAt` null and `retryAfterSeconds` null means no signal exists - never a fabricated constant). This is never an error - a worker pool should back off on the hint rather than poll hot. Prefer this over orboto_work_start whenever the caller does not care WHICH ticket it gets, only that it gets the best available one right now. Every response - reserved, empty or paused - also carries `landedIdle`: YOUR OWN tickets in this project that are still in_progress with a linked commit and no activity for days (ORB-1799). Those are finished-looking work nobody handed to the review lane; move them on instead of re-implementing them.',
442
- inputSchema: z.object({
443
- projectKey: z.string().min(1).describe('Project key (e.g. "ACME") or UUID.'),
444
- agentTag: z.string().min(1).max(64).optional()
445
- .describe('ORB-1772 - preferred-not-exclusive routing tag: tickets labeled `agent:<tag>` rank first for a matching caller, foreign `agent:*` tags rank last but stay eligible. Lowercased server-side. Set it to this worker\'s routing tag (often the model or fleet lane name).'),
446
- role: z.enum(['implementation', 'review', 'preflight', 'integration']).optional()
447
- .describe('Default `implementation`. The dispatcher only reserves a ticket whose (ticket, role) lease is free for THIS role.'),
448
- leaseSeconds: z.number().int().min(60).max(86_400).optional()
449
- .describe('How long the lease should hold without renewal. Default 900 (15 min).'),
450
- startTimer: z.boolean().optional()
451
- .describe('Defaults to true for `implementation`, false for the attach-only roles.'),
452
- agentSessionToken: z.string().optional()
453
- .describe('Stable per-agent-instance token. Omit to use this MCP connection\'s own instance id.'),
454
- resourceClaims: z.array(z.object(ResourceClaimShape)).max(50).optional()
455
- .describe('ORB-1610 - resource claims to acquire alongside the reservation, AND to filter candidates: a ticket already held under a conflicting GRANTED write claim elsewhere is skipped even when its (ticket, role) lease is free.'),
456
- onConflict: z.enum(['reject', 'queue']).optional()
457
- .describe('Only matters when `resourceClaims` is set on the WINNING candidate. Default `reject`.'),
458
- }).shape,
459
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
460
- };
461
- export function makeWorkNextHandler(client) {
462
- // Per-connection rules-hash cache, same pattern as orboto_work_start.
463
- let lastKnownRulesHash;
464
- return async (args, extra) => {
465
- const token = mcpInstanceToken(args.agentSessionToken, extra);
466
- const res = await client.post('/work-sessions/next', {
467
- projectKey: args.projectKey,
468
- ...(args.agentTag ? { agentTag: args.agentTag } : {}),
469
- ...(args.role ? { role: args.role } : {}),
470
- ...(args.leaseSeconds ? { leaseSeconds: args.leaseSeconds } : {}),
471
- ...(args.startTimer !== undefined ? { startTimer: args.startTimer } : {}),
472
- ...(args.resourceClaims && args.resourceClaims.length > 0 ? { resourceClaims: args.resourceClaims } : {}),
473
- ...(args.onConflict ? { onConflict: args.onConflict } : {}),
474
- agentSessionToken: token,
475
- ...(lastKnownRulesHash ? { knownRulesHash: lastKnownRulesHash } : {}),
476
- });
477
- if (!res.reserved) {
478
- // ORB-1774 - a pause is an operator decision, not a backoff situation:
479
- // tell the agent to idle, not to poll for a free slot.
480
- if (res.reason === 'autonomy_paused') {
481
- return {
482
- content: [{
483
- type: 'text',
484
- text: [
485
- 'Autonomous work is PAUSED for this agent (by an operator, per-bot or workspace-wide). Do not poll for new tickets - idle and wait for an operator instruction or an agent-notify wakeup. Explicitly assigned work via orboto_work_start still runs.',
486
- ...landedIdleLines(res.landedIdle),
487
- ].join('\n'),
488
- }],
489
- structuredContent: {
490
- reserved: null,
491
- reason: res.reason,
492
- retryAfterSeconds: null,
493
- earliestFreeAt: null,
494
- candidatesConsidered: 0,
495
- ...(res.landedIdle && res.landedIdle.length > 0 ? { landedIdle: res.landedIdle } : {}),
496
- },
497
- };
498
- }
499
- const lines = [`No ready ticket in "${args.projectKey}" right now (${res.reason}).`];
500
- lines.push(res.retryAfterSeconds != null
501
- ? `Retry in ~${res.retryAfterSeconds}s (earliest known free: ${res.earliestFreeAt}).`
502
- : 'No derivable ETA - poll again later or check the project board.');
503
- lines.push(`Candidates considered: ${res.candidatesConsidered}.`);
504
- lines.push(...landedIdleLines(res.landedIdle));
505
- return {
506
- content: [{ type: 'text', text: lines.join('\n') }],
507
- structuredContent: {
508
- reserved: null,
509
- reason: res.reason,
510
- retryAfterSeconds: res.retryAfterSeconds,
511
- earliestFreeAt: res.earliestFreeAt,
512
- candidatesConsidered: res.candidatesConsidered,
513
- ...(res.landedIdle && res.landedIdle.length > 0 ? { landedIdle: res.landedIdle } : {}),
514
- },
515
- };
516
- }
517
- const r = res.reserved;
518
- if (r.rulesHash)
519
- lastKnownRulesHash = r.rulesHash;
520
- const lines = [
521
- r.reused
522
- ? `Renewed your existing ${r.session.role} session on ${r.ticket.ticketKey ?? r.session.ticketId}.`
523
- : `Reserved ${r.ticket.ticketKey ?? r.session.ticketId} - started a ${r.session.role} work session.`,
524
- `Session id: ${r.session.id} (pass this to orboto_work_session_finish / orboto_work_finish).`,
525
- `Lease held until ${r.session.leaseUntil}; it renews automatically while you keep calling orboto.`,
526
- r.session.activeTimerId ? 'Timer running.' : 'No timer started for this role.',
527
- ];
528
- if (r.queued && r.queued.length > 0) {
529
- lines.push('Queued (waiting for a conflicting writer to release):', ...r.queued.map((q) => ` - ${q.claim.kind}:${q.claim.value} - position ${q.position}`));
530
- }
531
- lines.push('', '## Working rules');
532
- if (r.rulesUnchanged) {
533
- lines.push(`Unchanged since your last call on this connection (hash ${r.rulesHash}) - keep following what you already loaded.`);
534
- }
535
- else {
536
- lines.push(r.rules?.trim() || '(no workspace rules configured)');
537
- }
538
- lines.push('', '## Project primer');
539
- lines.push(r.primer.markdown.trim() || '(primer unavailable)');
540
- lines.push('', `## Ticket: ${r.ticket.ticketKey ?? '?'}`);
541
- lines.push(r.ticket.title);
542
- lines.push(`Status: ${r.ticket.statusName ?? r.ticket.status} Priority: ${r.ticket.priority} Type: ${r.ticket.type}`);
543
- if (r.ticket.description)
544
- lines.push('', r.ticket.description);
545
- lines.push('', '## Checklists');
546
- if (r.checklists.length === 0) {
547
- lines.push('(none)');
548
- }
549
- else {
550
- for (const cl of r.checklists) {
551
- lines.push(`${cl.title} (${cl.progress.done}/${cl.progress.total})${cl.triggersDone ? ' - triggers done' : ''}`);
552
- for (const i of cl.items) {
553
- const link = i.linkedTicketKey ? ` -> [${i.linkedTicketKey}] (${i.linkedTicketStatusCategory ?? 'unknown'})` : '';
554
- lines.push(`- [${i.effectiveCompleted ? 'x' : ' '}] ${i.content}${link}`);
555
- }
556
- }
557
- }
558
- // ORB-1614 - see the comment on the other fmtDeps above.
559
- const fmtDeps = (edges) => edges.length === 0 ? '(none)' : edges.map((e) => `- [${e.ticketKey ?? '?'}] ${e.title ?? `External dependency (access restricted)${e.resolved ? ' - resolved' : ' - still open'}`}${e.statusName ? ` - ${e.statusName}` : ''}`).join('\n');
560
- lines.push('', '## Dependencies');
561
- lines.push('Blocked by:', fmtDeps(r.dependencies.blockedBy), 'Blocks:', fmtDeps(r.dependencies.blocks));
562
- const unhealthy = r.gitHealth.filter((c) => !c.healthy);
563
- if (unhealthy.length > 0) {
564
- lines.push('', '## Git connection health - WARNING');
565
- for (const c of unhealthy) {
566
- lines.push(`- "${c.name}" (${c.provider}) - ${GIT_HEALTH_REASON_TEXT[c.reason ?? ''] ?? c.reason ?? 'unknown reason'}`);
567
- }
568
- }
569
- lines.push('', '## Other sessions on this ticket');
570
- lines.push(r.siblingSessions.length === 0
571
- ? '(none)'
572
- : r.siblingSessions.map((s) => ` - [${s.role}] ${s.userFullName ?? s.userEmail ?? 'unknown'} - lease until ${s.leaseUntil}`).join('\n'));
573
- lines.push(...landedIdleLines(res.landedIdle));
574
- return {
575
- content: [{ type: 'text', text: lines.join('\n') }],
576
- structuredContent: {
577
- reserved: {
578
- session: r.session,
579
- reused: r.reused,
580
- queued: r.queued ?? [],
581
- rulesHash: r.rulesHash,
582
- rulesUnchanged: r.rulesUnchanged,
583
- primer: r.primer,
584
- ticket: r.ticket,
585
- checklists: r.checklists,
586
- dependencies: r.dependencies,
587
- gitHealth: r.gitHealth,
588
- siblingSessions: r.siblingSessions,
589
- },
590
- reason: null,
591
- retryAfterSeconds: null,
592
- earliestFreeAt: null,
593
- candidatesConsidered: res.candidatesConsidered,
594
- ...(res.landedIdle && res.landedIdle.length > 0 ? { landedIdle: res.landedIdle } : {}),
595
- },
596
- };
597
- };
598
- }
599
417
  // ---------------------------------------------------------------------------
600
418
  // orboto_work_sessions
601
419
  // ---------------------------------------------------------------------------
@@ -1,5 +1,6 @@
1
1
  import { OrbotoApiError } from './orboto-client.js';
2
- import { shouldNudge, prependNudge, shouldGate, gateResult } from './session-nudge.js';
2
+ import { shouldNudge, prependNudge, shouldGate, gateResult, recordSessionStartResult } from './session-nudge.js';
3
+ import { RequiredRulesError } from './required-rules.js';
3
4
  import { applyResponseBudget, TruncationBlockAdvertisedSchema } from './response-budget.js';
4
5
  import { buildStrictInputSchema, isRawShape } from './input-schema.js';
5
6
  import { captureToolDoc, summarizeToolDescription } from './tool-docs.js';
@@ -62,8 +63,7 @@ nudge) {
62
63
  // regardless of its outcome. Applied to the returned result below.
63
64
  const wantsNudge = nudge ? shouldNudge(nudge, toolName) : false;
64
65
  // ORB-1471 - HARD session-start gate. When the workspace requires it,
65
- // refuse every tool call until `orboto_session_start` has run (this also
66
- // flips the "ran" flag when the tool IS session_start). The gate message
66
+ // refuse every tool call until `orboto_session_start` succeeds. The gate message
67
67
  // supersedes the soft nudge, so we return it directly without running the
68
68
  // handler. Disabled by default => `shouldGate` returns false and nothing
69
69
  // below changes.
@@ -92,6 +92,8 @@ nudge) {
92
92
  // as success=false in the log so dashboards reflect actual
93
93
  // user-visible failures.
94
94
  const isError = result.isError === true;
95
+ if (nudge)
96
+ recordSessionStartResult(nudge, toolName, !isError);
95
97
  void postLogEntry(client, {
96
98
  toolName,
97
99
  durationMs: Date.now() - start,
@@ -113,6 +115,12 @@ nudge) {
113
115
  }
114
116
  catch (err) {
115
117
  const durationMs = Date.now() - start;
118
+ if (nudge)
119
+ recordSessionStartResult(nudge, toolName, false);
120
+ if (err instanceof RequiredRulesError) {
121
+ void postLogEntry(client, { toolName, durationMs, success: false, statusCode: err.status, errorMessage: err.message, clientHint });
122
+ return { isError: true, content: [{ type: 'text', text: err.message }], structuredContent: { errorKey: err.errorKey, reason: err.reason, ...(err.status ? { status: err.status } : {}) } };
123
+ }
116
124
  // ORB-1174 - an OrbotoApiError carries a real HTTP status + message.
117
125
  // Return it as a structured isError result so the agent + human see
118
126
  // WHY (401 vs 404 vs 500) and can self-correct, instead of the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orboto/mcp",
3
- "version": "0.181.0",
3
+ "version": "0.182.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",