@h1r-ai/croche 0.0.0-stage → 0.5.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 (86) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +1176 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/dist/archive.d.ts +47 -0
  5. package/dist/archive.js +217 -0
  6. package/dist/atomic-replace.d.ts +18 -0
  7. package/dist/atomic-replace.js +39 -0
  8. package/dist/commands.d.ts +56 -0
  9. package/dist/commands.js +1 -0
  10. package/dist/control.d.ts +62 -0
  11. package/dist/control.js +269 -0
  12. package/dist/core-abi.d.ts +110 -0
  13. package/dist/core-abi.js +1 -0
  14. package/dist/core-bindgen.d.ts +413 -0
  15. package/dist/core-bindgen.js +1533 -0
  16. package/dist/core-runtime.d.ts +214 -0
  17. package/dist/core-runtime.js +837 -0
  18. package/dist/core-wasm-bytes.d.ts +4 -0
  19. package/dist/core-wasm-bytes.js +5 -0
  20. package/dist/core-wasm.d.ts +16 -0
  21. package/dist/core-wasm.js +63 -0
  22. package/dist/debug.d.ts +26 -0
  23. package/dist/debug.js +171 -0
  24. package/dist/file-lock.d.ts +46 -0
  25. package/dist/file-lock.js +300 -0
  26. package/dist/images.d.ts +53 -0
  27. package/dist/images.js +179 -0
  28. package/dist/index.d.ts +14 -0
  29. package/dist/index.js +9 -0
  30. package/dist/markers.d.ts +1 -0
  31. package/dist/markers.js +1 -0
  32. package/dist/node.d.ts +46 -0
  33. package/dist/node.js +281 -0
  34. package/dist/project-core.d.ts +79 -0
  35. package/dist/project-core.js +261 -0
  36. package/dist/project-session.d.ts +44 -0
  37. package/dist/project-session.js +143 -0
  38. package/dist/project-types.d.ts +97 -0
  39. package/dist/project-types.js +1 -0
  40. package/dist/project-wire.d.ts +19 -0
  41. package/dist/project-wire.js +39 -0
  42. package/dist/sse.d.ts +19 -0
  43. package/dist/sse.js +53 -0
  44. package/dist/storage.d.ts +24 -0
  45. package/dist/storage.js +32 -0
  46. package/dist/stream-branch.d.ts +47 -0
  47. package/dist/stream-branch.js +107 -0
  48. package/dist/stream-hub.d.ts +207 -0
  49. package/dist/stream-hub.js +210 -0
  50. package/dist/stream.d.ts +3 -0
  51. package/dist/stream.js +5 -0
  52. package/dist/types.d.ts +930 -0
  53. package/dist/types.js +8 -0
  54. package/dist/wiki.d.ts +15 -0
  55. package/dist/wiki.js +25 -0
  56. package/docs/CODING-AGENT.md +92 -0
  57. package/docs/DEBUGGER.md +230 -0
  58. package/docs/S2-IMPLEMENTATION.md +585 -0
  59. package/docs/SKILL.md +295 -0
  60. package/package.json +52 -4
  61. package/src/archive.ts +188 -0
  62. package/src/atomic-replace.ts +43 -0
  63. package/src/commands.ts +62 -0
  64. package/src/control.ts +179 -0
  65. package/src/core-abi.ts +52 -0
  66. package/src/core-bindgen.ts +1557 -0
  67. package/src/core-runtime.ts +750 -0
  68. package/src/core-wasm-bytes.ts +5 -0
  69. package/src/core-wasm.ts +57 -0
  70. package/src/debug.ts +160 -0
  71. package/src/file-lock.ts +269 -0
  72. package/src/images.ts +174 -0
  73. package/src/index.ts +15 -0
  74. package/src/markers.ts +1 -0
  75. package/src/node.ts +194 -0
  76. package/src/project-core.ts +231 -0
  77. package/src/project-session.ts +118 -0
  78. package/src/project-types.ts +77 -0
  79. package/src/project-wire.ts +39 -0
  80. package/src/sse.ts +57 -0
  81. package/src/storage.ts +30 -0
  82. package/src/stream-branch.ts +112 -0
  83. package/src/stream-hub.ts +249 -0
  84. package/src/stream.ts +7 -0
  85. package/src/types.ts +840 -0
  86. package/src/wiki.ts +25 -0
