@openengio/cli 0.38.0 → 0.39.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/README.md CHANGED
@@ -39,9 +39,9 @@ Install the public npm package:
39
39
  npm install -g @openengio/cli
40
40
  ```
41
41
 
42
- `openeng` has no host built in. The production host is `https://api.openeng.io`. Pass `--host
43
- https://api.openeng.io` to a command, or set `OPENENG_HOST=https://api.openeng.io` once to make it the
44
- default. An agent starts with `openeng skill`, which prints how to work with the platform.
42
+ `openeng` defaults to `https://api.openeng.io`. Pass `--host <origin>` or set `OPENENG_HOST=<origin>`
43
+ to use another deployment. An empty `OPENENG_HOST` turns the default off.
44
+ An agent starts with `openeng skill`, which prints how to work with the platform.
45
45
 
46
46
  `openeng --version` prints the published version, `0.<protocol>.<patch>`. `openeng organisations` and
47
47
  `openeng orgs` run the commands of `openeng org`, and `openeng project` runs the commands of `openeng projects`.
@@ -83,7 +83,7 @@ The installed package contains the bundled command and the skill. It carries no
83
83
  | `openeng types draft try --type <key> --sample <file> [--change-set <id>]` | checks one sample instance, a JSON object of raw property values in the file, against the open change set's version of the type, with the check a write runs; it reads the open change set (the attached organisation's, or the one `--change-set` names) and writes nothing; exits 0 with `{ valid: true, violations: [] }` when the sample fits, and 4 with each violation's path and rule on standard output when it does not; a file that is unreadable, not JSON or not an object, no open change set, or a type key the change set does not hold or that names a verb type, is refused (exit 2) | two reads, one with `--change-set` |
84
84
  | `openeng types draft discard --change-set <id>` | discards the change set | one |
85
85
  | `openeng types draft accept --change-set <id> --revision <token>` | publishes the change set's types at the revision the person reviewed, under a minted idempotency key | one |
86
- | `openeng attachment add <object> <property> <file> --project <id> --ref <ref>` | stages, saves and prints the descriptor | four |
86
+ | `openeng attachment add <object> <property> <file> --project <id> --ref <ref>` | uploads and saves | five |
87
87
  | `openeng attachment get <object> <property> [--out <path>] --project <id> --ref <ref>` | downloads and prints the written path | one |
88
88
  | `openeng attachment list <object> --project <id> --ref <ref>` | prints attachment properties and descriptors | two |
89
89
  | `openeng hosted-app publish <bundle> --project <id> --key <app key>` | publishes the bundle file as the next version of the project's hosted app under the key, creating the app when the project has none; prints the version, its SHA-256 and size, and the reduced isolation warning for an app that holds the reduced isolation permission | three to four |
@@ -105,12 +105,13 @@ The installed package contains the bundled command and the skill. It carries no
105
105
  | `openeng schema-update show` | reads the latest visible request, or no request | one |
106
106
  | `openeng skill [<topic> \| playbook <name>]` | prints the main skill and lists topics, or prints one bundled topic; needs no host and no session | none |
107
107
 
108
- Create the object first, then stage and save its attachment. Creation with a file is refused
108
+ Create the object first, then upload and save its attachment. Creation with a file is refused
109
109
  as `invalid-properties` with `attachment-requires-object` at each offending property.
110
110
 
111
111
  Attachments are top-level properties declared with kind `attachment`. Accepted file classes are
112
112
  `image` (PNG, JPEG, WebP, GIF), `pdf`, `step` (STEP), `mesh` (STL) and `text` (plain text and the
113
- admitted text-file extensions). Each body is limited to 26,214,400 bytes (25 MiB).
113
+ admitted text-file extensions). The deployment sets the per-file limit, which is 1 GiB in production.
114
+ The organisation storage limit is checked before opening an upload.
114
115
 
115
116
  The hosted-app commands take `--project`, and `publish` also takes `--key`, an app key: lower-case
116
117
  letters, digits and hyphens, at most 63 characters. The parser refuses any other value (exit 2), so
@@ -122,11 +123,25 @@ beside the version. A publisher who may not read the organisation's reduced isol
122
123
  still publishes: the command adds one line saying this account cannot read whether the app may send
123
124
  data out of the browser, and `--json` carries `"oneWall": "unknown"`.
124
125
 
126
+ The CLI and SDK upload file bytes directly to the file store in 8 MiB pieces, with at most
127
+ one following piece prefetched. Interrupted uploads query the committed offset and resume within
128
+ the same call, with at most three resumes per piece. The CLI prints upload and download progress
129
+ to standard error. The SDK accepts `{ onProgress: (committed, total) => void }` as the third
130
+ argument of `uploadAttachment(selector, source, options)`. An open refused as `storage-limit-reached` sends no
131
+ file bytes.
132
+ The upload uses `openAttachmentUpload` (`POST /attachments/upload/open`) and
133
+ `completeAttachmentUpload` (`POST /attachments/upload/complete`). `too-large` means the declared
134
+ file exceeds the host bound; `unsupported-content` means the extension or recognised content is
135
+ not admitted. `upload-not-found` means completion found no upload for this caller and object project;
136
+ start the upload again. These refusals are printed through the ordinary CLI refusal output.
137
+
125
138
  All three attachment commands require explicit `--project` and `--ref` and an attached organisation.
126
- `add` uses the local file's basename, stages it, reads the object and catalogue, then saves; it prints
139
+ `add` reads the object, uploads the local file lazily using its basename, reads the catalogue, then saves;
140
+ it prints
127
141
  the descriptor only after a succeeded save. `add` and `list` use the catalogue's latest version of
128
142
  the object's type key, even when the object pins an older version. `get` verifies the downloaded
129
- SHA-256 before writing, uses the descriptor's name when `--out` is absent, and overwrites an existing
143
+ MD5 or SHA-256 before renaming the completed file, uses the descriptor's name when `--out` is absent,
144
+ and overwrites an existing
130
145
  destination. `list` prints one `{ property, descriptor }` JSON object per present attachment in text
131
146
  mode, or `no attachments` when empty; `--json` returns `{ scope, value: [...] }`.
132
147
  `get --json` returns `{ path }` with scope metadata; `add --json` returns the descriptor with it.
@@ -446,7 +461,7 @@ command that needs one it was not given refuses before any call (exit 2).
446
461
 
447
462
  | setting | flag | what it is |
448
463
  |---|---|---|
449
- | `OPENENG_HOST` | `--host` | `unix:<absolute socket path>` or an `https` origin. Every other form, `http:` included, is refused before any request (exit 2). The flag wins. |
464
+ | `OPENENG_HOST` | `--host` | `unix:<absolute socket path>` or an `https` origin. Every other form, `http:` included, is refused before any request (exit 2). Unset means `https://api.openeng.io`. The flag wins. |
450
465
  | `OPENENG_SIGN_IN_ORIGIN` | `--sign-in-origin` | for a `unix:` host, the network host's `http://127.0.0.1:<port>` or `http://[::1]:<port>` origin. Only the browser visits it; no credential is sent to it. Any non-loopback origin is refused. The flag wins. |
451
466
  | `OPENENG_SESSION_STORE` | none | `file` selects the file store. Unset selects the platform's credential store where its tool answers, else the file store. Any other value is refused. |
452
467
  | `XDG_CONFIG_HOME` | none | the configuration directory when it is an absolute path, else `~/.config`. |
