@haikit/server 0.1.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 +21 -0
- package/README.md +21 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/routes.d.ts +11 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/routes.js +54 -0
- package/dist/routes.js.map +1 -0
- package/dist/runtime.d.ts +31 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +288 -0
- package/dist/runtime.js.map +1 -0
- package/dist/store.d.ts +10 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +50 -0
- package/dist/store.js.map +1 -0
- package/package.json +55 -0
- package/src/index.ts +6 -0
- package/src/routes.ts +63 -0
- package/src/runtime.ts +349 -0
- package/src/store.ts +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 hai contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# @haikit/server
|
|
2
|
+
|
|
3
|
+
The runtime: agent loop, elicit state machine, the interaction security
|
|
4
|
+
boundary, and a derived `query_ui`.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
import { createHai, memoryStore, nodeHandler } from "@haikit/server";
|
|
8
|
+
|
|
9
|
+
const hai = createHai({ model, store: memoryStore(), tools, surfaces, system });
|
|
10
|
+
const handle = nodeHandler(hai, "/hai");
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Two routes: `POST /hai/chat` and `POST /hai/interact`, both streaming SSE.
|
|
14
|
+
|
|
15
|
+
**`/hai/interact` accepts `{handle, action, value}` and nothing else.** What an
|
|
16
|
+
action *means* is resolved server-side from the surface's declared contract. If
|
|
17
|
+
the client could name a tool, a prompt injection inside any tool result would
|
|
18
|
+
become a button wired to it.
|
|
19
|
+
|
|
20
|
+
`memoryStore()` is for development. A parked elicit turn is durable state —
|
|
21
|
+
lose `pending` and that conversation can never be sent again.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { Hai, type HaiConfig } from "./runtime.js";
|
|
2
|
+
export { memoryStore } from "./store.js";
|
|
3
|
+
export { nodeHandler } from "./routes.js";
|
|
4
|
+
import { Hai, type HaiConfig } from "./runtime.js";
|
|
5
|
+
export declare const createHai: (config: HaiConfig) => Hai;
|
|
6
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,KAAK,SAAS,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,GAAG,EAAE,KAAK,SAAS,EAAE,MAAM,cAAc,CAAC;AACnD,eAAO,MAAM,SAAS,GAAI,QAAQ,SAAS,QAAoB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAkB,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,GAAG,EAAkB,MAAM,cAAc,CAAC;AACnD,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,MAAiB,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC"}
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { Hai } from "./runtime.js";
|
|
3
|
+
/**
|
|
4
|
+
* Node http handler for the two routes. Returns true if it handled the request.
|
|
5
|
+
*
|
|
6
|
+
* Both routes stream SSE, because both can resume the agent loop. Note what the
|
|
7
|
+
* interact route accepts: {handle, action, value} and nothing else. The client
|
|
8
|
+
* cannot name a tool, a handler, or an action target.
|
|
9
|
+
*/
|
|
10
|
+
export declare function nodeHandler(hai: Hai, basePath?: string): (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;
|
|
11
|
+
//# sourceMappingURL=routes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AAExC;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,SAAS,IACxB,KAAK,eAAe,EAAE,KAAK,cAAc,KAAG,OAAO,CAAC,OAAO,CAAC,CAiC1F"}
|
package/dist/routes.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node http handler for the two routes. Returns true if it handled the request.
|
|
3
|
+
*
|
|
4
|
+
* Both routes stream SSE, because both can resume the agent loop. Note what the
|
|
5
|
+
* interact route accepts: {handle, action, value} and nothing else. The client
|
|
6
|
+
* cannot name a tool, a handler, or an action target.
|
|
7
|
+
*/
|
|
8
|
+
export function nodeHandler(hai, basePath = "/hai") {
|
|
9
|
+
return async function handle(req, res) {
|
|
10
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
11
|
+
if (req.method !== "POST" || !url.pathname.startsWith(basePath))
|
|
12
|
+
return false;
|
|
13
|
+
const route = url.pathname.slice(basePath.length);
|
|
14
|
+
if (route !== "/chat" && route !== "/interact")
|
|
15
|
+
return false;
|
|
16
|
+
const body = await readJson(req);
|
|
17
|
+
const conversation = await hai.config.store.loadConversation(body.conversationId);
|
|
18
|
+
const emit = openSSE(res);
|
|
19
|
+
if (route === "/chat") {
|
|
20
|
+
emit({ type: "hello", conversationId: conversation.id, model: hai.config.model.id });
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
if (route === "/chat") {
|
|
24
|
+
await hai.send(conversation, String(body.message ?? ""), emit);
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
await hai.interact(conversation, { handle: body.handle, action: body.action, value: body.value }, emit);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
emit({ type: "error", message: err.message });
|
|
32
|
+
}
|
|
33
|
+
await hai.config.store.saveConversation(conversation);
|
|
34
|
+
res.end();
|
|
35
|
+
return true;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function openSSE(res) {
|
|
39
|
+
res.writeHead(200, {
|
|
40
|
+
"content-type": "text/event-stream",
|
|
41
|
+
"cache-control": "no-cache",
|
|
42
|
+
connection: "keep-alive",
|
|
43
|
+
});
|
|
44
|
+
return (event) => {
|
|
45
|
+
res.write(`data: ${JSON.stringify(event)}\n\n`);
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
async function readJson(req) {
|
|
49
|
+
const chunks = [];
|
|
50
|
+
for await (const chunk of req)
|
|
51
|
+
chunks.push(chunk);
|
|
52
|
+
return JSON.parse(Buffer.concat(chunks).toString() || "{}");
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=routes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAIA;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,GAAQ,EAAE,QAAQ,GAAG,MAAM;IACrD,OAAO,KAAK,UAAU,MAAM,CAAC,GAAoB,EAAE,GAAmB;QACpE,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,EAAE,kBAAkB,CAAC,CAAC;QACxD,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC,QAAQ,CAAC;YAAE,OAAO,KAAK,CAAC;QAE9E,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QAClD,IAAI,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,WAAW;YAAE,OAAO,KAAK,CAAC;QAE7D,MAAM,IAAI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mBAAmB;QACnC,eAAe,EAAE,UAAU;QAC3B,UAAU,EAAE,YAAY;KACzB,CAAC,CAAC;IACH,OAAO,CAAC,KAAgB,EAAE,EAAE;QAC1B,GAAG,CAAC,KAAK,CAAC,SAAS,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAClD,CAAC,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,QAAQ,CAAC,GAAoB;IAC1C,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG;QAAE,MAAM,CAAC,IAAI,CAAC,KAAe,CAAC,CAAC;IAC5D,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,IAAI,IAAI,CAAC,CAAC;AAC9D,CAAC"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type AnySurfaceImpl, type Conversation, type Emit, type ModelAdapter, type StoreAdapter, type Tool } from "@haikit/core";
|
|
2
|
+
export interface HaiConfig {
|
|
3
|
+
model: ModelAdapter;
|
|
4
|
+
store: StoreAdapter;
|
|
5
|
+
system: string;
|
|
6
|
+
tools: Tool[];
|
|
7
|
+
surfaces: AnySurfaceImpl[];
|
|
8
|
+
/** Guard against runaway tool loops. */
|
|
9
|
+
maxHops?: number;
|
|
10
|
+
/** Turn lease duration; a dead process releases after this. */
|
|
11
|
+
leaseMs?: number;
|
|
12
|
+
}
|
|
13
|
+
export declare class Hai {
|
|
14
|
+
readonly config: HaiConfig;
|
|
15
|
+
private readonly surfaces;
|
|
16
|
+
private readonly tools;
|
|
17
|
+
private seq;
|
|
18
|
+
constructor(config: HaiConfig);
|
|
19
|
+
private nid;
|
|
20
|
+
private buildQueryUiTool;
|
|
21
|
+
send(conversation: Conversation, text: string, emit: Emit): Promise<void>;
|
|
22
|
+
interact(conversation: Conversation, input: {
|
|
23
|
+
handle: string;
|
|
24
|
+
action: string;
|
|
25
|
+
value: unknown;
|
|
26
|
+
}, emit: Emit): Promise<void>;
|
|
27
|
+
private runTurn;
|
|
28
|
+
private invokeTool;
|
|
29
|
+
private emitContext;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=runtime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,IAAI,EACT,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,IAAI,EAGV,MAAM,cAAc,CAAC;AAEtB,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,YAAY,CAAC;IACpB,KAAK,EAAE,YAAY,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,IAAI,EAAE,CAAC;IACd,QAAQ,EAAE,cAAc,EAAE,CAAC;IAC3B,wCAAwC;IACxC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,+DAA+D;IAC/D,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAID,qBAAa,GAAG;IACd,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqC;IAC9D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA2B;IACjD,OAAO,CAAC,GAAG,CAAK;gBAEJ,MAAM,EAAE,SAAS;IAU7B,OAAO,CAAC,GAAG;IAMX,OAAO,CAAC,gBAAgB;IAuDlB,IAAI,CAAC,YAAY,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IA0BzE,QAAQ,CACZ,YAAY,EAAE,YAAY,EAC1B,KAAK,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,EACzD,IAAI,EAAE,IAAI,GACT,OAAO,CAAC,IAAI,CAAC;YAsDF,OAAO;YA0EP,UAAU;YA+DV,WAAW;CAa1B"}
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import { estTokens, makeCap, } from "@haikit/core";
|
|
2
|
+
const LEASE_MS = 120_000;
|
|
3
|
+
export class Hai {
|
|
4
|
+
config;
|
|
5
|
+
surfaces = new Map();
|
|
6
|
+
tools = new Map();
|
|
7
|
+
seq = 0;
|
|
8
|
+
constructor(config) {
|
|
9
|
+
this.config = config;
|
|
10
|
+
for (const s of config.surfaces)
|
|
11
|
+
this.surfaces.set(s.surface.name, s);
|
|
12
|
+
for (const t of config.tools)
|
|
13
|
+
this.tools.set(t.name, t);
|
|
14
|
+
// query_ui is DERIVED, never authored. It cannot drift from the surfaces
|
|
15
|
+
// that actually exist, and it always exists.
|
|
16
|
+
const queryUi = this.buildQueryUiTool();
|
|
17
|
+
this.tools.set(queryUi.name, queryUi);
|
|
18
|
+
}
|
|
19
|
+
nid(prefix) {
|
|
20
|
+
return `${prefix}_${++this.seq}`;
|
|
21
|
+
}
|
|
22
|
+
// ───────────────────────────────────────────────── derived tool
|
|
23
|
+
buildQueryUiTool() {
|
|
24
|
+
const catalogue = [...this.surfaces.values()]
|
|
25
|
+
.map((s) => {
|
|
26
|
+
const names = Object.keys(s.surface.queries);
|
|
27
|
+
return names.length ? `${s.surface.name}: ${names.join(", ")}` : null;
|
|
28
|
+
})
|
|
29
|
+
.filter(Boolean)
|
|
30
|
+
.join(" · ");
|
|
31
|
+
const self = this;
|
|
32
|
+
return {
|
|
33
|
+
name: "query_ui",
|
|
34
|
+
description: "Dereference a rendered component's full dataset. The digest in your context holds only " +
|
|
35
|
+
"highlights; use this for anything beyond it. Never guess about rows you have not seen. " +
|
|
36
|
+
(catalogue ? `Available queries — ${catalogue}.` : ""),
|
|
37
|
+
input: { parse: (v) => v },
|
|
38
|
+
inputJsonSchema: {
|
|
39
|
+
type: "object",
|
|
40
|
+
properties: {
|
|
41
|
+
handle: { type: "string", description: "e.g. ui_01" },
|
|
42
|
+
query: { type: "string" },
|
|
43
|
+
args: { type: "object" },
|
|
44
|
+
},
|
|
45
|
+
required: ["handle", "query"],
|
|
46
|
+
},
|
|
47
|
+
strict: false,
|
|
48
|
+
async run(input, ctx) {
|
|
49
|
+
const record = await self.config.store.getPayload(input.handle, ctx.conversationId);
|
|
50
|
+
if (!record)
|
|
51
|
+
return ctx.text(`No such handle: ${input.handle}`);
|
|
52
|
+
const impl = self.surfaces.get(record.component);
|
|
53
|
+
const handler = impl?.impl.queries?.[input.query];
|
|
54
|
+
if (!impl || !handler) {
|
|
55
|
+
const available = impl ? Object.keys(impl.surface.queries).join(", ") : "none";
|
|
56
|
+
return ctx.text(`Unsupported query "${input.query}". Available: ${available || "none"}.`);
|
|
57
|
+
}
|
|
58
|
+
const spec = impl.surface.queries[input.query];
|
|
59
|
+
let args;
|
|
60
|
+
try {
|
|
61
|
+
args = spec.input.parse(input.args ?? {});
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
return ctx.text(`Invalid args for "${input.query}": ${err.message}`);
|
|
65
|
+
}
|
|
66
|
+
const rows = record.props?.[primaryCollection(record.props)] ?? [];
|
|
67
|
+
const capped = handler(args, { props: record.props, cap: makeCap(rows.length) });
|
|
68
|
+
return ctx.text(capped.text);
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
// ─────────────────────────────────────────────────── public API
|
|
73
|
+
async send(conversation, text, emit) {
|
|
74
|
+
// The user typed while a tool was parked. Every tool_use in a turn must
|
|
75
|
+
// receive a tool_result, so close the pending one out honestly first.
|
|
76
|
+
if (conversation.status === "awaiting" && conversation.pending) {
|
|
77
|
+
const { toolUseId, handle, results, digest } = conversation.pending;
|
|
78
|
+
await this.config.store.freezePayload(handle);
|
|
79
|
+
emit({ type: "ui_state", handle, state: "frozen" });
|
|
80
|
+
conversation.messages.push({
|
|
81
|
+
role: "user",
|
|
82
|
+
content: [
|
|
83
|
+
...results,
|
|
84
|
+
{
|
|
85
|
+
type: "tool_result",
|
|
86
|
+
tool_use_id: toolUseId,
|
|
87
|
+
content: `${digest}\nUser did not select; they said: "${text}"`,
|
|
88
|
+
},
|
|
89
|
+
],
|
|
90
|
+
});
|
|
91
|
+
conversation.pending = null;
|
|
92
|
+
}
|
|
93
|
+
emit({ type: "block_start", block: { kind: "user", id: this.nid("b"), text } });
|
|
94
|
+
conversation.messages.push({ role: "user", content: text });
|
|
95
|
+
await this.runTurn(conversation, emit);
|
|
96
|
+
}
|
|
97
|
+
async interact(conversation, input, emit) {
|
|
98
|
+
const record = await this.config.store.getPayload(input.handle, conversation.id);
|
|
99
|
+
if (!record)
|
|
100
|
+
throw new Error("unknown handle");
|
|
101
|
+
if (record.state === "frozen")
|
|
102
|
+
throw new Error("component is frozen");
|
|
103
|
+
const impl = this.surfaces.get(record.component);
|
|
104
|
+
if (!impl)
|
|
105
|
+
throw new Error(`unknown component: ${record.component}`);
|
|
106
|
+
// GUARANTEE 4 in force at runtime: the client sent {handle, action, value}.
|
|
107
|
+
// What that action MEANS is decided here, from the declared contract.
|
|
108
|
+
const spec = impl.surface.actions[input.action];
|
|
109
|
+
const handler = impl.impl.actions?.[input.action];
|
|
110
|
+
if (!spec || !handler)
|
|
111
|
+
throw new Error("unbound action");
|
|
112
|
+
let value;
|
|
113
|
+
try {
|
|
114
|
+
value = spec.input.parse(input.value);
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
throw new Error(`invalid action payload: ${err.message}`);
|
|
118
|
+
}
|
|
119
|
+
const label = handler(value, { props: record.props, handle: record.handle });
|
|
120
|
+
if (spec.kind === "resolve") {
|
|
121
|
+
if (conversation.pending?.handle !== input.handle)
|
|
122
|
+
throw new Error("nothing awaiting this handle");
|
|
123
|
+
await this.config.store.freezePayload(input.handle);
|
|
124
|
+
emit({ type: "ui_state", handle: input.handle, state: "frozen", selection: value });
|
|
125
|
+
emit({ type: "block_start", block: { kind: "interaction", id: this.nid("b"), handle: input.handle, label } });
|
|
126
|
+
conversation.messages.push({
|
|
127
|
+
role: "user",
|
|
128
|
+
content: [
|
|
129
|
+
...conversation.pending.results,
|
|
130
|
+
{
|
|
131
|
+
type: "tool_result",
|
|
132
|
+
tool_use_id: conversation.pending.toolUseId,
|
|
133
|
+
// The digest rides along: this elicit tool never got a tool_result,
|
|
134
|
+
// so nothing about the search has reached the model yet.
|
|
135
|
+
content: `${conversation.pending.digest}\n${label}`,
|
|
136
|
+
},
|
|
137
|
+
],
|
|
138
|
+
});
|
|
139
|
+
conversation.pending = null;
|
|
140
|
+
return this.runTurn(conversation, emit);
|
|
141
|
+
}
|
|
142
|
+
// inform: enriches the conversation without having blocked it
|
|
143
|
+
emit({ type: "block_start", block: { kind: "interaction", id: this.nid("b"), handle: input.handle, label } });
|
|
144
|
+
conversation.messages.push({ role: "user", content: `[UI interaction] ${label}` });
|
|
145
|
+
return this.runTurn(conversation, emit);
|
|
146
|
+
}
|
|
147
|
+
// ──────────────────────────────────────────────── the agent loop
|
|
148
|
+
async runTurn(conversation, emit) {
|
|
149
|
+
conversation.status = "streaming";
|
|
150
|
+
conversation.leaseUntil = Date.now() + (this.config.leaseMs ?? LEASE_MS);
|
|
151
|
+
emit({ type: "status", status: "streaming" });
|
|
152
|
+
const toolDefs = [...this.tools.values()].map((t) => ({
|
|
153
|
+
name: t.name,
|
|
154
|
+
description: t.description,
|
|
155
|
+
input_schema: t.inputJsonSchema,
|
|
156
|
+
strict: t.strict,
|
|
157
|
+
}));
|
|
158
|
+
for (let hop = 0; hop < (this.config.maxHops ?? 8); hop++) {
|
|
159
|
+
const blockId = this.nid("b");
|
|
160
|
+
let opened = false;
|
|
161
|
+
const final = await this.config.model.generate({
|
|
162
|
+
system: this.config.system,
|
|
163
|
+
tools: toolDefs,
|
|
164
|
+
messages: conversation.messages,
|
|
165
|
+
onTextDelta: (text) => {
|
|
166
|
+
if (!opened) {
|
|
167
|
+
opened = true;
|
|
168
|
+
emit({ type: "block_start", block: { kind: "assistant", id: blockId, text: "" } });
|
|
169
|
+
}
|
|
170
|
+
emit({ type: "text_delta", id: blockId, text });
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
conversation.messages.push({ role: "assistant", content: final.content });
|
|
174
|
+
if (final.stop_reason !== "tool_use")
|
|
175
|
+
break;
|
|
176
|
+
const results = [];
|
|
177
|
+
let parked = null;
|
|
178
|
+
for (const call of final.content.filter((b) => b?.type === "tool_use")) {
|
|
179
|
+
const toolBlockId = this.nid("b");
|
|
180
|
+
emit({
|
|
181
|
+
type: "block_start",
|
|
182
|
+
block: { kind: "tool", id: toolBlockId, name: call.name, input: call.input, status: "running" },
|
|
183
|
+
});
|
|
184
|
+
const started = Date.now();
|
|
185
|
+
const { ret, mode } = await this.invokeTool(conversation, call, emit, toolBlockId);
|
|
186
|
+
const ms = Date.now() - started;
|
|
187
|
+
if (mode === "elicit" && ret.handle) {
|
|
188
|
+
emit({ type: "block_update", id: toolBlockId, status: "awaiting", ms, result: ret.model });
|
|
189
|
+
parked = { toolUseId: call.id, handle: ret.handle, digest: ret.model };
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
emit({ type: "block_update", id: toolBlockId, status: "ok", ms, result: ret.model });
|
|
193
|
+
results.push({ type: "tool_result", tool_use_id: call.id, content: ret.model });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (parked) {
|
|
197
|
+
// Hold the resolved siblings too — the API is all-or-nothing per batch.
|
|
198
|
+
conversation.status = "awaiting";
|
|
199
|
+
conversation.pending = { ...parked, results };
|
|
200
|
+
conversation.leaseUntil = null;
|
|
201
|
+
emit({ type: "status", status: "awaiting" });
|
|
202
|
+
await this.emitContext(conversation, emit);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
conversation.messages.push({ role: "user", content: results });
|
|
206
|
+
}
|
|
207
|
+
conversation.status = "idle";
|
|
208
|
+
conversation.leaseUntil = null;
|
|
209
|
+
emit({ type: "status", status: "idle" });
|
|
210
|
+
await this.emitContext(conversation, emit);
|
|
211
|
+
}
|
|
212
|
+
async invokeTool(conversation, call, emit, toolBlockId) {
|
|
213
|
+
const tool = this.tools.get(call.name);
|
|
214
|
+
if (!tool)
|
|
215
|
+
return { ret: { model: `Unknown tool: ${call.name}` }, mode: null };
|
|
216
|
+
let mode = null;
|
|
217
|
+
const ctx = {
|
|
218
|
+
conversationId: conversation.id,
|
|
219
|
+
text: (model) => ({ model }),
|
|
220
|
+
render: (async (impl, props, options) => {
|
|
221
|
+
const surfaceMode = options?.mode ?? "display";
|
|
222
|
+
mode = surfaceMode;
|
|
223
|
+
// Validate before storing: props may originate outside this process.
|
|
224
|
+
const parsed = impl.surface.props.parse(props);
|
|
225
|
+
const handle = await this.config.store.putPayload({
|
|
226
|
+
conversationId: conversation.id,
|
|
227
|
+
component: impl.surface.name,
|
|
228
|
+
version: impl.surface.version,
|
|
229
|
+
props: parsed,
|
|
230
|
+
mode: surfaceMode,
|
|
231
|
+
state: "live",
|
|
232
|
+
});
|
|
233
|
+
conversation.handles.push(handle);
|
|
234
|
+
// The split, in two lines. Digest -> model. Payload -> browser.
|
|
235
|
+
const digest = impl.impl.digest(parsed, { handle });
|
|
236
|
+
emit({
|
|
237
|
+
type: "ui_open",
|
|
238
|
+
handle,
|
|
239
|
+
toolId: toolBlockId,
|
|
240
|
+
component: impl.surface.name,
|
|
241
|
+
version: impl.surface.version,
|
|
242
|
+
mode: surfaceMode,
|
|
243
|
+
});
|
|
244
|
+
emit({ type: "ui_props", handle, props: parsed });
|
|
245
|
+
return { model: digest, handle };
|
|
246
|
+
}),
|
|
247
|
+
};
|
|
248
|
+
let input;
|
|
249
|
+
try {
|
|
250
|
+
input = tool.input.parse(call.input);
|
|
251
|
+
}
|
|
252
|
+
catch (err) {
|
|
253
|
+
return { ret: { model: `Invalid input for ${call.name}: ${err.message}` }, mode: null };
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
const ret = await tool.run(input, ctx);
|
|
257
|
+
return { ret, mode };
|
|
258
|
+
}
|
|
259
|
+
catch (err) {
|
|
260
|
+
return { ret: { model: `${call.name} failed: ${err.message}` }, mode: null };
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
async emitContext(conversation, emit) {
|
|
264
|
+
let uiTokens = 0;
|
|
265
|
+
for (const handle of conversation.handles) {
|
|
266
|
+
const record = await this.config.store.getPayload(handle, conversation.id);
|
|
267
|
+
if (record)
|
|
268
|
+
uiTokens += estTokens(record.props);
|
|
269
|
+
}
|
|
270
|
+
emit({
|
|
271
|
+
type: "context",
|
|
272
|
+
messages: conversation.messages,
|
|
273
|
+
modelTokens: estTokens(conversation.messages),
|
|
274
|
+
uiTokens,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/** Find the array prop a surface's queries operate over (for cap totals). */
|
|
279
|
+
function primaryCollection(props) {
|
|
280
|
+
if (props && typeof props === "object") {
|
|
281
|
+
for (const [key, value] of Object.entries(props)) {
|
|
282
|
+
if (Array.isArray(value))
|
|
283
|
+
return key;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return "";
|
|
287
|
+
}
|
|
288
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,OAAO,GASR,MAAM,cAAc,CAAC;AActB,MAAM,QAAQ,GAAG,OAAO,CAAC;AAEzB,MAAM,OAAO,GAAG;IACL,MAAM,CAAY;IACV,QAAQ,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC7C,KAAK,GAAG,IAAI,GAAG,EAAgB,CAAC;IACzC,GAAG,GAAG,CAAC,CAAC;IAEhB,YAAY,MAAiB;QAC3B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,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EAAE,CAAC;YAC1C,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,EAAE,YAAY,CAAC,EAAE,CAAC,CAAC;YAC3E,IAAI,MAAM;gBAAE,QAAQ,IAAI,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAClD,CAAC;QACD,IAAI,CAAC;YACH,IAAI,EAAE,SAAS;YACf,QAAQ,EAAE,YAAY,CAAC,QAAQ;YAC/B,WAAW,EAAE,SAAS,CAAC,YAAY,CAAC,QAAQ,CAAC;YAC7C,QAAQ;SACT,CAAC,CAAC;IACL,CAAC;CACF;AAED,6EAA6E;AAC7E,SAAS,iBAAiB,CAAC,KAAc;IACvC,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACvC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAgC,CAAC,EAAE,CAAC;YAC5E,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;gBAAE,OAAO,GAAG,CAAC;QACvC,CAAC;IACH,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC"}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { StoreAdapter } from "@haikit/core";
|
|
2
|
+
/**
|
|
3
|
+
* In-memory store. Implements the same interface a Postgres store would.
|
|
4
|
+
*
|
|
5
|
+
* Swapping this for a durable store is the single highest-value change for
|
|
6
|
+
* production: a parked `elicit` turn is durable state, and losing `pending`
|
|
7
|
+
* makes a conversation permanently unsendable.
|
|
8
|
+
*/
|
|
9
|
+
export declare function memoryStore(): StoreAdapter;
|
|
10
|
+
//# sourceMappingURL=store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA+B,YAAY,EAAE,MAAM,cAAc,CAAC;AAE9E;;;;;;GAMG;AACH,wBAAgB,WAAW,IAAI,YAAY,CA2C1C"}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory store. Implements the same interface a Postgres store would.
|
|
3
|
+
*
|
|
4
|
+
* Swapping this for a durable store is the single highest-value change for
|
|
5
|
+
* production: a parked `elicit` turn is durable state, and losing `pending`
|
|
6
|
+
* makes a conversation permanently unsendable.
|
|
7
|
+
*/
|
|
8
|
+
export function memoryStore() {
|
|
9
|
+
const conversations = new Map();
|
|
10
|
+
const payloads = new Map();
|
|
11
|
+
let convSeq = 0;
|
|
12
|
+
let handleSeq = 0;
|
|
13
|
+
return {
|
|
14
|
+
async loadConversation(id) {
|
|
15
|
+
if (id && conversations.has(id))
|
|
16
|
+
return conversations.get(id);
|
|
17
|
+
const conversation = {
|
|
18
|
+
id: `conv_${++convSeq}`,
|
|
19
|
+
status: "idle",
|
|
20
|
+
messages: [],
|
|
21
|
+
handles: [],
|
|
22
|
+
pending: null,
|
|
23
|
+
leaseUntil: null,
|
|
24
|
+
};
|
|
25
|
+
conversations.set(conversation.id, conversation);
|
|
26
|
+
return conversation;
|
|
27
|
+
},
|
|
28
|
+
async saveConversation(conversation) {
|
|
29
|
+
conversations.set(conversation.id, conversation);
|
|
30
|
+
},
|
|
31
|
+
async putPayload(record) {
|
|
32
|
+
const handle = `ui_${String(++handleSeq).padStart(2, "0")}`;
|
|
33
|
+
payloads.set(handle, { ...record, handle, createdAt: Date.now() });
|
|
34
|
+
return handle;
|
|
35
|
+
},
|
|
36
|
+
/** Scoped: a handle from another conversation must not resolve. */
|
|
37
|
+
async getPayload(handle, conversationId) {
|
|
38
|
+
const record = payloads.get(handle);
|
|
39
|
+
if (!record || record.conversationId !== conversationId)
|
|
40
|
+
return null;
|
|
41
|
+
return record;
|
|
42
|
+
},
|
|
43
|
+
async freezePayload(handle) {
|
|
44
|
+
const record = payloads.get(handle);
|
|
45
|
+
if (record)
|
|
46
|
+
record.state = "frozen";
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,MAAM,UAAU,WAAW;IACzB,MAAM,aAAa,GAAG,IAAI,GAAG,EAAwB,CAAC;IACtD,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAyB,CAAC;IAClD,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,IAAI,SAAS,GAAG,CAAC,CAAC;IAElB,OAAO;QACL,KAAK,CAAC,gBAAgB,CAAC,EAAE;YACvB,IAAI,EAAE,IAAI,aAAa,CAAC,GAAG,CAAC,EAAE,CAAC;gBAAE,OAAO,aAAa,CAAC,GAAG,CAAC,EAAE,CAAE,CAAC;YAC/D,MAAM,YAAY,GAAiB;gBACjC,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE;gBACvB,MAAM,EAAE,MAAM;gBACd,QAAQ,EAAE,EAAE;gBACZ,OAAO,EAAE,EAAE;gBACX,OAAO,EAAE,IAAI;gBACb,UAAU,EAAE,IAAI;aACjB,CAAC;YACF,aAAa,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,EAAE,YAAY,CAAC,CAAC;YACjD,OAAO,YAAY,CAAC;QACtB,CAAC;QAED,KAAK,CAAC,gBAAgB,CAAC,YAAY;YACjC,aAAa,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,EAAE,YAAY,CAAC,CAAC;QACnD,CAAC;QAED,KAAK,CAAC,UAAU,CAAC,MAAM;YACrB,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;YAC5D,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YACnE,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,mEAAmE;QACnE,KAAK,CAAC,UAAU,CAAC,MAAM,EAAE,cAAc;YACrC,MAAM,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACpC,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,cAAc,KAAK,cAAc;gBAAE,OAAO,IAAI,CAAC;YACrE,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,KAAK,CAAC,aAAa,CAAC,MAAM;YACxB,MAAM,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACpC,IAAI,MAAM;gBAAE,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC;QACtC,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@haikit/server",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The haikit server runtime: agent loop, elicit state machine, derived query_ui, and the interaction security boundary.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"haikit",
|
|
7
|
+
"llm",
|
|
8
|
+
"agent",
|
|
9
|
+
"agentic-ui",
|
|
10
|
+
"generative-ui",
|
|
11
|
+
"tool-use",
|
|
12
|
+
"tool-calling",
|
|
13
|
+
"elicitation",
|
|
14
|
+
"sse",
|
|
15
|
+
"ai"
|
|
16
|
+
],
|
|
17
|
+
"type": "module",
|
|
18
|
+
"main": "./dist/index.js",
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"default": "./dist/index.js"
|
|
24
|
+
},
|
|
25
|
+
"./package.json": "./package.json"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"dist",
|
|
29
|
+
"src"
|
|
30
|
+
],
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=22"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"prepack": "npm --prefix ../.. run build"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@haikit/core": "0.1.0",
|
|
40
|
+
"@types/node": ">=22"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"license": "MIT",
|
|
46
|
+
"homepage": "https://github.com/wfoxd/haikit/tree/main/packages/server#readme",
|
|
47
|
+
"bugs": {
|
|
48
|
+
"url": "https://github.com/wfoxd/haikit/issues"
|
|
49
|
+
},
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "git+https://github.com/wfoxd/haikit.git",
|
|
53
|
+
"directory": "packages/server"
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/index.ts
ADDED
package/src/routes.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { Emit, WireEvent } from "@haikit/core";
|
|
3
|
+
import type { Hai } from "./runtime.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Node http handler for the two routes. Returns true if it handled the request.
|
|
7
|
+
*
|
|
8
|
+
* Both routes stream SSE, because both can resume the agent loop. Note what the
|
|
9
|
+
* interact route accepts: {handle, action, value} and nothing else. The client
|
|
10
|
+
* cannot name a tool, a handler, or an action target.
|
|
11
|
+
*/
|
|
12
|
+
export function nodeHandler(hai: Hai, basePath = "/hai") {
|
|
13
|
+
return async function handle(req: IncomingMessage, res: ServerResponse): Promise<boolean> {
|
|
14
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
15
|
+
if (req.method !== "POST" || !url.pathname.startsWith(basePath)) return false;
|
|
16
|
+
|
|
17
|
+
const route = url.pathname.slice(basePath.length);
|
|
18
|
+
if (route !== "/chat" && route !== "/interact") return false;
|
|
19
|
+
|
|
20
|
+
const body = await readJson(req);
|
|
21
|
+
const conversation = await hai.config.store.loadConversation(body.conversationId);
|
|
22
|
+
|
|
23
|
+
const emit = openSSE(res);
|
|
24
|
+
if (route === "/chat") {
|
|
25
|
+
emit({ type: "hello", conversationId: conversation.id, model: hai.config.model.id });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
if (route === "/chat") {
|
|
30
|
+
await hai.send(conversation, String(body.message ?? ""), emit);
|
|
31
|
+
} else {
|
|
32
|
+
await hai.interact(
|
|
33
|
+
conversation,
|
|
34
|
+
{ handle: body.handle, action: body.action, value: body.value },
|
|
35
|
+
emit,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
} catch (err) {
|
|
39
|
+
emit({ type: "error", message: (err as Error).message });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
await hai.config.store.saveConversation(conversation);
|
|
43
|
+
res.end();
|
|
44
|
+
return true;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function openSSE(res: ServerResponse): Emit {
|
|
49
|
+
res.writeHead(200, {
|
|
50
|
+
"content-type": "text/event-stream",
|
|
51
|
+
"cache-control": "no-cache",
|
|
52
|
+
connection: "keep-alive",
|
|
53
|
+
});
|
|
54
|
+
return (event: WireEvent) => {
|
|
55
|
+
res.write(`data: ${JSON.stringify(event)}\n\n`);
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function readJson(req: IncomingMessage): Promise<any> {
|
|
60
|
+
const chunks: Buffer[] = [];
|
|
61
|
+
for await (const chunk of req) chunks.push(chunk as Buffer);
|
|
62
|
+
return JSON.parse(Buffer.concat(chunks).toString() || "{}");
|
|
63
|
+
}
|
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import {
|
|
2
|
+
estTokens,
|
|
3
|
+
makeCap,
|
|
4
|
+
type AnySurfaceImpl,
|
|
5
|
+
type Conversation,
|
|
6
|
+
type Emit,
|
|
7
|
+
type ModelAdapter,
|
|
8
|
+
type StoreAdapter,
|
|
9
|
+
type Tool,
|
|
10
|
+
type ToolCtx,
|
|
11
|
+
type ToolReturn,
|
|
12
|
+
} from "@haikit/core";
|
|
13
|
+
|
|
14
|
+
export interface HaiConfig {
|
|
15
|
+
model: ModelAdapter;
|
|
16
|
+
store: StoreAdapter;
|
|
17
|
+
system: string;
|
|
18
|
+
tools: Tool[];
|
|
19
|
+
surfaces: AnySurfaceImpl[];
|
|
20
|
+
/** Guard against runaway tool loops. */
|
|
21
|
+
maxHops?: number;
|
|
22
|
+
/** Turn lease duration; a dead process releases after this. */
|
|
23
|
+
leaseMs?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const LEASE_MS = 120_000;
|
|
27
|
+
|
|
28
|
+
export class Hai {
|
|
29
|
+
readonly config: HaiConfig;
|
|
30
|
+
private readonly surfaces = new Map<string, AnySurfaceImpl>();
|
|
31
|
+
private readonly tools = new Map<string, Tool>();
|
|
32
|
+
private seq = 0;
|
|
33
|
+
|
|
34
|
+
constructor(config: HaiConfig) {
|
|
35
|
+
this.config = config;
|
|
36
|
+
for (const s of config.surfaces) this.surfaces.set(s.surface.name, s);
|
|
37
|
+
for (const t of config.tools) this.tools.set(t.name, t);
|
|
38
|
+
// query_ui is DERIVED, never authored. It cannot drift from the surfaces
|
|
39
|
+
// that actually exist, and it always exists.
|
|
40
|
+
const queryUi = this.buildQueryUiTool();
|
|
41
|
+
this.tools.set(queryUi.name, queryUi);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
private nid(prefix: string) {
|
|
45
|
+
return `${prefix}_${++this.seq}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ───────────────────────────────────────────────── derived tool
|
|
49
|
+
|
|
50
|
+
private buildQueryUiTool(): Tool<any> {
|
|
51
|
+
const catalogue = [...this.surfaces.values()]
|
|
52
|
+
.map((s) => {
|
|
53
|
+
const names = Object.keys(s.surface.queries);
|
|
54
|
+
return names.length ? `${s.surface.name}: ${names.join(", ")}` : null;
|
|
55
|
+
})
|
|
56
|
+
.filter(Boolean)
|
|
57
|
+
.join(" · ");
|
|
58
|
+
|
|
59
|
+
const self = this;
|
|
60
|
+
return {
|
|
61
|
+
name: "query_ui",
|
|
62
|
+
description:
|
|
63
|
+
"Dereference a rendered component's full dataset. The digest in your context holds only " +
|
|
64
|
+
"highlights; use this for anything beyond it. Never guess about rows you have not seen. " +
|
|
65
|
+
(catalogue ? `Available queries — ${catalogue}.` : ""),
|
|
66
|
+
input: { parse: (v) => v as any },
|
|
67
|
+
inputJsonSchema: {
|
|
68
|
+
type: "object",
|
|
69
|
+
properties: {
|
|
70
|
+
handle: { type: "string", description: "e.g. ui_01" },
|
|
71
|
+
query: { type: "string" },
|
|
72
|
+
args: { type: "object" },
|
|
73
|
+
},
|
|
74
|
+
required: ["handle", "query"],
|
|
75
|
+
},
|
|
76
|
+
strict: false,
|
|
77
|
+
async run(input: { handle: string; query: string; args?: unknown }, ctx) {
|
|
78
|
+
const record = await self.config.store.getPayload(input.handle, ctx.conversationId);
|
|
79
|
+
if (!record) return ctx.text(`No such handle: ${input.handle}`);
|
|
80
|
+
|
|
81
|
+
const impl = self.surfaces.get(record.component);
|
|
82
|
+
const handler = impl?.impl.queries?.[input.query];
|
|
83
|
+
if (!impl || !handler) {
|
|
84
|
+
const available = impl ? Object.keys(impl.surface.queries).join(", ") : "none";
|
|
85
|
+
return ctx.text(`Unsupported query "${input.query}". Available: ${available || "none"}.`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const spec = impl.surface.queries[input.query];
|
|
89
|
+
let args: unknown;
|
|
90
|
+
try {
|
|
91
|
+
args = spec.input.parse(input.args ?? {});
|
|
92
|
+
} catch (err) {
|
|
93
|
+
return ctx.text(`Invalid args for "${input.query}": ${(err as Error).message}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const rows = (record.props as any)?.[primaryCollection(record.props)] ?? [];
|
|
97
|
+
const capped = handler(args, { props: record.props, cap: makeCap(rows.length) });
|
|
98
|
+
return ctx.text(capped.text);
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ─────────────────────────────────────────────────── public API
|
|
104
|
+
|
|
105
|
+
async send(conversation: Conversation, text: string, emit: Emit): Promise<void> {
|
|
106
|
+
// The user typed while a tool was parked. Every tool_use in a turn must
|
|
107
|
+
// receive a tool_result, so close the pending one out honestly first.
|
|
108
|
+
if (conversation.status === "awaiting" && conversation.pending) {
|
|
109
|
+
const { toolUseId, handle, results, digest } = conversation.pending;
|
|
110
|
+
await this.config.store.freezePayload(handle);
|
|
111
|
+
emit({ type: "ui_state", handle, state: "frozen" });
|
|
112
|
+
conversation.messages.push({
|
|
113
|
+
role: "user",
|
|
114
|
+
content: [
|
|
115
|
+
...results,
|
|
116
|
+
{
|
|
117
|
+
type: "tool_result",
|
|
118
|
+
tool_use_id: toolUseId,
|
|
119
|
+
content: `${digest}\nUser did not select; they said: "${text}"`,
|
|
120
|
+
},
|
|
121
|
+
],
|
|
122
|
+
});
|
|
123
|
+
conversation.pending = null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
emit({ type: "block_start", block: { kind: "user", id: this.nid("b"), text } });
|
|
127
|
+
conversation.messages.push({ role: "user", content: text });
|
|
128
|
+
await this.runTurn(conversation, emit);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async interact(
|
|
132
|
+
conversation: Conversation,
|
|
133
|
+
input: { handle: string; action: string; value: unknown },
|
|
134
|
+
emit: Emit,
|
|
135
|
+
): Promise<void> {
|
|
136
|
+
const record = await this.config.store.getPayload(input.handle, conversation.id);
|
|
137
|
+
if (!record) throw new Error("unknown handle");
|
|
138
|
+
if (record.state === "frozen") throw new Error("component is frozen");
|
|
139
|
+
|
|
140
|
+
const impl = this.surfaces.get(record.component);
|
|
141
|
+
if (!impl) throw new Error(`unknown component: ${record.component}`);
|
|
142
|
+
|
|
143
|
+
// GUARANTEE 4 in force at runtime: the client sent {handle, action, value}.
|
|
144
|
+
// What that action MEANS is decided here, from the declared contract.
|
|
145
|
+
const spec = impl.surface.actions[input.action];
|
|
146
|
+
const handler = impl.impl.actions?.[input.action];
|
|
147
|
+
if (!spec || !handler) throw new Error("unbound action");
|
|
148
|
+
|
|
149
|
+
let value: unknown;
|
|
150
|
+
try {
|
|
151
|
+
value = spec.input.parse(input.value);
|
|
152
|
+
} catch (err) {
|
|
153
|
+
throw new Error(`invalid action payload: ${(err as Error).message}`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const label = handler(value, { props: record.props, handle: record.handle });
|
|
157
|
+
|
|
158
|
+
if (spec.kind === "resolve") {
|
|
159
|
+
if (conversation.pending?.handle !== input.handle) throw new Error("nothing awaiting this handle");
|
|
160
|
+
await this.config.store.freezePayload(input.handle);
|
|
161
|
+
emit({ type: "ui_state", handle: input.handle, state: "frozen", selection: value });
|
|
162
|
+
emit({ type: "block_start", block: { kind: "interaction", id: this.nid("b"), handle: input.handle, label } });
|
|
163
|
+
|
|
164
|
+
conversation.messages.push({
|
|
165
|
+
role: "user",
|
|
166
|
+
content: [
|
|
167
|
+
...conversation.pending.results,
|
|
168
|
+
{
|
|
169
|
+
type: "tool_result",
|
|
170
|
+
tool_use_id: conversation.pending.toolUseId,
|
|
171
|
+
// The digest rides along: this elicit tool never got a tool_result,
|
|
172
|
+
// so nothing about the search has reached the model yet.
|
|
173
|
+
content: `${conversation.pending.digest}\n${label}`,
|
|
174
|
+
},
|
|
175
|
+
],
|
|
176
|
+
});
|
|
177
|
+
conversation.pending = null;
|
|
178
|
+
return this.runTurn(conversation, emit);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// inform: enriches the conversation without having blocked it
|
|
182
|
+
emit({ type: "block_start", block: { kind: "interaction", id: this.nid("b"), handle: input.handle, label } });
|
|
183
|
+
conversation.messages.push({ role: "user", content: `[UI interaction] ${label}` });
|
|
184
|
+
return this.runTurn(conversation, emit);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ──────────────────────────────────────────────── the agent loop
|
|
188
|
+
|
|
189
|
+
private async runTurn(conversation: Conversation, emit: Emit): Promise<void> {
|
|
190
|
+
conversation.status = "streaming";
|
|
191
|
+
conversation.leaseUntil = Date.now() + (this.config.leaseMs ?? LEASE_MS);
|
|
192
|
+
emit({ type: "status", status: "streaming" });
|
|
193
|
+
|
|
194
|
+
const toolDefs = [...this.tools.values()].map((t) => ({
|
|
195
|
+
name: t.name,
|
|
196
|
+
description: t.description,
|
|
197
|
+
input_schema: t.inputJsonSchema,
|
|
198
|
+
strict: t.strict,
|
|
199
|
+
}));
|
|
200
|
+
|
|
201
|
+
for (let hop = 0; hop < (this.config.maxHops ?? 8); hop++) {
|
|
202
|
+
const blockId = this.nid("b");
|
|
203
|
+
let opened = false;
|
|
204
|
+
|
|
205
|
+
const final = await this.config.model.generate({
|
|
206
|
+
system: this.config.system,
|
|
207
|
+
tools: toolDefs,
|
|
208
|
+
messages: conversation.messages,
|
|
209
|
+
onTextDelta: (text) => {
|
|
210
|
+
if (!opened) {
|
|
211
|
+
opened = true;
|
|
212
|
+
emit({ type: "block_start", block: { kind: "assistant", id: blockId, text: "" } });
|
|
213
|
+
}
|
|
214
|
+
emit({ type: "text_delta", id: blockId, text });
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
conversation.messages.push({ role: "assistant", content: final.content });
|
|
219
|
+
if (final.stop_reason !== "tool_use") break;
|
|
220
|
+
|
|
221
|
+
const results: unknown[] = [];
|
|
222
|
+
let parked: { toolUseId: string; handle: string; digest: string } | null = null;
|
|
223
|
+
|
|
224
|
+
for (const call of final.content.filter((b: any) => b?.type === "tool_use")) {
|
|
225
|
+
const toolBlockId = this.nid("b");
|
|
226
|
+
emit({
|
|
227
|
+
type: "block_start",
|
|
228
|
+
block: { kind: "tool", id: toolBlockId, name: call.name, input: call.input, status: "running" },
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
const started = Date.now();
|
|
232
|
+
const { ret, mode } = await this.invokeTool(conversation, call, emit, toolBlockId);
|
|
233
|
+
const ms = Date.now() - started;
|
|
234
|
+
|
|
235
|
+
if (mode === "elicit" && ret.handle) {
|
|
236
|
+
emit({ type: "block_update", id: toolBlockId, status: "awaiting", ms, result: ret.model });
|
|
237
|
+
parked = { toolUseId: call.id, handle: ret.handle, digest: ret.model };
|
|
238
|
+
} else {
|
|
239
|
+
emit({ type: "block_update", id: toolBlockId, status: "ok", ms, result: ret.model });
|
|
240
|
+
results.push({ type: "tool_result", tool_use_id: call.id, content: ret.model });
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (parked) {
|
|
245
|
+
// Hold the resolved siblings too — the API is all-or-nothing per batch.
|
|
246
|
+
conversation.status = "awaiting";
|
|
247
|
+
conversation.pending = { ...parked, results };
|
|
248
|
+
conversation.leaseUntil = null;
|
|
249
|
+
emit({ type: "status", status: "awaiting" });
|
|
250
|
+
await this.emitContext(conversation, emit);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
conversation.messages.push({ role: "user", content: results });
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
conversation.status = "idle";
|
|
258
|
+
conversation.leaseUntil = null;
|
|
259
|
+
emit({ type: "status", status: "idle" });
|
|
260
|
+
await this.emitContext(conversation, emit);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
private async invokeTool(
|
|
264
|
+
conversation: Conversation,
|
|
265
|
+
call: any,
|
|
266
|
+
emit: Emit,
|
|
267
|
+
toolBlockId: string,
|
|
268
|
+
): Promise<{ ret: ToolReturn; mode: "display" | "elicit" | null }> {
|
|
269
|
+
const tool = this.tools.get(call.name);
|
|
270
|
+
if (!tool) return { ret: { model: `Unknown tool: ${call.name}` }, mode: null };
|
|
271
|
+
|
|
272
|
+
let mode: "display" | "elicit" | null = null;
|
|
273
|
+
|
|
274
|
+
const ctx: ToolCtx = {
|
|
275
|
+
conversationId: conversation.id,
|
|
276
|
+
text: (model) => ({ model }),
|
|
277
|
+
render: (async (impl: AnySurfaceImpl, props: unknown, options?: { mode?: "display" | "elicit" }) => {
|
|
278
|
+
const surfaceMode = options?.mode ?? "display";
|
|
279
|
+
mode = surfaceMode;
|
|
280
|
+
|
|
281
|
+
// Validate before storing: props may originate outside this process.
|
|
282
|
+
const parsed = impl.surface.props.parse(props);
|
|
283
|
+
|
|
284
|
+
const handle = await this.config.store.putPayload({
|
|
285
|
+
conversationId: conversation.id,
|
|
286
|
+
component: impl.surface.name,
|
|
287
|
+
version: impl.surface.version,
|
|
288
|
+
props: parsed,
|
|
289
|
+
mode: surfaceMode,
|
|
290
|
+
state: "live",
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
conversation.handles.push(handle);
|
|
294
|
+
|
|
295
|
+
// The split, in two lines. Digest -> model. Payload -> browser.
|
|
296
|
+
const digest = impl.impl.digest(parsed, { handle });
|
|
297
|
+
emit({
|
|
298
|
+
type: "ui_open",
|
|
299
|
+
handle,
|
|
300
|
+
toolId: toolBlockId,
|
|
301
|
+
component: impl.surface.name,
|
|
302
|
+
version: impl.surface.version,
|
|
303
|
+
mode: surfaceMode,
|
|
304
|
+
});
|
|
305
|
+
emit({ type: "ui_props", handle, props: parsed });
|
|
306
|
+
|
|
307
|
+
return { model: digest, handle };
|
|
308
|
+
}) as ToolCtx["render"],
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
let input: unknown;
|
|
312
|
+
try {
|
|
313
|
+
input = tool.input.parse(call.input);
|
|
314
|
+
} catch (err) {
|
|
315
|
+
return { ret: { model: `Invalid input for ${call.name}: ${(err as Error).message}` }, mode: null };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
try {
|
|
319
|
+
const ret = await tool.run(input, ctx);
|
|
320
|
+
return { ret, mode };
|
|
321
|
+
} catch (err) {
|
|
322
|
+
return { ret: { model: `${call.name} failed: ${(err as Error).message}` }, mode: null };
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
private async emitContext(conversation: Conversation, emit: Emit) {
|
|
327
|
+
let uiTokens = 0;
|
|
328
|
+
for (const handle of conversation.handles) {
|
|
329
|
+
const record = await this.config.store.getPayload(handle, conversation.id);
|
|
330
|
+
if (record) uiTokens += estTokens(record.props);
|
|
331
|
+
}
|
|
332
|
+
emit({
|
|
333
|
+
type: "context",
|
|
334
|
+
messages: conversation.messages,
|
|
335
|
+
modelTokens: estTokens(conversation.messages),
|
|
336
|
+
uiTokens,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Find the array prop a surface's queries operate over (for cap totals). */
|
|
342
|
+
function primaryCollection(props: unknown): string {
|
|
343
|
+
if (props && typeof props === "object") {
|
|
344
|
+
for (const [key, value] of Object.entries(props as Record<string, unknown>)) {
|
|
345
|
+
if (Array.isArray(value)) return key;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return "";
|
|
349
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Conversation, PayloadRecord, StoreAdapter } from "@haikit/core";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* In-memory store. Implements the same interface a Postgres store would.
|
|
5
|
+
*
|
|
6
|
+
* Swapping this for a durable store is the single highest-value change for
|
|
7
|
+
* production: a parked `elicit` turn is durable state, and losing `pending`
|
|
8
|
+
* makes a conversation permanently unsendable.
|
|
9
|
+
*/
|
|
10
|
+
export function memoryStore(): StoreAdapter {
|
|
11
|
+
const conversations = new Map<string, Conversation>();
|
|
12
|
+
const payloads = new Map<string, PayloadRecord>();
|
|
13
|
+
let convSeq = 0;
|
|
14
|
+
let handleSeq = 0;
|
|
15
|
+
|
|
16
|
+
return {
|
|
17
|
+
async loadConversation(id) {
|
|
18
|
+
if (id && conversations.has(id)) return conversations.get(id)!;
|
|
19
|
+
const conversation: Conversation = {
|
|
20
|
+
id: `conv_${++convSeq}`,
|
|
21
|
+
status: "idle",
|
|
22
|
+
messages: [],
|
|
23
|
+
handles: [],
|
|
24
|
+
pending: null,
|
|
25
|
+
leaseUntil: null,
|
|
26
|
+
};
|
|
27
|
+
conversations.set(conversation.id, conversation);
|
|
28
|
+
return conversation;
|
|
29
|
+
},
|
|
30
|
+
|
|
31
|
+
async saveConversation(conversation) {
|
|
32
|
+
conversations.set(conversation.id, conversation);
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
async putPayload(record) {
|
|
36
|
+
const handle = `ui_${String(++handleSeq).padStart(2, "0")}`;
|
|
37
|
+
payloads.set(handle, { ...record, handle, createdAt: Date.now() });
|
|
38
|
+
return handle;
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
/** Scoped: a handle from another conversation must not resolve. */
|
|
42
|
+
async getPayload(handle, conversationId) {
|
|
43
|
+
const record = payloads.get(handle);
|
|
44
|
+
if (!record || record.conversationId !== conversationId) return null;
|
|
45
|
+
return record;
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
async freezePayload(handle) {
|
|
49
|
+
const record = payloads.get(handle);
|
|
50
|
+
if (record) record.state = "frozen";
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|