maka-agent 0.2.1-dev.83.20261014 → 0.2.1-dev.85.20261014

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.
Files changed (37) hide show
  1. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  2. package/node_modules/@maka/core/dist/image-delivery.js +83 -0
  3. package/node_modules/@maka/core/dist/image-markdown.js +44 -0
  4. package/node_modules/@maka/core/package.json +4 -1
  5. package/node_modules/@maka/runtime/dist/computer-use-tools.js +2 -0
  6. package/node_modules/@maka/runtime/dist/filesystem-executor.js +2 -0
  7. package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +7 -3
  8. package/node_modules/@maka/runtime/dist/filesystem-worker/protocol.js +6 -4
  9. package/node_modules/@maka/runtime/dist/image-file-reader.js +83 -0
  10. package/node_modules/@maka/runtime/dist/image-file.js +43 -10
  11. package/node_modules/@maka/runtime/dist/network/public-network-policy.js +97 -0
  12. package/node_modules/@maka/runtime/dist/network/scoped-fetch-transport.js +57 -4
  13. package/node_modules/@maka/runtime/dist/system-prompt/main-session-prompt.js +3 -0
  14. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.mjs +69 -12
  15. package/node_modules/@maka/runtime/dist/workspace-executor.js +3 -3
  16. package/node_modules/@maka/runtime/package.json +2 -0
  17. package/node_modules/@maka/runtime-host/dist/protocol/artifact.js +2 -0
  18. package/node_modules/@maka/runtime-host/dist/protocol/image-delivery.js +70 -0
  19. package/node_modules/@maka/runtime-host/dist/protocol/index.js +4 -1
  20. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  21. package/node_modules/@maka/runtime-host/dist/server/artifact-coordinator.js +10 -1
  22. package/node_modules/@maka/runtime-host/dist/server/chat-image-artifact.js +41 -0
  23. package/node_modules/@maka/runtime-host/dist/server/chat-image-delivery.js +232 -0
  24. package/node_modules/@maka/runtime-host/dist/server/chat-image-markdown.js +26 -0
  25. package/node_modules/@maka/runtime-host/dist/server/chat-image-source.js +121 -0
  26. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +67 -2
  27. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +11 -1
  28. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +3 -0
  29. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +40 -0
  30. package/node_modules/@maka/storage/dist/artifact-image-storage.js +62 -0
  31. package/node_modules/@maka/storage/dist/artifact-metadata-codec.js +3 -0
  32. package/node_modules/@maka/storage/dist/artifact-store.js +67 -5
  33. package/node_modules/@maka/storage/dist/artifact-stores.js +14 -0
  34. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +44 -0
  35. package/node_modules/@maka/storage/dist/sqlite-artifact-schema.js +8 -1
  36. package/node_modules/@maka/storage/dist/sqlite-image-delivery.js +63 -0
  37. package/package.json +1 -1
@@ -24360,6 +24360,7 @@ async function restoreTombstoneNoReplace(tombstone, path2) {
24360
24360
  }
24361
24361
 
24362
24362
  // src/image-file.ts
24363
+ import { constants as constants2 } from "node:fs";
24363
24364
  import { open as open3 } from "node:fs/promises";
24364
24365
  import { extname } from "node:path";
24365
24366
 
@@ -24755,6 +24756,20 @@ function imageDimensionsFromData(bytes) {
24755
24756
  return png(bytes) ?? gif(bytes) ?? jpeg(bytes) ?? webp(bytes) ?? avif(bytes) ?? heic(bytes);
24756
24757
  }
24757
24758
 
