Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,232 @@
|
||||
(function (root, factory) {
|
||||
const client = factory();
|
||||
if (typeof module === 'object' && module.exports) module.exports = client;
|
||||
else root.adpanelAgentLive = client;
|
||||
})(typeof globalThis === 'object' ? globalThis : this, function () {
|
||||
'use strict';
|
||||
|
||||
const scopeTimeoutMs = 12_000;
|
||||
const pollDeadlineMs = 10 * 60 * 1000;
|
||||
const maxUnacknowledged = 8;
|
||||
const unacknowledged = new Map();
|
||||
const discoveryQueue = [];
|
||||
let activeDiscoveries = 0;
|
||||
const defaultAccessMode = 'file_plan';
|
||||
const accessModes = new Set([defaultAccessMode, 'read_only']);
|
||||
|
||||
function bindAccessMode(select, account, server, storage) {
|
||||
const key = `adpanel:agent-access:${encodeURIComponent(account || '')}:${encodeURIComponent(server || '')}`;
|
||||
select.value = defaultAccessMode;
|
||||
try {
|
||||
const saved = storage?.getItem(key);
|
||||
if (accessModes.has(saved)) select.value = saved;
|
||||
} catch { }
|
||||
select.addEventListener('change', () => {
|
||||
if (!accessModes.has(select.value)) select.value = defaultAccessMode;
|
||||
try { storage?.setItem(key, select.value); } catch { }
|
||||
});
|
||||
return () => accessModes.has(select.value) ? select.value : defaultAccessMode;
|
||||
}
|
||||
|
||||
const accessPicker = globalThis.document?.getElementById('aiAgentAccessMode');
|
||||
const manualModelField = globalThis.document?.getElementById('aiManualModelField');
|
||||
const manualModelInput = globalThis.document?.getElementById('aiManualModelInput');
|
||||
let getAccessMode;
|
||||
if (accessPicker) {
|
||||
let storage;
|
||||
try { storage = globalThis.localStorage; } catch { }
|
||||
getAccessMode = bindAccessMode(accessPicker, globalThis.__ADPANEL_BOOTSTRAP__?.currentUser?.email,
|
||||
globalThis.document.documentElement.dataset.bot, storage);
|
||||
}
|
||||
|
||||
function showProviderModelInput(available, modelIds) {
|
||||
if (manualModelField) manualModelField.hidden = !available;
|
||||
if (manualModelInput) manualModelInput.value = available ? (Array.isArray(modelIds) ? modelIds.join('\n') : modelIds || '') : '';
|
||||
}
|
||||
|
||||
function readProviderModelIds() {
|
||||
if (manualModelField && !manualModelField.hidden) return manualModelInput?.value.split(/\r?\n/).map((id) => id.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
const states = {
|
||||
agent_interrupted: 'The Agent worker stopped before this reply was saved. Send again to start a new run.',
|
||||
agent_authority_revoked: 'Access changed while the Agent was working.',
|
||||
agent_disabled: 'ADPanel Agent is disabled.',
|
||||
agent_provider_busy: 'The AI provider or Agent reached its request limit. Try again shortly.',
|
||||
agent_provider_auth: 'The AI provider refused access. Ask an administrator to check its API key and model permissions.',
|
||||
agent_provider_account: 'The AI provider requires account or billing attention. Ask an administrator to check the provider account.',
|
||||
agent_provider_blocked: 'The AI provider blocked this reply. No new action was prepared.',
|
||||
agent_provider_configuration: 'This AI provider is no longer configured for the selected model. Check Agent settings or select another model.',
|
||||
agent_provider_incomplete: 'The AI provider did not return a complete reply. No new action was prepared. Try a smaller request.',
|
||||
agent_provider_model_unavailable: 'The AI provider could not find the selected model or endpoint. Select another model or check Agent settings.',
|
||||
agent_provider_rejected: 'The AI provider rejected this request. Try a shorter message or select another model that supports Agent tools.',
|
||||
agent_provider_unavailable: 'The AI provider returned a service error. Try again shortly or select another provider.',
|
||||
agent_provider_unreachable: 'The Agent could not reach the AI provider. Check the provider connection in Agent settings.',
|
||||
agent_provider_timeout: 'The AI provider did not respond in time. Try again or select another model.',
|
||||
agent_provider_tool_call_invalid: 'The AI provider did not return a valid tool call. No new action was prepared. Try again or select another model.',
|
||||
agent_provider_response_too_large: 'The AI provider response exceeded the size limit. Ask for a smaller change or shorter reply.',
|
||||
agent_panel_unavailable: 'The Agent could not reach the panel to complete this request. Try again shortly.',
|
||||
agent_unavailable: 'The Agent service did not respond. Try again shortly.',
|
||||
agent_diagnostic_not_allowed: 'The Agent could not use a requested diagnostic tool. Check your server permissions and try again.',
|
||||
agent_console_owner_unavailable: 'The Agent could not load the local console. Check the server console directly.',
|
||||
agent_console_owner_ambiguous: 'The Agent could not identify the current local console. Check the server console directly.',
|
||||
agent_transcript_changed: 'The chat changed before the Agent could read the request. Reopen the chat and send it again.',
|
||||
agent_run_stopped: 'Generation exceeded its time limit.',
|
||||
agent_automatic_edit_interrupted: 'The Agent stopped before saving the edit result. Check the affected files before trying again.',
|
||||
agent_automatic_edits_incomplete: 'The Agent did not complete all automatic edits. Review the result and check the affected files before retrying.',
|
||||
agent_automatic_edit_upgrade: 'This queued edit was stopped by an Agent upgrade. Review the request before sending it again.',
|
||||
agent_claim_inactive: 'This Agent run is no longer active.',
|
||||
};
|
||||
|
||||
function jobOutcomeMessage(job) {
|
||||
if (job?.status === 'failed') {
|
||||
if (Object.hasOwn(states, job.error)) return states[job.error];
|
||||
const reference = /^\d{1,20}$/.test(String(job.id)) ? ` (job ${job.id})` : '';
|
||||
return `The Agent could not finish this reply${reference}. Try again shortly.`;
|
||||
}
|
||||
if (job?.status === 'cancelled') return job.error === 'agent_automatic_edit_interrupted' ? states[job.error]
|
||||
: job.error === 'agent_disabled' ? 'This run was cancelled when ADPanel Agent was disabled.' : 'Generation stopped.';
|
||||
return '';
|
||||
}
|
||||
|
||||
function queueModelDiscovery(request) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const start = () => {
|
||||
activeDiscoveries += 1;
|
||||
Promise.resolve().then(request).then(resolve, reject).finally(() => {
|
||||
activeDiscoveries -= 1;
|
||||
discoveryQueue.shift()?.();
|
||||
});
|
||||
};
|
||||
if (activeDiscoveries < 2) start();
|
||||
else discoveryQueue.push(start);
|
||||
});
|
||||
}
|
||||
|
||||
async function requestJson(fetcher, path, options, signal) {
|
||||
const timeout = AbortSignal.timeout(scopeTimeoutMs);
|
||||
const response = await fetcher(path, { ...options, cache: 'no-store', signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
|
||||
const payload = await response.json().catch((error) => {
|
||||
if (response.ok) throw error;
|
||||
return {};
|
||||
});
|
||||
if (!response.ok) throw Object.assign(new Error(payload.error || `Agent request failed (${response.status}).`), {
|
||||
status: response.status, code: payload.code, retry: Number(response.headers.get('Retry-After')) || 0,
|
||||
});
|
||||
return payload;
|
||||
}
|
||||
|
||||
function wait(delay, signal) {
|
||||
return new Promise((resolve, reject) => {
|
||||
signal?.throwIfAborted();
|
||||
const dispose = () => signal?.removeEventListener('abort', abort);
|
||||
const abort = () => { clearTimeout(timer); dispose(); reject(signal.reason); };
|
||||
const timer = setTimeout(() => { dispose(); resolve(); }, delay);
|
||||
signal?.addEventListener('abort', abort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function makeRequestKey(cryptoApi = globalThis.crypto) {
|
||||
if (typeof cryptoApi.randomUUID === 'function') return cryptoApi.randomUUID();
|
||||
const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
|
||||
bytes[6] = (bytes[6] & 15) | 64;
|
||||
bytes[8] = (bytes[8] & 63) | 128;
|
||||
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
|
||||
function retryableSubmissionError(error) {
|
||||
return error.code !== 'agent_disabled' && (!error.status || error.status === 429 || error.status >= 500);
|
||||
}
|
||||
|
||||
function createRun(submission, { fetcher = globalThis.fetch, requestKey } = {}) {
|
||||
if (getAccessMode) submission = { ...submission, accessMode: getAccessMode() };
|
||||
const payload = JSON.stringify(submission);
|
||||
if (!requestKey) {
|
||||
const now = Date.now();
|
||||
for (const [pending, entry] of unacknowledged) {
|
||||
if (entry.expiresAt <= now) unacknowledged.delete(pending);
|
||||
}
|
||||
requestKey = unacknowledged.get(payload)?.key || makeRequestKey();
|
||||
unacknowledged.delete(payload);
|
||||
}
|
||||
const body = JSON.stringify({ ...submission, requestKey });
|
||||
const send = async () => {
|
||||
const response = await requestJson(fetcher, '/api/ai/chat', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' }, body,
|
||||
});
|
||||
if (!/^\d+$/.test(String(response?.jobId)) || !/^\d+$/.test(String(response?.chatId))) {
|
||||
throw new Error('The Agent returned an invalid job acknowledgement.');
|
||||
}
|
||||
return response;
|
||||
};
|
||||
|
||||
const accepted = (async () => {
|
||||
try { return await send(); } catch (error) {
|
||||
if (!retryableSubmissionError(error)) throw error;
|
||||
await wait(Math.min(3000, Math.max(300, (error.retry || 0) * 1000)));
|
||||
try { return await send(); } catch (retryError) {
|
||||
if (retryableSubmissionError(retryError)) {
|
||||
if (unacknowledged.size >= maxUnacknowledged) unacknowledged.delete(unacknowledged.keys().next().value);
|
||||
unacknowledged.set(payload, { key: requestKey, expiresAt: Date.now() + pollDeadlineMs });
|
||||
}
|
||||
throw retryError;
|
||||
}
|
||||
}
|
||||
})();
|
||||
return followRun(accepted, fetcher);
|
||||
}
|
||||
|
||||
function followRun(accepted, fetcher) {
|
||||
const controller = new AbortController();
|
||||
let stopping = false;
|
||||
let cancellation;
|
||||
|
||||
async function cancel() {
|
||||
stopping = true;
|
||||
cancellation ||= accepted.then(({ jobId }) => requestJson(fetcher, `/api/ai/jobs/${encodeURIComponent(jobId)}/cancel`, {
|
||||
method: 'POST',
|
||||
})).then((result) => {
|
||||
if (result.cancelled) controller.abort();
|
||||
return result;
|
||||
}).catch((error) => {
|
||||
stopping = false;
|
||||
cancellation = null;
|
||||
throw error;
|
||||
});
|
||||
return cancellation;
|
||||
}
|
||||
|
||||
async function result() {
|
||||
const { jobId } = await accepted;
|
||||
const deadline = Date.now() + pollDeadlineMs;
|
||||
let delay = 800;
|
||||
while (Date.now() < deadline) {
|
||||
if (stopping && cancellation) await cancellation.catch(() => {});
|
||||
await wait(delay, controller.signal);
|
||||
let payload;
|
||||
try {
|
||||
payload = await requestJson(fetcher, `/api/ai/jobs/${encodeURIComponent(jobId)}`, {}, controller.signal);
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted || error.code === 'agent_disabled' || (error.status && error.status < 500 && error.status !== 429)) throw error;
|
||||
delay = Math.min(15_000, Math.max(delay * 1.6, (error.retry || 0) * 1000));
|
||||
continue;
|
||||
}
|
||||
const { job } = payload;
|
||||
if (job?.status === 'completed') return job;
|
||||
if (job?.status === 'cancelled') throw new DOMException(jobOutcomeMessage(job), 'AbortError');
|
||||
if (job?.status === 'failed') throw Object.assign(new Error(jobOutcomeMessage(job)), { code: job.error });
|
||||
delay = Math.min(10_000, Math.ceil(delay * 1.4));
|
||||
}
|
||||
throw new Error('The Agent run is still pending. Reopen this chat to check for the reply.');
|
||||
}
|
||||
|
||||
return { accepted, result, cancel, detach: () => controller.abort() };
|
||||
}
|
||||
|
||||
function resumeRun(jobId, chatId, { fetcher = globalThis.fetch } = {}) {
|
||||
return followRun(Promise.resolve({ jobId, chatId }), fetcher);
|
||||
}
|
||||
|
||||
return { createRun, resumeRun, queueModelDiscovery, jobOutcomeMessage, bindAccessMode, showProviderModelInput, readProviderModelIds };
|
||||
});
|
||||
Reference in new issue
Block a user