File size: 3,951 Bytes
d02c2a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import { apiClient } from './api';

export type ScriptArgs = (string | number | boolean)[] | Record<string, string | number | boolean | null | undefined>;

export interface ScriptResult {
  ok: boolean;
  exitCode: number | null;
  signal: string | null;
  stdout: string;
  stderr: string;
  result: unknown;
  timedOut: boolean;
  error?: string;
}

export interface StreamEvent {
  type: 'stdout' | 'stderr' | 'exit' | 'error';
  data?: string;
  message?: string;
  exitCode?: number | null;
  signal?: string | null;
  ok?: boolean;
  timedOut?: boolean;
  result?: unknown;
  stderr?: string;
}

export interface CallScriptOptions {
  args?: ScriptArgs;
  signal?: AbortSignal;
  // Match the API's 20-minute ceiling by default so axios doesn't bail early.
  timeoutMs?: number;
}

export interface StreamCallScriptOptions extends CallScriptOptions {
  onEvent?: (event: StreamEvent) => void;
  onStdout?: (chunk: string) => void;
  onStderr?: (chunk: string) => void;
}

const DEFAULT_TIMEOUT_MS = 20 * 60 * 1000;

// Buffered call: resolves with full stdout/stderr after the script exits.
export const callScript = async (
  script: string,
  options: CallScriptOptions = {},
): Promise<ScriptResult> => {
  const response = await apiClient.post<ScriptResult>(
    '/api/scripts',
    { script, args: options.args },
    {
      timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
      signal: options.signal,
      // Don't throw on non-2xx so callers can inspect the structured failure.
      validateStatus: () => true,
    },
  );
  return response.data;
};

// Streaming call: invokes the callbacks for each NDJSON event as it arrives,
// then resolves with the final exit event.
export const callScriptStream = async (
  script: string,
  options: StreamCallScriptOptions = {},
): Promise<StreamEvent | null> => {
  const token = typeof window !== 'undefined' ? localStorage.getItem('AI_TOOLKIT_AUTH') : null;
  const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  if (token) headers['Authorization'] = `Bearer ${token}`;

  const controller = new AbortController();
  const onAbort = () => controller.abort();
  if (options.signal) {
    if (options.signal.aborted) controller.abort();
    else options.signal.addEventListener('abort', onAbort);
  }

  const timeout = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  const timer = setTimeout(() => controller.abort(), timeout);

  let finalEvent: StreamEvent | null = null;

  try {
    const response = await fetch('/api/scripts', {
      method: 'POST',
      headers,
      body: JSON.stringify({ script, args: options.args, stream: true }),
      signal: controller.signal,
    });

    if (!response.ok || !response.body) {
      const text = await response.text().catch(() => '');
      throw new Error(`Script stream failed: HTTP ${response.status} ${text}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while (true) {
      const { value, done } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });

      let newlineIdx: number;
      while ((newlineIdx = buffer.indexOf('\n')) >= 0) {
        const line = buffer.slice(0, newlineIdx).trim();
        buffer = buffer.slice(newlineIdx + 1);
        if (!line) continue;
        try {
          const event = JSON.parse(line) as StreamEvent;
          options.onEvent?.(event);
          if (event.type === 'stdout' && event.data) options.onStdout?.(event.data);
          if (event.type === 'stderr' && event.data) options.onStderr?.(event.data);
          if (event.type === 'exit' || event.type === 'error') finalEvent = event;
        } catch {
          // Ignore malformed lines and keep streaming.
        }
      }
    }
  } finally {
    clearTimeout(timer);
    if (options.signal) options.signal.removeEventListener('abort', onAbort);
  }

  return finalEvent;
};