@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.
- package/LICENSE +32 -0
- package/README.md +1176 -2
- package/THIRD-PARTY-NOTICES +5824 -0
- package/dist/archive.d.ts +47 -0
- package/dist/archive.js +217 -0
- package/dist/atomic-replace.d.ts +18 -0
- package/dist/atomic-replace.js +39 -0
- package/dist/commands.d.ts +56 -0
- package/dist/commands.js +1 -0
- package/dist/control.d.ts +62 -0
- package/dist/control.js +269 -0
- package/dist/core-abi.d.ts +110 -0
- package/dist/core-abi.js +1 -0
- package/dist/core-bindgen.d.ts +413 -0
- package/dist/core-bindgen.js +1533 -0
- package/dist/core-runtime.d.ts +214 -0
- package/dist/core-runtime.js +837 -0
- package/dist/core-wasm-bytes.d.ts +4 -0
- package/dist/core-wasm-bytes.js +5 -0
- package/dist/core-wasm.d.ts +16 -0
- package/dist/core-wasm.js +63 -0
- package/dist/debug.d.ts +26 -0
- package/dist/debug.js +171 -0
- package/dist/file-lock.d.ts +46 -0
- package/dist/file-lock.js +300 -0
- package/dist/images.d.ts +53 -0
- package/dist/images.js +179 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +9 -0
- package/dist/markers.d.ts +1 -0
- package/dist/markers.js +1 -0
- package/dist/node.d.ts +46 -0
- package/dist/node.js +281 -0
- package/dist/project-core.d.ts +79 -0
- package/dist/project-core.js +261 -0
- package/dist/project-session.d.ts +44 -0
- package/dist/project-session.js +143 -0
- package/dist/project-types.d.ts +97 -0
- package/dist/project-types.js +1 -0
- package/dist/project-wire.d.ts +19 -0
- package/dist/project-wire.js +39 -0
- package/dist/sse.d.ts +19 -0
- package/dist/sse.js +53 -0
- package/dist/storage.d.ts +24 -0
- package/dist/storage.js +32 -0
- package/dist/stream-branch.d.ts +47 -0
- package/dist/stream-branch.js +107 -0
- package/dist/stream-hub.d.ts +207 -0
- package/dist/stream-hub.js +210 -0
- package/dist/stream.d.ts +3 -0
- package/dist/stream.js +5 -0
- package/dist/types.d.ts +930 -0
- package/dist/types.js +8 -0
- package/dist/wiki.d.ts +15 -0
- package/dist/wiki.js +25 -0
- package/docs/CODING-AGENT.md +92 -0
- package/docs/DEBUGGER.md +230 -0
- package/docs/S2-IMPLEMENTATION.md +585 -0
- package/docs/SKILL.md +295 -0
- package/package.json +52 -4
- package/src/archive.ts +188 -0
- package/src/atomic-replace.ts +43 -0
- package/src/commands.ts +62 -0
- package/src/control.ts +179 -0
- package/src/core-abi.ts +52 -0
- package/src/core-bindgen.ts +1557 -0
- package/src/core-runtime.ts +750 -0
- package/src/core-wasm-bytes.ts +5 -0
- package/src/core-wasm.ts +57 -0
- package/src/debug.ts +160 -0
- package/src/file-lock.ts +269 -0
- package/src/images.ts +174 -0
- package/src/index.ts +15 -0
- package/src/markers.ts +1 -0
- package/src/node.ts +194 -0
- package/src/project-core.ts +231 -0
- package/src/project-session.ts +118 -0
- package/src/project-types.ts +77 -0
- package/src/project-wire.ts +39 -0
- package/src/sse.ts +57 -0
- package/src/storage.ts +30 -0
- package/src/stream-branch.ts +112 -0
- package/src/stream-hub.ts +249 -0
- package/src/stream.ts +7 -0
- package/src/types.ts +840 -0
- package/src/wiki.ts +25 -0
package/docs/SKILL.md
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: croche
|
|
3
|
+
description: Add a scoped AI agent (character, companion, assistant, NPC, tutor) to an app with the Croche SDK, and manage its Croche project and drafts, and inspect keys, attestation and usage with the croche CLI. Use when the user builds on Croche, mentions @h1r-ai/croche or @h1r-ai/croche-react-native, or asks to add AI behaviour to an app that uses Croche. Not for generic LLM integrations.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Croche
|
|
7
|
+
|
|
8
|
+
Croche gives an app a **scoped agent**: an AI with a clear purpose that acts through the app's
|
|
9
|
+
own commands. The Runtime (a Rust Core inside the SDK) already does the hard, generic part:
|
|
10
|
+
conversation history, long-term memory, the model and how it is called, the tool loop,
|
|
11
|
+
spending limits and reporting. **You write only
|
|
12
|
+
what is specific to this app.** This page is enough for most apps. Do not read the SDK
|
|
13
|
+
sources or its `.d.ts` files; open a reference only when a step below points to it.
|
|
14
|
+
|
|
15
|
+
## Do not build these (the Runtime does them)
|
|
16
|
+
|
|
17
|
+
History, windowing, summaries, memory files, retries of model calls, a tool loop, a model
|
|
18
|
+
client, provider choice, prompt caching. Every one of them is already correct in the Runtime,
|
|
19
|
+
and a second copy costs tokens on every call. Never call the model provider yourself.
|
|
20
|
+
|
|
21
|
+
## What you need first
|
|
22
|
+
|
|
23
|
+
Ask for anything you do not have; never invent a value.
|
|
24
|
+
|
|
25
|
+
- Croche Cloud URL and the project's **public project key**.
|
|
26
|
+
- The SDK from npm: `npm install @h1r-ai/croche@{{SDK_VERSION}}`. For React Native, also
|
|
27
|
+
`npm install @h1r-ai/croche-react-native@{{SDK_VERSION}}` (the native Core is inside;
|
|
28
|
+
see the [SDK reference](references/sdk.md), React Native).
|
|
29
|
+
- Native iOS (Swift) and Android (Kotlin) apps: the native SDKs are planned for 0.5.1, with the
|
|
30
|
+
same `Croche.open` API. Until then, use React Native, or run the Runtime on a web backend.
|
|
31
|
+
- In development (Node, simulator, browser): a **debug key** (`cdt_…`) passed as
|
|
32
|
+
`debugKey`. Release builds on phones use platform attestation instead; web apps run the
|
|
33
|
+
Runtime on their backend with a server key (`csk_…`). See [SDK reference](references/sdk.md)
|
|
34
|
+
only if you are in one of those cases.
|
|
35
|
+
|
|
36
|
+
## The recommended setup
|
|
37
|
+
|
|
38
|
+
One `Croche` project per user, opened once for the app's lifetime, and its agents
|
|
39
|
+
(Node shown; React Native is the same API):
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { Croche } from '@h1r-ai/croche';
|
|
43
|
+
import { FileStorage } from '@h1r-ai/croche/node';
|
|
44
|
+
|
|
45
|
+
const croche = await Croche.open({
|
|
46
|
+
projectKey, debugKey, // from .env; never hard-code or log keys
|
|
47
|
+
user: playerId, // your app's id for this person
|
|
48
|
+
storage: new FileStorage(join(dataDir, 'croche')), // one directory for the whole project
|
|
49
|
+
config: { instructions: PIP, tools: [shop] }, // who the agent is (short: paid on every call), and the app's actions, below
|
|
50
|
+
handlers: { shop: runShop }, // one handler per tool, by tool name
|
|
51
|
+
}); // leave every other option at its default
|
|
52
|
+
|
|
53
|
+
const pip = await croche.agent(); // the project's agent
|
|
54
|
+
const result = await pip.request({ id: messageId, text: userText, context: appState() });
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
- **`request`** resolves when the input is answered, with its `messages`; the reply is the
|
|
58
|
+
`message.end` among them. **`send`** returns at once with a receipt. To show replies as they
|
|
59
|
+
stream, `subscribe({ onEvent })` once and render `message.delta` (provisional) and
|
|
60
|
+
`message.end` (final) events.
|
|
61
|
+
- **Several agents:** declare them under `config.agents` (`{ helper: { instructions: … } }`)
|
|
62
|
+
and open each with `croche.agent('helper')`. A separate conversation of one agent, such as a
|
|
63
|
+
save slot, is `croche.agent(id, { instance: 'save-2' })`; `{ fresh: true }` starts a new one.
|
|
64
|
+
Each has its own history and memory.
|
|
65
|
+
- `CrocheRuntime.create` (one agent, no project) still works and the
|
|
66
|
+
[SDK reference](references/sdk.md) documents it. New apps use `Croche`.
|
|
67
|
+
|
|
68
|
+
- **`instructions`:** the character only: who, voice, what they care about, in a few short
|
|
69
|
+
paragraphs, in English (the persona's example lines may be in the user's language). No
|
|
70
|
+
command list, no app state, no rules the tool set already enforces.
|
|
71
|
+
- **Reply length and tone are yours.** The Runtime says nothing about how the agent talks. If
|
|
72
|
+
replies should be short (a task app, a store), say it in `instructions` ("one to three short
|
|
73
|
+
sentences unless asked for more"); a character may need more room. Measured: a brevity line
|
|
74
|
+
halves reply length and cuts cost on task apps, but flattened an NPC's voice.
|
|
75
|
+
- **`context`:** the current app state on **every** message: what most turns need to answer
|
|
76
|
+
(cart, balance, open tasks, today's schedule, recent orders). Rich state here saves a lookup
|
|
77
|
+
call on most turns and keeps the agent from answering without checking. Keep it bounded:
|
|
78
|
+
cap long lists and add a hint such as `"more": "use orders list"`. Kept earlier turns are
|
|
79
|
+
resent exactly as they were sent, earlier states included. Send the current state on every
|
|
80
|
+
message, even when unchanged: Croche sends only what changed, and resends it in full after older turns are folded.
|
|
81
|
+
- **Money:** per-user and project spending limits are the Runtime's and Cloud's; do not wrap or
|
|
82
|
+
gate the SDK's `fetch` to meter calls. To show or record usage, use `onUsage`: one event for
|
|
83
|
+
every paid call, including memory upkeep that belongs to no message.
|
|
84
|
+
- **Storage:** durable, one per project; the Runtime keeps each agent's store inside it.
|
|
85
|
+
Reopening with the same storage restores every conversation and memory.
|
|
86
|
+
- **Time in context:** Core adds the permanent conversation number and short local
|
|
87
|
+
time before the input channels, with a zone at the start and after reduction.
|
|
88
|
+
Kept messages are never re-dated. Do not add a time channel or `timeContext`;
|
|
89
|
+
that removed setting is refused by name.
|
|
90
|
+
- **The Runtime's own behaviour is tuned by Croche,** not by the app. Set `memory.policy` only
|
|
91
|
+
if this app must keep something specific.
|
|
92
|
+
- **Clock:** the Node/web host schedules the Runtime's upkeep. Only with `CrocheRuntime` and
|
|
93
|
+
an app clock of its own (tests, simulations): pass `clock` and call `runtime.maintain()` once
|
|
94
|
+
`clock()` reaches `runtime.wakeAt()` (epoch ms, like the clock).
|
|
95
|
+
|
|
96
|
+
## Commands: the app's actions
|
|
97
|
+
|
|
98
|
+
Each capability is a **command** of a grouped tool. Write per command: a one-line `summary`
|
|
99
|
+
saying what it does **and when to use it**, with the allowed values when they are few; typed
|
|
100
|
+
flags with `enum`, `minimum`/`maximum`, `required`.
|
|
101
|
+
|
|
102
|
+
**Say when each state-changing command may run.** A Croche agent acts on its own judgement by
|
|
103
|
+
default; limiting that is your app's call, and it takes one line. For every command that changes
|
|
104
|
+
something, put in its `summary` (or in `toolGuide`) whether it runs only when the person asks for
|
|
105
|
+
that change, e.g. "Change the cart only when the shopper asks for that change, not because an item
|
|
106
|
+
seems suitable or while answering a question." Without it, a shop agent answering "would the
|
|
107
|
+
notebook still fit?" may add the notebook (measured 2026-09-29: 17% of such questions changed the
|
|
108
|
+
cart; with that one line 0%, and requested changes still ran).
|
|
109
|
+
|
|
110
|
+
**Actions that need the person's agreement** (delete, refund, anything that spends or can't be
|
|
111
|
+
undone) are approved in your app, not by Croche. Croche has no approval step: a command with a
|
|
112
|
+
`confirm` field is refused (`invalid_configuration`). The tool's handler asks the person in your
|
|
113
|
+
UI and returns a value the agent reads, such as `{ status: 'waiting_for_approval' }`; once they
|
|
114
|
+
approve, a later call runs. Return a value, not an exception: an exception after the handler
|
|
115
|
+
starts ends the turn. Don't return `{ ok: false }` for a wait either: it tells the agent the
|
|
116
|
+
command failed. The SDK reference has the example ("Approval in your app").
|
|
117
|
+
|
|
118
|
+
**Every command that only reads (list, get, search, status, menu) must have `reads: true`.** Not
|
|
119
|
+
optional: the agent replies together with its commands, and without the mark a lookup can end
|
|
120
|
+
the turn on "let me check" before the answer.
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
import type { ToolDeclaration, ToolHandler } from '@h1r-ai/croche';
|
|
124
|
+
|
|
125
|
+
const shop: ToolDeclaration = { // goes in config.tools
|
|
126
|
+
name: 'shop',
|
|
127
|
+
summary: 'The inn shop.',
|
|
128
|
+
commands: [
|
|
129
|
+
{ key: 'shop_sell', name: 'sell', summary: 'Sell food or drink the player asks for: stew, bread, ale (evenings only).',
|
|
130
|
+
flags: [{ name: 'item', type: 'string', enum: ['stew', 'bread', 'ale'], required: true },
|
|
131
|
+
{ name: 'qty', type: 'integer', minimum: 1, maximum: 5 }] },
|
|
132
|
+
{ key: 'shop_menu', name: 'menu', summary: 'List today\'s menu and prices.', reads: true },
|
|
133
|
+
],
|
|
134
|
+
};
|
|
135
|
+
const runShop: ToolHandler = ({ key, args }, context) => { // goes in handlers.shop
|
|
136
|
+
// Enforce everything here: this is the real boundary, not the prompt.
|
|
137
|
+
const out = app.run(key, args, context.user);
|
|
138
|
+
return out.ok ? out.value : { status: 'rejected', reason: out.reason }; // return, never throw
|
|
139
|
+
};
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
- The declaration is data (a released config can replace it); the handler is code and stays in
|
|
143
|
+
the app. `context` names the `agentId`, the `user` and what caused the call.
|
|
144
|
+
- The model sees each command's usage line and `summary`. The tool's own `summary` (`'The inn
|
|
145
|
+
shop.'`) appears only in `help` output, so put rules in command summaries or `toolGuide`,
|
|
146
|
+
never only in the tool summary.
|
|
147
|
+
- Summaries have no length limit of their own and are never cut. The whole tool list is capped
|
|
148
|
+
at 256,000 bytes of JSON, and each `help` text at 32,000 bytes. Keep each summary to one line.
|
|
149
|
+
|
|
150
|
+
- `key` is global across all tools (and becomes the function name under `functions`): prefix
|
|
151
|
+
it with the tool name (`shop_sell`), never a bare `list` or `get`.
|
|
152
|
+
- If the app already has JSON-schema tool specs, map each to one command (property ->
|
|
153
|
+
flag, keeping `type`, `enum`, `minimum`, `maximum`, `required`, `description`) in a small
|
|
154
|
+
loop. Do not hand-write them twice.
|
|
155
|
+
- A rejected result teaches the model the rule at the moment it needs it; you do not need to
|
|
156
|
+
describe every rule in prose. Say what to do instead, in plain words, and name arguments as
|
|
157
|
+
the model writes them (`--order-id`).
|
|
158
|
+
|
|
159
|
+
**Good commands, in one minute.** Croche renders the usage line, reads forgivingly and answers
|
|
160
|
+
mistakes with the exact usage, so you only declare:
|
|
161
|
+
- a group noun and short verbs: `tasks add|list|done|delete`, `shop search|add-to-cart`;
|
|
162
|
+
- required arguments first: they may be written without their flag, in order
|
|
163
|
+
(`tasks done t5`, `shop cart-add notebook 2`);
|
|
164
|
+
- `enum` for allowed values. The usage line lists them only when there are at most 12 and they
|
|
165
|
+
fit in 120 characters; otherwise it shows a placeholder (`--item ITEM`), so name the values
|
|
166
|
+
in the summary or give a read command that lists them;
|
|
167
|
+
- `list: true` for several values (`--tags work,home`); the handler gets an array;
|
|
168
|
+
- `default` on a flag or positional: the handler's `args` has it filled in when the model omits
|
|
169
|
+
the argument;
|
|
170
|
+
- `aliases` for verbs a model may mix up (`update` also `edit`, `upgrade`), shown only in help.
|
|
171
|
+
Do not handle spelling variants yourself: a missing group, `_` for `-`, or an unquoted multi-word
|
|
172
|
+
value are accepted when unambiguous (and counted as `command.repaired` debug events).
|
|
173
|
+
- Money, inventory and progress live in the app, never only in what the model was told.
|
|
174
|
+
- The Runtime keeps a dated record of what each command did, for when the conversation has moved
|
|
175
|
+
on. A handler may add `record: 'one line of what happened'` to its result; otherwise the command
|
|
176
|
+
line is recorded.
|
|
177
|
+
|
|
178
|
+
## Tool interface
|
|
179
|
+
|
|
180
|
+
A `setTools` filter never changes the system prompt. `toolGuide` is app text,
|
|
181
|
+
verbatim at the start of `run_tool`'s **App tools:** section, after the compiled
|
|
182
|
+
base guide and **Croche tools:** section. It is not in the system prompt. App
|
|
183
|
+
command summaries are shown in full, within the registry's byte cap.
|
|
184
|
+
|
|
185
|
+
Use project config `crocheTools` for the built-in library: `memory.save` is on
|
|
186
|
+
when memory is on, `wiki` requires visible documents, and `schedule` defaults
|
|
187
|
+
off. Set a switch to `false` to remove that tool from both the description and
|
|
188
|
+
dispatch. These config fields are removed and refused at every layer (project,
|
|
189
|
+
`agents.X`, `languages.Y`, `agents.X.languages.Y`): `memory.keys`,
|
|
190
|
+
`memory.commands`, `memory.recall`, `memory.deltas`, `schedule.commands`,
|
|
191
|
+
`memoryRecall`, `timeContext`, and `defaultLanguage` anywhere below the project
|
|
192
|
+
root. All are refused by name except `memory.deltas` and a nested
|
|
193
|
+
`defaultLanguage`, which are refused as unknown fields. The `crocheTools` switch `"memory.recall"` is not that field: it turns the
|
|
194
|
+
model's `memory recall` command on or off. Only the model writes monotonic memory ids with `memory
|
|
195
|
+
save` or `memory replace`; the app can list, export, delete by id or clear them,
|
|
196
|
+
but cannot set keyed facts. A replacement retains its earlier version.
|
|
197
|
+
`memory history <tN>` reads bounded archived-turn text and `memory recall <words>`
|
|
198
|
+
searches every memory, each when enabled. Nothing is recalled automatically: the
|
|
199
|
+
model reads only what it asks for. Conversation summaries are not memory items: deleting or
|
|
200
|
+
clearing memories preserves the summary and does not rewrite kept or archived
|
|
201
|
+
turns. `clearHistory()` or `Croche.deleteStore()` removes the summary.
|
|
202
|
+
|
|
203
|
+
**Croche's own tools and modes, in config:**
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
config: {
|
|
207
|
+
toolGuide: 'Phone effects are rare: use them only when the person asks.', // app text for run_tool
|
|
208
|
+
crocheTools: { 'memory.save': true, 'memory.history': true, 'memory.recall': true, wiki: true, schedule: false },
|
|
209
|
+
modes: {
|
|
210
|
+
room: { tools: [room], toolGuide: 'In the room, place items only where the person says.' },
|
|
211
|
+
},
|
|
212
|
+
}
|
|
213
|
+
// later: await agent.setMode('room'); … await agent.setMode(null);
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
- `crocheTools` is a flat object with these five dotted keys and boolean values; a nested
|
|
217
|
+
`{ memory: { save: true } }` is refused. Defaults: `memory.save`, `memory.history` and `wiki`
|
|
218
|
+
on (memory tools only while memory is on; `wiki` only while the agent sees a document),
|
|
219
|
+
`memory.recall` follows `memory.save`, `schedule` off. `memory replace` is on exactly when
|
|
220
|
+
`memory.save` is.
|
|
221
|
+
- `toolGuide` and `crocheTools` are allowed at every config layer, applied in this order:
|
|
222
|
+
project → `languages.Y` → `agents.X` → `agents.X.languages.Y` → the `config` your code
|
|
223
|
+
passes to `croche.agent(id, { config })` (this agent only), so an agent's value beats a
|
|
224
|
+
project language's. `toolGuide` from a later layer replaces the
|
|
225
|
+
earlier one. `crocheTools` merges per key: a later layer changes only the keys it names
|
|
226
|
+
(project `{ wiki: false, schedule: true }` plus agent `{ schedule: false }` gives
|
|
227
|
+
`{ wiki: false, schedule: false }`). Neither has its own size limit; the whole config is
|
|
228
|
+
capped at 256 KiB.
|
|
229
|
+
- `modes.<name>` takes only `tools` and `toolGuide`. While a mode is on, each one it sets
|
|
230
|
+
**replaces** the agent's (no merge); what it leaves out stays. `setMode(null)` turns it off,
|
|
231
|
+
and a `setTools` filter still applies on top.
|
|
232
|
+
|
|
233
|
+
Tool-list changes are announced in the conversation. A changed app guide is
|
|
234
|
+
also a tool-description change, applied at the next turn; it does not edit the
|
|
235
|
+
system prompt. A changed description can prevent prefix reuse; this is not a
|
|
236
|
+
promise about how much the provider will cache.
|
|
237
|
+
|
|
238
|
+
The agent runs your commands as command lines. If your live check shows the same command
|
|
239
|
+
rejected with `invalid_arguments` again and again, fix that command (required arguments,
|
|
240
|
+
`enum`, `list`, `aliases`, a clearer summary).
|
|
241
|
+
|
|
242
|
+
## A store from an older build
|
|
243
|
+
|
|
244
|
+
An agent store written by an older build with keyed memory is refused before any write:
|
|
245
|
+
`croche.agent(id)` rejects with a `CrocheError` whose `code` is `memory_store_too_old`.
|
|
246
|
+
`Croche.open` itself succeeds, and other agents open normally. To recover:
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
let agent;
|
|
250
|
+
try {
|
|
251
|
+
agent = await croche.agent();
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if ((error as CrocheError).code !== 'memory_store_too_old') throw error;
|
|
254
|
+
await croche.close(); // simplest: delete with nothing open
|
|
255
|
+
await Croche.deleteStore({ ...openOptions, agent: 'default' }); // the default agent's id
|
|
256
|
+
croche = await Croche.open(openOptions);
|
|
257
|
+
agent = await croche.agent();
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
This deletes that agent's conversation, memory, user wiki, archive and message log for
|
|
262
|
+
that user; other agents and the project record stay. In the Core's words: "This agent's store
|
|
263
|
+
was written by an older Croche build whose memory this Core cannot read or convert. Nothing was
|
|
264
|
+
changed. To continue, delete this agent's store and reopen; this permanently loses this agent's
|
|
265
|
+
conversation and memories for this user. Only an older build that still runs can export them
|
|
266
|
+
first." After an app update the older build no longer runs, so tell the person before deleting.
|
|
267
|
+
If your app tracks the input ids it sent (pending sends, a retry queue), drop the ones the old
|
|
268
|
+
store accepted: their final status never comes. React Native has the same calls.
|
|
269
|
+
|
|
270
|
+
## Check it
|
|
271
|
+
|
|
272
|
+
- One short live session is the check: a real command changed app state, a restart restores
|
|
273
|
+
the conversation, and a refused action comes back as a rejection, not a crash. Test your own
|
|
274
|
+
handlers as you would any app code; do not test the Runtime.
|
|
275
|
+
- Report failures and costs as they are. Never fake an AI result, and never put a provider,
|
|
276
|
+
development or server key in a bundle, a repository or a log.
|
|
277
|
+
|
|
278
|
+
That is the whole integration. Stop there unless a measured problem sends you to
|
|
279
|
+
[Coding-agent guidance](references/coding-agent.md) (why each default is what it is) or the
|
|
280
|
+
[SDK reference](references/sdk.md) (streaming, several agents, markers, web backends, mobile).
|
|
281
|
+
|
|
282
|
+
## CLI
|
|
283
|
+
|
|
284
|
+
`croche --help` lists everything. The ones an integration usually needs:
|
|
285
|
+
|
|
286
|
+
```sh
|
|
287
|
+
croche projects list
|
|
288
|
+
croche keys development list <project-id>
|
|
289
|
+
croche keys server list <project-id>
|
|
290
|
+
croche attestation get <project-id>
|
|
291
|
+
croche projects usage <project-id> --period week
|
|
292
|
+
croche debug # attach the local debugger
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
Full reference: [CLI](references/cli.md).
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@h1r-ai/croche",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
}
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"description": "Shared Rust AI Runtime with web/Node WASM host, grouped commands, durable receipts and actual-cost control.",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"main": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./node": {
|
|
18
|
+
"types": "./dist/node.d.ts",
|
|
19
|
+
"import": "./dist/node.js",
|
|
20
|
+
"default": "./dist/node.js"
|
|
21
|
+
},
|
|
22
|
+
"./debug": {
|
|
23
|
+
"types": "./dist/debug.d.ts",
|
|
24
|
+
"import": "./dist/debug.js",
|
|
25
|
+
"default": "./dist/debug.js"
|
|
26
|
+
},
|
|
27
|
+
"./stream": {
|
|
28
|
+
"types": "./dist/stream.d.ts",
|
|
29
|
+
"import": "./dist/stream.js",
|
|
30
|
+
"default": "./dist/stream.js"
|
|
31
|
+
},
|
|
32
|
+
"./control": {
|
|
33
|
+
"types": "./dist/control.d.ts",
|
|
34
|
+
"import": "./dist/control.js",
|
|
35
|
+
"default": "./dist/control.js"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"src",
|
|
40
|
+
"dist",
|
|
41
|
+
"README.md",
|
|
42
|
+
"docs",
|
|
43
|
+
"LICENSE",
|
|
44
|
+
"THIRD-PARTY-NOTICES"
|
|
45
|
+
],
|
|
46
|
+
"scripts": {
|
|
47
|
+
"test": "vitest run --root ../.. packages/runtime/tests",
|
|
48
|
+
"test:package": "node scripts/verify-package.mjs",
|
|
49
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
50
|
+
"build": "tsc -p tsconfig.build.json",
|
|
51
|
+
"prepack": "npm run build"
|
|
52
|
+
},
|
|
53
|
+
"license": "SEE LICENSE IN LICENSE"
|
|
54
|
+
}
|
package/src/archive.ts
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import type { ArchiveRuntimeStorage } from './types.js';
|
|
2
|
+
import { CrocheError } from './types.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The turn archive's rules (F20), the SDK's default implementation of the Core's three archive
|
|
6
|
+
* calls over any `ArchiveRuntimeStorage`:
|
|
7
|
+
* - one segment per 100 turns, the entry `archive<NNNN>` with NNNN = ⌊n/100⌋ (F20.4);
|
|
8
|
+
* - past the byte bound, the oldest whole segment is deleted, never the one just written;
|
|
9
|
+
* - on read, the last record per turn number wins (F20.3), and a turn no longer held is absent;
|
|
10
|
+
* - clear is a real delete: everything, or the records of a range of turns.
|
|
11
|
+
* Torn lines are the line storage's (a file's) concern: `readLines` never returns one.
|
|
12
|
+
*/
|
|
13
|
+
const SEGMENT_TURNS = 100;
|
|
14
|
+
const SEGMENT = /^archive\d{4}$/;
|
|
15
|
+
|
|
16
|
+
export function segmentEntry(n: number): string {
|
|
17
|
+
if (!Number.isSafeInteger(n) || n < 1 || n > 999_999) throw new CrocheError('invalid_input', 'A turn number is 1 to 999999.');
|
|
18
|
+
return `archive${String(Math.floor(n / SEGMENT_TURNS)).padStart(4, '0')}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function segments(from: number, to: number): string[] {
|
|
22
|
+
const out: string[] = [];
|
|
23
|
+
for (let s = Math.floor(from / SEGMENT_TURNS); s <= Math.floor(to / SEGMENT_TURNS); s++) out.push(`archive${String(s).padStart(4, '0')}`);
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A line's record and its turn number, or null for anything that is not one. */
|
|
28
|
+
function parse(line: string): { n: number; record: Record<string, unknown> } | null {
|
|
29
|
+
try {
|
|
30
|
+
const record = JSON.parse(line) as Record<string, unknown> | null;
|
|
31
|
+
const n = record?.n;
|
|
32
|
+
return record && typeof record === 'object' && !Array.isArray(record) && typeof n === 'number' && Number.isSafeInteger(n) ? { n, record } : null;
|
|
33
|
+
} catch { return null; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function archiveAppend(storage: ArchiveRuntimeStorage, key: string, n: number, record: string, maxBytes: number): Promise<void> {
|
|
37
|
+
if (record.includes('\n')) throw new CrocheError('invalid_input', 'An archive record is one line.');
|
|
38
|
+
const entry = segmentEntry(n);
|
|
39
|
+
await storage.appendLine(key, entry, record);
|
|
40
|
+
const held = (await storage.entries(key, 'archive')).filter(e => SEGMENT.test(e.entry)).sort((a, b) => (a.entry < b.entry ? -1 : 1));
|
|
41
|
+
let total = held.reduce((sum, e) => sum + e.bytes, 0);
|
|
42
|
+
for (const oldest of held) {
|
|
43
|
+
if (total <= maxBytes || oldest.entry >= entry) break;
|
|
44
|
+
await storage.remove(key, oldest.entry);
|
|
45
|
+
total -= oldest.bytes;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function archiveRead(storage: ArchiveRuntimeStorage, key: string, from: number, to: number): Promise<Array<Record<string, unknown>>> {
|
|
50
|
+
const byN = new Map<number, Record<string, unknown>>();
|
|
51
|
+
for (const entry of segments(from, to)) {
|
|
52
|
+
for (const line of await storage.readLines(key, entry)) {
|
|
53
|
+
const parsed = parse(line);
|
|
54
|
+
if (parsed && parsed.n >= from && parsed.n <= to) byN.set(parsed.n, parsed.record);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return [...byN.keys()].sort((a, b) => a - b).map(n => byN.get(n)!);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A real delete. Without a range, every segment. With one, each segment that holds a record of
|
|
62
|
+
* those turns is replaced, atomically, by its other lines (`replaceLines`): a crash leaves the
|
|
63
|
+
* segment as it was or as it should be, and the other turns are never lost. This is the
|
|
64
|
+
* mechanism forget-scrubbing will use (F20.5.1a).
|
|
65
|
+
*/
|
|
66
|
+
export async function archiveClear(storage: ArchiveRuntimeStorage, key: string, from: number | null, to: number | null): Promise<void> {
|
|
67
|
+
if (from === null || to === null) {
|
|
68
|
+
for (const e of await storage.entries(key, 'archive')) if (SEGMENT.test(e.entry)) await storage.remove(key, e.entry);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
for (const entry of segments(from, to)) {
|
|
72
|
+
const lines = await storage.readLines(key, entry);
|
|
73
|
+
const keep = lines.filter(line => { const p = parse(line); return p !== null && (p.n < from || p.n > to); });
|
|
74
|
+
if (keep.length === lines.length) continue;
|
|
75
|
+
await storage.replaceLines(key, entry, keep);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const utf8 = (text: string) => new TextEncoder().encode(text).length;
|
|
80
|
+
const ENTRY = /^[a-z0-9]+$/;
|
|
81
|
+
function checkEntry(entry: string) {
|
|
82
|
+
if (!ENTRY.test(entry)) throw new CrocheError('invalid_input', 'An archive entry name is [a-z0-9]+.');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Archive entries in memory: `MemoryStorage`'s, for tests and one-shot prototypes. */
|
|
86
|
+
export class MemoryArchive implements ArchiveRuntimeStorage {
|
|
87
|
+
private readonly lines = new Map<string, string[]>();
|
|
88
|
+
async appendLine(key: string, entry: string, line: string) {
|
|
89
|
+
checkEntry(entry);
|
|
90
|
+
const id = JSON.stringify([key, entry]);
|
|
91
|
+
this.lines.set(id, [...(this.lines.get(id) ?? []), line]);
|
|
92
|
+
}
|
|
93
|
+
async readLines(key: string, entry: string) { return [...(this.lines.get(JSON.stringify([key, entry])) ?? [])]; }
|
|
94
|
+
async replaceLines(key: string, entry: string, lines: string[]) {
|
|
95
|
+
checkEntry(entry);
|
|
96
|
+
if (lines.length) this.lines.set(JSON.stringify([key, entry]), [...lines]);
|
|
97
|
+
else this.lines.delete(JSON.stringify([key, entry]));
|
|
98
|
+
}
|
|
99
|
+
async remove(key: string, entry: string) { this.lines.delete(JSON.stringify([key, entry])); }
|
|
100
|
+
async entries(key: string, prefix: string) {
|
|
101
|
+
const out: Array<{ entry: string; bytes: number }> = [];
|
|
102
|
+
for (const [id, lines] of this.lines) {
|
|
103
|
+
const [k, entry] = JSON.parse(id) as [string, string];
|
|
104
|
+
if (k === key && entry.startsWith(prefix)) out.push({ entry, bytes: lines.reduce((sum, l) => sum + utf8(l) + 1, 0) });
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Archive entries in IndexedDB (F20: the web default). One object store of lines, each
|
|
112
|
+
* `{key, entry, line, bytes}` under an increasing id, so an entry's lines read back in append
|
|
113
|
+
* order. Every call is one transaction: a line is in or out, never torn.
|
|
114
|
+
*/
|
|
115
|
+
export class IndexedDbArchive implements ArchiveRuntimeStorage {
|
|
116
|
+
private db?: Promise<IDBDatabase>;
|
|
117
|
+
constructor(private readonly name = 'croche-archive', private readonly factory: IDBFactory = globalThis.indexedDB) {
|
|
118
|
+
if (!factory) throw new CrocheError('host_unavailable', 'IndexedDbArchive needs IndexedDB.');
|
|
119
|
+
}
|
|
120
|
+
private open(): Promise<IDBDatabase> {
|
|
121
|
+
this.db ??= new Promise<IDBDatabase>((resolve, reject) => {
|
|
122
|
+
const request = this.factory.open(this.name, 1);
|
|
123
|
+
request.onupgradeneeded = () => {
|
|
124
|
+
const lines = request.result.createObjectStore('lines', { autoIncrement: true });
|
|
125
|
+
lines.createIndex('entry', ['key', 'entry']);
|
|
126
|
+
};
|
|
127
|
+
request.onsuccess = () => resolve(request.result);
|
|
128
|
+
request.onerror = () => reject(new CrocheError('storage_error', 'The archive database could not be opened.'));
|
|
129
|
+
});
|
|
130
|
+
return this.db;
|
|
131
|
+
}
|
|
132
|
+
private async run<T>(mode: IDBTransactionMode, work: (lines: IDBObjectStore, tx: IDBTransaction) => IDBRequest<T> | void): Promise<T | undefined> {
|
|
133
|
+
const db = await this.open();
|
|
134
|
+
return new Promise<T | undefined>((resolve, reject) => {
|
|
135
|
+
const tx = db.transaction('lines', mode);
|
|
136
|
+
let request: IDBRequest<T> | void;
|
|
137
|
+
try { request = work(tx.objectStore('lines'), tx); }
|
|
138
|
+
catch { try { tx.abort(); } catch { /* already finished */ } }
|
|
139
|
+
tx.oncomplete = () => resolve(request ? request.result : undefined);
|
|
140
|
+
tx.onerror = tx.onabort = () => reject(new CrocheError('storage_error', 'The archive could not be read or written.'));
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
async appendLine(key: string, entry: string, line: string) {
|
|
144
|
+
checkEntry(entry);
|
|
145
|
+
await this.run('readwrite', lines => lines.add(this.row(key, entry, line)));
|
|
146
|
+
}
|
|
147
|
+
async readLines(key: string, entry: string) {
|
|
148
|
+
const rows = await this.run<Array<{ line: string }>>('readonly', lines => lines.index('entry').getAll(IDBKeyRange.only([key, entry])));
|
|
149
|
+
return (rows ?? []).map(r => r.line);
|
|
150
|
+
}
|
|
151
|
+
/** The row stored for one line (a seam for tests that fail a rewrite midway). */
|
|
152
|
+
protected row(key: string, entry: string, line: string): unknown {
|
|
153
|
+
return { key, entry, line, bytes: utf8(line) + 1 };
|
|
154
|
+
}
|
|
155
|
+
/** One readwrite transaction: the old rows are deleted and the new ones put, or neither. */
|
|
156
|
+
async replaceLines(key: string, entry: string, replacement: string[]) {
|
|
157
|
+
checkEntry(entry);
|
|
158
|
+
await this.run('readwrite', (lines, tx) => {
|
|
159
|
+
const cursor = lines.index('entry').openKeyCursor(IDBKeyRange.only([key, entry]));
|
|
160
|
+
cursor.onsuccess = () => {
|
|
161
|
+
const c = cursor.result;
|
|
162
|
+
if (c) { lines.delete(c.primaryKey); c.continue(); return; }
|
|
163
|
+
try { for (const line of replacement) lines.add(this.row(key, entry, line)); }
|
|
164
|
+
catch { tx.abort(); }
|
|
165
|
+
};
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
async remove(key: string, entry: string) {
|
|
169
|
+
await this.run('readwrite', lines => {
|
|
170
|
+
const cursor = lines.index('entry').openKeyCursor(IDBKeyRange.only([key, entry]));
|
|
171
|
+
cursor.onsuccess = () => { const c = cursor.result; if (c) { lines.delete(c.primaryKey); c.continue(); } };
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
async entries(key: string, prefix: string) {
|
|
175
|
+
const sizes = new Map<string, number>();
|
|
176
|
+
await this.run('readonly', lines => {
|
|
177
|
+
const cursor = lines.index('entry').openCursor(IDBKeyRange.bound([key, prefix], [key, `${prefix}`]));
|
|
178
|
+
cursor.onsuccess = () => {
|
|
179
|
+
const c = cursor.result;
|
|
180
|
+
if (!c) return;
|
|
181
|
+
const row = c.value as { entry: string; bytes: number };
|
|
182
|
+
sizes.set(row.entry, (sizes.get(row.entry) ?? 0) + row.bytes);
|
|
183
|
+
c.continue();
|
|
184
|
+
};
|
|
185
|
+
});
|
|
186
|
+
return [...sizes].map(([entry, bytes]) => ({ entry, bytes }));
|
|
187
|
+
}
|
|
188
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { rename } from 'node:fs/promises';
|
|
2
|
+
import { CrocheError } from './types.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Waits between attempts to replace a file on Windows. There, another process (antivirus, the
|
|
6
|
+
* search indexer, a backup or sync agent) can hold the target or the temporary file open for a
|
|
7
|
+
* moment, and rename then fails with EPERM, EBUSY or EACCES although nothing is wrong. About
|
|
8
|
+
* 0.8 s in all, then the failure is reported.
|
|
9
|
+
*/
|
|
10
|
+
export const REPLACE_RETRY_DELAYS_MS: readonly number[] = [10, 25, 50, 100, 200, 400];
|
|
11
|
+
const TRANSIENT = new Set(['EPERM', 'EBUSY', 'EACCES']);
|
|
12
|
+
|
|
13
|
+
export interface ReplaceIo {
|
|
14
|
+
rename(from: string, to: string): Promise<void>;
|
|
15
|
+
platform(): NodeJS.Platform;
|
|
16
|
+
sleep(ms: number): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
const io: ReplaceIo = {
|
|
19
|
+
rename,
|
|
20
|
+
platform: () => process.platform,
|
|
21
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Atomically replaces `to` with `from` (rename). On win32 only, a transient sharing failure is
|
|
26
|
+
* retried with bounded backoff; past the bound it is `storage_error`, its cause the last
|
|
27
|
+
* failure. Every other failure, and every failure on other platforms, is thrown as it is.
|
|
28
|
+
*/
|
|
29
|
+
export async function replaceFile(from: string, to: string, override: Partial<ReplaceIo> = {}): Promise<void> {
|
|
30
|
+
const { rename: move, platform, sleep } = { ...io, ...override };
|
|
31
|
+
for (let attempt = 0; ; attempt++) {
|
|
32
|
+
try { await move(from, to); return; }
|
|
33
|
+
catch (error) {
|
|
34
|
+
const code = (error as NodeJS.ErrnoException).code ?? '';
|
|
35
|
+
if (platform() !== 'win32' || !TRANSIENT.has(code)) throw error;
|
|
36
|
+
if (attempt >= REPLACE_RETRY_DELAYS_MS.length) {
|
|
37
|
+
const failure = new CrocheError('storage_error', `The stored value could not be replaced: ${code} on each of ${attempt + 1} attempts. Another program (often antivirus or a sync agent) is holding the file open.`);
|
|
38
|
+
throw Object.assign(failure, { cause: error });
|
|
39
|
+
}
|
|
40
|
+
await sleep(REPLACE_RETRY_DELAYS_MS[attempt]);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/commands.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { JsonValue, RuntimeOptions, ToolContext } from './types.js';
|
|
2
|
+
import type { ToolResult } from './images.js';
|
|
3
|
+
|
|
4
|
+
/** A typed CLI argument interpreted by the shared Core, without executing a shell. */
|
|
5
|
+
export interface CommandArgument {
|
|
6
|
+
name: string;
|
|
7
|
+
/** Callback argument name; defaults to name. */
|
|
8
|
+
arg?: string;
|
|
9
|
+
type: 'string' | 'integer' | 'number' | 'boolean' | 'duration';
|
|
10
|
+
description?: string;
|
|
11
|
+
required?: boolean;
|
|
12
|
+
default?: JsonValue;
|
|
13
|
+
enum?: JsonValue[];
|
|
14
|
+
minimum?: number;
|
|
15
|
+
maximum?: number;
|
|
16
|
+
minLength?: number;
|
|
17
|
+
maxLength?: number;
|
|
18
|
+
/** Other flag names accepted for this one (e.g. `id` for `task-id`); shown only in help. */
|
|
19
|
+
aliases?: string[];
|
|
20
|
+
/** Flags only: several values, written `--tags work,home` or `--tags work --tags home`; the
|
|
21
|
+
* handler receives an array. */
|
|
22
|
+
list?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface RuntimeCommand {
|
|
26
|
+
/** Stable application receipt/telemetry identifier, independent of CLI spelling. */
|
|
27
|
+
key: string;
|
|
28
|
+
/** One CLI segment; omit for a command at the Tool root. */
|
|
29
|
+
name?: string;
|
|
30
|
+
summary: string;
|
|
31
|
+
/** Other names accepted for this command (e.g. `edit`, `upgrade` for `update`), for verbs a
|
|
32
|
+
* model may mix up; shown only in help. */
|
|
33
|
+
aliases?: string[];
|
|
34
|
+
timeoutMs?: number;
|
|
35
|
+
/** A read: its result is the answer (a lookup, a list, a status). With replyWithCommands, a
|
|
36
|
+
* round that runs a read always gets a reply written after the result. */
|
|
37
|
+
reads?: boolean;
|
|
38
|
+
flags?: CommandArgument[];
|
|
39
|
+
positionals?: CommandArgument[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface CommandInvocation {
|
|
43
|
+
tool: string;
|
|
44
|
+
command?: string;
|
|
45
|
+
key: string;
|
|
46
|
+
args: Record<string, JsonValue>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A grouped application capability. The model still sees only run_tool({cmd}). */
|
|
50
|
+
export interface RuntimeTool {
|
|
51
|
+
name: string;
|
|
52
|
+
summary: string;
|
|
53
|
+
commands: RuntimeCommand[];
|
|
54
|
+
/** Return structured rejection JSON for an action the model can correct.
|
|
55
|
+
* A throw after dispatch ends the turn because its effects may be unknown. */
|
|
56
|
+
execute(invocation: CommandInvocation, context: ToolContext): JsonValue | ToolResult | Promise<JsonValue | ToolResult>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type RuntimeToolMetadata = Omit<RuntimeTool, 'execute'>;
|
|
60
|
+
|
|
61
|
+
/** Options consumed by the shared Core host. */
|
|
62
|
+
export type CoreRuntimeOptions = RuntimeOptions;
|