@vecteur/cli 0.9.1 → 0.11.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/src/mcp.js CHANGED
@@ -1,17 +1,65 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { dirname, join } from "node:path";
3
+
1
4
  import { McpServer } from "@modelcontextprotocol/server";
2
5
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
6
  import * as z from "zod/v4";
4
7
 
5
8
  import { CliError, VecteurClient, redact } from "./client.js";
6
- import { EVENT_KINDS, RETIRED_EVENT_KINDS, TERMINAL_STATES } from "./contract.js";
9
+ import { EVENT_KINDS, RETIRED_EVENT_KINDS, STORED_WIRE_VERSIONS, TERMINAL_STATES } from "./contract.js";
7
10
  import { canonicalJson } from "./format.js";
11
+ import { artifactToFolder, materialAttach } from "./exchange.js";
12
+ import { credentialsPath } from "./credentials.js";
13
+ import { readStore, withStoreLock, writeStore } from "./store.js";
8
14
 
9
15
  const projectInput = z.object({ project_id: z.string().min(1) }).strict();
16
+ // The composer's selection shape: one exact-extract selection per material source (the
17
+ // `selections` that vecteur_material_attach returns).
18
+ const selectionInput = z.object({
19
+ source_handle: z.object({ cas_ref: z.string().regex(/^sha256:[0-9a-f]{64}$/), acquisition_ref: z.string().min(1) }).strict(),
20
+ offer_id: z.string().min(1),
21
+ selected_extract_ids: z.array(z.string().min(1)).min(1),
22
+ method: z.literal("exact-extract"),
23
+ }).strict();
24
+ // v5 §2.5 explicit Produce: one named specialist child, started by the host before Engineering's turn. A38: Code Produce
25
+ // is off at the run door, so this tool does not offer it; the door's `produce_unavailable` words still name any entry kept off.
26
+ const produceInput = z.object({
27
+ specialist: z.enum(["business", "knowledge"]).describe("Business, or Knowledge documents (profile nasa or esa; a document needs a completed analysis in this Project first)"),
28
+ mode: z.string().min(1).max(64),
29
+ target: z.string().min(1).max(256).optional(),
30
+ profile: z.string().min(1).max(256).optional(),
31
+ standard: z.string().min(1).max(256).optional(),
32
+ }).strict();
10
33
  const submitInput = z.object({
11
34
  project_id: z.string().min(1),
12
35
  ask: z.string().min(1),
36
+ selections: z.array(selectionInput).min(1).optional(),
37
+ discard_pending_material: z.boolean().optional(),
38
+ produce: produceInput.optional(),
13
39
  }).strict();
14
40
  const runInput = z.object({ run_id: z.string().min(1) }).strict();
41
+ const startInput = z.object({
42
+ project_id: z.string().min(1), ask: z.string().min(1),
43
+ selections: z.array(selectionInput).min(1).optional(),
44
+ discard_pending_material: z.boolean().optional(),
45
+ request_key: z.string().regex(/^[A-Za-z0-9_-]{8,64}$/),
46
+ parent_state_hash: z.string().regex(/^[0-9a-f]{64}$/).nullable().optional(),
47
+ }).strict();
48
+ const ackFields = {
49
+ run_id: z.string().min(1), state_hash: z.string().min(1),
50
+ accepted_at: z.number().int().safe(), requested_route_id: z.string().min(1),
51
+ };
52
+ const ackOutput = z.object(ackFields).strict();
53
+ const startOutput = z.object({ ...ackFields, parent_state_hash: z.string().nullable() }).strict();
54
+ const answerInput = z.object({
55
+ run_id: z.string().min(1), clarification_id: z.string().min(1),
56
+ answers: z.array(z.object({ id: z.string().min(1), selected: z.array(z.string()),
57
+ custom: z.string().nullable().optional() }).strict()).min(1),
58
+ }).strict();
59
+ const statusOutput = z.object({
60
+ run_id: z.string().min(1), terminal: z.union([z.enum([...TERMINAL_STATES]), z.literal("")]),
61
+ last_seq: z.number().int().safe().min(-1), clarification: z.record(z.string(), z.json()).nullable(),
62
+ }).strict();
15
63
  const eventKind = z.enum([...EVENT_KINDS, ...RETIRED_EVENT_KINDS]);
