pi-webapp 0.1.38-alpha.1 → 0.1.38

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,5 @@
1
+ export interface HttpFailureContext { requestId: string; phase: 'headers' | 'body'; proxied: boolean; status?: number }
2
+ export interface EnvironmentFetchOptions { env?: Record<string,string | undefined>; onFailure?: (error: unknown, context: HttpFailureContext) => void; fetchRequest?: typeof globalThis.fetch; autoClose?: boolean }
3
+ export function createEnvironmentFetch(options?: EnvironmentFetchOptions): { fetch: typeof globalThis.fetch; close(): Promise<void> };
4
+ export const environmentFetch: typeof globalThis.fetch;
5
+ export function configureEnvironmentProxy(options?: Pick<EnvironmentFetchOptions,'env' | 'onFailure'>): () => Promise<void>;
@@ -0,0 +1,92 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { channel } from 'node:diagnostics_channel';
3
+ import { EnvHttpProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';
4
+
5
+ const optionsFor = env => ({ httpProxy: env.http_proxy ?? env.HTTP_PROXY ?? env.all_proxy ?? env.ALL_PROXY ?? '', httpsProxy: env.https_proxy ?? env.HTTPS_PROXY ?? env.all_proxy ?? env.ALL_PROXY ?? '', noProxy: env.no_proxy ?? env.NO_PROXY ?? '' });
6
+ function proxyRoute(env, input) {
7
+ const options = optionsFor(env); let url;
8
+ try { url = new URL(typeof input === 'string' || input instanceof URL ? input : input.url); } catch { return false; }
9
+ if (!(url.protocol === 'https:' ? options.httpsProxy || options.httpProxy : options.httpProxy)) return false;
10
+ const noProxy = options.noProxy.toLowerCase(); if (noProxy === '*') return false;
11
+ const port = Number(url.port) || (url.protocol === 'https:' ? 443 : 80), host = url.hostname.toLowerCase();
12
+ return !noProxy.split(/[,\s]/).filter(Boolean).some(entry => {
13
+ const match = entry.match(/^(.+):(\d+)$/), domain = (match?.[1] ?? entry).replace(/^\*?\./, '');
14
+ return (!match || Number(match[2]) === port) && (host === domain || host.endsWith('.' + domain));
15
+ });
16
+ }
17
+ function environmentDispatcher(env) {
18
+ const options = optionsFor(env);
19
+ for (const value of [options.httpProxy, options.httpsProxy].filter(Boolean)) {
20
+ try { if (!['http:', 'https:'].includes(new URL(value).protocol)) throw new Error(); }
21
+ catch { throw Object.assign(new Error('HTTP proxy configuration is invalid or unsupported'), { code: 'PROXY_CONFIGURATION_INVALID' }); }
22
+ }
23
+ return new EnvHttpProxyAgent(options);
24
+ }
25
+ /** A neutral transport seam shared by registry downloads and model adapters.
26
+ * autoClose gives EACH request its own lease, released on body completion,
27
+ * cancellation or failure. Reusing this fetch never reuses an already closed
28
+ * dispatcher. Explicit custom fetches retain ownership of their transport. */
29
+ export function createEnvironmentFetch({ env = process.env, onFailure = () => {}, fetchRequest = globalThis.fetch, autoClose = false } = {}) {
30
+ let shared; const leases = new Set(), managed = fetchRequest === globalThis.fetch;
31
+ const emit = (error, context) => { try { onFailure(error, context); } catch { /* Diagnostics cannot break transport. */ } };
32
+ const release = dispatcher => {
33
+ if (!dispatcher) return Promise.resolve();
34
+ return dispatcher.close().finally(() => leases.delete(dispatcher));
35
+ };
36
+ const fetch = async (input, init) => {
37
+ const context = { requestId: randomUUID(), phase: 'headers', proxied: managed && proxyRoute(env, input) };
38
+ let dispatcher = autoClose ? undefined : shared, settled = false;
39
+ const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
40
+ const aborted = () => settle();
41
+ const settle = () => {
42
+ signal?.removeEventListener('abort', aborted);
43
+ if (!settled && autoClose) { settled = true; void release(dispatcher).catch(() => {}); }
44
+ };
45
+ let response;
46
+ try {
47
+ if (managed) {
48
+ dispatcher ??= environmentDispatcher(env); leases.add(dispatcher); if (!autoClose) shared = dispatcher;
49
+ response = await fetchRequest(input, { ...init, dispatcher });
50
+ } else response = await fetchRequest(input, init);
51
+ } catch (error) { emit(error, context); settle(); throw error; }
52
+ if (!response.ok) emit(undefined, { ...context, status: response.status });
53
+ if (!response.body) { settle(); return response; }
54
+ const reader = response.body.getReader();
55
+ // Abort owns lease cleanup even when the consumer has paused body reads.
56
+ // Native fetch keeps its original AbortError semantics; we do not substitute
57
+ // a clean EOF or manufacture a successful partial download.
58
+ signal?.addEventListener('abort', aborted, { once: true });
59
+ if (signal?.aborted) settle();
60
+ const body = new ReadableStream({
61
+ async pull(controller) {
62
+ try {
63
+ const item = await reader.read();
64
+ if (item.done) { controller.close(); reader.releaseLock(); settle(); } else controller.enqueue(item.value);
65
+ } catch (error) {
66
+ emit(error, { ...context, phase: 'body' }); controller.error(error); reader.releaseLock(); settle();
67
+ }
68
+ },
69
+ async cancel(reason) { try { await reader.cancel(reason); } finally { reader.releaseLock(); settle(); } },
70
+ });
71
+ const wrapped = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
72
+ Object.defineProperties(wrapped, { url: { value: response.url }, redirected: { value: response.redirected }, type: { value: response.type } });
73
+ return wrapped;
74
+ };
75
+ return { fetch, close: async () => { await Promise.all([...leases].map(release)); } };
76
+ }
77
+ /** Production one-shot requests: no installer lifetime/close protocol and no
78
+ * process-global mutation. The response body owns the transport lease. */
79
+ export const environmentFetch = (input, init) => createEnvironmentFetch({ autoClose: true }).fetch(input, init);
80
+
81
+ /** Opt-in process scope for an owned launcher child only. Callers decide how to
82
+ * report failures; this transport knows nothing about models or plugins. */
83
+ export function configureEnvironmentProxy({ env = process.env, onFailure = () => {} } = {}) {
84
+ const previous = getGlobalDispatcher(); let dispatcher;
85
+ try { dispatcher = environmentDispatcher(env); }
86
+ catch (error) { onFailure(error, { requestId: randomUUID(), phase: 'headers', proxied: true }); return async () => {}; }
87
+ setGlobalDispatcher(dispatcher);
88
+ const errors = channel('undici:request:error');
89
+ const receive = ({ error, request }) => { try { onFailure(error, { requestId: randomUUID(), phase: 'headers', proxied: proxyRoute(env, request?.origin) }); } catch {} };
90
+ errors.subscribe(receive);
91
+ return async () => { errors.unsubscribe(receive); if (getGlobalDispatcher() === dispatcher) setGlobalDispatcher(previous); await dispatcher.close(); };
92
+ }
@@ -0,0 +1 @@
1
+ export function observeStopOutcome(activeState: () => Promise<{ nonce?: string } | null>, stopPath: string, nonce: string): Promise<"stopped" | "pending" | "refused">;
@@ -0,0 +1,16 @@
1
+ import { stat } from "node:fs/promises";
2
+
3
+ /** Marker removal is a refusal only while the same owner is still published.
4
+ * Normal exit removes its state first; sample again after observing removal to
5
+ * avoid interpreting a completed teardown as a rejected save/drain.
6
+ */
7
+ export async function observeStopOutcome(activeState, stopPath, nonce) {
8
+ const current = await activeState();
9
+ if (!current || current.nonce !== nonce) return "stopped";
10
+ try { await stat(stopPath); return "pending"; }
11
+ catch (error) {
12
+ if (error.code !== "ENOENT") throw error;
13
+ const latest = await activeState();
14
+ return !latest || latest.nonce !== nonce ? "stopped" : "refused";
15
+ }
16
+ }
@@ -0,0 +1,4 @@
1
+ // Loaded before the SDK only by the managed Pi child. Importing the extension in
2
+ // an existing user TUI never installs global transport configuration.
3
+ import { configureOwnedProcessNetworking } from './model-network.mjs';
4
+ if (process.env.PI_WEBAPP_LAUNCHER_NONCE) configureOwnedProcessNetworking();
@@ -0,0 +1,9 @@
1
+ export interface ModelNetworkDiagnostic {
2
+ errorId: string; requestId: string; operationId?: string;
3
+ stage: 'model_headers' | 'model_stream' | 'model_admission' | 'http_transport';
4
+ kind: 'lifecycle' | 'tls' | 'proxy' | 'timeout' | 'dns' | 'server' | 'http' | 'interrupted' | 'cancelled' | 'network';
5
+ status?: number; proxied: boolean; causes: Array<{ name: string; code?: string }>;
6
+ }
7
+ export function modelNetworkDiagnostic(error: unknown, context?: { stage?: string; requestId?: string; operationId?: string; status?: number; proxied?: boolean }): ModelNetworkDiagnostic;
8
+ export function createModelFetch(options?: { env?: Record<string,string | undefined>; onDiagnostic?: (diagnostic: ModelNetworkDiagnostic) => void; fetchRequest?: typeof globalThis.fetch }): { fetch: typeof globalThis.fetch; close(): Promise<void> };
9
+ export function configureOwnedProcessNetworking(options?: { env?: Record<string,string | undefined>; onDiagnostic?: (diagnostic: ModelNetworkDiagnostic) => void }): () => Promise<void>;
@@ -0,0 +1,46 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createEnvironmentFetch, configureEnvironmentProxy } from './http-transport.mjs';
3
+
4
+ const errorNames = new Set(['Error', 'TypeError', 'RangeError', 'SyntaxError', 'AbortError', 'TimeoutError', 'AggregateError', 'ConnectTimeoutError', 'HeadersTimeoutError', 'BodyTimeoutError', 'SocketError', 'RequestAbortedError', 'InvalidArgumentError', 'ResponseStatusCodeError', 'DOMException']);
5
+ const allowedCode = value => typeof value === 'string' && /^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(value) ? value : undefined;
6
+ /** Rebuild diagnostic fields, never copy native messages (which may contain
7
+ * signed URLs, proxy passwords, request bodies, provider output or user paths). */
8
+ export function modelNetworkDiagnostic(error, context = {}) {
9
+ const causes = []; const seen = new Set();
10
+ const visit = (cause, depth = 0) => {
11
+ if (!cause || depth > 4 || seen.has(cause) || causes.length >= 8) return;
12
+ seen.add(cause);
13
+ const code = allowedCode(cause.code);
14
+ causes.push({ name: errorNames.has(cause.name) ? cause.name : 'Error', ...(code ? { code } : {}) });
15
+ visit(cause.cause, depth + 1);
16
+ if (cause instanceof AggregateError) for (const child of cause.errors.slice(0, 4)) visit(child, depth + 1);
17
+ };
18
+ visit(error);
19
+ const codes = causes.flatMap(item => item.code ? [item.code] : []);
20
+ const kind = context.stage === 'model_admission' || codes.some(code => ['agent_settlement_timeout', 'sdk_capability_missing', 'hosted_admission_blocked'].includes(code)) ? 'lifecycle'
21
+ : codes.some(code => /CERT|TLS|SSL/.test(code)) ? 'tls'
22
+ : codes.some(code => /^PROXY_/.test(code)) || context.proxied && codes.some(code => /ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(code)) ? 'proxy'
23
+ : codes.some(code => /TIMEOUT|ETIMEDOUT/.test(code)) || causes.some(item => /TimeoutError$/.test(item.name)) ? 'timeout'
24
+ : causes.some(item => item.name === 'AbortError' || item.code === 'ABORT_ERR' || item.code === 'UND_ERR_ABORTED') ? 'cancelled'
25
+ : codes.some(code => /ENOTFOUND|EAI_AGAIN/.test(code)) ? 'dns'
26
+ : context.status >= 500 ? 'server'
27
+ : context.status >= 400 ? 'http'
28
+ : context.stage === 'model_stream' ? 'interrupted'
29
+ : 'network';
30
+ const id = value => typeof value === 'string' && /^[\w-]{1,80}$/.test(value) ? value : undefined;
31
+ return { errorId: randomUUID(), requestId: id(context.requestId) ?? randomUUID(), ...(id(context.operationId) ? { operationId: context.operationId } : {}),
32
+ stage: ['model_headers', 'model_stream', 'model_admission', 'http_transport'].includes(context.stage) ? context.stage : 'model_headers', kind,
33
+ ...(Number.isInteger(context.status) ? { status: context.status } : {}), proxied: context.proxied === true, causes };
34
+ }
35
+ /** Model-specific diagnosis decorates the generic HTTP transport. Registry
36
+ * download code never imports or depends on model telemetry. */
37
+ export function createModelFetch({ env = process.env, onDiagnostic = () => {}, fetchRequest = globalThis.fetch } = {}) {
38
+ return createEnvironmentFetch({ env, fetchRequest, onFailure: (error, context) => onDiagnostic(modelNetworkDiagnostic(error, {
39
+ ...context, stage: context.phase === 'body' ? 'model_stream' : 'model_headers',
40
+ })) });
41
+ }
42
+ /** Owned launcher process only. An extension must not change a parent TUI's
43
+ * global dispatcher; independently created web sessions use createModelFetch. */
44
+ export function configureOwnedProcessNetworking({ env = process.env, onDiagnostic = diagnostic => console.error(JSON.stringify({ event: 'http_transport_failure', ...diagnostic })) } = {}) {
45
+ return configureEnvironmentProxy({ env, onFailure: (error, context) => onDiagnostic(modelNetworkDiagnostic(error, { ...context, stage: 'http_transport' })) });
46
+ }
package/bin/pi-webapp.mjs CHANGED
@@ -10,6 +10,7 @@ import spawn from "cross-spawn";
10
10
  import { openWebPage } from "./open-web-page.mjs";
