@h1r-ai/croche-react-native 0.6.0 → 0.7.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.
Files changed (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -1,3 +1,5 @@
1
+ import { captureReadVersioned, captureWriteIf } from '../../runtime/src/pal/storage-version-contract.js';
2
+ import { owned } from '../../runtime/src/core/wasm-owner';
1
3
  import { CrocheError, thrownFacts } from '../../runtime/src/errors';
2
4
  function answer(json) {
3
5
  const result = JSON.parse(json);
@@ -10,11 +12,37 @@ function answer(json) {
10
12
  }
11
13
  return result.value;
12
14
  }
15
+ /** Default native encoded-image effects use the same owned cancel handles as Core. */
16
+ export function createNativeImageAdapter(wire) {
17
+ const sync = (method, args = []) => answer(wire.callSync('', method, JSON.stringify(args)));
18
+ const support = sync('platformImageSupport');
19
+ if (!support)
20
+ return undefined;
21
+ async function operation(method, bytes, options, signal) {
22
+ const token = sync('newCancel');
23
+ const abort = () => { answer(wire.callSync(token, 'cancel', '[]')); };
24
+ signal.addEventListener('abort', abort, { once: true });
25
+ try {
26
+ if (signal.aborted)
27
+ abort();
28
+ return answer(await wire.call('', 'platformImageOperation', JSON.stringify([method, Array.from(bytes), options, token])));
29
+ }
30
+ finally {
31
+ signal.removeEventListener('abort', abort);
32
+ wire.callSync(token, 'release', '[]');
33
+ }
34
+ }
35
+ return { kind: 'image', support,
36
+ info: async (bytes, { signal }) => (await operation('info', bytes, {}, signal)).info,
37
+ resize: async (bytes, limits, { signal }) => new Uint8Array((await operation('resize', bytes, limits, signal)).bytes),
38
+ };
39
+ }
13
40
  export function createNativeCore(wire, defaultStorage) {
14
41
  let next = 0;
15
42
  const hosts = new Map(), storages = new Map(), sinks = new Map();
16
43
  const executors = new Map(), tokens = new Map();
17
44
  const ids = new WeakMap();
45
+ const toolFactories = new WeakMap();
18
46
  const references = new Map();
19
47
  let sweeping = false;
20
48
  const release = (id) => { try {
@@ -31,7 +59,7 @@ export function createNativeCore(wire, defaultStorage) {
31
59
  continue;
32
60
  references.delete(id);
33
61
  tokens.delete(id);
34
- if (record.closed || !record.mode) {
62
+ if (!record.mode) {
35
63
  release(id);
36
64
  continue;
37
65
  }
@@ -51,14 +79,15 @@ export function createNativeCore(wire, defaultStorage) {
51
79
  sweeping = false;
52
80
  }
53
81
  }
54
- function closed(id) { const record = references.get(id); if (record)
55
- record.closed = true; }
56
82
  const name = (kind) => `${kind}:${++next}`;
57
- const sync = (id, method, args = []) => { sweep(); const value = answer(wire.callSync(id, method, JSON.stringify(args))); if (method === 'shutdown')
58
- closed(id); return value; };
59
- const call = async (id, method, args = [], images) => { sweep(); const value = answer(await wire.call(id, method, JSON.stringify(args), images)); if (method === 'shutdown')
60
- closed(id); return value; };
61
- const remember = (id, object, mode) => { ids.set(object, id); references.set(id, { ref: new WeakRef(object), mode, closed: false }); return object; };
83
+ const sync = (id, method, args = []) => { sweep(); const value = answer(wire.callSync(id, method, JSON.stringify(args))); return value; };
84
+ const call = async (id, method, args = [], images) => { sweep(); const value = answer(await wire.call(id, method, JSON.stringify(args), images)); return value; };
85
+ const remember = (id, object, mode) => {
86
+ Object.defineProperty(object, 'free', { value: () => { references.delete(id); tokens.delete(id); release(id); } });
87
+ ids.set(object, id);
88
+ references.set(id, { ref: new WeakRef(object), mode });
89
+ return object;
90
+ };
62
91
  const handle = (object) => {
63
92
  const id = ids.get(object);
64
93
  if (id === undefined)
@@ -72,28 +101,38 @@ export function createNativeCore(wire, defaultStorage) {
72
101
  this.id = id;
73
102
  tokens.set(id, new WeakRef(this));
74
103
  ids.set(this, id);
75
- references.set(id, { ref: new WeakRef(this), closed: false });
104
+ references.set(id, { ref: new WeakRef(this) });
76
105
  }
106
+ free() { references.delete(this.id); tokens.delete(this.id); release(this.id); }
77
107
  cancel() { sync(this.id, 'cancel'); }
78
108
  isCancelled() { return sync(this.id, 'isCancelled'); }
79
109
  onCancel(callback) { this.listeners.push(callback); }
80
110
  }
111
+ const attachmentReader = (id) => remember(id, { attachment: key => call(id, 'attachment', [key]) }, 'async');
81
112
  const token = (id) => tokens.get(id)?.deref() ?? new NativeCancel(id);
82
113
  const sinkId = (sink) => { const id = name('sink'); sinks.set(id, sink); return id; };
83
114
  const hostId = (host) => { const id = name('host'); hosts.set(id, host); return id; };
84
115
  const storageId = (storage) => { const id = name('storage'); storages.set(id, storage); return id; };
85
- const registrations = (tools) => tools.map(({ tool, optionsJson }) => ({ tool: handle(tool), ...(optionsJson === undefined ? {} : { optionsJson }) }));
116
+ const registrations = (tools, temporary) => tools.map(({ tool, optionsJson }) => {
117
+ const make = toolFactories.get(tool), id = make ? make() : handle(tool);
118
+ if (make)
119
+ temporary.push(id);
120
+ return { tool: id, ...(optionsJson === undefined ? {} : { optionsJson }) };
121
+ });
86
122
  const subscription = (id) => remember(id, {
87
123
  history: options => call(id, 'history', [options]),
88
124
  shutdown: () => { sync(id, 'shutdown'); }, get ended() { return sync(id, 'ended'); },
89
125
  }, 'sync');
90
126
  const agent = (id) => remember(id, {
127
+ attachment: key => call(id, 'attachment', [key]), deleteAttachment: key => call(id, 'deleteAttachment', [key]),
128
+ listAttachments: options => call(id, 'listAttachments', [options]), copyAttachment: source => call(id, 'copyAttachment', [source]), releaseAttachment: key => call(id, 'releaseAttachment', [key]),
91
129
  get id() { return sync(id, 'id'); }, get instance() { return sync(id, 'instance'); },
130
+ decide: (input, options, cancel) => call(id, 'decide', [input, options, handle(cancel)]),
92
131
  send: (input, images, options, cancel) => call(id, 'send', [input, options, handle(cancel)], images),
93
132
  request: (input, images, options, cancel) => call(id, 'request', [input, options, handle(cancel)], images),
94
133
  subscribe: (selection, sink) => subscription(sync(id, 'subscribe', [selection, sinkId(sink)])),
95
- cancel: input => call(id, 'cancel', [input]), clearHistory: () => call(id, 'clearHistory'),
96
- memoryList: () => call(id, 'memoryList'), memoryDelete: key => call(id, 'memoryDelete', [key]),
134
+ cancel: input => call(id, 'cancel', [input]), clearHistory: options => call(id, 'clearHistory', [options]),
135
+ memoryList: options => call(id, 'memoryList', [options]), memoryDelete: key => call(id, 'memoryDelete', [key]),
97
136
  memoryClear: () => call(id, 'memoryClear'), memoryEnabled: on => call(id, 'memoryEnabled', [on]),
98
137
  setTools: scope => call(id, 'setTools', [scope]), resetTools: () => call(id, 'resetTools'),
99
138
  setWiki: scope => call(id, 'setWiki', [scope]), resetWiki: () => call(id, 'resetWiki'),
@@ -102,16 +141,29 @@ export function createNativeCore(wire, defaultStorage) {
102
141
  const croche = (id) => remember(id, {
103
142
  runTool: (name, args, options, cancel) => call(id, 'runTool', [name, args, options, handle(cancel)]),
104
143
  deleteData: scope => call(id, 'deleteData', [scope]),
144
+ attachment: key => call(id, 'attachment', [key]), deleteAttachment: key => call(id, 'deleteAttachment', [key]), listAttachments: options => call(id, 'listAttachments', [options]),
145
+ allowanceSet: limit => call(id, 'allowanceSet', [limit]), verification: () => call(id, 'verification'),
105
146
  agent: async (key, options) => agent(await call(id, 'agent', [key, options])),
106
- agentIds: () => sync(id, 'agentIds'),
107
147
  deliverDue: (options, cancel) => call(id, 'deliverDue', [options, handle(cancel)]),
108
148
  wikiPut: doc => call(id, 'wikiPut', [doc]), wikiRemove: path => call(id, 'wikiRemove', [path]),
109
- wikiList: () => call(id, 'wikiList'),
149
+ wikiList: options => call(id, 'wikiList', [options]),
110
150
  debugAttach: options => call(id, 'debugAttach', [options]),
111
151
  debugDetach: () => call(id, 'debugDetach'),
112
152
  shutdown: () => call(id, 'shutdown'),
113
153
  }, 'async');
114
- const definition = (id) => remember(id, { get name() { return sync(id, 'name'); } });
154
+ const definition = (make) => {
155
+ const id = make();
156
+ let name;
157
+ try {
158
+ name = sync(id, 'name');
159
+ }
160
+ finally {
161
+ release(id);
162
+ }
163
+ const value = { name };
164
+ toolFactories.set(value, make);
165
+ return value;
166
+ };
115
167
  // No SDK event queue: this runs on the JS invocation stack. The SAME shared
116
168
  // sink checks entry immediately before the app call and completes after finish.
117
169
  function receive(packet) {
@@ -128,18 +180,67 @@ export function createNativeCore(wire, defaultStorage) {
128
180
  case 'execute': {
129
181
  const execute = executors.get(packet.execute);
130
182
  if (!execute) {
183
+ sync(packet.attachments, 'release');
131
184
  wire.reply(packet.call, '{"type":"unavailable"}');
132
185
  return;
133
186
  }
134
187
  // CoreExecute already yields the exact completion JSON. No re-mapping,
135
188
  // JSON wrapping, error codes or result inference at this boundary.
136
- void execute(packet.callJson, packet.contextJson, token(packet.cancel)).then(json => wire.reply(packet.call, json), () => wire.reply(packet.call, '{"type":"unavailable"}'));
189
+ void execute(packet.callJson, packet.contextJson, token(packet.cancel), attachmentReader(packet.attachments)).then(json => wire.reply(packet.call, json), () => wire.reply(packet.call, '{"type":"unavailable"}'));
137
190
  return;
138
191
  }
139
192
  case 'cancel':
140
193
  for (const listener of tokens.get(packet.token)?.deref()?.listeners ?? [])
141
194
  listener();
142
195
  return;
196
+ case 'image': {
197
+ const host = hosts.get(packet.host);
198
+ if (!host) {
199
+ wire.reply(packet.call, '{"unavailable":true}');
200
+ return;
201
+ }
202
+ void host.imageOperation(packet.operation, new Uint8Array(packet.bytes), packet.options, token(packet.cancel)).then(value => wire.reply(packet.call, JSON.stringify({ value: { ...value, ...(value.bytes ? { bytes: Array.from(value.bytes) } : {}) } })), error => wire.reply(packet.call, JSON.stringify({ error: thrownFacts(error) })));
203
+ return;
204
+ }
205
+ case 'blob': {
206
+ const host = hosts.get(packet.host);
207
+ if (!host?.blobGet || !host.blobPut || !host.blobDelete || !host.blobList) {
208
+ wire.reply(packet.call, '{"unavailable":true}');
209
+ return;
210
+ }
211
+ const { blobGet, blobPut, blobDelete, blobList, blobPurgeStaging } = host;
212
+ const { operation, key, cursor, bytes: rawBytes } = packet;
213
+ async function blob() {
214
+ switch (operation) {
215
+ case 'get': {
216
+ const bytes = await blobGet(key);
217
+ return { bytes: bytes === null ? null : Array.from(bytes) };
218
+ }
219
+ case 'put': {
220
+ const bytes = rawBytes;
221
+ if (!bytes?.every(byte => Number.isInteger(byte) && byte >= 0 && byte <= 255))
222
+ throw Error('Invalid blob bytes');
223
+ await blobPut(key, new Uint8Array(bytes));
224
+ return {};
225
+ }
226
+ case 'delete':
227
+ await blobDelete(key);
228
+ return {};
229
+ case 'list': {
230
+ const page = await blobList(key, cursor ?? undefined);
231
+ if (!Array.isArray(page.entries) || page.entries.some(({ key, size }) => typeof key !== 'string' || !Number.isSafeInteger(size) || size < 0) ||
232
+ (page.nextCursor !== undefined && typeof page.nextCursor !== 'string'))
233
+ throw Error('Invalid blob page');
234
+ return page;
235
+ }
236
+ case 'purgeStaging':
237
+ await blobPurgeStaging?.(key);
238
+ return {};
239
+ }
240
+ }
241
+ void blob().then(value => wire.reply(packet.call, JSON.stringify({ value })), error => wire.reply(packet.call, JSON.stringify({ error: { detail: thrownFacts(error).message ?? '' } })));
242
+ return;
243
+ }
143
244
  case 'storage': {
144
245
  const storage = storages.get(packet.storage);
145
246
  if (!storage) {
@@ -150,7 +251,17 @@ export function createNativeCore(wire, defaultStorage) {
150
251
  const owner = packet.method in secrets ? storage.secrets : storage;
151
252
  const key = packet.method in secrets ? secrets[packet.method] : packet.method;
152
253
  const method = owner[key];
153
- void Promise.resolve().then(() => method.apply(owner, packet.args)).then(value => wire.reply(packet.call, JSON.stringify({ value: value ?? null })),
254
+ void Promise.resolve().then(() => {
255
+ if (packet.method === 'readVersioned') {
256
+ const r = captureReadVersioned(packet.args[0]);
257
+ return storage.readVersioned(r.key).then(r.decode);
258
+ }
259
+ if (packet.method === 'writeIf') {
260
+ const r = captureWriteIf(...packet.args.slice(0, 3));
261
+ return storage.writeIf(r.key, r.value, r.expect).then(r.decode);
262
+ }
263
+ return method.apply(owner, packet.args);
264
+ }).then(value => wire.reply(packet.call, JSON.stringify({ value: value ?? null })),
154
265
  // Storage carries detail only. Core assigns storage_error; codes and categories never cross.
155
266
  error => wire.reply(packet.call, JSON.stringify({ error: { detail: thrownFacts(error).message ?? '' } })));
156
267
  return;
@@ -170,24 +281,36 @@ export function createNativeCore(wire, defaultStorage) {
170
281
  }
171
282
  wire.listen(receive);
172
283
  return {
173
- newCancel: () => token(sync('', 'newCancel')),
174
- open: async (json, tools, storage, host, recovery) => croche(await call('', 'open', [json, registrations(tools), storageId(storage), hostId(host), recovery])),
175
- wakeTimes: (json, query, storage, host) => call('', 'wakeTimes', [json, query, storageId(storage), hostId(host)]),
284
+ decisions: { decide: (agent, input, options, cancel) => agent.decide(input, options, cancel) },
285
+ newCancel: () => owned(token(sync('', 'newCancel')), 'token', error => error),
286
+ open: async (json, tools, storage, host, recovery) => {
287
+ const temporary = [];
288
+ try {
289
+ return owned(croche(await call('', 'open', [json, registrations(tools, temporary), storageId(storage), hostId(host), recovery, host.imageSupport() ?? null, ...(host.blobGet ? [true] : [])])), 'croche', error => error);
290
+ }
291
+ finally {
292
+ for (const id of temporary)
293
+ release(id);
294
+ }
295
+ },
296
+ wakeTimes: (json, query, storage, host) => call('', 'wakeTimes', [json, query, storageId(storage), hostId(host), host.imageSupport() ?? null, ...(host.blobGet ? [true] : [])]),
176
297
  registerBackground: (json, sink, storage, platformStorage, host) => {
177
298
  const markerStorage = platformStorage ?? (storage === defaultStorage ? undefined : defaultStorage);
178
- sync('', 'registerBackground', [json, sink && sinkId(sink), storageId(storage), hostId(host), markerStorage && storageId(markerStorage)]);
299
+ sync('', 'registerBackground', [json, sink && sinkId(sink), storageId(storage), hostId(host), markerStorage && storageId(markerStorage),
300
+ ...(host.blobGet ? [host.imageSupport() ?? null, true] : [])]);
179
301
  },
180
- defineTool: (manifest, execute) => {
302
+ defineTool: (manifest, execute) => definition(() => {
181
303
  const id = name('execute');
182
304
  executors.set(id, execute);
183
305
  try {
184
- return definition(sync('', 'defineTool', [manifest, id]));
306
+ return sync('', 'defineTool', [manifest, id]);
185
307
  }
186
308
  catch (error) {
187
309
  executors.delete(id);
188
310
  throw error;
189
311
  }
190
- },
191
- webSearch: () => definition(sync('', 'webSearch')),
312
+ }),
313
+ webSearch: () => definition(() => sync('', 'webSearch')),
314
+ image: () => definition(() => sync('', 'image')),
192
315
  };
193
316
  }
@@ -1,6 +1,6 @@
1
- import type { CoreImageInput } from '../../runtime/src/core/port';
1
+ import type { CoreAttachmentInput } from '../../runtime/src/core/port';
2
2
  export interface NativeCoreWire {
3
- call(handle: string, method: string, argsJson: string, images?: readonly CoreImageInput[]): Promise<string>;
3
+ call(handle: string, method: string, argsJson: string, images?: readonly CoreAttachmentInput[]): Promise<string>;
4
4
  callSync(handle: string, method: string, argsJson: string): string;
5
5
  reply(call: string, completionJson: string): void;
6
6
  listen(receive: (packet: NativeCorePacket) => void): () => void;
@@ -18,9 +18,26 @@ export type NativeCorePacket = {
18
18
  callJson: string;
19
19
  contextJson: string;
20
20
  cancel: string;
21
+ attachments: string;
21
22
  } | {
22
23
  type: 'cancel';
23
24
  token: string;
25
+ } | {
26
+ type: 'image';
27
+ host: string;
28
+ call: string;
29
+ operation: string;
30
+ bytes: number[];
31
+ options: Record<string, unknown>;
32
+ cancel: string;
33
+ } | {
34
+ type: 'blob';
35
+ host: string;
36
+ call: string;
37
+ operation: 'put' | 'get' | 'delete' | 'list' | 'purgeStaging';
38
+ key: string;
39
+ cursor?: string | null;
40
+ bytes?: number[] | null;
24
41
  } | {
25
42
  type: 'storage';
26
43
  storage: string;
@@ -35,4 +52,4 @@ export type NativeCorePacket = {
35
52
  executors: string[];
36
53
  tokens: string[];
37
54
  };
38
- export type StorageMethod = 'read' | 'write' | 'remove' | 'list' | 'lock' | 'unlock' | 'readSecret' | 'writeSecret' | 'removeSecret';
55
+ export type StorageMethod = 'listState' | 'commit' | 'readVersioned' | 'writeIf' | 'read' | 'write' | 'remove' | 'purgeInstance' | 'list' | 'lock' | 'unlock' | 'readSecret' | 'writeSecret' | 'removeSecret';
@@ -2,15 +2,15 @@
2
2
  "entry": "runtime/src/rn-entry.js",
3
3
  "adapter": "packages/react-native/src/shared-adapter.ts",
4
4
  "sharedSources": {
5
- "index.native.ts": "547a67537afc3779155b72908ff258d79c6942190e8e8dda889cc36d65c85688",
6
- "croche.ts": "1199107945e28cec9df5d036a0db0fac2edc6cb176b784683b3580351ce22b09",
7
- "agent.ts": "111db2caf774094da0fb3c8292ec0ee2beb8a1068f258ee3532ccb3986fdf7d0",
8
- "tools.ts": "5225d7bd5b5a970a8c8aac38bbf650b079c99ac083140c549c0057de24423b7d",
9
- "app-api.ts": "d5c718aa3ed87f2167f12ed42f273e1d9c3302e721a5f89dfa83d08f74b2510d",
5
+ "index.native.ts": "fd49a25a980261999953af3751957beaab10ba50fb0ff4e2337a48de28223190",
6
+ "croche.ts": "82fecd1846a74db9670cc99b9531c53624a92250798feb85a6deeb2ef1fa21d6",
7
+ "agent.ts": "841d7186955bea267deb5036de573a3fe5dbf5f1feddc1318084da790c744462",
8
+ "tools.ts": "0a986ed325134af30d32bf2e7f88808e8e8ae10e7ab56945346f01d7b3a2a85d",
9
+ "app-api.ts": "c6b331da01222f449513e97f9feeb7464b14b53ba73be769fc2d8c510878741d",
10
10
  "json.ts": "b46f716b14c7db7945e6e9291736f1594e7bd141dcb48dd0823bc34e0500255c",
11
- "errors.ts": "9f2dfdc12d4a4e689e90c39544747cf8014d6e9a16b31d17e422bbec4df494cb",
12
- "cancel.ts": "a0bfb67aab8543b19790da28f0b0014c3f77009bf5ab376d636aec9dd785cd93",
13
- "core/port.ts": "686f27c508782b9d8fa66076989d849a871f13e1478c3ff3d32a35a3880db3fb"
11
+ "errors.ts": "4700c124cddcd35572654e994e52e1aad77bc41bf08cad6956a422cb48007a51",
12
+ "cancel.ts": "56d985e387b6f7364546779d89b55e3b8388473c31ed6ecc37d052624896a169",
13
+ "core/port.ts": "90a7155ba0cb2ff9005e6f89c130f37c590d9d5238753a1f14cc306c996f5d03"
14
14
  },
15
15
  "wasm": false
16
16
  }
@@ -0,0 +1,8 @@
1
+ import type { Adapter, BlobStore, ImageAdapter, StateStore } from './app-api.js';
2
+ type SelectedAdapters = {
3
+ blob?: BlobStore;
4
+ image?: ImageAdapter;
5
+ storage?: StateStore;
6
+ };
7
+ export declare function adaptersFor(adapters: readonly Adapter[] | undefined): SelectedAdapters;
8
+ export {};
@@ -0,0 +1,29 @@
1
+ import { CrocheError } from './errors.js';
2
+ export function adaptersFor(adapters) {
3
+ const selected = {};
4
+ if (adapters === undefined)
5
+ return selected;
6
+ if (!Array.isArray(adapters))
7
+ throw new CrocheError('invalid_configuration', 'adapters must be an array.', 'setup');
8
+ for (const adapter of adapters) {
9
+ const kind = adapter?.kind;
10
+ if (kind !== 'blob' && kind !== 'image' && kind !== 'state')
11
+ throw new CrocheError('invalid_configuration', 'Unknown adapter kind.', 'setup');
12
+ const slot = kind === 'state' ? 'storage' : kind;
13
+ if (selected[slot] !== undefined)
14
+ throw new CrocheError('invalid_configuration', `Duplicate adapter kind: ${kind}.`, 'setup');
15
+ if (kind === 'image')
16
+ selected.image = adapter;
17
+ else if (kind === 'state')
18
+ selected.storage = adapter;
19
+ else {
20
+ const blobs = adapter;
21
+ const missing = ['put', 'get', 'delete', 'list'].filter(name => typeof blobs[name] !== 'function');
22
+ if (missing.length) {
23
+ throw new CrocheError('invalid_configuration', `BlobStore is missing required methods: ${missing.join(', ')}.`, 'setup');
24
+ }
25
+ selected.blob = blobs;
26
+ }
27
+ }
28
+ return selected;
29
+ }
@@ -1,4 +1,4 @@
1
- import type { DecideInput, DecisionResult, MemoryItem, RequestResult, SendInput, SendOptions, SendReceipt, SubscribeOptions, Subscription, ToolScope, WikiScope } from './app-api.js';
1
+ import type { DecideInput, DecisionResult, MemoryItem, RequestResult, SendInput, SendOptions, SendReceipt, SubscribeOptions, Subscription, ToolScope, WikiScope, ListOptions, Page } from './app-api.js';
2
2
  import type { CoreAgent, CoreModule } from './core/port.js';
3
3
  /** Core's handle for an Agent (the debugger takes it); undefined for anything else. */
4
4
  export declare function coreAgent(agent: unknown): CoreAgent | undefined;
@@ -10,34 +10,82 @@ export declare function coreAgent(agent: unknown): CoreAgent | undefined;
10
10
  export declare const wrapAgent: (module: CoreModule, core: CoreAgent) => Agent;
11
11
  /** Available through the web/Node entry; RN omits it until the native bridge is proven. */
12
12
  export interface Agent {
13
+ /** Classify app data for a workflow, such as routing a support ticket without starting a chat. */
13
14
  decide(input: DecideInput, options?: {
14
15
  signal?: AbortSignal;
15
16
  }): Promise<DecisionResult>;
16
17
  }
18
+ /** One agent conversation with requests, transcript subscription and instance controls. */
17
19
  export declare class Agent {
18
20
  #private;
19
21
  private constructor();
22
+ /** Load an attachment when someone opens it from this conversation. */
23
+ attachment(id: string): Promise<{
24
+ mediaType: string;
25
+ data: string;
26
+ }>;
27
+ /** Let a user remove a file they no longer want kept with this conversation. */
28
+ deleteAttachment(id: string): Promise<void>;
29
+ /** Show the files a user can revisit from this conversation. */
30
+ listAttachments(options?: ListOptions): Promise<Page<import('./app-api.js').Attachment>>;
31
+ /** Bring a file from another conversation into this one before sharing it here. */
32
+ copyAttachment(source: {
33
+ agent: string;
34
+ instance?: string;
35
+ id: string;
36
+ }): Promise<import('./app-api.js').Attachment>;
37
+ /** Let the app drop its hold on a file when the user removes it from a draft. */
38
+ releaseAttachment(id: string): Promise<void>;
39
+ /** Let an app associate a reply with the configured agent that produced it. */
20
40
  get id(): string;
41
+ /** Let an app distinguish two conversations that use the same agent definition. */
21
42
  get instance(): string | null;
22
- /** Resolves when Core has ACCEPTED the input. The signal is sugar for cancel(id): before acceptance = never queued. */
43
+ /**
44
+ * Accept input from chat without making the UI wait for the reply.
45
+ *
46
+ * Resolves when Core accepts the input. Aborting before acceptance prevents it from being queued.
47
+ */
23
48
  send(input: SendInput, options?: SendOptions): Promise<SendReceipt>;
24
- /** Resolves when the input is final; with wait: 'idle', when the agent is idle too. */
49
+ /**
50
+ * Wait for an outcome when an app workflow needs to decide what happens next.
51
+ *
52
+ * Resolves when the input is final; with wait: 'idle', when the agent is idle too.
53
+ * After acceptance, aborting the signal rejects the wait with `aborted` and the input continues.
54
+ */
25
55
  request(input: SendInput, options?: SendOptions & {
26
56
  wait?: 'idle';
27
57
  }): Promise<RequestResult>;
28
- /** Events arrive in Core's order; an unknown type passes through unchanged. */
58
+ /**
59
+ * Keep a chat screen in step with the agent as messages and tool activity arrive.
60
+ *
61
+ * Events arrive in Core's order; an unknown type passes through unchanged.
62
+ */
29
63
  subscribe(options: SubscribeOptions): Subscription;
64
+ /** Let the user stop a reply or withdraw input they no longer want processed. */
30
65
  cancel(id?: string): Promise<void>;
66
+ /** Let a user clear the conversation they see while keeping the agent available. Clears
67
+ * the whole conversation; it takes no options (partial clear was removed in 0.7). An
68
+ * untyped caller's argument still reaches Core, which refuses it rather than clear all. */
31
69
  clearHistory(): Promise<void>;
70
+ /** Access controls for this conversation's memory. */
32
71
  readonly memory: {
33
- list: () => Promise<MemoryItem[]>;
72
+ /** Show the user what the agent remembers so they can review it. */
73
+ list: (options?: ListOptions) => Promise<Page<MemoryItem>>;
74
+ /** Let the user remove one remembered fact without clearing the rest. */
34
75
  delete: (id: string) => Promise<void>;
76
+ /** Let the user start over with a clean memory while keeping their conversation. */
35
77
  clear: () => Promise<void>;
78
+ /** Let the user choose whether the agent uses memory in this conversation. */
36
79
  enabled: (on: boolean) => Promise<void>;
37
80
  };
81
+ /** Limit an agent to the actions appropriate for the user’s current workflow. */
38
82
  setTools(scope: ToolScope | 'all'): Promise<void>;
83
+ /** Restore the usual actions after the user leaves a restricted workflow. */
39
84
  resetTools(): Promise<void>;
85
+ /** Give an agent help material relevant to the screen or workspace the user is in. */
40
86
  setWiki(scope: WikiScope | 'all'): Promise<void>;
87
+ /** Restore the usual help material after the user leaves a specialized workspace. */
41
88
  resetWiki(): Promise<void>;
89
+ /** Release an agent when the app leaves its conversation and no longer needs the handle. */
42
90
  close(): Promise<void>;
43
91
  }
@@ -2,6 +2,7 @@ import { tokenFor } from './cancel.js';
2
2
  import { eventSink } from './events.js';
3
3
  import { decodeAgentEvent } from './generated/app-stream.js';
4
4
  import { jsonText, optionsText } from './json.js';
5
+ import { imageInput } from './image-input.js';
5
6
  const handles = new WeakMap();
6
7
  /** Core's handle for an Agent (the debugger takes it); undefined for anything else. */
7
8
  export function coreAgent(agent) {
@@ -20,6 +21,7 @@ function withoutSignal(options) {
20
21
  * Native 0.87 Babel preset cannot parse in an app's Metro bundle (0.6.1 P12).
21
22
  */
22
23
  export const wrapAgent = (module, core) => Reflect.construct(Agent, [module, core]);
24
+ /** One agent conversation with requests, transcript subscription and instance controls. */
23
25
  export class Agent {
24
26
  #core;
25
27
  #module;
@@ -35,21 +37,50 @@ export class Agent {
35
37
  } });
36
38
  }
37
39
  }
40
+ /** Load an attachment when someone opens it from this conversation. */
41
+ attachment(id) { return this.#core.attachment(id).then(JSON.parse); }
42
+ /** Let a user remove a file they no longer want kept with this conversation. */
43
+ deleteAttachment(id) { return this.#core.deleteAttachment(id); }
44
+ /** Show the files a user can revisit from this conversation. */
45
+ listAttachments(options) {
46
+ return this.#core.listAttachments(optionsText(options)).then(JSON.parse);
47
+ }
48
+ /** Bring a file from another conversation into this one before sharing it here. */
49
+ copyAttachment(source) { return this.#core.copyAttachment(jsonText(source)).then(JSON.parse); }
50
+ /** Let the app drop its hold on a file when the user removes it from a draft. */
51
+ releaseAttachment(id) { return this.#core.releaseAttachment(id); }
52
+ /** Let an app associate a reply with the configured agent that produced it. */
38
53
  get id() { return this.#core.id; }
54
+ /** Let an app distinguish two conversations that use the same agent definition. */
39
55
  get instance() { return this.#core.instance ?? null; }
40
- /** Resolves when Core has ACCEPTED the input. The signal is sugar for cancel(id): before acceptance = never queued. */
56
+ /**
57
+ * Accept input from chat without making the UI wait for the reply.
58
+ *
59
+ * Resolves when Core accepts the input. Aborting before acceptance prevents it from being queued.
60
+ */
41
61
  async send(input, options) {
42
62
  const [signal, rest] = withoutSignal(options);
43
- const answer = await this.#core.send(jsonText(input), [], optionsText(rest), tokenFor(this.#module, signal));
63
+ const [inputJson, images] = imageInput(input);
64
+ const answer = await this.#core.send(inputJson, images, optionsText(rest), tokenFor(this.#module, signal));
44
65
  return JSON.parse(answer);
45
66
  }
46
- /** Resolves when the input is final; with wait: 'idle', when the agent is idle too. */
67
+ /**
68
+ * Wait for an outcome when an app workflow needs to decide what happens next.
69
+ *
70
+ * Resolves when the input is final; with wait: 'idle', when the agent is idle too.
71
+ * After acceptance, aborting the signal rejects the wait with `aborted` and the input continues.
72
+ */
47
73
  async request(input, options) {
48
74
  const [signal, rest] = withoutSignal(options);
49
- const answer = await this.#core.request(jsonText(input), [], optionsText(rest), tokenFor(this.#module, signal));
75
+ const [inputJson, images] = imageInput(input);
76
+ const answer = await this.#core.request(inputJson, images, optionsText(rest), tokenFor(this.#module, signal));
50
77
  return JSON.parse(answer);
51
78
  }
52
- /** Events arrive in Core's order; an unknown type passes through unchanged. */
79
+ /**
80
+ * Keep a chat screen in step with the agent as messages and tool activity arrive.
81
+ *
82
+ * Events arrive in Core's order; an unknown type passes through unchanged.
83
+ */
53
84
  subscribe(options) {
54
85
  const { onEvent, ...selection } = options;
55
86
  const subscription = this.#core.subscribe(optionsText(selection), eventSink(onEvent, decodeAgentEvent));
@@ -59,17 +90,48 @@ export class Agent {
59
90
  get ended() { return subscription.ended; },
60
91
  };
61
92
  }
93
+ /** Let the user stop a reply or withdraw input they no longer want processed. */
62
94
  cancel(id) { return this.#core.cancel(id); }
63
- clearHistory() { return this.#core.clearHistory(); }
95
+ /** Let a user clear the conversation they see while keeping the agent available. Clears
96
+ * the whole conversation; it takes no options (partial clear was removed in 0.7). An
97
+ * untyped caller's argument still reaches Core, which refuses it rather than clear all. */
98
+ // eslint-disable-next-line prefer-rest-params
99
+ clearHistory() { return this.#core.clearHistory(clearOptionsText(arguments[0])); }
100
+ /** Access controls for this conversation's memory. */
64
101
  memory = {
65
- list: async () => JSON.parse(await this.#core.memoryList()),
102
+ /** Show the user what the agent remembers so they can review it. */
103
+ list: async (options) => JSON.parse(await this.#core.memoryList(optionsText(options))),
104
+ /** Let the user remove one remembered fact without clearing the rest. */
66
105
  delete: (id) => this.#core.memoryDelete(id),
106
+ /** Let the user start over with a clean memory while keeping their conversation. */
67
107
  clear: () => this.#core.memoryClear(),
108
+ /** Let the user choose whether the agent uses memory in this conversation. */
68
109
  enabled: (on) => this.#core.memoryEnabled(on),
69
110
  };
111
+ /** Limit an agent to the actions appropriate for the user’s current workflow. */
70
112
  setTools(scope) { return this.#core.setTools(jsonText(scope)); }
113
+ /** Restore the usual actions after the user leaves a restricted workflow. */
71
114
  resetTools() { return this.#core.resetTools(); }
115
+ /** Give an agent help material relevant to the screen or workspace the user is in. */
72
116
  setWiki(scope) { return this.#core.setWiki(jsonText(scope)); }
117
+ /** Restore the usual help material after the user leaves a specialized workspace. */
73
118
  resetWiki() { return this.#core.resetWiki(); }
119
+ /** Release an agent when the app leaves its conversation and no longer needs the handle. */
74
120
  close() { return this.#core.shutdown(); }
75
121
  }
122
+ /** `clearHistory` takes no options, and Core refuses any. A supplied key reaches Core even
123
+ * when its value is `undefined` (sent as null), so `{before: undefined}` from a cursor that
124
+ * has not loaded is refused instead of becoming `{}`, a full clear (Tarn, #1799). */
125
+ function clearOptionsText(options) {
126
+ if (options === null || typeof options !== 'object' || Array.isArray(options))
127
+ return optionsText(options);
128
+ const keys = Reflect.ownKeys(options);
129
+ if (keys.length === 0)
130
+ return optionsText(options);
131
+ const sent = Object.create(null);
132
+ for (const key of keys) {
133
+ const value = options[key];
134
+ sent[String(key)] = value === undefined ? null : value;
135
+ }
136
+ return optionsText(sent);
137
+ }