@workpowers/speckle 0.8.1 → 0.9.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/README.md CHANGED
@@ -54,6 +54,32 @@ and it cannot tell the server anything about your checkout — so freshness stay
54
54
  `unknown` no matter what is installed on disk. `speckle-mcp doctor` prints which
55
55
  directory it searched.
56
56
 
57
+ ### Cloud sessions (Claude Code on the web)
58
+
59
+ A cloud session starts in a fresh container that has no user-scope
60
+ registration, and it loads MCP servers **before** any SessionStart hook runs, so
61
+ a hook that writes `.mcp.json` comes too late. Register the router from the
62
+ cloud environment's **Setup script** instead (claude.ai → Settings →
63
+ Environments), which runs before Claude Code launches:
64
+
65
+ ```bash
66
+ #!/bin/bash
67
+ # Speckle MCP for cloud sessions. Claude Code loads MCP servers before SessionStart hooks run, so the repo hook comes too late; this runs before launch.
68
+ root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
69
+ printf '%s\n' '{"generated-by":"session-start-hook","mcpServers":{"speckle":{"command":"npx","args":["-y","@workpowers/speckle"],"env":{"SPECKLE_MCP_BASE_URL":"https://speckle.workpowers.ai","SPECKLE_MCP_KEY":"${SPECKLE_MCP_KEY}"}}}}' > "$root/.mcp.json"
70
+ ```
71
+
72
+ The same environment needs:
73
+
74
+ - the environment variable `SPECKLE_MCP_KEY=lsk_...` (from `/account#mcp`);
75
+ - network access to `speckle.workpowers.ai` (package registries stay allowed, so
76
+ `npx` can fetch the router).
77
+
78
+ The key is written into `.mcp.json` as the literal `${SPECKLE_MCP_KEY}`, which
79
+ Claude Code expands when it reads the file, so the key itself never reaches
80
+ disk. The file is gitignored; the `generated-by` marker is kept from the retired
81
+ SessionStart hook so the file is recognisably machine-written.
82
+
57
83
  ## Point a repo at a project
58
84
 
59
85
  Commit a `.speckle` marker at the repo root:
@@ -103,8 +129,8 @@ restart the router after updating the router package itself.
103
129
 
104
130
  The bootstrap above says "ask Speckle". The `instructions` command adds what
105
131
  THIS project's spec says, for the coding tools that read `AGENTS.md` and never
106
- call MCP: the project's charter and its Knowledge index (one line per
107
- perspective, rows as `S-code · name · summary`, pinned rows always present),
132
+ call MCP: the project's charter and its Knowledge index (a table of contents
133
+ over every perspective with its P-code, rows and rules; no rows, never cut),
108
134
  generated from confirmed main with no model and fenced between two markers.
109
135
 
110
136
  ```sh
@@ -128,6 +154,47 @@ charter live with `speckle_get_workflow` and the index with
128
154
  `get_standards_brief` — and Speckle's own repositories do not commit it
129
155
  (I-7085). Use it for tools that cannot call Speckle.
130
156
 
157
+ ## Upload recordings
158
+
159
+ `upload` sends video and audio recordings to a project from the command line,
160
+ so a multi-hour recording does not need a browser tab left open:
161
+
162
+ ```sh
163
+ npx -y @workpowers/speckle upload "2025-07-23 14-08-54.mkv"
164
+ npx -y @workpowers/speckle upload --project 5 --card I-42 talk.mp4 interview.m4a
165
+ ```
166
+
167
+ Accepted files: mp4, mov, mkv, webm, m4v, avi, mp3, m4a, aac, wav, flac, ogg,
168
+ opus. Files go one after another; each is hashed, then sent in parts, four at
169
+ a time. The recording date comes from an OBS-style name
170
+ (`YYYY-MM-DD HH-MM-SS`, read as this machine's local time), otherwise from the
171
+ file's modification time. A file that changes while it is being hashed or sent
172
+ is refused rather than uploaded half-written.
173
+
174
+ Re-running is safe. Speckle knows a file by its SHA-256: one it already has is
175
+ reported as already uploaded and nothing is sent, and an interrupted upload of
176
+ the same file picks up from the parts that already landed.
177
+
178
+ | Flag | Meaning |
179
+ |---|---|
180
+ | `--project <id>` | Project to upload to. Default: the `.speckle` marker's project, then `SPECKLE_PROJECT_ID`. Works outside any repo. |
181
+ | `--card <ref>` | Attach the recordings to a card, such as `I-42`. |
182
+ | `--dry-run` | Hash each file and say whether Speckle has it, has part of it, or not. Sends nothing. |
183
+ | `--json` | One JSON object per file on stdout (`file`, `status`, `document_id`, `sha256`, `recorded_at`, `error`), nothing else. |
184
+
185
+ Progress goes to stderr; results go to stdout. Exit codes: `0` every file is
186
+ uploaded or was already there, `1` at least one file failed, `2` a usage or
187
+ configuration problem (an unknown flag, no key, no project).
188
+
189
+ It needs `SPECKLE_MCP_BASE_URL` and `SPECKLE_MCP_KEY`. Those usually live in
190
+ your MCP client's config, which a shell or a watcher script does not see, so
191
+ export them there. From a folder watcher, call it once per new file:
192
+
193
+ ```sh
194
+ export SPECKLE_MCP_BASE_URL=https://speckle.workpowers.ai SPECKLE_MCP_KEY=lsk_...
195
+ npx -y @workpowers/speckle upload --project 5 --json "$NEW_FILE" >> uploads.log
196
+ ```
197
+
131
198
  ## Diagnosing
132
199
 
133
200
  ```bash
@@ -11,7 +11,8 @@ const args = process.argv.slice(2);
11
11
  const sub = args[0];
12
12
 
13
13
  const isCliSubcommand =
14
- sub === "init" || sub === "doctor" || sub === "workflow" || sub === "help" || sub === "--help" || sub === "-h";
14
+ sub === "init" || sub === "doctor" || sub === "workflow" || sub === "instructions" || sub === "upload" ||
15
+ sub === "help" || sub === "--help" || sub === "-h";
15
16
 