11
11
  import { npmCommand } from "./npm-command.mjs";
12
12
  import { packagePiCli } from "./package-pi-cli.mjs";
13
+ import { observeStopOutcome } from "./launcher-state.mjs";
13
14
  import { compareVersions, parseVersion } from "../desktop/release-version.mjs";
14
15
  import { desktopProtocolVersion, desktopUpdatePath, readDesktopRelease, rollbackDesktopRelease } from "../desktop/managed-release.mjs";
15
16
 
@@ -126,7 +127,7 @@ async function serve(pi, args) {
126
127
  const pluginRoots = (process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS ?? "").split(delimiter).filter(Boolean).map((root) => resolve(root));
127
128
  const piPrefix = process.env.PI_WEBAPP_PI_CLI ? [resolve(process.env.PI_WEBAPP_PI_CLI)] : [];
128
129
  const child = spawn(pi, [...piPrefix, "--mode", "rpc", "-e", extension, ...pluginRoots.flatMap((root) => ["-e", root]), ...args], {
129
- cwd: process.cwd(), env: { ...process.env, PI_WEBAPP_AUTO_OPEN: "0", PI_WEBAPP_LAUNCHER_NONCE: nonce }, stdio: ["pipe", "pipe", "pipe"],
130
+ cwd: process.cwd(), env: { ...process.env, NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --import=${JSON.stringify(new URL("./model-network-bootstrap.mjs", import.meta.url).href)}`.trim(), PI_WEBAPP_AUTO_OPEN: "0", PI_WEBAPP_LAUNCHER_NONCE: nonce }, stdio: ["pipe", "pipe", "pipe"],
130
131
  });
131
132
  child.stderr?.pipe(process.stderr, { end: false });
132
133
  let ready = false;
@@ -337,11 +338,11 @@ async function serve(pi, args) {
337
338
  for (const watcher of devWatchers) watcher.close();
338
339
  clearInterval(stopTimer);
339
340
  clearTimeout(killTimer);
340
- try { if ((await readFile(stopPath, "utf8")).trim() === nonce) await unlink(stopPath); } catch { /* Already removed. */ }
341
341
  if (claimed) {
342
342
  try { if (JSON.parse(await readFile(statePath, "utf8")).nonce === nonce) await unlink(statePath); }
343
343
  catch { /* Already removed. */ }
344
344
  }
345
+ try { if ((await readFile(stopPath, "utf8")).trim() === nonce) await unlink(stopPath); } catch { /* Already removed. */ }
345
346
  if (restartRequest && runningUrl) {
346
347
  await unlink(restartPath).catch(() => {});
347
348
  const oldUrl = new URL(runningUrl);
@@ -468,10 +469,9 @@ async function stop() {
468
469
  await writeFile(stopPath, state.nonce, { mode: 0o600 });
469
470
  for (let attempt = 0; attempt < 400; attempt++) {
470
471
  await new Promise((resolveWait) => setTimeout(resolveWait, 100));
471
- const current = await activeState();
472
- if (!current || current.nonce !== state.nonce) { console.log("pi-webapp 已停止"); return; }
473
- try { await stat(stopPath); }
474
- catch (error) { if (error?.code === "ENOENT") throw new Error("停止已取消:插件保存或释放未完成,服务及数据已保留。请处理插件诊断后重试。"); throw error; }
472
+ const outcome = await observeStopOutcome(activeState, stopPath, state.nonce);
473
+ if (outcome === "stopped") { console.log("pi-webapp 已停止"); return; }
474
+ if (outcome === "refused") throw new Error("停止已取消:插件保存或释放未完成,服务及数据已保留。请处理插件诊断后重试。");
475
475
  }
476
476
  throw new Error(`停止超时。后台进程 PID:${state.pid};日志:${logPath}`);
477
477
  }