24759
+ // ../core/dist/artifacts.js
24760
+ var ARTIFACT_IMAGE_PREVIEW_MAX_BYTES = 2 * 1024 * 1024;
24761
+ var ARTIFACT_IMAGE_PREVIEW_MIME_BY_EXTENSION = {
24762
+ ".png": "image/png",
24763
+ ".jpg": "image/jpeg",
24764
+ ".jpeg": "image/jpeg",
24765
+ ".gif": "image/gif",
24766
+ ".webp": "image/webp",
24767
+ ".avif": "image/avif"
24768
+ };
24769
+ var ARTIFACT_IMAGE_PREVIEW_MIMES = new Set(Object.values(ARTIFACT_IMAGE_PREVIEW_MIME_BY_EXTENSION));
24770
+ var ARTIFACT_ENTITY_ID_MAX_CHARS = 128;
24771
+ var ARTIFACT_ENTITY_ID_PATTERN = new RegExp(`^[A-Za-z0-9_-]{1,${ARTIFACT_ENTITY_ID_MAX_CHARS}}$`);
24772
+
24758
24773
  // ../core/dist/attachments.js
24759
24774
  var MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024;
24760
24775
  var MAX_READ_IMAGE_BYTES = 5 * 1024 * 1024;
@@ -24802,12 +24817,30 @@ function containsAscii(bytes, signature) {
24802
24817
 
24803
24818
  // src/image-file.ts
24804
24819
  var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);
24820
+ var ImageFileError = class extends Error {
24821
+ constructor(code, message) {
24822
+ super(message);
24823
+ this.code = code;
24824
+ }
24825
+ code;
24826
+ };
24805
24827
  function isSupportedImagePath(path2) {
24806
24828
  return IMAGE_EXTENSIONS.has(extname(path2).toLowerCase());
24807
24829
  }