16
17
  if (isCliSubcommand) {
17
18
  runCli(args).catch((err) => {
package/dist/cli.d.ts CHANGED
@@ -8,6 +8,10 @@
8
8
  * Fetches the project's spec-derived agent instructions and previews or
9
9
  * writes them as the managed section of AGENTS.md (I-4367).
10
10
  *
11
+ * speckle mcp upload [--project <id>] [--card <ref>] [--dry-run] [--json] <file...>
12
+ * Uploads recordings (video or audio) to the project, resumably; safe to
13
+ * re-run on the same file. Exits 0 / 1 (a file failed) / 2 (usage).
14
+ *
11
15
  * speckle mcp doctor
12
16
  * Resolves marker + workspace + env and prints a diagnostic
13
17
  * summary. Never sends a network request — diagnoses local config
package/dist/cli.js CHANGED
@@ -8,6 +8,10 @@
8
8
  * Fetches the project's spec-derived agent instructions and previews or
9
9
  * writes them as the managed section of AGENTS.md (I-4367).
10
10
  *
11
+ * speckle mcp upload [--project <id>] [--card <ref>] [--dry-run] [--json] <file...>
12
+ * Uploads recordings (video or audio) to the project, resumably; safe to
13
+ * re-run on the same file. Exits 0 / 1 (a file failed) / 2 (usage).
14
+ *
11
15
  * speckle mcp doctor
12
16
  * Resolves marker + workspace + env and prints a diagnostic
13
17
  * summary. Never sends a network request — diagnoses local config
@@ -29,6 +33,13 @@ export async function runCli(args) {
29
33
  return runWorkflowCommand(rest);
30
34
  case "instructions":
31
35
  return runInstructionsCommand(rest);
36
+ case "upload": {
37
+ // Loaded here, never at the top: the router's start path imports this
38
+ // module and must not pull in the upload code.
39
+ const { runUploadCommand } = await import("./upload-command.js");
40
+ process.exitCode = await runUploadCommand(rest);
41
+ return;
42
+ }
32
43
  case "init":
33
44
  return runInit(rest);
34
45
  case "doctor":
@@ -154,6 +165,11 @@ function printHelp() {
154
165
  " --url <speckle_url> Optional Speckle host URL when not using the default.",
155
166
  " --force Overwrite an existing .speckle file.",
156
167
  " speckle-mcp doctor Diagnose local config and marker state (no network).",
168
+ " speckle-mcp upload <file...> Upload recordings (video/audio); safe to re-run on the same file.",
169
+ " --project <id> Project to upload to (default: the .speckle marker's).",
170
+ " --card <ref> Attach the recordings to a card, e.g. I-42.",
171
+ " --dry-run Hash and check each file; upload nothing.",
172
+ " --json One JSON object per file on stdout.",
157
173
  "",
158
174
  "Environment:",
159
175
  " SPECKLE_MCP_WORKSPACE_ROOT Directory to resolve the .speckle marker from,",
package/dist/headers.d.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import type { ResolvedWorkspace } from "./workspace.js";
15
15
  export declare const ROUTER_CLIENT_NAME = "@workpowers/speckle";
16
- export declare const ROUTER_CLIENT_VERSION = "0.8.1";
16
+ export declare const ROUTER_CLIENT_VERSION = "0.9.1";
17
17
  /**
18
18
  * The MCP client the router serves, as it named itself at initialize
19
19
  * (`claude-code/2.1.0`), so the server can say which door a person's quoted
@@ -37,7 +37,8 @@ export declare function buildRouterHeaders(args: {
37
37
  workspace?: ResolvedWorkspace;
38
38
  /**
39
39
  * Env-configured project binding used ONLY when no workspace/marker
40
- * resolved (SPECKLE_PROJECT_ID — Claude Desktop / Cowork installs). Sends
40
+ * resolved (SPECKLE_PROJECT_ID — Claude Desktop / Cowork installs — or
41
+ * `upload --project`, which skips the marker on purpose). Sends
41
42
  * a bare `X-Speckle-Project-Id`; the marker-derived provenance headers are
42
43
  * deliberately absent because there is no marker to attest.
43
44
  */
package/dist/headers.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * the server then exposes a project-agnostic discovery toolset.
13
13
  */
14
14
  export const ROUTER_CLIENT_NAME = "@workpowers/speckle";
15
- export const ROUTER_CLIENT_VERSION = "0.8.1";
15
+ export const ROUTER_CLIENT_VERSION = "0.9.1";
16
16
  /**
17
17
  * The MCP client the router serves, as it named itself at initialize
18
18
  * (`claude-code/2.1.0`), so the server can say which door a person's quoted
@@ -0,0 +1,48 @@
1
+ /**
2
+ * `speckle-mcp upload <file...>` — send recordings (video or audio) to a
3
+ * Speckle project without a browser tab open.
4
+ *
5
+ * Files go one after another; each file's parts go four at a time. Safe to
6
+ * run again on the same file, which is what a folder watcher will do: the
7
+ * server knows a file by its SHA-256 and answers that it already has it.
8
+ *
9
+ * Exit codes: 0 every file uploaded or already there; 1 any file failed;
10
+ * 2 a usage or configuration error (bad flags, no key, no project).
11
+ *
12
+ * Loaded only by `cli.ts` with a dynamic import, so the MCP router's start
13
+ * path never pulls this in.
14
+ */
15
+ import { type FileOutcome, type ToolCaller, type UploadDeps } from "./upload-transfer.js";
16
+ export declare const UPLOAD_USAGE: string;
17
+ export declare class UploadUsageError extends Error {
18
+ }
19
+ export interface UploadArgs {
20
+ files: string[];
21
+ projectId?: number;
22
+ card?: string;
23
+ dryRun: boolean;
24
+ json: boolean;
25
+ help: boolean;
26
+ }
27
+ export declare function parseUploadArgs(args: string[]): UploadArgs;
28
+ export interface UploadIo {
29
+ stdout: (text: string) => void;
30
+ stderr: (text: string) => void;
31
+ /** Is stderr a terminal? Then progress redraws one line in place. */
32
+ stderrIsTTY: boolean;
33
+ }
34
+ export interface RunUploadOptions {
35
+ env?: NodeJS.ProcessEnv;
36
+ io?: UploadIo;
37
+ /** Replaces the MCP connection (tests). */
38
+ callTool?: ToolCaller;
39
+ fetch?: typeof fetch;
40
+ deps?: Partial<UploadDeps>;
41
+ }
42
+ /** Runs the command and returns its exit code; never throws for a file's failure. */
43
+ export declare function runUploadCommand(args: string[], opts?: RunUploadOptions): Promise<number>;
44
+ /** A tool's answer is JSON in its first text block; `isError` carries `{ error, code }`. */
45
+ export declare function parseToolResult(result: unknown): unknown;
46
+ export declare function formatBytes(n: number): string;
47
+ export declare function describeOutcome(o: FileOutcome): string;
48
+ //# sourceMappingURL=upload-command.d.ts.map
@@ -0,0 +1,318 @@
1
+ /**
2
+ * `speckle-mcp upload <file...>` — send recordings (video or audio) to a
3
+ * Speckle project without a browser tab open.
4
+ *
5
+ * Files go one after another; each file's parts go four at a time. Safe to
6
+ * run again on the same file, which is what a folder watcher will do: the
7
+ * server knows a file by its SHA-256 and answers that it already has it.
8
+ *
9
+ * Exit codes: 0 every file uploaded or already there; 1 any file failed;
10
+ * 2 a usage or configuration error (bad flags, no key, no project).
11
+ *
12
+ * Loaded only by `cli.ts` with a dynamic import, so the MCP router's start
13
+ * path never pulls this in.
14
+ */
15
+ import path from "node:path";
16
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
17
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
18
+ import { loadRouterConfig, resolveSpeckleHost } from "./config.js";
19
+ import { resolveWorkspace, workspaceOptionsFromConfig } from "./workspace.js";
20
+ import { buildRouterHeaders, ROUTER_CLIENT_NAME, ROUTER_CLIENT_VERSION } from "./headers.js";
21
+ import { SpeckleRouterError } from "./errors.js";
22
+ import { errorMessage, scrubSecrets, ToolCallError, uploadFile, } from "./upload-transfer.js";
23
+ export const UPLOAD_USAGE = [
24
+ "Usage: speckle-mcp upload [options] <file...>",
25
+ "",
26
+ "Upload recordings (mp4 mov mkv webm m4v avi mp3 m4a aac wav flac ogg opus) to a",
27
+ "Speckle project. Re-running on a file Speckle already has is harmless.",
28
+ "",
29
+ "Options:",
30
+ " --project <id> Project to upload to (default: the .speckle marker's project).",
31
+ " --card <ref> Attach the recordings to a card, e.g. I-42.",
32
+ " --dry-run Hash and check each file; upload nothing.",
33
+ " --json One JSON object per file on stdout, nothing else.",
34
+ " --help Show this message.",
35
+ "",
36
+ "Needs SPECKLE_MCP_BASE_URL and SPECKLE_MCP_KEY in the environment.",
37
+ "Exit codes: 0 all uploaded or already there, 1 a file failed, 2 usage or config error.",
38
+ "",
39
+ ].join("\n");
40
+ export class UploadUsageError extends Error {
41
+ }
42
+ export function parseUploadArgs(args) {
43
+ const out = { files: [], dryRun: false, json: false, help: false };
44
+ let flagsDone = false;
45
+ for (let i = 0; i < args.length; i++) {
46
+ const raw = args[i];
47
+ if (flagsDone || !raw.startsWith("-") || raw === "-") {
48
+ out.files.push(raw);
49
+ continue;
50
+ }
51
+ if (raw === "--") {
52
+ flagsDone = true;
53
+ continue;
54
+ }
55
+ const eq = raw.indexOf("=");
56
+ const flag = eq > 0 ? raw.slice(0, eq) : raw;
57
+ const inline = eq > 0 ? raw.slice(eq + 1) : undefined;
58
+ const value = () => {
59
+ const v = inline ?? args[++i];
60
+ if (v === undefined || v === "")
61
+ throw new UploadUsageError(`${flag} needs a value.`);
62
+ return v;
63
+ };
64
+ const noValue = () => {
65
+ if (inline !== undefined)
66
+ throw new UploadUsageError(`${flag} does not take a value.`);
67
+ };
68
+ switch (flag) {
69
+ case "--project":
70
+ case "-p": {
71
+ const v = value();
72
+ if (!/^\d+$/.test(v) || Number.parseInt(v, 10) <= 0) {
73
+ throw new UploadUsageError(`--project needs a positive integer (got ${JSON.stringify(v)}).`);
74
+ }
75
+ out.projectId = Number.parseInt(v, 10);
76
+ break;
77
+ }
78
+ case "--card":
79
+ out.card = value();
80
+ break;
81
+ case "--dry-run":
82
+ noValue();
83
+ out.dryRun = true;
84
+ break;
85
+ case "--json":
86
+ noValue();
87
+ out.json = true;
88
+ break;
89
+ case "--help":
90
+ case "-h":
91
+ noValue();
92
+ out.help = true;
93
+ break;
94
+ default:
95
+ throw new UploadUsageError(`Unknown option: ${flag}`);
96
+ }
97
+ }
98
+ if (!out.help && out.files.length === 0)
99
+ throw new UploadUsageError("Name at least one file.");
100
+ return out;
101
+ }
102
+ const processIo = {
103
+ stdout: (t) => void process.stdout.write(t),
104
+ stderr: (t) => void process.stderr.write(t),
105
+ get stderrIsTTY() {
106
+ return Boolean(process.stderr.isTTY);
107
+ },
108
+ };
109
+ /** Runs the command and returns its exit code; never throws for a file's failure. */
110
+ export async function runUploadCommand(args, opts = {}) {
111
+ const io = opts.io ?? processIo;
112
+ let parsed;
113
+ try {
114
+ parsed = parseUploadArgs(args);
115
+ }
116
+ catch (err) {
117
+ io.stderr(`speckle-mcp upload: ${errorMessage(err)}\n\n${UPLOAD_USAGE}`);
118
+ return 2;
119
+ }
120
+ if (parsed.help) {
121
+ io.stdout(UPLOAD_USAGE);
122
+ return 0;
123
+ }
124
+ let connection;
125
+ if (opts.callTool) {
126
+ connection = { callTool: opts.callTool, close: async () => undefined };
127
+ }
128
+ else {
129
+ try {
130
+ connection = connectLazily(resolveTarget(parsed, opts.env ?? process.env));
131
+ }
132
+ catch (err) {
133
+ const text = err instanceof SpeckleRouterError ? err.toUserFacing() : errorMessage(err);
134
+ io.stderr(`speckle-mcp upload: ${scrubSecrets(text)}\n`);
135
+ return 2;
136
+ }
137
+ }
138
+ const deps = {
139
+ ...opts.deps,
140
+ callTool: connection.callTool,
141
+ fetch: opts.fetch ?? opts.deps?.fetch ?? fetch,
142
+ };
143
+ let failed = 0;
144
+ try {
145
+ for (const file of parsed.files) {
146
+ const progress = new ProgressLine(io, path.basename(file));
147
+ const outcome = await uploadFile(file, { card: parsed.card, dryRun: parsed.dryRun }, deps, (event) => progress.update(event));
148
+ progress.end();
149
+ if (outcome.status === "failed")
150
+ failed++;
151
+ io.stdout(parsed.json ? JSON.stringify(outcome) + "\n" : describeOutcome(outcome) + "\n");
152
+ }
153
+ }
154
+ finally {
155
+ await connection.close().catch(() => undefined);
156
+ }
157
+ return failed > 0 ? 1 : 0;
158
+ }
159
+ /**
160
+ * The project comes from `--project` when given — the marker is then not
161
+ * read at all, so it works outside any repo and overrides a marker that names
162
+ * another project — else from the `.speckle` marker, else `SPECKLE_PROJECT_ID`.
163
+ * No project at all is a configuration error: an upload has to land somewhere.
164
+ */
165
+ function resolveTarget(parsed, env) {
166
+ const config = loadRouterConfig(env);
167
+ let workspace;
168
+ let projectId = parsed.projectId;
169
+ if (projectId === undefined) {
170
+ try {
171
+ workspace = resolveWorkspace(workspaceOptionsFromConfig(config));
172
+ }
173
+ catch (err) {
174
+ if (!(err instanceof SpeckleRouterError && err.code === "marker_not_found"))
175
+ throw err;
176
+ projectId = config.fallbackProjectId;
177
+ }
178
+ if (!workspace && projectId === undefined) {
179
+ throw new UploadUsageError("No project to upload to: pass --project <id>, run inside a repo with a .speckle marker, or set SPECKLE_PROJECT_ID.");
180
+ }
181
+ }
182
+ const host = resolveSpeckleHost(config, workspace?.marker.marker.speckleUrl).hostUrl;
183
+ const headers = buildRouterHeaders({
184
+ apiKey: config.apiKey,
185
+ workspace,
186
+ fallbackProjectId: workspace ? undefined : projectId,
187
+ });
188
+ return { host, headers: { ...headers } };
189
+ }
190
+ /** Connects on the first tool call, so a run whose files all fail their
191
+ * local checks never touches the network. */
192
+ function connectLazily(target) {
193
+ const client = new Client({ name: ROUTER_CLIENT_NAME, version: ROUTER_CLIENT_VERSION }, { capabilities: {} });
194
+ let connected = null;
195
+ const callTool = async (name, args) => {
196
+ connected ??= client.connect(new StreamableHTTPClientTransport(new URL(`${target.host}/mcp`), {
197
+ requestInit: { headers: target.headers },
198
+ }));
199
+ try {
200
+ await connected;
201
+ }
202
+ catch (err) {
203
+ throw new Error(`Could not connect to Speckle: ${errorMessage(err)}`);
204
+ }
205
+ // Finishing assembles a multi-gigabyte object in the bucket; give it room.
206
+ const timeout = name === "finish_document_upload" ? 300_000 : 60_000;
207
+ // The upload tools are not in a session's default listing; the toolbox
208
+ // calls them through and hands their answer back verbatim.
209
+ const result = await client.callTool({ name: "speckle_toolbox", arguments: { tool: name, arguments: args } }, undefined, { timeout });
210
+ return parseToolResult(result);
211
+ };
212
+ return { callTool, close: () => (connected ? client.close() : Promise.resolve()) };
213
+ }
214
+ /** A tool's answer is JSON in its first text block; `isError` carries `{ error, code }`. */
215
+ export function parseToolResult(result) {
216
+ const r = result;
217
+ const text = r.content?.find((c) => c.type === "text")?.text;
218
+ let body = r.structuredContent;
219
+ if (text !== undefined) {
220
+ try {
221
+ body = JSON.parse(text);
222
+ }
223
+ catch {
224
+ body = body ?? text;
225
+ }
226
+ }
227
+ if (r.isError) {
228
+ const e = (body && typeof body === "object" ? body : {});
229
+ const message = typeof e.error === "string" ? e.error : typeof body === "string" ? body : "The tool refused the call.";
230
+ throw new ToolCallError(typeof e.code === "string" ? e.code : "tool_error", message);
231
+ }
232
+ return body;
233
+ }
234
+ // ── Output ──────────────────────────────────────────────────────────────────
235
+ export function formatBytes(n) {
236
+ if (n < 1024)
237
+ return `${n} B`;
238
+ const units = ["KB", "MB", "GB", "TB"];
239
+ let v = n / 1024;
240
+ let u = 0;
241
+ while (v >= 1024 && u < units.length - 1) {
242
+ v /= 1024;
243
+ u++;
244
+ }
245
+ return `${v.toFixed(v < 10 ? 1 : 0)} ${units[u]}`;
246
+ }
247
+ export function describeOutcome(o) {
248
+ const name = path.basename(o.file);
249
+ const facts = [o.byte_size !== undefined ? formatBytes(o.byte_size) : null, o.recorded_at ? `recorded ${o.recorded_at}` : null]
250
+ .filter(Boolean)
251
+ .join(", ");
252
+ const doc = o.document_id !== undefined ? `document ${o.document_id}` : "";
253
+ switch (o.status) {
254
+ case "uploaded": {
255
+ const notes = [
256
+ o.duplicate_of_document_id != null ? `looks like a copy of document ${o.duplicate_of_document_id}` : null,
257
+ o.ambiguous ? "the server could not tell for certain what it is" : null,
258
+ ].filter(Boolean);
259
+ return `uploaded ${name} -> ${doc} (${facts})${notes.length ? `; ${notes.join("; ")}` : ""}`;
260
+ }
261
+ case "already_uploaded":
262
+ return `already uploaded ${name} -> ${doc}${facts ? ` (${facts})` : ""}`;
263
+ case "would_upload":
264
+ return `not uploaded ${name} (${facts})`;
265
+ case "would_resume": {
266
+ const done = o.stored_part_count !== undefined && o.part_count !== undefined
267
+ ? `, ${o.stored_part_count} of ${o.part_count} parts stored` : "";
268
+ return `resumable ${name} (${facts}${done})`;
269
+ }
270
+ case "failed":
271
+ return `failed ${name}: ${o.error ?? "unknown error"}`;
272
+ }
273
+ }
274
+ const PLAIN_PROGRESS_EVERY_MS = 15_000;
275
+ /** One progress line per file on stderr: redrawn with `\r` on a terminal,
276
+ * a plain line every 15 s otherwise (a watcher's log). */
277
+ class ProgressLine {
278
+ io;
279
+ name;
280
+ lastPlain = 0;
281
+ drawn = false;
282
+ lastText = "";
283
+ constructor(io, name) {
284
+ this.io = io;
285
+ this.name = name;
286
+ }
287
+ update(event) {
288
+ const pct = event.total > 0 ? Math.floor((event.done / event.total) * 100) : 100;
289
+ let text;
290
+ if (event.phase === "hashing") {
291
+ text = `${this.name}: hashing ${pct}%`;
292
+ }
293
+ else {
294
+ const seconds = Math.max((Date.now() - event.startedAt) / 1000, 0.001);
295
+ const rate = event.sentThisRun / seconds;
296
+ text = `${this.name}: ${pct}% ${formatBytes(event.done)} of ${formatBytes(event.total)}` +
297
+ (event.sentThisRun > 0 ? `, ${formatBytes(rate)}/s` : "");
298
+ }
299
+ if (text === this.lastText)
300
+ return;
301
+ this.lastText = text;
302
+ if (this.io.stderrIsTTY) {
303
+ this.io.stderr(`\r\x1b[2K${text}`);
304
+ this.drawn = true;
305
+ return;
306
+ }
307
+ const now = Date.now();
308
+ if (now - this.lastPlain >= PLAIN_PROGRESS_EVERY_MS) {
309
+ this.lastPlain = now;
310
+ this.io.stderr(text + "\n");
311
+ }
312
+ }
313
+ end() {
314
+ if (this.drawn)
315
+ this.io.stderr("\r\x1b[2K");
316
+ }
317
+ }
318
+ //# sourceMappingURL=upload-command.js.map
@@ -0,0 +1,86 @@
1
+ /**
2
+ * One recording file into Speckle: check it, hash it, send the parts the
3
+ * bucket does not hold yet, and finish the upload.
4
+ *
5
+ * The server recognises a file by its SHA-256 and size, so this is safe to
6
+ * run again on the same file: a file it already has is reported and left
7
+ * alone, and an unfinished upload of it resumes from the parts that landed.
8
+ * Everything that talks to the outside — the tool caller, `fetch`, `stat`,
9
+ * the clock — is passed in, so the whole loop runs in tests without a server.
10
+ *
11
+ * Nothing here prints or returns a presigned URL: every error that leaves
12
+ * this module goes through `scrubSecrets`, because fetch errors embed them.
13
+ */
14
+ /** Extensions accepted as recordings, with the MIME type sent for each. The
15
+ * server decides from the bytes at finish; this only keeps a stray PDF out. */
16
+ export declare const RECORDING_MIME_TYPES: Readonly<Record<string, string>>;
17
+ export declare function recordingMimeType(filePath: string): string | undefined;
18
+ /**
19
+ * When was this recorded? OBS names files `2025-07-23 14-08-54.mkv` (`_` or
20
+ * `T` also seen between date and time); the stamp is local time on the
21
+ * machine that recorded, so it is read as local time here. A stamp that does
22
+ * not name a real local moment (Feb 31, a skipped DST hour) is ignored.
23
+ * Without a stamp, the file's mtime — for OBS, when recording stopped.
24
+ */
25
+ export declare function recordedAtFor(filename: string, mtimeMs: number): string;
26
+ export declare function recordedAtFromFilename(filename: string): Date | null;
27
+ /** ISO-8601 in the machine's local time with its offset: `2025-07-23T14:08:54+02:00`. */
28
+ export declare function formatLocalIso(date: Date): string;
29
+ export declare function sha256File(filePath: string, onProgress?: (hashed: number) => void): Promise<string>;
30
+ /** Presigned URLs are bearer credentials and fetch errors embed them; keys
31
+ * sometimes ride in a message too. Everything surfaced passes through here. */
32
+ export declare function scrubSecrets(message: string): string;
33
+ export declare function errorMessage(err: unknown): string;
34
+ /** A tool refused: the JSON body's `{ error, code }`. */
35
+ export declare class ToolCallError extends Error {
36
+ readonly code: string;
37
+ constructor(code: string, message: string);
38
+ }
39
+ /** Calls a Speckle MCP tool and returns its parsed JSON answer; throws
40
+ * `ToolCallError` when the tool answers `isError`. */
41
+ export type ToolCaller = (name: string, args: Record<string, unknown>) => Promise<unknown>;
42
+ export type FileStatus = "uploaded" | "already_uploaded" | "would_upload" | "would_resume" | "failed";
43
+ export interface FileOutcome {
44
+ file: string;
45
+ status: FileStatus;
46
+ document_id?: number | string;
47
+ display_name?: string;
48
+ sha256?: string;
49
+ recorded_at?: string;
50
+ byte_size?: number;
51
+ stored_part_count?: number;
52
+ part_count?: number;
53
+ ambiguous?: boolean;
54
+ duplicate_of_document_id?: number | string;
55
+ error?: string;
56
+ }
57
+ export interface FileStat {
58
+ size: number;
59
+ mtimeMs: number;
60
+ isFile(): boolean;
61
+ isDirectory(): boolean;
62
+ }
63
+ export interface UploadDeps {
64
+ callTool: ToolCaller;
65
+ fetch: typeof fetch;
66
+ stat?: (filePath: string) => Promise<FileStat>;
67
+ now?: () => number;
68
+ sleep?: (ms: number) => Promise<void>;
69
+ }
70
+ export interface UploadOptions {
71
+ card?: string;
72
+ dryRun?: boolean;
73
+ }
74
+ export type ProgressEvent = {
75
+ phase: "hashing";
76
+ done: number;
77
+ total: number;
78
+ } | {
79
+ phase: "uploading";
80
+ done: number;
81
+ total: number;
82
+ sentThisRun: number;
83
+ startedAt: number;
84
+ };
85
+ export declare function uploadFile(filePath: string, options: UploadOptions, deps: UploadDeps, onProgress?: (event: ProgressEvent) => void): Promise<FileOutcome>;
86
+ //# sourceMappingURL=upload-transfer.d.ts.map
@@ -0,0 +1,445 @@
1
+ /**
2
+ * One recording file into Speckle: check it, hash it, send the parts the
3
+ * bucket does not hold yet, and finish the upload.
4
+ *
5
+ * The server recognises a file by its SHA-256 and size, so this is safe to
6
+ * run again on the same file: a file it already has is reported and left
7
+ * alone, and an unfinished upload of it resumes from the parts that landed.
8
+ * Everything that talks to the outside — the tool caller, `fetch`, `stat`,
9
+ * the clock — is passed in, so the whole loop runs in tests without a server.
10
+ *
11
+ * Nothing here prints or returns a presigned URL: every error that leaves
12
+ * this module goes through `scrubSecrets`, because fetch errors embed them.
13
+ */
14
+ import { createHash } from "node:crypto";
15
+ import { createReadStream } from "node:fs";
16
+ import { open, stat as fsStat } from "node:fs/promises";
17
+ import path from "node:path";
18
+ import { z } from "zod";
19
+ // ── File checks ─────────────────────────────────────────────────────────────
20
+ /** Extensions accepted as recordings, with the MIME type sent for each. The
21
+ * server decides from the bytes at finish; this only keeps a stray PDF out. */
22
+ export const RECORDING_MIME_TYPES = {
23
+ ".mp4": "video/mp4",
24
+ ".mov": "video/quicktime",
25
+ ".mkv": "video/x-matroska",
26
+ ".webm": "video/webm",
27
+ ".m4v": "video/x-m4v",
28
+ ".avi": "video/x-msvideo",
29
+ ".mp3": "audio/mpeg",
30
+ ".m4a": "audio/mp4",
31
+ ".aac": "audio/aac",
32
+ ".wav": "audio/wav",
33
+ ".flac": "audio/flac",
34
+ ".ogg": "audio/ogg",
35
+ ".opus": "audio/opus",
36
+ };
37
+ export function recordingMimeType(filePath) {
38
+ return RECORDING_MIME_TYPES[path.extname(filePath).toLowerCase()];
39
+ }
40
+ // ── Recorded date ───────────────────────────────────────────────────────────
41
+ /**
42
+ * When was this recorded? OBS names files `2025-07-23 14-08-54.mkv` (`_` or
43
+ * `T` also seen between date and time); the stamp is local time on the
44
+ * machine that recorded, so it is read as local time here. A stamp that does
45
+ * not name a real local moment (Feb 31, a skipped DST hour) is ignored.
46
+ * Without a stamp, the file's mtime — for OBS, when recording stopped.
47
+ */
48
+ export function recordedAtFor(filename, mtimeMs) {
49
+ return formatLocalIso(recordedAtFromFilename(filename) ?? new Date(mtimeMs));
50
+ }
51
+ export function recordedAtFromFilename(filename) {
52
+ const m = path.basename(filename).match(/(\d{4})-(\d{2})-(\d{2})[ _T](\d{2})-(\d{2})-(\d{2})/);
53
+ if (!m)
54
+ return null;
55
+ const [y, mo, d, h, mi, s] = m.slice(1).map(Number);
56
+ const date = new Date(y, mo - 1, d, h, mi, s);
57
+ const roundTrips = date.getFullYear() === y && date.getMonth() === mo - 1 && date.getDate() === d &&
58
+ date.getHours() === h && date.getMinutes() === mi && date.getSeconds() === s;
59
+ return roundTrips ? date : null;
60
+ }
61
+ /** ISO-8601 in the machine's local time with its offset: `2025-07-23T14:08:54+02:00`. */
62
+ export function formatLocalIso(date) {
63
+ const pad = (n) => String(n).padStart(2, "0");
64
+ const offset = -date.getTimezoneOffset();
65
+ const sign = offset >= 0 ? "+" : "-";
66
+ const abs = Math.abs(offset);
67
+ return (`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` +
68
+ `T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` +
69
+ `${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`);
70
+ }
71
+ // ── Hashing ─────────────────────────────────────────────────────────────────
72
+ const HASH_CHUNK_BYTES = 8 * 1024 * 1024;
73
+ export async function sha256File(filePath, onProgress) {
74
+ const hash = createHash("sha256");
75
+ let hashed = 0;
76
+ for await (const chunk of createReadStream(filePath, { highWaterMark: HASH_CHUNK_BYTES })) {
77
+ hash.update(chunk);
78
+ hashed += chunk.length;
79
+ onProgress?.(hashed);
80
+ }
81
+ return hash.digest("hex");
82
+ }
83
+ // ── Secrets ─────────────────────────────────────────────────────────────────
84
+ /** Presigned URLs are bearer credentials and fetch errors embed them; keys
85
+ * sometimes ride in a message too. Everything surfaced passes through here. */
86
+ export function scrubSecrets(message) {
87
+ return message
88
+ .replace(/https?:\/\/\S+/gi, "<url>")
89
+ .replace(/Bearer\s+\S+/gi, "Bearer <redacted>")
90
+ .replace(/lsk_\S+/g, "<redacted>");
91
+ }
92
+ export function errorMessage(err) {
93
+ if (err instanceof Error) {
94
+ const cause = err.cause instanceof Error ? `: ${err.cause.message}` : "";
95
+ return scrubSecrets(`${err.message}${cause}`);
96
+ }
97
+ return scrubSecrets(String(err));
98
+ }
99
+ // ── The server contract ─────────────────────────────────────────────────────
100
+ /** A tool refused: the JSON body's `{ error, code }`. */
101
+ export class ToolCallError extends Error {
102
+ code;
103
+ constructor(code, message) {
104
+ super(message);
105
+ this.code = code;
106
+ this.name = "ToolCallError";
107
+ }
108
+ }
109
+ const signedPartSchema = z.object({ part_number: z.number().int().positive(), url: z.string() });
110
+ const storedPartSchema = z.object({
111
+ part_number: z.number().int().positive(),
112
+ etag: z.string(),
113
+ byte_size: z.number().int().nonnegative(),
114
+ });
115
+ const documentSchema = z
116
+ .object({ id: z.union([z.number(), z.string()]), display_name: z.string().nullish() })
117
+ .passthrough();
118
+ const openUploadSchema = z.object({
119
+ status: z.enum(["upload", "resume"]),
120
+ upload_id: z.string(),
121
+ part_size: z.number().int().positive(),
122
+ part_count: z.number().int().positive(),
123
+ parts: z.array(signedPartSchema).default([]),
124
+ stored_parts: z.array(storedPartSchema).default([]),
125
+ expires_in_seconds: z.number().positive(),
126
+ });
127
+ const startAnswerSchema = z.union([
128
+ z.object({ status: z.literal("already_uploaded"), document: documentSchema }),
129
+ z.object({ status: z.literal("not_uploaded") }),
130
+ z.object({
131
+ status: z.literal("resumable"),
132
+ stored_part_count: z.number().int().nonnegative().optional(),
133
+ part_count: z.number().int().positive().optional(),
134
+ }),
135
+ openUploadSchema,
136
+ ]);
137
+ const refreshAnswerSchema = z.object({
138
+ parts: z.array(signedPartSchema).default([]),
139
+ stored_parts: z.array(storedPartSchema).default([]),
140
+ expires_in_seconds: z.number().positive(),
141
+ });
142
+ const finishAnswerSchema = z.object({
143
+ document: documentSchema,
144
+ ambiguous: z.boolean().nullish(),
145
+ duplicate_of_document_id: z.union([z.number(), z.string()]).nullish(),
146
+ });
147
+ const PART_CONCURRENCY = 4;
148
+ const PART_ATTEMPTS = 4;
149
+ /** How many part URLs one refresh asks for — enough to keep four workers busy
150
+ * for a while, few enough that they are used before they go stale. */
151
+ const URL_BATCH = 32;
152
+ /** A URL counts as stale this long before the server says it expires. */
153
+ const URL_STALE_MARGIN_MS = 60_000;
154
+ /** Raised for a reason that is the file's, not a network blip: never retried. */
155
+ class FileRefused extends Error {
156
+ }
157
+ export async function uploadFile(filePath, options, deps, onProgress) {
158
+ const outcome = { file: filePath, status: "failed" };
159
+ try {
160
+ return await runFile(filePath, options, deps, outcome, onProgress);
161
+ }
162
+ catch (err) {
163
+ outcome.status = "failed";
164
+ outcome.error =
165
+ err instanceof ToolCallError ? scrubSecrets(`${err.message} (${err.code})`)
166
+ : err instanceof z.ZodError ? scrubSecrets(`Unexpected answer from the server: ${describeZodError(err)}`)
167
+ : errorMessage(err);
168
+ return outcome;
169
+ }
170
+ }
171
+ function describeZodError(err) {
172
+ return err.issues.map((i) => `${i.path.join(".") || "(root)"} ${i.message}`).join("; ");
173
+ }
174
+ async function runFile(filePath, options, deps, outcome, onProgress) {
175
+ const stat = deps.stat ?? fsStat;
176
+ const before = await statOrRefuse(stat, filePath);
177
+ if (before.isDirectory())
178
+ throw new FileRefused("is a directory");
179
+ if (!before.isFile())
180
+ throw new FileRefused("is not a regular file");
181
+ if (before.size === 0)
182
+ throw new FileRefused("is empty");
183
+ const mimeType = recordingMimeType(filePath);
184
+ if (!mimeType) {
185
+ throw new FileRefused(`is not an audio or video file (accepted: ${Object.keys(RECORDING_MIME_TYPES).join(" ")})`);
186
+ }
187
+ outcome.byte_size = before.size;
188
+ outcome.recorded_at = recordedAtFor(filePath, before.mtimeMs);
189
+ const sha256 = await sha256File(filePath, (done) => onProgress?.({ phase: "hashing", done, total: before.size }));
190
+ const afterHash = await statOrRefuse(stat, filePath);
191
+ if (changed(before, afterHash)) {
192
+ throw new FileRefused("is still being written (it changed while it was hashed); try again once it is finished");
193
+ }
194
+ outcome.sha256 = sha256;
195
+ const startArgs = {
196
+ kind: "recording",
197
+ filename: path.basename(filePath),
198
+ byte_size: before.size,
199
+ mime_type: mimeType,
200
+ sha256,
201
+ ...(options.card ? { card: options.card } : {}),
202
+ };
203
+ if (options.dryRun) {
204
+ const answer = startAnswerSchema.parse(await deps.callTool("start_document_upload", { ...startArgs, check_only: true }));
205
+ switch (answer.status) {
206
+ case "already_uploaded":
207
+ return alreadyUploaded(outcome, answer.document);
208
+ case "resumable":
209
+ outcome.status = "would_resume";
210
+ outcome.stored_part_count = answer.stored_part_count;
211
+ outcome.part_count = answer.part_count;
212
+ return outcome;
213
+ case "not_uploaded":
214
+ outcome.status = "would_upload";
215
+ return outcome;
216
+ default:
217
+ throw new Error(`The server opened an upload for a check-only request (${answer.status}).`);
218
+ }
219
+ }
220
+ const answer = startAnswerSchema.parse(await deps.callTool("start_document_upload", startArgs));
221
+ if (answer.status === "already_uploaded")
222
+ return alreadyUploaded(outcome, answer.document);
223
+ if (answer.status !== "upload" && answer.status !== "resume") {
224
+ throw new Error(`The server answered "${answer.status}" to an upload request.`);
225
+ }
226
+ if (answer.part_count !== Math.ceil(before.size / answer.part_size)) {
227
+ throw new Error(`The server's part layout (${answer.part_count} parts of ${answer.part_size} bytes) does not fit a ${before.size}-byte file.`);
228
+ }
229
+ const parts = await sendParts(filePath, before.size, answer, deps, onProgress);
230
+ const afterUpload = await statOrRefuse(stat, filePath);
231
+ if (changed(before, afterUpload)) {
232
+ throw new FileRefused("changed while it was uploading; the upload was not finished");
233
+ }
234
+ const finished = finishAnswerSchema.parse(await deps.callTool("finish_document_upload", {
235
+ upload_id: answer.upload_id,
236
+ parts,
237
+ recorded_at: outcome.recorded_at,
238
+ }));
239
+ outcome.status = "uploaded";
240
+ outcome.document_id = finished.document.id;
241
+ if (finished.document.display_name)
242
+ outcome.display_name = finished.document.display_name;
243
+ if (finished.ambiguous)
244
+ outcome.ambiguous = true;
245
+ if (finished.duplicate_of_document_id != null) {
246
+ outcome.duplicate_of_document_id = finished.duplicate_of_document_id;
247
+ }
248
+ return outcome;
249
+ }
250
+ function alreadyUploaded(outcome, document) {
251
+ outcome.status = "already_uploaded";
252
+ outcome.document_id = document.id;
253
+ if (document.display_name)
254
+ outcome.display_name = document.display_name;
255
+ return outcome;
256
+ }
257
+ async function statOrRefuse(stat, filePath) {
258
+ try {
259
+ return await stat(filePath);
260
+ }
261
+ catch (err) {
262
+ const code = err?.code;
263
+ if (code === "ENOENT")
264
+ throw new FileRefused("does not exist");
265
+ if (code === "EACCES" || code === "EPERM")
266
+ throw new FileRefused("cannot be read (permission denied)");
267
+ throw err;
268
+ }
269
+ }
270
+ function changed(a, b) {
271
+ return a.size !== b.size || a.mtimeMs !== b.mtimeMs;
272
+ }
273
+ /**
274
+ * Send every part the bucket lacks, four at a time, and return the full,
275
+ * sorted `{ part_number, etag }` list `finish_document_upload` needs.
276
+ *
277
+ * URLs come in batches and are thrown away a minute before they expire; a
278
+ * failed PUT (a 403 from an expired signature, a dropped connection) asks for
279
+ * that part's URL again — which also tells us if the bucket had it after all —
280
+ * and retries, up to four attempts. Each refresh keeps the upload alive on the
281
+ * server too.
282
+ */
283
+ async function sendParts(filePath, size, grant, deps, onProgress) {
284
+ const now = deps.now ?? Date.now;
285
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
286
+ const { part_size: partSize, part_count: partCount, upload_id: uploadId } = grant;
287
+ const startedAt = now();
288
+ const done = new Map();
289
+ const urls = new Map();
290
+ let sent = 0;
291
+ let sentThisRun = 0;
292
+ const report = () => onProgress?.({ phase: "uploading", done: Math.min(sent, size), total: size, sentThisRun, startedAt });
293
+ const partBytes = (n) => Math.min(n * partSize, size) - (n - 1) * partSize;
294
+ const markStored = (parts) => {
295
+ for (const p of parts) {
296
+ if (p.part_number > partCount || done.has(p.part_number))
297
+ continue;
298
+ done.set(p.part_number, p.etag);
299
+ sent += p.byte_size;
300
+ }
301
+ };
302
+ const remember = (signed, expiresInSeconds) => {
303
+ const lifetime = expiresInSeconds * 1000;
304
+ const staleAt = now() + lifetime - Math.min(URL_STALE_MARGIN_MS, lifetime / 2);
305
+ for (const p of signed)
306
+ urls.set(p.part_number, { url: p.url, staleAt });
307
+ };
308
+ markStored(grant.stored_parts);
309
+ remember(grant.parts, grant.expires_in_seconds);
310
+ report();
311
+ const fresh = (n) => {
312
+ const u = urls.get(n);
313
+ return u !== undefined && now() < u.staleAt;
314
+ };
315
+ // One refresh at a time; a worker that needs a URL while one is in flight
316
+ // waits for it and looks again.
317
+ let inflight = null;
318
+ const refresh = (first) => {
319
+ const batch = [first];
320
+ for (let n = first + 1; n <= partCount && batch.length < URL_BATCH; n++) {
321
+ if (!done.has(n) && !fresh(n))
322
+ batch.push(n);
323
+ }
324
+ const run = async () => {
325
+ const answer = refreshAnswerSchema.parse(await deps.callTool("refresh_upload_parts", { upload_id: uploadId, part_numbers: batch }));
326
+ markStored(answer.stored_parts);
327
+ remember(answer.parts, answer.expires_in_seconds);
328
+ report();
329
+ };
330
+ // `.finally` runs on a later tick, so `inflight` is always this promise
331
+ // by then — even when the call fails synchronously.
332
+ const pending = run().finally(() => {
333
+ if (inflight === pending)
334
+ inflight = null;
335
+ });
336
+ inflight = pending;
337
+ return pending;
338
+ };
339
+ const urlFor = async (n) => {
340
+ for (let pass = 0; pass < 3; pass++) {
341
+ if (done.has(n))
342
+ return null;
343
+ if (fresh(n))
344
+ return urls.get(n).url;
345
+ if (inflight)
346
+ await inflight;
347
+ else
348
+ await refresh(n);
349
+ }
350
+ if (done.has(n))
351
+ return null;
352
+ if (fresh(n))
353
+ return urls.get(n).url;
354
+ throw new Error(`The server did not sign part ${n}.`);
355
+ };
356
+ const file = await open(filePath, "r");
357
+ try {
358
+ const readPart = async (n) => {
359
+ const length = partBytes(n);
360
+ const buf = new Uint8Array(length);
361
+ let offset = 0;
362
+ while (offset < length) {
363
+ const { bytesRead } = await file.read(buf, offset, length - offset, (n - 1) * partSize + offset);
364
+ if (bytesRead === 0)
365
+ throw new FileRefused("got shorter while it was uploading");
366
+ offset += bytesRead;
367
+ }
368
+ return buf;
369
+ };
370
+ const putPart = async (n) => {
371
+ let lastError = null;
372
+ for (let attempt = 1; attempt <= PART_ATTEMPTS; attempt++) {
373
+ if (done.has(n))
374
+ return;
375
+ try {
376
+ const url = await urlFor(n);
377
+ if (url === null)
378
+ return;
379
+ const body = await readPart(n);
380
+ // No Content-Type: the part was signed without one.
381
+ const res = await deps.fetch(url, { method: "PUT", body });
382
+ if (res.ok) {
383
+ const etag = res.headers.get("etag");
384
+ await res.arrayBuffer().catch(() => undefined);
385
+ if (!etag)
386
+ throw new FileRefused(`The bucket did not answer an ETag for part ${n}.`);
387
+ if (!done.has(n)) {
388
+ done.set(n, etag);
389
+ sent += body.length;
390
+ sentThisRun += body.length;
391
+ }
392
+ report();
393
+ return;
394
+ }
395
+ await res.arrayBuffer().catch(() => undefined);
396
+ lastError = new Error(`The bucket refused part ${n} (HTTP ${res.status}).`);
397
+ }
398
+ catch (err) {
399
+ if (err instanceof FileRefused || err instanceof ToolCallError)
400
+ throw err;
401
+ lastError = err;
402
+ }
403
+ // Expired or failed: drop this URL so the next attempt signs it again
404
+ // (and learns whether the bucket kept the part after all).
405
+ urls.delete(n);
406
+ if (attempt < PART_ATTEMPTS)
407
+ await sleep(1000 * attempt);
408
+ }
409
+ throw new Error(`Part ${n} could not be uploaded after ${PART_ATTEMPTS} attempts: ${errorMessage(lastError)}`);
410
+ };
411
+ const queue = [];
412
+ for (let n = 1; n <= partCount; n++)
413
+ if (!done.has(n))
414
+ queue.push(n);
415
+ let failure = null;
416
+ const workers = Array.from({ length: Math.min(PART_CONCURRENCY, queue.length) }, async () => {
417
+ while (failure === null) {
418
+ const n = queue.shift();
419
+ if (n === undefined)
420
+ return;
421
+ try {
422
+ await putPart(n);
423
+ }
424
+ catch (err) {
425
+ failure ??= err;
426
+ }
427
+ }
428
+ });
429
+ await Promise.all(workers);
430
+ if (failure !== null)
431
+ throw failure;
432
+ }
433
+ finally {
434
+ await file.close().catch(() => undefined);
435
+ }
436
+ for (let n = 1; n <= partCount; n++) {
437
+ if (!done.has(n))
438
+ throw new Error(`Part ${n} was never stored.`);
439
+ }
440
+ report();
441
+ return [...done.entries()]
442
+ .map(([part_number, etag]) => ({ part_number, etag }))
443
+ .sort((a, b) => a.part_number - b.part_number);
444
+ }
445
+ //# sourceMappingURL=upload-transfer.js.map
@@ -1,7 +1,7 @@
1
1
  /** Per-router-session metadata. Re-read checkout evidence on every call; never equate notice delivery with adoption. */
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
- import { WORKFLOW_META, publicationSchema } from "./workflow-contract.js";
4
+ import { WORKFLOW_META, guidanceRevision, publicationSchema } from "./workflow-contract.js";
5
5
  import { observeWorkflowFiles, cachedWorkflowFallback } from "./workflow-files.js";
6
6
  const responseMeta = z.object({
7
7
  notice_id: z.string(), notice_delivered: z.boolean(), fetched_revision: z.string().optional(),
@@ -29,7 +29,7 @@ export function createWorkflowClient(options) {
29
29
  if (isWorkflowFetch(params) && !r.isError) {
30
30
  const publication = publicationSchema.safeParse(r.structuredContent);
31
31
  if (publication.success)
32
- fetchedRevision = publication.data.planning.revision;
32
+ fetchedRevision = guidanceRevision(publication.data);
33
33
  }
34
34
  },
35
35
  fallback(params) {
@@ -47,6 +47,27 @@ export declare const publicationSchema: z.ZodObject<{
47
47
  content: string;
48
48
  summary: string;
49
49
  }>;
50
+ rules: z.ZodOptional<z.ZodEffects<z.ZodObject<{
51
+ revision: z.ZodString;
52
+ content: z.ZodString;
53
+ summary: z.ZodString;
54
+ }, "strip", z.ZodTypeAny, {
55
+ revision: string;
56
+ content: string;
57
+ summary: string;
58
+ }, {
59
+ revision: string;
60
+ content: string;
61
+ summary: string;
62
+ }>, {
63
+ revision: string;
64
+ content: string;
65
+ summary: string;
66
+ }, {
67
+ revision: string;
68
+ content: string;
69
+ summary: string;
70
+ }>>;
50
71
  bootstrap: z.ZodEffects<z.ZodObject<{
51
72
  revision: z.ZodString;
52
73
  content: z.ZodString;
@@ -80,6 +101,11 @@ export declare const publicationSchema: z.ZodObject<{
80
101
  content: string;
81
102
  summary: string;
82
103
  };
104
+ rules?: {
105
+ revision: string;
106
+ content: string;
107
+ summary: string;
108
+ } | undefined;
83
109
  }, {
84
110
  protocol_version: 1;
85
111
  planning: {
@@ -92,8 +118,19 @@ export declare const publicationSchema: z.ZodObject<{
92
118
  content: string;
93
119
  summary: string;
94
120
  };
121
+ rules?: {
122
+ revision: string;
123
+ content: string;
124
+ summary: string;
125
+ } | undefined;
95
126
  }>;
96
127
  export type WorkflowPublication = z.infer<typeof publicationSchema>;
128
+ /**
129
+ * The revision a session has fetched: the planning revision, or, once the
130
+ * answer carries rules, one hash over both, so a changed rule raises the
131
+ * same notice a changed step does (I-8746).
132
+ */
133
+ export declare const guidanceRevision: (publication: WorkflowPublication) => string;
97
134
  declare const observation: z.ZodObject<{
98
135
  state: z.ZodEnum<["observed", "missing", "unreadable"]>;
99
136
  hash: z.ZodOptional<z.ZodString>;
@@ -290,8 +327,6 @@ export declare function compareObservation(observed: FileObservation | undefined
290
327
  export declare function workflowStatus(publication: WorkflowPublication, context?: WorkflowContext): {
291
328
  notice_id: string;
292
329
  notify: boolean;
293
- protocol_version: 1;
294
- planning_revision: string;
295
330
  bootstrap_revision: string;
296
331
  session: string;
297
332
  checkout: {
@@ -301,6 +336,9 @@ export declare function workflowStatus(publication: WorkflowPublication, context
301
336
  bootstrap: string;
302
337
  planning_cache: string;
303
338
  };
339
+ rules_revision?: string | undefined;
340
+ protocol_version: 1;
341
+ planning_revision: string;
304
342
  };
305
343
  export {};
306
344
  //# sourceMappingURL=workflow-contract.d.ts.map
@@ -15,8 +15,19 @@ export const artifactSchema = z.object({
15
15
  export const publicationSchema = z.object({
16
16
  protocol_version: z.literal(1),
17
17
  planning: artifactSchema,
18
+ // Rules for every project (I-8746): standing rules beside the steps, with
19
+ // their own revision. Optional so a client reading an older server parses.
20
+ rules: artifactSchema.optional(),
18
21
  bootstrap: artifactSchema,
19
22
  });
23
+ /**
24
+ * The revision a session has fetched: the planning revision, or, once the
25
+ * answer carries rules, one hash over both, so a changed rule raises the
26
+ * same notice a changed step does (I-8746).
27
+ */
28
+ export const guidanceRevision = (publication) => publication.rules
29
+ ? hashContent(`${publication.planning.revision}\n${publication.rules.revision}`)
30
+ : publication.planning.revision;
20
31
  const observation = z.object({
21
32
  state: z.enum(["observed", "missing", "unreadable"]),
22
33
  hash: hash.optional(),
@@ -66,8 +77,12 @@ export function workflowStatus(publication, context = {}) {
66
77
  const status = {
67
78
  protocol_version: 1,
68
79
  planning_revision: publication.planning.revision,
80
+ ...(publication.rules ? { rules_revision: publication.rules.revision } : {}),
69
81
  bootstrap_revision: publication.bootstrap.revision,
70
- session: context.fetched_revision === publication.planning.revision ? "fetched" :
82
+ // A router published before I-8746 echoes the planning revision alone; it
83
+ // keeps planning-only freshness rather than an endless notice.
84
+ session: context.fetched_revision === guidanceRevision(publication) ||
85
+ context.fetched_revision === publication.planning.revision ? "fetched" :
71
86
  context.fetched_revision ? "outdated" : "unknown",
72
87
  checkout: {
73
88
  workspace_id: context.workspace_id ?? null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workpowers/speckle",
3
- "version": "0.8.1",
3
+ "version": "0.9.1",
4
4
  "description": "Local MCP router for Speckle — resolves project context from a committed .speckle marker and forwards calls to the remote Speckle MCP endpoint.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",