@openshain/mcp 0.2.0 → 0.4.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/NOTICE +4 -0
- package/dist/server.js +492 -17
- package/dist/session.d.ts +3 -0
- package/dist/session.js +6 -0
- package/package.json +5 -4
- package/src/server.ts +572 -20
- package/src/session.ts +7 -0
package/NOTICE
ADDED
package/dist/server.js
CHANGED
|
@@ -1,21 +1,38 @@
|
|
|
1
|
+
import { relative } from "node:path";
|
|
1
2
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
2
3
|
import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
3
|
-
import { compileInputValidator, createToolCaller, createToolRegistry, isOpenshainError, isTerminal, loadConfig, parseWorkId, resolveWorkspacePath, SESSION_WORK_TYPE, uuidv7, verifyArtifact, WorkStore, } from "@openshain/core";
|
|
4
|
+
import { ASK_USER, compileInputValidator, countToolCalls, createToolCaller, createToolRegistry, DecisionFileSchema, isKnownEventType, isOpenshainError, isTerminal, loadAuthority, loadConfig, parsePayloadFile, parseWorkId, pendingApprovals, pendingQuestions, RUNTIME_PROVIDER_ID, resolveWorkspacePath, SESSION_WORK_TYPE, uuidv7, verifyArtifact, WorkStore, workHistory, writeDecision, } from "@openshain/core";
|
|
4
5
|
import pkg from "../package.json" with { type: "json" };
|
|
5
6
|
import { Session } from "./session.js";
|
|
6
7
|
/** The tools every session has, before the workspace's own. Their names are reserved in the runtime. */
|
|
7
8
|
const WORK_TOOLS = [
|
|
8
9
|
{
|
|
9
10
|
name: "work_create",
|
|
10
|
-
description:
|
|
11
|
+
description: 'Start a work for a request from the person you work for, and make it the current work. Tool calls are recorded against the current work. Finish the current work with work_complete or work_fail before starting another. The type "session" records a conversation: no tool can run inside it, so start the actual work with parent set to the session\'s id.',
|
|
11
12
|
inputSchema: {
|
|
12
13
|
type: "object",
|
|
13
14
|
properties: {
|
|
14
|
-
objective: {
|
|
15
|
+
objective: {
|
|
16
|
+
type: "string",
|
|
17
|
+
minLength: 1,
|
|
18
|
+
maxLength: 10_000,
|
|
19
|
+
description: "The request, in the person's words.",
|
|
20
|
+
},
|
|
15
21
|
type: {
|
|
16
22
|
type: "string",
|
|
23
|
+
maxLength: 50,
|
|
17
24
|
description: "A short label for the kind of work. Defaults to request.",
|
|
18
25
|
},
|
|
26
|
+
parent: {
|
|
27
|
+
type: "string",
|
|
28
|
+
maxLength: 100,
|
|
29
|
+
description: "The id of the work this one was started from, such as the session.",
|
|
30
|
+
},
|
|
31
|
+
agent_name: {
|
|
32
|
+
type: "string",
|
|
33
|
+
maxLength: 100,
|
|
34
|
+
description: "The name the agent goes by in this work. A session picks one; the works under it carry the same.",
|
|
35
|
+
},
|
|
19
36
|
},
|
|
20
37
|
required: ["objective"],
|
|
21
38
|
additionalProperties: false,
|
|
@@ -33,10 +50,10 @@ const WORK_TOOLS = [
|
|
|
33
50
|
},
|
|
34
51
|
{
|
|
35
52
|
name: "work_get",
|
|
36
|
-
description: "The state of the current work, or of the work with the given id.",
|
|
53
|
+
description: "The state of the current work, or of the work with the given id. With history, also the tool calls so far, the calls that never got a result, and the questions still waiting for an answer, so a stopped work can be picked up.",
|
|
37
54
|
inputSchema: {
|
|
38
55
|
type: "object",
|
|
39
|
-
properties: { id: { type: "string" } },
|
|
56
|
+
properties: { id: { type: "string" }, history: { type: "boolean" } },
|
|
40
57
|
additionalProperties: false,
|
|
41
58
|
},
|
|
42
59
|
},
|
|
@@ -51,12 +68,15 @@ const WORK_TOOLS = [
|
|
|
51
68
|
inputSchema: {
|
|
52
69
|
type: "object",
|
|
53
70
|
properties: {
|
|
54
|
-
summary: { type: "string" },
|
|
71
|
+
summary: { type: "string", maxLength: 20_000 },
|
|
55
72
|
artifacts: {
|
|
56
73
|
type: "array",
|
|
57
74
|
items: {
|
|
58
75
|
type: "object",
|
|
59
|
-
properties: {
|
|
76
|
+
properties: {
|
|
77
|
+
path: { type: "string", maxLength: 1000 },
|
|
78
|
+
sha256: { type: "string", maxLength: 64 },
|
|
79
|
+
},
|
|
60
80
|
required: ["path"],
|
|
61
81
|
additionalProperties: false,
|
|
62
82
|
},
|
|
@@ -71,12 +91,130 @@ const WORK_TOOLS = [
|
|
|
71
91
|
description: "Give up on the current work. Say why in a short reason and, if useful, a detail.",
|
|
72
92
|
inputSchema: {
|
|
73
93
|
type: "object",
|
|
74
|
-
properties: {
|
|
94
|
+
properties: {
|
|
95
|
+
reason: { type: "string", maxLength: 200 },
|
|
96
|
+
detail: { type: "string", maxLength: 20_000 },
|
|
97
|
+
},
|
|
75
98
|
required: ["reason"],
|
|
76
99
|
additionalProperties: false,
|
|
77
100
|
},
|
|
78
101
|
},
|
|
102
|
+
{
|
|
103
|
+
name: ASK_USER.name,
|
|
104
|
+
description: ASK_USER.description,
|
|
105
|
+
inputSchema: ASK_USER.inputSchema,
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
name: "work_answer",
|
|
109
|
+
description: "Record the person's answer to a question the current work is waiting on, and let the work continue.",
|
|
110
|
+
inputSchema: {
|
|
111
|
+
type: "object",
|
|
112
|
+
properties: {
|
|
113
|
+
call_id: { type: "string", maxLength: 100 },
|
|
114
|
+
answer: { type: "string", maxLength: 20_000 },
|
|
115
|
+
},
|
|
116
|
+
required: ["call_id", "answer"],
|
|
117
|
+
additionalProperties: false,
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
name: "context",
|
|
122
|
+
description: "Where and when you are working: the current time with its offset, the time zone, today's business date, the company folder, the company, the person you work for, and the current work. Call it when a date or a time matters; the answer is recorded.",
|
|
123
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
124
|
+
annotations: { readOnlyHint: true },
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
name: "approval_list",
|
|
128
|
+
description: "Every tool call held for a person's approval across the works of this workspace, oldest first: approval_id, work_id, the call, the rule, and who may approve.",
|
|
129
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
130
|
+
annotations: { readOnlyHint: true },
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
name: "approval_decide",
|
|
134
|
+
description: "Decide a held tool call as the person this connection acts for. approve runs the call now and returns its result; reject refuses it. Either way the work continues.",
|
|
135
|
+
inputSchema: {
|
|
136
|
+
type: "object",
|
|
137
|
+
properties: {
|
|
138
|
+
approval_id: { type: "string", maxLength: 100 },
|
|
139
|
+
decision: { type: "string", enum: ["approve", "reject"] },
|
|
140
|
+
comment: { type: "string", maxLength: 2000 },
|
|
141
|
+
},
|
|
142
|
+
required: ["approval_id", "decision"],
|
|
143
|
+
additionalProperties: false,
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
name: "review_decide",
|
|
148
|
+
description: "Record what a qualified reviewer decided about a call the policy held for review. approve and modify write a decision under authority/decisions/ and run the call (modify runs the reviewer's input); reject refuses it. The reviewer is named by the company; openshain does not verify a qualification.",
|
|
149
|
+
inputSchema: {
|
|
150
|
+
type: "object",
|
|
151
|
+
properties: {
|
|
152
|
+
approval_id: { type: "string", maxLength: 100 },
|
|
153
|
+
decision: { type: "string", enum: ["approve", "reject", "modify"] },
|
|
154
|
+
reviewer: {
|
|
155
|
+
type: "object",
|
|
156
|
+
properties: {
|
|
157
|
+
name: { type: "string", maxLength: 200 },
|
|
158
|
+
role: { type: "string", maxLength: 100 },
|
|
159
|
+
qualification: { type: "string", maxLength: 500 },
|
|
160
|
+
},
|
|
161
|
+
required: ["name", "role"],
|
|
162
|
+
additionalProperties: false,
|
|
163
|
+
},
|
|
164
|
+
interpretation: { type: "string", maxLength: 20_000 },
|
|
165
|
+
modified_input: { type: "object" },
|
|
166
|
+
effective_from: { type: "string", maxLength: 10 },
|
|
167
|
+
effective_until: { type: "string", maxLength: 10 },
|
|
168
|
+
applies_to: {
|
|
169
|
+
type: "object",
|
|
170
|
+
properties: {
|
|
171
|
+
action: { type: "string", maxLength: 200 },
|
|
172
|
+
path: { type: "string", maxLength: 1000 },
|
|
173
|
+
},
|
|
174
|
+
additionalProperties: false,
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
required: ["approval_id", "decision", "reviewer"],
|
|
178
|
+
additionalProperties: false,
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
name: "work_record",
|
|
183
|
+
description: "Record an event of the client itself on a work: what the person said (human.message), a prompt command expanded for the model (prompt.expanded), a model call (model.requested, model.completed, model.failed) or its usage (usage.recorded with kind model_inference). The payload is in the file form of spec/schemas/events.v1.json. Tool calls are recorded by the runtime and cannot be recorded here.",
|
|
184
|
+
inputSchema: {
|
|
185
|
+
type: "object",
|
|
186
|
+
properties: {
|
|
187
|
+
work_id: { type: "string" },
|
|
188
|
+
type: {
|
|
189
|
+
type: "string",
|
|
190
|
+
enum: [
|
|
191
|
+
"human.message",
|
|
192
|
+
"prompt.expanded",
|
|
193
|
+
"model.requested",
|
|
194
|
+
"model.completed",
|
|
195
|
+
"model.failed",
|
|
196
|
+
"usage.recorded",
|
|
197
|
+
],
|
|
198
|
+
},
|
|
199
|
+
payload: { type: "object" },
|
|
200
|
+
},
|
|
201
|
+
required: ["work_id", "type", "payload"],
|
|
202
|
+
additionalProperties: false,
|
|
203
|
+
},
|
|
204
|
+
},
|
|
79
205
|
];
|
|
206
|
+
/** A client event larger than this is refused: the log is for records, not for payloads. */
|
|
207
|
+
const MAX_RECORD_CHARS = 262_144;
|
|
208
|
+
/** The event types a client may record itself. Everything else is the runtime's to write. */
|
|
209
|
+
const RECORDABLE_TYPES = new Set([
|
|
210
|
+
"human.message",
|
|
211
|
+
"prompt.expanded",
|
|
212
|
+
"model.requested",
|
|
213
|
+
"model.completed",
|
|
214
|
+
"model.failed",
|
|
215
|
+
"usage.recorded",
|
|
216
|
+
]);
|
|
217
|
+
const SESSION_HAS_NO_TOOLS = "a session records the conversation and runs no tools: call work_create with parent set to the session's id, then call the tool inside that work";
|
|
80
218
|
const NO_WORK = "no current work: call work_create to start one for the person's request, or work_select to pick an existing one";
|
|
81
219
|
const validators = new Map(WORK_TOOLS.map((tool) => [tool.name, compileInputValidator(tool.inputSchema)]));
|
|
82
220
|
/**
|
|
@@ -88,7 +226,14 @@ export async function createMcpServer(options) {
|
|
|
88
226
|
const { workspaceRoot } = options;
|
|
89
227
|
const config = await loadConfig(workspaceRoot);
|
|
90
228
|
const registry = await createToolRegistry(workspaceRoot, config, options.tools);
|
|
91
|
-
|
|
229
|
+
// Reloaded when a reviewer writes a decision, so the next call can cite it.
|
|
230
|
+
let authority = await loadAuthority(workspaceRoot);
|
|
231
|
+
const callTool = createToolCaller({
|
|
232
|
+
registry,
|
|
233
|
+
config,
|
|
234
|
+
workspaceRoot,
|
|
235
|
+
authority: () => authority,
|
|
236
|
+
});
|
|
92
237
|
const works = new WorkStore(workspaceRoot);
|
|
93
238
|
const session = new Session();
|
|
94
239
|
const server = new Server({ name: "openshain", version: pkg.version }, { capabilities: { tools: {} } });
|
|
@@ -115,18 +260,26 @@ export async function createMcpServer(options) {
|
|
|
115
260
|
switch (name) {
|
|
116
261
|
case "work_create": {
|
|
117
262
|
const current = session.current;
|
|
118
|
-
if (current
|
|
119
|
-
|
|
263
|
+
if (current) {
|
|
264
|
+
const open = await works.get(current);
|
|
265
|
+
// A session is a conversation: starting a work under it is the normal thing to do.
|
|
266
|
+
if (!isTerminal(open.status) && open.type !== SESSION_WORK_TYPE) {
|
|
267
|
+
return failure(`work ${current} is still in progress; finish it with work_complete or work_fail before starting another`);
|
|
268
|
+
}
|
|
120
269
|
}
|
|
121
|
-
const { objective, type } = input;
|
|
122
|
-
if (
|
|
123
|
-
|
|
270
|
+
const { objective, type, parent, agent_name: agentName, } = input;
|
|
271
|
+
if (parent !== undefined)
|
|
272
|
+
await works.get(parseWorkId(parent));
|
|
273
|
+
if (type === SESSION_WORK_TYPE && parent !== undefined) {
|
|
274
|
+
return failure("a session is a conversation of its own and cannot have a parent");
|
|
124
275
|
}
|
|
125
276
|
const work = await works.create({
|
|
126
277
|
objective,
|
|
127
278
|
principal: config.principal.id,
|
|
128
279
|
profession: config.profession.id,
|
|
129
280
|
...(type && { type }),
|
|
281
|
+
...(parent !== undefined && { parent }),
|
|
282
|
+
...(agentName !== undefined && { agentName }),
|
|
130
283
|
});
|
|
131
284
|
await works.transition(work.id, "in_progress", "an agent took the work over MCP");
|
|
132
285
|
session.select(work.id);
|
|
@@ -138,14 +291,292 @@ export async function createMcpServer(options) {
|
|
|
138
291
|
if (isTerminal(work.status))
|
|
139
292
|
return failure(`work ${id} is already ${work.status}`);
|
|
140
293
|
session.select(id);
|
|
141
|
-
return json(work);
|
|
294
|
+
return json({ ...work, history: workHistory(await works.events(id)) });
|
|
142
295
|
}
|
|
143
296
|
case "work_get": {
|
|
144
|
-
const given = input
|
|
297
|
+
const { id: given, history } = input;
|
|
145
298
|
const id = given ? parseWorkId(given) : session.current;
|
|
146
299
|
if (!id)
|
|
147
300
|
return failure(NO_WORK);
|
|
148
|
-
|
|
301
|
+
const work = await works.get(id);
|
|
302
|
+
if (!history)
|
|
303
|
+
return json(work);
|
|
304
|
+
return json({ ...work, history: workHistory(await works.events(id)) });
|
|
305
|
+
}
|
|
306
|
+
case ASK_USER.name: {
|
|
307
|
+
const gate = await openWork();
|
|
308
|
+
if ("refused" in gate)
|
|
309
|
+
return gate.refused;
|
|
310
|
+
const work = await works.get(gate.id);
|
|
311
|
+
if (work.type === SESSION_WORK_TYPE)
|
|
312
|
+
return failure(SESSION_HAS_NO_TOOLS);
|
|
313
|
+
if (work.status === "waiting_input") {
|
|
314
|
+
return failure(`work ${gate.id} is already waiting for an answer; record it with work_answer before asking again`);
|
|
315
|
+
}
|
|
316
|
+
const { question } = input;
|
|
317
|
+
const callId = newCallId();
|
|
318
|
+
const opened = await works.open(gate.id);
|
|
319
|
+
try {
|
|
320
|
+
await opened.append({
|
|
321
|
+
type: "tool.called",
|
|
322
|
+
payload: { callId, provider: RUNTIME_PROVIDER_ID, name: ASK_USER.name, input },
|
|
323
|
+
});
|
|
324
|
+
await opened.append({ type: "human.input_requested", payload: { callId, question } });
|
|
325
|
+
await opened.transition("waiting_input", "the agent asked the person a question");
|
|
326
|
+
}
|
|
327
|
+
finally {
|
|
328
|
+
await opened.close();
|
|
329
|
+
}
|
|
330
|
+
return json({ pending: true, call_id: callId, question });
|
|
331
|
+
}
|
|
332
|
+
case "work_answer": {
|
|
333
|
+
const gate = await openWork();
|
|
334
|
+
if ("refused" in gate)
|
|
335
|
+
return gate.refused;
|
|
336
|
+
const { call_id: callId, answer } = input;
|
|
337
|
+
const work = await works.get(gate.id);
|
|
338
|
+
if (work.status !== "waiting_input") {
|
|
339
|
+
return failure(`work ${gate.id} is ${work.status}, not waiting for an answer`);
|
|
340
|
+
}
|
|
341
|
+
const pending = pendingQuestions(await works.events(gate.id));
|
|
342
|
+
if (!pending.some((q) => q.callId === callId)) {
|
|
343
|
+
return failure(`no unanswered question with call_id ${callId}; pending: ${pending.map((q) => q.callId).join(", ") || "none"}`);
|
|
344
|
+
}
|
|
345
|
+
const opened = await works.open(gate.id);
|
|
346
|
+
try {
|
|
347
|
+
await opened.append({ type: "human.input_provided", payload: { callId, answer } });
|
|
348
|
+
await opened.append({
|
|
349
|
+
type: "tool.completed",
|
|
350
|
+
payload: { callId, content: [{ type: "text", text: answer }], isError: false },
|
|
351
|
+
});
|
|
352
|
+
await opened.transition("in_progress", "the person answered");
|
|
353
|
+
return json(await opened.current());
|
|
354
|
+
}
|
|
355
|
+
finally {
|
|
356
|
+
await opened.close();
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
case "work_record": {
|
|
360
|
+
const { work_id, type, payload } = input;
|
|
361
|
+
const id = parseWorkId(work_id);
|
|
362
|
+
if (!RECORDABLE_TYPES.has(type) || !isKnownEventType(type)) {
|
|
363
|
+
return failure(`type ${type} cannot be recorded by a client`);
|
|
364
|
+
}
|
|
365
|
+
if (JSON.stringify(payload).length > MAX_RECORD_CHARS) {
|
|
366
|
+
return failure(`payload is larger than ${MAX_RECORD_CHARS} characters`);
|
|
367
|
+
}
|
|
368
|
+
if (!session.knows(id)) {
|
|
369
|
+
return failure(`work ${id} was not created or selected on this connection; a client records only on its own works`);
|
|
370
|
+
}
|
|
371
|
+
const parsed = parsePayloadFile(type, payload);
|
|
372
|
+
if (type === "usage.recorded" && parsed.kind !== "model_inference") {
|
|
373
|
+
return failure("usage.recorded from a client must have kind model_inference");
|
|
374
|
+
}
|
|
375
|
+
const opened = await works.open(id);
|
|
376
|
+
try {
|
|
377
|
+
const status = (await opened.current()).status;
|
|
378
|
+
if (isTerminal(status))
|
|
379
|
+
return failure(`work ${id} is already ${status}`);
|
|
380
|
+
const event = await opened.append({ type, payload: parsed });
|
|
381
|
+
return json({ id: event.id, seq: event.seq });
|
|
382
|
+
}
|
|
383
|
+
finally {
|
|
384
|
+
await opened.close();
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
case "context": {
|
|
388
|
+
const now = new Date();
|
|
389
|
+
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
390
|
+
const info = {
|
|
391
|
+
now: localIso(now),
|
|
392
|
+
timezone,
|
|
393
|
+
business_date: localIso(now).slice(0, 10),
|
|
394
|
+
workspace: workspaceRoot,
|
|
395
|
+
company: config.company.name,
|
|
396
|
+
principal: { id: config.principal.id, name: config.principal.name },
|
|
397
|
+
profession: config.profession.id,
|
|
398
|
+
work: session.current ?? null,
|
|
399
|
+
};
|
|
400
|
+
const result = json(info);
|
|
401
|
+
// Recorded on the current work when there is one, even a session: it touches no file.
|
|
402
|
+
const current = session.current;
|
|
403
|
+
if (current && !isTerminal((await works.get(current)).status)) {
|
|
404
|
+
const callId = newCallId();
|
|
405
|
+
const opened = await works.open(current);
|
|
406
|
+
try {
|
|
407
|
+
await opened.append({
|
|
408
|
+
type: "tool.called",
|
|
409
|
+
payload: { callId, provider: RUNTIME_PROVIDER_ID, name: "context", input: {} },
|
|
410
|
+
});
|
|
411
|
+
await opened.append({
|
|
412
|
+
type: "tool.completed",
|
|
413
|
+
payload: { callId, content: [{ type: "json", value: info }], isError: false },
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
finally {
|
|
417
|
+
await opened.close();
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return result;
|
|
421
|
+
}
|
|
422
|
+
case "approval_list": {
|
|
423
|
+
const held = [];
|
|
424
|
+
const { works: all } = await works.list();
|
|
425
|
+
for (const w of all) {
|
|
426
|
+
if (w.status !== "waiting_approval")
|
|
427
|
+
continue;
|
|
428
|
+
for (const a of pendingApprovals(await works.events(w.id))) {
|
|
429
|
+
held.push({ ...a, work_id: w.id, objective: w.objective });
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return json({ approvals: held });
|
|
433
|
+
}
|
|
434
|
+
case "approval_decide": {
|
|
435
|
+
const { approval_id: approvalId, decision, comment, } = input;
|
|
436
|
+
const found = await findApproval(works, approvalId);
|
|
437
|
+
if (!found)
|
|
438
|
+
return failure(`no pending approval ${approvalId}`);
|
|
439
|
+
const { workId, approval } = found;
|
|
440
|
+
const by = config.principal.id;
|
|
441
|
+
if (approval.kind === "review") {
|
|
442
|
+
return failure(`${approvalId} waits for a qualified reviewer, not a person's approval; use review_decide`);
|
|
443
|
+
}
|
|
444
|
+
if (approval.approvers && !approval.approvers.includes(by)) {
|
|
445
|
+
return failure(`${by} may not decide ${approvalId}; approvers: ${approval.approvers.join(", ")}`);
|
|
446
|
+
}
|
|
447
|
+
const opened = await works.open(workId);
|
|
448
|
+
try {
|
|
449
|
+
// Under the lock: another connection may have decided this approval in between.
|
|
450
|
+
if (!pendingApprovals(await opened.events()).some((a) => a.approvalId === approvalId)) {
|
|
451
|
+
return failure(`approval ${approvalId} was already decided`);
|
|
452
|
+
}
|
|
453
|
+
await opened.append({
|
|
454
|
+
type: "approval.decided",
|
|
455
|
+
payload: { approvalId, decision, by, ...(comment !== undefined && { comment }) },
|
|
456
|
+
});
|
|
457
|
+
if (decision === "reject") {
|
|
458
|
+
await opened.append({
|
|
459
|
+
type: "tool.rejected",
|
|
460
|
+
payload: {
|
|
461
|
+
callId: approval.call.callId,
|
|
462
|
+
name: approval.call.name,
|
|
463
|
+
code: "rejected_by_person",
|
|
464
|
+
reason: comment ?? `${by} rejected ${approvalId}`,
|
|
465
|
+
},
|
|
466
|
+
});
|
|
467
|
+
await opened.transition("in_progress", `${by} rejected ${approvalId}`);
|
|
468
|
+
return json({ approval_id: approvalId, decision, work_id: workId });
|
|
469
|
+
}
|
|
470
|
+
await opened.transition("in_progress", `${by} approved ${approvalId}`);
|
|
471
|
+
const result = await callTool(opened, { id: approval.call.callId, name: approval.call.name, input: approval.call.input }, { approvedBy: approvalId });
|
|
472
|
+
return json({
|
|
473
|
+
approval_id: approvalId,
|
|
474
|
+
decision,
|
|
475
|
+
work_id: workId,
|
|
476
|
+
result: { content: result.content, isError: result.isError ?? false },
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
finally {
|
|
480
|
+
await opened.close();
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
case "review_decide": {
|
|
484
|
+
const { approval_id: approvalId, decision, reviewer, interpretation, modified_input: modifiedInput, effective_from: effectiveFrom, effective_until: effectiveUntil, applies_to: appliesTo, } = input;
|
|
485
|
+
const found = await findApproval(works, approvalId);
|
|
486
|
+
if (!found)
|
|
487
|
+
return failure(`no pending approval ${approvalId}`);
|
|
488
|
+
const { workId, approval } = found;
|
|
489
|
+
if (approval.kind !== "review") {
|
|
490
|
+
return failure(`${approvalId} waits for a person's approval, not a review; use approval_decide`);
|
|
491
|
+
}
|
|
492
|
+
if (decision !== "reject" && (interpretation ?? "") === "") {
|
|
493
|
+
return failure("a decision needs the reviewer's interpretation in their own words");
|
|
494
|
+
}
|
|
495
|
+
if (approval.reviewer && approval.reviewer.role !== reviewer.role) {
|
|
496
|
+
return failure(`rule ${approval.ruleId} asks for a ${approval.reviewer.role}; the decision names a ${reviewer.role}`);
|
|
497
|
+
}
|
|
498
|
+
if (decision === "modify" && modifiedInput) {
|
|
499
|
+
// Checked before anything is recorded: a refused input leaves the approval pending.
|
|
500
|
+
const before = (approval.call.input ?? {});
|
|
501
|
+
const after = modifiedInput;
|
|
502
|
+
if (before.path !== after.path) {
|
|
503
|
+
return failure(`a modified call must touch the same path: ${String(before.path)} was held, ${String(after.path)} was given`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
// Built and checked before anything is recorded: an input the decision refuses must not
|
|
507
|
+
// consume the approval and leave the work waiting with nobody able to move it.
|
|
508
|
+
const today = new Date();
|
|
509
|
+
let record;
|
|
510
|
+
if (decision !== "reject") {
|
|
511
|
+
const parsed = DecisionFileSchema.safeParse({
|
|
512
|
+
id: `dec_${uuidv7()}`,
|
|
513
|
+
reviewer,
|
|
514
|
+
approval_id: approvalId,
|
|
515
|
+
decided_at: today.toISOString(),
|
|
516
|
+
effective_from: effectiveFrom ?? today.toISOString().slice(0, 10),
|
|
517
|
+
effective_until: effectiveUntil ?? null,
|
|
518
|
+
interpretation,
|
|
519
|
+
applies_to: appliesTo ?? {},
|
|
520
|
+
});
|
|
521
|
+
if (!parsed.success) {
|
|
522
|
+
return failure(`the decision is not well formed: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
|
|
523
|
+
}
|
|
524
|
+
record = parsed.data;
|
|
525
|
+
}
|
|
526
|
+
const opened = await works.open(workId);
|
|
527
|
+
try {
|
|
528
|
+
// Under the lock: another connection may have decided this approval in between.
|
|
529
|
+
if (!pendingApprovals(await opened.events()).some((a) => a.approvalId === approvalId)) {
|
|
530
|
+
return failure(`approval ${approvalId} was already decided`);
|
|
531
|
+
}
|
|
532
|
+
await opened.append({
|
|
533
|
+
type: "approval.decided",
|
|
534
|
+
payload: {
|
|
535
|
+
approvalId,
|
|
536
|
+
decision,
|
|
537
|
+
by: reviewer.name,
|
|
538
|
+
...(interpretation !== undefined && { comment: interpretation }),
|
|
539
|
+
...(decision === "modify" && modifiedInput && { modifiedInput }),
|
|
540
|
+
},
|
|
541
|
+
});
|
|
542
|
+
if (decision === "reject") {
|
|
543
|
+
await opened.append({ type: "review.decided", payload: { approvalId } });
|
|
544
|
+
await opened.append({
|
|
545
|
+
type: "tool.rejected",
|
|
546
|
+
payload: {
|
|
547
|
+
callId: approval.call.callId,
|
|
548
|
+
name: approval.call.name,
|
|
549
|
+
code: "rejected_by_person",
|
|
550
|
+
reason: interpretation ?? `${reviewer.name} did not approve ${approvalId}`,
|
|
551
|
+
},
|
|
552
|
+
});
|
|
553
|
+
await opened.transition("in_progress", `${reviewer.name} rejected ${approvalId}`);
|
|
554
|
+
return json({ approval_id: approvalId, decision, work_id: workId });
|
|
555
|
+
}
|
|
556
|
+
const written = record;
|
|
557
|
+
const file = await writeDecision(workspaceRoot, written);
|
|
558
|
+
await opened.append({
|
|
559
|
+
type: "review.decided",
|
|
560
|
+
payload: { approvalId, decisionId: written.id },
|
|
561
|
+
});
|
|
562
|
+
await opened.transition("in_progress", `${reviewer.name} decided ${approvalId}`);
|
|
563
|
+
const ranWith = decision === "modify" && modifiedInput ? modifiedInput : approval.call.input;
|
|
564
|
+
const ran = await callTool(opened, { id: approval.call.callId, name: approval.call.name, input: ranWith }, { approvedBy: approvalId });
|
|
565
|
+
// The decision is on disk; a rule that cites its id can use it from here on. Reloaded
|
|
566
|
+
// so that a rule already written for it takes effect without a restart.
|
|
567
|
+
authority = await loadAuthority(workspaceRoot);
|
|
568
|
+
return json({
|
|
569
|
+
approval_id: approvalId,
|
|
570
|
+
decision,
|
|
571
|
+
work_id: workId,
|
|
572
|
+
decision_id: written.id,
|
|
573
|
+
decision_file: relative(workspaceRoot, file),
|
|
574
|
+
result: { content: ran.content, isError: ran.isError ?? false },
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
finally {
|
|
578
|
+
await opened.close();
|
|
579
|
+
}
|
|
149
580
|
}
|
|
150
581
|
case "work_list": {
|
|
151
582
|
const { works: all, problems } = await works.list();
|
|
@@ -153,8 +584,11 @@ export async function createMcpServer(options) {
|
|
|
153
584
|
works: all.map((w) => ({
|
|
154
585
|
id: w.id,
|
|
155
586
|
status: w.status,
|
|
587
|
+
type: w.type,
|
|
156
588
|
objective: w.objective,
|
|
157
589
|
createdAt: w.createdAt,
|
|
590
|
+
...(w.parent !== undefined && { parent: w.parent }),
|
|
591
|
+
...(w.agentName !== undefined && { agentName: w.agentName }),
|
|
158
592
|
})),
|
|
159
593
|
problems: problems.map((p) => ({
|
|
160
594
|
id: p.id,
|
|
@@ -191,8 +625,26 @@ export async function createMcpServer(options) {
|
|
|
191
625
|
const gate = await openWork();
|
|
192
626
|
if ("refused" in gate)
|
|
193
627
|
return gate.refused;
|
|
628
|
+
const work = await works.get(gate.id);
|
|
629
|
+
if (work.type === SESSION_WORK_TYPE)
|
|
630
|
+
return failure(SESSION_HAS_NO_TOOLS);
|
|
631
|
+
if (work.status === "waiting_input") {
|
|
632
|
+
return failure(`work ${gate.id} is waiting for the person's answer; record it with work_answer before calling tools`);
|
|
633
|
+
}
|
|
634
|
+
if (work.status === "waiting_approval") {
|
|
635
|
+
return failure(`work ${gate.id} is waiting for an approval; decide it with approval_decide (see approval_list) before calling tools`);
|
|
636
|
+
}
|
|
194
637
|
const opened = await works.open(gate.id);
|
|
195
638
|
try {
|
|
639
|
+
const limit = config.limits.maxToolCalls;
|
|
640
|
+
if (countToolCalls(await opened.events()) >= limit) {
|
|
641
|
+
const reason = `this work has reached its limit of ${limit} tool calls; finish it with work_complete or work_fail`;
|
|
642
|
+
await opened.append({
|
|
643
|
+
type: "tool.rejected",
|
|
644
|
+
payload: { callId: newCallId(), name, code: "limit_reached", reason },
|
|
645
|
+
});
|
|
646
|
+
return failure(`limit_reached: ${reason}`);
|
|
647
|
+
}
|
|
196
648
|
const result = await callTool(opened, { id: newCallId(), name, input });
|
|
197
649
|
return toMcpResult(result);
|
|
198
650
|
}
|
|
@@ -265,6 +717,7 @@ function toMcpTool(definition) {
|
|
|
265
717
|
name: definition.name,
|
|
266
718
|
description: definition.description,
|
|
267
719
|
inputSchema: definition.inputSchema,
|
|
720
|
+
annotations: { readOnlyHint: definition.effect === "observe" },
|
|
268
721
|
};
|
|
269
722
|
}
|
|
270
723
|
function toMcpResult(result) {
|
|
@@ -284,3 +737,25 @@ function failure(text) {
|
|
|
284
737
|
function newCallId() {
|
|
285
738
|
return `call_${uuidv7()}`;
|
|
286
739
|
}
|
|
740
|
+
/** The work holding a pending approval, found by scanning the works that wait for one. */
|
|
741
|
+
async function findApproval(works, approvalId) {
|
|
742
|
+
const { works: all } = await works.list();
|
|
743
|
+
for (const w of all) {
|
|
744
|
+
if (w.status !== "waiting_approval")
|
|
745
|
+
continue;
|
|
746
|
+
const approval = pendingApprovals(await works.events(w.id)).find((a) => a.approvalId === approvalId);
|
|
747
|
+
if (approval)
|
|
748
|
+
return { workId: w.id, approval };
|
|
749
|
+
}
|
|
750
|
+
return undefined;
|
|
751
|
+
}
|
|
752
|
+
/** ISO 8601 with the local offset instead of Z, so the time reads as the person's clock. */
|
|
753
|
+
function localIso(date) {
|
|
754
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
755
|
+
const offset = -date.getTimezoneOffset();
|
|
756
|
+
const sign = offset >= 0 ? "+" : "-";
|
|
757
|
+
const abs = Math.abs(offset);
|
|
758
|
+
return (`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` +
|
|
759
|
+
`T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` +
|
|
760
|
+
`${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`);
|
|
761
|
+
}
|
package/dist/session.d.ts
CHANGED
|
@@ -2,9 +2,12 @@ import type { WorkId } from "@openshain/core";
|
|
|
2
2
|
/** What one connection remembers: the work the agent is on, and the order of its calls. */
|
|
3
3
|
export declare class Session {
|
|
4
4
|
private currentId;
|
|
5
|
+
private readonly known;
|
|
5
6
|
private queue;
|
|
6
7
|
get current(): WorkId | undefined;
|
|
7
8
|
select(id: WorkId): void;
|
|
9
|
+
/** Whether this connection created or selected the work, so it may record its own events on it. */
|
|
10
|
+
knows(id: WorkId): boolean;
|
|
8
11
|
clear(): void;
|
|
9
12
|
/** Runs one call after the previous one finished, so calls the agent makes in parallel do not fight over the work's lock. */
|
|
10
13
|
run<T>(fn: () => Promise<T>): Promise<T>;
|
package/dist/session.js
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
/** What one connection remembers: the work the agent is on, and the order of its calls. */
|
|
2
2
|
export class Session {
|
|
3
3
|
currentId;
|
|
4
|
+
known = new Set();
|
|
4
5
|
queue = Promise.resolve();
|
|
5
6
|
get current() {
|
|
6
7
|
return this.currentId;
|
|
7
8
|
}
|
|
8
9
|
select(id) {
|
|
9
10
|
this.currentId = id;
|
|
11
|
+
this.known.add(id);
|
|
12
|
+
}
|
|
13
|
+
/** Whether this connection created or selected the work, so it may record its own events on it. */
|
|
14
|
+
knows(id) {
|
|
15
|
+
return this.known.has(id);
|
|
10
16
|
}
|
|
11
17
|
clear() {
|
|
12
18
|
this.currentId = undefined;
|