package/src/control.ts ADDED
@@ -0,0 +1,179 @@
1
+ import type { RuntimeStatus, SendInput, SendOptions } from './types.js';
2
+
3
+ /** External host control is separate from the model-facing run_tool command. */
4
+ export interface ControllableRuntime {
5
+ status():RuntimeStatus;
6
+ history?():unknown[];
7
+ send?(input:SendInput,options?:SendOptions):Promise<unknown>;
8
+ sync?():Promise<unknown>;
9
+ userBudget?:{get():unknown;set?(input:{amount:number}):Promise<unknown>};
10
+ }
11
+ export interface RuntimeControlOptions {
12
+ runtime:ControllableRuntime;
13
+ url?:string;
14
+ token?:string;
15
+ /** An explicitly supplied app-origin fetch adapter authenticates on the server.
16
+ * No broker credential is sent to the browser. Requires fetch and no token. */
17
+ relayAuthentication?:boolean;
18
+ /** Supply an app-origin relay adapter for HTTPS development pages. */
19
+ fetch?:typeof fetch;
20
+ /** Current permitted metadata only. Functions and private stores are never exposed. */
21
+ tools?:()=>unknown;
22
+ /** App adapters own transcript, context, source IDs and input receipt handling. */
23
+ send?:(input:{id:string;text:string},options:{signal:AbortSignal})=>Promise<unknown>;
24
+ /** Return false if there is no active app turn; no result claims rollback. */
25
+ cancel?:()=>void|boolean|Promise<void|boolean>;
26
+ /** Opt-in debugger control of this existing handle; never creates a Runtime. */
27
+ debug?:{
28
+ attach:(options:{url:string;token:string;visibility:'runtime'|'full'})=>Promise<unknown>;
29
+ detach:()=>Promise<unknown>;
30
+ };
31
+ onError?:(error:{code:string;message:string})=>void;
32
+ pollIntervalMs?:number;
33
+ /** Wait for a previous attachment's lease to expire (for example after reload).
34
+ * Default 0 fails immediately; maximum 60 seconds. Never retries commands. */
35
+ registrationTimeoutMs?:number;
36
+ }
37
+ export interface RuntimeControlConnection {readonly runtimeInstanceId:string;readonly capabilities:readonly string[];close():Promise<void>}
38
+ class ControlError extends Error {constructor(readonly code:string,message:string){super(message);}}
39
+ const copy=<T>(value:T):T=>JSON.parse(JSON.stringify(value)) as T;
40
+ const validId=(value:unknown):value is string=>typeof value==='string'&&/^[A-Za-z0-9_.:-]{1,200}$/.test(value);
41
+ function object(value:unknown):Record<string,unknown>{if(!value||typeof value!=='object'||Array.isArray(value))throw new ControlError('invalid_command','Expected a command payload object.');return value as Record<string,unknown>;}
42
+ function keys(value:Record<string,unknown>,allowed:string[]){if(Object.keys(value).some(key=>!allowed.includes(key)))throw new ControlError('invalid_command','Command contains unsupported fields.');}
43
+
44
+ /** Attach an existing Runtime to an explicitly authenticated local broker.
45
+ * Does not open stores, create Runtime identities, or run a provider loop.
46
+ * The broker never automatically resubmits a dispatched command after loss.
47
+ */
48
+ export async function attachRuntimeControl(options:RuntimeControlOptions):Promise<RuntimeControlConnection>{
49
+ const url=new URL(options.url??'http://127.0.0.1:8791');
50
+ if(url.protocol!=='http:'||!['localhost','127.0.0.1','[::1]'].includes(url.hostname)||url.username||url.password||url.search||url.hash||url.pathname!=='/')throw new ControlError('invalid_configuration','Runtime control requires a loopback HTTP origin.');
51
+ if(options.relayAuthentication===true){
52
+ if(!options.fetch||options.token!==undefined)throw new ControlError('invalid_configuration','Relay authentication requires an explicit fetch adapter and no browser token.');
53
+ }else if(typeof options.token!=='string'||!/^[A-Za-z0-9._~-]{24,4096}$/.test(options.token))throw new ControlError('invalid_configuration','Runtime control needs an explicit 24–4096 character local token.');
54
+ const registrationTimeoutMs=options.registrationTimeoutMs??0;
55
+ if(!Number.isFinite(registrationTimeoutMs)||registrationTimeoutMs<0||registrationTimeoutMs>60000)throw new ControlError('invalid_configuration','Registration timeout must be between 0 and 60,000 milliseconds.');
56
+ const runtime=options.runtime,transport=options.fetch??globalThis.fetch.bind(globalThis);
57
+ const runtimeId=runtime.status().runtimeInstanceId;
58
+ if(!validId(runtimeId))throw new ControlError('invalid_configuration','Runtime instance identity is invalid.');
59
+ const clientId=crypto.randomUUID(),lifetime=new AbortController();
60
+ const controllers=new Map<string,AbortController>();
61
+ const handled=new Set<string>(),results=new Map<string,Record<string,unknown>>();
62
+ const tasks=new Set<Promise<void>>();
63
+ let closed=false;
64
+ const capabilities=['status',...(runtime.history?['history']:[]),...(options.send||runtime.send?['send','cancel']:options.cancel?['cancel']:[]),...(runtime.sync?['sync']:[]),...(runtime.userBudget?['budget.get']:[]),...(runtime.userBudget?.set?['budget.set']:[]),...(options.tools?['tools']:[]),...(options.debug?['debug.attach','debug.detach']:[])];
65
+ const report=(error:unknown)=>{try{const issue=error instanceof ControlError?error:new ControlError('control_error','Local Runtime control could not complete a request.');options.onError?.({code:issue.code,message:issue.message});}catch{/* Optional observer cannot affect Runtime. */}};
66
+ async function post(path:string,body:unknown):Promise<any>{
67
+ const controller=new AbortController(),abort=()=>controller.abort();
68
+ lifetime.signal.addEventListener('abort',abort,{once:true});
69
+ if(lifetime.signal.aborted)controller.abort();
70
+ let timer:ReturnType<typeof setTimeout>|undefined;
71
+ try{
72
+ return await Promise.race([(async()=>{
73
+ const response=await transport(`${url.origin}/v1/control/${path}`,{method:'POST',headers:{...(options.token?{Authorization:`Bearer ${options.token}`}:{ }),'Content-Type':'application/json'},body:JSON.stringify(body),credentials:'omit',redirect:'error',signal:controller.signal});
74
+ const reader=response.body?.getReader();if(!reader)throw new ControlError('invalid_response','Control broker returned an empty response.');
75
+ let raw='',bytes=0;const decoder=new TextDecoder();
76
+ try{while(true){const part=await reader.read();if(part.done)break;bytes+=part.value.byteLength;if(bytes>1024*1024)throw new ControlError('response_too_large','Control response exceeded its size limit.');raw+=decoder.decode(part.value,{stream:true});}raw+=decoder.decode();}finally{void reader.cancel().catch(()=>{});}
77
+ let data:any;try{data=JSON.parse(raw);}catch{throw new ControlError('invalid_response','Control broker returned invalid JSON.');}
78
+ if(!response.ok)throw new ControlError(typeof data.error?.code==='string'?data.error.code:'control_error',typeof data.error?.message==='string'?data.error.message:'Control broker rejected the request.');
79
+ return data;
80
+ })(),new Promise<never>((_,reject)=>{timer=setTimeout(()=>{controller.abort();reject(new ControlError('control_timeout','Local control transport timed out.'));},5000);})]);
81
+ }finally{clearTimeout(timer);lifetime.signal.removeEventListener('abort',abort);controller.abort();}
82
+ }
83
+ const identity={client_id:clientId,runtime_instance_id:runtimeId};
84
+ const register=()=>post('register',{client_id:clientId,runtime:copy(runtime.status()),capabilities});
85
+ const registrationDeadline=Date.now()+registrationTimeoutMs;
86
+ for(;;){
87
+ try{await register();break;}
88
+ catch(error){
89
+ const remaining=registrationDeadline-Date.now();
90
+ if(!(error instanceof ControlError)||error.code!=='runtime_already_attached'||remaining<=0)throw error;
91
+ await new Promise(resolve=>setTimeout(resolve,Math.min(250,remaining)));
92
+ if(Date.now()>=registrationDeadline)throw error;
93
+ }
94
+ }
95
+ async function execute(command:string,payload:Record<string,unknown>,requestId:string):Promise<unknown>{
96
+ if(closed)throw new ControlError('control_closed','This control attachment is closed.');
97
+ if(!capabilities.includes(command))throw new ControlError('unsupported_capability','This Runtime does not expose that control capability.');
98
+ if(command==='debug.attach'){
99
+ keys(payload,['url','token','visibility']);
100
+ let endpoint:URL;try{endpoint=new URL(String(payload.url));}catch{throw new ControlError('invalid_command','Debugger URL must be a loopback HTTP origin.');}
101
+ if(endpoint.protocol!=='http:'||!['localhost','127.0.0.1','[::1]'].includes(endpoint.hostname)||endpoint.username||endpoint.password||endpoint.search||endpoint.hash||endpoint.pathname!=='/')throw new ControlError('invalid_command','Debugger URL must be a loopback HTTP origin.');
102
+ if(typeof payload.token!=='string'||!/^[A-Za-z0-9._~-]{16,4096}$/.test(payload.token)||!['runtime','full'].includes(String(payload.visibility)))throw new ControlError('invalid_command','Debugger attachment requires a pairing token and runtime or full visibility.');
103
+ return options.debug!.attach({url:endpoint.origin,token:payload.token,visibility:payload.visibility as 'runtime'|'full'});
104
+ }
105
+ if(command==='debug.detach'){keys(payload,[]);return options.debug!.detach();}
106
+ if(command==='send'){
107
+ keys(payload,['id','text']);
108
+ if(!validId(payload.id)||typeof payload.text!=='string'||!payload.text.trim()||payload.text.length>32000)throw new ControlError('invalid_command','send needs a stable input id and 1–32,000 characters of text.');
109
+ const controller=new AbortController();controllers.set(requestId,controller);
110
+ try{
111
+ const input={id:payload.id,text:payload.text};
112
+ return options.send?await options.send(input,{signal:controller.signal}):await runtime.send!(input,{signal:controller.signal});
113
+ }finally{controllers.delete(requestId);}
114
+ }
115
+ if(command==='history'){
116
+ keys(payload,['offset','limit']);const offset=payload.offset??0,limit=payload.limit??100;
117
+ if(!Number.isInteger(offset)||Number(offset)<0||!Number.isInteger(limit)||Number(limit)<1||Number(limit)>200)throw new ControlError('invalid_command','History needs a non-negative offset and a limit from 1 to 200.');
118
+ const all=runtime.history!();return {messages:copy(all.slice(Number(offset),Number(offset)+Number(limit))),total:all.length,offset,limit};
119
+ }
120
+ if(command==='budget.set'){
121
+ keys(payload,['amount']);if(typeof payload.amount!=='number'||!Number.isFinite(payload.amount)||payload.amount<0)throw new ControlError('invalid_command','Budget amount must be finite, non-negative USD.');
122
+ return runtime.userBudget!.set!({amount:payload.amount});
123
+ }
124
+ keys(payload,[]);
125
+ if(command==='status')return {...copy(runtime.status()),control:{cancellation_scope:options.cancel?'host':'control_client'}};
126
+ if(command==='tools')return copy(options.tools!());
127
+ if(command==='budget.get')return copy(runtime.userBudget!.get());
128
+ if(command==='sync'){await runtime.sync!();return copy(runtime.status());}
129
+ if(command==='cancel'){
130
+ const active=controllers.size;for(const controller of controllers.values())controller.abort();
131
+ const host=options.cancel?await options.cancel():false;
132
+ return {requested:active>0||Boolean(options.cancel&&host!==false),scope:options.cancel?'host':'control_client',rollback:false};
133
+ }
134
+ throw new ControlError('unsupported_capability','Unsupported Runtime control command.');
135
+ }
136
+ function accept(value:unknown){
137
+ if(closed)return;
138
+ const command=object(value),requestId=command.request_id;
139
+ if(!validId(requestId)||typeof command.command!=='string')throw new ControlError('invalid_command','Control command identity is invalid.');
140
+ if(handled.has(requestId))return;
141
+ if(handled.size>=1000)throw new ControlError('control_capacity','This attachment has reached its command limit. Reattach explicitly.');
142
+ handled.add(requestId);
143
+ const task=(async()=>{
144
+ try{
145
+ const result=await execute(String(command.command),object(command.payload??{}),requestId);
146
+ const normalized=result===undefined?null:copy(result);
147
+ if(new TextEncoder().encode(JSON.stringify(normalized)).byteLength>900000)throw new ControlError('result_too_large','Control result is too large. Request a smaller history page.');
148
+ results.set(requestId,{...identity,request_id:requestId,result:normalized});
149
+ }catch(error){
150
+ const code=error instanceof ControlError?error.code:'runtime_error';
151
+ // A generic host exception may contain application secrets. Runtime's
152
+ // normal failed TurnResult remains structured result data.
153
+ results.set(requestId,{...identity,request_id:requestId,error:{code,message:error instanceof ControlError?error.message:'The Runtime command failed. Inspect the Runtime before retrying.',uncertain:command.command==='send'||command.command==='budget.set'}});
154
+ }
155
+ })();
156
+ tasks.add(task);void task.finally(()=>tasks.delete(task));
157
+ }
158
+ const sleep=()=>new Promise<void>(resolve=>{
159
+ const done=()=>{clearTimeout(timer);lifetime.signal.removeEventListener('abort',done);resolve();};
160
+ const timer=setTimeout(done,Math.max(100,Math.min(options.pollIntervalMs??500,5000)));lifetime.signal.addEventListener('abort',done,{once:true});if(lifetime.signal.aborted)done();
161
+ });
162
+ const loop=(async()=>{
163
+ while(!closed){
164
+ try{
165
+ for(const [id,result]of [...results].slice(0,8)){
166
+ try{await post('results',result);results.delete(id);}catch(error){if(error instanceof ControlError&&['not_found','attachment_lost'].includes(error.code))results.delete(id);throw error;}
167
+ }
168
+ if(results.size<32&&tasks.size<16){const response=await post('poll',identity);if(!Array.isArray(response.commands))throw new ControlError('invalid_response','Broker command list is invalid.');for(const command of response.commands.slice(0,8))accept(command);}
169
+ }catch(error){if(!closed){report(error);if(!closed&&error instanceof ControlError&&error.code==='attachment_lost')try{await register();}catch(failure){report(failure);}}}
170
+ if(!closed)await sleep();
171
+ }
172
+ })();
173
+ return {runtimeInstanceId:runtimeId,capabilities:Object.freeze([...capabilities]),async close(){
174
+ if(closed)return;closed=true;
175
+ for(const controller of controllers.values())controller.abort();
176
+ try{await post('unregister',identity);}catch{/* Broker expires a lost attachment. */}
177
+ lifetime.abort();await loop;
178
+ }};
179
+ }
@@ -0,0 +1,52 @@
1
+ import type { RuntimeDebugEvent, RuntimeEvent } from './types.js';
2
+
3
+ export type CoreObject = Record<string, any>;
4
+ export type CoreEffect =
5
+ /** `secrets` is present only when credentials changed; write it before `state`. */
6
+ | { kind: 'persist'; id: string; state: CoreObject; secrets?: CoreObject }
7
+ /** Platform app attestation. A web or Node host has none and must refuse it. */
8
+ | { kind: 'attest'; id: string; platform: string; clientData: string; clientDataHash: string; timeoutMs: number }
9
+ | { kind: 'http'; id: string; url: string; method: 'POST'; headers: Record<string, string>; body: CoreObject; timeoutMs: number; stream?: boolean; preemptible?: boolean }
10
+ /** The turn archive (F20). An `append` precedes the persist of the state that holds its turn
11
+ * (F20.3); `read` answers `records`; `clear` without a range deletes everything. Not
12
+ * interruptible: like a persist, it ends before a cancellation is seen. A host without an
13
+ * archive answers `{ok: false, error: {code: 'archive_unavailable'}}`. */
14
+ | { kind: 'archive'; id: string; op: 'append'; n: number; record: CoreObject; maxBytes: number }
15
+ | { kind: 'archive'; id: string; op: 'read'; from: number; to: number }
16
+ | { kind: 'archive'; id: string; op: 'clear'; from?: number; to?: number }
17
+ | { kind: 'tool'; id: string; tool: string; command?: string; key: string; args: CoreObject; context: { callId: string; messageId: string; userId: string; agentId: string | null }; timeoutMs: number }
18
+ /**
19
+ * The agent's WHOLE pending schedule set (`at`: ISO UTC), after the write holding it and at
20
+ * every open. Answer `{ok: true}` (an acknowledgement is enough) or `{ok: false, error}`;
21
+ * either way the operation continues. Added without an ABI bump: it appears only for a
22
+ * store whose app turned `crocheTools.schedule` on, every shipped host drives the Core through
23
+ * the Rust driver (which answers it), and the raw step is used only by tests.
24
+ */
25
+ | { kind: 'schedule'; id: string; entries: Array<{ id: string; at: string }> };
26
+
27
+ export interface CoreOutput {
28
+ abi: 2;
29
+ state: CoreObject | null;
30
+ /** Credentials, kept apart from `state` so a host can hold them in a secret store. */
31
+ secrets: CoreObject;
32
+ /** Opaque continuation. Only Rust interprets it. Never persist this value. */
33
+ machine: CoreObject | null;
34
+ effect: CoreEffect | null;
35
+ events: RuntimeEvent[];
36
+ debug: Array<Pick<RuntimeDebugEvent, 'type' | 'data' | 'turnId' | 'operationId' | 'callId'>>;
37
+ result?: any;
38
+ error?: { code: string; message: string };
39
+ /** When the Core next wants upkeep (maintain), e.g. to prepare memory before idle. */
40
+ wakeAt?: string;
41
+ }
42
+
43
+ export interface CoreInput {
44
+ abi: 2;
45
+ config: CoreObject;
46
+ state: CoreObject | null;
47
+ secrets?: CoreObject;
48
+ machine: CoreObject | null;
49
+ command: CoreObject;
50
+ now: string;
51
+ nonce: string;
52
+ }