24808
- async function readWorkspaceFile(path2) {
24809
- const file2 = await open3(path2, "r");
24830
+ async function readWorkspaceFile(path2, options = {}) {
24831
+ options.abortSignal?.throwIfAborted();
24832
+ const file2 = await open3(
24833
+ path2,
24834
+ options.imagePurpose === "chat" ? constants2.O_RDONLY | constants2.O_NONBLOCK : "r"
24835
+ );
24810
24836
  try {
24837
+ options.abortSignal?.throwIfAborted();
24838
+ if (options.imagePurpose === "chat") {
24839
+ const size = await file2.stat();
24840
+ if (!size.isFile()) throw new Error("Image path is not a file.");
24841
+ if (size.size > ARTIFACT_IMAGE_PREVIEW_MAX_BYTES) throw imageTooLargeError("chat");
24842
+ return validateImageBytes(await file2.readFile({ signal: options.abortSignal }), "chat");
24843
+ }
24811
24844
  const prefix = Buffer.alloc(ATTACHMENT_MIME_SNIFF_BYTES);
24812
24845
  const { bytesRead } = await file2.read(prefix, 0, prefix.length, 0);
24813
24846
  if (isSupportedImagePath(path2) || sniffImageMime(prefix.subarray(0, bytesRead))) {
@@ -24821,23 +24854,37 @@ async function readWorkspaceFile(path2) {
24821
24854
  await file2.close();
24822
24855
  }
24823
24856
  }
24824
- function validateImageBytes(bytes) {
24825
- if (bytes.length > MAX_READ_IMAGE_BYTES) throw imageTooLargeError();
24857
+ function validateImageBytes(bytes, purpose = "model") {
24858
+ if (bytes.length > (purpose === "chat" ? ARTIFACT_IMAGE_PREVIEW_MAX_BYTES : MAX_READ_IMAGE_BYTES))
24859
+ throw imageTooLargeError(purpose);
24826
24860
  const mimeType = sniffImageMime(bytes);
24827
- if (!mimeType) throw new Error("Image content is not a supported PNG, JPEG, GIF, or WebP file.");
24861
+ if (!mimeType)
24862
+ throw new ImageFileError(
24863
+ "ERR_INVALID_IMAGE",
24864
+ "Image content is not a supported PNG, JPEG, GIF, or WebP file."
24865
+ );
24828
24866
  const dimensions = imageDimensionsFromData(bytes);
24829
24867
  if (!dimensions || !Number.isFinite(dimensions.width) || !Number.isFinite(dimensions.height) || !Number.isInteger(dimensions.width) || !Number.isInteger(dimensions.height) || dimensions.width <= 0 || dimensions.height <= 0) {
24830
- throw new Error("Image dimensions could not be read; verify the image file is valid.");
24868
+ throw new ImageFileError(
24869
+ "ERR_INVALID_IMAGE",
24870
+ "Image dimensions could not be read; verify the image file is valid."
24871
+ );
24831
24872
  }
24832
- if (Math.max(dimensions.width, dimensions.height) > MAX_MODEL_IMAGE_EDGE) {
24873
+ if (purpose === "model" && Math.max(dimensions.width, dimensions.height) > MAX_MODEL_IMAGE_EDGE) {
24833
24874
  throw new Error(
24834
24875
  `Image dimensions ${dimensions.width}x${dimensions.height} exceed the ${MAX_MODEL_IMAGE_EDGE}px model input limit; downscale it and try again.`
24835
24876
  );
24836
24877
  }
24878
+ if (purpose === "chat" && (Math.max(dimensions.width, dimensions.height) > 16384 || dimensions.width * dimensions.height > 32 * 1024 * 1024)) {
24879
+ throw imageTooLargeError(purpose);
24880
+ }
24837
24881
  return { bytes, mimeType };
24838
24882
  }
24839
- function imageTooLargeError() {
24840
- return new Error(READ_IMAGE_TOO_LARGE_MESSAGE);
24883
+ function imageTooLargeError(purpose = "model") {
24884
+ return new ImageFileError(
24885
+ "ERR_IMAGE_TOO_LARGE",
24886
+ purpose === "chat" ? "Image exceeds a chat preview limit (2 MiB, 16384px per edge, or 32 megapixels); resize it before publishing." : READ_IMAGE_TOO_LARGE_MESSAGE
24887
+ );
24841
24888
  }
24842
24889
  function sniffImageMime(bytes) {
24843
24890
  const sniffed = sniffAttachmentMimeType(bytes);
@@ -24845,7 +24892,7 @@ function sniffImageMime(bytes) {
24845
24892
  }
24846
24893
 
24847
24894
  // src/filesystem-worker/protocol.ts
24848
- var FILESYSTEM_WORKER_PROTOCOL_VERSION = 11;
24895
+ var FILESYSTEM_WORKER_PROTOCOL_VERSION = 12;
24849
24896
  function operationAccess(kind) {
24850
24897
  return kind === "write" || kind === "apply_patch" || kind === "edit" || kind === "format_json" ? "write" : "read";
24851
24898
  }
@@ -24895,6 +24942,7 @@ var FilesystemWorkerOperationSchema = external_exports.union([
24895
24942
  kind: external_exports.literal("read"),
24896
24943
  cwd,
24897
24944
  path,
24945
+ imagePurpose: external_exports.literal("chat").optional(),
24898
24946
  offset: external_exports.number().int().nonnegative().optional(),
24899
24947
  limit: external_exports.number().int().positive().optional(),
24900
24948
  continuation: readContinuationSchema.optional()
@@ -25004,6 +25052,8 @@ var FilesystemWorkerErrorCodeSchema = external_exports.enum([
25004
25052
  "grep_unavailable",
25005
25053
  "sandbox_denied",
25006
25054
  "filesystem_denied",
25055
+ "image_too_large",
25056
+ "invalid_image",
25007
25057
  "filesystem_error",
25008
25058
  // The worker may have applied the mutation before it lost the ability to
25009
25059
  // report back (e.g. it wrote the file then the post-write identity check
@@ -25085,9 +25135,11 @@ async function executeFilesystemOperation(operation, operationBoundary, dependen
25085
25135
  "read",
25086
25136
  operationBoundary
25087
25137
  );
25088
- const file2 = await readWorkspaceFile(path2).catch((error62) => {
25138
+ const file2 = await readWorkspaceFile(path2, {
25139
+ ...operation.imagePurpose ? { imagePurpose: operation.imagePurpose } : {}
25140
+ }).catch((error62) => {
25089
25141
  throw operationError(
25090
- "filesystem_error",
25142
+ normalizeOperationError(error62).code,
25091
25143
  error62 instanceof Error ? error62.message : "File could not be read."
25092
25144
  );
25093
25145
  });
@@ -25361,6 +25413,11 @@ function operationError(code, message) {
25361
25413
  }
25362
25414
  function normalizeOperationError(error62) {
25363
25415
  if (error62 instanceof FilesystemOperationError) return error62;
25416
+ if (error62 instanceof ImageFileError)
25417
+ return operationError(
25418
+ error62.code === "ERR_IMAGE_TOO_LARGE" ? "image_too_large" : "invalid_image",
25419
+ error62.message
25420
+ );
25364
25421
  if (error62 instanceof StableWriteFailure) {
25365
25422
  return operationError(error62.code, error62.message);
25366
25423
  }
@@ -68,7 +68,7 @@ export class LocalWorkspaceExecutor {
68
68
  };
69
69
  }
70
70
  async readFile(input) {
71
- const file = await readWorkspaceFile(input.path);
71
+ const file = await readWorkspaceFile(input.path, input);
72
72
  if ('bytes' in file)
73
73
  return file;
74
74
  return { content: readTextLineWindow(file.content, input.offset, input.limit) };
@@ -245,8 +245,8 @@ async function resolveDirectoryEntryPathInScope(cwd, inputPath, label, scope) {
245
245
  }
246
246
  function assertInsideCwd(root, candidate, inputPath, label) {
247
247
  if (!isPathInside(root, candidate)) {
248
- throw new Error(`${label} path must stay inside session cwd ${JSON.stringify(root)}; ` +
249
- `received ${JSON.stringify(inputPath)}, which resolves to ${JSON.stringify(candidate)}.`);
248
+ throw Object.assign(new Error(`${label} path must stay inside session cwd ${JSON.stringify(root)}; ` +
249
+ `received ${JSON.stringify(inputPath)}, which resolves to ${JSON.stringify(candidate)}.`), { code: 'EACCES' });
250
250
  }
251
251
  return candidate;
252
252
  }
@@ -10,6 +10,8 @@
10
10
  "./ai-sdk-backend": "./dist/ai-sdk-backend.js",
11
11
  "./mcp-tools": "./dist/mcp-tools.js",
12
12
  "./read-page": "./dist/read-page.js",
13
+ "./image-file-reader": "./dist/image-file-reader.js",
14
+ "./image-file": "./dist/image-file.js",
13
15
  "./builtin-tools": "./dist/builtin-tools.js",
14
16
  "./shell-tools": "./dist/shell-tools.js",
15
17
  "./shell-run-manager": "./dist/shell-run-manager.js",
@@ -16,6 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { IMAGE_DELIVERY_OPERATION_SPECS } from './image-delivery.js';
19
20
  import { ARTIFACT_KINDS, ARTIFACT_SOURCES, isArtifactTurnKey, isCanonicalArtifactEntityId, } from '@maka/core/artifacts';
20
21
  import { MAX_ATTACHMENT_BYTES } from '@maka/core/attachments';
21
22
  import { isCanonicalAttachmentRef } from '@maka/core/events';
@@ -54,6 +55,7 @@ const ARTIFACT_REQUIRED_FIELDS = [
54
55
  ];
55
56
  const ARTIFACT_FIELDS = new Set([...ARTIFACT_REQUIRED_FIELDS, 'mimeType', 'summary']);
56
57
  export const ARTIFACT_OPERATION_SPECS = {
58
+ ...IMAGE_DELIVERY_OPERATION_SPECS,
57
59
  'artifact.ingest': defineOperation({
58
60
  mode: 'command',
59
61
  availability: 'ready',
@@ -0,0 +1,70 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ import { IMAGE_DELIVERY_FAILURES, isImageDeliveryRequest, } from '@maka/core/image-delivery';
20
+ import { isCanonicalArtifactEntityId } from '@maka/core/artifacts';
21
+ import { requireExactRecord, requireEntityId, requireRecord, requireShapedRecord, } from './codec.js';
22
+ import { invalidProtocolFrame } from './errors.js';
23
+ import { defineOperation } from './operation-spec.js';
24
+ export const IMAGE_DELIVERY_OPERATION_SPECS = {
25
+ 'artifact.image.resolve': defineOperation({
26
+ mode: 'command',
27
+ availability: 'ready',
28
+ errors: [
29
+ 'host_not_ready',
30
+ 'host_draining',
31
+ 'operation_unavailable',
32
+ 'invalid_request',
33
+ 'not_found',
34
+ 'internal_failure',
35
+ ],
36
+ decodeInput(value) {
37
+ const { sessionId, ...request } = requireShapedRecord(value, 'image delivery request', ['sessionId', 'turnId', 'messageId', 'source'], ['retry', 'loadRemote']);
38
+ if (!isImageDeliveryRequest(request))
39
+ throw invalidProtocolFrame('Invalid image delivery request');
40
+ const { retry, loadRemote, ...identity } = request;
41
+ return {
42
+ sessionId: requireEntityId(sessionId, 'sessionId'),
43
+ ...identity,
44
+ ...(retry === true ? { retry: true } : {}),
45
+ ...(loadRemote === true ? { loadRemote: true } : {}),
46
+ };
47
+ },
48
+ decodeOutput(value) {
49
+ const v = requireRecord(value, 'image delivery result');
50
+ if (v.status === 'pending' ||
51
+ v.status === 'unavailable' ||
52
+ v.status === 'requires_confirmation') {
53
+ requireExactRecord(v, 'image delivery status', ['status']);
54
+ return { status: v.status };
55
+ }
56
+ if (v.status === 'ready' && isCanonicalArtifactEntityId(v.artifactId)) {
57
+ requireExactRecord(v, 'image delivery ready', ['status', 'artifactId']);
58
+ return { status: 'ready', artifactId: v.artifactId };
59
+ }
60
+ if (v.status === 'failed' && IMAGE_DELIVERY_FAILURES.includes(v.reason)) {
61
+ requireExactRecord(v, 'image delivery failure', ['status', 'reason']);
62
+ return {
63
+ status: 'failed',
64
+ reason: v.reason,
65
+ };
66
+ }
67
+ throw invalidProtocolFrame('Invalid image delivery result');
68
+ },
69
+ }),
70
+ };
@@ -67,7 +67,10 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1;
67
67
  export const RUNTIME_HOST_PROTOCOL_VERSION = 0;
68
68
  // Increment when the same protocol version no longer guarantees safe Client-Host
69
69
  // interoperability. Mismatches are rejected before domain commands are admitted.
70
- export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 220;
70
+ export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 221;
71
+ // 221: Epoch-220 peers do not support `artifact.image.resolve` or its image
72
+ // delivery result shapes. Older Hosts reject the unknown operation and close
73
+ // the connection, so mixed peers must fail admission.
71
74
  // 220: Client Capability results require a tri-state outcome; session tool
72
75
  // continuity and trace steps carry interrupted results. Older peers cannot
73
76
  // decode the changed strict shapes.
@@ -115,6 +115,7 @@ export const REMOTE_OWNER_OPERATION_GRANTS = Object.freeze([
115
115
  'agent.graph.stop',
116
116
  'artifact.delete',
117
117
  'artifact.ingest',
118
+ 'artifact.image.resolve',
118
119
  'artifact.query',
119
120
  'client.capability.replace',
120
121
  'client.capability.unregister',
@@ -29,7 +29,15 @@ const MAX_STAGED_ARTIFACT_UPLOAD_BYTES = 128 * 1024 * 1024;
29
29
  const ARTIFACT_UPLOAD_TTL_MS = 5 * 60 * 1000;
30
30
  /** Session-scoped Host projection and deletion authority for Artifacts. */
31
31
  export class HostArtifactCoordinator {
32
+ imageDelivery;
32
33
  handlers = {
34
+ 'artifact.image.resolve': async (input, context) => {
35
+ if (context.principalKind === 'session_guest' || !this.imageDelivery)
36
+ return { ok: true, result: { status: 'unavailable' } };
37
+ if ((await this.#sessions.probeSessionRemoval(input.sessionId)).kind !== 'present')
38
+ return { ok: false, error: { code: 'not_found', message: 'Session was not found' } };
39
+ return { ok: true, result: await this.imageDelivery.resolve(input) };
40
+ },
33
41
  'artifact.ingest': (input, context) => this.#sessionAdmission.run(input.sessionId, () => this.#ingest(input, context)),
34
42
  'artifact.query': (input, context) => this.#sessionAdmission.run(input.sessionId, () => this.#query(input, context)),
35
43
  'artifact.delete': (input) => this.#sessionAdmission.run(input.sessionId, () => this.#delete(input)),
@@ -41,7 +49,8 @@ export class HostArtifactCoordinator {
41
49
  #sessionAccessAuthority;
42
50
  #uploads;
43
51
  #onArtifactDeleted;
44
- constructor(store, requestDrain, sessionAdmission, sessions, now = Date.now, sessionAccessAuthority, onArtifactDeleted) {
52
+ constructor(store, requestDrain, sessionAdmission, sessions, now = Date.now, sessionAccessAuthority, onArtifactDeleted, imageDelivery) {
53
+ this.imageDelivery = imageDelivery;
45
54
  this.#store = authenticateInteractiveArtifactStoreWriter(store);
46
55
  this.#requestDrain = requestDrain;
47
56
  this.#sessionAdmission = sessionAdmission;
@@ -0,0 +1,41 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ import { createHash } from 'node:crypto';
20
+ import { DEFAULT_IMAGE_ARCHIVE_LIMITS } from '@maka/core/image-delivery';
21
+ /** Build the shared ready record; callers own admission, identity and failures. */
22
+ export function readyChatImageArtifact(input) {
23
+ return {
24
+ id: input.id,
25
+ sessionId: input.sessionId,
26
+ turnId: input.turnId,
27
+ name: input.name,
28
+ kind: 'image',
29
+ content: input.image.bytes,
30
+ mimeType: input.image.mimeType,
31
+ source: 'tool_result_projection',
32
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
33
+ imageDelivery: {
34
+ messageId: input.messageId,
35
+ source: input.source,
36
+ status: 'ready',
37
+ contentSha256: createHash('sha256').update(input.image.bytes).digest('hex'),
38
+ },
39
+ imageArchiveLimits: input.limits ?? DEFAULT_IMAGE_ARCHIVE_LIMITS,
40
+ };
41
+ }
@@ -0,0 +1,232 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ import { createHash } from 'node:crypto';
20
+ import { ImageFileReadError } from '@maka/runtime/image-file-reader';
21
+ import { IMAGE_MARKDOWN_MAX_LENGTH, isRemoteImageSource, } from '@maka/core/image-delivery';
22
+ import { ImageArchiveQuotaError, } from '@maka/storage/artifact-stores';
23
+ import { chatImageSources } from './chat-image-markdown.js';
24
+ import { readyChatImageArtifact } from './chat-image-artifact.js';
25
+ import { abortable } from '../client/wait-for-ready.js';
26
+ import { downloadChatImage, ImageSourceError, localImagePath, } from './chat-image-source.js';
27
+ /** Host owns capture and persistence; clients can only resolve sources already in an assistant message. */
28
+ export class ChatImageDeliveryService {
29
+ ports;
30
+ #jobs = new Map();
31
+ #queue = [];
32
+ #abort = new AbortController();
33
+ #running = 0;
34
+ #closed = false;
35
+ constructor(ports) {
36
+ this.ports = ports;
37
+ }
38
+ observe(sessionId, event) {
39
+ if (this.#closed || event.text.length > IMAGE_MARKDOWN_MAX_LENGTH)
40
+ return;
41
+ // Reference destinations can grow during streaming. Only settled text
42
+ // grants local capture. Remote media loads only when a client displays it.
43
+ try {
44
+ for (const source of chatImageSources(event.text)) {
45
+ if (isRemoteImageSource(source))
46
+ continue;
47
+ this.#enqueue({ sessionId, turnId: event.turnId, messageId: event.messageId, source });
48
+ }
49
+ }
50
+ catch (error) {
51
+ this.ports.presentationFailed(error);
52
+ }
53
+ }
54
+ async resolve(identity) {
55
+ if (this.#closed)
56
+ return { status: 'unavailable' };
57
+ const metadata = await this.ports.artifacts.findImageDelivery(identity.sessionId, identity.turnId, identity.messageId, identity.source);
58
+ // A browser decode/read failure is not authority to destroy saved history.
59
+ if (metadata?.status === 'ready')
60
+ return metadata;
61
+ if (this.#jobs.has(deliveryKey(identity)))
62
+ return { status: 'pending' };
63
+ if (metadata?.status === 'failed' && !identity.retry)
64
+ return metadata;
65
+ // A client-provided path is never a read grant. Legacy/restarted deliveries
66
+ // must be found in canonical assistant text before any source is opened.
67
+ if (!metadata) {
68
+ const text = await this.ports.readMessage(identity);
69
+ if (text === undefined || !chatImageSources(text).includes(identity.source))
70
+ return { status: 'unavailable' };
71
+ }
72
+ if (isRemoteImageSource(identity.source)) {
73
+ if (!(await this.ports.canLoadRemote(identity.sessionId)))
74
+ return { status: 'failed', reason: 'not_allowed' };
75
+ if (!identity.loadRemote)
76
+ return { status: 'requires_confirmation' };
77
+ }
78
+ return this.#enqueue(identity)
79
+ ? { status: 'pending' }
80
+ : { status: 'failed', reason: 'queue_full' };
81
+ }
82
+ #enqueue(identity) {
83
+ const key = deliveryKey(identity);
84
+ if (this.#jobs.has(key))
85
+ return true;
86
+ if (this.#closed || this.#jobs.size >= 128)
87
+ return false;
88
+ let settle;
89
+ const done = new Promise((resolve) => {
90
+ settle = resolve;
91
+ });
92
+ const residency = this.ports.acquireResidency();
93
+ const finish = () => {
94
+ this.#jobs.delete(key);
95
+ residency.release();
96
+ settle();
97
+ };
98
+ const job = {
99
+ done,
100
+ cancel: finish,
101
+ run: async () => {
102
+ try {
103
+ await this.#capture(identity);
104
+ }
105
+ catch (error) {
106
+ if (!this.#abort.signal.aborted) {
107
+ if (error instanceof ImagePersistenceError)
108
+ this.ports.persistenceFailed(error.cause);
109
+ else
110
+ this.ports.presentationFailed(error);
111
+ }
112
+ }
113
+ finally {
114
+ finish();
115
+ }
116
+ },
117
+ };
118
+ this.#jobs.set(key, job);
119
+ this.#queue.push(job);
120
+ this.#pump();
121
+ return true;
122
+ }
123
+ #pump() {
124
+ while (!this.#closed && this.#running < 2 && this.#queue.length) {
125
+ const job = this.#queue.shift();
126
+ this.#running++;
127
+ void job.run().finally(() => {
128
+ this.#running--;
129
+ this.#pump();
130
+ });
131
+ }
132
+ }
133
+ async #capture(identity) {
134
+ const { sessionId, turnId, messageId, source } = identity;
135
+ const existing = await this.ports.artifacts.findImageDelivery(sessionId, turnId, messageId, source);
136
+ if (existing?.status === 'ready' || (existing?.status === 'failed' && !identity.retry))
137
+ return;
138
+ const metadata = { messageId, source };
139
+ const resultId = `chat_image_result_${deliveryKey(identity)}`;
140
+ const publish = async (write) => this.ports.admission.runOrJoin(sessionId, async () => {
141
+ if (this.#abort.signal.aborted || !(await this.ports.isPresent(sessionId)))
142
+ return;
143
+ try {
144
+ await write();
145
+ }
146
+ catch (error) {
147
+ if (error instanceof ImageArchiveQuotaError)
148
+ throw error;
149
+ throw new ImagePersistenceError('Image persistence failed', { cause: error });
150
+ }
151
+ });
152
+ const publishAttempt = (attempt) => publish(() => this.ports.artifacts.setImageDeliveryAttempt(identity, attempt));
153
+ const publishFailure = (reason) => publishAttempt({ status: 'failed', reason });
154
+ await publishAttempt({ status: 'pending' });
155
+ if (this.#abort.signal.aborted || !(await this.ports.isPresent(sessionId)))
156
+ return;
157
+ const readAbort = new AbortController();
158
+ // Keep the read deadline alive even when a source has no active handles.
159
+ const deadline = setTimeout(() => readAbort.abort(), this.ports.sourceReadTimeoutMs ?? 10_000);
160
+ const signal = AbortSignal.any([this.#abort.signal, readAbort.signal]);
161
+ let image;
162
+ try {
163
+ const path = localImagePath(source);
164
+ if (path !== undefined) {
165
+ image = await abortable(() => this.ports.readLocalImage(sessionId, path, signal), signal);
166
+ }
167
+ else {
168
+ if (!identity.loadRemote || !(await this.ports.canLoadRemote(sessionId)))
169
+ throw new ImageSourceError('not_allowed');
170
+ image = await (this.ports.download ?? downloadChatImage)(source, signal);
171
+ }
172
+ }
173
+ catch (error) {
174
+ if (this.#abort.signal.aborted)
175
+ return;
176
+ await publishFailure(failureReason(error, source));
177
+ return;
178
+ }
179
+ finally {
180
+ clearTimeout(deadline);
181
+ }
182
+ if (this.#abort.signal.aborted)
183
+ return;
184
+ if (signal.aborted) {
185
+ await publishFailure(failureReason(signal.reason, source));
186
+ return;
187
+ }
188
+ try {
189
+ await publish(() => this.ports.artifacts.create(readyChatImageArtifact({
190
+ id: resultId,
191
+ sessionId,
192
+ turnId,
193
+ name: 'chat-image',
194
+ ...metadata,
195
+ image,
196
+ limits: this.ports.limits,
197
+ })));
198
+ }
199
+ catch (error) {
200
+ if (!(error instanceof ImageArchiveQuotaError))
201
+ throw error;
202
+ await publishFailure('quota_exceeded');
203
+ }
204
+ }
205
+ beginDrain() {
206
+ this.#closed = true;
207
+ this.#abort.abort();
208
+ for (const job of this.#queue.splice(0))
209
+ job.cancel();
210
+ }
211
+ async close() {
212
+ this.beginDrain();
213
+ await this.waitForIdle();
214
+ }
215
+ async waitForIdle() {
216
+ await Promise.all([...this.#jobs.values()].map((job) => job.done));
217
+ }
218
+ }
219
+ class ImagePersistenceError extends Error {
220
+ }
221
+ function deliveryKey(i) {
222
+ return createHash('sha256')
223
+ .update(JSON.stringify([i.sessionId, i.turnId, i.messageId, i.source]))
224
+ .digest('hex');
225
+ }
226
+ function failureReason(error, source) {
227
+ if (error instanceof ImageSourceError)
228
+ return error.reason;
229
+ if (error instanceof ImageFileReadError)
230
+ return error.reason;
231
+ return isRemoteImageSource(source) ? 'download_failed' : 'read_failed';
232
+ }
@@ -0,0 +1,26 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ import { isImageDeliverySource } from '@maka/core/image-delivery';
20
+ import { markdownImageSources } from '@maka/core/image-markdown';
21
+ /** Capture policy excludes explicit attachments and limits jobs per message. */
22
+ export function chatImageSources(text) {
23
+ return markdownImageSources(text)
24
+ .filter((source) => isImageDeliverySource(source) && !source.startsWith('maka:'))
25
+ .slice(0, 64);
26
+ }