@h1r-ai/croche-react-native 0.0.0-stage → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +32 -0
- package/README.md +486 -2
- package/THIRD-PARTY-NOTICES +5824 -0
- package/android/build.gradle +47 -0
- package/android/src/main/AndroidManifest.xml +8 -0
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +837 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
- package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +14 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +32 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +120 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +116 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +415 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +379 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +25 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +46 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +44 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +227 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +28 -0
- package/ios/CrocheRuntimeBridge.swift +1008 -0
- package/ios/RNCrocheRuntime.mm +221 -0
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +215 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +562 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +172 -0
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
- package/ios/vendor/CrocheRuntimeSDK/PortableSHA256.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +271 -0
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +558 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +453 -0
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +345 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
- package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +40 -4
- package/scripts/vendor-native.sh +56 -0
- package/src/NativeCrocheRuntime.ts +162 -0
- package/src/index.ts +660 -0
- package/src/project-types.ts +35 -0
- package/src/project.ts +434 -0
- package/src/protocol.ts +28 -0
- package/src/types.ts +9 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// TurboModule entry point (New Architecture). Forwards to the Swift CrocheRuntimeBridge and
|
|
2
|
+
// emits the single `CrocheRuntimeEvent` stream.
|
|
3
|
+
#import <React/RCTEventEmitter.h>
|
|
4
|
+
#import <CrocheRuntimeSpec/CrocheRuntimeSpec.h>
|
|
5
|
+
#import "croche_react_native-Swift.h"
|
|
6
|
+
|
|
7
|
+
@interface RNCrocheRuntime : RCTEventEmitter <NativeCrocheRuntimeSpec>
|
|
8
|
+
@end
|
|
9
|
+
|
|
10
|
+
// RN converts synchronous NSExceptions to JSError.cause, losing the top-level code.
|
|
11
|
+
// Restore the Core code at the native boundary; the JS package remains unchanged.
|
|
12
|
+
class CrocheRuntimeSpecJSI final : public facebook::react::NativeCrocheRuntimeSpecJSI {
|
|
13
|
+
public:
|
|
14
|
+
explicit CrocheRuntimeSpecJSI(const facebook::react::ObjCTurboModule::InitParams ¶ms)
|
|
15
|
+
: NativeCrocheRuntimeSpecJSI(params) {
|
|
16
|
+
methodMap_["projectInfo"] = {1, [](facebook::jsi::Runtime &runtime, facebook::react::TurboModule &module,
|
|
17
|
+
const facebook::jsi::Value *args, size_t count) -> facebook::jsi::Value {
|
|
18
|
+
try {
|
|
19
|
+
return static_cast<facebook::react::ObjCTurboModule &>(module).invokeObjCMethod(
|
|
20
|
+
runtime, facebook::react::StringKind, "projectInfo", @selector(projectInfo:), args, count);
|
|
21
|
+
} catch (facebook::jsi::JSError &error) {
|
|
22
|
+
auto object = error.value().asObject(runtime);
|
|
23
|
+
auto cause = object.getProperty(runtime, "cause");
|
|
24
|
+
if (cause.isObject()) {
|
|
25
|
+
auto details = cause.asObject(runtime);
|
|
26
|
+
object.setProperty(runtime, "code", details.getProperty(runtime, "name"));
|
|
27
|
+
object.setProperty(runtime, "message", details.getProperty(runtime, "message"));
|
|
28
|
+
}
|
|
29
|
+
throw;
|
|
30
|
+
}
|
|
31
|
+
}};
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
@implementation RNCrocheRuntime {
|
|
36
|
+
CrocheRuntimeBridge *_bridge;
|
|
37
|
+
BOOL _observing;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
RCT_EXPORT_MODULE(CrocheRuntime)
|
|
41
|
+
|
|
42
|
+
- (instancetype)init {
|
|
43
|
+
if (self = [super init]) {
|
|
44
|
+
_bridge = [CrocheRuntimeBridge new];
|
|
45
|
+
__weak RNCrocheRuntime *weakSelf = self;
|
|
46
|
+
_bridge.emit = ^(NSString *handle, NSString *type, NSString *json) {
|
|
47
|
+
RNCrocheRuntime *strongSelf = weakSelf;
|
|
48
|
+
if (strongSelf && strongSelf->_observing) {
|
|
49
|
+
[strongSelf sendEventWithName:@"CrocheRuntimeEvent" body:@{@"handle": handle, @"type": type, @"json": json}];
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
_bridge.emitStream = ^(NSString *handle, NSString *type, NSString *json) {
|
|
53
|
+
RNCrocheRuntime *strongSelf = weakSelf;
|
|
54
|
+
if (!strongSelf) return;
|
|
55
|
+
// Raw stream callbacks are never filtered by the legacy _observing flag.
|
|
56
|
+
[strongSelf sendEventWithName:@"CrocheRuntimeEvent" body:@{@"handle": handle, @"type": type, @"json": json}];
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
return self;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
+ (BOOL)requiresMainQueueSetup { return NO; }
|
|
63
|
+
// One serial queue: sends are admitted on it (CrocheRuntimeBridge.send) in the order JS made them.
|
|
64
|
+
- (dispatch_queue_t)methodQueue {
|
|
65
|
+
static dispatch_queue_t queue;
|
|
66
|
+
static dispatch_once_t once;
|
|
67
|
+
dispatch_once(&once, ^{ queue = dispatch_queue_create("dev.croche.react-native", DISPATCH_QUEUE_SERIAL); });
|
|
68
|
+
return queue;
|
|
69
|
+
}
|
|
70
|
+
- (NSArray<NSString *> *)supportedEvents { return @[@"CrocheRuntimeEvent"]; }
|
|
71
|
+
- (void)startObserving { _observing = YES; }
|
|
72
|
+
- (void)stopObserving { _observing = NO; }
|
|
73
|
+
|
|
74
|
+
- (void)open:(NSString *)handle configJson:(NSString *)configJson optionsJson:(NSString *)optionsJson
|
|
75
|
+
resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
76
|
+
[_bridge open:handle configJson:configJson optionsJson:optionsJson
|
|
77
|
+
resolve:^(NSString *value) { resolve(value); }
|
|
78
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
- (void)send:(NSString *)handle inputJson:(NSString *)inputJson responseFormatJson:(NSString *)responseFormatJson callId:(NSString *)callId
|
|
82
|
+
resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
83
|
+
[_bridge send:handle inputJson:inputJson responseFormatJson:responseFormatJson callId:callId
|
|
84
|
+
resolve:^(NSString *value) { resolve(value); }
|
|
85
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
- (void)projectDeleteStore:(NSString *)optionsJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
89
|
+
[_bridge projectDeleteStore:optionsJson resolve:^{ resolve(nil); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
90
|
+
}
|
|
91
|
+
- (void)projectOpen:(NSString *)project optionsJson:(NSString *)optionsJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
92
|
+
[_bridge projectOpen:project optionsJson:optionsJson resolve:^(NSString *value) { resolve(value); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
93
|
+
}
|
|
94
|
+
- (NSString *)projectInfo:(NSString *)project {
|
|
95
|
+
NSError *error = nil;
|
|
96
|
+
NSString *value = [_bridge projectInfo:project error:&error];
|
|
97
|
+
if (!value) {
|
|
98
|
+
// The native JSI wrapper below retains this code on the synchronous JS error.
|
|
99
|
+
@throw [NSException exceptionWithName:error.userInfo[@"code"] ?: @"native_error"
|
|
100
|
+
reason:error.localizedDescription userInfo:nil];
|
|
101
|
+
}
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
- (NSString *)agentState:(NSString *)handle { return [_bridge agentState:handle]; }
|
|
105
|
+
- (void)projectAgent:(NSString *)project handle:(NSString *)handle id:(NSString *)id optionsJson:(NSString *)optionsJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
106
|
+
[_bridge projectAgent:project handle:handle id:id optionsJson:optionsJson resolve:^(NSString *value) { resolve(value); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
107
|
+
}
|
|
108
|
+
- (void)projectClose:(NSString *)project resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
109
|
+
[_bridge projectClose:project resolve:^{ resolve(nil); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
110
|
+
}
|
|
111
|
+
- (void)agentControl:(NSString *)handle op:(NSString *)op argsJson:(NSString *)argsJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
112
|
+
[_bridge agentControl:handle op:op argsJson:argsJson resolve:^(NSString *value) { resolve(value); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
113
|
+
}
|
|
114
|
+
- (void)cancelTurn:(NSString *)handle resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
115
|
+
[_bridge cancelTurn:handle resolve:^{ resolve(nil); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
- (void)observe:(NSString *)handle resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
119
|
+
[_bridge observe:handle resolve:^{ resolve(nil); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
120
|
+
}
|
|
121
|
+
- (void)unobserve:(NSString *)handle { [_bridge unobserve:handle]; }
|
|
122
|
+
- (void)select:(NSString *)handle selectionJson:(NSString *)selectionJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
123
|
+
[_bridge select:handle selectionJson:selectionJson resolve:^(NSNumber *value) { resolve(value); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
124
|
+
}
|
|
125
|
+
- (void)closeProjection:(NSString *)handle projection:(double)projection { [_bridge closeProjection:handle projection:projection]; }
|
|
126
|
+
- (void)history:(NSString *)handle projection:(double)projection before:(double)before limit:(double)limit resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
127
|
+
[_bridge history:handle projection:projection before:before limit:limit resolve:^{ resolve(nil); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
128
|
+
}
|
|
129
|
+
- (void)readOutcome:(NSString *)handle id:(NSString *)id fromSeq:(double)fromSeq readId:(NSString *)readId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
130
|
+
[_bridge readOutcome:handle id:id fromSeq:fromSeq readId:readId resolve:^(NSString *value) { resolve(value); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
131
|
+
}
|
|
132
|
+
- (void)sendReceipt:(NSString *)handle inputJson:(NSString *)inputJson responseFormatJson:(NSString *)responseFormatJson callId:(NSString *)callId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
133
|
+
[_bridge sendReceipt:handle inputJson:inputJson responseFormatJson:responseFormatJson callId:callId resolve:^(NSString *value) { resolve(value); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
134
|
+
}
|
|
135
|
+
- (void)cancelInput:(NSString *)handle id:(NSString *)id resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
136
|
+
[_bridge cancelInput:handle id:id resolve:^{ resolve(nil); } reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
- (void)cancel:(NSString *)handle { [_bridge cancel:handle]; }
|
|
140
|
+
|
|
141
|
+
- (void)cancelSend:(NSString *)handle callId:(NSString *)callId { [_bridge cancelSend:handle callId:callId]; }
|
|
142
|
+
|
|
143
|
+
- (void)clearQueued:(NSString *)handle resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
144
|
+
[_bridge clearQueued:handle
|
|
145
|
+
resolve:^(NSNumber *value) { resolve(value); }
|
|
146
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
- (void)inspect:(NSString *)handle resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
150
|
+
[_bridge inspect:handle
|
|
151
|
+
resolve:^(NSString *value) { resolve(value); }
|
|
152
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
- (void)maintain:(NSString *)handle force:(BOOL)force
|
|
156
|
+
resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
157
|
+
[_bridge maintain:handle force:force
|
|
158
|
+
resolve:^(NSString *value) { resolve(value); }
|
|
159
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
- (void)deliverDue:(NSString *)handle resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
163
|
+
[_bridge deliverDue:handle
|
|
164
|
+
resolve:^(NSString *value) { resolve(value); }
|
|
165
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
- (void)schedules:(NSString *)handle resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
169
|
+
[_bridge schedules:handle
|
|
170
|
+
resolve:^(NSString *value) { resolve(value); }
|
|
171
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
- (void)adjustBudget:(NSString *)handle amount:(double)amount absolute:(BOOL)absolute id:(NSString *)id
|
|
175
|
+
resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
176
|
+
[_bridge adjustBudget:handle amount:amount absolute:absolute id:id
|
|
177
|
+
resolve:^(NSString *value) { resolve(value); }
|
|
178
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
- (void)wiki:(NSString *)handle op:(NSString *)op argsJson:(NSString *)argsJson
|
|
182
|
+
resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
183
|
+
[_bridge wiki:handle op:op argsJson:argsJson
|
|
184
|
+
resolve:^(NSString *value) { resolve(value); }
|
|
185
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
- (void)memory:(NSString *)handle op:(NSString *)op argsJson:(NSString *)argsJson
|
|
189
|
+
resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
190
|
+
[_bridge memory:handle op:op argsJson:argsJson
|
|
191
|
+
resolve:^(NSString *value) { resolve(value); }
|
|
192
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
- (void)setTools:(NSString *)handle toolsJson:(NSString *)toolsJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
196
|
+
[_bridge setTools:handle toolsJson:toolsJson
|
|
197
|
+
resolve:^{ resolve(nil); }
|
|
198
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
- (void)clearHistory:(NSString *)handle resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
202
|
+
[_bridge clearHistory:handle
|
|
203
|
+
resolve:^{ resolve(nil); }
|
|
204
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
- (void)close:(NSString *)handle resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
208
|
+
[_bridge close:handle
|
|
209
|
+
resolve:^{ resolve(nil); }
|
|
210
|
+
reject:^(NSString *code, NSString *message) { reject(code, message, nil); }];
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
- (void)resolveTool:(NSString *)callId ok:(BOOL)ok resultJson:(NSString *)resultJson {
|
|
214
|
+
[_bridge resolveTool:callId ok:ok resultJson:resultJson];
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {
|
|
218
|
+
return std::make_shared<CrocheRuntimeSpecJSI>(params);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
@end
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(BackgroundTasks) && os(iOS)
|
|
3
|
+
import BackgroundTasks
|
|
4
|
+
|
|
5
|
+
/// The agent's scheduled notes on iOS while the app is not running: one `BGAppRefreshTaskRequest`
|
|
6
|
+
/// at the earliest note (`earliestBeginDate`), replaced at each change and withdrawn when none is
|
|
7
|
+
/// pending. iOS decides when it runs, possibly late or never for a rarely used app; the next
|
|
8
|
+
/// foreground delivers what it missed. No permission prompt, no notification.
|
|
9
|
+
///
|
|
10
|
+
/// App setup (Xcode): add `identifier` to `BGTaskSchedulerPermittedIdentifiers` in Info.plist,
|
|
11
|
+
/// enable Background Modes > Background fetch, and call `registerHandler` before
|
|
12
|
+
/// `application(_:didFinishLaunchingWithOptions:)` returns. Without the Info.plist entry a request
|
|
13
|
+
/// is refused, and the Runtime reports `schedule.degraded` with reason `not_configured`.
|
|
14
|
+
public final class AppRefreshScheduler: RuntimeScheduler, @unchecked Sendable {
|
|
15
|
+
public let identifier: String
|
|
16
|
+
public init(identifier: String) { self.identifier = identifier }
|
|
17
|
+
|
|
18
|
+
public func schedule(earliest: Date) throws {
|
|
19
|
+
let request = BGAppRefreshTaskRequest(identifier: identifier)
|
|
20
|
+
request.earliestBeginDate = earliest
|
|
21
|
+
do { try BGTaskScheduler.shared.submit(request) }
|
|
22
|
+
catch let error as BGTaskScheduler.Error where error.code == .notPermitted {
|
|
23
|
+
throw CrocheError("not_configured", "Add \(identifier) to BGTaskSchedulerPermittedIdentifiers and enable Background fetch")
|
|
24
|
+
} catch let error as BGTaskScheduler.Error where error.code == .unavailable {
|
|
25
|
+
throw CrocheError("background_unavailable", "Background App Refresh is off or unavailable here")
|
|
26
|
+
} catch {
|
|
27
|
+
throw CrocheError("schedule_failed", "BGTaskScheduler refused the request")
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
public func cancel() { BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: identifier) }
|
|
31
|
+
|
|
32
|
+
/// One open Runtime per identifier: a run delivers through the one Runtime its identifier
|
|
33
|
+
/// names (Atlas, #323 P1-2). This scheduler object is no exception: `create` attaches once per
|
|
34
|
+
/// Runtime, so a second attach while the identifier is held is refused, whoever holds it
|
|
35
|
+
/// (Atlas, #323 at dc38bf0). Close-and-reuse stays valid.
|
|
36
|
+
public func attach() throws { try Self.claims.claim(identifier, by: self) }
|
|
37
|
+
public func detach() { Self.claims.release(identifier, by: self) }
|
|
38
|
+
private static let claims = SchedulerClaims(what: "task identifier")
|
|
39
|
+
|
|
40
|
+
/// Registers what runs when iOS launches the task: `runtime` returns the app's Runtime
|
|
41
|
+
/// (opening it when the app was launched for this task), whose `deliverDue()` then runs. When
|
|
42
|
+
/// iOS ends the background time first, the delivery turn is cancelled and its notes stay
|
|
43
|
+
/// pending. Call once, before `application(_:didFinishLaunchingWithOptions:)` returns.
|
|
44
|
+
@discardableResult
|
|
45
|
+
public func registerHandler(runtime: @escaping @Sendable () async throws -> CrocheRuntime) -> Bool {
|
|
46
|
+
BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: nil) { task in
|
|
47
|
+
let granted = GrantedTask(task)
|
|
48
|
+
let delivery = BackgroundDelivery(open: runtime)
|
|
49
|
+
task.expirationHandler = { delivery.expire() }
|
|
50
|
+
delivery.start { success in granted.task.setTaskCompleted(success: success) }
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private final class GrantedTask: @unchecked Sendable {
|
|
56
|
+
let task: BGTask
|
|
57
|
+
init(_ task: BGTask) { self.task = task }
|
|
58
|
+
}
|
|
59
|
+
#endif
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
public typealias ControlSend = @Sendable (_ input: JSON, _ cancellation: RuntimeCancellation) async throws -> JSON
|
|
4
|
+
public typealias ControlCancel = @Sendable () async -> Bool
|
|
5
|
+
|
|
6
|
+
/// Opt-in attachment of an existing Runtime. This broker token is unrelated to Cloud
|
|
7
|
+
/// developer/project credentials. No Runtime identity or storage is opened here.
|
|
8
|
+
public actor RuntimeControl {
|
|
9
|
+
public nonisolated let runtimeInstanceId: String
|
|
10
|
+
public nonisolated let capabilities = ["status", "history", "send", "cancel", "sync", "budget.get", "budget.set", "tools"]
|
|
11
|
+
private let runtime: CrocheRuntime
|
|
12
|
+
private let url: String
|
|
13
|
+
private let token: String
|
|
14
|
+
private let clientId = UUID().uuidString
|
|
15
|
+
private let http: RuntimeHTTP
|
|
16
|
+
private let sendAdapter: ControlSend?
|
|
17
|
+
private let cancelAdapter: ControlCancel?
|
|
18
|
+
private let onError: (@Sendable (CrocheError) -> Void)?
|
|
19
|
+
private let lifetime = RuntimeCancellation()
|
|
20
|
+
private var loop: Task<Void, Never>?
|
|
21
|
+
private var closed = false
|
|
22
|
+
private var handled = Set<String>()
|
|
23
|
+
private var results: [String: JSON] = [:]
|
|
24
|
+
private var active: [String: RuntimeCancellation] = [:]
|
|
25
|
+
private var tasks: [String: Task<Void, Never>] = [:]
|
|
26
|
+
|
|
27
|
+
private init(runtime: CrocheRuntime, runtimeInstanceId: String, url: String, token: String,
|
|
28
|
+
http: @escaping RuntimeHTTP, send: ControlSend?, cancel: ControlCancel?,
|
|
29
|
+
onError: (@Sendable (CrocheError) -> Void)?) {
|
|
30
|
+
self.runtime = runtime; self.runtimeInstanceId = runtimeInstanceId; self.url = url; self.token = token
|
|
31
|
+
self.http = http; sendAdapter = send; cancelAdapter = cancel; self.onError = onError
|
|
32
|
+
}
|
|
33
|
+
public static func attach(runtime: CrocheRuntime, url: String = "http://127.0.0.1:8791", token: String,
|
|
34
|
+
http: @escaping RuntimeHTTP = { try await RuntimeURLSession.send($0, cancellation: $1, onDelta: $2) },
|
|
35
|
+
send: ControlSend? = nil, cancel: ControlCancel? = nil,
|
|
36
|
+
onError: (@Sendable (CrocheError) -> Void)? = nil) async throws -> RuntimeControl {
|
|
37
|
+
guard let parsed = URLComponents(string: url), parsed.scheme == "http",
|
|
38
|
+
["localhost", "127.0.0.1", "[::1]", "::1"].contains(parsed.host ?? ""),
|
|
39
|
+
parsed.user == nil, parsed.password == nil, parsed.query == nil, parsed.fragment == nil,
|
|
40
|
+
parsed.path.isEmpty || parsed.path == "/",
|
|
41
|
+
token.range(of: "^[A-Za-z0-9._~-]{24,4096}$", options: .regularExpression) != nil else {
|
|
42
|
+
throw CrocheError("invalid_configuration", "Control requires a loopback HTTP origin and explicit local token")
|
|
43
|
+
}
|
|
44
|
+
let status = try await runtime.inspect()["status"]
|
|
45
|
+
let id = status["runtimeInstanceId"].string ?? ""
|
|
46
|
+
guard validControlId(id) else { throw CrocheError("invalid_configuration", "Invalid Runtime identity") }
|
|
47
|
+
let control = RuntimeControl(runtime: runtime, runtimeInstanceId: id,
|
|
48
|
+
url: url.hasSuffix("/") ? String(url.dropLast()) : url, token: token,
|
|
49
|
+
http: http, send: send, cancel: cancel, onError: onError)
|
|
50
|
+
try await control.start(status)
|
|
51
|
+
return control
|
|
52
|
+
}
|
|
53
|
+
private var identity: [String: JSON] { ["client_id": .string(clientId), "runtime_instance_id": .string(runtimeInstanceId)] }
|
|
54
|
+
private func register(_ status: JSON) async throws {
|
|
55
|
+
_ = try await post("register", .object(["client_id": .string(clientId), "runtime": status,
|
|
56
|
+
"capabilities": .array(capabilities.map(JSON.string))]))
|
|
57
|
+
}
|
|
58
|
+
private func start(_ status: JSON) async throws {
|
|
59
|
+
try await register(status)
|
|
60
|
+
loop = Task { [weak self] in
|
|
61
|
+
while !Task.isCancelled {
|
|
62
|
+
guard let keep = await self?.tick(), keep else { break }
|
|
63
|
+
do { try await Task.sleep(nanoseconds: 100_000_000) } catch { break }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
private func post(_ path: String, _ body: JSON) async throws -> JSON {
|
|
68
|
+
guard try body.encoded().count <= 1024 * 1024 else { throw CrocheError("control_capacity", "Control request exceeds 1MiB") }
|
|
69
|
+
let effect = JSON.object(["url": .string(url + "/v1/control/" + path), "method": .string("POST"),
|
|
70
|
+
"headers": .object(["Authorization": .string("Bearer " + token), "Content-Type": .string("application/json")]),
|
|
71
|
+
"body": body, "timeoutMs": .number(5000)])
|
|
72
|
+
let transport = http
|
|
73
|
+
let response = try await boundedEffect(milliseconds: 5000, cancellation: lifetime) { signal in try await transport(effect, signal) { _ in } }
|
|
74
|
+
let data = response["body"]
|
|
75
|
+
guard data.object != nil, try data.encoded().count <= 1024 * 1024 else { throw CrocheError("invalid_response", "Invalid bounded control response") }
|
|
76
|
+
guard let status = response["status"].number, (200..<300).contains(status) else {
|
|
77
|
+
throw CrocheError(data["error"]["code"].string ?? "control_error", "Local control broker rejected the request")
|
|
78
|
+
}
|
|
79
|
+
return data
|
|
80
|
+
}
|
|
81
|
+
private func tick() async -> Bool {
|
|
82
|
+
if closed { return false }
|
|
83
|
+
do {
|
|
84
|
+
for (id, result) in Array(results.prefix(8)) {
|
|
85
|
+
do { _ = try await post("results", result); results.removeValue(forKey: id) }
|
|
86
|
+
catch let error as CrocheError {
|
|
87
|
+
if ["not_found", "attachment_lost"].contains(error.code) { results.removeValue(forKey: id) }
|
|
88
|
+
throw error
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if results.count < 32 && tasks.count < 16 {
|
|
92
|
+
let response = try await post("poll", .object(identity))
|
|
93
|
+
guard let commands = response["commands"].array else { throw CrocheError("invalid_response", "Broker command list is invalid") }
|
|
94
|
+
for command in commands.prefix(8) { try accept(command) }
|
|
95
|
+
}
|
|
96
|
+
} catch {
|
|
97
|
+
if !closed {
|
|
98
|
+
let issue = error as? CrocheError ?? CrocheError("control_error", "Local control failed")
|
|
99
|
+
onError?(issue)
|
|
100
|
+
if issue.code == "attachment_lost" {
|
|
101
|
+
do { try await register(runtime.inspect()["status"]) } catch {}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return !closed
|
|
106
|
+
}
|
|
107
|
+
private func accept(_ value: JSON) throws {
|
|
108
|
+
let id = value["request_id"].string ?? "", command = value["command"].string ?? ""
|
|
109
|
+
guard validControlId(id), capabilities.contains(command), let payload = value["payload"].object else {
|
|
110
|
+
throw CrocheError("invalid_command", "Invalid control command envelope")
|
|
111
|
+
}
|
|
112
|
+
if handled.contains(id) { return }
|
|
113
|
+
guard handled.count < 1000 else { throw CrocheError("control_capacity", "Reattach after 1000 control requests") }
|
|
114
|
+
handled.insert(id)
|
|
115
|
+
tasks[id] = Task { await self.perform(id, command, .object(payload)) }
|
|
116
|
+
}
|
|
117
|
+
private func perform(_ id: String, _ command: String, _ payload: JSON) async {
|
|
118
|
+
var response = identity; response["request_id"] = .string(id)
|
|
119
|
+
do {
|
|
120
|
+
let result = try await execute(command, payload, id)
|
|
121
|
+
guard try result.encoded().count <= 900_000 else { throw CrocheError("result_too_large", "Request a smaller result page") }
|
|
122
|
+
response["result"] = result
|
|
123
|
+
} catch {
|
|
124
|
+
response["error"] = .object(["code": .string(publicControlCode(error)),
|
|
125
|
+
"message": .string("The Runtime command failed. Inspect it before retrying."),
|
|
126
|
+
"uncertain": .bool(command == "send" || command == "budget.set")])
|
|
127
|
+
}
|
|
128
|
+
if !closed { results[id] = .object(response) }
|
|
129
|
+
tasks.removeValue(forKey: id)
|
|
130
|
+
}
|
|
131
|
+
private func execute(_ command: String, _ payload: JSON, _ id: String) async throws -> JSON {
|
|
132
|
+
guard !closed else { throw CrocheError("control_closed", "Control is closed") }
|
|
133
|
+
let keys = Set(payload.object!.keys)
|
|
134
|
+
if command == "send" {
|
|
135
|
+
guard keys.isSubset(of: ["id", "text"]), validControlId(payload["id"].string ?? ""),
|
|
136
|
+
let text = payload["text"].string, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
|
137
|
+
text.utf16.count <= 32000 else { throw CrocheError("invalid_command", "send needs immutable id and text only") }
|
|
138
|
+
let signal = RuntimeCancellation(); active[id] = signal; defer { active.removeValue(forKey: id) }
|
|
139
|
+
if let sendAdapter { return try await sendAdapter(payload, signal) }
|
|
140
|
+
let task = Task { try await runtime.send(payload) }
|
|
141
|
+
let listener = signal.observe { task.cancel() }; defer { signal.remove(listener) }
|
|
142
|
+
return try await task.value
|
|
143
|
+
}
|
|
144
|
+
if command == "history" {
|
|
145
|
+
guard keys.isSubset(of: ["offset", "limit"]) else { throw CrocheError("invalid_command", "Unsupported history fields") }
|
|
146
|
+
guard (!keys.contains("offset") || payload["offset"].number != nil), (!keys.contains("limit") || payload["limit"].number != nil) else { throw CrocheError("invalid_command", "History page values must be numbers") }
|
|
147
|
+
let offset = payload["offset"].number ?? 0, limit = payload["limit"].number ?? 100
|
|
148
|
+
guard offset.isFinite, offset >= 0, offset <= Double(Int.max / 2), offset.rounded() == offset,
|
|
149
|
+
limit >= 1, limit <= 200, limit.rounded() == limit else { throw CrocheError("invalid_command", "Invalid history page") }
|
|
150
|
+
let history = try await runtime.inspect()["history"].array ?? []
|
|
151
|
+
return .object(["messages": .array(Array(history.dropFirst(Int(offset)).prefix(Int(limit)))),
|
|
152
|
+
"total": .number(Double(history.count)), "offset": .number(offset), "limit": .number(limit)])
|
|
153
|
+
}
|
|
154
|
+
if command == "budget.set" {
|
|
155
|
+
guard keys == ["amount"], let amount = payload["amount"].number, amount.isFinite, amount >= 0 else {
|
|
156
|
+
throw CrocheError("invalid_command", "Budget needs a non-negative finite amount")
|
|
157
|
+
}
|
|
158
|
+
return try await runtime.adjustBudget(amount, absolute: true)
|
|
159
|
+
}
|
|
160
|
+
guard keys.isEmpty else { throw CrocheError("invalid_command", "Unsupported command fields") }
|
|
161
|
+
if command == "cancel" {
|
|
162
|
+
let hadActive = !active.isEmpty; for signal in active.values { signal.cancel() }
|
|
163
|
+
let host = await cancelAdapter?() ?? false
|
|
164
|
+
return .object(["requested": .bool(hadActive || host), "scope": .string(cancelAdapter == nil ? "control_client" : "host"), "rollback": .bool(false)])
|
|
165
|
+
}
|
|
166
|
+
if command == "sync" { _ = try await runtime.sync() }
|
|
167
|
+
let view = try await runtime.inspect()
|
|
168
|
+
switch command {
|
|
169
|
+
case "status":
|
|
170
|
+
var status = view["status"]; status["control"] = .object(["cancellation_scope": .string(cancelAdapter == nil ? "control_client" : "host")]); return status
|
|
171
|
+
case "sync": return view["status"]
|
|
172
|
+
case "tools": return view["tools"]
|
|
173
|
+
case "budget.get": return view["budget"]
|
|
174
|
+
default: throw CrocheError("unsupported_capability", "Unsupported Runtime command")
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
public func close() async {
|
|
178
|
+
if closed { return }; closed = true
|
|
179
|
+
for signal in active.values { signal.cancel() }
|
|
180
|
+
// Transport stays alive for unregister; closing attachment never closes Runtime.
|
|
181
|
+
_ = try? await post("unregister", .object(identity))
|
|
182
|
+
lifetime.cancel(); loop?.cancel(); await loop?.value; loop = nil
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
private func validControlId(_ value: String) -> Bool {
|
|
186
|
+
value.range(of: "^[A-Za-z0-9_.:-]{1,200}$", options: .regularExpression) != nil
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
private func publicControlCode(_ error: Error) -> String {
|
|
190
|
+
let code = (error as? CrocheError)?.code ?? "runtime_error"
|
|
191
|
+
return ["invalid_command", "control_closed", "unsupported_capability", "result_too_large", "busy", "closed", "storage_error", "context_limit", "budget_limit"].contains(code) ? code : "runtime_error"
|
|
192
|
+
}
|