antinet 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,53 @@
1
+ import type { OpenAI } from "openai";
2
+ import * as routes from "./routes.ts";
3
+ import { type Timeouts } from "./transport.ts";
4
+ import type { Action, ActionOptions, Decision, Explanation, JsonObject, TypedDecision } from "./types.ts";
5
+ export interface ConnectOptions {
6
+ /** The service's socket or pipe; else `$ANET_SOCKET`, else the platform's default. */
7
+ socket?: string;
8
+ timeouts?: Partial<Timeouts>;
9
+ }
10
+ /**
11
+ * One connection to the local service.
12
+ *
13
+ * Without `login`, the service knows the caller by its operating-system
14
+ * account, which the site binds to a program. After `login`, every request
15
+ * through this client, the OpenAI client it hands out included, is the
16
+ * person's. Requests on one client take turns on its connection; open more
17
+ * clients for parallel calls.
18
+ */
19
+ export declare class Client {
20
+ #private;
21
+ readonly socket: string;
22
+ readonly timeouts: Timeouts;
23
+ constructor(options?: ConnectOptions);
24
+ /** The `fetch` over the socket or pipe, for other HTTP clients; it sends this client's credentials. */
25
+ get fetch(): typeof globalThis.fetch;
26
+ login(name: string, password: string): Promise<void>;
27
+ logout(): Promise<void>;
28
+ /** The official OpenAI client over this connection, retries off. */
29
+ openai(): OpenAI;
30
+ models(): Promise<JsonObject[]>;
31
+ loadModel(name: string): Promise<JsonObject>;
32
+ unloadModel(name: string): Promise<JsonObject>;
33
+ status(): Promise<JsonObject>;
34
+ tasks(): Promise<JsonObject[]>;
35
+ loadTask(task: string): Promise<JsonObject>;
36
+ unloadTask(task: string): Promise<JsonObject>;
37
+ decide(task: string, item: JsonObject): Promise<Decision>;
38
+ /** Waits until the explanation is written or has failed. */
39
+ explanation(task: string, decisionId: string): Promise<Explanation>;
40
+ /** A person's action on a decision: confirm, dismiss or reassign. */
41
+ act(task: string, decisionId: string, action: Action, options?: ActionOptions): Promise<void>;
42
+ records(range?: routes.RecordRange): Promise<JsonObject>;
43
+ typedModels(): Promise<JsonObject[]>;
44
+ loadTyped(name: string): Promise<JsonObject>;
45
+ unloadTyped(name: string): Promise<JsonObject>;
46
+ decideTyped(model: string, state: unknown, questions: Record<string, JsonObject>): Promise<TypedDecision>;
47
+ actTyped(model: string, decisionId: string, action: Action, options?: ActionOptions): Promise<void>;
48
+ /** Closes the connection, which ends a logged-in person's session. */
49
+ close(): Promise<void>;
50
+ [Symbol.asyncDispose](): Promise<void>;
51
+ }
52
+ /** A client of the local service at `socket`, else `$ANET_SOCKET`, else the platform's default socket or pipe. */
53
+ export declare function connect(options?: ConnectOptions): Client;
package/dist/client.js ADDED
@@ -0,0 +1,141 @@
1
+ /** `connect()` and the client (specs/0056, NODE-1 to NODE-5, NODE-7). */
2
+ import { createRequire } from "node:module";
3
+ import { AnetError } from "./errors.js";
4
+ import * as routes from "./routes.js";
5
+ import { BASE_URL, DEFAULT_TIMEOUTS, PLACEHOLDER_KEY, openConnection, resolveSocket, } from "./transport.js";
6
+ const require = createRequire(import.meta.url);
7
+ function openaiPackage() {
8
+ try {
9
+ return require("openai");
10
+ }
11
+ catch (error) {
12
+ throw new Error("client.openai() needs the openai package: npm install openai", { cause: error });
13
+ }
14
+ }
15
+ function describe(error) {
16
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : error;
17
+ return cause instanceof Error ? cause.message : String(cause);
18
+ }
19
+ /**
20
+ * One connection to the local service.
21
+ *
22
+ * Without `login`, the service knows the caller by its operating-system
23
+ * account, which the site binds to a program. After `login`, every request
24
+ * through this client, the OpenAI client it hands out included, is the
25
+ * person's. Requests on one client take turns on its connection; open more
26
+ * clients for parallel calls.
27
+ */
28
+ export class Client {
29
+ socket;
30
+ timeouts;
31
+ #credentials = { token: null };
32
+ #connection;
33
+ constructor(options = {}) {
34
+ this.socket = resolveSocket(options.socket);
35
+ this.timeouts = { ...DEFAULT_TIMEOUTS, ...options.timeouts };
36
+ this.#connection = openConnection(this.socket, this.#credentials, this.timeouts);
37
+ }
38
+ /** The `fetch` over the socket or pipe, for other HTTP clients; it sends this client's credentials. */
39
+ get fetch() {
40
+ return this.#connection.fetch;
41
+ }
42
+ async #send(call) {
43
+ const init = { method: call.method };
44
+ if (call.body !== null) {
45
+ init.headers = { "content-type": "application/json" };
46
+ init.body = JSON.stringify(call.body);
47
+ }
48
+ let response;
49
+ try {
50
+ response = await this.fetch(`${BASE_URL}${call.path}`, init);
51
+ }
52
+ catch (error) {
53
+ throw new AnetError(null, null, `could not reach the service at ${this.socket}: ${describe(error)}`, {
54
+ cause: error,
55
+ });
56
+ }
57
+ return routes.answer(call, response);
58
+ }
59
+ async login(name, password) {
60
+ this.#credentials.token = await this.#send(routes.login(name, password));
61
+ }
62
+ async logout() {
63
+ await this.#send(routes.logout());
64
+ this.#credentials.token = null;
65
+ }
66
+ /** The official OpenAI client over this connection, retries off. */
67
+ openai() {
68
+ const { OpenAI } = openaiPackage();
69
+ return new OpenAI({
70
+ baseURL: `${BASE_URL}/v1`,
71
+ apiKey: PLACEHOLDER_KEY,
72
+ adminAPIKey: null,
73
+ organization: null,
74
+ project: null,
75
+ fetch: this.fetch,
76
+ maxRetries: 0,
77
+ timeout: this.timeouts.requestMs,
78
+ });
79
+ }
80
+ models() {
81
+ return this.#send(routes.models());
82
+ }
83
+ loadModel(name) {
84
+ return this.#send(routes.loadModel(name));
85
+ }
86
+ unloadModel(name) {
87
+ return this.#send(routes.unloadModel(name));
88
+ }
89
+ status() {
90
+ return this.#send(routes.status());
91
+ }
92
+ tasks() {
93
+ return this.#send(routes.tasks());
94
+ }
95
+ loadTask(task) {
96
+ return this.#send(routes.loadTask(task));
97
+ }
98
+ unloadTask(task) {
99
+ return this.#send(routes.unloadTask(task));
100
+ }
101
+ decide(task, item) {
102
+ return this.#send(routes.decide(task, item));
103
+ }
104
+ /** Waits until the explanation is written or has failed. */
105
+ explanation(task, decisionId) {
106
+ return this.#send(routes.explanation(task, decisionId));
107
+ }
108
+ /** A person's action on a decision: confirm, dismiss or reassign. */
109
+ async act(task, decisionId, action, options) {
110
+ await this.#send(routes.act(task, decisionId, action, options));
111
+ }
112
+ records(range) {
113
+ return this.#send(routes.records(range));
114
+ }
115
+ typedModels() {
116
+ return this.#send(routes.typedModels());
117
+ }
118
+ loadTyped(name) {
119
+ return this.#send(routes.loadTyped(name));
120
+ }
121
+ unloadTyped(name) {
122
+ return this.#send(routes.unloadTyped(name));
123
+ }
124
+ decideTyped(model, state, questions) {
125
+ return this.#send(routes.decideTyped(model, state, questions));
126
+ }
127
+ async actTyped(model, decisionId, action, options) {
128
+ await this.#send(routes.actTyped(model, decisionId, action, options));
129
+ }
130
+ /** Closes the connection, which ends a logged-in person's session. */
131
+ async close() {
132
+ await this.#connection.agent.close();
133
+ }
134
+ async [Symbol.asyncDispose]() {
135
+ await this.close();
136
+ }
137
+ }
138
+ /** A client of the local service at `socket`, else `$ANET_SOCKET`, else the platform's default socket or pipe. */
139
+ export function connect(options = {}) {
140
+ return new Client(options);
141
+ }
@@ -0,0 +1,19 @@
1
+ /** The one error the SDK raises (specs/0056, NODE-7). */
2
+ export declare class AnetError extends Error {
3
+ name: string;
4
+ /** The HTTP status, or `null` when no answer came. */
5
+ readonly status: number | null;
6
+ /** The service's own code for the refusal, such as `unbound_peer` or `MODEL_NOT_LOADED`. */
7
+ readonly code: string | null;
8
+ constructor(status: number | null, code: string | null, message: string, options?: ErrorOptions);
9
+ }
10
+ /**
11
+ * Reads whichever of the service's error shapes the route answered with:
12
+ * - OpenAI family: `{"error": {"message", "type": <service code>, "code": <status>}}`
13
+ * - Responses: `{"error": {"message", "type", "param", "code": <service code>}}`
14
+ * - Messages: `{"type": "error", "error": {"type", "message", "code": <service code>}}`
15
+ * - typed decisions: `{"error": <message>, "code": <CODE>}`
16
+ */
17
+ export declare function errorFromBody(status: number, statusText: string, text: string): AnetError;
18
+ export declare function errorFromResponse(response: Response): Promise<AnetError>;
19
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
package/dist/errors.js ADDED
@@ -0,0 +1,50 @@
1
+ /** The one error the SDK raises (specs/0056, NODE-7). */
2
+ export class AnetError extends Error {
3
+ name = "AnetError";
4
+ /** The HTTP status, or `null` when no answer came. */
5
+ status;
6
+ /** The service's own code for the refusal, such as `unbound_peer` or `MODEL_NOT_LOADED`. */
7
+ code;
8
+ constructor(status, code, message, options) {
9
+ super(message, options);
10
+ this.status = status;
11
+ this.code = code;
12
+ }
13
+ }
14
+ /**
15
+ * Reads whichever of the service's error shapes the route answered with:
16
+ * - OpenAI family: `{"error": {"message", "type": <service code>, "code": <status>}}`
17
+ * - Responses: `{"error": {"message", "type", "param", "code": <service code>}}`
18
+ * - Messages: `{"type": "error", "error": {"type", "message", "code": <service code>}}`
19
+ * - typed decisions: `{"error": <message>, "code": <CODE>}`
20
+ */
21
+ export function errorFromBody(status, statusText, text) {
22
+ let body;
23
+ try {
24
+ body = JSON.parse(text);
25
+ }
26
+ catch {
27
+ return new AnetError(status, null, text || statusText);
28
+ }
29
+ const error = isObject(body) ? body["error"] : undefined;
30
+ if (typeof error === "string") {
31
+ const code = isObject(body) ? body["code"] : undefined;
32
+ return new AnetError(status, typeof code === "string" ? code : null, error);
33
+ }
34
+ if (isObject(error)) {
35
+ const message = typeof error["message"] === "string" ? error["message"] : statusText;
36
+ const serviceCode = error["code"];
37
+ if (typeof serviceCode === "string") {
38
+ return new AnetError(status, serviceCode, message);
39
+ }
40
+ const kind = error["type"];
41
+ return new AnetError(status, typeof kind === "string" ? kind : null, message);
42
+ }
43
+ return new AnetError(status, null, text);
44
+ }
45
+ export async function errorFromResponse(response) {
46
+ return errorFromBody(response.status, response.statusText, await response.text());
47
+ }
48
+ export function isObject(value) {
49
+ return typeof value === "object" && value !== null && !Array.isArray(value);
50
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The local Antinet service from Node (specs/0056).
3
+ *
4
+ * ```ts
5
+ * import { connect } from "antinet";
6
+ * const client = connect();
7
+ * const reply = await client.openai().chat.completions.create({ model: "qwen3", messages });
8
+ * const decision = await client.decide("inspection", item);
9
+ * ```
10
+ */
11
+ export { Client, type ConnectOptions, connect } from "./client.ts";
12
+ export { AnetError } from "./errors.ts";
13
+ export type { RecordRange } from "./routes.ts";
14
+ export type { Timeouts } from "./transport.ts";
15
+ export { type Action, type ActionOptions, type Decision, type Explanation, type JsonObject, type QuestionType, type TypedAnswer, type TypedDecision, choice, score, yesOrNo, } from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The local Antinet service from Node (specs/0056).
3
+ *
4
+ * ```ts
5
+ * import { connect } from "antinet";
6
+ * const client = connect();
7
+ * const reply = await client.openai().chat.completions.create({ model: "qwen3", messages });
8
+ * const decision = await client.decide("inspection", item);
9
+ * ```
10
+ */
11
+ export { Client, connect } from "./client.js";
12
+ export { AnetError } from "./errors.js";
13
+ export { choice, score, yesOrNo, } from "./types.js";
@@ -0,0 +1,34 @@
1
+ /**
2
+ * LangChain.js chat and embedding models over the local service (specs/0056,
3
+ * NODE-9).
4
+ *
5
+ * Both are `@langchain/openai`'s classes pointed at the service's
6
+ * OpenAI-compatible routes through an `anet` client's connection, so tool
7
+ * binding, structured output and streaming are LangChain's own code:
8
+ *
9
+ * ```ts
10
+ * import { ChatAnet, AnetEmbeddings } from "antinet/langchain";
11
+ * const chat = new ChatAnet({ model: "qwen3" });
12
+ * const vectors = await new AnetEmbeddings({ model: "bge-small" }).embedDocuments(["pump", "valve"]);
13
+ * ```
14
+ *
15
+ * Without `client`, each model opens one program connection of its own.
16
+ */
17
+ import { type ChatOpenAIFields, ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
18
+ import { Client } from "./client.ts";
19
+ export interface AnetFields {
20
+ /** An `anet` client, logged in or not; its connection carries the model's requests. */
21
+ client?: Client;
22
+ /** The socket or pipe for a connection of the model's own, when no client is given. */
23
+ socket?: string;
24
+ }
25
+ type EmbeddingsFields = NonNullable<ConstructorParameters<typeof OpenAIEmbeddings>[0]>;
26
+ /** A chat model of the local service, as a LangChain.js chat model. */
27
+ export declare class ChatAnet extends ChatOpenAI {
28
+ constructor(fields: ChatOpenAIFields & AnetFields);
29
+ }
30
+ /** An embedding model of the local service; texts are sent as text. */
31
+ export declare class AnetEmbeddings extends OpenAIEmbeddings {
32
+ constructor(fields: EmbeddingsFields & AnetFields);
33
+ }
34
+ export {};
@@ -0,0 +1,51 @@
1
+ /**
2
+ * LangChain.js chat and embedding models over the local service (specs/0056,
3
+ * NODE-9).
4
+ *
5
+ * Both are `@langchain/openai`'s classes pointed at the service's
6
+ * OpenAI-compatible routes through an `anet` client's connection, so tool
7
+ * binding, structured output and streaming are LangChain's own code:
8
+ *
9
+ * ```ts
10
+ * import { ChatAnet, AnetEmbeddings } from "antinet/langchain";
11
+ * const chat = new ChatAnet({ model: "qwen3" });
12
+ * const vectors = await new AnetEmbeddings({ model: "bge-small" }).embedDocuments(["pump", "valve"]);
13
+ * ```
14
+ *
15
+ * Without `client`, each model opens one program connection of its own.
16
+ */
17
+ import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
18
+ import { Client } from "./client.js";
19
+ import { BASE_URL, PLACEHOLDER_KEY } from "./transport.js";
20
+ function overTheService(fields) {
21
+ const { client: given, socket, ...rest } = fields;
22
+ const client = given ?? new Client(socket === undefined ? {} : { socket });
23
+ for (const taken of ["apiKey", "openAIApiKey"]) {
24
+ if (rest[taken] !== undefined) {
25
+ throw new TypeError(`${taken} is set by the anet client; give client or socket instead`);
26
+ }
27
+ }
28
+ for (const taken of ["baseURL", "apiKey", "fetch"]) {
29
+ if (rest.configuration?.[taken] !== undefined) {
30
+ throw new TypeError(`configuration.${taken} is set by the anet client; give client or socket instead`);
31
+ }
32
+ }
33
+ return {
34
+ ...rest,
35
+ apiKey: PLACEHOLDER_KEY,
36
+ maxRetries: rest.maxRetries ?? 0,
37
+ configuration: { ...rest.configuration, baseURL: `${BASE_URL}/v1`, fetch: client.fetch },
38
+ };
39
+ }
40
+ /** A chat model of the local service, as a LangChain.js chat model. */
41
+ export class ChatAnet extends ChatOpenAI {
42
+ constructor(fields) {
43
+ super(overTheService(fields));
44
+ }
45
+ }
46
+ /** An embedding model of the local service; texts are sent as text. */
47
+ export class AnetEmbeddings extends OpenAIEmbeddings {
48
+ constructor(fields) {
49
+ super(overTheService(fields));
50
+ }
51
+ }
@@ -0,0 +1,31 @@
1
+ import { type Action, type ActionOptions, type Decision, type Explanation, type JsonObject, type TypedDecision } from "./types.ts";
2
+ export interface Call<T> {
3
+ readonly method: "GET" | "POST";
4
+ readonly path: string;
5
+ readonly body: JsonObject | null;
6
+ readonly read: (body: unknown) => T;
7
+ }
8
+ /** Reads the answer to a call, consuming its body so the one connection is free for the next request. */
9
+ export declare function answer<T>(call: Call<T>, response: Response): Promise<T>;
10
+ export declare const login: (name: string, password: string) => Call<string>;
11
+ export declare const logout: () => Call<void>;
12
+ export declare const models: () => Call<JsonObject[]>;
13
+ export declare const loadModel: (name: string) => Call<JsonObject>;
14
+ export declare const unloadModel: (name: string) => Call<JsonObject>;
15
+ export declare const status: () => Call<JsonObject>;
16
+ export declare const tasks: () => Call<JsonObject[]>;
17
+ export declare const loadTask: (task: string) => Call<JsonObject>;
18
+ export declare const unloadTask: (task: string) => Call<JsonObject>;
19
+ export declare const decide: (task: string, item: JsonObject) => Call<Decision>;
20
+ export declare const explanation: (task: string, decisionId: string) => Call<Explanation>;
21
+ export declare const act: (task: string, decisionId: string, action: Action, options?: ActionOptions) => Call<void>;
22
+ export interface RecordRange {
23
+ fromSeq?: number;
24
+ toSeq?: number;
25
+ }
26
+ export declare function records(range?: RecordRange): Call<JsonObject>;
27
+ export declare const typedModels: () => Call<JsonObject[]>;
28
+ export declare const loadTyped: (name: string) => Call<JsonObject>;
29
+ export declare const unloadTyped: (name: string) => Call<JsonObject>;
30
+ export declare const decideTyped: (model: string, state: unknown, questions: Record<string, JsonObject>) => Call<TypedDecision>;
31
+ export declare const actTyped: (model: string, decisionId: string, action: Action, options?: ActionOptions) => Call<void>;
package/dist/routes.js ADDED
@@ -0,0 +1,72 @@
1
+ /** Every route the SDK calls, once (specs/0056, Design). */
2
+ import { errorFromResponse, isObject } from "./errors.js";
3
+ import { actionBody, readDecision, readExplanation, readTypedDecision, } from "./types.js";
4
+ /** Reads the answer to a call, consuming its body so the one connection is free for the next request. */
5
+ export async function answer(call, response) {
6
+ if (!response.ok) {
7
+ throw await errorFromResponse(response);
8
+ }
9
+ if (response.status === 204) {
10
+ await response.body?.cancel();
11
+ return call.read(null);
12
+ }
13
+ return call.read(await response.json());
14
+ }
15
+ function segment(name) {
16
+ return encodeURIComponent(name);
17
+ }
18
+ function json(body) {
19
+ if (!isObject(body)) {
20
+ throw new TypeError("the service answered something that is not an object");
21
+ }
22
+ return body;
23
+ }
24
+ function nothing() { }
25
+ function listed(body) {
26
+ const data = json(body)["data"];
27
+ if (!Array.isArray(data) || !data.every(isObject)) {
28
+ throw new TypeError("the service answered a list without its data");
29
+ }
30
+ return data;
31
+ }
32
+ function token(body) {
33
+ const value = json(body)["token"];
34
+ if (typeof value !== "string") {
35
+ throw new TypeError("the service answered a login without its token");
36
+ }
37
+ return value;
38
+ }
39
+ const call = (method, path, body, read) => ({
40
+ method,
41
+ path,
42
+ body,
43
+ read,
44
+ });
45
+ export const login = (name, password) => call("POST", "/v1/login", { name, password }, token);
46
+ export const logout = () => call("POST", "/v1/logout", null, nothing);
47
+ export const models = () => call("GET", "/v1/models", null, listed);
48
+ export const loadModel = (name) => call("POST", "/v1/models/load", { model: name }, json);
49
+ export const unloadModel = (name) => call("POST", "/v1/models/unload", { model: name }, json);
50
+ export const status = () => call("GET", "/v1/status", null, json);
51
+ export const tasks = () => call("GET", "/v1/tasks", null, listed);
52
+ export const loadTask = (task) => call("POST", `/v1/tasks/${segment(task)}/load`, null, json);
53
+ export const unloadTask = (task) => call("POST", `/v1/tasks/${segment(task)}/unload`, null, json);
54
+ export const decide = (task, item) => call("POST", `/v1/tasks/${segment(task)}/decisions`, { case: item }, readDecision);
55
+ export const explanation = (task, decisionId) => call("GET", `/v1/tasks/${segment(task)}/decisions/${segment(decisionId)}/explanation`, null, readExplanation);
56
+ export const act = (task, decisionId, action, options) => call("POST", `/v1/tasks/${segment(task)}/decisions/${segment(decisionId)}/actions`, actionBody(action, options), nothing);
57
+ export function records(range = {}) {
58
+ const query = new URLSearchParams();
59
+ if (range.fromSeq !== undefined) {
60
+ query.set("from_seq", String(range.fromSeq));
61
+ }
62
+ if (range.toSeq !== undefined) {
63
+ query.set("to_seq", String(range.toSeq));
64
+ }
65
+ const suffix = query.size > 0 ? `?${query}` : "";
66
+ return call("GET", `/v1/records${suffix}`, null, json);
67
+ }
68
+ export const typedModels = () => call("GET", "/v1/typed/models", null, listed);
69
+ export const loadTyped = (name) => call("POST", `/v1/typed/models/${segment(name)}/load`, null, json);
70
+ export const unloadTyped = (name) => call("POST", `/v1/typed/models/${segment(name)}/unload`, null, json);
71
+ export const decideTyped = (model, state, questions) => call("POST", "/v1/typed/decide", { model, state, questions }, readTypedDecision);
72
+ export const actTyped = (model, decisionId, action, options) => call("POST", `/v1/typed/decisions/${segment(decisionId)}/actions`, { model, ...actionBody(action, options) }, nothing);
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The socket or named pipe under `fetch` (specs/0056, NODE-1, NODE-2, NODE-10).
3
+ *
4
+ * Each client holds one connection that the client never closes for being
5
+ * idle, because the service binds a person's session to the connection that
6
+ * logged in. The fetch also owns the credentials: it strips whatever
7
+ * `authorization` or `x-api-key` a caller such as the OpenAI client adds, and
8
+ * sends the logged-in person's token, or nothing, so the service knows a
9
+ * program by its account.
10
+ */
11
+ import { Agent, Headers } from "undici";
12
+ export declare const UNIX_SOCKET = "/var/run/anet/anet.sock";
13
+ export declare const WINDOWS_PIPE = "\\\\.\\pipe\\anet";
14
+ export declare const BASE_URL = "http://anet";
15
+ export declare const PLACEHOLDER_KEY = "anet";
16
+ export interface Timeouts {
17
+ /** How long a request may wait for its answer and for each part of its body. */
18
+ requestMs: number;
19
+ /** How long opening the socket or pipe may take. */
20
+ connectMs: number;
21
+ }
22
+ /** Generation and blocking explanations can take minutes on the CPU floor; connecting never should. */
23
+ export declare const DEFAULT_TIMEOUTS: Timeouts;
24
+ /** `socket`, else `$ANET_SOCKET`, else the platform's default. */
25
+ export declare function resolveSocket(socket?: string): string;
26
+ /** The token of the person logged in on this client's connection. */
27
+ export interface Credentials {
28
+ token: string | null;
29
+ }
30
+ export declare function authorise(headers: Headers, credentials: Credentials): void;
31
+ /** A connection of one client: its `fetch`, and the agent that holds the one socket. */
32
+ export interface Connection {
33
+ fetch: typeof globalThis.fetch;
34
+ agent: Agent;
35
+ }
36
+ export declare function openConnection(socket: string, credentials: Credentials, timeouts: Timeouts): Connection;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The socket or named pipe under `fetch` (specs/0056, NODE-1, NODE-2, NODE-10).
3
+ *
4
+ * Each client holds one connection that the client never closes for being
5
+ * idle, because the service binds a person's session to the connection that
6
+ * logged in. The fetch also owns the credentials: it strips whatever
7
+ * `authorization` or `x-api-key` a caller such as the OpenAI client adds, and
8
+ * sends the logged-in person's token, or nothing, so the service knows a
9
+ * program by its account.
10
+ */
11
+ import { Agent, Headers, fetch as undiciFetch } from "undici";
12
+ export const UNIX_SOCKET = "/var/run/anet/anet.sock";
13
+ export const WINDOWS_PIPE = "\\\\.\\pipe\\anet";
14
+ export const BASE_URL = "http://anet";
15
+ // The OpenAI client refuses to start without a key; this one never leaves
16
+ // the process, because the fetch removes it from every request.
17
+ export const PLACEHOLDER_KEY = "anet";
18
+ // undici refuses an infinite keep-alive, and a Node timer longer than
19
+ // 2^31 - 1 ms overflows and fires at once.
20
+ const LONGEST_TIMER_MS = 2_147_483_647;
21
+ /** Generation and blocking explanations can take minutes on the CPU floor; connecting never should. */
22
+ export const DEFAULT_TIMEOUTS = { requestMs: 600_000, connectMs: 10_000 };
23
+ /** `socket`, else `$ANET_SOCKET`, else the platform's default. */
24
+ export function resolveSocket(socket) {
25
+ if (socket) {
26
+ return socket;
27
+ }
28
+ const fromEnvironment = process.env["ANET_SOCKET"];
29
+ if (fromEnvironment) {
30
+ return fromEnvironment;
31
+ }
32
+ return process.platform === "win32" ? WINDOWS_PIPE : UNIX_SOCKET;
33
+ }
34
+ export function authorise(headers, credentials) {
35
+ headers.delete("authorization");
36
+ headers.delete("x-api-key");
37
+ if (credentials.token !== null) {
38
+ headers.set("authorization", `Bearer ${credentials.token}`);
39
+ }
40
+ }
41
+ export function openConnection(socket, credentials, timeouts) {
42
+ const agent = new Agent({
43
+ socketPath: socket,
44
+ connections: 1,
45
+ connectTimeout: timeouts.connectMs,
46
+ headersTimeout: timeouts.requestMs,
47
+ bodyTimeout: timeouts.requestMs,
48
+ keepAliveTimeout: LONGEST_TIMER_MS,
49
+ keepAliveMaxTimeout: LONGEST_TIMER_MS,
50
+ });
51
+ const fetch = async (input, init) => {
52
+ if (typeof input !== "string" && !(input instanceof URL)) {
53
+ // A Request carries headers of its own that would pass the credential check unseen.
54
+ throw new TypeError("the anet fetch takes a URL and its options, not a Request");
55
+ }
56
+ const headers = new Headers(init?.headers);
57
+ authorise(headers, credentials);
58
+ const options = { ...init, headers, dispatcher: agent };
59
+ // undici's Response is the same implementation as Node's own; only their
60
+ // type declarations differ.
61
+ return (await undiciFetch(input, options));
62
+ };
63
+ return { fetch, agent };
64
+ }
@@ -0,0 +1,73 @@
1
+ export type JsonObject = Record<string, unknown>;
2
+ export declare const ACTIONS: readonly ["confirm", "dismiss", "reassign"];
3
+ export type Action = (typeof ACTIONS)[number];
4
+ /** A decision model's answer to one case of a task. */
5
+ export interface Decision {
6
+ readonly id: string;
7
+ readonly task: string;
8
+ readonly time: string;
9
+ readonly label: string;
10
+ readonly attributes: JsonObject | null;
11
+ readonly assignee: string | null;
12
+ readonly confidence: number;
13
+ readonly threshold: number;
14
+ /** True when the confidence was below the threshold, so the case goes to a person with an explanation; false when the answer is advice. */
15
+ readonly toPerson: boolean;
16
+ readonly modelDigest: string;
17
+ readonly modelVersion: number;
18
+ readonly runtimeDigest: string;
19
+ }
20
+ /** The local language model's explanation of a decision sent to a person: written with its text, or failed with the error. */
21
+ export interface Explanation {
22
+ readonly id: string;
23
+ readonly written: boolean;
24
+ readonly text: string | null;
25
+ readonly error: string | null;
26
+ }
27
+ export type QuestionType = "choice" | "score" | "noul";
28
+ /**
29
+ * One question's answer: the chosen label of a `choice`, the level of a
30
+ * `score` as a number, or for a yes-or-no (`noul`) how true the statement
31
+ * is, from 0 to 1.
32
+ */
33
+ export interface TypedAnswer {
34
+ readonly question: string;
35
+ readonly type: QuestionType;
36
+ readonly value: string | number;
37
+ readonly confidence: number | null;
38
+ readonly probabilities: Readonly<Record<string, number>> | null;
39
+ readonly legend: unknown;
40
+ readonly decisionId: string;
41
+ }
42
+ /** A typed model's answers to the questions of one request. */
43
+ export interface TypedDecision {
44
+ readonly model: string;
45
+ readonly answers: Readonly<Record<string, TypedAnswer>>;
46
+ readonly stateTruncated: boolean;
47
+ readonly inputTokens: number;
48
+ }
49
+ export declare function readDecision(value: unknown): Decision;
50
+ export declare function readExplanation(value: unknown): Explanation;
51
+ export declare function readTypedDecision(value: unknown): TypedDecision;
52
+ export interface ActionOptions {
53
+ /** Who takes the case; required for `reassign` and refused otherwise. */
54
+ assignee?: string;
55
+ comment?: string;
56
+ }
57
+ /** An operator's action, checked before anything is sent (NODE-8). */
58
+ export declare function actionBody(action: Action, options?: ActionOptions): JsonObject;
59
+ /** A question answered by one of the named options, each with an optional description (`{ refund: "Wants money back" }`). */
60
+ export declare function choice(criteria: Record<string, string> | string[], options?: {
61
+ instructions?: string;
62
+ ordinal?: boolean;
63
+ }): JsonObject;
64
+ /** A question answered by a level, lowest first (`["calm", "angry"]`). */
65
+ export declare function score(levels: string[], options?: {
66
+ instructions?: string;
67
+ }): JsonObject;
68
+ /** A yes-or-no question, answered with how true it is, from 0 to 1; `true` and `false` optionally describe the two ends. */
69
+ export declare function yesOrNo(options?: {
70
+ instructions?: string;
71
+ true?: string;
72
+ false?: string;
73
+ }): JsonObject;
package/dist/types.js ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * What the decision loop and typed decisions answer (specs/0056, NODE-6),
3
+ * read strictly from the service's JSON: a field the service always sends is
4
+ * required, and one it may leave out is `null` when it does.
5
+ */
6
+ import { isObject } from "./errors.js";
7
+ export const ACTIONS = ["confirm", "dismiss", "reassign"];
8
+ function object(value, where) {
9
+ if (!isObject(value)) {
10
+ throw new TypeError(`the service answered ${where} that is not an object`);
11
+ }
12
+ return value;
13
+ }
14
+ function text(body, field) {
15
+ const value = body[field];
16
+ if (typeof value !== "string") {
17
+ throw new TypeError(`the service answered without the text field ${field}`);
18
+ }
19
+ return value;
20
+ }
21
+ function number(body, field) {
22
+ const value = body[field];
23
+ if (typeof value !== "number") {
24
+ throw new TypeError(`the service answered without the number field ${field}`);
25
+ }
26
+ return value;
27
+ }
28
+ function flag(body, field) {
29
+ const value = body[field];
30
+ if (typeof value !== "boolean") {
31
+ throw new TypeError(`the service answered without the true-or-false field ${field}`);
32
+ }
33
+ return value;
34
+ }
35
+ function optional(body, field, read) {
36
+ return body[field] === undefined || body[field] === null ? null : read(body, field);
37
+ }
38
+ function probabilities(body, field) {
39
+ const map = object(body[field], field);
40
+ for (const [key, value] of Object.entries(map)) {
41
+ if (typeof value !== "number") {
42
+ throw new TypeError(`the service answered a probability for ${key} that is not a number`);
43
+ }
44
+ }
45
+ return map;
46
+ }
47
+ export function readDecision(value) {
48
+ const body = object(value, "a decision");
49
+ const answer = object(body["answer"], "a decision answer");
50
+ const model = object(body["model"], "a decision model");
51
+ const route = text(body, "route");
52
+ if (route !== "advice" && route !== "to_person") {
53
+ throw new TypeError(`the service answered an unknown route ${route}`);
54
+ }
55
+ return {
56
+ id: text(body, "id"),
57
+ task: text(body, "task"),
58
+ time: text(body, "time"),
59
+ label: text(answer, "label"),
60
+ attributes: optional(answer, "attributes", (from, field) => object(from[field], field)),
61
+ assignee: optional(answer, "assignee", text),
62
+ confidence: number(body, "confidence"),
63
+ threshold: number(body, "threshold"),
64
+ toPerson: route === "to_person",
65
+ modelDigest: text(model, "digest"),
66
+ modelVersion: number(model, "version"),
67
+ runtimeDigest: text(body, "runtime_digest"),
68
+ };
69
+ }
70
+ export function readExplanation(value) {
71
+ const body = object(value, "an explanation");
72
+ const outcome = text(body, "outcome");
73
+ if (outcome === "written") {
74
+ return { id: text(body, "id"), written: true, text: text(body, "text"), error: null };
75
+ }
76
+ if (outcome === "failed") {
77
+ return { id: text(body, "id"), written: false, text: null, error: text(body, "error") };
78
+ }
79
+ throw new TypeError(`the service answered an unknown outcome ${outcome}`);
80
+ }
81
+ function readTypedAnswer(question, value, decisionId) {
82
+ const body = object(value, `the answer to ${question}`);
83
+ const type = text(body, "type");
84
+ let answer;
85
+ if (type === "choice") {
86
+ answer = text(body, "choice");
87
+ }
88
+ else if (type === "score" || type === "noul") {
89
+ answer = number(body, type);
90
+ }
91
+ else {
92
+ throw new TypeError(`the service answered an unknown question type ${type}`);
93
+ }
94
+ return {
95
+ question,
96
+ type,
97
+ value: answer,
98
+ confidence: optional(body, "confidence", number),
99
+ probabilities: optional(body, "probabilities", probabilities),
100
+ legend: body["legend"] ?? null,
101
+ decisionId,
102
+ };
103
+ }
104
+ export function readTypedDecision(value) {
105
+ const body = object(value, "a typed decision");
106
+ const decisions = object(body["decisions"], "the decision ids");
107
+ const answers = {};
108
+ for (const [question, answer] of Object.entries(object(body["answers"], "the answers"))) {
109
+ answers[question] = readTypedAnswer(question, answer, text(decisions, question));
110
+ }
111
+ return {
112
+ model: text(body, "model"),
113
+ answers,
114
+ stateTruncated: flag(body, "state_truncated"),
115
+ inputTokens: number(object(body["usage"], "the usage"), "input_tokens"),
116
+ };
117
+ }
118
+ /** An operator's action, checked before anything is sent (NODE-8). */
119
+ export function actionBody(action, options = {}) {
120
+ if (!ACTIONS.includes(action)) {
121
+ throw new TypeError(`action must be one of ${ACTIONS.join(", ")}, not ${String(action)}`);
122
+ }
123
+ if (action === "reassign" && !options.assignee) {
124
+ throw new TypeError("reassign needs the assignee who takes the case");
125
+ }
126
+ if (action !== "reassign" && options.assignee !== undefined) {
127
+ throw new TypeError(`${action} takes no assignee; only reassign does`);
128
+ }
129
+ const body = { action };
130
+ if (options.assignee !== undefined) {
131
+ body["assignee"] = options.assignee;
132
+ }
133
+ if (options.comment !== undefined) {
134
+ body["comment"] = options.comment;
135
+ }
136
+ return body;
137
+ }
138
+ /** A question answered by one of the named options, each with an optional description (`{ refund: "Wants money back" }`). */
139
+ export function choice(criteria, options = {}) {
140
+ return { type: "choice", criteria, ...options };
141
+ }
142
+ /** A question answered by a level, lowest first (`["calm", "angry"]`). */
143
+ export function score(levels, options = {}) {
144
+ return { type: "score", criteria: levels, ...options };
145
+ }
146
+ /** A yes-or-no question, answered with how true it is, from 0 to 1; `true` and `false` optionally describe the two ends. */
147
+ export function yesOrNo(options = {}) {
148
+ if ((options.true === undefined) !== (options.false === undefined)) {
149
+ throw new TypeError("describe both answers, true and false, or neither");
150
+ }
151
+ const question = { type: "noul" };
152
+ if (options.instructions !== undefined) {
153
+ question["instructions"] = options.instructions;
154
+ }
155
+ if (options.true !== undefined) {
156
+ question["criteria"] = { true: options.true, false: options.false };
157
+ }
158
+ return question;
159
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "antinet",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "The local Antinet service from Node: the OpenAI client and LangChain.js over its socket or pipe, the decision loop and typed decisions",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22.19.0"
8
+ },
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./langchain": {
15
+ "types": "./dist/langchain.d.ts",
16
+ "default": "./dist/langchain.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.build.json",
24
+ "prepack": "npm run build",
25
+ "check": "tsc -p tsconfig.json",
26
+ "test:unit": "node --test test/unit.test.ts"
27
+ },
28
+ "dependencies": {
29
+ "undici": "^8.12.4"
30
+ },
31
+ "peerDependencies": {
32
+ "@langchain/core": "^1.4.1",
33
+ "@langchain/openai": "^1.8.4",
34
+ "openai": "^7.57.0"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "@langchain/core": {
38
+ "optional": true
39
+ },
40
+ "@langchain/openai": {
41
+ "optional": true
42
+ },
43
+ "openai": {
44
+ "optional": true
45
+ }
46
+ },
47
+ "devDependencies": {
48
+ "@langchain/core": "1.4.1",
49
+ "@langchain/openai": "1.8.4",
50
+ "@types/node": "22.20.5",
51
+ "openai": "7.57.0",
52
+ "typescript": "7.0.2"
53
+ }
54
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.