@pi-dstools/deepseek 0.0.0-stage → 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 +30 -0
- package/README.md +16 -2
- package/package.json +46 -3
- package/src/constants.ts +8 -0
- package/src/credentials.ts +81 -0
- package/src/errors.ts +61 -0
- package/src/files.ts +50 -0
- package/src/http.ts +183 -0
- package/src/index.ts +8 -0
- package/src/text.ts +45 -0
- package/src/theme.ts +35 -0
- package/src/types.ts +107 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Copyright (c) 2026 YogiLiu. All rights reserved.
|
|
2
|
+
|
|
3
|
+
Redistribution and use in
|
|
4
|
+
source and binary forms, with or without modification, are permitted provided
|
|
5
|
+
that the following conditions are met:
|
|
6
|
+
|
|
7
|
+
1. Redistributions of source code must
|
|
8
|
+
retain the above copyright notice, this list of conditions and the following
|
|
9
|
+
disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above
|
|
12
|
+
copyright notice, this list of conditions and the following disclaimer in the
|
|
13
|
+
documentation and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3.
|
|
16
|
+
Neither the name of the copyright holder nor the names of its contributors may be
|
|
17
|
+
used to endorse or promote products derived from this software without specific
|
|
18
|
+
prior written permission.
|
|
19
|
+
|
|
20
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
|
|
21
|
+
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
22
|
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
|
23
|
+
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
|
|
24
|
+
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
|
25
|
+
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
26
|
+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
27
|
+
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
|
|
28
|
+
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
|
29
|
+
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
|
|
30
|
+
DAMAGE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pi-dstools/deepseek
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Shared runtime library for the DeepSeek Search and Fetch APIs.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
See `package.json` for the required Node.js version.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pnpm add @pi-dstools/deepseek
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
Import the public API from `@pi-dstools/deepseek`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pi-dstools/deepseek",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Shared runtime library for the DeepSeek Search and Fetch APIs",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"deepseek",
|
|
7
|
+
"library"
|
|
8
|
+
],
|
|
9
|
+
"license": "BSD-3-Clause",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/YogiLiu/pi-dstools.git"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"src",
|
|
16
|
+
"README.md"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"types": "./src/index.ts",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": "./src/index.ts"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@earendil-works/pi-coding-agent": "1.5.2",
|
|
28
|
+
"@earendil-works/pi-tui": "1.5.2",
|
|
29
|
+
"@types/node": "^22.19.19",
|
|
30
|
+
"typescript": "^5.9.3"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
34
|
+
"@earendil-works/pi-tui": "*"
|
|
35
|
+
},
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=22.19.0"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"lint": "oxlint .",
|
|
41
|
+
"lint:fix": "oxlint --fix --fix-suggestions .",
|
|
42
|
+
"fmt": "oxfmt --write .",
|
|
43
|
+
"fmt:check": "oxfmt --check .",
|
|
44
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
45
|
+
"test": "pnpm --dir ../.. test",
|
|
46
|
+
"test:watch": "pnpm --dir ../.. test:watch",
|
|
47
|
+
"pack:dry-run": "pnpm pack --dry-run"
|
|
48
|
+
}
|
|
6
49
|
}
|
package/src/constants.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const DEEPSEEK_PROVIDER_ID = "deepseek";
|
|
2
|
+
export const DEEPSEEK_OFFICIAL_ORIGIN = "https://api.deepseek.com";
|
|
3
|
+
export const DEEPSEEK_SEARCH_URL = `${DEEPSEEK_OFFICIAL_ORIGIN}/v1/tools/search`;
|
|
4
|
+
export const DEEPSEEK_FETCH_URL = `${DEEPSEEK_OFFICIAL_ORIGIN}/v1/tools/fetch`;
|
|
5
|
+
|
|
6
|
+
export const MAX_TOOL_RETRIES = 2;
|
|
7
|
+
export const DEFAULT_RETRY_DELAYS_MS = [500, 1000] as const;
|
|
8
|
+
export const MAX_RETRY_DELAY_MS = 60_000;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { DEEPSEEK_OFFICIAL_ORIGIN, DEEPSEEK_PROVIDER_ID } from "./constants";
|
|
2
|
+
import { DeepSeekToolError, toUserMessage } from "./errors";
|
|
3
|
+
import type {
|
|
4
|
+
CredentialRegistry,
|
|
5
|
+
DeepSeekToolContext,
|
|
6
|
+
PreparedToolCall,
|
|
7
|
+
ToolIdentity,
|
|
8
|
+
} from "./types";
|
|
9
|
+
|
|
10
|
+
export async function resolveDeepSeekApiKey(
|
|
11
|
+
registry: CredentialRegistry,
|
|
12
|
+
toolName: string,
|
|
13
|
+
): Promise<string> {
|
|
14
|
+
let auth: Awaited<ReturnType<CredentialRegistry["getProviderAuth"]>>;
|
|
15
|
+
try {
|
|
16
|
+
auth = await registry.getProviderAuth(DEEPSEEK_PROVIDER_ID);
|
|
17
|
+
} catch (error) {
|
|
18
|
+
throw new DeepSeekToolError(
|
|
19
|
+
`${toolName} is installed but unavailable: Pi could not resolve credentials for its DeepSeek provider (${toUserMessage(error)}).`,
|
|
20
|
+
"auth",
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const apiKey = auth?.auth.apiKey;
|
|
25
|
+
if (typeof apiKey !== "string" || apiKey.trim().length === 0) {
|
|
26
|
+
throw new DeepSeekToolError(
|
|
27
|
+
`${toolName} is installed but unavailable: Pi did not resolve credentials for its DeepSeek provider.`,
|
|
28
|
+
"auth",
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
return apiKey;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function configuredBaseUrl(value: string | undefined): string | undefined {
|
|
35
|
+
if (value === undefined) return undefined;
|
|
36
|
+
const trimmed = value.trim();
|
|
37
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function isOfficialDeepSeekBaseUrl(value: string | undefined): boolean {
|
|
41
|
+
const configured = configuredBaseUrl(value);
|
|
42
|
+
if (configured === undefined) return true;
|
|
43
|
+
try {
|
|
44
|
+
return new URL(configured).origin === DEEPSEEK_OFFICIAL_ORIGIN;
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function endpointOrigin(value: string): string {
|
|
51
|
+
try {
|
|
52
|
+
return new URL(value.trim()).origin;
|
|
53
|
+
} catch {
|
|
54
|
+
return "(invalid URL)";
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function assertOfficialDeepSeekEndpoint(
|
|
59
|
+
baseUrl: string | undefined,
|
|
60
|
+
identity: ToolIdentity,
|
|
61
|
+
): void {
|
|
62
|
+
const configured = configuredBaseUrl(baseUrl);
|
|
63
|
+
if (configured === undefined || isOfficialDeepSeekBaseUrl(configured)) return;
|
|
64
|
+
throw new DeepSeekToolError(
|
|
65
|
+
`${identity.toolName} is installed but unavailable: Pi connects to DeepSeek via ${endpointOrigin(configured)}, not the official ${DEEPSEEK_OFFICIAL_ORIGIN} endpoint. This tool only works with DeepSeek's official ${identity.apiName} API.`,
|
|
66
|
+
"endpoint",
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function prepareDeepSeekToolCall(
|
|
71
|
+
ctx: DeepSeekToolContext,
|
|
72
|
+
identity: ToolIdentity,
|
|
73
|
+
signal: Readonly<AbortSignal> | undefined,
|
|
74
|
+
): Promise<PreparedToolCall> {
|
|
75
|
+
assertOfficialDeepSeekEndpoint(
|
|
76
|
+
ctx.modelRegistry.getProvider(DEEPSEEK_PROVIDER_ID)?.baseUrl,
|
|
77
|
+
identity,
|
|
78
|
+
);
|
|
79
|
+
const apiKey = await resolveDeepSeekApiKey(ctx.modelRegistry, identity.toolName);
|
|
80
|
+
return { apiKey, signal: signal ?? ctx.signal };
|
|
81
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { DeepSeekToolErrorKind, ToolApiName } from "./types";
|
|
2
|
+
|
|
3
|
+
export class DeepSeekToolError extends Error {
|
|
4
|
+
constructor(
|
|
5
|
+
message: string,
|
|
6
|
+
readonly kind: DeepSeekToolErrorKind,
|
|
7
|
+
readonly status?: number,
|
|
8
|
+
) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "DeepSeekToolError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
15
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function errorMessage(error: unknown): string {
|
|
19
|
+
return error instanceof Error ? error.message : String(error);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isAbortError(error: unknown, signal?: Readonly<AbortSignal>): boolean {
|
|
23
|
+
if (signal?.aborted === true) return true;
|
|
24
|
+
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function requiredString(value: unknown, field: string, apiName: ToolApiName): string {
|
|
28
|
+
if (typeof value !== "string") {
|
|
29
|
+
throw new DeepSeekToolError(
|
|
30
|
+
`DeepSeek ${apiName} API returned an invalid ${field}.`,
|
|
31
|
+
"response",
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function nullableString(value: unknown, field: string, apiName: ToolApiName): string | null {
|
|
38
|
+
if (value === undefined || value === null) return null;
|
|
39
|
+
if (typeof value !== "string") {
|
|
40
|
+
throw new DeepSeekToolError(
|
|
41
|
+
`DeepSeek ${apiName} API returned an invalid ${field}.`,
|
|
42
|
+
"response",
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function finiteNumber(value: unknown, field: string, apiName: ToolApiName): number {
|
|
49
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
50
|
+
throw new DeepSeekToolError(
|
|
51
|
+
`DeepSeek ${apiName} API returned an invalid ${field}.`,
|
|
52
|
+
"response",
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function toUserMessage(error: unknown): string {
|
|
59
|
+
if (error instanceof DeepSeekToolError) return error.message;
|
|
60
|
+
return error instanceof Error ? error.message : String(error);
|
|
61
|
+
}
|
package/src/files.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir as systemTmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
|
|
6
|
+
import { DeepSeekToolError, errorMessage } from "./errors";
|
|
7
|
+
import type {
|
|
8
|
+
ContentFileSystem,
|
|
9
|
+
ContentOptions,
|
|
10
|
+
ContentWrite,
|
|
11
|
+
ResolvedContentOptions,
|
|
12
|
+
} from "./types";
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_FILE_SYSTEM: ContentFileSystem = {
|
|
15
|
+
async mkdir(path, options) {
|
|
16
|
+
await mkdir(path, options);
|
|
17
|
+
},
|
|
18
|
+
async writeFile(path, data, encoding) {
|
|
19
|
+
await writeFile(path, data, encoding);
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function resolveContentOptions(options: ContentOptions = {}): ResolvedContentOptions {
|
|
24
|
+
return {
|
|
25
|
+
makeTempDir: options.tmpdir ?? systemTmpdir,
|
|
26
|
+
makeUuid: options.uuid ?? randomUUID,
|
|
27
|
+
fileSystem: options.fs ?? DEFAULT_FILE_SYSTEM,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function contentDirectory(root: string, tool: string, id: string): string {
|
|
32
|
+
return join(root, "pi-dstools", tool, id);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function writeContentFiles(
|
|
36
|
+
fileSystem: ContentFileSystem,
|
|
37
|
+
directory: string,
|
|
38
|
+
writes: readonly ContentWrite[],
|
|
39
|
+
failureMessage: string,
|
|
40
|
+
): Promise<void> {
|
|
41
|
+
if (writes.length === 0) return;
|
|
42
|
+
try {
|
|
43
|
+
await fileSystem.mkdir(directory, { recursive: true });
|
|
44
|
+
await Promise.all(
|
|
45
|
+
writes.map(({ path, content }) => fileSystem.writeFile(path, content, "utf8")),
|
|
46
|
+
);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
throw new DeepSeekToolError(`${failureMessage}: ${errorMessage(error)}`, "filesystem");
|
|
49
|
+
}
|
|
50
|
+
}
|
package/src/http.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { DEFAULT_RETRY_DELAYS_MS, MAX_RETRY_DELAY_MS, MAX_TOOL_RETRIES } from "./constants";
|
|
2
|
+
import { DeepSeekToolError, errorMessage, isAbortError, isRecord } from "./errors";
|
|
3
|
+
import type {
|
|
4
|
+
DeepSeekRequestInit,
|
|
5
|
+
HttpHeaders,
|
|
6
|
+
HttpResponse,
|
|
7
|
+
JsonPrimitive,
|
|
8
|
+
PostDeepSeekJsonOptions,
|
|
9
|
+
ToolApiName,
|
|
10
|
+
} from "./types";
|
|
11
|
+
|
|
12
|
+
function abortError(): Error {
|
|
13
|
+
const error = new Error("DeepSeek request was cancelled.");
|
|
14
|
+
error.name = "AbortError";
|
|
15
|
+
return error;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function defaultSleep(delayMs: number, signal?: Readonly<AbortSignal>): Promise<void> {
|
|
19
|
+
return new Promise<void>((resolve, reject) => {
|
|
20
|
+
if (signal?.aborted === true) {
|
|
21
|
+
reject(abortError());
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const onAbort = () => {
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
reject(abortError());
|
|
27
|
+
};
|
|
28
|
+
const timer = setTimeout(() => {
|
|
29
|
+
signal?.removeEventListener("abort", onAbort);
|
|
30
|
+
resolve();
|
|
31
|
+
}, delayMs);
|
|
32
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function isRetryableStatus(status: number): boolean {
|
|
37
|
+
return status === 408 || status === 429 || (status >= 500 && status <= 599);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function retryDelayMs(
|
|
41
|
+
headers: HttpHeaders | undefined,
|
|
42
|
+
retryIndex: number,
|
|
43
|
+
now: number,
|
|
44
|
+
): number {
|
|
45
|
+
const milliseconds = headers?.get("retry-after-ms");
|
|
46
|
+
if (milliseconds !== undefined && milliseconds !== null) {
|
|
47
|
+
const parsed = Number(milliseconds);
|
|
48
|
+
if (Number.isFinite(parsed) && parsed >= 0) {
|
|
49
|
+
return Math.min(Math.max(parsed, 0), MAX_RETRY_DELAY_MS);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const retryAfter = headers?.get("retry-after");
|
|
54
|
+
if (retryAfter !== undefined && retryAfter !== null) {
|
|
55
|
+
const seconds = Number(retryAfter);
|
|
56
|
+
if (Number.isFinite(seconds)) {
|
|
57
|
+
if (seconds >= 0) return Math.min(Math.max(seconds * 1000, 0), MAX_RETRY_DELAY_MS);
|
|
58
|
+
} else {
|
|
59
|
+
const date = Date.parse(retryAfter);
|
|
60
|
+
if (Number.isFinite(date)) return Math.min(Math.max(date - now, 0), MAX_RETRY_DELAY_MS);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return DEFAULT_RETRY_DELAYS_MS[retryIndex] ?? 1000;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function buildRequestInit(
|
|
68
|
+
body: Readonly<Record<string, JsonPrimitive>>,
|
|
69
|
+
apiKey: string,
|
|
70
|
+
signal: Readonly<AbortSignal> | undefined,
|
|
71
|
+
): DeepSeekRequestInit {
|
|
72
|
+
return {
|
|
73
|
+
method: "POST",
|
|
74
|
+
headers: {
|
|
75
|
+
Authorization: `Bearer ${apiKey}`,
|
|
76
|
+
"Content-Type": "application/json",
|
|
77
|
+
},
|
|
78
|
+
body: JSON.stringify(body),
|
|
79
|
+
...(signal === undefined ? {} : { signal }),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function readHttpError(response: HttpResponse, apiName: ToolApiName): Promise<string> {
|
|
84
|
+
let rawBody: string;
|
|
85
|
+
try {
|
|
86
|
+
rawBody = await response.text();
|
|
87
|
+
} catch {
|
|
88
|
+
rawBody = "";
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
let providerMessage = "";
|
|
92
|
+
if (rawBody) {
|
|
93
|
+
try {
|
|
94
|
+
const parsed: unknown = JSON.parse(rawBody);
|
|
95
|
+
if (isRecord(parsed) && isRecord(parsed.error) && typeof parsed.error.message === "string") {
|
|
96
|
+
providerMessage = parsed.error.message.trim();
|
|
97
|
+
}
|
|
98
|
+
} catch {
|
|
99
|
+
providerMessage = rawBody.trim();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (response.status === 401) {
|
|
104
|
+
return "DeepSeek rejected the API key Pi resolved for its DeepSeek provider.";
|
|
105
|
+
}
|
|
106
|
+
if (response.status === 402) {
|
|
107
|
+
return "DeepSeek account has insufficient balance.";
|
|
108
|
+
}
|
|
109
|
+
if (response.status === 429) {
|
|
110
|
+
return `DeepSeek ${apiName} API rate limit exceeded.`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const status = `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""}`;
|
|
114
|
+
const detail = providerMessage ? `: ${providerMessage.slice(0, 500)}` : "";
|
|
115
|
+
return `DeepSeek ${apiName} API returned ${status}${detail}`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function parseJsonPayload(response: HttpResponse, apiName: ToolApiName): Promise<unknown> {
|
|
119
|
+
try {
|
|
120
|
+
return await response.json();
|
|
121
|
+
} catch (error) {
|
|
122
|
+
throw new DeepSeekToolError(
|
|
123
|
+
`DeepSeek ${apiName} API returned invalid JSON: ${errorMessage(error)}`,
|
|
124
|
+
"parse",
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function asClientError(
|
|
130
|
+
error: unknown,
|
|
131
|
+
apiName: ToolApiName,
|
|
132
|
+
signal: Readonly<AbortSignal> | undefined,
|
|
133
|
+
): DeepSeekToolError {
|
|
134
|
+
if (error instanceof DeepSeekToolError) return error;
|
|
135
|
+
if (isAbortError(error, signal)) {
|
|
136
|
+
return new DeepSeekToolError(`DeepSeek ${apiName.toLowerCase()} was cancelled.`, "aborted");
|
|
137
|
+
}
|
|
138
|
+
return new DeepSeekToolError(
|
|
139
|
+
`DeepSeek ${apiName} request failed: ${errorMessage(error)}`,
|
|
140
|
+
"network",
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function postDeepSeekJson(options: PostDeepSeekJsonOptions): Promise<unknown> {
|
|
145
|
+
if (!options.apiKey) {
|
|
146
|
+
throw new DeepSeekToolError("Missing DeepSeek API key.", "auth");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
150
|
+
const sleepImpl = options.sleep ?? defaultSleep;
|
|
151
|
+
const now = options.now ?? Date.now;
|
|
152
|
+
|
|
153
|
+
const attemptRequest = async (attempt: number): Promise<unknown> => {
|
|
154
|
+
try {
|
|
155
|
+
options.signal?.throwIfAborted();
|
|
156
|
+
const response = await fetchImpl(
|
|
157
|
+
options.endpoint,
|
|
158
|
+
buildRequestInit(options.body, options.apiKey, options.signal),
|
|
159
|
+
);
|
|
160
|
+
if (!response.ok) {
|
|
161
|
+
const message = await readHttpError(response, options.apiName);
|
|
162
|
+
const error = new DeepSeekToolError(message, "http", response.status);
|
|
163
|
+
if (attempt < MAX_TOOL_RETRIES && isRetryableStatus(response.status)) {
|
|
164
|
+
const delayMs = retryDelayMs(response.headers, attempt, now());
|
|
165
|
+
options.onRetry?.({
|
|
166
|
+
attempt: attempt + 1,
|
|
167
|
+
maxRetries: MAX_TOOL_RETRIES,
|
|
168
|
+
status: response.status,
|
|
169
|
+
delayMs,
|
|
170
|
+
});
|
|
171
|
+
await sleepImpl(delayMs, options.signal);
|
|
172
|
+
return await attemptRequest(attempt + 1);
|
|
173
|
+
}
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
return await parseJsonPayload(response, options.apiName);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
throw asClientError(error, options.apiName, options.signal);
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
return attemptRequest(0);
|
|
183
|
+
}
|
package/src/index.ts
ADDED
package/src/text.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { RetryProgress } from "./types";
|
|
2
|
+
|
|
3
|
+
// oxlint-disable-next-line no-control-regex -- terminal control characters must be stripped from untrusted remote text
|
|
4
|
+
const CONTROL_CHARACTERS = /[\u0000-\u001F\u007F]+/gu;
|
|
5
|
+
// oxlint-disable-next-line no-control-regex -- terminal control characters must be stripped from untrusted remote text
|
|
6
|
+
const CONTENT_CONTROL_CHARACTERS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]+/gu;
|
|
7
|
+
const CONTENT_LINE_BREAKS = /\r\n|\n|\r/u;
|
|
8
|
+
|
|
9
|
+
export function displayText(value: string): string {
|
|
10
|
+
return value.replaceAll(CONTROL_CHARACTERS, " ");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function displayContent(value: string): string {
|
|
14
|
+
return value.replaceAll(CONTENT_CONTROL_CHARACTERS, " ");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function markdownLinkText(value: string): string {
|
|
18
|
+
return displayText(value).replaceAll("\\", "\\\\").replaceAll("[", "\\[").replaceAll("]", "\\]");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function markdownLinkUrl(value: string): string {
|
|
22
|
+
return value
|
|
23
|
+
.replaceAll(CONTROL_CHARACTERS, "")
|
|
24
|
+
.replaceAll(/\s+/gu, "%20")
|
|
25
|
+
.replaceAll("\\", "\\\\")
|
|
26
|
+
.replaceAll("(", "\\(")
|
|
27
|
+
.replaceAll(")", "\\)");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function truncateText(value: string, maxLength = 80): string {
|
|
31
|
+
if (value.length <= maxLength) return value;
|
|
32
|
+
return `${value.slice(0, Math.max(0, maxLength - 3))}...`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function unicodeLength(value: string): number {
|
|
36
|
+
return Array.from(value).length;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function splitContentLines(value: string): string[] {
|
|
40
|
+
return value.split(CONTENT_LINE_BREAKS);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function retryMessage(progress: RetryProgress): string {
|
|
44
|
+
return `Retrying (${progress.attempt}/${progress.maxRetries}) after HTTP ${progress.status}...`;
|
|
45
|
+
}
|
package/src/theme.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { MarkdownTheme } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
type OptionalStyleName = "bold" | "italic" | "strikethrough" | "underline";
|
|
5
|
+
|
|
6
|
+
// oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- Theme is a host class with private fields
|
|
7
|
+
function themedText(theme: Theme, token: Parameters<Theme["fg"]>[0]): (text: string) => string {
|
|
8
|
+
return (text) => theme.fg(token, text);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- Partial<Theme> is derived from a host class
|
|
12
|
+
function optionalStyle(theme: Partial<Theme>, name: OptionalStyleName): (text: string) => string {
|
|
13
|
+
return (text) => theme[name]?.(text) ?? text;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- Theme is a host class with private fields
|
|
17
|
+
export function toMarkdownTheme(theme: Theme): MarkdownTheme {
|
|
18
|
+
const optionalStyles: Partial<Theme> = theme;
|
|
19
|
+
return {
|
|
20
|
+
heading: themedText(theme, "mdHeading"),
|
|
21
|
+
link: themedText(theme, "mdLink"),
|
|
22
|
+
linkUrl: themedText(theme, "mdLinkUrl"),
|
|
23
|
+
code: themedText(theme, "mdCode"),
|
|
24
|
+
codeBlock: themedText(theme, "mdCodeBlock"),
|
|
25
|
+
codeBlockBorder: themedText(theme, "mdCodeBlockBorder"),
|
|
26
|
+
quote: themedText(theme, "mdQuote"),
|
|
27
|
+
quoteBorder: themedText(theme, "mdQuoteBorder"),
|
|
28
|
+
hr: themedText(theme, "mdHr"),
|
|
29
|
+
listBullet: themedText(theme, "mdListBullet"),
|
|
30
|
+
bold: optionalStyle(optionalStyles, "bold"),
|
|
31
|
+
italic: optionalStyle(optionalStyles, "italic"),
|
|
32
|
+
strikethrough: optionalStyle(optionalStyles, "strikethrough"),
|
|
33
|
+
underline: optionalStyle(optionalStyles, "underline"),
|
|
34
|
+
};
|
|
35
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
export type ToolApiName = "Search" | "Fetch";
|
|
2
|
+
|
|
3
|
+
export type DeepSeekToolErrorKind =
|
|
4
|
+
| "auth"
|
|
5
|
+
| "endpoint"
|
|
6
|
+
| "validation"
|
|
7
|
+
| "http"
|
|
8
|
+
| "network"
|
|
9
|
+
| "parse"
|
|
10
|
+
| "response"
|
|
11
|
+
| "aborted"
|
|
12
|
+
| "filesystem";
|
|
13
|
+
|
|
14
|
+
export type JsonPrimitive = string | number | boolean | null;
|
|
15
|
+
|
|
16
|
+
export interface ToolIdentity {
|
|
17
|
+
readonly toolName: string;
|
|
18
|
+
readonly apiName: ToolApiName;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface CredentialRegistry {
|
|
22
|
+
readonly getProvider: (provider: string) => { readonly baseUrl?: string } | undefined;
|
|
23
|
+
readonly getProviderAuth: (
|
|
24
|
+
provider: string,
|
|
25
|
+
) => Promise<{ readonly auth: { readonly apiKey?: string } } | undefined>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface DeepSeekToolContext {
|
|
29
|
+
readonly modelRegistry: CredentialRegistry;
|
|
30
|
+
readonly signal: Readonly<AbortSignal> | undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface PreparedToolCall {
|
|
34
|
+
readonly apiKey: string;
|
|
35
|
+
readonly signal: Readonly<AbortSignal> | undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface HttpHeaders {
|
|
39
|
+
readonly get: (name: string) => string | null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface HttpResponse {
|
|
43
|
+
readonly ok: boolean;
|
|
44
|
+
readonly status: number;
|
|
45
|
+
readonly statusText: string;
|
|
46
|
+
readonly headers?: HttpHeaders;
|
|
47
|
+
readonly json: () => Promise<unknown>;
|
|
48
|
+
readonly text: () => Promise<string>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface DeepSeekRequestInit {
|
|
52
|
+
readonly method: "POST";
|
|
53
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
54
|
+
readonly body: string;
|
|
55
|
+
readonly signal?: Readonly<AbortSignal>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type DeepSeekFetch = (url: string, init: DeepSeekRequestInit) => Promise<HttpResponse>;
|
|
59
|
+
|
|
60
|
+
export interface RetryProgress {
|
|
61
|
+
readonly attempt: number;
|
|
62
|
+
readonly maxRetries: number;
|
|
63
|
+
readonly status: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface RetryEvent extends RetryProgress {
|
|
67
|
+
readonly delayMs: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export type Sleep = (delayMs: number, signal?: Readonly<AbortSignal>) => Promise<void>;
|
|
71
|
+
|
|
72
|
+
export interface ClientOptions {
|
|
73
|
+
readonly signal?: Readonly<AbortSignal>;
|
|
74
|
+
readonly fetchImpl?: DeepSeekFetch;
|
|
75
|
+
readonly sleep?: Sleep;
|
|
76
|
+
readonly now?: () => number;
|
|
77
|
+
readonly onRetry?: (event: RetryEvent) => void;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface PostDeepSeekJsonOptions extends ClientOptions {
|
|
81
|
+
readonly endpoint: string;
|
|
82
|
+
readonly apiName: ToolApiName;
|
|
83
|
+
readonly apiKey: string;
|
|
84
|
+
readonly body: Readonly<Record<string, JsonPrimitive>>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface ContentFileSystem {
|
|
88
|
+
readonly mkdir: (path: string, options: { readonly recursive: true }) => Promise<void>;
|
|
89
|
+
readonly writeFile: (path: string, data: string, encoding: "utf8") => Promise<void>;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface ContentWrite {
|
|
93
|
+
readonly path: string;
|
|
94
|
+
readonly content: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface ContentOptions {
|
|
98
|
+
readonly tmpdir?: () => string;
|
|
99
|
+
readonly uuid?: () => string;
|
|
100
|
+
readonly fs?: ContentFileSystem;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface ResolvedContentOptions {
|
|
104
|
+
readonly makeTempDir: () => string;
|
|
105
|
+
readonly makeUuid: () => string;
|
|
106
|
+
readonly fileSystem: ContentFileSystem;
|
|
107
|
+
}
|