16
64
  const eventOutput = z.object({
17
65
  run_id: z.string().min(1), seq: z.number().int().safe().nonnegative(),
@@ -55,7 +103,7 @@ const runControlOutput = z.object({
55
103
  const admittedOutput = z.object({
56
104
  run_id: z.string().min(1), state_hash: z.string().min(1), result_hash: z.string(),
57
105
  requested_route_id: z.string().min(1), profile: z.string().min(1),
58
- stored_wire_version: z.union([z.literal(1), z.literal(2)]),
106
+ stored_wire_version: z.union(STORED_WIRE_VERSIONS.map(version => z.literal(version))),
59
107
  terminal: z.union([z.enum([...TERMINAL_STATES]), z.literal("")]),
60
108
  duration_seconds: z.number().int().safe().nonnegative().nullable().optional(),
61
109
  usage: z.object({
@@ -69,6 +117,30 @@ const admittedOutput = z.object({
69
117
  ? value.result_hash === "" && value.events.at(-1)?.kind !== "terminal"
70
118
  : value.result_hash.length > 0, "Run terminal and result hash are not paired");
71
119
 
120
+ const artifactInput = z.object({
121
+ project_id: z.string().min(1),
122
+ cas_ref: z.string().regex(/^sha256:[0-9a-f]{64}$/).optional(),
123
+ run_id: z.string().min(1).optional(),
124
+ artifact_id: z.string().min(1).optional(),
125
+ output: z.string().min(1).optional(),
126
+ }).strict();
127
+ const artifactOutput = z.object({
128
+ path: z.string().min(1), bytes: z.number().int().safe().nonnegative(),
129
+ cas_ref: z.string().regex(/^sha256:[0-9a-f]{64}$/), content_type: z.string().min(1), verified: z.literal(true),
130
+ }).strict();
131
+ const materialInput = z.object({
132
+ project_id: z.string().min(1), path: z.string().min(1),
133
+ confirm_origin: z.string().min(1),
134
+ expected_state_hash: z.string().min(1).nullable(),
135
+ }).strict();
136
+ const materialOutput = z.object({
137
+ project_id: z.string().min(1), project_name: z.string().min(1), destination: z.string().min(1),
138
+ filename: z.string().min(1), bytes: z.number().int().safe().positive(),
139
+ cas_ref: z.string().min(1), acquisition_ref: z.string().min(1), offer_id: z.string().min(1),
140
+ extract_count: z.number().int().safe().nonnegative(),
141
+ selections: z.array(selectionInput).min(1),
142
+ }).strict();
143
+
72
144
  function success(value) {
73
145
  return {
74
146
  content: [{ type: "text", text: canonicalJson(value) }],
@@ -76,27 +148,62 @@ function success(value) {
76
148
  };
77
149
  }
78
150
 
79
- function failure(error) {
151
+ function failure(error, lifecycle = false) {
80
152
  const code = error instanceof CliError && /^[a-z][a-z0-9_]{0,63}$/.test(error.code)
81
153
  ? error.code : "internal_error";
154
+ // A38: the run door's product words naming the Produce entry it keeps off (validated by the client) ride along.
155
+ const message = code === "produce_unavailable" ? { message: error.message } : {};
156
+ const details = Object.fromEntries((lifecycle ? ["run_id", "request_key", "parent_state_hash", "pending"] : ["run_id", "pending"])
157
+ .filter(field => error instanceof CliError && Object.hasOwn(error, field))
158
+ .map(field => [field, typeof error[field] === "string" ? redact(error[field]) : error[field]]));
82
159
  return {
83
160
  isError: true,
84
- content: [{ type: "text", text: canonicalJson({ error: { code } }) }],
161
+ content: [{ type: "text", text: canonicalJson({ error: { code, ...message, ...details } }) }],
85
162
  };
86
163
  }
87
164
 
88
- function tool(server, name, description, inputSchema, outputSchema, call) {
165
+ function tool(server, name, description, inputSchema, outputSchema, call, lifecycle = false) {
89
166
  server.registerTool(name, { description, inputSchema, outputSchema }, async (input, context) => {
90
167
  try {
91
168
  return success(await call(input, context));
92
169
  } catch (error) {
93
- return failure(error);
170
+ return failure(error, lifecycle);
94
171
  }
95
172
  });
96
173
  }
97
174
 
98
175
  export function createVecteurMcpServer(client = new VecteurClient(), shutdownSignal = undefined) {
99
176
  const server = new McpServer({ name: "vecteur", version: "0.1.0" });
177
+ // Upload is not admission. Pending material lives in the private local store beside the login,
178
+ // so a restarted server still refuses a submit/start that omits it. It is kept until a submit/start
179
+ // succeeds, including after refusals, unless the caller deliberately discards this Project's material.
180
+ const origin = client.config.origin, file = join(dirname(credentialsPath()), "mcp-pending.json");
181
+ const pendingStore = () => {
182
+ const value = readStore(file) ?? { version: 1, pending: {} };
183
+ if (value.version !== 1 || !value.pending || typeof value.pending !== "object") throw new CliError("store_unreadable", `${file} is not a pending-material store; bytes preserved`);
184
+ return value;
185
+ };
186
+ const updatePending = change => withStoreLock(file, () => { const value = pendingStore(); change(value.pending); writeStore(file, value); });
187
+ // One entry per Project and bytes: re-attaching the same file replaces its handle (the recovery after a restart).
188
+ const materialKey = (projectId, casRef) => canonicalJson([origin, projectId, casRef]);
189
+ const withMaterial = async (projectId, selections, discardPendingMaterial, call) => {
190
+ const pending = Object.entries(pendingStore().pending).filter(([, value]) => value.origin === origin && value.projectId === projectId);
191
+ const selected = new Set((selections ?? []).map(value => canonicalJson([value.source_handle.cas_ref, value.source_handle.acquisition_ref])));
192
+ if (discardPendingMaterial) {
193
+ if (pending.length) updatePending(store => { for (const [key] of pending) delete store[key]; });
194
+ } else if (pending.some(([, value]) => !selected.has(canonicalJson([value.cas_ref, value.acquisition_ref])))) {
195
+ // Name what is pending: a session that lost the selections re-attaches that file rather than discarding blind.
196
+ throw Object.assign(new CliError("selection_required", "Pass the attached material's returned selections to submit or start"),
197
+ { pending: pending.map(([, value]) => value.cas_ref) });
198
+ }
199
+ const result = await call();
200
+ // The Run is admitted: a store failure now must not read as a refusal (a retry would admit a second Run).
201
+ // A leftover entry fails closed on the next call, where the caller can re-attach or discard.
202
+ if (!discardPendingMaterial && pending.length) try { updatePending(store => {
203
+ for (const [key, value] of pending) if (store[key]?.nonce === value.nonce) delete store[key];
204
+ }); } catch { /* fail closed: the entry stays pending */ }
205
+ return result;
206
+ };
100
207
  const signal = (context) => shutdownSignal
101
208
  ? AbortSignal.any([context.mcpReq.signal, shutdownSignal]) : context.mcpReq.signal;
102
209
 
@@ -104,8 +211,8 @@ export function createVecteurMcpServer(client = new VecteurClient(), shutdownSig
104
211
  ({ project_id: projectId }, context) => client.projectGet(projectId, signal(context)));
105
212
 
106
213
  tool(server, "vecteur_run_submit",
107
- "Submit one project turn that continues the Project's current head and return its terminal record.",
108
- submitInput, admittedOutput, async ({ project_id: projectId, ask }, context) => {
214
+ "Submit an ask and return its terminal record. Pass vecteur_material_attach's returned selections verbatim; omitting this Project's pending material refuses, also after a server restart (attach again for its selections). Set discard_pending_material=true to forget this Project's pending material and use only the supplied selections (or none). For long Runs use vecteur_run_start and poll vecteur_run_status.",
215
+ submitInput, admittedOutput, async ({ project_id: projectId, ask, selections, discard_pending_material, produce }, context) => {
109
216
  const progressToken = context.mcpReq._meta?.progressToken;
110
217
  const onEvent = progressToken === undefined ? null : (event) => context.mcpReq.notify({
111
218
  method: "notifications/progress",
@@ -115,7 +222,8 @@ export function createVecteurMcpServer(client = new VecteurClient(), shutdownSig
115
222
  message: event.kind,
116
223
  },
117
224
  });
118
- return client.runSubmit(projectId, ask, onEvent, signal(context));
225
+ return withMaterial(projectId, selections, discard_pending_material, () => client.runSubmit(projectId, ask, onEvent, signal(context), undefined, selections,
226
+ produce === undefined ? undefined : { kind: "produce", ...produce }));
119
227
  });
120
228
 
121
229
  tool(server, "vecteur_run_get", "Get one Vecteur run record, including an open run.", runInput, admittedOutput,
@@ -124,6 +232,32 @@ export function createVecteurMcpServer(client = new VecteurClient(), shutdownSig
124
232
  tool(server, "vecteur_run_events", "Validate run events against its direct record.", runInput,
125
233
  admittedOutput, ({ run_id: runId }, context) => client.runEvents(runId, null, signal(context)));
126
234
 
235
+ tool(server, "vecteur_run_start", "Admit without waiting. Pass attached material's returned selections verbatim; omitting this Project's pending material refuses, also after a server restart (attach again for its selections). Set discard_pending_material=true to forget this Project's pending material and use only the supplied selections (or none). Freeze request_key, ask and parent_state_hash (null for no head) for retries. Detaching never cancels.",
236
+ startInput, startOutput, ({ project_id, ask, request_key, parent_state_hash, selections, discard_pending_material }, context) =>
237
+ withMaterial(project_id, selections, discard_pending_material, () => client.runStart(project_id, ask, {
238
+ requestKey: request_key, parentStateHash: parent_state_hash, selections, signal: signal(context),
239
+ })), true);
240
+ tool(server, "vecteur_run_status", "Poll one bounded Run record; preserve its terminal and latest requested clarification verbatim.",
241
+ runInput, statusOutput, ({ run_id }, context) => client.runStatus(run_id, signal(context)), true);
242
+ tool(server, "vecteur_clarification_answer", "Answer the requested clarification with wire answers, including multi-select and custom text. Stale or duplicate answers refuse.",
243
+ answerInput, ackOutput, ({ run_id, clarification_id, answers }, context) =>
244
+ client.clarificationAnswer(run_id, clarification_id, answers, signal(context)), true);
245
+
246
+ const cwd = process.cwd();
247
+ tool(server, "vecteur_artifact_get",
248
+ "Download one run artifact into the server's working folder (never outside it), verified against its sha256 CAS id. Give cas_ref, or run_id with artifact_id. Never overwrites.",
249
+ artifactInput, artifactOutput, ({ project_id: projectId, cas_ref: casRef, run_id: runId, artifact_id: artifactId, output }, context) =>
250
+ artifactToFolder(client, { projectId, casRef, runId, artifactId, output, cwd, signal: signal(context) }));
251
+
252
+ tool(server, "vecteur_material_attach",
253
+ `Upload one local file to ${client.config.origin}. Pass the returned selections verbatim to vecteur_run_submit or vecteur_run_start for this Project; upload alone is not Run admission. Requires confirm_origin equal to that origin and expected_state_hash equal to the current head (null if none).`,
254
+ materialInput, materialOutput, async ({ project_id: projectId, path, confirm_origin: confirmOrigin, expected_state_hash: expectedStateHash }, context) => {
255
+ const result = await materialAttach(client, { projectId, path, confirmOrigin, expectedStateHash, cwd, signal: signal(context) });
256
+ updatePending(store => { for (const { source_handle: handle } of result.selections) store[materialKey(projectId, handle.cas_ref)] = {
257
+ origin, projectId, cas_ref: handle.cas_ref, acquisition_ref: handle.acquisition_ref, nonce: randomUUID() }; });
258
+ return result;
259
+ });
260
+
127
261
  return server;
128
262
  }
129
263
 
package/src/produce.js ADDED
@@ -0,0 +1,49 @@
1
+ /** v5 §2.5, CU-4 parity: the closed Produce entries, in the words of the cockpit's Produce panel (`ProducePanel.vue`; its spec
2
+ * holds this table to the panel). The same intent has one mode on every door. This is the grammar only: which entry is
3
+ * available is the run door's alone (A38, `backend/src/vecteur/contract/produce-availability.json`), and its refusal
4
+ * `produce_unavailable` names the entry. */
5
+ import { CliError } from "./client.js";
6
+
7
+ const documents = { field: "profile", choices: ["nasa", "esa"] };
8
+ const code = { field: "standard", choices: ["vecteur", "nasa", "user"] };
9
+ const standalone = target => ({ mode: "standalone", target, ...code });
10
+
11
+ export const PRODUCE_ENTRIES = {
12
+ business: { fleet_market_benchmark: { mode: "fleet_market_benchmark" } },
13
+ knowledge: {
14
+ mrd: { mode: "mrd", ...documents }, srd: { mode: "srd", ...documents }, dddj: { mode: "dddj", ...documents },
15
+ ard: { mode: "ard", ...documents }, ingest: { mode: "ingest" },
16
+ },
17
+ code: {
18
+ numpy_scipy: standalone("numpy_scipy"), orekit: standalone("orekit"), spice: standalone("spice"),
19
+ gmat: standalone("gmat"), basilisk: standalone("basilisk"), integrate: { mode: "integrate", ...code },
20
+ // The coding agent: no target and no standard; the host re-runs the tests it delivers.
21
+ standalone: { mode: "standalone" },
22
+ },
23
+ };
24
+
25
+ const USAGE = `Use /produce business <ask> or /produce knowledge <${Object.keys(PRODUCE_ENTRIES.knowledge).join("|")}> [profile=nasa|esa] <ask>; `
26
+ + "a knowledge document needs a completed analysis in this Project first";
27
+
28
+ /** `<specialist> [entry] [field=choice] <ask>` -> { ask, intent }. Business has one entry; the others name theirs. An absent
29
+ * choice is the panel's first option. Anything else sends nothing. */
30
+ export function produceIntent(argument) {
31
+ const match = /^(business|knowledge|code)\s+([\s\S]+)$/.exec(argument.trim());
32
+ if (!match) throw new CliError("usage_invalid", USAGE);
33
+ const specialist = match[1];
34
+ let rest = match[2].trim();
35
+ let name = "fleet_market_benchmark";
36
+ if (specialist !== "business") {
37
+ const head = /^(\S+)\s+([\s\S]+)$/.exec(rest);
38
+ if (!head || !Object.hasOwn(PRODUCE_ENTRIES[specialist], head[1])) throw new CliError("usage_invalid", USAGE);
39
+ [name, rest] = [head[1], head[2].trim()];
40
+ }
41
+ const { mode, target, field, choices } = PRODUCE_ENTRIES[specialist][name];
42
+ let chosen = choices?.[0];
43
+ const stated = field ? new RegExp(`^${field}=(\\S+)\\s+([\\s\\S]+)$`).exec(rest) : null;
44
+ if (stated) {
45
+ if (!choices.includes(stated[1])) throw new CliError("usage_invalid", USAGE);
46
+ [chosen, rest] = [stated[1], stated[2].trim()];
47
+ }
48
+ return { ask: rest, intent: { kind: "produce", specialist, mode, ...(target ? { target } : {}), ...(field ? { [field]: chosen } : {}) } };
49
+ }