@skyphusion/create-prism 0.1.0 → 1.0.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/README.md +5 -3
- package/index.js +4 -2
- package/package.json +1 -1
- package/template/CONTRIBUTING.md +6 -2
- package/template/README.md +227 -48
- package/template/docs/legal/README.md +1 -0
- package/template/migrations/0002_auth_public_mode.sql +32 -0
- package/template/migrations/0003_conversation_compact.sql +24 -0
- package/template/package.json +6 -6
- package/template/public/app.js +128 -19
- package/template/public/index.html +50 -4
- package/template/public/styles.css +16 -2
- package/template/schema.sql +17 -0
- package/template/src/auth-kdf.ts +7 -4
- package/template/src/auth.ts +11 -2
- package/template/src/control-plane.ts +254 -0
- package/template/src/conversation-context.ts +126 -0
- package/template/src/env.ts +15 -0
- package/template/src/gateway-credentials.ts +23 -4
- package/template/src/health-schema.ts +4 -0
- package/template/src/index.ts +73 -3982
- package/template/src/longrun-params.ts +4 -2
- package/template/src/models.ts +65 -19
- package/template/src/output-extract.ts +58 -8
- package/template/src/parsers/openai-sse.ts +43 -14
- package/template/src/providers/anthropic.ts +105 -0
- package/template/src/providers/openai-image.ts +66 -0
- package/template/src/providers/openai.ts +79 -13
- package/template/src/providers/xai.ts +91 -0
- package/template/src/proxied-image-params.ts +29 -16
- package/template/src/routes/artifacts.ts +51 -0
- package/template/src/routes/chat.ts +1682 -0
- package/template/src/routes/conversations.ts +494 -0
- package/template/src/routes/documents.ts +262 -0
- package/template/src/routes/health.ts +105 -0
- package/template/src/routes/history.ts +92 -0
- package/template/src/routes/prefs.ts +95 -0
- package/template/src/routes/projects.ts +574 -0
- package/template/src/routes/rag.ts +657 -0
- package/template/src/routes/shared.ts +226 -0
- package/template/src/routes/workflow.ts +304 -0
- package/template/src/stt-session.ts +1 -1
- package/template/src/user-prefs.ts +10 -0
- package/template/src/zip.ts +7 -0
- package/template/tests/anthropic-binding.test.ts +181 -0
- package/template/tests/control-plane.test.ts +112 -0
- package/template/tests/conversation-compact.test.ts +103 -0
- package/template/tests/gateway-credentials.test.ts +37 -0
- package/template/tests/longrun-params.test.ts +19 -0
- package/template/tests/openai-image.test.ts +47 -0
- package/template/tests/openai-responses.test.ts +78 -0
- package/template/tests/openai-sse.test.ts +28 -0
- package/template/tests/output-extract.test.ts +75 -1
- package/template/tests/proxied-image-params.test.ts +16 -7
- package/template/tests/sprint1-catalog.test.ts +27 -0
- package/template/tests/sprint2-catalog.test.ts +51 -0
- package/template/tests/sprint3-catalog.test.ts +29 -0
- package/template/tests/xai-binding.test.ts +127 -0
- package/template/tests-integration/worker.test.ts +9 -2
- package/template/wrangler.example.toml +19 -7
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
// HTTP client for prism-control-plane (play-proxy).
|
|
2
|
+
//
|
|
3
|
+
// When a user configures a pcp_ client key, chat bills through the metered proxy
|
|
4
|
+
// instead of the user's own AI Gateway (BYOK). The base URL is NOT user-chosen
|
|
5
|
+
// (SSRF): only an allowlisted host from worker config / default, never prefs.
|
|
6
|
+
//
|
|
7
|
+
// Contract: skyphusion-labs/prism-control-plane docs/CONTRACT.md
|
|
8
|
+
|
|
9
|
+
import type { Env } from "./env";
|
|
10
|
+
import type { UserPrefsJson } from "./user-prefs";
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_CONTROL_PLANE_URL = "https://play-proxy.skyphusion.org";
|
|
13
|
+
|
|
14
|
+
/** Exact hostnames the worker may call for control-plane inference. */
|
|
15
|
+
export const CONTROL_PLANE_ALLOWED_HOSTS: readonly string[] = [
|
|
16
|
+
"play-proxy.skyphusion.org",
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
export interface ControlPlaneCredentials {
|
|
20
|
+
baseUrl: string;
|
|
21
|
+
clientKey: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Shape-check a pcp_ client key without hitting the network. */
|
|
25
|
+
export function looksLikeClientKey(raw: string): boolean {
|
|
26
|
+
// pcp_ + 16 hex + _ + 43 base64url (matches control-plane parseClientKey)
|
|
27
|
+
return /^pcp_[0-9a-f]{16}_[A-Za-z0-9_-]{43}$/.test(raw.trim());
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Strip trailing slashes without a regex (CodeQL js/polynomial-redos on /\/+$/). */
|
|
31
|
+
export function stripTrailingSlashes(s: string): string {
|
|
32
|
+
let end = s.length;
|
|
33
|
+
while (end > 0 && s.charCodeAt(end - 1) === 47 /* / */) end -= 1;
|
|
34
|
+
return s.slice(0, end);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Parse and allowlist a control-plane origin.
|
|
39
|
+
* Returns canonical `https://host` or null (refuse everything else).
|
|
40
|
+
*
|
|
41
|
+
* SSRF guard: only CONTROL_PLANE_ALLOWED_HOSTS (plus optional localhost when
|
|
42
|
+
* CONTROL_PLANE_ALLOW_LOCALHOST=true for local wrangler dev).
|
|
43
|
+
*/
|
|
44
|
+
export function allowlistedControlPlaneOrigin(
|
|
45
|
+
raw: string,
|
|
46
|
+
opts?: { allowLocalhost?: boolean },
|
|
47
|
+
): string | null {
|
|
48
|
+
const trimmed = raw.trim();
|
|
49
|
+
if (!trimmed || trimmed.length > 256) return null;
|
|
50
|
+
let url: URL;
|
|
51
|
+
try {
|
|
52
|
+
url = new URL(trimmed);
|
|
53
|
+
} catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
if (url.protocol !== "https:" && !(opts?.allowLocalhost && url.protocol === "http:")) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
if (url.username || url.password) return null;
|
|
60
|
+
if (url.search || url.hash) return null;
|
|
61
|
+
// Only origin path: empty or single slash.
|
|
62
|
+
if (url.pathname !== "/" && url.pathname !== "") return null;
|
|
63
|
+
if (url.port && url.port !== "443" && !(opts?.allowLocalhost && url.port === "8787")) {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const host = url.hostname.toLowerCase();
|
|
68
|
+
const allowed = new Set(CONTROL_PLANE_ALLOWED_HOSTS);
|
|
69
|
+
if (opts?.allowLocalhost) {
|
|
70
|
+
allowed.add("localhost");
|
|
71
|
+
allowed.add("127.0.0.1");
|
|
72
|
+
}
|
|
73
|
+
if (!allowed.has(host)) return null;
|
|
74
|
+
|
|
75
|
+
if (opts?.allowLocalhost && (host === "localhost" || host === "127.0.0.1")) {
|
|
76
|
+
const port = url.port ? `:${url.port}` : "";
|
|
77
|
+
return `${url.protocol}//${host}${port}`;
|
|
78
|
+
}
|
|
79
|
+
return `https://${host}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Resolve control-plane credentials.
|
|
84
|
+
* URL comes from env (or default allowlisted host), NEVER from user prefs.
|
|
85
|
+
*/
|
|
86
|
+
export function resolveControlPlane(
|
|
87
|
+
prefs: UserPrefsJson | null,
|
|
88
|
+
env?: Pick<Env, "CONTROL_PLANE_URL" | "CONTROL_PLANE_ALLOW_LOCALHOST">,
|
|
89
|
+
): ControlPlaneCredentials | null {
|
|
90
|
+
const key = prefs?.control_plane_key?.trim() || "";
|
|
91
|
+
if (!key || !looksLikeClientKey(key)) return null;
|
|
92
|
+
|
|
93
|
+
const allowLocalhost = (env?.CONTROL_PLANE_ALLOW_LOCALHOST ?? "").trim() === "true";
|
|
94
|
+
const configured = (env?.CONTROL_PLANE_URL ?? "").trim() || DEFAULT_CONTROL_PLANE_URL;
|
|
95
|
+
const base = allowlistedControlPlaneOrigin(configured, { allowLocalhost });
|
|
96
|
+
if (!base) return null;
|
|
97
|
+
return { baseUrl: base, clientKey: key };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface ControlPlaneChatMessage {
|
|
101
|
+
role: "system" | "user" | "assistant";
|
|
102
|
+
content: string;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface ControlPlaneChatResult {
|
|
106
|
+
text: string;
|
|
107
|
+
model: string;
|
|
108
|
+
usage: { prompt_tokens: number | null; completion_tokens: number | null };
|
|
109
|
+
requestId: string | null;
|
|
110
|
+
raw: unknown;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function authHeaders(cp: ControlPlaneCredentials): HeadersInit {
|
|
114
|
+
return {
|
|
115
|
+
authorization: `Bearer ${cp.clientKey}`,
|
|
116
|
+
"content-type": "application/json",
|
|
117
|
+
accept: "application/json",
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Build a fixed path under the allowlisted origin (no user path injection). */
|
|
122
|
+
export function controlPlaneUrl(cp: ControlPlaneCredentials, path: "/v1/chat/completions" | "/v1/models" | "/v1/me"): string {
|
|
123
|
+
return `${cp.baseUrl}${path}`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Non-streaming chat completion against the control plane.
|
|
128
|
+
* Throws Error with optional .status / .code for API failures.
|
|
129
|
+
*/
|
|
130
|
+
export async function controlPlaneChat(
|
|
131
|
+
cp: ControlPlaneCredentials,
|
|
132
|
+
args: {
|
|
133
|
+
model: string;
|
|
134
|
+
messages: ControlPlaneChatMessage[];
|
|
135
|
+
max_tokens?: number;
|
|
136
|
+
temperature?: number;
|
|
137
|
+
},
|
|
138
|
+
fetchImpl: typeof fetch = fetch,
|
|
139
|
+
): Promise<ControlPlaneChatResult> {
|
|
140
|
+
// Defense in depth: re-allowlist before fetch (credentials must already be clean).
|
|
141
|
+
if (!allowlistedControlPlaneOrigin(cp.baseUrl, { allowLocalhost: true })) {
|
|
142
|
+
throw new Error("control-plane base URL is not allowlisted");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const res = await fetchImpl(controlPlaneUrl(cp, "/v1/chat/completions"), {
|
|
146
|
+
method: "POST",
|
|
147
|
+
headers: authHeaders(cp),
|
|
148
|
+
body: JSON.stringify({
|
|
149
|
+
model: args.model,
|
|
150
|
+
messages: args.messages,
|
|
151
|
+
...(args.max_tokens !== undefined ? { max_tokens: args.max_tokens } : {}),
|
|
152
|
+
...(args.temperature !== undefined ? { temperature: args.temperature } : {}),
|
|
153
|
+
stream: false,
|
|
154
|
+
}),
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
const requestId = res.headers.get("prism-request-id");
|
|
158
|
+
let body: unknown;
|
|
159
|
+
try {
|
|
160
|
+
body = await res.json();
|
|
161
|
+
} catch {
|
|
162
|
+
const err = new Error(`control-plane: unparseable body (HTTP ${res.status})`) as Error & {
|
|
163
|
+
status?: number;
|
|
164
|
+
};
|
|
165
|
+
err.status = res.status;
|
|
166
|
+
throw err;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (!res.ok) {
|
|
170
|
+
const errObj = body as { error?: { message?: string; code?: string } };
|
|
171
|
+
const msg =
|
|
172
|
+
errObj?.error?.message ||
|
|
173
|
+
(typeof body === "object" && body && "error" in body
|
|
174
|
+
? String((body as { error: unknown }).error)
|
|
175
|
+
: `control-plane HTTP ${res.status}`);
|
|
176
|
+
const err = new Error(msg) as Error & { status?: number; code?: string };
|
|
177
|
+
err.status = res.status;
|
|
178
|
+
err.code = errObj?.error?.code;
|
|
179
|
+
throw err;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const text = extractChatText(body);
|
|
183
|
+
const usageRaw = (body as { usage?: Record<string, unknown> })?.usage;
|
|
184
|
+
return {
|
|
185
|
+
text,
|
|
186
|
+
model: String((body as { model?: string })?.model || args.model),
|
|
187
|
+
usage: {
|
|
188
|
+
prompt_tokens: intOrNull(usageRaw?.prompt_tokens ?? usageRaw?.input_tokens),
|
|
189
|
+
completion_tokens: intOrNull(usageRaw?.completion_tokens ?? usageRaw?.output_tokens),
|
|
190
|
+
},
|
|
191
|
+
requestId,
|
|
192
|
+
raw: body,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** List models the caller may use (plan-filtered, with prices). */
|
|
197
|
+
export async function controlPlaneListModels(
|
|
198
|
+
cp: ControlPlaneCredentials,
|
|
199
|
+
fetchImpl: typeof fetch = fetch,
|
|
200
|
+
): Promise<unknown> {
|
|
201
|
+
if (!allowlistedControlPlaneOrigin(cp.baseUrl, { allowLocalhost: true })) {
|
|
202
|
+
throw new Error("control-plane base URL is not allowlisted");
|
|
203
|
+
}
|
|
204
|
+
const res = await fetchImpl(controlPlaneUrl(cp, "/v1/models"), {
|
|
205
|
+
method: "GET",
|
|
206
|
+
headers: {
|
|
207
|
+
authorization: `Bearer ${cp.clientKey}`,
|
|
208
|
+
accept: "application/json",
|
|
209
|
+
},
|
|
210
|
+
});
|
|
211
|
+
if (!res.ok) {
|
|
212
|
+
const detail = (await res.text()).slice(0, 200);
|
|
213
|
+
throw new Error(`control-plane /v1/models HTTP ${res.status}${detail ? `: ${detail}` : ""}`);
|
|
214
|
+
}
|
|
215
|
+
return res.json();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Account/plan/usage snapshot. */
|
|
219
|
+
export async function controlPlaneMe(
|
|
220
|
+
cp: ControlPlaneCredentials,
|
|
221
|
+
fetchImpl: typeof fetch = fetch,
|
|
222
|
+
): Promise<unknown> {
|
|
223
|
+
if (!allowlistedControlPlaneOrigin(cp.baseUrl, { allowLocalhost: true })) {
|
|
224
|
+
throw new Error("control-plane base URL is not allowlisted");
|
|
225
|
+
}
|
|
226
|
+
const res = await fetchImpl(controlPlaneUrl(cp, "/v1/me"), {
|
|
227
|
+
method: "GET",
|
|
228
|
+
headers: {
|
|
229
|
+
authorization: `Bearer ${cp.clientKey}`,
|
|
230
|
+
accept: "application/json",
|
|
231
|
+
},
|
|
232
|
+
});
|
|
233
|
+
if (!res.ok) {
|
|
234
|
+
throw new Error(`control-plane /v1/me HTTP ${res.status}`);
|
|
235
|
+
}
|
|
236
|
+
return res.json();
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function extractChatText(body: unknown): string {
|
|
240
|
+
if (!body || typeof body !== "object") return "";
|
|
241
|
+
const o = body as Record<string, unknown>;
|
|
242
|
+
const choices = o.choices;
|
|
243
|
+
if (Array.isArray(choices) && choices[0] && typeof choices[0] === "object") {
|
|
244
|
+
const msg = (choices[0] as { message?: { content?: unknown } }).message;
|
|
245
|
+
if (msg && typeof msg.content === "string") return msg.content;
|
|
246
|
+
}
|
|
247
|
+
if (typeof o.response === "string") return o.response;
|
|
248
|
+
if (typeof o.result === "string") return o.result;
|
|
249
|
+
return "";
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function intOrNull(v: unknown): number | null {
|
|
253
|
+
return typeof v === "number" && Number.isFinite(v) ? Math.trunc(v) : null;
|
|
254
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Conversation context for multi-turn chat: prior turns + optional compact
|
|
2
|
+
// summary (v0.175.7). Pure helpers live here so chat routes and the compact
|
|
3
|
+
// endpoint share one assembly rule, and so unit tests cover it without D1.
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_KEEP_RECENT = 2;
|
|
6
|
+
/** Soft cap on stored / injected summary text (chars). */
|
|
7
|
+
export const COMPACT_SUMMARY_MAX_CHARS = 12_000;
|
|
8
|
+
/** Minimum completed chat turns before compact is useful (keep_recent + 1). */
|
|
9
|
+
export const MIN_TURNS_TO_COMPACT = DEFAULT_KEEP_RECENT + 1;
|
|
10
|
+
|
|
11
|
+
export type ChatTurnRow = {
|
|
12
|
+
user_input: string;
|
|
13
|
+
output: string;
|
|
14
|
+
turn_index: number;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type ConversationCompactState = {
|
|
18
|
+
summary: string;
|
|
19
|
+
through_turn_index: number;
|
|
20
|
+
keep_recent: number;
|
|
21
|
+
model: string;
|
|
22
|
+
updated_at: string;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type PriorContext = {
|
|
26
|
+
/** Raw user/assistant pairs to put on the wire after any compact block. */
|
|
27
|
+
priorTurns: Array<{ user_input: string; output: string }>;
|
|
28
|
+
/** Next turn_index for persistChat. */
|
|
29
|
+
turnIndex: number;
|
|
30
|
+
/** System-prompt block for compacted earlier turns, or null. */
|
|
31
|
+
compactBlock: string | null;
|
|
32
|
+
compact: ConversationCompactState | null;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Split turns into those summarized vs kept raw. */
|
|
36
|
+
export function splitTurnsForCompact(
|
|
37
|
+
turns: ChatTurnRow[],
|
|
38
|
+
keepRecent: number,
|
|
39
|
+
): { summarize: ChatTurnRow[]; keep: ChatTurnRow[] } {
|
|
40
|
+
const k = Math.max(0, Math.floor(keepRecent));
|
|
41
|
+
if (turns.length === 0) return { summarize: [], keep: [] };
|
|
42
|
+
if (k === 0) return { summarize: turns.slice(), keep: [] };
|
|
43
|
+
if (turns.length <= k) return { summarize: [], keep: turns.slice() };
|
|
44
|
+
return {
|
|
45
|
+
summarize: turns.slice(0, turns.length - k),
|
|
46
|
+
keep: turns.slice(turns.length - k),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Flatten turns into a plain transcript the summarizer model can read. */
|
|
51
|
+
export function formatTurnsForSummary(turns: ChatTurnRow[]): string {
|
|
52
|
+
const parts: string[] = [];
|
|
53
|
+
for (const t of turns) {
|
|
54
|
+
const u = (t.user_input ?? "").trim();
|
|
55
|
+
const a = (t.output ?? "").trim();
|
|
56
|
+
if (!u && !a) continue;
|
|
57
|
+
parts.push(`User:\n${u || "(empty)"}\n\nAssistant:\n${a || "(empty)"}`);
|
|
58
|
+
}
|
|
59
|
+
return parts.join("\n\n---\n\n");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** System-prompt block injected when a conversation is compacted. */
|
|
63
|
+
export function buildCompactSystemBlock(summary: string): string {
|
|
64
|
+
const s = summary.trim();
|
|
65
|
+
if (!s) return "";
|
|
66
|
+
return (
|
|
67
|
+
"[Compacted earlier conversation]\n" +
|
|
68
|
+
"The following is a summary of earlier turns in this thread. Treat it as " +
|
|
69
|
+
"authoritative context. Recent turns (if any) follow as normal messages.\n\n" +
|
|
70
|
+
s +
|
|
71
|
+
"\n\n[End compacted context]"
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Apply compact state to a full ordered turn list.
|
|
77
|
+
* - priorTurns: only turns AFTER through_turn_index (raw recent context)
|
|
78
|
+
* - compactBlock: summary system block when state is present
|
|
79
|
+
* - turnIndex: max(turn_index)+1 or 0
|
|
80
|
+
*/
|
|
81
|
+
export function applyCompactToPriorTurns(
|
|
82
|
+
allTurns: ChatTurnRow[],
|
|
83
|
+
state: ConversationCompactState | null,
|
|
84
|
+
): PriorContext {
|
|
85
|
+
const usable = allTurns.filter((t) => t.user_input && t.output);
|
|
86
|
+
// Next index must clear every stored turn_index, including empty/failed rows
|
|
87
|
+
// that were filtered out of the wire history.
|
|
88
|
+
const turnIndex = allTurns.length
|
|
89
|
+
? Math.max(...allTurns.map((t) => t.turn_index)) + 1
|
|
90
|
+
: 0;
|
|
91
|
+
|
|
92
|
+
if (!state?.summary?.trim()) {
|
|
93
|
+
return {
|
|
94
|
+
priorTurns: usable.map((t) => ({ user_input: t.user_input, output: t.output })),
|
|
95
|
+
turnIndex,
|
|
96
|
+
compactBlock: null,
|
|
97
|
+
compact: null,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const through = state.through_turn_index;
|
|
102
|
+
const recent = usable.filter((t) => t.turn_index > through);
|
|
103
|
+
const block = buildCompactSystemBlock(state.summary);
|
|
104
|
+
return {
|
|
105
|
+
priorTurns: recent.map((t) => ({ user_input: t.user_input, output: t.output })),
|
|
106
|
+
turnIndex,
|
|
107
|
+
compactBlock: block || null,
|
|
108
|
+
compact: state,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Clamp and normalize a model-produced summary for storage / injection. */
|
|
113
|
+
export function normalizeSummary(raw: string): string {
|
|
114
|
+
let s = (raw ?? "").trim();
|
|
115
|
+
if (s.length > COMPACT_SUMMARY_MAX_CHARS) {
|
|
116
|
+
s = s.slice(0, COMPACT_SUMMARY_MAX_CHARS) + "\n[summary truncated]";
|
|
117
|
+
}
|
|
118
|
+
return s;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export const COMPACT_SYSTEM_PROMPT =
|
|
122
|
+
"You compress multi-turn chat history into a continuity brief for another " +
|
|
123
|
+
"assistant that will continue the conversation. Preserve: decisions, facts, " +
|
|
124
|
+
"names, constraints, open questions, and anything the user asked to remember. " +
|
|
125
|
+
"Drop chit-chat and repeated boilerplate. Write in neutral third person or " +
|
|
126
|
+
"tight bullet form. No preamble like 'Here is a summary'.";
|
package/template/src/env.ts
CHANGED
|
@@ -25,6 +25,8 @@ export interface Env {
|
|
|
25
25
|
// Email) and keep worker-secret gateway fallback for private self-host.
|
|
26
26
|
// A var, not a secret; set it in wrangler.toml [vars].
|
|
27
27
|
AUTH_MODE?: string;
|
|
28
|
+
/** access mode only: set to "1" to allow anonymous when Access header is absent (local dev). */
|
|
29
|
+
ACCESS_ALLOW_ANONYMOUS?: string;
|
|
28
30
|
GATEWAY_ID?: string;
|
|
29
31
|
// v0.164.0: optional on the worker when running in public demo mode; each
|
|
30
32
|
// user may store their own gateway slug in D1 user_prefs instead.
|
|
@@ -42,6 +44,19 @@ export interface Env {
|
|
|
42
44
|
// sent as cf-aig-authorization. Also used when Authenticated Gateway is on.
|
|
43
45
|
// v0.164.0: optional on the worker in public demo mode (per-user token in D1).
|
|
44
46
|
CF_AIG_TOKEN?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Optional origin for prism-control-plane (default https://play-proxy.skyphusion.org).
|
|
49
|
+
* Must be an allowlisted host; user prefs cannot override (SSRF).
|
|
50
|
+
*/
|
|
51
|
+
CONTROL_PLANE_URL?: string;
|
|
52
|
+
/** Set to "true" to allow http://localhost for local wrangler + local control-plane. */
|
|
53
|
+
CONTROL_PLANE_ALLOW_LOCALHOST?: string;
|
|
54
|
+
// Optional. Sole deployer BYOK exception (v0.174.0 restore of the v0.22.1
|
|
55
|
+
// path): when set, openai/gpt-image-* go direct to api.openai.com for
|
|
56
|
+
// transparent PNG (background + output_format). When unset, those models
|
|
57
|
+
// stay on Unified Billing and render opaque. No other provider reads a
|
|
58
|
+
// deployer key.
|
|
59
|
+
OPENAI_API_KEY?: string;
|
|
45
60
|
// v0.166.0: base URL of the self-hosted SearXNG instance for the optional
|
|
46
61
|
// web-search retrieval source (our deploy: https://search.skyphusion.org).
|
|
47
62
|
// Optional: when unset, the SearXNG source is silently skipped (Wikipedia,
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
// as absent: source is only ever "user" or "none", never "worker"/"mixed".
|
|
15
15
|
|
|
16
16
|
import type { Env } from "./env";
|
|
17
|
+
import { resolveControlPlane } from "./control-plane";
|
|
17
18
|
import { loadUserPrefs, type UserPrefsJson } from "./user-prefs";
|
|
18
19
|
|
|
19
20
|
export interface GatewayCredentials {
|
|
@@ -24,14 +25,21 @@ export interface GatewayCredentials {
|
|
|
24
25
|
export type GatewaySource = "user" | "worker" | "mixed" | "none";
|
|
25
26
|
|
|
26
27
|
export interface GatewayStatus {
|
|
28
|
+
/**
|
|
29
|
+
* True when the user can run inference: AI Gateway BYOK (gateway id) and/or
|
|
30
|
+
* a control-plane pcp_ key. SPA boot (GET /api/models) uses this to hide the
|
|
31
|
+
* "configure instance" banner -- pcp-only accounts must count as configured.
|
|
32
|
+
*/
|
|
27
33
|
configured: boolean;
|
|
28
34
|
source: GatewaySource;
|
|
29
35
|
gateway_id: string | null;
|
|
30
36
|
cf_aig_token_set: boolean;
|
|
37
|
+
control_plane_configured: boolean;
|
|
38
|
+
control_plane_key_set: boolean;
|
|
31
39
|
}
|
|
32
40
|
|
|
33
41
|
export const GATEWAY_NOT_CONFIGURED_MSG =
|
|
34
|
-
"
|
|
42
|
+
"Inference not configured. Open Account > AI Gateway and either (1) enter your Cloudflare gateway slug + API token (BYOK), or (2) paste a prism-control-plane client key (pcp_…) to bill chat through play-proxy.";
|
|
35
43
|
|
|
36
44
|
export const CF_AIG_TOKEN_REQUIRED_MSG =
|
|
37
45
|
"This model requires a Cloudflare API token with AI Gateway Run permission. Add it under Account > AI Gateway.";
|
|
@@ -78,17 +86,28 @@ export async function loadGatewayCredentials(
|
|
|
78
86
|
return resolveGatewayFromParts(prefs, env);
|
|
79
87
|
}
|
|
80
88
|
|
|
81
|
-
|
|
82
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Build the UI/boot inference status from already-loaded prefs (no DB).
|
|
91
|
+
* Control-plane pcp_ keys count as configured even with no gateway slug.
|
|
92
|
+
*/
|
|
93
|
+
export function buildGatewayStatus(prefs: UserPrefsJson | null, env: Env): GatewayStatus {
|
|
83
94
|
const resolved = resolveGatewayFromParts(prefs, env);
|
|
95
|
+
const cp = resolveControlPlane(prefs, env);
|
|
84
96
|
return {
|
|
85
|
-
configured: !!resolved?.gatewayId,
|
|
97
|
+
configured: !!resolved?.gatewayId || !!cp,
|
|
86
98
|
source: gatewaySource(prefs, env),
|
|
87
99
|
gateway_id: resolved?.gatewayId ?? null,
|
|
88
100
|
cf_aig_token_set: !!(resolved?.cfAigToken),
|
|
101
|
+
control_plane_configured: !!cp,
|
|
102
|
+
control_plane_key_set: !!prefs?.control_plane_key?.trim(),
|
|
89
103
|
};
|
|
90
104
|
}
|
|
91
105
|
|
|
106
|
+
export async function loadGatewayStatus(env: Env, userEmail: string): Promise<GatewayStatus> {
|
|
107
|
+
const prefs = await loadUserPrefs(env.DB, userEmail);
|
|
108
|
+
return buildGatewayStatus(prefs, env);
|
|
109
|
+
}
|
|
110
|
+
|
|
92
111
|
export function maskSecret(value: string | undefined): string | null {
|
|
93
112
|
if (!value?.trim()) return null;
|
|
94
113
|
const v = value.trim();
|
|
@@ -10,6 +10,10 @@ export const REQUIRED_D1_TABLES = [
|
|
|
10
10
|
"project_documents",
|
|
11
11
|
"project_messages",
|
|
12
12
|
"user_prefs",
|
|
13
|
+
// Public-mode auth (v0.167.0 / migration 0002). Missing these makes signup 500.
|
|
14
|
+
"users",
|
|
15
|
+
"sessions",
|
|
16
|
+
"auth_attempts",
|
|
13
17
|
] as const;
|
|
14
18
|
|
|
15
19
|
export async function probeD1Schema(db: D1Database): Promise<{ ok: boolean; missing: string[] }> {
|