@yaks/anthropic 0.0.0-stage → 0.2.36
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 +202 -0
- package/README.md +114 -2
- package/_dist/batches.d.ts +77 -0
- package/_dist/batches.d.ts.map +1 -0
- package/_dist/mark.d.ts +6 -0
- package/_dist/mark.d.ts.map +1 -0
- package/_dist/mod.d.ts +63 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/provider.d.ts +8 -0
- package/_dist/provider.d.ts.map +1 -0
- package/_dist/reads.d.ts +2 -0
- package/_dist/reads.d.ts.map +1 -0
- package/_dist/vocab.d.ts +6 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/_dist/wire.d.ts +94 -0
- package/_dist/wire.d.ts.map +1 -0
- package/batches.js +110 -0
- package/batches.js.map +1 -0
- package/batches.ts +136 -0
- package/deno.json +1 -0
- package/mark.js +16 -0
- package/mark.js.map +1 -0
- package/mark.ts +18 -0
- package/mod.js +546 -0
- package/mod.js.map +1 -0
- package/mod.ts +523 -0
- package/package.json +38 -4
- package/provider.js +37 -0
- package/provider.js.map +1 -0
- package/provider.ts +58 -0
- package/reads.js +18 -0
- package/reads.js.map +1 -0
- package/reads.ts +19 -0
- package/vocab.js +16 -0
- package/vocab.js.map +1 -0
- package/vocab.json +24 -0
- package/vocab.ts +17 -0
- package/web.js +48 -0
- package/web.js.map +1 -0
- package/web.ts +44 -0
- package/wire.js +136 -0
- package/wire.js.map +1 -0
- package/wire.ts +266 -0
package/reads.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// What Claude reads as it is, beside text, importable without the model
|
|
2
|
+
// (./mod.ts): a host that loads the model lazily still knows what to hand it.
|
|
3
|
+
|
|
4
|
+
// https://platform.claude.com/docs/en/build-with-claude/vision
|
|
5
|
+
// https://platform.claude.com/docs/en/build-with-claude/pdf-support
|
|
6
|
+
// https://platform.claude.com/docs/en/build-with-claude/files
|
|
7
|
+
// First-party API: images are at most 10 MB base64; whole requests 128 MB.
|
|
8
|
+
// PDFs also have a request-wide page cap: 600, or 100 below 1M context tokens.
|
|
9
|
+
// Plain text is the only other native document type; office formats require
|
|
10
|
+
// conversion or code execution and are not document inputs.
|
|
11
|
+
/** Native MIME types and raw-byte ceilings, before other request content. */
|
|
12
|
+
export let READS: Record<string, number> = {
|
|
13
|
+
'image/png': 7.5 * 1024 * 1024,
|
|
14
|
+
'image/jpeg': 7.5 * 1024 * 1024,
|
|
15
|
+
'image/gif': 7.5 * 1024 * 1024,
|
|
16
|
+
'image/webp': 7.5 * 1024 * 1024,
|
|
17
|
+
'application/pdf': 96 * 1024 * 1024,
|
|
18
|
+
'text/plain': 128 * 1024 * 1024,
|
|
19
|
+
}
|
package/vocab.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// The component declaration, and nothing else: the module a server or a
|
|
2
|
+
// browser page imports at `@yaks/anthropic/vocab`. It makes no HTTP requests
|
|
3
|
+
// and reaches no runtime.
|
|
4
|
+
import doc from './vocab.json' with {
|
|
5
|
+
type: 'json'
|
|
6
|
+
};
|
|
7
|
+
import manifest from './package.json' with {
|
|
8
|
+
type: 'json'
|
|
9
|
+
};
|
|
10
|
+
/** What this adapter records about a reply, in the form `loadVocab` accepts. */ export let anthropicDoc = doc;
|
|
11
|
+
/** What this package is: its manifest's description, the one place it is
|
|
12
|
+
* written, which a host stamps on each document here. */ export let description = manifest.description;
|
|
13
|
+
/** Every document this plugin declares. */ export let docs = [
|
|
14
|
+
anthropicDoc
|
|
15
|
+
];
|
|
16
|
+
//# sourceMappingURL=vocab.js.map
|
package/vocab.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vocab.js","sources":["./vocab.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,6EAA6E;AAC7E,0BAA0B;AAG1B,OAAO,SAAS,oBAAoB;EAAE,MAAM;AAAO,EAAC;AACpD,OAAO,cAAc,sBAAsB;EAAE,MAAM;AAAO,EAAC;AAE3D,8EAA8E,GAC9E,OAAO,IAAI,eAAyB,IAAG;AAEvC;uDACuD,GACvD,OAAO,IAAI,cAAsB,SAAS,WAAW,CAAA;AAErD,yCAAyC,GACzC,OAAO,IAAI,OAAmB;EAAC;CAAa,CAAA"}
|
package/vocab.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$id": "urn:uuid:71cfb63d-06df-4d9f-981d-77c388d141f1",
|
|
3
|
+
"title": "anthropic",
|
|
4
|
+
"$defs": {
|
|
5
|
+
"anthropic": {
|
|
6
|
+
"$id": "urn:uuid:73e79444-fb2c-4bd9-923a-0c8d59e4eae3",
|
|
7
|
+
"component": true,
|
|
8
|
+
"journal": false,
|
|
9
|
+
"description": "Anthropic message metadata; the Messages API keeps nothing to continue from.",
|
|
10
|
+
"properties": {
|
|
11
|
+
"response_id": {
|
|
12
|
+
"$id": "urn:uuid:9512c0a1-320e-4d49-8d18-ebc07fc19e0e",
|
|
13
|
+
"type": "string"
|
|
14
|
+
},
|
|
15
|
+
"cache_expires_at": {
|
|
16
|
+
"$id": "urn:uuid:933e5867-582c-4212-92f4-1cd978d68739",
|
|
17
|
+
"type": "string",
|
|
18
|
+
"format": "date-time",
|
|
19
|
+
"description": "the recorded expiry of this request’s cached prefix: request start plus the documented five minutes. Missing means unknown, not warm"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
package/vocab.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// The component declaration, and nothing else: the module a server or a
|
|
2
|
+
// browser page imports at `@yaks/anthropic/vocab`. It makes no HTTP requests
|
|
3
|
+
// and reaches no runtime.
|
|
4
|
+
|
|
5
|
+
import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
|
|
6
|
+
import doc from './vocab.json' with { type: 'json' }
|
|
7
|
+
import manifest from './package.json' with { type: 'json' }
|
|
8
|
+
|
|
9
|
+
/** What this adapter records about a reply, in the form `loadVocab` accepts. */
|
|
10
|
+
export let anthropicDoc: VocabDoc = doc
|
|
11
|
+
|
|
12
|
+
/** What this package is: its manifest's description, the one place it is
|
|
13
|
+
* written, which a host stamps on each document here. */
|
|
14
|
+
export let description: string = manifest.description
|
|
15
|
+
|
|
16
|
+
/** Every document this plugin declares. */
|
|
17
|
+
export let docs: VocabDoc[] = [anthropicDoc]
|
package/web.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// The API's own web search and page fetch, which it runs between a reply's
|
|
2
|
+
// blocks. Each is used at most USES times a request and a fetched page is cut
|
|
3
|
+
// at FETCHED tokens, so what a request offering them may add is bounded
|
|
4
|
+
// (`HOSTED`). The API cuts no search's results, so SEARCHED is the most one is
|
|
5
|
+
// taken to read back.
|
|
6
|
+
let USES = 4;
|
|
7
|
+
let FETCHED = 25_000;
|
|
8
|
+
let SEARCHED = 15_000;
|
|
9
|
+
/** What a request offering the web may add: its searches, and what they and
|
|
10
|
+
* its fetches read back. */ export let HOSTED = {
|
|
11
|
+
searches: USES,
|
|
12
|
+
input: USES * (SEARCHED + FETCHED)
|
|
13
|
+
};
|
|
14
|
+
// The models whose web tools filter what they read with code before it
|
|
15
|
+
// reaches the context; older ones have the plain versions.
|
|
16
|
+
let FILTERING = /^claude-(opus-(5|4-[678])|sonnet-(5|4-6))/;
|
|
17
|
+
/** The web tools offered to a model: held to `sites` where given, which
|
|
18
|
+
* fetches only from them and searches nothing (@yaks/model `Request`). */ export let web = (model, sites)=>{
|
|
19
|
+
let [search, fetch] = FILTERING.test(model) ? [
|
|
20
|
+
'20260209',
|
|
21
|
+
'20260209'
|
|
22
|
+
] : [
|
|
23
|
+
'20250305',
|
|
24
|
+
'20250910'
|
|
25
|
+
];
|
|
26
|
+
return [
|
|
27
|
+
...sites ? [] : [
|
|
28
|
+
{
|
|
29
|
+
type: `web_search_${search}`,
|
|
30
|
+
name: 'web_search',
|
|
31
|
+
max_uses: USES
|
|
32
|
+
}
|
|
33
|
+
],
|
|
34
|
+
{
|
|
35
|
+
type: `web_fetch_${fetch}`,
|
|
36
|
+
name: 'web_fetch',
|
|
37
|
+
max_uses: USES,
|
|
38
|
+
max_content_tokens: FETCHED,
|
|
39
|
+
citations: {
|
|
40
|
+
enabled: true
|
|
41
|
+
},
|
|
42
|
+
...sites ? {
|
|
43
|
+
allowed_domains: sites
|
|
44
|
+
} : {}
|
|
45
|
+
}
|
|
46
|
+
];
|
|
47
|
+
};
|
|
48
|
+
//# sourceMappingURL=web.js.map
|
package/web.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"web.js","sources":["./web.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,8EAA8E;AAC9E,wEAAwE;AACxE,+EAA+E;AAC/E,sBAAsB;AAKtB,IAAI,OAAO;AACX,IAAI,UAAU;AACd,IAAI,WAAW;AAEf;0BAC0B,GAC1B,OAAO,IAAI,SAAiB;EAC1B,UAAU;EACV,OAAO,OAAO,CAAC,WAAW,OAAO;AACnC,EAAC;AAED,uEAAuE;AACvE,2DAA2D;AAC3D,IAAI,YAAY;AAEhB;wEACwE,GACxE,OAAO,IAAI,MAAM,CAAC,OAAe;EAC/B,IAAI,CAAC,QAAQ,MAAM,GAAG,UAAU,IAAI,CAAC,SACjC;IAAC;IAAY;GAAW,GACxB;IAAC;IAAY;GAAW;EAC5B,OAAO;OACF,QACC,EAAE,GACF;MAAC;QAAE,MAAM,CAAC,WAAW,EAAE,QAAQ;QAAE,MAAM;QAAc,UAAU;MAAK;KAAE;IAC1E;MACE,MAAM,CAAC,UAAU,EAAE,OAAO;MAC1B,MAAM;MACN,UAAU;MACV,oBAAoB;MACpB,WAAW;QAAE,SAAS;MAAK;MAC3B,GAAG,QAAQ;QAAE,iBAAiB;MAAM,IAAI,CAAC,CAAC;IAC5C;GACD;AACH,EAAC"}
|
package/web.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// The API's own web search and page fetch, which it runs between a reply's
|
|
2
|
+
// blocks. Each is used at most USES times a request and a fetched page is cut
|
|
3
|
+
// at FETCHED tokens, so what a request offering them may add is bounded
|
|
4
|
+
// (`HOSTED`). The API cuts no search's results, so SEARCHED is the most one is
|
|
5
|
+
// taken to read back.
|
|
6
|
+
|
|
7
|
+
import type { Hosted } from 'jsr:@yaks/model@0.2.36'
|
|
8
|
+
import type { HostedParam } from './wire.ts'
|
|
9
|
+
|
|
10
|
+
let USES = 4
|
|
11
|
+
let FETCHED = 25_000
|
|
12
|
+
let SEARCHED = 15_000
|
|
13
|
+
|
|
14
|
+
/** What a request offering the web may add: its searches, and what they and
|
|
15
|
+
* its fetches read back. */
|
|
16
|
+
export let HOSTED: Hosted = {
|
|
17
|
+
searches: USES,
|
|
18
|
+
input: USES * (SEARCHED + FETCHED),
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// The models whose web tools filter what they read with code before it
|
|
22
|
+
// reaches the context; older ones have the plain versions.
|
|
23
|
+
let FILTERING = /^claude-(opus-(5|4-[678])|sonnet-(5|4-6))/
|
|
24
|
+
|
|
25
|
+
/** The web tools offered to a model: held to `sites` where given, which
|
|
26
|
+
* fetches only from them and searches nothing (@yaks/model `Request`). */
|
|
27
|
+
export let web = (model: string, sites?: string[]): HostedParam[] => {
|
|
28
|
+
let [search, fetch] = FILTERING.test(model)
|
|
29
|
+
? ['20260209', '20260209']
|
|
30
|
+
: ['20250305', '20250910']
|
|
31
|
+
return [
|
|
32
|
+
...sites
|
|
33
|
+
? []
|
|
34
|
+
: [{ type: `web_search_${search}`, name: 'web_search', max_uses: USES }],
|
|
35
|
+
{
|
|
36
|
+
type: `web_fetch_${fetch}`,
|
|
37
|
+
name: 'web_fetch',
|
|
38
|
+
max_uses: USES,
|
|
39
|
+
max_content_tokens: FETCHED,
|
|
40
|
+
citations: { enabled: true },
|
|
41
|
+
...sites ? { allowed_domains: sites } : {},
|
|
42
|
+
},
|
|
43
|
+
]
|
|
44
|
+
}
|
package/wire.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// The Messages API on the wire, spoken over fetch: the shapes this package
|
|
2
|
+
// sends and reads (only the parts it uses), one request to the API, what a
|
|
3
|
+
// refusal means, and the message a reply's event stream builds.
|
|
4
|
+
import { ModelError } from "@yaks/model";
|
|
5
|
+
import { jsonFrames } from "@yaks/model/sse";
|
|
6
|
+
import { Stalled } from "@yaks/model/stall";
|
|
7
|
+
/** The API version every request names. */ export let VERSION = '2026-10-21';
|
|
8
|
+
let BASE = 'https://api.anthropic.com';
|
|
9
|
+
// The status each error type comes with, so an error event mid-stream is read
|
|
10
|
+
// as the status it would have been sent with.
|
|
11
|
+
let STATUS = {
|
|
12
|
+
authentication_error: 401,
|
|
13
|
+
permission_error: 403,
|
|
14
|
+
not_found_error: 404,
|
|
15
|
+
rate_limit_error: 429,
|
|
16
|
+
api_error: 500,
|
|
17
|
+
overloaded_error: 529
|
|
18
|
+
};
|
|
19
|
+
let parse = (text)=>{
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(text);
|
|
22
|
+
} catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* What the API refused with, said the way a model's failure is said here: a
|
|
28
|
+
* rate limit or an overloaded or failing server is `busy` and may pass, the
|
|
29
|
+
* key's account out of credit is `credit`, a refused key is `key`, an unknown
|
|
30
|
+
* model is `model`, and a request it would not take is `request`. A spent
|
|
31
|
+
* credit balance is never `limit`: that is a caller's own ceiling, which is
|
|
32
|
+
* expected, while the account running dry is a failure of whoever holds the
|
|
33
|
+
* key. `status` is the HTTP status, or none for an error event mid-stream.
|
|
34
|
+
*/ export let failure = (status, body, headers)=>{
|
|
35
|
+
let error = parse(body)?.error;
|
|
36
|
+
let at = status ?? STATUS[error?.type ?? ''] ?? 400;
|
|
37
|
+
let said = [
|
|
38
|
+
status,
|
|
39
|
+
error?.message ?? body
|
|
40
|
+
].filter(Boolean).join(' ') || `${at}`;
|
|
41
|
+
let wait = Number(headers?.get('retry-after'));
|
|
42
|
+
let retry = Number.isFinite(wait) && wait > 0 ? {
|
|
43
|
+
after: wait * 1000
|
|
44
|
+
} : {};
|
|
45
|
+
let response = {
|
|
46
|
+
body
|
|
47
|
+
};
|
|
48
|
+
return at == 429 || at >= 500 ? new ModelError('busy', said, retry, response) : at == 401 || at == 403 ? new ModelError('key', said, undefined, response) : at == 404 ? new ModelError('model', said, undefined, response) : /credit balance/i.test(body) ? new ModelError('credit', said, undefined, response) : new ModelError('request', said, undefined, response);
|
|
49
|
+
};
|
|
50
|
+
/** A request to the API, refused as {@link failure} says. A connection that
|
|
51
|
+
* fails is `busy`, one a watched fetch gave up on `stalled`
|
|
52
|
+
* (@yaks/model/stall); a stop the caller asked for is thrown as its reason. */ export let send = async (wire, key, path, init = {})=>{
|
|
53
|
+
init.signal?.throwIfAborted();
|
|
54
|
+
let headers = {
|
|
55
|
+
...Object.fromEntries(new Headers(init.headers)),
|
|
56
|
+
accept: 'application/json',
|
|
57
|
+
authorization: `Bearer ${key}`,
|
|
58
|
+
'anthropic-version': VERSION,
|
|
59
|
+
...init.body ? {
|
|
60
|
+
'content-type': 'application/json'
|
|
61
|
+
} : {}
|
|
62
|
+
};
|
|
63
|
+
// Named, so a host's ANTHROPIC_BASE_URL never redirects the key.
|
|
64
|
+
let url = (wire.base ?? BASE).replace(/\/$/, '') + path;
|
|
65
|
+
let response;
|
|
66
|
+
try {
|
|
67
|
+
response = await (wire.fetch ?? fetch)(url, {
|
|
68
|
+
...init,
|
|
69
|
+
headers
|
|
70
|
+
});
|
|
71
|
+
} catch (e) {
|
|
72
|
+
init.signal?.throwIfAborted();
|
|
73
|
+
if (e instanceof Stalled) throw fault('stalled', `stalled — ${e.message}`);
|
|
74
|
+
throw new ModelError('busy', e?.message ?? String(e), {});
|
|
75
|
+
}
|
|
76
|
+
if (response.ok) return response;
|
|
77
|
+
let body = await response.text().catch(()=>'');
|
|
78
|
+
throw failure(response.status, body, response.headers);
|
|
79
|
+
};
|
|
80
|
+
// A dropped connection is the API being busy; one that went quiet is a stall.
|
|
81
|
+
// Both told us nothing about the request, so either is asked again.
|
|
82
|
+
let fault = (kind, message)=>kind == 'transport' ? new ModelError('busy', message, {}) : kind == 'stalled' ? new ModelError('stalled', message, {}) : new ModelError(kind, message);
|
|
83
|
+
/** A reply's events as they arrive; an error event is thrown as
|
|
84
|
+
* {@link failure} reads it, a dropped connection is `busy` and one that went
|
|
85
|
+
* quiet `stalled`. */ export let events = (body)=>jsonFrames(body, fault, (e)=>{
|
|
86
|
+
if (typeof e.type != 'string') {
|
|
87
|
+
throw fault('malformed_stream', 'a stream event has no type');
|
|
88
|
+
}
|
|
89
|
+
if (e.type == 'error') throw failure(undefined, JSON.stringify(e));
|
|
90
|
+
});
|
|
91
|
+
let present = (o)=>Object.fromEntries(Object.entries(o).filter(([, v])=>v != null));
|
|
92
|
+
/** The message after one more event of its stream: a block begins, grows by
|
|
93
|
+
* its delta (text, thinking, a tool call's input, a citation) or ends, or the message
|
|
94
|
+
* says why it stopped and what it used. A tool call's input is parsed as its
|
|
95
|
+
* block ends; input that spells no JSON keeps its text in `json`, which only
|
|
96
|
+
* a reply cut at its output limit may hold (@yaks/model `Reply.cut`).
|
|
97
|
+
* Usage is cumulative, so each count the event names replaces the last. */ export let built = (m, e)=>{
|
|
98
|
+
let at = e.index ?? 0;
|
|
99
|
+
let block = m.content[at];
|
|
100
|
+
let d = e.delta ?? {};
|
|
101
|
+
if (e.type == 'content_block_start') {
|
|
102
|
+
m.content[at] = {
|
|
103
|
+
...e.content_block
|
|
104
|
+
};
|
|
105
|
+
} else if (e.type == 'content_block_delta' && block) {
|
|
106
|
+
if (d.type == 'text_delta') block.text = (block.text ?? '') + d.text;
|
|
107
|
+
if (d.type == 'thinking_delta') {
|
|
108
|
+
block.thinking = (block.thinking ?? '') + d.thinking;
|
|
109
|
+
}
|
|
110
|
+
if (d.type == 'input_json_delta') {
|
|
111
|
+
block.json = (block.json ?? '') + d.partial_json;
|
|
112
|
+
}
|
|
113
|
+
if (d.type == 'citations_delta' && d.citation) {
|
|
114
|
+
block.citations = [
|
|
115
|
+
...block.citations ?? [],
|
|
116
|
+
d.citation
|
|
117
|
+
];
|
|
118
|
+
}
|
|
119
|
+
} else if (e.type == 'content_block_stop' && block?.json != null) {
|
|
120
|
+
let { json, ...rest } = block;
|
|
121
|
+
let input = json ? parse(json) : rest.input;
|
|
122
|
+
m.content[at] = input === undefined ? block : {
|
|
123
|
+
...rest,
|
|
124
|
+
input
|
|
125
|
+
};
|
|
126
|
+
} else if (e.type == 'message_delta') {
|
|
127
|
+
m.stop_reason = d.stop_reason;
|
|
128
|
+
m.stop_details = d.stop_details;
|
|
129
|
+
m.usage = {
|
|
130
|
+
...m.usage,
|
|
131
|
+
...present(e.usage ?? {})
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
return m;
|
|
135
|
+
};
|
|
136
|
+
//# sourceMappingURL=wire.js.map
|
package/wire.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wire.js","sources":["./wire.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,2EAA2E;AAC3E,gEAAgE;AAChE,SAAS,UAAU,2BAAgC;AACnD,SAAS,UAAU,+BAAoC;AACvD,SAAS,OAAO,iCAAsC;AAEtD,yCAAyC,GACzC,OAAO,IAAI,UAAU,aAAY;AACjC,IAAI,OAAO;AAoHX,8EAA8E;AAC9E,8CAA8C;AAC9C,IAAI,SAAiC;EACnC,sBAAsB;EACtB,kBAAkB;EAClB,iBAAiB;EACjB,kBAAkB;EAClB,WAAW;EACX,kBAAkB;AACpB;AAEA,IAAI,QAAQ,CAAC;EACX,IAAI;IACF,OAAO,KAAK,KAAK,CAAC;EACpB,EAAE,OAAM;IACN,OAAO;EACT;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,IAAI,UAAU,CACnB,QACA,MACA;EAEA,IAAI,QAA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AAI,EAAE,IAAI,EAAE,IAAI;IACpE,IAAI,EAAE,IAAI,IAAI,kBAAkB;MAC9B,MAAM,QAAQ,GAAG,CAAC,MAAM,QAAQ,IAAI,EAAE,IAAI,EAAE,QAAQ;IACtD;IACA,IAAI,EAAE,IAAI,IAAI,oBAAoB;MAChC,MAAM,IAAI,GAAG,CAAC,MAAM,IAAI,IAAI,EAAE,IAAI,EAAE,YAAY;IAClD;IACA,IAAI,EAAE,IAAI,IAAI,qBAAqB,EAAE,QAAQ,EAAE;MAC7C,MAAM,SAAS,GAAG;WAAI,MAAM,SAAS,IAAI,EAAE;QAAE,EAAE,QAAQ;OAAC;IAC1D;EACF,OAAO,IAAI,EAAE,IAAI,IAAI,wBAAwB,OAAO,QAAQ,MAAM;IAChE,IAAI,EAAE,IAAI,EAAE,GAAG,MAAM,GAAG;IACxB,IAAI,QAAQ,OAAO,MAAM,QAAQ,KAAK,KAAK;IAC3C,EAAE,OAAO,CAAC,GAAG,GAAG,UAAU,YAAY,QAAQ;MAAE,GAAG,IAAI;MAAE;IAAM;EACjE,OAAO,IAAI,EAAE,IAAI,IAAI,iBAAiB;IACpC,EAAE,WAAW,GAAG,EAAE,WAAW;IAC7B,EAAE,YAAY,GAAG,EAAE,YAAY;IAC/B,EAAE,KAAK,GAAG;MAAE,GAAG,EAAE,KAAK;MAAE,GAAG,QAAQ,EAAE,KAAK,IAAI,CAAC,EAAE;IAAC;EACpD;EACA,OAAO;AACT,EAAC"}
|
package/wire.ts
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// The Messages API on the wire, spoken over fetch: the shapes this package
|
|
2
|
+
// sends and reads (only the parts it uses), one request to the API, what a
|
|
3
|
+
// refusal means, and the message a reply's event stream builds.
|
|
4
|
+
import { ModelError } from '@yaks/model'
|
|
5
|
+
import { jsonFrames } from '@yaks/model/sse'
|
|
6
|
+
import { Stalled } from '@yaks/model/stall'
|
|
7
|
+
|
|
8
|
+
/** The API version every request names. */
|
|
9
|
+
export let VERSION = '2026-10-21'
|
|
10
|
+
let BASE = 'https://api.anthropic.com'
|
|
11
|
+
|
|
12
|
+
type Base64 = { type: 'base64'; media_type: string; data: string }
|
|
13
|
+
|
|
14
|
+
/** A block of a message sent. */
|
|
15
|
+
export type CacheControl = { type: 'ephemeral'; ttl?: '1h' }
|
|
16
|
+
|
|
17
|
+
export type Block =
|
|
18
|
+
& (
|
|
19
|
+
| { type: 'text'; text: string }
|
|
20
|
+
| { type: 'image'; source: Base64 }
|
|
21
|
+
| {
|
|
22
|
+
type: 'document'
|
|
23
|
+
source: Base64 | { type: 'text'; media_type: 'text/plain'; data: string }
|
|
24
|
+
title?: string
|
|
25
|
+
}
|
|
26
|
+
| { type: 'tool_use'; id: string; name: string; input: unknown }
|
|
27
|
+
| { type: 'tool_result'; tool_use_id: string; content: string }
|
|
28
|
+
)
|
|
29
|
+
& { cache_control?: CacheControl }
|
|
30
|
+
|
|
31
|
+
/** A message sent: one role's turn. */
|
|
32
|
+
export type Param = { role: 'user' | 'assistant'; content: Block[] }
|
|
33
|
+
|
|
34
|
+
export type ToolSystem = {
|
|
35
|
+
role: 'system'
|
|
36
|
+
content: {
|
|
37
|
+
type: 'tool_addition'
|
|
38
|
+
tool: { type: 'tool_definition'; definition: ToolParam }
|
|
39
|
+
}[]
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type ToolParam = {
|
|
43
|
+
name: string
|
|
44
|
+
description: string
|
|
45
|
+
input_schema: Record<string, unknown>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A tool the API runs itself, named by its `type`. */
|
|
49
|
+
export type HostedParam =
|
|
50
|
+
& { type: string; name: string }
|
|
51
|
+
& Record<
|
|
52
|
+
string,
|
|
53
|
+
unknown
|
|
54
|
+
>
|
|
55
|
+
|
|
56
|
+
/** What a reply used, as the API counts it. */
|
|
57
|
+
export type ApiUsage = {
|
|
58
|
+
input_tokens?: number | null
|
|
59
|
+
output_tokens: number
|
|
60
|
+
cache_read_input_tokens?: number | null
|
|
61
|
+
cache_creation_input_tokens?: number | null
|
|
62
|
+
cache_creation?: { ephemeral_1h_input_tokens?: number } | null
|
|
63
|
+
server_tool_use?: { web_search_requests?: number | null } | null
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Where a block of a reply's text came from: a web search result names its
|
|
67
|
+
* page by `url`. */
|
|
68
|
+
export type Citation = { type: string; url?: string; title?: string | null }
|
|
69
|
+
|
|
70
|
+
/** A block of a reply: text, a tool call, or one this package passes by.
|
|
71
|
+
* `json` is a call's input as the stream has sent it so far. */
|
|
72
|
+
export type Content = {
|
|
73
|
+
type: string
|
|
74
|
+
text?: string
|
|
75
|
+
/** a thinking block's words */
|
|
76
|
+
thinking?: string
|
|
77
|
+
id?: string
|
|
78
|
+
name?: string
|
|
79
|
+
input?: unknown
|
|
80
|
+
json?: string
|
|
81
|
+
citations?: Citation[]
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export type Message = {
|
|
85
|
+
id: string
|
|
86
|
+
model: string
|
|
87
|
+
content: Content[]
|
|
88
|
+
stop_reason?: string | null
|
|
89
|
+
stop_details?: { explanation?: string | null } | null
|
|
90
|
+
usage: ApiUsage
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** One page of a list, and where the next begins. */
|
|
94
|
+
export type Page<T> = { data: T[]; has_more: boolean; last_id?: string | null }
|
|
95
|
+
|
|
96
|
+
export type ModelInfo = {
|
|
97
|
+
id: string
|
|
98
|
+
display_name: string
|
|
99
|
+
max_input_tokens?: number | null
|
|
100
|
+
max_tokens?: number | null
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** One event of a reply's stream. */
|
|
104
|
+
export type Event = {
|
|
105
|
+
type: string
|
|
106
|
+
index?: number
|
|
107
|
+
message?: Message
|
|
108
|
+
content_block?: Content
|
|
109
|
+
delta?: {
|
|
110
|
+
type?: string
|
|
111
|
+
text?: string
|
|
112
|
+
thinking?: string
|
|
113
|
+
partial_json?: string
|
|
114
|
+
citation?: Citation
|
|
115
|
+
stop_reason?: string | null
|
|
116
|
+
stop_details?: Message['stop_details']
|
|
117
|
+
}
|
|
118
|
+
usage?: Partial<ApiUsage>
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export type Wire = {
|
|
122
|
+
fetch?: typeof fetch
|
|
123
|
+
base?: string
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// The status each error type comes with, so an error event mid-stream is read
|
|
127
|
+
// as the status it would have been sent with.
|
|
128
|
+
let STATUS: Record<string, number> = {
|
|
129
|
+
authentication_error: 401,
|
|
130
|
+
permission_error: 403,
|
|
131
|
+
not_found_error: 404,
|
|
132
|
+
rate_limit_error: 429,
|
|
133
|
+
api_error: 500,
|
|
134
|
+
overloaded_error: 529,
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
let parse = (text: string): unknown => {
|
|
138
|
+
try {
|
|
139
|
+
return JSON.parse(text)
|
|
140
|
+
} catch {
|
|
141
|
+
return undefined
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* What the API refused with, said the way a model's failure is said here: a
|
|
147
|
+
* rate limit or an overloaded or failing server is `busy` and may pass, the
|
|
148
|
+
* key's account out of credit is `credit`, a refused key is `key`, an unknown
|
|
149
|
+
* model is `model`, and a request it would not take is `request`. A spent
|
|
150
|
+
* credit balance is never `limit`: that is a caller's own ceiling, which is
|
|
151
|
+
* expected, while the account running dry is a failure of whoever holds the
|
|
152
|
+
* key. `status` is the HTTP status, or none for an error event mid-stream.
|
|
153
|
+
*/
|
|
154
|
+
export let failure = (
|
|
155
|
+
status: number | undefined,
|
|
156
|
+
body: string,
|
|
157
|
+
headers?: Headers,
|
|
158
|
+
): ModelError => {
|
|
159
|
+
let error = (parse(body) as { error?: { type?: string; message?: string } })
|
|
160
|
+
?.error
|
|
161
|
+
let at = status ?? STATUS[error?.type ?? ''] ?? 400
|
|
162
|
+
let said = [status, error?.message ?? body].filter(Boolean).join(' ') ||
|
|
163
|
+
`${at}`
|
|
164
|
+
let wait = Number(headers?.get('retry-after'))
|
|
165
|
+
let retry = Number.isFinite(wait) && wait > 0 ? { after: wait * 1000 } : {}
|
|
166
|
+
let response = { body }
|
|
167
|
+
return at == 429 || at >= 500
|
|
168
|
+
? new ModelError('busy', said, retry, response)
|
|
169
|
+
: at == 401 || at == 403
|
|
170
|
+
? new ModelError('key', said, undefined, response)
|
|
171
|
+
: at == 404
|
|
172
|
+
? new ModelError('model', said, undefined, response)
|
|
173
|
+
: /credit balance/i.test(body)
|
|
174
|
+
? new ModelError('credit', said, undefined, response)
|
|
175
|
+
: new ModelError('request', said, undefined, response)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** A request to the API, refused as {@link failure} says. A connection that
|
|
179
|
+
* fails is `busy`, one a watched fetch gave up on `stalled`
|
|
180
|
+
* (@yaks/model/stall); a stop the caller asked for is thrown as its reason. */
|
|
181
|
+
export let send = async (
|
|
182
|
+
wire: Wire,
|
|
183
|
+
key: string,
|
|
184
|
+
path: string,
|
|
185
|
+
init: RequestInit = {},
|
|
186
|
+
): Promise<Response> => {
|
|
187
|
+
init.signal?.throwIfAborted()
|
|
188
|
+
let headers = {
|
|
189
|
+
...Object.fromEntries(new Headers(init.headers)),
|
|
190
|
+
accept: 'application/json',
|
|
191
|
+
authorization: `Bearer ${key}`,
|
|
192
|
+
'anthropic-version': VERSION,
|
|
193
|
+
...init.body ? { 'content-type': 'application/json' } : {},
|
|
194
|
+
}
|
|
195
|
+
// Named, so a host's ANTHROPIC_BASE_URL never redirects the key.
|
|
196
|
+
let url = (wire.base ?? BASE).replace(/\/$/, '') + path
|
|
197
|
+
let response: Response
|
|
198
|
+
try {
|
|
199
|
+
response = await (wire.fetch ?? fetch)(url, { ...init, headers })
|
|
200
|
+
} catch (e) {
|
|
201
|
+
init.signal?.throwIfAborted()
|
|
202
|
+
if (e instanceof Stalled) throw fault('stalled', `stalled — ${e.message}`)
|
|
203
|
+
throw new ModelError('busy', (e as Error)?.message ?? String(e), {})
|
|
204
|
+
}
|
|
205
|
+
if (response.ok) return response
|
|
206
|
+
let body = await response.text().catch(() => '')
|
|
207
|
+
throw failure(response.status, body, response.headers)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// A dropped connection is the API being busy; one that went quiet is a stall.
|
|
211
|
+
// Both told us nothing about the request, so either is asked again.
|
|
212
|
+
let fault = (kind: string, message: string) =>
|
|
213
|
+
kind == 'transport'
|
|
214
|
+
? new ModelError('busy', message, {})
|
|
215
|
+
: kind == 'stalled'
|
|
216
|
+
? new ModelError('stalled', message, {})
|
|
217
|
+
: new ModelError(kind, message)
|
|
218
|
+
|
|
219
|
+
/** A reply's events as they arrive; an error event is thrown as
|
|
220
|
+
* {@link failure} reads it, a dropped connection is `busy` and one that went
|
|
221
|
+
* quiet `stalled`. */
|
|
222
|
+
export let events = (body: ReadableStream<Uint8Array>) =>
|
|
223
|
+
jsonFrames(body, fault, (e) => {
|
|
224
|
+
if (typeof e.type != 'string') {
|
|
225
|
+
throw fault('malformed_stream', 'a stream event has no type')
|
|
226
|
+
}
|
|
227
|
+
if (e.type == 'error') throw failure(undefined, JSON.stringify(e))
|
|
228
|
+
}) as AsyncGenerator<Event>
|
|
229
|
+
|
|
230
|
+
let present = <T extends object>(o: T) =>
|
|
231
|
+
Object.fromEntries(Object.entries(o).filter(([, v]) => v != null))
|
|
232
|
+
|
|
233
|
+
/** The message after one more event of its stream: a block begins, grows by
|
|
234
|
+
* its delta (text, thinking, a tool call's input, a citation) or ends, or the message
|
|
235
|
+
* says why it stopped and what it used. A tool call's input is parsed as its
|
|
236
|
+
* block ends; input that spells no JSON keeps its text in `json`, which only
|
|
237
|
+
* a reply cut at its output limit may hold (@yaks/model `Reply.cut`).
|
|
238
|
+
* Usage is cumulative, so each count the event names replaces the last. */
|
|
239
|
+
export let built = (m: Message, e: Event): Message => {
|
|
240
|
+
let at = e.index ?? 0
|
|
241
|
+
let block = m.content[at]
|
|
242
|
+
let d = e.delta ?? {}
|
|
243
|
+
if (e.type == 'content_block_start') {
|
|
244
|
+
m.content[at] = { ...e.content_block! }
|
|
245
|
+
} else if (e.type == 'content_block_delta' && block) {
|
|
246
|
+
if (d.type == 'text_delta') block.text = (block.text ?? '') + d.text
|
|
247
|
+
if (d.type == 'thinking_delta') {
|
|
248
|
+
block.thinking = (block.thinking ?? '') + d.thinking
|
|
249
|
+
}
|
|
250
|
+
if (d.type == 'input_json_delta') {
|
|
251
|
+
block.json = (block.json ?? '') + d.partial_json
|
|
252
|
+
}
|
|
253
|
+
if (d.type == 'citations_delta' && d.citation) {
|
|
254
|
+
block.citations = [...block.citations ?? [], d.citation]
|
|
255
|
+
}
|
|
256
|
+
} else if (e.type == 'content_block_stop' && block?.json != null) {
|
|
257
|
+
let { json, ...rest } = block
|
|
258
|
+
let input = json ? parse(json) : rest.input
|
|
259
|
+
m.content[at] = input === undefined ? block : { ...rest, input }
|
|
260
|
+
} else if (e.type == 'message_delta') {
|
|
261
|
+
m.stop_reason = d.stop_reason
|
|
262
|
+
m.stop_details = d.stop_details
|
|
263
|
+
m.usage = { ...m.usage, ...present(e.usage ?? {}) }
|
|
264
|
+
}
|
|
265
|
+
return m
|
|
266
|
+
}
|