@@ -104,6 +104,10 @@ var RULE_ENTRIES = {
104
104
  "too-many-links": entry("The review chain or aggregate exceeds 100 contributing objects or links.", { option: "Reduce the chain or the contributing links before reading or clearing again." }),
105
105
  "unsupported-content": entry("The file's content or name is not an admitted attachment format.", FIX_REQUEST),
106
106
  "too-large": entry("The attachment exceeds the per-file byte limit.", FIX_REQUEST),
107
+ "storage-limit-reached": entry("The organisation has no room left for a file of this size.", ASK_ADMINISTRATOR),
108
+ "upload-not-found": entry("No finished upload of yours matches this identifier.", { option: "Open a new upload and send the file again." }),
109
+ "upload-length-mismatch": entry("The stored file is not the length the upload declared.", { option: "Open a new upload and send the whole file again." }),
110
+ "attachment-collision": entry("A different file is already stored under this file's name in the store.", { option: "Open a new upload and send the file again; if it recurs, tell an administrator." }),
107
111
  "not-an-attachment-property": entry("The object's stored type version does not declare this property as an attachment.", FIX_REQUEST),
108
112
  "no-attachment": entry("The property holds no attachment."),
109
113
  "attachment-unavailable": entry("The attachment's stored bytes are unavailable.", { option: "Ask an administrator to restore the attachment." }),
@@ -434,8 +438,9 @@ var ROUTE_DOCS = Object.freeze({
434
438
  enterHumanMode: doc("Switches the presenting CLI session to human mode after one web confirmation. Already-human sessions return their current state without another write; web sessions are refused. CLI: openeng session human prints the confirm address, polls and retries once with unchanged bytes and key, then prints the stored state. Human mode lasts for this session; a new CLI sign-in starts in agent mode.", SIGNED_IN),
435
439
  readSessionStatus: doc("Reads the presenting person's stored session channel, mode and sign-in time, without organisation attachment. CLI: openeng session status prints { channel, mode, issuedAt } under --json; it never reads a local mode.", SIGNED_IN),
436
440
  readStepUpProof: doc("Polls as the requesting person session or run. Only that actor receives a confirmed live proof. Without an eligible confirmation it answers awaiting. No organisation attachment is required.", SIGNED_IN),
437
- stageAttachment: doc("Stages attachment bytes for an existing object after its guard admits the caller on the selected ref. Admits person, service, app:client and agent:apply actors.", [...ATTACHMENT_SCOPED, "not-permitted", "frozen", "protected", "unsupported-content", "too-large"]),
438
- readAttachment: doc("Downloads the attachment held by an object's property at its stored type version. Admits person, service, app:client, agent:explore and agent:apply actors.", [...ATTACHMENT_SCOPED, "organisation-not-ready", "branch-needs-schema-update", "not-an-attachment-property", "no-attachment", "attachment-unavailable"]),
441
+ openAttachmentUpload: doc("Opens an upload session for a file of a declared length on an existing object after its guard admits the caller on the selected ref. The answer carries the upload identifier and a session address that accepts the bytes with no other credential. Admits person, service, app:client and agent:apply actors.", [...ATTACHMENT_SCOPED, "not-permitted", "frozen", "protected", "unsupported-content", "too-large", "storage-limit-reached"]),
442
+ completeAttachmentUpload: doc("Finishes an upload the caller opened: checks the stored file and stages it for the caller, then answers its descriptor. The object's guard is asked again. A repeated call for the same upload answers the same descriptor. Admits person, service, app:client and agent:apply actors.", [...ATTACHMENT_SCOPED, "not-permitted", "frozen", "protected", "unsupported-content", "upload-not-found", "upload-length-mismatch", "attachment-collision"]),
443
+ readAttachment: doc("Downloads the attachment held by an object's property at its stored type version. A file within the download threshold is streamed in the answer; a larger file is answered with a redirect whose Location is a short-lived link to the stored file. Admits person, service, app:client, agent:explore and agent:apply actors.", [...ATTACHMENT_SCOPED, "organisation-not-ready", "branch-needs-schema-update", "not-an-attachment-property", "no-attachment", "attachment-unavailable"]),
439
444
  readObject: doc("Reads one object at a branch or baseline.", REF_READ),
440
445
  queryObjects: doc(`Runs a filtered, ordered, paged query over the objects of a branch or baseline, or pages the union, intersection or difference of two plain object-set descriptions on that ref. A top-level type filter {kind:"type",op:"in",values:["part","system"]} selects any of 1 to 100 published type keys and may be combined with a text filter; continuation binds to the entire selection. ${QUERY_PROJECT_SCOPE}`, [
441
446
  ...REF_READ,
@@ -660,13 +665,6 @@ function deepFreeze(value) {
660
665
  return value;
661
666
  }
662
667
  var BINARY_REQUESTS = {
663
- stageAttachment: {
664
- "contentType": "application/octet-stream",
665
- "selectorHeader": "x-oe2-selector",
666
- "selectorEncoding": "json",
667
- "nameHeader": "x-oe2-attachment-name",
668
- "nameEncoding": "rfc8187"
669
- },
670
668
  publishHostedVersion: {
671
669
  "contentType": "application/octet-stream",
672
670
  "selectorHeader": "x-oe2-selector",
@@ -679,7 +677,8 @@ var BINARY_REQUEST_INPUTS = deepFreeze(BINARY_REQUESTS);
679
677
  var BINARY_RESPONSES = {
680
678
  readAttachment: {
681
679
  "contentType": "attachment",
682
- "headers": "attachmentResponseHeaders"
680
+ "headers": "attachmentResponseHeaders",
681
+ "redirect": "see-other"
683
682
  }
684
683
  };
685
684
  var BINARY_RESPONSE_OUTPUTS = deepFreeze(BINARY_RESPONSES);
@@ -714,6 +713,8 @@ var SCHEMAS = {
714
713
  enterHumanMode: { "type": "object", "properties": {}, "required": [], "additionalProperties": false },
715
714
  readSessionStatus: { "type": "object", "properties": {}, "required": [], "additionalProperties": false },
716
715
  readStepUpProof: { "type": "object", "properties": { "pendingId": { "type": "string" } }, "required": ["pendingId"], "additionalProperties": false },
716
+ openAttachmentUpload: { "type": "object", "properties": { "name": { "type": "string" }, "declaredLength": { "type": "integer" } }, "required": ["name", "declaredLength"], "additionalProperties": false },
717
+ completeAttachmentUpload: { "type": "object", "properties": { "uploadId": { "type": "string" } }, "required": ["uploadId"], "additionalProperties": false },
717
718
  readAttachment: {
718
719
  "type": "object",
719
720
  "properties": {
@@ -918,6 +919,8 @@ var EXAMPLES = {
918
919
  enterHumanMode: {},
919
920
  readSessionStatus: {},
920
921
  readStepUpProof: { "pendingId": "<pendingId>" },
922
+ openAttachmentUpload: { "name": "<name>", "declaredLength": 1 },
923
+ completeAttachmentUpload: { "uploadId": "<uploadId>" },
921
924
  readAttachment: {
922
925
  "objectId": "<objectId>",
923
926
  "property": "<property>"
@@ -1075,7 +1078,7 @@ var ROUTE_INPUT_EXAMPLES = deepFreeze(EXAMPLES);
1075
1078
  var DESCRIPTION_ROUTES = Object.freeze(["queryRows", "queryObjects", "aggregateObjects", "queryGraph", "readStructure", "findPaths"]);
1076
1079
 
1077
1080
  // packages/api-contract/dist/routes.js
1078
- var PROTOCOL_VERSION = 38;
1081
+ var PROTOCOL_VERSION = 39;
1079
1082
  var VERSION_HEADER = "oe2-protocol-version";
1080
1083
  var TOKEN_HEADER = "authorization";
1081
1084
  var IDEMPOTENCY_HEADER = "oe2-idempotency-key";
@@ -1083,7 +1086,9 @@ var STEP_UP_HEADER = "oe2-step-up";
1083
1086
  var STEP_UP_KEY_HEADER = "oe2-step-up-key";
1084
1087
  var IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._~-]{1,128}$/;
1085
1088
  var STREAMED_ROUTE_NAMES = Object.freeze(["sendMessageStreamed", "answerPlanStreamed"]);
1086
- var BINARY_REQUEST_ROUTE_NAMES = Object.freeze(["stageAttachment", "publishHostedVersion"]);
1089
+ var BINARY_REQUEST_ROUTE_NAMES = Object.freeze([
1090
+ "publishHostedVersion"
1091
+ ]);
1087
1092
  var BINARY_RESPONSE_ROUTE_NAMES = Object.freeze(["readAttachment"]);
1088
1093
  function isBinaryRequestRoute(name) {
1089
1094
  return BINARY_REQUEST_ROUTE_NAMES.some((binary) => binary === name);
@@ -1137,7 +1142,8 @@ var STEP_UP_ROUTE_GROUPS = Object.freeze({
1137
1142
  readStepUpProof: "unmarked",
1138
1143
  enterHumanMode: "marked",
1139
1144
  readSessionStatus: "unmarked",
1140
- stageAttachment: "unmarked",
1145
+ openAttachmentUpload: "unmarked",
1146
+ completeAttachmentUpload: "unmarked",
1141
1147
  readAttachment: "unmarked",
1142
1148
  readObject: "unmarked",
1143
1149
  queryObjects: "unmarked",
@@ -1445,10 +1451,23 @@ var ROUTES = Object.freeze({
1445
1451
  module: "sdk-core",
1446
1452
  capability: "core.sessionStatus"
1447
1453
  }),
1448
- stageAttachment: route({
1449
- name: "stageAttachment",
1454
+ openAttachmentUpload: route({
1455
+ name: "openAttachmentUpload",
1456
+ method: "POST",
1457
+ path: "/attachments/upload/open",
1458
+ group: "write",
1459
+ selector: "existingObject",
1460
+ subject: "project",
1461
+ idempotent: false,
1462
+ policy: admittingActors("person", "service", "app:client", "agent:apply"),
1463
+ versioned: true,
1464
+ module: "objects-sdk",
1465
+ capability: "objects.write"
1466
+ }),
1467
+ completeAttachmentUpload: route({
1468
+ name: "completeAttachmentUpload",
1450
1469
  method: "POST",
1451
- path: "/attachments/stage",
1470
+ path: "/attachments/upload/complete",
1452
1471
  group: "write",
1453
1472
  selector: "existingObject",
1454
1473
  subject: "project",
@@ -1916,7 +1935,8 @@ var ROUTE_CARRIES_CREDENTIAL = Object.freeze({
1916
1935
  readStepUpProof: true,
1917
1936
  enterHumanMode: false,
1918
1937
  readSessionStatus: false,
1919
- stageAttachment: false,
1938
+ openAttachmentUpload: true,
1939
+ completeAttachmentUpload: false,
1920
1940
  readAttachment: false,
1921
1941
  readObject: false,
1922
1942
  queryObjects: false,
@@ -2139,10 +2159,10 @@ var CLIENT_SCOPES = Object.freeze({
2139
2159
 
2140
2160
  // packages/api-contract/dist/attachment-headers.js
2141
2161
  var ATTACHMENT_SELECTOR_HEADER = "x-oe2-selector";
2142
- var ATTACHMENT_NAME_HEADER = "x-oe2-attachment-name";
2143
2162
  function attachmentNameHeader(name) {
2144
2163
  return `UTF-8''${encodeURIComponent(name).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)}`;
2145
2164
  }
2165
+ var ATTACHMENT_NAME_HEADER = "x-oe2-attachment-name";
2146
2166
 
2147
2167
  // packages/api-contract/dist/actor-kind-label.js
2148
2168
  var ACTOR_KIND_LABELS = Object.freeze({
@@ -2154,63 +2174,6 @@ var ACTOR_KIND_LABELS = Object.freeze({
2154
2174
  // packages/api-contract/dist/links.js
2155
2175
  var MAX_CLEAR_ENTRIES = 100;
2156
2176
 
2157
- // packages/sdk-dispatch/dist/response.js
2158
- function responseOf(status, body, reason, headers = {}) {
2159
- let read = false;
2160
- const claim = () => {
2161
- if (read)
2162
- throw new Error("the response body has already been read");
2163
- read = true;
2164
- };
2165
- const source = async function* () {
2166
- if (typeof body === "string")
2167
- yield Buffer.from(body, "utf8");
2168
- else if (body instanceof Uint8Array)
2169
- yield body;
2170
- else
2171
- yield* body;
2172
- };
2173
- const members = {
2174
- status,
2175
- ...reason === void 0 || reason === "" ? {} : { reason },
2176
- header: (name) => {
2177
- const entry2 = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase());
2178
- const value = entry2?.[1];
2179
- return value === void 0 ? null : typeof value === "string" || typeof value === "number" ? String(value) : value.join(", ");
2180
- },
2181
- bytes: () => {
2182
- claim();
2183
- let iterated = false;
2184
- return {
2185
- async *[Symbol.asyncIterator]() {
2186
- if (iterated)
2187
- throw new Error("the response body has already been read");
2188
- iterated = true;
2189
- yield* source();
2190
- }
2191
- };
2192
- },
2193
- json: async () => {
2194
- claim();
2195
- const chunks = [];
2196
- for await (const chunk of source())
2197
- chunks.push(chunk);
2198
- const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
2199
- return value;
2200
- }
2201
- };
2202
- return new Proxy(members, {
2203
- get(target, member) {
2204
- if (member === "status" || member === "reason" || member === "json" || member === "header" || member === "bytes") {
2205
- return target[member];
2206
- }
2207
- if (member === "then" || typeof member === "symbol")
2208
- return void 0;
2209
- throw new Error(`the response member ${String(member)} is not implemented`);
2210
- }
2211
- });
2212
- }
2213
-
2214
2177
  // packages/sdk-dispatch/dist/step-up.js
2215
2178
  function stepUpHeaders(route2, attempt) {
2216
2179
  if (!owesStepUp(route2.policy)) {
@@ -2370,6 +2333,65 @@ function unauthenticatedEnvelope() {
2370
2333
 
2371
2334
  // packages/sdk-dispatch/dist/socket-transport.js
2372
2335
  import { request } from "node:http";
2336
+
2337
+ // packages/sdk-dispatch/dist/response.js
2338
+ function responseOf(status, body, reason, headers = {}) {
2339
+ let read = false;
2340
+ const claim = () => {
2341
+ if (read)
2342
+ throw new Error("the response body has already been read");
2343
+ read = true;
2344
+ };
2345
+ const source = async function* () {
2346
+ if (typeof body === "string")
2347
+ yield Buffer.from(body, "utf8");
2348
+ else if (body instanceof Uint8Array)
2349
+ yield body;
2350
+ else
2351
+ yield* body;
2352
+ };
2353
+ const members = {
2354
+ status,
2355
+ ...reason === void 0 || reason === "" ? {} : { reason },
2356
+ header: (name) => {
2357
+ const entry2 = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase());
2358
+ const value = entry2?.[1];
2359
+ return value === void 0 ? null : typeof value === "string" || typeof value === "number" ? String(value) : value.join(", ");
2360
+ },
2361
+ bytes: () => {
2362
+ claim();
2363
+ let iterated = false;
2364
+ return {
2365
+ async *[Symbol.asyncIterator]() {
2366
+ if (iterated)
2367
+ throw new Error("the response body has already been read");
2368
+ iterated = true;
2369
+ yield* source();
2370
+ }
2371
+ };
2372
+ },
2373
+ json: async () => {
2374
+ claim();
2375
+ const chunks = [];
2376
+ for await (const chunk of source())
2377
+ chunks.push(chunk);
2378
+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
2379
+ return value;
2380
+ }
2381
+ };
2382
+ return new Proxy(members, {
2383
+ get(target, member) {
2384
+ if (member === "status" || member === "reason" || member === "json" || member === "header" || member === "bytes") {
2385
+ return target[member];
2386
+ }
2387
+ if (member === "then" || typeof member === "symbol")
2388
+ return void 0;
2389
+ throw new Error(`the response member ${String(member)} is not implemented`);
2390
+ }
2391
+ });
2392
+ }
2393
+
2394
+ // packages/sdk-dispatch/dist/socket-transport.js
2373
2395
  var REQUEST_DEADLINE_MS = 1e4;
2374
2396
  function requestDeadlineOf(path, method, override) {
2375
2397
  if (override !== void 0)
@@ -2411,7 +2433,7 @@ var HostStatusNotEnvelope = class extends Error {
2411
2433
  };
2412
2434
  var INIT_MEMBERS = Object.freeze(["method", "headers", "body", "signal"]);
2413
2435
  function unsupported(member) {
2414
- return new Error(`the socket-bound request function does not implement ${member}`);
2436
+ return new Error(`the request function does not implement ${member}`);
2415
2437
  }
2416
2438
  function isPlainObject2(value) {
2417
2439
  return typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype;
@@ -2542,6 +2564,13 @@ function createHostFetch(socketPath, deadlineMs) {
2542
2564
  };
2543
2565
  }
2544
2566
  function createHostStreamFetch(socketPath, headDeadlineMs = REQUEST_DEADLINE_MS) {
2567
+ return streamFetchOver(headDeadlineMs, (url) => {
2568
+ if (url.protocol !== "http:") {
2569
+ throw unsupported(`the protocol ${url.protocol}`);
2570
+ }
2571
+ }, (url, checked, onResponse) => request({ socketPath, method: checked.method, path: `${url.pathname}${url.search}`, headers: checked.headers }, onResponse));
2572
+ }
2573
+ function streamFetchOver(headDeadlineMs, admit, open2) {
2545
2574
  return async (input, init) => {
2546
2575
  if (typeof input !== "string") {
2547
2576
  throw unsupported("an input that is not a string URL");
@@ -2551,9 +2580,7 @@ function createHostStreamFetch(socketPath, headDeadlineMs = REQUEST_DEADLINE_MS)
2551
2580
  throw unsupported("an input that is not a URL");
2552
2581
  }
2553
2582
  const url = new URL(input);
2554
- if (url.protocol !== "http:") {
2555
- throw unsupported(`the protocol ${url.protocol}`);
2556
- }
2583
+ admit(url);
2557
2584
  const path = `${url.pathname}${url.search}`;
2558
2585
  return new Promise((resolve, reject) => {
2559
2586
  let headSettled = false;
@@ -2565,7 +2592,7 @@ function createHostStreamFetch(socketPath, headDeadlineMs = REQUEST_DEADLINE_MS)
2565
2592
  outgoing.destroy();
2566
2593
  reject(new HostOutcomeUnknown(path, "deadline", `the host did not answer the head of ${path} within the deadline of ${String(headDeadlineMs)} ms`));
2567
2594
  }, headDeadlineMs);
2568
- const outgoing = request({ socketPath, method: checked.method, path, headers: checked.headers }, (incoming) => {
2595
+ const outgoing = open2(url, checked, (incoming) => {
2569
2596
  if (headSettled) {
2570
2597
  return;
2571
2598
  }
@@ -2824,14 +2851,14 @@ async function* callStreamed(transport, origin, route2, body, token, signal) {
2824
2851
  yield JSON.parse(line);
2825
2852
  }
2826
2853
  }
2827
- function attachmentDescriptorOf(response) {
2854
+ function attachmentFactsOf(response, length) {
2828
2855
  const fault = () => new Error("the host answered /attachments/read with invalid attachment headers");
2829
- const sha256 = response.header("x-oe2-attachment-sha256");
2830
- const mediaType = response.header("content-type");
2831
- const length = response.header("content-length");
2856
+ const digest = response.header("x-oe2-attachment-digest");
2857
+ const sha256 = digest === null ? null : /^sha256:([0-9a-f]{64})$/.exec(digest);
2858
+ const md5 = digest === null ? null : /^md5:([0-9a-f]{32})$/.exec(digest);
2832
2859
  const disposition = response.header("content-disposition");
2833
2860
  const encodedName = disposition === null ? null : /;\s*filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1];
2834
- if (sha256 === null || !/^[0-9a-f]{64}$/.test(sha256) || mediaType === null || mediaType.length === 0 || length === null || !/^(0|[1-9][0-9]*)$/.test(length) || !Number.isSafeInteger(Number(length)) || encodedName === null || encodedName === void 0)
2861
+ if (sha256 === null && md5 === null || length === null || !/^(0|[1-9][0-9]*)$/.test(length) || !Number.isSafeInteger(Number(length)) || encodedName === null || encodedName === void 0)
2835
2862
  throw fault();
2836
2863
  let name;
2837
2864
  try {
@@ -2841,13 +2868,94 @@ function attachmentDescriptorOf(response) {
2841
2868
  throw error;
2842
2869
  throw fault();
2843
2870
  }
2844
- return { sha256, name, mediaType, bytes: Number(length) };
2871
+ if (sha256 !== null)
2872
+ return { digest: { algorithm: "sha256", hex: sha256[1] }, bytes: Number(length), name };
2873
+ if (md5 !== null)
2874
+ return { digest: { algorithm: "md5", hex: md5[1] }, bytes: Number(length), name };
2875
+ throw fault();
2845
2876
  }
2846
- async function callAttachment(transport, origin, selector, input, token) {
2877
+ function descriptorOf(facts, mediaType) {
2878
+ const { digest, name, bytes } = facts;
2879
+ return digest.algorithm === "sha256" ? { digest: "sha256", sha256: digest.hex, name, mediaType, bytes } : { digest: "md5", md5: digest.hex, name, mediaType, bytes };
2880
+ }
2881
+ function streamDescriptorOf(response) {
2882
+ const mediaType = response.header("content-type");
2883
+ if (mediaType === null || mediaType.length === 0) {
2884
+ throw new Error("the host answered /attachments/read with invalid attachment headers");
2885
+ }
2886
+ const contentLength = response.header("content-length");
2887
+ return descriptorOf(attachmentFactsOf(response, contentLength === null ? response.header("x-oe2-attachment-bytes") : contentLength), mediaType);
2888
+ }
2889
+ var DEFAULT_ATTACHMENT_DEADLINES = Object.freeze({ headerMs: 12e4, gapMs: 6e4 });
2890
+ async function cancelBody(response) {
2891
+ const iterator = response.bytes()[Symbol.asyncIterator]();
2892
+ try {
2893
+ await iterator.next();
2894
+ } finally {
2895
+ await iterator.return?.();
2896
+ }
2897
+ }
2898
+ async function readWithin(reader, gapMs, controller) {
2899
+ return new Promise((resolve, reject) => {
2900
+ const timer = setTimeout(() => {
2901
+ controller.abort();
2902
+ reject(new Error("the stored file stopped sending"));
2903
+ }, gapMs);
2904
+ reader.read().then((piece) => {
2905
+ clearTimeout(timer);
2906
+ resolve(piece);
2907
+ }, (error) => {
2908
+ clearTimeout(timer);
2909
+ reject(error);
2910
+ });
2911
+ });
2912
+ }
2913
+ async function* storeBytes(body, gapMs, controller) {
2914
+ const reader = body.getReader();
2915
+ try {
2916
+ for (; ; ) {
2917
+ const piece = await readWithin(reader, gapMs, controller);
2918
+ if (piece.done)
2919
+ return;
2920
+ yield piece.value;
2921
+ }
2922
+ } finally {
2923
+ controller.abort();
2924
+ }
2925
+ }
2926
+ async function followLink(href, deadlines) {
2927
+ const controller = new AbortController();
2928
+ const headerTimer = setTimeout(() => controller.abort(), deadlines.headerMs);
2929
+ let redirected;
2930
+ try {
2931
+ redirected = await fetch(href, { redirect: "follow", credentials: "omit", signal: controller.signal });
2932
+ } catch (error) {
2933
+ if (!(error instanceof TypeError) && !controller.signal.aborted)
2934
+ throw error;
2935
+ throw new Error(controller.signal.aborted ? "the stored file did not answer in time" : "the stored file could not be fetched");
2936
+ } finally {
2937
+ clearTimeout(headerTimer);
2938
+ }
2939
+ if (redirected.status !== 200) {
2940
+ controller.abort();
2941
+ throw new Error(`the stored file answered with status ${String(redirected.status)}`);
2942
+ }
2943
+ const mediaType = redirected.headers.get("content-type");
2944
+ if (mediaType === null || mediaType.length === 0) {
2945
+ controller.abort();
2946
+ throw new Error("the stored file answered without a content type");
2947
+ }
2948
+ if (redirected.body === null) {
2949
+ throw new Error("the attachment redirect answered without a body");
2950
+ }
2951
+ return { mediaType, body: storeBytes(redirected.body, deadlines.gapMs, controller) };
2952
+ }
2953
+ async function callAttachment(transport, origin, selector, input, token, options = {}) {
2847
2954
  if (token === null)
2848
2955
  return unauthenticatedEnvelope();
2956
+ const deadlines = options.deadlines === void 0 ? DEFAULT_ATTACHMENT_DEADLINES : options.deadlines;
2849
2957
  const entry2 = ROUTES.readAttachment;
2850
- let response = await transport(`${origin}${entry2.path}`, {
2958
+ const response = await transport(`${origin}${entry2.path}`, {
2851
2959
  method: entry2.method,
2852
2960
  headers: {
2853
2961
  "content-type": "application/json",
@@ -2857,6 +2965,7 @@ async function callAttachment(transport, origin, selector, input, token) {
2857
2965
  body: JSON.stringify({ selector, input })
2858
2966
  });
2859
2967
  if ([302, 303, 307].includes(response.status)) {
2968
+ await cancelBody(response);
2860
2969
  const location = response.header("location");
2861
2970
  if (location === null)
2862
2971
  throw new Error("the host answered /attachments/read with a redirect without Location");
@@ -2864,19 +2973,16 @@ async function callAttachment(transport, origin, selector, input, token) {
2864
2973
  if (target.origin === new URL(origin).origin) {
2865
2974
  throw new Error("the host answered /attachments/read with a same-origin redirect");
2866
2975
  }
2867
- const redirected = await fetch(target.href, {
2868
- redirect: "follow",
2869
- credentials: "omit",
2870
- signal: AbortSignal.timeout(12e4)
2871
- });
2872
- if (redirected.body === null)
2873
- throw new Error("the attachment redirect answered without a body");
2874
- response = responseOf(redirected.status, redirected.body, redirected.statusText, Object.fromEntries(redirected.headers));
2976
+ const facts = attachmentFactsOf(response, response.header("x-oe2-attachment-bytes"));
2977
+ if (options.follow === false) {
2978
+ return { version: PROTOCOL_VERSION, result: { kind: "link", link: target.href, ...facts } };
2979
+ }
2980
+ const stored = await followLink(target.href, deadlines);
2981
+ return { version: PROTOCOL_VERSION, result: { kind: "stream", descriptor: descriptorOf(facts, stored.mediaType), body: stored.body } };
2875
2982
  }
2876
2983
  if (response.status !== 200)
2877
2984
  return explainedEnvelopeOf(await readEnvelope(response, entry2.path));
2878
- const descriptor2 = attachmentDescriptorOf(response);
2879
- return { version: PROTOCOL_VERSION, result: { descriptor: descriptor2, body: response.bytes() } };
2985
+ return { version: PROTOCOL_VERSION, result: { kind: "stream", descriptor: streamDescriptorOf(response), body: response.bytes() } };
2880
2986
  }
2881
2987
 
2882
2988
  // packages/sdk-dispatch/dist/module-factory.js
@@ -2973,7 +3079,7 @@ function createHttpsTransport(origin, options = {}, deadlineMs) {
2973
3079
  });
2974
3080
  };
2975
3081
  const outgoing = request2({
2976
- hostname: url.hostname,
3082
+ hostname: url.hostname.replace(/^\[|\]$/g, ""),
2977
3083
  port: url.port === "" ? 443 : Number(url.port),
2978
3084
  path,
2979
3085
  method: init.method,
@@ -3160,6 +3266,107 @@ function enterHumanMode(transport, origin, token, body, stepUp) {
3160
3266
  return call(transport, origin, "enterHumanMode", body, token, null, stepUp);
3161
3267
  }
3162
3268
 
3269
+ // packages/sdk-dispatch/dist/upload.js
3270
+ var ATTACHMENT_UPLOAD_PIECE_BYTES = 8 * 1024 * 1024;
3271
+ async function uploadPieces(sessionUri, source, fetchStore, onProgress) {
3272
+ if (!Number.isSafeInteger(source.size) || source.size <= 0) {
3273
+ throw new TypeError("an upload needs a positive safe integer size");
3274
+ }
3275
+ const failed = () => new Error("the stored file could not be uploaded");
3276
+ async function put(range, body) {
3277
+ try {
3278
+ const response = await fetchStore(sessionUri, {
3279
+ // Follow exposes a 308 without Location in both Node and browsers; manual hides it in browsers.
3280
+ method: "PUT",
3281
+ credentials: "omit",
3282
+ redirect: "follow",
3283
+ headers: { "Content-Range": range },
3284
+ ...body === void 0 ? {} : { body: new Uint8Array(body) }
3285
+ });
3286
+ await response.body?.cancel();
3287
+ if (response.redirected)
3288
+ throw failed();
3289
+ return response;
3290
+ } catch (error) {
3291
+ if (!(error instanceof TypeError))
3292
+ throw failed();
3293
+ return null;
3294
+ }
3295
+ }
3296
+ async function read(offset2, end) {
3297
+ const piece = await source.read(offset2, end - offset2);
3298
+ if (piece.byteLength !== end - offset2)
3299
+ throw new Error("the upload source returned an incorrect piece length");
3300
+ return piece;
3301
+ }
3302
+ let offset = 0;
3303
+ let reported = 0;
3304
+ const pending = /* @__PURE__ */ new Map();
3305
+ while (offset < source.size) {
3306
+ const end = Math.min(offset + ATTACHMENT_UPLOAD_PIECE_BYTES, source.size);
3307
+ for (let ahead = offset; ahead < Math.min(end + ATTACHMENT_UPLOAD_PIECE_BYTES, source.size); ahead += ATTACHMENT_UPLOAD_PIECE_BYTES) {
3308
+ if (!pending.has(ahead)) {
3309
+ const piece2 = read(ahead, Math.min(ahead + ATTACHMENT_UPLOAD_PIECE_BYTES, source.size)).then((bytes) => ({ bytes }), (error) => ({ error }));
3310
+ pending.set(ahead, piece2);
3311
+ }
3312
+ }
3313
+ const ready = await pending.get(offset);
3314
+ pending.delete(offset);
3315
+ if ("error" in ready)
3316
+ throw ready.error;
3317
+ let piece = ready.bytes;
3318
+ let resumes = 0;
3319
+ while (offset < end) {
3320
+ const response = await put(`bytes ${String(offset)}-${String(end - 1)}/${String(source.size)}`, piece);
3321
+ let status = response;
3322
+ if (status === null || status.status >= 500) {
3323
+ if (resumes === 3)
3324
+ throw failed();
3325
+ resumes++;
3326
+ status = await put(`bytes */${String(source.size)}`);
3327
+ while (status === null || status.status >= 500) {
3328
+ if (resumes === 3)
3329
+ throw failed();
3330
+ resumes++;
3331
+ status = await put(`bytes */${String(source.size)}`);
3332
+ }
3333
+ if (status.status === 200 || status.status === 201) {
3334
+ offset = source.size;
3335
+ break;
3336
+ }
3337
+ if (status.status !== 308)
3338
+ throw failed();
3339
+ } else {
3340
+ if (end === source.size && (status.status === 200 || status.status === 201)) {
3341
+ offset = end;
3342
+ break;
3343
+ }
3344
+ if (status.status !== 308) {
3345
+ throw new Error(`the stored file answered with status ${String(status.status)}`);
3346
+ }
3347
+ }
3348
+ const range = status.headers.get("Range");
3349
+ const matched = range === null ? null : /^bytes=0-(\d+)$/.exec(range);
3350
+ if (range !== null && matched === null)
3351
+ throw failed();
3352
+ const committed = matched === null ? 0 : Number(matched[1]) + 1;
3353
+ if (!Number.isSafeInteger(committed) || committed < offset || committed > end)
3354
+ throw failed();
3355
+ if (status === response && committed === offset) {
3356
+ if (resumes === 3)
3357
+ throw failed();
3358
+ resumes++;
3359
+ }
3360
+ offset = committed;
3361
+ if (offset < end)
3362
+ piece = await read(offset, end);
3363
+ }
3364
+ for (; reported < offset; reported = Math.min(reported + ATTACHMENT_UPLOAD_PIECE_BYTES, source.size)) {
3365
+ onProgress?.(Math.min(reported + ATTACHMENT_UPLOAD_PIECE_BYTES, source.size), source.size);
3366
+ }
3367
+ }
3368
+ }
3369
+
3163
3370
  // packages/sdk-core/dist/index.js
3164
3371
  var SDK_CORE_ROUTE_ENTRIES = routeEntriesOf("sdk-core");
3165
3372
 
@@ -3502,10 +3709,28 @@ function displayPropertyValue(value, definition) {
3502
3709
  return JSON.stringify(value);
3503
3710
  }
3504
3711
 
3712
+ // packages/objects-sdk/dist/upload.js
3713
+ async function uploadAttachment(transport, origin, token, selector, source, options) {
3714
+ const opened = await call(transport, origin, "openAttachmentUpload", {
3715
+ selector,
3716
+ input: { name: source.name, declaredLength: source.size }
3717
+ }, token, null);
3718
+ if ("refusal" in opened)
3719
+ return opened;
3720
+ if (opened.replayed === true)
3721
+ throw new Error("the host replayed an upload open");
3722
+ await uploadPieces(opened.result.sessionUri, source, fetch, options?.onProgress);
3723
+ return call(transport, origin, "completeAttachmentUpload", {
3724
+ selector,
3725
+ input: { uploadId: opened.result.uploadId }
3726
+ }, token, null);
3727
+ }
3728
+
3505
3729
  // packages/objects-sdk/dist/transport-client.js
3506
3730
  var OBJECTS_ROUTE_ENTRIES = routeEntriesOf("objects-sdk");
3507
3731
  var OBJECTS_ROUTE_NAMES = [
3508
- "stageAttachment",
3732
+ "openAttachmentUpload",
3733
+ "completeAttachmentUpload",
3509
3734
  "readAttachment",
3510
3735
  "createObjectSet",
3511
3736
  "listObjectSets",
@@ -3556,15 +3781,13 @@ function entries4() {
3556
3781
  return JSON_OBJECTS_ROUTE_NAMES.map((name) => ROUTES[name]);
3557
3782
  }
3558
3783
  function createObjectsTransportClient(transport, origin, token) {
3784
+ function readAttachment(selector, input, options) {
3785
+ return options === void 0 ? callAttachment(transport, origin, selector, input, token) : callAttachment(transport, origin, selector, input, token, options);
3786
+ }
3559
3787
  return Object.freeze({
3560
3788
  ...createTypedClient(JSON_OBJECTS_ROUTE_NAMES, entries4(), transport, origin, token),
3561
- readAttachment: (selector, input) => callAttachment(transport, origin, selector, input, token),
3562
- stageAttachment: (selector, file) => call(transport, origin, "stageAttachment", {
3563
- selector,
3564
- input: { name: file.name, body: (async function* () {
3565
- yield file.bytes;
3566
- })() }
3567
- }, token, null)
3789
+ readAttachment,
3790
+ uploadAttachment: (selector, source, options) => uploadAttachment(transport, origin, token, selector, source, options)
3568
3791
  });
3569
3792
  }
3570
3793
 
@@ -3771,7 +3994,7 @@ function walk(schema, value, path, violations, ownerProperties) {
3771
3994
  return;
3772
3995
  }
3773
3996
  case "attachment": {
3774
- if (!isAttachmentDescriptor(value))
3997
+ if (!isAttachmentWireDescriptor(value))
3775
3998
  violations.push({ path, rule: "invalid-attachment" });
3776
3999
  return;
3777
4000
  }
@@ -3923,14 +4146,25 @@ function checkBoundReference(reference, count, path, violations, ownerProperties
3923
4146
  violations.push({ path: [...path, "value"], rule: "count-bound-unit" });
3924
4147
  }
3925
4148
  }
3926
- function isAttachmentDescriptor(value) {
3927
- if (typeof value !== "object" || value === null || Array.isArray(value) || !("sha256" in value) || !("name" in value) || !("mediaType" in value) || !("bytes" in value))
4149
+ function isAttachmentWireDescriptor(value) {
4150
+ if (!isRecord(value) || Object.keys(value).length !== 5 || !["digest", "name", "mediaType", "bytes"].every((key) => Object.hasOwn(value, key)))
3928
4151
  return false;
3929
- if (Object.keys(value).length !== 4 || !["sha256", "name", "mediaType", "bytes"].every((key) => Object.hasOwn(value, key)) || typeof value.sha256 !== "string" || value.sha256.length !== 64 || !/^[a-f0-9]{64}$/.test(value.sha256) || typeof value.name !== "string" || value.name.length < 1 || value.name.length > 255 || value.name.startsWith(".") || hasForbiddenNameCharacter(value.name) || typeof value.mediaType !== "string" || typeof value.bytes !== "number" || !Number.isSafeInteger(value.bytes) || value.bytes <= 0 || value.bytes > 26214400)
4152
+ if (value.digest === "sha256") {
4153
+ if (!Object.hasOwn(value, "sha256") || typeof value.sha256 !== "string" || value.sha256.length !== 64 || !/^[a-f0-9]{64}$/.test(value.sha256))
4154
+ return false;
4155
+ } else if (value.digest === "md5") {
4156
+ if (!Object.hasOwn(value, "md5") || typeof value.md5 !== "string" || value.md5.length !== 32 || !/^[a-f0-9]{32}$/.test(value.md5))
4157
+ return false;
4158
+ } else
4159
+ return false;
4160
+ if (typeof value.name !== "string" || !attachmentNameRuleHolds(value.name) || typeof value.mediaType !== "string" || typeof value.bytes !== "number" || !Number.isSafeInteger(value.bytes) || value.bytes <= 0)
3930
4161
  return false;
3931
4162
  const name = value.name.toLowerCase();
3932
4163
  return Object.values(ATTACHMENT_CLASSES).some((formats) => formats.some((format) => format.mediaType === value.mediaType && format.extensions.some((extension) => name.endsWith(extension))));
3933
4164
  }
4165
+ function attachmentNameRuleHolds(name) {
4166
+ return name.length >= 1 && name.length <= 255 && !name.startsWith(".") && !hasForbiddenNameCharacter(name);
4167
+ }
3934
4168
  function hasForbiddenNameCharacter(name) {
3935
4169
  for (let index = 0; index < name.length; index++) {
3936
4170
  const code = name.charCodeAt(index);
@@ -4602,6 +4836,15 @@ var VERB_TEMPLATE = deepFreeze3({
4602
4836
  }
4603
4837
  });
4604
4838
 
4839
+ // packages/schema-language/dist/attachment-viewer-limits.js
4840
+ var ATTACHMENT_VIEWER_LIMITS = Object.freeze({
4841
+ image: 52428800,
4842
+ pdf: 104857600,
4843
+ mesh: 67108864,
4844
+ step: 33554432,
4845
+ text: 33554432
4846
+ });
4847
+
4605
4848
  // packages/objects-sdk/dist/validation.js
4606
4849
  function validateLocally(schema, languageVersion, value, category) {
4607
4850
  const checked = validateSchema(schema, languageVersion, category);
@@ -5780,11 +6023,11 @@ var createFileStore = (configDirectory) => {
5780
6023
  try {
5781
6024
  mkdirSync(directory, { recursive: true, mode: 448 });
5782
6025
  chmodSync(directory, 448);
5783
- const descriptor2 = openSync(temporary, "wx", 384);
6026
+ const descriptor = openSync(temporary, "wx", 384);
5784
6027
  try {
5785
- writeSync(descriptor2, secretOf(hostKey, session, organisation));
6028
+ writeSync(descriptor, secretOf(hostKey, session, organisation));
5786
6029
  } finally {
5787
- closeSync(descriptor2);
6030
+ closeSync(descriptor);
5788
6031
  }
5789
6032
  renameSync(temporary, final);
5790
6033
  } catch (error) {
@@ -5828,6 +6071,8 @@ var storedSummary = async (store, hostKey) => {
5828
6071
  };
5829
6072
 
5830
6073
  // packages/cli/src/host-binding.ts
6074
+ var DEFAULT_HOST = "https://api.openeng.io";
6075
+ var resolveHostSetting = (flag, environment) => flag ?? environment ?? DEFAULT_HOST;
5831
6076
  var UNIX_PREFIX = "unix:";
5832
6077
  var LOOPBACK_HOSTNAMES = ["127.0.0.1", "[::1]"];
5833
6078
  var parseHost = (host, signInOrigin) => {
@@ -6164,11 +6409,11 @@ async function takeLock(path, deps) {
6164
6409
  let unreadableSince = null;
6165
6410
  for (; ; ) {
6166
6411
  try {
6167
- const descriptor2 = openSync2(path, "wx", 384);
6412
+ const descriptor = openSync2(path, "wx", 384);
6168
6413
  try {
6169
- writeSync2(descriptor2, text);
6414
+ writeSync2(descriptor, text);
6170
6415
  } finally {
6171
- closeSync2(descriptor2);
6416
+ closeSync2(descriptor);
6172
6417
  }
6173
6418
  return () => {
6174
6419
  if (readLockText(path) === text) {
@@ -6808,8 +7053,8 @@ var resolveAliases = (words) => {
6808
7053
  return group === void 0 ? words : [group, ...rest];
6809
7054
  };
6810
7055
  var HOST_GUIDANCE = [
6811
- "production host: https://api.openeng.io",
6812
- "openeng has no default host: use --host or set OPENENG_HOST=https://api.openeng.io",
7056
+ "default host: https://api.openeng.io",
7057
+ "to use another host: --host <origin>, or set OPENENG_HOST=<origin>",
6813
7058
  "agents: start with openeng skill, which prints how to work with the platform."
6814
7059
  ];
6815
7060
  function wrapped(names) {
@@ -13467,7 +13712,8 @@ var typesDraftAccept = {
13467
13712
 
13468
13713
  // packages/cli/src/commands/attachment.ts
13469
13714
  import { createHash as createHash3, randomUUID as randomUUID5 } from "node:crypto";
13470
- import { readFileSync as readFileSync6, writeFileSync } from "node:fs";
13715
+ import { renameSync as renameSync2, rmSync } from "node:fs";
13716
+ import { open } from "node:fs/promises";
13471
13717
  import { basename } from "node:path";
13472
13718
  var usageAdd = "openeng attachment add <object> <property> <file> --project <id> --ref <ref>";
13473
13719
  var usageGet = "openeng attachment get <object> <property> [--out <path>] --project <id> --ref <ref>";
@@ -13492,18 +13738,57 @@ function isSelector(value) {
13492
13738
  function isRecord4(value) {
13493
13739
  return typeof value === "object" && value !== null && !Array.isArray(value);
13494
13740
  }
13495
- function descriptor(value) {
13496
- return isRecord4(value) && typeof value.sha256 === "string" && typeof value.name === "string" && typeof value.mediaType === "string" && typeof value.bytes === "number";
13741
+ async function writeAll(file, chunk) {
13742
+ let offset = 0;
13743
+ while (offset < chunk.byteLength) {
13744
+ const { bytesWritten } = await file.write(chunk, offset, chunk.byteLength - offset);
13745
+ if (bytesWritten === 0) throw new Error("the file system accepted no bytes of the download");
13746
+ offset += bytesWritten;
13747
+ }
13748
+ }
13749
+ var SHA256_HEX = /^[0-9a-f]{64}$/;
13750
+ var MD5_HEX = /^[0-9a-f]{32}$/;
13751
+ function wireDescriptor(value) {
13752
+ if (!isRecord4(value) || typeof value.name !== "string" || typeof value.mediaType !== "string" || typeof value.bytes !== "number" || !Number.isSafeInteger(value.bytes) || value.bytes < 0) return null;
13753
+ const { name, mediaType, bytes } = value;
13754
+ const digest = Object.hasOwn(value, "digest") ? value.digest : "sha256";
13755
+ if (digest === "sha256" && typeof value.sha256 === "string" && SHA256_HEX.test(value.sha256)) {
13756
+ return { digest, sha256: value.sha256, name, mediaType, bytes };
13757
+ }
13758
+ if (digest === "md5" && typeof value.md5 === "string" && MD5_HEX.test(value.md5)) {
13759
+ return { digest, md5: value.md5, name, mediaType, bytes };
13760
+ }
13761
+ return null;
13497
13762
  }
13498
13763
  async function saveDescriptor(context, selector, objectId, property, file) {
13499
- const bytes = new Uint8Array(readFileSync6(file));
13500
13764
  const name = basename(file);
13501
13765
  const settle2 = `openeng attachment get ${objectId} ${property} --project ${selector.projectId} --ref ${selector.ref}`;
13502
13766
  const run2 = await runAuthenticated(context.host, context.deps, async (clients) => {
13503
13767
  const object = await clients.objects.readObject({ selector, input: { objectId } });
13504
13768
  if ("refusal" in object) return { outcome: outcomeOfEnvelope(object, settle2, (value2) => JSON.stringify(value2)) };
13505
13769
  if (object.replayed === true) return { outcome: outcomeOfEnvelope(object, settle2, (value2) => JSON.stringify(value2)) };
13506
- const staged = await clients.objects.stageAttachment({ ...selector, objectId }, { name, bytes });
13770
+ const handle = await open(file, "r");
13771
+ const staged = await (async () => {
13772
+ try {
13773
+ const { size } = await handle.stat();
13774
+ return await clients.objects.uploadAttachment({ ...selector, objectId }, {
13775
+ name,
13776
+ size,
13777
+ read: async (offset, length) => {
13778
+ const bytes = new Uint8Array(length);
13779
+ let read = 0;
13780
+ while (read < length) {
13781
+ const { bytesRead } = await handle.read(bytes, read, length - read, offset + read);
13782
+ if (bytesRead === 0) throw new Error("the upload file ended before its declared size");
13783
+ read += bytesRead;
13784
+ }
13785
+ return bytes;
13786
+ }
13787
+ }, { onProgress: (committed, total) => context.note(`uploaded ${committed}/${total} bytes`) });
13788
+ } finally {
13789
+ await handle.close();
13790
+ }
13791
+ })();
13507
13792
  if ("refusal" in staged) return { outcome: outcomeOfEnvelope(staged, settle2, (value2) => JSON.stringify(value2)) };
13508
13793
  if (staged.replayed === true) return { outcome: outcomeOfEnvelope(staged, settle2, (value2) => JSON.stringify(value2)) };
13509
13794
  const catalogue = await clients.objects.readCatalogue({ selector: { projectId: selector.projectId }, input: {} });
@@ -13590,16 +13875,42 @@ var attachmentGet = {
13590
13875
  const answer = await clients.objects.readAttachment(selector, { objectId, property });
13591
13876
  if ("refusal" in answer) return { outcome: outcomeOfEnvelope(answer, settle2, (value) => JSON.stringify(value)) };
13592
13877
  if (answer.replayed === true) return { outcome: outcomeOfEnvelope(answer, settle2, (value) => JSON.stringify(value)) };
13593
- const chunks = [];
13594
- for await (const chunk of answer.result.body) chunks.push(chunk);
13595
- const bytes = Buffer.concat(chunks);
13596
- const digest = createHash3("sha256").update(bytes).digest("hex");
13597
- if (digest !== answer.result.descriptor.sha256) {
13598
- const outcome2 = { kind: "internal-failure", message: "the downloaded attachment did not match its descriptor's SHA-256" };
13599
- return { outcome: outcome2 };
13600
- }
13601
- const path = context.options.out ?? answer.result.descriptor.name;
13602
- writeFileSync(path, bytes);
13878
+ const stored = answer.result.descriptor;
13879
+ const algorithm = stored.digest === "sha256" ? "SHA-256" : "MD5";
13880
+ const expected = stored.digest === "sha256" ? stored.sha256 : stored.md5;
13881
+ const hash = createHash3(stored.digest);
13882
+ const path = context.options.out ?? stored.name;
13883
+ const partial = `${path}.part`;
13884
+ const file = await open(partial, "w");
13885
+ let finished = false;
13886
+ try {
13887
+ let committed = 0;
13888
+ let failure2 = null;
13889
+ try {
13890
+ for await (const chunk of answer.result.body) {
13891
+ hash.update(chunk);
13892
+ await writeAll(file, chunk);
13893
+ committed += chunk.byteLength;
13894
+ context.note(`downloaded ${committed}/${stored.bytes} bytes`);
13895
+ }
13896
+ } catch (error) {
13897
+ failure2 = { error };
13898
+ }
13899
+ try {
13900
+ await file.close();
13901
+ } catch (error) {
13902
+ failure2 ??= { error };
13903
+ }
13904
+ if (failure2 !== null) throw failure2.error;
13905
+ if (hash.digest("hex") !== expected) {
13906
+ const outcome2 = { kind: "internal-failure", message: `the downloaded attachment did not match its descriptor's ${algorithm}` };
13907
+ return { outcome: outcome2 };
13908
+ }
13909
+ renameSync2(partial, path);
13910
+ finished = true;
13911
+ } finally {
13912
+ if (!finished) rmSync(partial, { force: true });
13913
+ }
13603
13914
  const outcome = { kind: "success", value: { path }, text: path };
13604
13915
  return { outcome };
13605
13916
  });
@@ -13613,8 +13924,8 @@ function attachmentProperties(object, propertyDefinitions) {
13613
13924
  const entries7 = Object.entries(propertyDefinitions).flatMap(([property, definition]) => {
13614
13925
  if (!isRecord4(definition) || definition.kind !== "attachment") return [];
13615
13926
  const stored = properties[property];
13616
- if (!isRecord4(stored) || !descriptor(stored.value)) return [];
13617
- return [{ property, descriptor: stored.value }];
13927
+ const read = isRecord4(stored) ? wireDescriptor(stored.value) : null;
13928
+ return read === null ? [] : [{ property, descriptor: read }];
13618
13929
  });
13619
13930
  return { ok: true, entries: entries7 };
13620
13931
  }
@@ -13792,7 +14103,7 @@ var branchesImpact = {
13792
14103
  };
13793
14104
 
13794
14105
  // packages/cli/src/commands/hosted-app.ts
13795
- import { readFileSync as readFileSync7 } from "node:fs";
14106
+ import { readFileSync as readFileSync6 } from "node:fs";
13796
14107
  var ONE_WALL_WARNING_LEAD = "Reduced isolation lets an app use React in the normal way, so agents can build better apps. One browser feature, WebRTC, cannot be blocked which creates a security risk if used by a hosted app.";
13797
14108
  var ONE_WALL_WARNING_DETAIL = "WebRTC lets a web page connect directly to other computers on the internet, for example for video calls. An app with reduced isolation could use WebRTC to send data out of the viewer's browser. The app runs with the access of each person who opens it, so this data could be anything that person can read. Use of WebRTC in an app with reduced isolation is a security risk. Review the app's code for WebRTC use before you allow it, and again for each new version. A coding agent can do the review. If you remove this permission, the app stops at its next request, but data it already read cannot be recalled.";
13798
14109
  var ONE_WALL_WARNING = `${ONE_WALL_WARNING_LEAD}
@@ -13841,7 +14152,7 @@ var hostedAppPublish = {
13841
14152
  if (isOutcome2(file)) return file;
13842
14153
  const key = context.options.key;
13843
14154
  if (key === void 0 || key === "") return invalid2(`openeng hosted-app publish needs --key <app key>; usage: ${usagePublish}`);
13844
- const bytes = new Uint8Array(readFileSync7(file));
14155
+ const bytes = new Uint8Array(readFileSync6(file));
13845
14156
  const settle2 = `openeng hosted-app versions ${key} --project ${project}, which only reads; publish again only if the version is absent`;
13846
14157
  const run2 = await runAuthenticated(context.host, context.deps, async (clients) => {
13847
14158
  const found = await appOfKey(clients, project, key, settle2);
@@ -13966,7 +14277,7 @@ var loginCommand = {
13966
14277
  help: [
13967
14278
  "openeng login [--no-open]",
13968
14279
  "does: signs the person in through the browser and stores the session; --no-open prints the sign-in address instead of opening it",
13969
- "example: openeng login --host https://api.openeng.io",
14280
+ "example: openeng login",
13970
14281
  "output: one line naming the principal, the host, the store and the expiry; under --json an object with principalId, hostKey, store and expiresAt",
13971
14282
  ...HOST_GUIDANCE
13972
14283
  ],
@@ -14075,7 +14386,7 @@ var PUBLIC_COMMANDS = [
14075
14386
 
14076
14387
  // packages/cli/src/main.ts
14077
14388
  import { spawn } from "node:child_process";
14078
- import { readFileSync as readFileSync9 } from "node:fs";
14389
+ import { readFileSync as readFileSync8 } from "node:fs";
14079
14390
  import { homedir } from "node:os";
14080
14391
  import { parseArgs } from "node:util";
14081
14392
 
@@ -14149,7 +14460,7 @@ var createTransport = (host) => host.kind === "unix" ? createHostFetch(host.sock
14149
14460
 
14150
14461
  // packages/cli/src/update-check.ts
14151
14462
  import { randomUUID as randomUUID7 } from "node:crypto";
14152
- import { existsSync, mkdirSync as mkdirSync3, readFileSync as readFileSync8, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync2 } from "node:fs";
14463
+ import { existsSync, mkdirSync as mkdirSync3, readFileSync as readFileSync7, renameSync as renameSync3, unlinkSync as unlinkSync3, writeFileSync } from "node:fs";
14153
14464
  import { join as join4 } from "node:path";
14154
14465
  function versionParts(value) {
14155
14466
  if (typeof value !== "string" || !/^\d+\.\d+\.\d+$/.test(value)) {
@@ -14162,7 +14473,7 @@ function readCache(file) {
14162
14473
  if (!existsSync(file)) {
14163
14474
  return null;
14164
14475
  }
14165
- const value = JSON.parse(readFileSync8(file, "utf8"));
14476
+ const value = JSON.parse(readFileSync7(file, "utf8"));
14166
14477
  if (typeof value !== "object" || value === null || !("latest" in value) || !("checkedAt" in value)) {
14167
14478
  return null;
14168
14479
  }
@@ -14195,8 +14506,8 @@ function writeCache(directory, file, cache) {
14195
14506
  mkdirSync3(directory, { recursive: true, mode: 448 });
14196
14507
  const temporary = `${file}.${randomUUID7()}.tmp`;
14197
14508
  try {
14198
- writeFileSync2(temporary, JSON.stringify(cache), { flag: "wx", mode: 384 });
14199
- renameSync2(temporary, file);
14509
+ writeFileSync(temporary, JSON.stringify(cache), { flag: "wx", mode: 384 });
14510
+ renameSync3(temporary, file);
14200
14511
  } finally {
14201
14512
  if (existsSync(temporary)) {
14202
14513
  unlinkSync3(temporary);
@@ -14418,7 +14729,7 @@ ${usageLines(commands).join("\n")}` : unknownCommandMessage(commands, invocation
14418
14729
  return { outcome: await command.run(invocation.words.slice(command.words.length)), json: options.json, scope: null };
14419
14730
  }
14420
14731
  const environment = readEnvironment();
14421
- const parsedHost = parseHost(invocation.host ?? environment.OPENENG_HOST, invocation.signInOrigin ?? environment.OPENENG_SIGN_IN_ORIGIN);
14732
+ const parsedHost = parseHost(resolveHostSetting(invocation.host, environment.OPENENG_HOST), invocation.signInOrigin ?? environment.OPENENG_SIGN_IN_ORIGIN);
14422
14733
  if (!parsedHost.ok) {
14423
14734
  return { outcome: outcomeOfHostRefusal(parsedHost.refusal), json: options.json, scope: null };
14424
14735
  }
@@ -14460,7 +14771,7 @@ ${usageLines(commands).join("\n")}` : unknownCommandMessage(commands, invocation
14460
14771
  deps,
14461
14772
  options,
14462
14773
  args: invocation.words.slice(command.words.length),
14463
- readStandardInput: () => readFileSync9(0, "utf8"),
14774
+ readStandardInput: () => readFileSync8(0, "utf8"),
14464
14775
  promptSecret,
14465
14776
  writeLine: (line) => process.stdout.write(`${line}
14466
14777
  `),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openengio/cli",
3
- "version": "0.38.0",
3
+ "version": "0.39.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {
@@ -238,7 +238,7 @@ classes: adding a class is compatible; removing one or changing the property's k
238
238
  The accepted classes are `image` (`.png`, `.jpg`, `.jpeg`, `.webp`, `.gif`), `pdf` (`.pdf`),
239
239
  `step` (`.step`, `.stp`), `mesh` (`.stl`) and `text` (`.txt`, `.md`, `.csv`, `.json`, `.yaml`,
240
240
  `.yml`, `.toml`, `.ini`, `.log`, `.xml`, `.ts`, `.tsx`, `.js`, `.py`, `.c`, `.h`, `.cpp`, `.hpp`,
241
- `.rs`, `.go`, `.java`, `.m`, `.sql`, `.sh`). The maximum file body is 26,214,400 bytes (25 MiB).
241
+ `.rs`, `.go`, `.java`, `.m`, `.sql`, `.sh`). Choose a file within the per-file limit (1 GiB in production).
242
242
  Use `openeng attachment add <object> <property> <file> --project <id> --ref <ref>` to attach a
243
243
  file, `openeng attachment list <object> --project <id> --ref <ref>` to list attachment properties,
244
244
  and `openeng attachment get <object> <property> [--out <path>] --project <id> --ref <ref>` to save
@@ -63,15 +63,27 @@ that step; do not construct a page address yourself. For example:
63
63
 
64
64
  ## Attachments
65
65
 
66
- Create the object first, then stage and save its attachment. Creation with a file is refused
66
+ Create the object first, then upload and save its attachment. Creation with a file is refused
67
67
  as `invalid-properties` with `attachment-requires-object` at each offending property.
68
68
 
69
+ The CLI and SDK upload file bytes directly to the file store in 8 MiB pieces, with at most
70
+ one following piece prefetched. Interrupted uploads query the committed offset and resume within
71
+ the same call, with at most three resumes per piece. The CLI prints upload and download progress
72
+ to standard error. The SDK accepts `{ onProgress: (committed, total) => void }` as the third
73
+ argument of `uploadAttachment(selector, source, options)`. An open refused as `storage-limit-reached` sends no
74
+ file bytes.
75
+ The upload uses `openAttachmentUpload` (`POST /attachments/upload/open`) and
76
+ `completeAttachmentUpload` (`POST /attachments/upload/complete`). `too-large` means the declared
77
+ file exceeds the host bound; `unsupported-content` means the extension or recognised content is
78
+ not admitted. `upload-not-found` means completion found no upload for this caller and object project;
79
+ start the upload again. These refusals are printed through the ordinary CLI refusal output.
80
+
69
81
  For a top-level object property declared with kind `attachment`, use
70
- `openeng attachment add <object> <property> <file> --project <id> --ref <ref>` to stage a file and
82
+ `openeng attachment add <object> <property> <file> --project <id> --ref <ref>` to upload a file and
71
83
  save its descriptor, `openeng attachment list <object> --project <id> --ref <ref>` to read its
72
84
  attachment properties, and `openeng attachment get <object> <property> [--out <path>]` with the
73
85
  project and ref flags to download it. The `get` command uses the descriptor's file name when `--out`
74
- is omitted. The accepted classes and file-size limit are in `openeng skill conventions`.
86
+ is omitted, writes the file as it arrives, and checks it against the descriptor's digest (SHA-256 or MD5), keeping no partial file on a mismatch. The accepted classes and file-size limit are in `openeng skill conventions`.
75
87
 
76
88
  ## Link review and impact
77
89
 
@@ -145,11 +157,11 @@ person asks. Hosted apps run only in Google Chrome.
145
157
  - `openeng help` lists every command. `openeng help <command words>` prints one command's help: what it
146
158
  does and an example. `openeng help <group>` lists a group's commands.
147
159
  `openeng --version` prints the published version.
148
- - `openeng` has no host built in. The production host is `https://api.openeng.io`: pass
149
- `--host https://api.openeng.io` on every command, or prefix it as
150
- `OPENENG_HOST=https://api.openeng.io openeng ...`. An export in `~/.zshrc` does not reach
151
- an agent's shell or a Claude Code `!` shell. In zsh, persist it in `~/.zshenv`.
152
- Fix `no-host` by adding the flag or prefix.
160
+ - `openeng` defaults to `https://api.openeng.io`; no host setting is needed for production.
161
+ For another deployment, pass `--host <origin>` or prefix the command as
162
+ `OPENENG_HOST=<origin> openeng ...`. An export in `~/.zshrc` does not reach
163
+ an agent's shell or a Claude Code `!` shell. In zsh, persist the override in `~/.zshenv`.
164
+ An explicitly empty host turns the default off and causes `no-host`.
153
165
  - `openeng orgs list` and `openeng organisations list` mean `openeng org list`; `openeng project list` means
154
166
  `openeng projects list`.
155
167
  - A mutation or a branch command that needs a `correlation` mints it for you when your input has
@@ -355,7 +367,7 @@ the confirmed write and replace the placeholders below. One start address and on
355
367
  read that object's connections, including the edges in the answer:
356
368
 
357
369
  ```sh
358
- openeng objects-sdk queryGraph --host https://api.openeng.io --selector '{"projectId":"<project-id>","ref":"<project-id>/<branch>"}' --input '{"kind":"graph","start":{"kind":"objects","objects":[{"projectId":"<project-id>","objectId":"<object-id>"}]},"steps":[{"depth":1}]}' --json
370
+ openeng objects-sdk queryGraph --selector '{"projectId":"<project-id>","ref":"<project-id>/<branch>"}' --input '{"kind":"graph","start":{"kind":"objects","objects":[{"projectId":"<project-id>","objectId":"<object-id>"}]},"steps":[{"depth":1}]}' --json
359
371
  ```
360
372
 
361
373
  Check the returned hops against the relationships you wrote. Use `findPaths` for paths across