owenloop 0.3.1 → 0.4.1
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/CHANGELOG.md +32 -0
- package/README.md +53 -1
- package/dist/add.d.ts +12 -40
- package/dist/add.js +11 -176
- package/dist/cli.d.ts +52 -7
- package/dist/cli.js +1072 -382
- package/dist/credentials.d.ts +274 -0
- package/dist/credentials.js +695 -0
- package/dist/defs.js +23 -0
- package/dist/engine.js +15 -6
- package/dist/hub.d.ts +363 -6
- package/dist/hub.js +551 -4
- package/dist/index.d.ts +4 -1
- package/dist/index.js +2 -1
- package/dist/lock.d.ts +80 -0
- package/dist/lock.js +217 -0
- package/dist/mcp/serve.d.ts +84 -0
- package/dist/mcp/serve.js +565 -0
- package/dist/mcp/server.d.ts +135 -0
- package/dist/mcp/server.js +330 -0
- package/dist/model.d.ts +59 -4
- package/dist/model.js +148 -21
- package/dist/owenwork.d.ts +57 -0
- package/dist/owenwork.js +84 -0
- package/dist/types.d.ts +48 -6
- package/dist/util.d.ts +24 -0
- package/dist/util.js +25 -0
- package/docs/authoring.md +9 -0
- package/docs/cli.md +411 -15
- package/docs/design.md +86 -12
- package/docs/embedding.md +58 -0
- package/package.json +1 -1
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `owenloop mcp` — the owenloop-cli-mcp stdio control-plane surface (O2).
|
|
3
|
+
*
|
|
4
|
+
* TWO-PLANE MODEL (identity-and-setup-model doc, §5/§6/§8, in the
|
|
5
|
+
* owenloop-service repo): owenloop runs two distinct planes. The HUMAN control
|
|
6
|
+
* plane is the everyday operator surface — starting runs, answering gates,
|
|
7
|
+
* pushing defs — and it authenticates as the logged-in human. The AGENT plane
|
|
8
|
+
* is what a delivery-line worker uses with its own `olp_` bearer. This module
|
|
9
|
+
* serves the HUMAN plane to a local MCP host (Claude Code) over stdio: it reads
|
|
10
|
+
* newline-delimited JSON-RPC 2.0 on stdin, translates each `tools/call` into one
|
|
11
|
+
* authenticated HTTPS request to the hub's `/api/*` REST mirror, and writes the
|
|
12
|
+
* JSON-RPC reply on stdout. It is spawned by hosts, never run by a human at a
|
|
13
|
+
* prompt.
|
|
14
|
+
*
|
|
15
|
+
* The model doc's cardinal rule (§6): the MODEL must never see a live token.
|
|
16
|
+
* Two consequences are load-bearing here:
|
|
17
|
+
* 1. Every hub call reads the stored `human` credential fresh and refreshes it
|
|
18
|
+
* through O1's locked path (`ensureFreshOAuth`/`refreshOAuth` in
|
|
19
|
+
* `src/credentials.ts`); the bearer only ever rides the `Authorization`
|
|
20
|
+
* header, never a tool result. The server holds NO credential state between
|
|
21
|
+
* calls — its only state is the resolved origin and the fixed tool list.
|
|
22
|
+
* 2. `create_agent` MINTS an `olp_` agent token and writes it straight to the
|
|
23
|
+
* local store (`storeCredential`, slot `agent:<name>`, scopes `['work']`);
|
|
24
|
+
* the token is NEVER returned in a tool result, printed, or logged. The
|
|
25
|
+
* mint response body carries the plaintext in TWO fields (`data.token` AND
|
|
26
|
+
* the human `text` "Store this secret now…"), so the handler builds its
|
|
27
|
+
* result object FROM SCRATCH (`{name, pools, stored:true}`) and never
|
|
28
|
+
* passes any field of the raw body outbound.
|
|
29
|
+
*
|
|
30
|
+
* The transport core is in `./server.ts` (a copy of owenwork's; see its header).
|
|
31
|
+
* Everything owenloop-specific — origin resolution, the authenticated hub
|
|
32
|
+
* client, the tool registrations, the enrollment capability gate, and the
|
|
33
|
+
* command body — lives here.
|
|
34
|
+
*/
|
|
35
|
+
import { CliError } from "../util.js";
|
|
36
|
+
import { authHeader, ensureFreshOAuth, hubFetch, refreshOAuth, storeCredential, } from "../credentials.js";
|
|
37
|
+
import { credentialBackend, listStoredHubOrigins, normalizeOrigin, readStoredCredential, resolveEndpoint, } from "../hub.js";
|
|
38
|
+
import { createMcpServer, pumpStdin, textResult } from "./server.js";
|
|
39
|
+
/** The human control plane authenticates as the human slot, always. */
|
|
40
|
+
const HUMAN = { principal: 'human' };
|
|
41
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
42
|
+
/**
|
|
43
|
+
* Resolve the hub origin this server binds to, precedence:
|
|
44
|
+
* 1. `--hub <origin>` flag,
|
|
45
|
+
* 2. `OWENLOOP_HUB` env,
|
|
46
|
+
* 3. if the FILE credential backend holds exactly ONE hub with a valid `human`
|
|
47
|
+
* slot, use it,
|
|
48
|
+
* 4. else exit 2 with a message naming BOTH remedies.
|
|
49
|
+
*
|
|
50
|
+
* Rungs 1–2 normalize the origin (a malformed value throws a `CliError` → the
|
|
51
|
+
* command's exit-1 path via `mainAsync`'s catch, matching every other command).
|
|
52
|
+
* Rung 3 is file-backend-only because only the file backend can enumerate
|
|
53
|
+
* (`listStoredHubOrigins`); `null` (cannot enumerate — keychain/external), `[]`
|
|
54
|
+
* (nothing stored), and length>1 (ambiguous) each get a tailored exit-2 message.
|
|
55
|
+
*
|
|
56
|
+
* DELIBERATELY there is NO silent production fallback (the CLI's `resolveHub`
|
|
57
|
+
* `DEFAULT_HUB` rung): a control-plane server must never bind to a hub the
|
|
58
|
+
* operator did not name.
|
|
59
|
+
*/
|
|
60
|
+
export function resolveMcpOrigin(io, hubFlag) {
|
|
61
|
+
const explicit = hubFlag ?? io.env.OWENLOOP_HUB;
|
|
62
|
+
if (explicit !== undefined && explicit.trim() !== '') {
|
|
63
|
+
try {
|
|
64
|
+
return { origin: normalizeOrigin(explicit) };
|
|
65
|
+
}
|
|
66
|
+
catch (e) {
|
|
67
|
+
throw new CliError(e.message);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const origins = listStoredHubOrigins(io.env, io.keychain);
|
|
71
|
+
if (origins === null) {
|
|
72
|
+
const backend = credentialBackend(io.env, io.keychain);
|
|
73
|
+
const which = backend.kind === 'external' ? 'external-command' : 'keychain';
|
|
74
|
+
return {
|
|
75
|
+
exitCode: 2,
|
|
76
|
+
message: `cannot list stored hubs from the ${which} credential store — ` +
|
|
77
|
+
'pass --hub <origin> (or set OWENLOOP_HUB)',
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
if (origins.length === 0) {
|
|
81
|
+
return {
|
|
82
|
+
exitCode: 2,
|
|
83
|
+
message: 'no hub credentials stored — run `owenloop login --hub <origin>` first, or pass --hub <origin>',
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
if (origins.length > 1) {
|
|
87
|
+
return {
|
|
88
|
+
exitCode: 2,
|
|
89
|
+
message: `multiple hubs in the credential store (${origins.join(', ')}) — pass --hub <origin>`,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
return { origin: origins[0] };
|
|
93
|
+
}
|
|
94
|
+
// ---- the authenticated hub client -------------------------------------------
|
|
95
|
+
/** The non-interactive "you are not authenticated" instruction (Decision 8). */
|
|
96
|
+
function loginHint(origin) {
|
|
97
|
+
return `not logged in to ${origin} — run \`owenloop login --hub ${origin}\` in a terminal, then retry`;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Make ONE authenticated hub call for the current `tools/call`, mirroring the
|
|
101
|
+
* CLI's `authedGet` refresh-and-retry discipline (cli.ts):
|
|
102
|
+
* 1. read the `human` slot fresh (picks up a `login` performed while the
|
|
103
|
+
* server runs) — missing → `authFailed`;
|
|
104
|
+
* 2. `ensureFreshOAuth` (persist=true → O1's locked, double-checked refresh) —
|
|
105
|
+
* a `CliError` → `authFailed` with its message + the login hint;
|
|
106
|
+
* 3. the HTTP call with `Authorization: authHeader(cred)`;
|
|
107
|
+
* 4. on a 401 with an oauth credential, exactly ONE `refreshOAuth` + one
|
|
108
|
+
* retry; a final 401 → `authFailed`.
|
|
109
|
+
* The response body is parsed leniently (a parse failure yields `{}`, status
|
|
110
|
+
* preserved). The bearer never leaves the `Authorization` header.
|
|
111
|
+
*/
|
|
112
|
+
async function callHub(deps, req) {
|
|
113
|
+
const { io, origin } = deps;
|
|
114
|
+
let cred;
|
|
115
|
+
try {
|
|
116
|
+
cred = readStoredCredential(origin, { principal: 'human', env: io.env, keychain: io.keychain });
|
|
117
|
+
}
|
|
118
|
+
catch (e) {
|
|
119
|
+
// External-command backend failing to supply a credential is an auth failure.
|
|
120
|
+
return { status: 0, json: undefined, authFailed: true, authMessage: `${e.message}\n${loginHint(origin)}` };
|
|
121
|
+
}
|
|
122
|
+
if (cred === null) {
|
|
123
|
+
return { status: 0, json: undefined, authFailed: true, authMessage: loginHint(origin) };
|
|
124
|
+
}
|
|
125
|
+
let current;
|
|
126
|
+
try {
|
|
127
|
+
current = await ensureFreshOAuth(io, origin, HUMAN, cred);
|
|
128
|
+
}
|
|
129
|
+
catch (e) {
|
|
130
|
+
return { status: 0, json: undefined, authFailed: true, authMessage: `${e.message}\n${loginHint(origin)}` };
|
|
131
|
+
}
|
|
132
|
+
const fetchOnce = async (c) => {
|
|
133
|
+
const headers = {
|
|
134
|
+
Authorization: authHeader(c),
|
|
135
|
+
Accept: 'application/json',
|
|
136
|
+
...(req.body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
|
137
|
+
};
|
|
138
|
+
return hubFetch(io, resolveEndpoint(origin, req.path + (req.query ?? '')), {
|
|
139
|
+
method: req.method,
|
|
140
|
+
headers,
|
|
141
|
+
...(req.body !== undefined ? { body: JSON.stringify(req.body) } : {}),
|
|
142
|
+
});
|
|
143
|
+
};
|
|
144
|
+
let res = await fetchOnce(current);
|
|
145
|
+
if (res.status === 401 && current.kind === 'oauth') {
|
|
146
|
+
try {
|
|
147
|
+
current = await refreshOAuth(io, origin, HUMAN, current);
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
return { status: 401, json: undefined, authFailed: true, authMessage: `${e.message}\n${loginHint(origin)}` };
|
|
151
|
+
}
|
|
152
|
+
res = await fetchOnce(current);
|
|
153
|
+
}
|
|
154
|
+
if (res.status === 401) {
|
|
155
|
+
return { status: 401, json: undefined, authFailed: true, authMessage: loginHint(origin) };
|
|
156
|
+
}
|
|
157
|
+
let json;
|
|
158
|
+
try {
|
|
159
|
+
json = await res.json();
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
json = {};
|
|
163
|
+
}
|
|
164
|
+
return { status: res.status, json };
|
|
165
|
+
}
|
|
166
|
+
/** Whether an HTTP status is a 2xx success. */
|
|
167
|
+
const isOk = (status) => status >= 200 && status < 300;
|
|
168
|
+
/**
|
|
169
|
+
* The MCP tool result for a baseline REST passthrough: 2xx → the body as one
|
|
170
|
+
* text block; non-2xx → an `isError` result carrying the body's `message` when
|
|
171
|
+
* it parses as `{error, message}`, else `HTTP <status>`.
|
|
172
|
+
*/
|
|
173
|
+
function toolResultFromRest(r) {
|
|
174
|
+
if (isOk(r.status))
|
|
175
|
+
return textResult(r.json);
|
|
176
|
+
let error = `http_${r.status}`;
|
|
177
|
+
let message = `HTTP ${r.status}`;
|
|
178
|
+
if (isObject(r.json)) {
|
|
179
|
+
if (typeof r.json['error'] === 'string')
|
|
180
|
+
error = r.json['error'];
|
|
181
|
+
if (typeof r.json['message'] === 'string')
|
|
182
|
+
message = r.json['message'];
|
|
183
|
+
}
|
|
184
|
+
return textResult({ error, message }, true);
|
|
185
|
+
}
|
|
186
|
+
/** An `isError` result whose single text block is `text` verbatim (not JSON). */
|
|
187
|
+
function errorText(text) {
|
|
188
|
+
return { content: [{ type: 'text', text }], isError: true };
|
|
189
|
+
}
|
|
190
|
+
// ---- tool table -------------------------------------------------------------
|
|
191
|
+
/** JSON-Schema fragment for a `{kind:'session'|'exec', id}` holder tag. */
|
|
192
|
+
const HOLDER_SCHEMA = {
|
|
193
|
+
type: 'object',
|
|
194
|
+
properties: { kind: { type: 'string', enum: ['session', 'exec'] }, id: { type: 'string' } },
|
|
195
|
+
required: ['kind', 'id'],
|
|
196
|
+
additionalProperties: false,
|
|
197
|
+
};
|
|
198
|
+
/** Build a baseline passthrough handler from a request-builder. */
|
|
199
|
+
function passthrough(deps, build) {
|
|
200
|
+
return async (args) => {
|
|
201
|
+
const r = await callHub(deps, build(args));
|
|
202
|
+
if (r.authFailed)
|
|
203
|
+
return errorText(r.authMessage ?? loginHint(deps.origin));
|
|
204
|
+
return toolResultFromRest(r);
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* The 17 baseline tools — names, descriptions, and schemas mirror the hub's own
|
|
209
|
+
* HTTP-MCP toolset (owenloop-service `apps/hub-edge/src/mcp/tools.ts`); each maps
|
|
210
|
+
* to an H3 `/api/*` REST mirror. Descriptions say "agent" for the identity,
|
|
211
|
+
* never "tool" (model-doc §0/§10).
|
|
212
|
+
*/
|
|
213
|
+
function buildBaselineTools(deps) {
|
|
214
|
+
return [
|
|
215
|
+
{
|
|
216
|
+
name: 'whats_next',
|
|
217
|
+
description: 'THE verb. With workflow: ticks it and returns the next work order(s), or a status summary if none. Without workflow: the inbox of started instances. Serves only YOUR OWN runs by default. Pass serve_pools to partition your own runs further (intersects with each step\'s labels; absent or [] = no label filter). serve_pools is ignored in inbox mode (no workflow).',
|
|
218
|
+
inputSchema: {
|
|
219
|
+
type: 'object',
|
|
220
|
+
properties: { workflow: { type: 'string' }, serve_pools: { type: 'array', items: { type: 'string' } } },
|
|
221
|
+
additionalProperties: false,
|
|
222
|
+
},
|
|
223
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/whats_next', body: a })),
|
|
224
|
+
},
|
|
225
|
+
{
|
|
226
|
+
name: 'submit',
|
|
227
|
+
description: 'Submit a work order output. On schema-rejected the run stays open — fix the value and submit again with the same run.',
|
|
228
|
+
inputSchema: {
|
|
229
|
+
type: 'object',
|
|
230
|
+
properties: {
|
|
231
|
+
workflow: { type: 'string' },
|
|
232
|
+
run: { type: 'string' },
|
|
233
|
+
path: { type: 'string' },
|
|
234
|
+
value: { type: 'object', additionalProperties: true },
|
|
235
|
+
done: { type: 'boolean' },
|
|
236
|
+
},
|
|
237
|
+
required: ['workflow', 'run', 'path', 'value'],
|
|
238
|
+
additionalProperties: false,
|
|
239
|
+
},
|
|
240
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/submit', body: a })),
|
|
241
|
+
},
|
|
242
|
+
{
|
|
243
|
+
name: 'reject_artifact',
|
|
244
|
+
description: 'Reject an upstream artifact, sending it back to its producer with a reason.',
|
|
245
|
+
inputSchema: {
|
|
246
|
+
type: 'object',
|
|
247
|
+
properties: { workflow: { type: 'string' }, path: { type: 'string' }, reason: { type: 'string' } },
|
|
248
|
+
required: ['workflow', 'path', 'reason'],
|
|
249
|
+
additionalProperties: false,
|
|
250
|
+
},
|
|
251
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/reject_artifact', body: a })),
|
|
252
|
+
},
|
|
253
|
+
{
|
|
254
|
+
name: 'provide_input',
|
|
255
|
+
description: 'The human-gate answer path: provide a value for a seeded/owed input.',
|
|
256
|
+
inputSchema: {
|
|
257
|
+
type: 'object',
|
|
258
|
+
properties: {
|
|
259
|
+
workflow: { type: 'string' },
|
|
260
|
+
name: { type: 'string' },
|
|
261
|
+
value: { type: 'object', additionalProperties: true },
|
|
262
|
+
},
|
|
263
|
+
required: ['workflow', 'name', 'value'],
|
|
264
|
+
additionalProperties: false,
|
|
265
|
+
},
|
|
266
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/provide_input', body: a })),
|
|
267
|
+
},
|
|
268
|
+
{
|
|
269
|
+
name: 'start_run',
|
|
270
|
+
description: 'Create a new workflow instance from a definition name, optionally seeding provided inputs.',
|
|
271
|
+
inputSchema: {
|
|
272
|
+
type: 'object',
|
|
273
|
+
properties: { workflow_name: { type: 'string' }, provide: { type: 'object', additionalProperties: true } },
|
|
274
|
+
required: ['workflow_name'],
|
|
275
|
+
additionalProperties: false,
|
|
276
|
+
},
|
|
277
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/start_run', body: a })),
|
|
278
|
+
},
|
|
279
|
+
{
|
|
280
|
+
name: 'create_workflow',
|
|
281
|
+
description: 'The authoring hard gate: parse + load a workflow def YAML through the engine. Only stored if it loads clean. On failure returns the engine/parser error verbatim. Idempotent: re-pushing identical content is a no-op success (unchanged: true with the existing version); changed content version-forwards.',
|
|
282
|
+
inputSchema: {
|
|
283
|
+
type: 'object',
|
|
284
|
+
properties: { yaml: { type: 'string' } },
|
|
285
|
+
required: ['yaml'],
|
|
286
|
+
additionalProperties: false,
|
|
287
|
+
},
|
|
288
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/create_workflow', body: a })),
|
|
289
|
+
},
|
|
290
|
+
{
|
|
291
|
+
name: 'get_workflow',
|
|
292
|
+
description: 'Def summary and full workflow bundle: steps with consumes/produces, schemas, judges, each step\'s prompt body, model/worker/command, and x extension bags, plus mermaid source and the def content hash/version.',
|
|
293
|
+
inputSchema: {
|
|
294
|
+
type: 'object',
|
|
295
|
+
properties: { name: { type: 'string' } },
|
|
296
|
+
required: ['name'],
|
|
297
|
+
additionalProperties: false,
|
|
298
|
+
},
|
|
299
|
+
handler: passthrough(deps, (a) => ({
|
|
300
|
+
method: 'GET',
|
|
301
|
+
path: `/api/workflows/${encodeURIComponent(String(a['name'] ?? ''))}`,
|
|
302
|
+
})),
|
|
303
|
+
},
|
|
304
|
+
{
|
|
305
|
+
name: 'list_workflows',
|
|
306
|
+
description: 'Names, titles, step counts, and def content hash/version of every loaded workflow definition.',
|
|
307
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
308
|
+
handler: passthrough(deps, () => ({ method: 'GET', path: '/api/workflows' })),
|
|
309
|
+
},
|
|
310
|
+
{
|
|
311
|
+
name: 'get_status',
|
|
312
|
+
description: 'engine.status verbatim plus a plain-English one-paragraph rendering.',
|
|
313
|
+
inputSchema: {
|
|
314
|
+
type: 'object',
|
|
315
|
+
properties: { workflow: { type: 'string' } },
|
|
316
|
+
required: ['workflow'],
|
|
317
|
+
additionalProperties: false,
|
|
318
|
+
},
|
|
319
|
+
handler: passthrough(deps, (a) => ({
|
|
320
|
+
method: 'GET',
|
|
321
|
+
path: `/api/status/${encodeURIComponent(String(a['workflow'] ?? ''))}`,
|
|
322
|
+
})),
|
|
323
|
+
},
|
|
324
|
+
{
|
|
325
|
+
name: 'heartbeat',
|
|
326
|
+
description: 'Touch the liveness timestamp on an open run so it is not reaped mid-step (the design-doc "renew"). The first heartbeat on a freshly served claim is "first contact" — it closes the ~2-minute pickup window. Optionally tag who holds the claim (session or exec).',
|
|
327
|
+
inputSchema: {
|
|
328
|
+
type: 'object',
|
|
329
|
+
properties: { workflow: { type: 'string' }, run: { type: 'string' }, holder: HOLDER_SCHEMA },
|
|
330
|
+
required: ['workflow', 'run'],
|
|
331
|
+
additionalProperties: false,
|
|
332
|
+
},
|
|
333
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/heartbeat', body: a })),
|
|
334
|
+
},
|
|
335
|
+
{
|
|
336
|
+
name: 'get_order',
|
|
337
|
+
description: 'Re-fetch the persisted order packet for a run you hold, plus its live lease state (claimed/claimedAt/heartbeatAt/outcome) — for a holder rebinding to work it already had served. Optionally tag who holds the claim.',
|
|
338
|
+
inputSchema: {
|
|
339
|
+
type: 'object',
|
|
340
|
+
properties: { workflow: { type: 'string' }, run: { type: 'string' }, holder: HOLDER_SCHEMA },
|
|
341
|
+
required: ['workflow', 'run'],
|
|
342
|
+
additionalProperties: false,
|
|
343
|
+
},
|
|
344
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/get_order', body: a })),
|
|
345
|
+
},
|
|
346
|
+
{
|
|
347
|
+
name: 'release',
|
|
348
|
+
description: 'Voluntarily give back a claim so its order is re-offered without waiting out the reap TTL. Either target one run (`workflow`+`run`) or drain a session (`session`). Idempotent: releasing an unheld/closed run is a no-op, never an error.',
|
|
349
|
+
inputSchema: {
|
|
350
|
+
type: 'object',
|
|
351
|
+
properties: { workflow: { type: 'string' }, run: { type: 'string' }, session: { type: 'string' } },
|
|
352
|
+
additionalProperties: false,
|
|
353
|
+
},
|
|
354
|
+
handler: async (a) => {
|
|
355
|
+
// Mirror the hub tool's client-side "either session or workflow+run" guard.
|
|
356
|
+
const hasSession = a['session'] !== undefined;
|
|
357
|
+
const hasRunPair = a['workflow'] !== undefined && a['run'] !== undefined;
|
|
358
|
+
if (!hasSession && !hasRunPair) {
|
|
359
|
+
return errorText('release requires either `session`, or both `workflow` and `run`.');
|
|
360
|
+
}
|
|
361
|
+
const r = await callHub(deps, { method: 'POST', path: '/api/release', body: a });
|
|
362
|
+
if (r.authFailed)
|
|
363
|
+
return errorText(r.authMessage ?? loginHint(deps.origin));
|
|
364
|
+
return toolResultFromRest(r);
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
{
|
|
368
|
+
name: 'publish_event',
|
|
369
|
+
description: 'Publish an event against a contract: validate the payload against the pinned contract version schema, then start one run per matched active subscription (best-effort, per-target isolation). Returns the per-match outcome. Requires agent scope `run`.',
|
|
370
|
+
inputSchema: {
|
|
371
|
+
type: 'object',
|
|
372
|
+
properties: {
|
|
373
|
+
name: { type: 'string' },
|
|
374
|
+
version: { type: 'integer', minimum: 1 },
|
|
375
|
+
payload: {},
|
|
376
|
+
},
|
|
377
|
+
required: ['name', 'payload'],
|
|
378
|
+
additionalProperties: false,
|
|
379
|
+
},
|
|
380
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/publish_event', body: a })),
|
|
381
|
+
},
|
|
382
|
+
{
|
|
383
|
+
name: 'list_subscriptions',
|
|
384
|
+
description: "The org's contract subscriptions — what a publish will cascade into. Creating/revoking a subscription is admin-only and deliberately not exposed here.",
|
|
385
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
386
|
+
handler: passthrough(deps, () => ({ method: 'GET', path: '/api/subscriptions' })),
|
|
387
|
+
},
|
|
388
|
+
{
|
|
389
|
+
name: 'presence_ping',
|
|
390
|
+
description: 'Register or refresh this conductor in the presence registry (name + the labels it serves). Call it on a ~60s cadence; the entry reads as offline after ~3 min of missed pings. Observability only. Omitting serve_pools stores an empty label set (overwrite, NOT keep-previous).',
|
|
391
|
+
inputSchema: {
|
|
392
|
+
type: 'object',
|
|
393
|
+
properties: { name: { type: 'string' }, serve_pools: { type: 'array', items: { type: 'string' } } },
|
|
394
|
+
required: ['name'],
|
|
395
|
+
additionalProperties: false,
|
|
396
|
+
},
|
|
397
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/presence_ping', body: a })),
|
|
398
|
+
},
|
|
399
|
+
{
|
|
400
|
+
name: 'list_conductors',
|
|
401
|
+
description: "Your principal's registered conductors, each with an online/offline flag (derived from its last ping), the labels it serves, and how long since it was last seen.",
|
|
402
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
403
|
+
handler: passthrough(deps, () => ({ method: 'GET', path: '/api/conductors' })),
|
|
404
|
+
},
|
|
405
|
+
{
|
|
406
|
+
name: 'wake',
|
|
407
|
+
description: 'A cheap "has anything relevant to you changed since cursor X" pre-check for a polling loop — returns { cursor, changed }. Keep the returned cursor and pass it next time; call whats_next ONLY when changed is true. Omit cursor to bootstrap. NOT a substitute for whats_next — it never returns work orders, only whether to ask.',
|
|
408
|
+
inputSchema: {
|
|
409
|
+
type: 'object',
|
|
410
|
+
properties: { cursor: { type: 'integer', minimum: 0 } },
|
|
411
|
+
additionalProperties: false,
|
|
412
|
+
},
|
|
413
|
+
handler: passthrough(deps, (a) => {
|
|
414
|
+
const cursor = a['cursor'];
|
|
415
|
+
const query = typeof cursor === 'number' ? `?cursor=${encodeURIComponent(String(cursor))}` : undefined;
|
|
416
|
+
return { method: 'GET', path: '/api/wake', query };
|
|
417
|
+
}),
|
|
418
|
+
},
|
|
419
|
+
];
|
|
420
|
+
}
|
|
421
|
+
/** Legal agent name, mirroring hub.ts's `ACCOUNT_RE` shape — advisory in the schema, ENFORCED in the handler. */
|
|
422
|
+
const AGENT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
423
|
+
/**
|
|
424
|
+
* Tool 18 — `create_agent`. Mints a NEW agent identity and writes its `olp_`
|
|
425
|
+
* token straight to the local store; NEVER returns the token. Decision 6: the
|
|
426
|
+
* mint response leaks the plaintext in `data.token` AND the human `text` field,
|
|
427
|
+
* so this handler never passes the raw body outbound — it takes only the
|
|
428
|
+
* validated `token` (to store) and the safe `pools` names (to report), and
|
|
429
|
+
* builds `{name, pools, stored:true}` from scratch.
|
|
430
|
+
*/
|
|
431
|
+
function createAgentTool(deps) {
|
|
432
|
+
return {
|
|
433
|
+
name: 'create_agent',
|
|
434
|
+
description: 'Create a NEW agent identity on the hub and store its credential locally. NEVER returns the token — it is written to this machine\'s credential store only. Refuses a name that is already taken. Mints with `work` scope.',
|
|
435
|
+
inputSchema: {
|
|
436
|
+
type: 'object',
|
|
437
|
+
properties: {
|
|
438
|
+
name: { type: 'string', pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$' },
|
|
439
|
+
pools: { type: 'array', items: { type: 'string' } },
|
|
440
|
+
},
|
|
441
|
+
required: ['name'],
|
|
442
|
+
additionalProperties: false,
|
|
443
|
+
},
|
|
444
|
+
handler: async (args) => {
|
|
445
|
+
const name = args['name'];
|
|
446
|
+
// Re-validate the name BEFORE any network call — the advertised schema is
|
|
447
|
+
// advisory (hosts may not enforce it); `credentialSlot` is the backstop.
|
|
448
|
+
if (typeof name !== 'string' || !AGENT_NAME_RE.test(name)) {
|
|
449
|
+
return errorText('invalid agent name — expected 1-64 chars matching [A-Za-z0-9][A-Za-z0-9._-]*');
|
|
450
|
+
}
|
|
451
|
+
const pools = args['pools'];
|
|
452
|
+
const body = { name, scopes: ['work'] };
|
|
453
|
+
if (Array.isArray(pools))
|
|
454
|
+
body.pools = pools;
|
|
455
|
+
const r = await callHub(deps, { method: 'POST', path: '/api/mint_agent_token', body });
|
|
456
|
+
if (r.authFailed)
|
|
457
|
+
return errorText(r.authMessage ?? loginHint(deps.origin));
|
|
458
|
+
if (!isOk(r.status)) {
|
|
459
|
+
// Surface the hub's `message` ONLY (error bodies never carry tokens, but
|
|
460
|
+
// never echo the whole body regardless).
|
|
461
|
+
const message = isObject(r.json) && typeof r.json['message'] === 'string' ? r.json['message'] : `HTTP ${r.status}`;
|
|
462
|
+
return errorText(message);
|
|
463
|
+
}
|
|
464
|
+
// 2xx: extract and validate the token WITHOUT echoing the body.
|
|
465
|
+
const token = isObject(r.json) ? r.json['token'] : undefined;
|
|
466
|
+
if (typeof token !== 'string' || !token.startsWith('olp_')) {
|
|
467
|
+
return errorText('hub response did not include an agent token');
|
|
468
|
+
}
|
|
469
|
+
try {
|
|
470
|
+
await storeCredential(deps.io, deps.origin, { principal: 'agent', account: name }, { kind: 'agent', accessToken: token });
|
|
471
|
+
}
|
|
472
|
+
catch (e) {
|
|
473
|
+
return errorText(`${e.message} — the minted token was NOT stored — revoke/re-key the agent '${name}' from the console`);
|
|
474
|
+
}
|
|
475
|
+
// Success: built from scratch. `pools` (poolNames) is safe; token/text/id
|
|
476
|
+
// /agentId/poolIds from the body must never reach an outbound frame.
|
|
477
|
+
const outPools = isObject(r.json) && Array.isArray(r.json['pools']) ? r.json['pools'] : [];
|
|
478
|
+
return textResult({ name, pools: outPools, stored: true });
|
|
479
|
+
},
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
/** Tool 19 (gated) — `stage_enrollment`: a plain passthrough (join codes are transcript-legal per model-doc §6). */
|
|
483
|
+
function stageEnrollmentTool(deps) {
|
|
484
|
+
return {
|
|
485
|
+
name: 'stage_enrollment',
|
|
486
|
+
description: 'Stage an agent enrollment on the hub, returning a join code the new agent redeems. A join code is transferred authority, not a credential — it is safe to surface.',
|
|
487
|
+
inputSchema: {
|
|
488
|
+
type: 'object',
|
|
489
|
+
properties: {
|
|
490
|
+
name: { type: 'string', pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$' },
|
|
491
|
+
pools: { type: 'array', items: { type: 'string' } },
|
|
492
|
+
},
|
|
493
|
+
required: ['name'],
|
|
494
|
+
additionalProperties: false,
|
|
495
|
+
},
|
|
496
|
+
handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/stage_enrollment', body: a })),
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
// ---- enrollment capability gate (Decision 7) --------------------------------
|
|
500
|
+
/** The probe deadline; `OWENLOOP_MCP_PROBE_TIMEOUT_MS` overrides the 3000ms default. */
|
|
501
|
+
function probeTimeoutMs(env) {
|
|
502
|
+
const override = Number(env.OWENLOOP_MCP_PROBE_TIMEOUT_MS);
|
|
503
|
+
return Number.isFinite(override) && override > 0 ? override : 3000;
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Decide, ONCE at startup, whether `stage_enrollment` is registered (the core's
|
|
507
|
+
* tool list is fixed at construction). `OWENLOOP_MCP_ENROLLMENT=1` → yes; `=0` →
|
|
508
|
+
* no; unset → PROBE. Probe (only when a human credential is stored): a
|
|
509
|
+
* short-deadline `POST /api/stage_enrollment {}` via the authed client; register
|
|
510
|
+
* iff the call completes with a status that is neither 404 nor 401 (a registered
|
|
511
|
+
* route answers 400/403/2xx to an empty body; an unregistered route 404s). Any
|
|
512
|
+
* network error, timeout, refresh failure, or missing credential → NOT
|
|
513
|
+
* registered (fail-closed: worst case the tool is hidden until H4/H7 revisit).
|
|
514
|
+
*/
|
|
515
|
+
async function shouldRegisterEnrollment(deps) {
|
|
516
|
+
const flag = deps.io.env.OWENLOOP_MCP_ENROLLMENT;
|
|
517
|
+
if (flag === '1')
|
|
518
|
+
return true;
|
|
519
|
+
if (flag === '0')
|
|
520
|
+
return false;
|
|
521
|
+
try {
|
|
522
|
+
const cred = readStoredCredential(deps.origin, { principal: 'human', env: deps.io.env, keychain: deps.io.keychain });
|
|
523
|
+
if (cred === null)
|
|
524
|
+
return false;
|
|
525
|
+
const probeTimeout = probeTimeoutMs(deps.io.env);
|
|
526
|
+
const probeIo = { ...deps.io, env: { ...deps.io.env, OWENLOOP_HUB_TIMEOUT_MS: String(probeTimeout) } };
|
|
527
|
+
const r = await callHub({ io: probeIo, origin: deps.origin }, { method: 'POST', path: '/api/stage_enrollment', body: {} });
|
|
528
|
+
if (r.authFailed)
|
|
529
|
+
return false;
|
|
530
|
+
return r.status !== 404 && r.status !== 401;
|
|
531
|
+
}
|
|
532
|
+
catch {
|
|
533
|
+
return false;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
// ---- command body -----------------------------------------------------------
|
|
537
|
+
/**
|
|
538
|
+
* Run the `owenloop mcp` command: resolve the origin, decide the enrollment
|
|
539
|
+
* gate, build the tool list, construct the JSON-RPC server, and pump stdin until
|
|
540
|
+
* EOF. Returns the process exit code: 2 on an origin-ambiguity (message to
|
|
541
|
+
* stderr, nothing to stdout — stdout is the protocol channel), else 0 on stdin
|
|
542
|
+
* EOF. A malformed `--hub`/`OWENLOOP_HUB` throws a `CliError` (exit-1 path).
|
|
543
|
+
*/
|
|
544
|
+
export async function runMcpCommand(io, opts) {
|
|
545
|
+
const resolved = resolveMcpOrigin(io, opts.hubFlag);
|
|
546
|
+
if ('exitCode' in resolved) {
|
|
547
|
+
io.err(resolved.message);
|
|
548
|
+
return resolved.exitCode;
|
|
549
|
+
}
|
|
550
|
+
const deps = { io, origin: resolved.origin };
|
|
551
|
+
const tools = [...buildBaselineTools(deps), createAgentTool(deps)];
|
|
552
|
+
if (await shouldRegisterEnrollment(deps))
|
|
553
|
+
tools.push(stageEnrollmentTool(deps));
|
|
554
|
+
const server = createMcpServer({
|
|
555
|
+
name: 'owenloop-cli-mcp',
|
|
556
|
+
version: '0.0.1',
|
|
557
|
+
tools,
|
|
558
|
+
write: (msg) => io.out(JSON.stringify(msg)),
|
|
559
|
+
err: (line) => io.err(line),
|
|
560
|
+
});
|
|
561
|
+
return new Promise((resolve) => {
|
|
562
|
+
const stream = io.stdinStream ?? process.stdin;
|
|
563
|
+
pumpStdin(stream, server, () => resolve(0));
|
|
564
|
+
});
|
|
565
|
+
}
|